Add payment method surcharge on single page checkout Using Drupal 7, Drupal Commerce module.

I have a single page checkout on which the user enters Billing Info, selects one of two payment methods and enters their credit card or E-Check information (using the Commerce NMI payment gateway which utilizes a direct-post method), and ultimately submits the payment.  The Review pane is empty and therefore skipped, so the checkout proceeds directly to the Third-party Payment Redirect pane.

My issue: I use a Rule to apply a fee (using Commerce Fees) depending on payment method, but it seems like the payment method isn't being set before the information is sent to the payment gatway--the payment method comparison always evaluates to false.

The rule is recognized after the fact, however, as the fee gets added after the payment has been submitted, resulting in an unpaid balance on the order.

The client is set on a single page checkout process, and so what I need is this:

How can I grab and alter the order information after submitting the checkout form but before the third party redirect fires? This would be very helpful as I would also like to add a custom code to the order ID this way.

You need to be careful here. Obviously you want to share with your customer that their order total will change, even slightly, before they pay. Often, most payment gateways strongly discourage passing on their fee to the customer, or flat out do not allow it.

But let's assume you want to charge more for "Cash on Delivery."

According to the commerce_fee documentation, you have to use two pages.

  Notice: if using fees based on payment type, be sure to move the payment type pane to a screen before the review pane on admin/commerce/config/checkout so that customers can see the fee before accepting.

This requirement would prevent nearly all normal payment gateways that require an off-site-payment-redirect step after putting payment details into a form from functioning correctly, if at all.

One way to create a single page, with ajax is the following recipe:

Ingredients

Commerce Checkout Field Group
Field Group
Commerce Payment Methods Field - (I just created this module because it didn't exist, just gives you a field that is populated with payment methods available to that order).
Commerce Checkout Ajax

Directions

Add a payment method field to your order. Use field group and checkout field group to add this field to a checkout page. Use Rules to make only a pre-selected payment method available based on the field on orders (might require a custom rule condition?). Use Rules to calculate your fee based on that field selection and not on the actual payment gateway selected. Use Commerce Checkout Ajax to re-load panes as needed.


Chosen module present but inactive To replicate the issue:

Install and enable Chosen module ->

(Apply Chosen to exposed filter)

Add .views-widget-filter-title to /config/user-interface/chosen under                 "Apply Chosen to the following elements"

Why is my chosen element present but inactive? (See picture)

The selector added to "Apply Chosen to the following elements" section would be

.view-filters .views-exposed-form select

in order for Chosen plugin to be applied to Views exposed filter with select drop-down widget.


How to display add node form with node reference? I have a very similar functionality to stackoverflow - i.e. I have a a view that display question and below it there are answers (seperate nodes references).

Currently, in order to add new answer to the question, the user has to click on a link, which takes him to add node form. But I need to display the form below the view, so the user can answer without being redirected to add node form on a seperate page. I guess it can be done programatically using drupal_get_form() function, but I have no idea how to start. Can anyone give me any suggestion or tutorial? Or maybe there is module for that..?  Any advice is greatly appreciated.

Don't worry, there's a module for that! http://drupal.org/project/formblock I believe this can work with node-references with a bit of configuration. If not, you can use this tutorial to populate the node reference: http://grayside.org/comment/830 which should get carried over by the FormBlock module.


How to display Views fields as a drop down menu? I have several fields in a View which I would like to appear as a drop down when another field is hovered over. It is possible to create a jump menu and a fieldset in Views, but how does one create a drop down menu? I have tried using the Block Reference module but this doesn't seem to show in Views. The only other option I can think of is writing the HTML in a global Views field and using replacement patterns, but there's got to be a better way. How can this be done?

It depends on the specific context - are you simply wanting to use the view results as a menu (in which case Menu Views would do this), or are you wanting to display a number of items e.g. users, and have more detailed info on the items spill out on hover (in which case, a display format such as Views App Folders might be what you're looking for).


Embed a node add form on a parent node I have a product display node and I'm trying to add a rental form to the node so that anyone can submit a rental form and have that reference the node. I was thinking of making the rental form a new Content Type so that the author information is automatically stored. I was also looking at Entityforms and specifically Inline EntityForms since that seems to incorporate the entityreference field.

Approach 1

What's interesting about the Inline Entityform is that you don't need an Entityform type to use it. You can select the Target type as 'node' and have that create a node form within the parent node's edit page.

The problem I'm facing with this approach is that you can't render the form on the front-end. I've tried setting the Display settings to 'Rendered entity' and I'm still not seeing anything on the front-end of the parent node, logged in as admin.

Is the Inline Entityform module only for embedding node add forms to the back-end?

Approach 2

The second approach was using Inline Entityform to target a node of type 'Rental' with the same settings but I was still unable to produce a node add form on the parent node front-end.

I do not want to use Panels but it's looking like I might have to? Any thoughts are appreciated.

Inline EntityForm is for placing an entity's form within an Edit page of an existing  Node, eg (/node/edit/123). It's not for showing a form on a Nodes' page with a view_mode set to like full.

You want to use either:

webform entity
entityform

And then either use Display Suite or alter the Node Template for your theme to include form for reservations when people view your Node.

Alternatively you can just use 2 content types: 1 for product and 1 for reservations. and use the Prepopulate module to build a link to create a Reservation -- which you can place on the product node. Clicking this link would send the user to create a reservation, you could always send them back to the product node using $form['#redirect'] on your reservation type.

And if you were crazy you could try to make a url using Prepopulate that loads an Ajax popup node reservation form on the product page.

Hopefully one of these ideas sets you on your path.


change RegEx in filter_url for text field I have nodes with text field containing URLs. The content is imported from XML file. The URLs are converted to links with drupals filter system, which works fine for most of the links but not all. I guess its the regex in filter_url function, but I can't figure it out.

Example URL:

http://example.net/2027/uc1.$b81009?urlappend=%3Bseq=7

is converted to

http://example.net/2027/uc1.$b81009?urlappend=%3Bseq=7

I'm not a php expert but I'm trying to fix this issue with a custom module. I copied the function _filter_url to mymodule.module, renamed it to mymodule_filter_url. Invoking hook_filter_info_alter(&$info) I change the process callback:

$info['filter_url']['process callback'] = 'mymodule_filter_url';

Now I have to find the regex expression, which stops the URL encoding right before the '.$'. I guess it's in one of these lines:

$trail = '[a-zA-Z0-9:%_+*~#&\[\]=/;?!\.,-]*[a-zA-Z0-9:%_+*~#&\[\]=/;-]';
$punctuation = '[\.,?!]*?';

But here I'm stuck. Can someone help me?

I think, I got the answer. I added "\$" to the $trail RegEx pattern.

$trail = '[a-zA-Z0-9:%_+*~#&\[\]=/;?!\.,\-\$]*[a-zA-Z0-9:%_+*~#&\[\]=/;-]';

Are there any drawbacks with this solution or is there a better way solving it?


Add meta tags when block exist on page and its cached I have block with social sharing buttons. Need add 'og' and 'twitter' meta tags on page where block exists. I know that can add it throw drupal_add_html_head() inside block content render, but if block is cached meta tags not appear.
How do this?

Instead of adding php code in the block you could add the code in a preprocess function for the block.

/**
 * Implements template_preprocess_block().
 */
function MYTHEME_preprocess_block(&$variables) {
  if ($variables['block']->bid == 'MYBLOCKID') {
    $og_title = array(
      '#tag' => 'meta',
      '#attributes' => array(
        'property' => 'og:title',
        'content' => "My example title",
      ),
    );
    drupal_add_html_head($og_title, 'MYMODULE_og_title');
  }
}


Grouping Nodes by first letter of field I've around 300 pages in wiki style (word -> explanation).

I need to create an overview page with all words categorized by first letter of page title/custom field (so basically [0-9] or a, b, c etc).

I would like to know you there are any already some good solution to do that?
Also considering in best way to go :)

I need something like this (actually in 3 columns)

Thanks.

Add the field a second time so it appears twice in Fields, check exclude from display and uncheck link this field to the original piece of content. Under rewrite results check trim this field to a maximum length, and enter 1 in the textfield.

Under format click settings next to unformatted list, etc. and select the right field in the grouping options.

You'll probably need to adjust the sort criteria too


How to make a text field box appear after clicking select option by using ajax? I have created a content type and with a field which is a select type and the options is:

Text
Text area
File

Now, when I select text area option, then a text area box have to appear below the select field and same for text option also. And if a select file option, then a button should appear after the select field for file functionality. I heard this can be done by ajax, but don't know where to start and how to do it.

You can use the Conditional Fields module, which allows you to show/hide fields based on other field's values.
From the module description:

Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.
When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API.
A simple use case would be defining a custom “Article teaser" field that is shown only if a "Has teaser" checkbox is checked, but much more complex options are available.


Combine all nodes of two content types as table rows / columns I have two content types: Ingredients (Butter, Flour, ...) and Units of mesure (Cup, Tablespoon, ...).

Ingredients have Density field (e.g Flour, 0.53g/ml) and Units of mesure a Capacity field (e.g. Cup, 250ml).

Using views, I am stuck trying to create a table similar to:

==================================================
|               | Nodes of "Units of measure"    |
|------------------------------------------------|
| Nodes of      | Math calculation based on      |
| "Ingredients" | "Desnsity" and "Capacity" values
|               |                                |
|               |                                |
==================================================

For example:

==================================================
|         | Grams | Cup  | Tablespoon | Teaspoon |
|------------------------------------------------|
| Butter  | 100   | 0.44 | 7.05       | 21.16    |
| Flour   | 100   | 0.80 | 12.80      | 38.43    |
| ...     |       |      |            |          |
|                                                |
==================================================

I don't know how to generate such a table with two content types titles as rows and columns respectively.

Any help would be appreciated. Thanks!

EDIT:

I read about similar questions that use references and relationships,
but this view should show all nodes of both content types. So, they don't need to be related.
Maybe Units of measure should be a Taxonomy instead of a content type? I am open to answers changing the scenario/context described. How would you create such a table with Drupal?

its very easy if contentypes are "entity reference" related, on "less important" contentype add an entityreference field and relate that node to "main contentype", in views add a relationship with your entityreference field, filter (not exposed) to display only "main contentype", and when adding fields to your view (now both contentypes fields are listed in drop menu field listings), specify if you use or not the relationship, for fields on "main contentype" do not use relationship, do it in all "less important contentype" fields. done.


Drupal Commerce and large product inventories Does anyone have any insight into using Drupal commerce with a large inventory? We are utilising using Drupal 8.1 headless and scoping an eCommerce integration using Drupal Commerce with around 30 million products. Currently, our thoughts are to use a MongoDB backend and Elasticsearch on top of it.

Does anyone have any experience or insight into handling such a large inventory and our planned approach?

The products will not have to be managed via the front end and instead will be imported with their various categories and attributes. Any changes we plan to do from a staging database and synchronise accordingly.

Thank you for any insight.

The Akademika case study might help. They're at 18 million products right now, regular MySQL database plus Elasticsearch.

You can find the NyMedia team in #commerce on Drupal Slack (or contact them directly).


Add Images in WebForm Dropdown list Using Drupal 7 and WebForm Module (version 7.x-4.2). How would I go about adding images, next to text, in a dropdown listbox?

Is this even possible?

I have a dropdown with a list of products and I'd like to add an image next to the name.

It would probably be better to have that form coded by hand where you can turn your  list into a set of divs with a jQuery library, eg. http://designwithpc.com/Plugins/ddSlick

Or, you can set a background image to each option with CSS (which kinds of takes a bit of time depending on how much options you have in your select list):

select option[value="your_value"] {
  background-image: url(your_image.png);
}


Auto-create navigation link to a node I use RULES module to create a node (my custom content type) on user creation - so another words every user gets ONE, UNIQUE node when creating account.

Now I would like to have a navigation menu for users, where each user has a link to his own node. How can I achieve this?

EDIT:

Just as example, imagine we are talking about node as user profile. Each user gets one of those nodes on user creation and I want to have a navigation link to edit/view this node.

To achieve this I wrote a module, which creates a node on user create. The node has an alias, which is the username. Code below:

function mymodule_user_insert(&$edit, $account, $category) {
    $node = new stdClass();
    $node->type = 'article';
    node_object_prepare($node);

    $node->title = $edit['name'];
    $node->path = array(
        'alias' => $edit['name'],
    );
    $node->uid = $account->uid;
    $node->language = LANGUAGE_NONE;
    node_save($node);
}

Additionally I used MENU_TOKEN module, which allows to input tokens into title and path of menu links. So my new navigation link path is [current-user:name], which links user's article to his profile.

EDIT: Of course in the example I used 'article' as content type, but in practice I use a custom content type. So if you want to use this code, make sure this line:

$node->type = 'article';

is adjusted as per requirements.


No PHP validation criteria in Views In order to specify a PHP validation criteria for a View - do I need some additional module? In previous installation of Drupal I had this position in select box. Now there is everyone of them apart from PHP code. Where did it go?

Check if the PHP Filter module (Core, optional) is enabled.


Organic Groups - Display the Group Name that a peice of content belongs to I have a view that is listing all of the content tagged with a taxonomy terms (contextual filter).  Underneath the note title, I would like to include some meta that says: posted by username who belongs to "group name" and link that over to the associated group. Here is a screenshot of my current view:

http://cl.ly/image/0Z103y3q3D1z

Any help is much appreciated. I can't seem to find a "group name" or "group title" field anywhere when attempting to use fields associated with a relationship.

Thanks for any help.

Found the answer with the help of this post: Using Views to List a Member's Organic Groups (7.x-2.3)

Here is a screeshot of my view: http://cl.ly/image/2O1h1x3T3J43

by adding the relationship: "OG Membership: Group Node from OG membership" I was able to use that relationship in a new title field and display.


Help changing views HTML output I have View set up to display a list of images that are related to nodes elsewhere in my site, and I've styled them so that hovering over them darkens the image and displays the node's title. Unfortunately, the title div obscures the image, and making the title into a link only affects the title text.

What I'd like to do is wrap the title div in  tags, so this:

Title

Turns into this:

Title

I have an inkling that I'll have to do this either with hooks or in one of the views.php files, but I'm not sure where to start; can anyone help me?

Filter title and use token like:
[Title]


How to integrate the drush help --filter option with your custom module? You can use the drush help --filter command to present a list of
command categories to view. When you run the command: drush --filter=devel_generate you can see the following output:
All commands in devel_generate: (devel_generate)
 generate-content  Create content.
 (genc)
 generate-menus    Create menus and menu items.
 (genm)
 generate-terms    Create terms in specified vocabulary.
 (gent)
 generate-users    Create users.
 (genu)
 generate-vocabs   Create vocabularies.
 (genv)

You can read in the Drush Command page:

help
Options:  --filter=[category]  Restrict command list to those commands defined in the specified file. Omit value to choose from a list of names.

I create the onlyone.drush.inc file with the following code:
<?php
/**
 * @file
 * Drush commands related to OnlyOne.
 */

/**
* Implements hook_drush_command().
*/
function onlyone_drush_command() {
  $items['onlyone-list'] = array(
    'description' => dt("List the configured content types to have Only One node."),
    'aliases' => array('ol'),
    'examples' => array(
      'drush onlyone-list' => dt("List the configured content types to have Only One node."),
    ),
  );
  return $items;
}

/**
 * Callback for the onlyone-list command.
 */
function drush_onlyone_list() {
  $onlyone_content_types = variable_get('onlyone_node_types');

  if (count($onlyone_content_types)) {
    drush_print(dt("Content types configured to have only one node:"));
    drush_print(implode("\n", $onlyone_content_types));
  }
  else {
    drush_print(dt("There is not content types configured to have only one node."));
  }
}

I clean the cache with drush cc drush but when I use drush help --filter=onlyone I get this output:
 [error]  The specified command category onlyone does not exist.

So, how can I obtain the list of the commands defined in my module?

I found the answer searching in the code of the drush project:

If the module have less than 4 commands you can't use the drush --filter=MODULE_NAME because your commands are classified as other:

See the function drush_commands_categorize(), and at line 1125 you can see this comment:

  // Post-process the categories that have no title.
  // Any that have fewer than 4 commands go into a section called "other".

I create 3 more commands and now the drush --filter=onlyone command works.


How to export Drupal page as PDF? I am using Drupal 7.17, and have created content of type book. I want the users to be able to export it to PDF format. The pages contains images, HTML tables, HTML ordered and unordered list (ul and li). What is the best way to do this? The content styles should be preserved when exported.

You can use the Print module

  This module allows you to generate the following printer-friendly
  versions of any node:

  Printer-friendly version (webpage format) (at
  www.example.com/print/nid) PDF version (at
  www.example.com/printpdf/nid) Send by email (at
  www.example.com/printmail/nid) where nid is the node id of content to
  render.

And your choice of one of the 4 PDF libraries it supports. It does have very high memory requirements when generating PDF as previous comments have noted. It is well documented and the PDF output is fully themeable.


Adding a Meta tags CMS function to drupal 7 I would like to be able to manually configure the meta tags, keywords and description,for each individual page of the sites. I couldn't find any module out there for drupal 7 that does so.
Anyone have heard of such a module? If not how hard would it be to make this a custom module ?

There is a complete rewrite of the old drupal 6 module nodewords in progress now - it is called metatags. However the metatags module looks like it is still in the initial development phase, so you might be better off using http://drupal.org/project/metatags_quick - which already has a stable 7.x release

There is no releases on the project page, but you could clone the git repo and help with the issue queue and submitting patches back etc


Pop up Information windows D7 I am new in Drupal 7. What i am trying to do is to show pop up information windows for the following case:

I have a view with links (internal links to drupal site). I want by clicking on them:

1.To show an information pop-up window with the message "Redirection to the official position..."

This message to be showing for 3 seconds and
The message to disappear after 3 seconds and the redirection to be completed.

How can i show specific pop-up windows by clicking a link and before the redirection takes place?

I am not aware of a contrib module to achieve this, but you can always use jQuery in your theme or custom module.

Something like this might work (not tested, but that's the main idea - out of scope for Drupal Answers):

jQuery(document).ready(function() {
  // on link click (jQuery 1.4)
  jQuery('#my-link').click(function(e) {
    // preventDefault otherwise browser will go to link
    e.preventDefault();
    // show the pop-up layer which is assumed hidden with css or sth.
    jQuery('#my-popup-layer').fadeIn();
    // here you can possibly chain up more actions in order to
    // update the contents of the pop-up
    // now delay 3sec
    jQuery(this)
      .delay(3000)
      .queue(function(next) {
        // redirect
        window.location.href = jQuery(this).attr('href');
        next(); // prob redundant
      });
  });
});


How to customize the text of "SUBMITTED BY" (article) I like to customize the output of SUBMITTED BY, e.g. I like to change it to WRITTEN BY.
Where can I do it? Thanks for help

In node.html.twig change the line SUBMITTED BY to WRITTEN BY

  {% if display_submitted %}
    <footer class="node__meta">
      {{ author_picture }}
      <div{{ author_attributes.addClass('node__submitted') }}>
        {% trans %}Submitted by {{ author_name }} on {{ date }}{% endtrans %}
        {{ metadata }}
      </div>
    </footer>
  {% endif %}


Form text field is too wide for the side bar I created custom block for my entity and I want to add this entity creation form to the 2nd sidebar. I managed to do this and this is how it looks like now:

First textfield goes out of bounds, where as second one, which is textarea type, is okay. After looking at Form API, I realized that textarea is re-sizable and textfield is not. How can I solve this? If I put title as text area it doesn't look that nice so I would be very happy if I could stick to textfield and make it fit somehow?

You can change field size .Default size is 60.You can text field width by css.


Only Show Nodes From Child Terms (-1 excluding parent) Hello i have some nodes which i am using as to hold information on a taxonomy term (image, desc etc) and I have created some block views to pull that information to display on my taxonomy/term pages (yes om on D6 due to custom modules and upgrade problems)

Also ive made the term nodes appear on the parents term page in a node view.

Sport
-American Sports
--Baseball
--NFL
-Football
--England
(etc)

This is in a View with tax depth of -1 (just show the immediate children) If i visit 'Sport' I only see my 'Sport' stuff and then below in the child term (node) View i see

American Sports
Football

Well in an ideal world thats all i see but because i am in 'Sport' I also see the node for the 'Sport' term that i am in.

Sport
American Sports
Football

I want the -1 in depth but i dont want the '0' if that makes sense.

I have tried excluding the argument, like you do for for nodes with nid but it doesnt seem to work the same.

Its the same all the way down. If i go into 'American Sports' in my list of nodes that are referance (like that old drupal video from Bob (the christian) 'taxonomy on steroids) shows as-

American Sports
Baseball
NFL

etc.

Aye so in a round about way i was wondering how to exclude...no how to only display, nodes of child terms (-1)

All help appreciated as its been annoying me for a while and ive been trying to sort it for ages.

thanks

You could add an Node Nid as argument and check "Exclude the argument"

Select "Provide default argument" and select "Taxonomy Term ID from URL"

And then check "Load default argument from term page"

Thank should work for you.

Let me know if that helps.


How can I show menu according their role? I have three roles Business Manager, General Manager and Handler.

How can I show only specific menu according their role?

Note: This answer is for drupal 7.

You can use Menu Block. And make blocks of menu and use on page. And you can set visibility settings for that block.


How to make filter that can find users by location of each other in miles or kilometers? On  a lot of dating sites like this one:

http://www.pof.com/basicsearch.aspx

users can search each other by proximity, can this be done with Drupal? Like searching for users within X kilometers of my IP?

IP Geolocation Views and Maps looks like what you are looking for. It can obtain user's location, and it integrates with Views using Views PHP as it's connector.


How to find out which context reaction is firing? im creating some pages that have specific layouts for tablets and mobiles, to send a targeted view and template im using context, context breakpoints and delta.

But i need some way of seeing which context reaction s being fired as on some pages an endless auto-reload is occurring, i think it might be due to some paths having multiple reactions, so im looking for some way to see which reaction is being fired and getting buggy

About a year ago I was working on a project where the breakpoints module would periodically send us into refresh loops.  I don't remember the particulars - only that the issue was due to the cookies not being cleared properly.

Breakpoints relies heavily on cookies to determine which display to use and when the cookies aren't cleared the module receives somewhat mixed messages.  I use Chrome for my development and found the extension Edit This Cookie very helpful.


How do I hide translation vertical tab programmatically? I would like to hide the Translation vertical tab. I tried with $form['content_translation']['#access'] = FALSE; but it seems not working.

How do I remove that vertical tab?

I think I found it.

In core\modules\content_translatio\src\ContentTranslationHandler.php, there is an entityFormAlter() method, which adds this vertical tab. It seems that this method is executed after your code. I would try changing the weight of your module (so your code will run later).

(I found this looking for the If you made a significant change string in core; doing so, I found where the translation tab was coming from.)


Correct analysis for "Mismatched entity and/or field definitions" Drupal 8 sometimes displays a warning in site status

  Mismatched entity and/or field definitions

There has already been a question about this and the answer is to run drush entity-updates.  I can't find any description of a solution directly from the GUI.

I have run the command several times and it works fine.  But I don't understand the point of Drupal printing this warning, rather than Drupal solving the problem automatically (by executing whatever the entity-updates command does).

Please can anyone tell me

Is there any analysis that I should do before running entity-updates?
Is there any reason I shouldn't write a cron hook that will call entity-updates automatically?
Should I raise an issue against Drupal core to request that Drupal runs the clean-up automatically rather than printing a warning?

Thanks to 4k4 and Clive and following the link I think I can now write up the answer to my question.

This Drupal Change Record (and more detail) documents that
module developers should write hook_update functions for entity updates.
So if you get the "mismatched" warning after a contrib module update
then it's a bug in that module and you should not apply to update to the live site.
This question explains that entity-updates is a developer tool.
If you are a developer working on a test site you may see the
"mismatched" warning whilst making changes.  You will run
entity-updates when you are ready.

So the answer to my questions 2 and 3 is no.


Change the default upload file location for a particular content type I have a content type "Test" which have "upload file" field. Only for this "Test" content type i want to change the location where uploaded file is stored. I want to store anywhere in my drupal instance not just only in sites/all/default/files/subdirectory.

How can I achieve this.

You might find some information about how to code changing file names in the File Path module.

File (Field) Paths allows you to automatically sort and rename your uploaded files using token based replacement patterns to maintain a nice clean filesystem.


Which megamenu supports i18n content translation? Do you know which megamenu supports i18n content translation?

At this time only tb_megamenu seems to support i18n.


Re-Theme Private Message Function I would like to rewrite the original function code for the Private messages block module. The original code displays a text message for no messages or messages in the inbox. I would like to change it to an image but am no where near on the right track.  Here is the coded that I am trying to change

 /**
 * Theme a block which displays the number of new messages a user has.
 */
function theme_privatemsg_new_block($count) {
  $count = $count['count'];
  if ($count == 0) {
    $text = t('0 Messages');
  }
  else {
    $text = format_plural($count, 'You have a new message!',
                        'You have @count new messages!');
  }

  return l($text, 'messages', array('attributes' => array('id' => 'privatemsg-new-link')));
}

I was trying the following replacement:

/**
 * Theme a block which displays the number of new messages a user has.
 */
function theme_privatemsg_new_block($count) {
  $count = $count['count'];
  if ($count == 0) {
    /*$text = t('0 Messages');*/
    $text = l(');
  }
  else {
    /*$text = format_plural($count, 'You have a new message!',
                        'You have @count new messages!');*/
    $text = l('');
  }

  return l($text, 'messages', array('attributes' => array('id' => 'privatemsg-new-link')));
}

I suspect there are issues with the fact that it is designated as a text string instead of code that should be rendered.  What do you think?

Using PHP I am trying:

/**
 * Theme a block which displays the number of new messages a user has.
 */
function theme_privatemsg_new_block($count) {
  $count = $count['count'];
  if ($count == 0) {
    /*$text = t('0 Messages');*/
    $theme_path = drupal_get_path('theme', 'eternal'));
    $text = '';
  }
  else {
    /*$text = format_plural($count, 'You have a new message!',
                        'You have @count new messages!');*/
    $theme_path = drupal_get_path('theme', 'eternal'));
    $text = '';
  }

  return l($text, 'messages', array('attributes' => array('id' => 'privatemsg-new-link'), 'html' => TRUE));
}

$text = l('); looks wrong. "l" is function to create links, i guess thats what is failing here. Try to remove it and leave just $text = '';.

For reference on "l" see drupal api page - please note that there is also 'HTML' parametr in "l" function that you should set to true, since you are passing HTLM code in $text to that returning "l".

  'html' (default FALSE): Whether $text is HTML or just plain-text. For example, to make an image tag into a link, this must be set to TRUE, or you will see the escaped HTML image tag. $text is not sanitized if 'html' is TRUE. The calling function must ensure that $text is already safe.


Add a button that when clicked adds the user to the entity reference field I have a Job content type (created only by a Client), with an Entity Reference field, "candidates".

Freelancers (user role) see a Views block of jobs created.

How do I add an "Express interest" button to each job so that the freelancer who clicks it gets referenced by the job?

You can create a custom module dealing with the subscriptions. Implement hook_menu(), and create a callback url that gets the NID (I suppose your content type is derived from the node entity, but it would work for custom entities as well) as parameter, e.g. 'node/%node/subscribe'.

Within the callback function you check whether the current user has already subscribed for this job and create the reference programmatically if not.

In your view make sure to read the NID property. You may hide it from display. Then you can easily add another field, and rewrite its output as link using the [nid] token from the previously hidden NID, in the above example, the URI would be 'node/[nid]/subscribe'.

Last not least you can CSS style your link to look like a button.


How to create an Ecommerce Loyalty scheme for customers? How can I create a 'loyalty scheme' where customers are awarded with 5 pence for every £ spent, to be used on furture purchases. The rewards will be saved up until the user decides to redeem them against an order.

I have looked for a few solutions but cannot seem to find a way to make this work.

Any suggestions?

This may be too much overhead for your system of point usage, but check out the Commerce Userpoints module.  It integrates Commerce with the Userpoints module, which should handle most of what you're after.


Is there a way with drush or console to delete all active config with a certain prefix? I'm currently trying to migrate a site with drush migrate-upgrade --configure-only ... and copying the export migrate_plus.migration_*.yml into a custom module for tweaking. Now I want to enable that module but I get PreExistingConfigException.php and ... provided by MYMODULE already exist in active configuration.

I'd like to delete all config but it looks like the latest drush has removed drush config-delete and drupal config:delete is gone too. How do I achieve this?

This isn't the greatest solution, but it does work, and also allows you to not have to execute a dozen steps/commands to register your migrations.

In my custom module where I'm creating migration sources/plugins, I added a .install file and implemented hook_uninstall().  In there I delete the configurations remaining manually.

<?php

/**
 * @file
 * Contains my_module_migrate.install.
 */

/**
 * Implements hook_uninstall().
 *
 * Removes stale migration configs during uninstall.
 */
function my_module_migrate_uninstall() {
  $query = db_select('config', 'c')
    ->fields('c', array('name'))
    ->condition('name', db_like('migrate_plus.') . '%', 'LIKE')
    ->execute();

  $config_names = $query->fetchAll();

  // Delete each config using configFactory.
  foreach ($config_names as $config_name) {
    \Drupal::configFactory()->getEditable($config_name->name)->delete();
  }
}

Note: You may need to clear cache after uninstalling for the changes to show before re-enabling the module.

If you want to remove them before you uninstall you can either run each line from hook_uninstall() implementation in devel/php, or you can run them via drush:
drush ev "\Drupal:;configFactory()->getEditable('migrate_plus.migration.xxxxxx')->delete();"
You will probably have to clear cache after removing all of them manually via drush as well.

If you'd like to just run a couple of drush commands to re-register your migrations, you can add this drush plugin file my_module.drush.inc to your modules' root directory, clear cache, and run drush mpc -y && drush mcr my_module.  You may need to also run drush cache-clear drush for the commands to be come available.

Here's the code for the my_module.drush.inc file:

<?php
/**
 * @file
 * Contains my_module_migrate.drush.inc
 */

/**
 * Implements hook_drush_command().
 *
 * Defines drush commands.
 */
function my_module_migrate_drush_command() {
  // Company update Dynamically
  $items['migrate-prune-configs'] = array(
    'description' => dt('Prune migrate configs.'),
    'aliases' => array('mpc'),
    'examples' => array(
      'drush migrate-prune-configs' => 'Removes migrate configuations.',
    ),
    'callback' => 'my_module_migrate_migrate_prune_configs',
  );

  $items['module-config-reset'] = array(
    'description' => dt('Resets default config for a given module.'),
    'arguments' => [
      'module_name' => dt('Module name'),
    ],
    'aliases' => ['mcr'],
    'required-arguments' => 1,
    'callback' => 'my_module_migrate_config_reset',
  );

  return $items;
}

/**
 * Callback for drush command migrate-prune-configs to prune migratin configs.
 */
function my_module_migrate_migrate_prune_configs() {
  //Confirmation will be Y/N when use type “y” the condition will be executed if not it will not
  if (drush_confirm(dt("Are you sure you want to remove migrate configs?"))) {
    drush_print("Removing.....");
    // Get all of the migration config names.
    $query = db_select('config', 'c')
      ->fields('c', array('name'))
      ->condition('name', db_like('migrate_plus.') . '%', 'LIKE')
      ->execute();

    $config_names = $query->fetchAll();

    // Delete each config using configFactory.
    foreach ($config_names as $config_name) {
      drush_print("..." . $config_name->name);
      \Drupal::configFactory()->getEditable($config_name->name)->delete();
    }

    drush_print("Removed succesfully");

    return TRUE;
  }
}

/**
 * Reinstall default module's config files
 */
function my_module_migrate_config_reset($module_name) {
  if (!in_array($module_name, array_keys(\Drupal::moduleHandler()->getModuleList()))) {
    return drush_set_error(dt('Module @module_name not found.', ['@module_name' => $module_name]));
  }
  // Initiate config installer for given module.
  \Drupal::service('config.installer')->installDefaultConfig('module', $module_name);

  drush_print('Configuration was successfully reset.');

  return TRUE;
}

The code for resetting the module's configs was found in this issue on d.o.  I found that it doesn't work unless the configs are already removed, hence the first command to remove them.


How to add another option to promote an article content to? Take a look at my screenshot.

How can I make another option to promote my article contents to? Like promote my content as Affiliate Slideshow or to Slideshow?

form_alter will allow you to add another option

eg

hook_form_alter(&$form, &$form_state, $form_id){

     $form['my_field]['#options'][] = array('id' => 'value');

}

however, that in itself will not promote it, just allow you to set a value that can be picked up by a view or other means


Fixing Class Not Found error I recently moved a module from one location to another location and I am getting a ClassNotFoundException. Is there something similar to Registry Rebuild Module that can help rebuild the registry?

In addition to the usual cache rebuild, the additional need to restart the web server is due to a decision in Drupal 8 to be 'fast by default' use the APC Classloader if it is available.  It is faster, but it doesn't necessarily catch changes as you make them.  To not have to restart your web server during development, you can set your local environment to not try to use a better-for-production class loader.

For instance, in local.settings.php add:

$settings['class_loader_auto_detect'] = FALSE;

Via, and more background information at, what to do when developing a Drupal 8 module and a class file just isn't being loaded even though it is definitely there.


Why does the "admin/modules" page show up in the wrong language? The error appears on a single language page with just one other language than English enabled (here: German) and set to default. All other admin pages show the the right language. Admin theme is "seven". I know, this is probably to broad or localized, but I can't wrap my head around this one...

Update: I have installed "Administration Toolbar" and this fixes at least language error in the toolbar. If i deliberately enable the "better toolbar" - option (that means 2 toolbars, one is drupal core and the other from "Administration Toolbar" at the same time), one shows up in German as it should and the drupal core one still in English.

But all the other text strings are still in English. Although they are present and properly translated on the "translate interface"-page (admin/config/regional/translate/translate).

I have installed the latest .po (7.43) file for German, cleared cache several times but to no avail.

Any hint where to look?

UPDATE II: Bug is related to Features module (https://www.drupal.org/node/2636140) That one was hard to track down.

UPDATE III: The bug was fixed in the latest Feature module update (7.x-2.8)

I did a similar verification in one of our sites, which has 3 languages (EN, NL and FR). I disabled the "module_filter" module, so that I could see what the result would be if I look at what's shown on admin/modules. I also use "admin menu", but for my verifications I've not experimented with anything related to that menu (I just wanted to check what the CONTENT of  admin/modules actually is, depending on the language I used. And I experimented with EN and NL (=Dutch), assuming that FR would give similar results like NL. And I've been using the (same) Seven theme for admin

To actually do my experiments, I've enabled the "language switcher block" so that it is shown within my theme used for Administration. I have this block shown in the "Content" region above the block "Main Content Page" (so that I can switch between EN and NL for my experiment). BUT: nowhere in the question here it says anything about using that "language switcher block". So that's already something for you to check: you are aware I assume about how to use that block for switching languages, right?

Anyway, when I then use that language switcher block to switch from EN to NL, PARTs of what is shown on that page is in NL (Dutch), though other parts remain in EN. E.g.:

the descriptions for my modules (from the .info files) are shown in Dutch
but the strings like "Requires" and "Required by" are NOT translated in Dutch. Though the values like "(enabled)" or "(disabled)" or also translated to NL, like to "(ingeschakeld)" or "(uitgeschakeld)".
the (hardcoded) tekst near the top, like "Download additional ..." is NOT translated.
typical messages (in green, yellow or red) near the top are translated to NL also.
Module names, like "Color" are not translated (to something like "Kleur").
links like "configure" are also translated to "instellen".
module groups like "Core" are translated to "Kern".

With all this, I have the impression that by using the "language switcher block" and setting it to the NL-language, this admin/modules page gives me an "as good as it gets" translated version of that entire page. But if you don't use that  "language switcher block" (to switch to NL), then everything remains in EN (of course). And for things that are not translated, I guess that's because it's either not using the typical t() function, or the required translated string is still missing (for NL in my case).

Not sure to what extend it will actually answer your question, but at least it should help to understand what is happening, and how the "language switcher block" seems to be part of the puzzle.

But, don't worry ... D8 has a lot of improvements for multi-language stuff (not sure yet about this specific "issue" however ...).


sharing authentication within two drupal distributions I am looking for a module or a way where two different drupal distributions can share the same authentication or user database ? Is there a module that can help with that ?

possibilities-

if user A logged into site-1,  the user should be logged in automatically to site-2.

if thats not possible, if user 1 creates a login on site-1, he should also be able to use the same login credentials on site-2 or vice versa.

This method comes with a list of caveats, but it's possible to simply share the users table across multiple installations via a table prefix array in settings.php.

  Example: Sharing Users
  This example shows how to share users. The
  users from a master site prefixed with 'master_' are shared to a slave
  site prefixed with 'slave1_'.

$db_prefix = array(
    "default" => "slave1_", // the prefix for tables that are not shared.
    "users" => "master_",
    "sessions" => "master_",
    "authmap" => "master_",
    "sequences" => "master_",
    "profile_fields" => "master_",
    "profile_values" => "master_",
);


Displaying Taxonomy on the menu Friends -

Please help with this... to some of you, this is really easy. But, I have been struggling with this issue since two weeks:  I need to create categories structures such as Creating Categories/Subcategories/Subsubcategories/Products and have it appear on the menu of a newly install drupal commerce. this is what I have done so far:

I created the taxonomies necessary
I created the categories and subcategories: i.e.: Products Categories\Air Conditioners\
I created the product "Samsung Air Conditioner Unit" and inserted it into the correct categories
I clicked on All Products and observed that Samsung Air Conditioner is properly inserted into the correct subcategories
However, when I clicked on the root category "Product Category" on the main menu, which is generated by Taxonomy, I do not see the product listed.

I just need to know how to configure the content type to allow the product to display in the correct category\subcategory group.

The reason the Samsung Air Conditioner Unit was not showing as we clicked on the category was because we inserted as  Product Categories\Air Conditioner\Air Conditioning Unit instead of Product Categories\Air Conditioning Unit.

The subcategory Air Conditioner was not defined.  So, drupal did not know how to display it.  Once we moved to Product Catogoies\Air Conditioning Unit, it displayed.

Now, the task is how to create the subcategory Air Conditioners so that we could insert Air Conditioner Unit there instead of inserting it directly under Product Categories.


Show a custom field in a block I 'm getting crazy trying to show a value of a custom field (now in core) in a sidebar block. I have tried to show it with the render function, calling directly the field, with no luck.

I have a custom content type named "content1" and a  custom field named "field_test1"; I want that value to be shown on a block that will be visible while viewing the page node.

Do you have any suggestion on how to do it?

I would use the following code, to render a field.

render(field_view_field('node', $node, 'field_test1'));


Zen theme doesn't append content titles to breadcrumbs I've inherited a site with a subtheme designed on Zen 7x-5.4 to maintain and I'm having a problem with the breadcrumbs. I've checked the append content title to breadcrumb options in Appearance=>Settings however this doesn't seem to have any effect on the breadcrumb trail (i.e. the individual content page titles aren't displayed in the breadcrumb). So, I assume something must be overriding the breadcrumb settings through the UI. I'm not sure what that could be, or where it would be set/configured. I've looked through the template.php, and theme-settings.php files. I have the following options set in the mytheme.info file

settings[zen_breadcrumb]           = yes
settings[zen_breadcrumb_separator] = ' › '
settings[zen_breadcrumb_home]      = 1
settings[zen_breadcrumb_trailing]  = 0
settings[zen_breadcrumb_title]     = 0
settings[zen_skip_link_anchor]     = main-menu
settings[zen_skip_link_text]       = Jump to navigation
settings[zen_html5_respond_meta][] = respond
settings[zen_html5_respond_meta][] = html5
settings[zen_html5_respond_meta][] = meta
settings[zen_rebuild_registry]     = 1
settings[zen_wireframes]           = 0

But changing the breadcrumb trailing or title values to 1, and flushing the theme registry didn't pull anything off.

For further context, I do have one breadcrumb set with the Path Breadcrumbs module. For development purposes I have css aggregation turned off.

So, what is preventing my theme from adding the content title to the breadcrumbs and or how to do find where the conflict is?

The theme breadcrumbs were being overridden by the Path Breadcrumb module. You can fix this in the Path Breadcrumb settings.


Multi select files in media browser I would like to multi-select files in media browser. I came across this sandbox module: Media Multiselect but it has bugs that render it not usable. Does anyone know of a solution to multi-selecting files in media browser?

People are using this patch on latest media to multi-select media files on fields: https://www.drupal.org/node/951004#comment-9681531

Personally I had some problems to make it work at first, but finally I got it working (Had to disable admin_language module).


Can't get preprocess_node function to override items I've been stuck on getting a custom preprocess_node function to work in a Drupal 6 install. I can get it to echo out things based on values but I just can't seem to get overrides working. The latest thing I've tried is the answer described in the answer on this page. If I do:

$node->title = "Test";

and do a print_r on the $node I can see that it is overridden in the array with the new value but the title that's being output is still the old one. I've also tried setting $variables[title] but no luck. I'm actually trying to target something deeper than the title but thought I'd start with this. Here's an example I've tried putting in the template.php file. I've replaced my actual theme name with mythemename.

function mythemename_preprocess_node(&$variables) {

//Profiles
if($variables['type'] == "child_profile"){

    $node = $variables['node'];

        $node->title = "Test";
        //This echo correctly shows the new title but it's not actually overriding anything
        echo $node->title;

    $variables['node']=$node;
}}

If you look at node.tpl.php, the title is being printed like this:

<?php if (!$page): ?>

<a href="<?php print $node_url ?>" title="<?php print $title ?>"><?php print $title ?>

<?php endif; ?>

As you can see that's using the $title variable, not $node->title.

There's a one-to-one mapping between the array keys of the template's variables, and names of variables available in the template file. If you have $variables['my_awesome_var'] in the preprocess function, that variable will be available as $my_awesome_var in the template file.

So with that in mind, all you should need to do in your preprocess function is this:

function mythemename_preprocess_node(&$variables) {
  //Profiles
  if ($variables['type'] == "child_profile") {
    $variables['title'] = 'Test';
  }
}

To complete the thought - you could also change the node template to print $node->title instead, and your current code would work fine. But since the original template file uses a separate $title variable, it would be better to stick to convention and use that method.


How do I put a div around table with class = table-responsive? I want to put a div around tables in general and give them the class table-responsible. Therefore I changed the table.html.twig in my theme like this:

<div {{attributes.addClass('table-responsive') }}>
  <table{{ attributes.addClass('table') }}>
    ...
  </table>
</div>

But if I create a table in CKEditor nothing happend. It's only an ordinary table and nothing changed.

What did I do wrong?

CKEditor generates the table on its own. You can see this, if you switch to source. So the changes in twig will have no effekt, because the theme layer doesn't touch the source code that is coming out of the ckeditor. Only the filter layer is checking the source. More for security reasons. But it would be possible to change the table here, if you want to do it in drupal. Or you can modify the configuration of ckeditor itself.


Remove old role once new one purchased Someone created a module for this called uc_clear roles so you can stop what's happening to me now which is when a new role is purchased it is just added to the old one.
But this module is only for Drupal 6 and I am using 7.

Logintoboggan preauthorize role if the user neglects to verify it and then buys a role, the new role will replace it but if verified and user makes purchase for upgrade they end up with both free membership status as well as paid. I don't yet know how to write php or create a module but, could the RULES module do the job?

Yes, you can use Rules to manage roles.

Rules need Event to react on, Condition to evaluate for truth, Action to perform.

Event: It is hard to tell from from your post what would be your Event. I don't use Ubercart, but I assume it provides some Rules Events like Commerce, e.g. 'After adding a product to the cart,' 'On checkout coompletion,' and so on. There's also 'Before saving a user account,' 'After saving a user account' and so on.

Condition: "User has role(s)"

Action: "Add user role", "Remove user role"

Very simple actually.

[ Note also that the current version of Rules (2.8) is BROKEN with Commerce 2 ... not sure if the problem also exists with Ubercart ... users of Commerce have to downgrade Rules to 2.7 ]


How to set blog post under event section in Drupal commons I use the Drupal Commons distribution. I already created blog-post depends under group section using OG_MEMBERSHIP. Likewise, blog-post depends under content type event. How to achieve this?

We also have some event section (with particular time/date and location), which is used for maintaining some blog-post (content type).

Can anyone provide some insight about how to do this? I.e some procedure or modules for creating such blog-post (content type) under event.

Entity reference

Not sure if I correctly understand the question, but it sounds to me that using the Entity Reference module might be the solution you are looking for. Here's a quote from the module's project page:

  Provides a field type that can reference arbitrary entities

References

Another option is to consider the References module, which provides D7 versions of the 'node_reference' (and 'user_reference') field types, that were part of the CCK package in D6.

Recommended tutorials

If these module don't help for what you're trying to achieve, then reviewing the amazing set of videos to Learn Organic Groups might help somehow.


How to create new node programmatically, when a new user is created, in Drupal 7? At the time when a new user is created, I want programmatically to create a new node (of some defined type) and make him the owner of that node.

How can I do this in Drupal 7 ?

It is correct that you need to implement hook_user_insert(). The code that needs to be implemented is different from the code you would implement in Drupal 6 because the node body is a field, in Drupal 7 (see Field API).

The implementation of hook_user_insert() should be similar to the following.

function mymodule_user_insert(&$edit, $account, $category) {
  $body_text = 'This is the text contained in the node body.'; // [1]
  $node = new stdClass();
  $node->type = 'article';  // [1]
  node_object_prepare($node);

  $node->language = LANGUAGE_NONE;

  $node->body[$node->language][0]['value']   = $body_text;
  $node->body[$node->language][0]['summary'] = text_summary($body_text);
  $node->body[$node->language][0]['format']  = 'filtered_html';

  $node->title    = 'Node Created Programmatically on ' . date('c'); // [1]
  $node->uid      = $account->uid;

  $path = 'content/programmatically_created_node_' . date('YmdHis'); // [1]
  $node->path = array('alias' => $path);

  node_save($node);
}

The lines marked with [1] are the parts that you need to personalize.


How to programmatically check a view to test if it has any results? What's the most lightweight way to test if a view has any results in it or not? I have a system which creates links to various views, but if the view has no results I want the link to be greyed out. I can only think to load the whole view and execute it, but hopefully there is an easier solution?

I should also note that these views contain contextual filters, if it makes any difference.

Your options:

Trim down the "view" to return only 1 row of possible results.
Attack the problem from the other side. Use a Rule or a Hook to track the condition of your event (eg, "is there new content of type X") in a site variable and check that value instead of your View.

... etc ...


How to redirect all URLs of all terms in a specific vocabulary to custom URLs I am a newbie to Drupal and having hard time to understand how to redirect all URLs for all terms in a specific vocabulary to custom URLs.

I have tried to use Entity Path, but it did not work for me. By some reasons this module sets automatic alias field empty in a term edit form. This breaks Pretty Path module that I am also using.

I have also tried to implement custom hook as described here, but cannot understand how to make it work only for a specific vocabulary, the hook applies to all vocabularies on my site.

I would be greatly appreciate if someone can provide a step-by-step instruction to solve this issue.

edit after I tried to get it to work via Rues

Here is exported Rules

{ "rules_redirect_an_old_path_to_a_new_path" : {
    "LABEL" : "Redirect Categories Terms to Custom Path",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : { "text" : [ "site:current-page:url" ], "match" : "existing_vocabulary_alias/[term:name]" } }
    ],
    "DO" : [ { "redirect" : { "url" : "custom_text\/custom_text\/[term:name]" } } ]
  }
}

The Rules module is your friend to implement such redirects ...

Here is the rule you'd need for it (in Rules export format, just use copy/paste it to import it in your own setup via the Rules UI):

{ "rules_redirect_an_old_path_to_a_new_path" : {
    "LABEL" : "Redirect an old path to a new path",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "the_old_path",
          "operation" : "starts"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Sorry, the old path (= /the_old_path) is no longer in use, you will be redirected automatically to its corresponding path (= /the_new_path)" } },
      { "redirect" : { "url" : "the_new_path" } }
    ]
  }
}

A few more tweaks to make it fit your exact scenario:

change all occurences of the_old_path to your old path corresponding to [term:vocabulary]/[term:name].
change all occurences of the_new_path to your new path corresponding to CUSTOM_WORDS/CUSTOM_WORDS/[term:name].

Attention (1): when applying those 2 changes above, you want to do so using the Views UI. So that you are sure that you'll use the exact Rules syntax, e.g. using "tokens" that the Rules module makes available. But also know that sometimes it's a bit tough and/or tricky to get that right.

Attention (2): it could well be that the Rules condition (with that text_matches) has to be replaced by something using a "regular expression" (instead of that starts in my sample).

Whenever such redirect actually happens, the user will also receive an informational message like so:

  Sorry, the old path (= /the_old_path) is no longer in use, you will be redirected automatically to its corresponding path (= /the_new_path)

If you don't want such message to appear, then just delete the line containing drupal_message in the exported rule above.


Tab field formatter for Entity Reference field? I'm looking for similar module to this: Reference Tabs
but to work with the  Entity Reference module

The Reference Tabs module works with the References module, I need the same functionallity but for the   Entity Reference module

If there is no module for this, then: can I get this with the Field formatter settings using UI jquery tabs?

You can find this functionality in my sandbox.

https://www.drupal.org/sandbox/legolasbo/2383347

Please submit issues if you find any.


How to theme the taxonomy add/edit term form? I would like to change the design of the taxonomy add/edit term form, how do you create a template for the taxonomy "Add Term" / "Edit Term" just like creating a node form template? Not creating a custom module because I already have some custom fields for my term.

As of now this is the code on my template.tpl

'admin/structure/taxonomy/type_of_category/add' => array(
        'arguments' => array(
            'form' => NULL,
            ),
       'template' => 'templates/type-of-build-your-event-category-taxonomy-form-term', // set the path here if not in root theme directory
       'render element' => 'form',
    )

These are the filenames I've tried for my template file:

taxonomy-term--type_of_category-taxonomy-form-term.tpl.php
type_of_category-taxonomy-form-term.tpl.php
taxonomy-form-term.tpl.php
type_of_category.tpl.php

None of it works.

Does anyone have any suggestion on how to make this work?

Thank you in advance!

Use hook_theme() inside your theme's template.php file to set a custom template file (tpl.php) for the taxonomy add and edit forms. However, your theme needs to be set as the Administration Theme, even if Use the administration theme when editing or creating content is not checked.

The taxonomy module implements only one form template file for the taxonomy add and edit forms for all vocabularies. In other words, the taxonomy module does not provide, on its own, a way to have a different taxonomy form template file for a specific vocabulary. However, it is possible for you to add this capability by implementing hook_form_alter() within your theme's template.php file (explained below).

PSA: clear your site's cache after making changes to your templatate.php file.

This is what would be in the template.php file for the theme_name administration theme if you wanted to theme the taxonomy add and edit forms for all vocabularies:

/**
 * Implements hook_theme().
 */
function theme_name_theme($existing, $type, $theme, $path) {
  $items['taxonomy_form_term'] = array(
    'render element' => 'form',
    'template' => 'taxonomy-form-term',
    'path' => drupal_get_path('theme', 'theme_name') . '/templates',
  );
  return $items;
}

$items['taxonomy_form_term'] = array(...: The key taxonomy_form_term indicates the values inside the array are to theme the taxonomy add and edit forms. This key is defined by the taxonomy module.
'render element' => 'form':  $form will be the variable that holds the renerable form array. Note that the words "render path" are separated by a space, and not an underscore.
'template' => 'taxonomy-form-term': The name of the template file without the extension. When the extension is added, the name of the file will be taxonomy-form-term.tpl.php.
'path' => drupal_get_path('theme', 'theme_name') . '/templates': The template file will be in the templates sub-directories within the theme_name theme's path. You are not required to use this exact directory, and can omit path from the array if you place the template file directly inside the theme's default path.

When you implement a theme hook, you will also have a preprocess function that you can implement in your theme's template.php file for that theme hook:

function theme_name_preprocess_taxonomy_form_term(&$variables){}

Create a file named taxonomy-form-term.tpl.php in the templates sub-directory of your theme, e.g. sites/all/themes/theme_name/templates/taxonomy-form-term.tpl.php. Use the $form variable for rendering the form.

// Move the Relations fieldset to the top of the form.
print render($form['relations']);
print drupal_render_children($form);

You can use hook_form_alter() to define keys for hook_theme() to theme the forms for specific vocabularies, specific terms, and/or for just the add (or edit) form. You add the keys to the $form['#theme'] array. You can name them whatever you want, but the order that they appear in the array matters. Keys at the beginning of the array take precedence over others, so add them starting with the most specific keys first. taxonomy_form_term,and possibly other keys, will already be in $form['#theme'], so you will need to prepend your keys to the beginning of the array.

/**
 * Implements hook_form_alter().
 */
function theme_name_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'taxonomy_form_term') {
    $term = $form['#term'];
    $vocabulary = $term['vocabulary_machine_name'];
    $tid = $term['tid'];

    $theme_keys = array();
    if (!$tid) {
      // Key to theme the 'add' form for this vocabulary.
      $theme_keys[] = 'taxonomy_form_' . $vocabulary . '_term_add';
      // Key to theme the add form for any vocabulary.
      $theme_keys[] = 'taxonomy_form_term_add';
    }
    else {
      // Key to theme the 'edit' form for this term using its term id.
      $theme_keys[] = 'taxonomy_form_term_edit_' . $tid;
      // Key to theme the 'edit' form for this term for this vocabulary, using
      // the term's name (after replacing non-alphanumeric characters with "_").
      $term_name = preg_replace('/[^a-z0-9]+/', '_', strtolower($term['name']));
      $theme_keys[] = 'taxonomy_form_' . $vocabulary . '_term_edit_' . $term_name;
      // Key to theme the 'edit' form for this vocabulary.
      $theme_keys[] = 'taxonomy_form_' . $vocabulary . '_term_edit';
    }
    // Key to theme the add/edit form for this vocabulary.
    $theme_keys[] = 'taxonomy_form_' . $vocabulary . '_term';

    // Add the theme keys to the beginning of the #theme array so they have
    // precedence over any preexisting ones.
    $form['#theme'] = array_merge($theme_keys, $form['#theme']);
  }
}

Implement the new theme hooks in your hook_theme(). For example, if you wanted to theme the edit form for the my_vocabulary vocabulary:

$items['taxonomy_form_my_vocabulary_term_edit'] = array(
  'render element' => 'form',
  'template' => 'taxonomy-form-my-vocabulary-term-edit',
  'path' => drupal_get_path('theme', 'theme_name') . '/templates',
);

You will also have a new preprocess function that you can implement in your theme's template.php file:

function theme_name_preprocess_taxonomy_form_my_vocabulary_term_edit(&$variables){}

Create the taxonomy-form-my-vocabulary-term-edit.tpl.php file in the templates sub-directory of your theme, and use the $form variable to render the form.


Ideas on how to create a multi-part form, where the form requires completion/approval by another user Desired form submission workflow:

User A fills out a form, along with an email address for User B
User A submits the form, which then notifies User B by email of a request to complete and approve the form
User B clicks a link in the notification email and is able to complete (and approve) User A's submission

User B would actually be adding extra data to the form, not just "approving" it.

What are your ideas for ways to accomplish such a multi-part form? Are there any modules (besides webform) that could assist with this type of form logic? Would you base this on webform, or Drupal 7's forms API?

All you need is D7 forms API if you are comfortable writing PHP. There are several ways you could go about it. One assumes that the e-mail address of User B is the same e-mail they used to create their Drupal account. You'll need to store the result of User A's submission in a database somehow. Depends if you are already storing data from the DB or not. If not you can use variable_set() to store the e-mail address in one of Drupal's core tables and then variable_get() to retrieve it.

The idea is to save whatever user A stores to the DB after filling out the form. In your form definition, at the top check to see if that value is there. If so, you know user A has completed his part, next step is to check the user accessing this form. If their e-mail address matches the e-mail supplied during user A's part then you display user B's part of the form.


Downgrade Drush from 8-dev to 7 I installed Drush  with composer global require drush/drush:dev-master but it has some problems. I am using Xampp and Windows 8.

How can I downgrade Drush from 8-dev to 7?

# Remove the current version of drush.
composer global remove drush/drush
# Install drush version 7.
composer global require drush/drush:7.*


Which alias do I use to run it with another PHP version? The Server available for our new Drupal project uses an old PHP CLI Version by default. But I have setup an alias in .bash_profile like so:

alias php7=/path/to/php7

and that is working fine. I would like to use Drush, so I cloned the repository, such that I can use Drush with the PHP version from the alias with php7 ./path/to/drush.

Doing so just prints the content of Drush to the terminal.

How can I setup an alias for PHP 7 that allows me to run Drush with that PHP version?

I have added these lines to the .bash_profile file.

alias php7=/path/to/php7
export DRUSH_PHP=/path/to/php7
alias drush="php7 $HOME/path/to/drush.phar"

When I run drush pm-update drupal, I get the following errors.

  The external command could not be executed due to an application error.
  The command could not be executed successfully
  Returned: PHP Parse error:  syntax error, unexpected '[' in    phar:///path/to/drush.phar/includes/startup.inc on line 63, code: 255)
  pm-updatestatus failed.

Why? How can I fix that?

Running drush pm-updatestatus or drush cr works, and drush status shows no errors.

Is there a bug in a specific version?

This is possible by setting the environment variable DRUSH_PHP as described in the documentation.
https://www.drupal.org/node/1302418

Also you can make use of "php" global otpion which allows to specify the absolute path to PHP interpreter.


Relation and Entity Share a Field / Reference Each Other I can't seem to get this to work. I've searched and search, and maybe I'm not using the correct terminology, but I need to add a custom field to a Relation that reads a value from the Entity its related to. Or another way to put this, I need a field from the Relation to update a field in an Entity when the Relation is updated. Example:

Entity -> Worker
Relation -> Employed At
Entity -> Company

I want to update my custom field "classification" through the Employed At Relation and then see that change reflected in the "classification" custom field in my Worker Entity.

If you are talking about the Relation module, then you can use Rules to trigger entity updates whenever a relationship (which is also an entity) changes.

The workflow would be like this :

Trigger on entity update.
Check that entity is a relation.
Update linked entity.

Check the video documentation on Relation, there are two (1, 2) of them talking about Rules.


How to add a checkbox form to a panel? I have set up user comment email notification on my Drupal 7 site. When a comment is posted the author is notified by email. I did it using rules module as described here.

Now the user has the option to get notified or not. For this, I added a new boolean field checkbox on the user's account form page. So currently the user must go to his user account page to change this setting. I would like to make this setting available in a panel.

How can I add a checkbox to a panel in order to control that "notify me setting"? (The panel currently displays content type fields, comment forms etc).

One way is to define your own form and add it to a block in the panel.

After that, you save the value to the user account in the form submit handler.

Background:

Form generation summary

Relevant hooks:

hook_block_info ( define form in a block )
hook_block_view ( return $block['content'] = drupal_get_form('my_module_user_notify_form'); )

and some custom functions you'll need.

my_module_user_notify_form ( return form array )
my_module_user_notify_form_submit ( save to user )

If you use something like Profile2, you could also just embed the relevant user profile form in the block. It would then handle the form build and processing for you.


Customizing Drupal Commerce Bundle module How can I customize Drupal Commerce Bundle module? My situation is that I am developing an Ecommerce site where user can buy Necklaces from necklace collection and lockets from locket collection, both combined to form a single product. So I have used commerce bundle module to achieve this. Now I am stuck in an issue which is what if the user wants to buy multiple lockets or multiple necklaces? Currently the user have the option to select only one of each type to form a single product. How can I achieve multiple selection?

Thanks In Advance

IIRC you may have better results using Commerce Product Add-on, which allows you to have other products as add-ons. Product Bundles work well when you have fixed bundles - i.e. "A fork, spade, and bucket", not "Forks", "Spades", and "Buckets" you want to cross/upsell - if you know what I mean...!

https://www.drupal.org/project/commerce_pado


Create a view with user filter by default and all users after reset I come here because i want to create a view who display all content of type "Document" of my website, but by default i want to show the content of type "Document" of the user connected. And after when i click on the button reset of the view, i want to see all content of type "Document" of all users.

For example the view when i come on the page :

Me | document 1
Me | document 3
Me | document 4
Me | document 6

When i reset the view :

Me | document 1
Jean | document 2
Me | document 3
Me | document 4
Jean | document 5
Me | document 6
Mickael | document 7

this is possible ?

Thanks

This is possible. What you want to look into here is the concept of Views Contextual Filters. So you'll set this up something like this:

This will allow you to have a default view that works on the currently logged in user. Then you can setup another Exposed Filter which shows all authors. Hope this helps.

Thanks to this somewhat related post for the image.


Render Array for hook_field_formatter_view not displaying I'm updating this question on the suggestion of the initial provided answer.

When trying to render out the content of my custom field, outputting the data into a custom theming function to render on to the page when using the suggested method is resulting in the theming function being ignored, even when attempting to output just static strings of text or using the devel module to test it, nothing happens, the code is updated as below

/**
 * Implements hook_field_formatter_view().
 */
function mymodule_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
$element = array();
  foreach ($items as $delta => $item) {
    if ($file = file_load($item['image'])) {
      list($hours, $mins, $secs) = explode(':', $item['time']);
      $time = ((3600 * $hours) + (60 * $mins) + $secs);
      $element[$delta] = array(
        '#theme' => 'mymodule_formatter',
        '#image' => (array) $file,
        '#time' => $time,
        '#comment' => $item['comment'],
      );
    }
  }
return $element;
}

Hook and Theming function

/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  return array(
    'mymodule_formatter' => array(
      'variables' => array('variables' => array()),
      'file' => 'theme_mymodule.inc',
    ),
  );
}

In the theme_mymodule.inc file

/**
 * Returns HTML for a MyModule.
 */
function theme_mymodule_formatter($variables) {
  $output = t('test');

  return $output;
}

I think I'm a little confused about the naming of the theme hook, when I was copying the image module, the #theme variable was just declared as 'image_formatter' but the function named was 'theme_image_formatter', I'm wondering if I've declared my theme hook wrong.

--Previous question--

Im trying to write my own custom field in my own module, I've written the field setup, and it's accepting and evaluating data fine, that's all good. I'm struggling to grasp what I need to do when trying to write my own theming output function. As an example to the parts of code I'm working on:

/**
 * Implements hook_field_formatter_view().
 */
function mymodule_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
$element = array();
  foreach ($items as $delta => $item) {
    if ($file = file_load($item['image'])) {
      list($hours, $mins, $secs) = explode(':', $item['time']);
      $time = ((3600 * $hours) + (60 * $mins) + $secs);
      $variables = array(
        'image' => (array) $file,
        'time' => $time,
        'comment' => $item['comment'],
      );
      $element[$delta] = theme('mymodule_formatter', $variables);
    }
  }
return $element;
}

And my theming function

/**
 * Returns HTML for a MyModule.
 */
function theme_mymodule_formatter($variables) {
  $item = $variables['image'];
  $image = array(
    'path' => $item['uri'],
  );

  if (isset($item['attributes'])) {
    $image['attributes'] = $item['attributes'];
  }

  if (isset($variables['image_style'])) {
    $image['style_name'] = $variables['image_style'];
    $output = theme('image_style', $image);
  }
  else {
    $output = theme('image', $image);
  }

  return $output;
}

Now this returns the correct HTML for my image, so it actually returns a string like

<img typeof="foaf:Image" src="[img_path]" width="120" height="90" alt="" />

However this doesn't actually render on my page, it doesn't come back with an error, it just doesn't show anything.

When I change my $element[$delta] line in my hook_field_formatter_view() function to say

$element[$delta] = array('#markup' => theme('mymodule_formatter', $variables));

By putting the element into a '#markup' array, it does actually render the image, however I don't want to just throw everything into a '#markup' array if that's not the proper way of doing it.

To add markup that's already been prepared to a render array, you would indeed use #markup. There's nothing wrong with using it where appropriate.

However, since you're preparing the markup in the same function anyway, you may as well use the render array version of the call to theme(), e.g.

$element[$delta] = array(
  '#theme' => 'mymodule_formatter',
  '#image' => $image,
  '#another_var' => 'foo',
);

It provides better structure, makes it easier for other modules to alter if necessary, and is better for caching.


How to Add Taxonomy Vocabulary in Rules when User Registers Using the Drupal Rules module, I'm trying to create a rule whereby when a user registers, a taxonomy vocabulary is created.

So far, I've done the following:

EVENT: After saving a new user account

ACTIONS: Create a new Entity, value Taxonomy vocabulary. I enter a name using tokens but it doesn't seem to accept tokens for the machine name. The machine name obviously has to be unique to each vocabulary.

Just to give you a bit more info, each member registering is a Tutor (needs to be the taxonomy vocabulary) and each Tutor will create multiple Students (taxonomy terms).

Can anyone help me with this please? I'm using Drupal 7. Thank you :)

I have checked the rules and I couldn't find a Data Selector for user name. But if you are fine with achieving the same using custom code then you can use the following code.

function YOURMODULENAME_user_insert(&$edit, $account, $category){
   $vocabulary = new stdClass();
   $vocabulary->name = $account->name;
   $vocabulary->machine_name = "tutor_".$account->uid;
   $vocabulary->hierarchy = 0;
   taxonomy_vocabulary_save($vocabulary);
}


Disappearing Content I just inherited a Drupal 7 website from another agency. The site was fairing well in our DEV and STAGE environments. The problem started occurring when we switched DNS over to our PRODUCTION site.

We have all the nodes (from the same content type) that seem to be "randomly" disappearing.

I've made sure to upgrade the core to the latest and any security fixes for any modules that are being used.

I was wondering what I could do to troubleshoot this issue - as I'm exhausting all my efforts and nothing seems to be working.

It looks like a cache problem. I will suggest to do this, as usual backup is always a good idea:

See if this happens also if you are login. You might have your node permissions corrupted. If you rebuild and have a lot of node, it might take a little while to do this.
Turning cache off for page and blocks.
is your content generated by a view? if so check the permission


How to link 'no result behaviour' to node? When editing a view, i'm faced with a difficulty.
There's an image field, in the field settings i set the images (submitted when creating the node) to be linking to the node.
The problem is that in set up a default image in the no result behaviour setting.

<img alt="No Image" class="no-img" src="/sites/default/files/img-custom/no-image.gif" height="190px" />

I'd like this 'default image' to be linking to the node as well.

Any ideas on how to do this ?

An easy way would be to set up a default image for the field. This setting is on the field settings page for the field on the node.

OR

You could to use tokens in the view. Add the path field to the view (set it to not visible), make sure it is higher than the image field. Then you should be able to add an anchor tag around your image tag and use the token value. eg.

OR

You could to use tokens in the view like this. Add the path field to the view (set it to not visible), make sure it is higher than the image field. Under the 'rewrite results' section, check 'Output this field as a link' and add the link path token there.


Make a picture display images if a CCK checkbox is checked I am creating a website in which, there is a view that displays content, and then several icons. theses icons tell the user weather something is available, for example, the icons on this site show you that there is no sound available to listen to, but there is a video to watch. the icons are as follows:

The "find it" and the video buttons are black, but the rest of the buttons are grayed out. (They are actually displaying two different images depending on weather or not there is something to link to.) The reason that they are grayed out is that there is nothing available for them to link to.

What I want is something very similar; I want several icons that will be either grayed out or black, depending on weather or not a checkbox in one of my CCK fields is checked.

How would I go about doing this? Can I do it with a view? Is there a script that I can use?

You will have to rewrite the results of your fields.  NodeOne has some videos that describes what to do and I think this one http://nodeone.se/blogg/learn-views-with-nodeone-part-17-rewriting-fields will have the info you need.

Short answer is that you will configure field > Rewrite Results > Rewrite the output of this field and then use the "REPLACEMENT PATTERNS" that will show only the fields that are available (can't use fields that come after in the list).

You can use [field_NAME]_icon.png where the [field_NAME] will either be black or grey to load the correct icon.  This would work if Black and Grey were the allowed values of a radio button for each field.  Checkboxes should be similar, but I didn't need to use them for my issue.


How to change boostrap seach button class from btn-default to btn-primary? I'd like to change the class from btn-default to btn-primary like says in here: http://getbootstrap.com/css/#buttons

<!-- Standard button -->
<button type="button" class="btn btn-default">Default</button>

<!-- Provides extra visual weight and identifies the primary action in a set of buttons -->
<button type="button" class="btn btn-primary">Primary</button>

Copy /sites/all/themes/bootstrap/theme/bootstrap/bootstrap-search-form-wrapper.func.php

to

/sites/all/themes/my-bootstrap-subtheme/templates

and edit that file at line 14:

 $output .= '<button type="submit" class="btn btn-default">';

to:

 $output .= '<button type="submit" class="btn btn-primary">';

This might be helpful:
https://drupal.org/node/225125


How to render the form tag I am using this code to make the user_profile_form available on my user-profile.tpl.php so the user profile filed can be edited directly from the sure page.

function parce_preprocess_user_profile(&$variables) {
  $variables['user_edit']  = drupal_get_form('user_profile_form', menu_get_object('user'));
}

Then, I can correctly print them individually using this code:

<?php print drupal_render($user_edit['account']['mail']); ?>

It works fine, but the problem is that the <form> tag doesn't appear on the page, and the form doesn't submit. When I add it manually in the template page, it works, but I was wondering how to get Drupal to insert these tags automatically.

I tried something like this (out of pure guess):

function parce_theme($existing, $type, $theme, $path){
  return array(
    'user_profile_form' => array(
      'render element' => 'profile_edit',
      'template' => 'user-profile',
    ),
  );
}

It doesn't work. Am I doing anything wrong?

You have to render the full form, so drupal_render($user_edit) is needed.


Module to upload a file for attachment to many nodes as a bulk operation I have a large number of nodes created with a large subset for a specific term that I would like to add one file to all of these nodes at one time.

For a single case, I have a CCK field for uploading a file. If I had to do this one by one for every node, it would take a long time.

At this time, I am planning on writing code to do this work using code to query the db for all nodes for the term, and loop over each of those attaching the file to the CCK field of each node.

There's one file on the server, I want to attach it to many nodes as a bulk operation, rather than attach the file to each node, one by one. This seems like a problem that would have been run into before. Is there any suggestions on modules that might already do what I want?

If you want to do it a little easier, Views Bulk Operations might be helpful. But otherwise, adding the file to one node, then adding a reference to the file from all the other nodes is the best solution (this way the file isn't independently added to hundreds of nodes, creating hundreds of duplicate files).

You should also check out how FileField Sources adds references to existing files for inspiration.


Can I add external js and css via module info files? I have read that I can add js and css file via .info files. Can I add external css and js files there as well? Eg http://somewhere.com/in_a_galaxy

External JS/CSS files can't be specified in the info file at all. You need to add them via hooks, typically I use THEMENAME_preprocess_page() for things that need to be included on all pages, or you can use drupal_add_js() in your .module file.

And you can refer to this page. Here you can see how many ways you can add script/css files.


joining profile types using views module According to this thread, click here, I need to use relationships to inner join different content types.

I used the same method with profile types but I ended up with the following result.

Instead of using the views UI, do I need to custom code it?

Thanks

Currently it's creating a join for each relationship (each profile type) that's why you see several rows. Question is what would happen if a user has several profile types (can they have that)?

You might get by with putting Distinct on your query.

In Views, fold out Advanced and look for Query settings under Other. Choose settings and check Distinct. Hit save.


Remove classes from field display When fields are rendered they have classes. For example here is the template for a taxonomy term reference field:

<div class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>
  <?php if (!$label_hidden) : ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;

  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item) : ?>
      <div style="display:inline;" class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>>
        <?php
          print render($item);
          // Add comma if not last item
          if ($delta < (count($items) - 1)) {
            print ',';
          }
        ?>

    <?php endforeach; ?>

In the first line you'l see <?php print $classes ?>, in that $classes string there are some classes and I don't want. Obviously I can use php to str_replace in the tpl file to remove the classes I want, but that seems like a very wrong solution. What's the correct way to modify $classes?

You can implement hook_preprocess_field() in your template.php and remove the classes you want after checking the field name .

Update: As @tenken suggested you can also look into Display Suite module.


How to not show a comments field if user logged in I have a field called 'email' I added to my node comments form. However I don't want this to display to users who are logged in. What's the best way to hide this field for logged in users?

I created a module 'hideemail.module' (and info file) with the following code, and flushed caches multiple times...but it's still not working. Note: I double-checked the form name with Firebug and the field name in the resource content type > comments fields.

From hideemail.module (and yes its enabled):

 <?php
 /**
 * Implements hook_form_alter().
 */
function hideemail_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($form_id == 'comment-form' && $user->uid != 0) {
    $form['field_email']['#access'] = FALSE;
  }
}
?>

Use hook_form_alter():

/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($form_id == 'comment_form' && $user->uid != 0) {
    $form['field_email']['#access'] = FALSE;
  }
}


Sharing only one content type between 2 websites I have 2 websites set on the same drupal 7.32 instance. There are completely different, with different databases. But I need to show some content from website1 in website2.

I just need to get a list of nodes from the database for website1 with one specific type and list some details about them in website2.

I know I can get all the nodes with a certain type like this:

$nodes = node_load_multiple(array(), array('type' => 'node_type_here'));

But this (obviously) works within the same site.

Any tips on how I can get them on a different site?

If you are trying to share content between sites, you may want to look at the deploy module....

  The Deploy module is designed to allow users to easily stage content
  from one Drupal site to another. Deploy automatically manages
  dependencies between entities (like node references). It is designed
  to have a rich API which can be easily extended to be used in a
  variety of content staging situations.

To share a Content Type between sites, look into features:

  The features module enables the capture and management of features in
  Drupal. A feature is a collection of Drupal entities which taken
  together satisfy a certain use-case.

  Features provides a UI and API for taking different site building
  components from modules with exportables and bundling them together in
  a single feature module. A feature module is like any other Drupal
  module except that it declares its components (e.g. views, contexts,
  CCK fields, etc.) in its .info file so that it can be checked,
  updated, or reverted programmatically.

Alternatively if you're only trying to share a list of things, what about using RSS feeds from Website 1 and using the Feeds Module to pull it into Website 2?

  Import or aggregate data as nodes, users, taxonomy terms or simple database records.

  One-off imports and periodic aggregation of content Import or
  aggregate RSS/Atom feeds Import or aggregate CSV files Import or
  aggregate OPML files PubSubHubbub support Create nodes, users,
  taxonomy terms or simple database records from import Extensible to
  import any other kind of content Granular mapping of input elements to
  Drupal content elements Exportable configurations Batched import for
  large files

Also as mentioned in the comments the Migrate Module is worth a look.

  The migrate module provides a flexible framework for migrating content
  into Drupal from other sources (e.g., when converting a web site from
  another CMS to Drupal). Out-of-the-box, support for creating core
  Drupal objects such as nodes, users, files, terms, and comments are
  included - it can easily be extended for migrating other kinds of
  content. Content is imported and rolled back using a bundled web
  interface (Migrate UI module) or included Drush commands (strongly
  recommended).


Views & colorbox trigger, make the colorbox image adapt to screen size When I use a colorbox-trigger to open a colorbox, I have to specify the  width  and height of the overlay - unlike in a regular colorbox image field, where it adapts nicely to the screen size.
Is there any way to get such a feature in views?

The colorbox-trigger is normally only required when you want to display HTML in your colorbox. You are then required to set height and width as colorbox is not able to determine the dimensions of the HTML content before it is loaded.

If you want to display an image in a colorbox, there's no need to use the colorbox-trigger but instead just add the image field and use colorbox as image style. Within the field formatter settings of colorbox you can then define the image styles to be used for preview and inside the colorbox. If the colorbox image style exceeds the screen, colorbox will automatically resize the image to fit the screen/window.

In your case, you want to have the image displayed along with custom HTML captions. Thus, you need to define the colorbox content and then set height and width to 100%. The colorbox will then use up maximum available space. However, your image is still not diplayed at 100% width. To achieve that, you would need a quite large image to be displayed in the colorbox, eventually add a wrapper div to it and set a CSS rule like

div.wrapper img { max-width: 100%; }


Taxonomy field in code I am working on a module that has an install file that creates a taxonomy with postal codes.
And then imports all contacts from a csv file.

Now i would like to add a field to my taxonomy (boolean).

How would i approach this?

Thanks in advance!

Create a vocabulary  with fields

taxonomy_vocabulary_save((object) array(
      'name' => 'Vocabulary Name',
      'machine_name' => 'vocabulary_machine_name',
    ));

// Create a field
 $field = array(
    'field_name' => 'field_your_field',
    'type' => 'text',
    'label' => 'your label'
  );
  field_create_field($field);

  // Attach the field to our taxonomy entity
  $instance = array(
      'field_name' => 'field_your_field',
      'entity_type' => 'taxonomy_term',
      'bundle' => 'vocabulary_machine_name',
      'label' => 'Label',
      'description' => 'Description',
      'required' => true,
      'widget' => array(
        'type' => 'text_textfield',

      )
  );
  field_create_instance($instance);

You can create terms like below :

 $term = new stdClass();
    $term->name = ‘Your Term name’;
    $term->vid = 'vocabulary id';
    $term->field_your_field[LANGUAGE_NONE][0]['value'] = ‘data’;
    taxonomy_term_save($term);


How to integrate the Piwik web statistics tracking system in a Drupal site? Right now, I put the Piwik code at the end of html.tpl.php.

How I can integrate it in a Drupal site, so that this JavaScript can be aggregated? Or better loaded and keep my template clean?

Can I put this code to an external JavaScript file (+ how?) and then just declare it at theme.info?

Even better, use the drupal module that does all the hard work - Piwik Web Analytics.
Here is a quote about it (from the module's project page):

... Adds the Piwik web statistics tracking system to your website.
The module allows you to add the following statistics features to your site:

Single/multi domain tracking
Selectively track/exclude certain users, roles and pages
Monitor what type of links are tracked (downloads, outgoing and mailto)
Monitor what files are downloaded from your pages
Cache the Piwik code on your local server for improved page loading times
Custom variables support with tokens (D7 only)
Custom code snippets
Site Search
Drupal messages tracking
Modal dialog tracking (Colorbox)
Access denied (403) and Page not found (404) tracking
User ID tracking across devices
DoNotTrack support