# Question
Title: Undefined error: 0 OR Unable to load autoload.php. Drush now requires Composer
I've installed drush in /usr/local/lib/drush/drush and composer in /usr/local/bin/composer.

When I try to run drush /usr/local/lib/drush/drush I get the following:

> /usr/local/lib/drush/drush: line 129: /Applications/MAMP/bin/php/php5.2.17/bin: is a directory /usr/local/lib/drush/drush: line 129: exec: /Applications/MAMP/bin/php/php5.2.17/bin: cannot execute: Undefined error: 0 –

OR the following:

> Unable to load autoload.php. Drush now requires Composer in order to install its depedencies and autoload classes. Please see README.md

What am I doing wrong? I'd like to install drush to use with MAMP if anyone has any suggestions. I've done through the readme and nothing seems to be working.

# Answer
> 8 votes
Drush switched to requiring composer. The documentation provides details on how to install both composer and drush, but it boils down to:

* Install composer globally:

```
curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer

```
* Install drush globally (for your user), you can specify the version:

```
composer global require drush/drush:6.*

```
* Add the composer path to your path (in your *.bashrc* or *.zshrc* or other):

```
export PATH="$HOME/.composer/vendor/bin:$PATH"

```

# Answer
> 3 votes
These were the steps I used to install drush globally using composer in Linux (not in ~/.composer/vendor/bin logged in as root which makes absolutely no sense):

1. Login as root
2. Install composer if necessary. See. http://getcomposer.org/doc/00-intro.md#system-requirements.
3. composer global require drush/drush:6.\* or composer global require drush/drush:dev-master
4. cd ~/.composer
5. composer config --global bin-dir /usr/local/bin
6. composer config --global vendor-dir /usr/local/share
7. composer install
8. cp -r vendor/ /usr/local/share/drush/drush/
9. cd /usr/local/share/drush/drush
10. composer install

Now any user with /usr/local/bin in their path can run drush.

Security precaution: You might want to chown and chmod /usr/local/bin/drush so only authorized users in a certain group can execute drush.

Notes: Lines 5 and 6 create the file ~/.composer/config.json. Line 10 is needed to delete (yes, delete) the /usr/local/share/drush/drush/vendor/drush folder which is unnecessary.

# Answer
> 2 votes
Have you googled for like "OSX + drush + mamp" ... http://kerasai.com/blog/2013/07/30/easy-way-make-drush-work-mamp

> The main hiccup with drush on MAMP is that drush doesn't use the PHP packaged with MAMP and commonly the PHP shipped with OSX is not configured to meet Drupal's requirements. It's possible to reconfigure the PHP that ships with OSX to meet Drupal's requirements, but wouldn't the smart thing to do be to use MAMP's PHP? You can do this by adding the following line to ~/.profile, adjust as needed.

```
alias drush='DRUSH_PHP=/Applications/MAMP/bin/php/php5.4.10/bin/php /usr/local/drush/drush'

```

---
Tags: drush, composer
---


# Question
Title: How to change programmatically the link of a field in a View
I have a View, with a hidden field with a URL, and an image field which has the following property:

Output this field as a link and linked to the URL field: `[field_url_slider]` and `_blank` as Target.

I want to change dynamically the behaviour, so when the image is a given one, to rewrite programatically the URL and also the Target.

In `hoo_views_pre_render` don't see how to do it, because the complete link, i.e. `a href=""`, etc. is not any data of `view->result` and I don't know if this can be achieved via `$view->display` (I only want to change a result). So, in a few words, I want to change the HTML output of the Views display for just a result.

# Answer
> 1 votes
I have finally solved using hook\_views\_pre\_render and setting the display of one of the fields to "do not display", and adding as pure HTML around the field, replacing the content with the other field. In other words, by writing at low level the link of the field.

Surely there must be another way of doing this.

---
Tags: views, theming
---


# Question
Title: How to add images (as entity) in ckeditor?
The background: I'm creating an asset management system with Drupal, so for this purpose I've created a content type called `Image` which has an image (widget) attached to it. I then use module Entity Reference to link this content type with other content types (for instance, `Article`).

So far so far. This works for my requirements, however I'd like to:

1) Add the ability to upload a new image (therefore new node) from within `Article` 2) Use an existing entity (previously created) within CKEditor in `Article`

Is it possible? How?

# Answer
I would take a look at something like Shortcode module. In general you are looking to insert a token for your image entity.
> 0 votes

---
Tags: wysiwyg, media
---


# Question
Title: Different suffix for multiple field value
I have multiple field value -3 value-, each value have a defferent suffix. For exemple there is a field vessel consumption with 3 value, each value have a unit of measure: HFO or MGO, MDO.
Is there a way to show every value with a suffix or I have to use text field type?

# Answer
> 0 votes
You could use field collection and create two fields, one for the value and one for the suffix.

---
Tags: entities
---


# Question
Title: After Module updates got "Warning: require_once() "
I am using **Drupal -7** and my website is on **cloud(not local host)**. This is **NOT** a multi site and using **Omegasubtheme**.

I have just updated **workbench Moderation** module from **1.3 to 1.4** and have also added **Workbench Media module(7.x-1.1)** to my dev. site. After running update script, I got bunch of errors on my site. So, I again moved Worbench Moderation Module from **1.4 to 1.3**.

**Devel Generate** and **Devel Node Access** Modules were enabled in my site and I made those module disabled.

After that, I got these errors so I made them enabled again. I found this thread but, this is for **database.inc** for memory allocation error message in database.inc.

**Devel Module**

Can anyone help me how to get rid of these errors?

**Errors which I got on front page:**

> Warning: require\_once() \[function.require-once\]: Unable to allocate memory for pool. in \_registry\_check\_code() (line 3177 of /docroot/includes/bootstrap.inc). Warning: require\_once() \[function.require-once\]: Unable to allocate memory for pool. in \_registry\_check\_code() (line 3177 of /docroot/includes/bootstrap.inc).

**Errors on available updates module page:**

> ```
> Warning: require_once() [function.require-once]: Unable to allocate memory for pool. in menu_execute_active_handler() (line 515
>
> ```
>
> of /docroot/includes/menu.inc). Warning: require\_once() \[function.require-once\]: Unable to allocate memory for pool. in module\_load\_include() (line 330 of /docroot/includes/module.inc).

# Answer
> 1 votes
It would be interesting to see if your problems could be related to the "memory limit", which might not be high enough (anymore), especially because of the "... have also added Workbench Media module ...".

Assuming this is NOT a multi site, consider editing your /sites/default/settings.php, and change the line to set the memory limit. If it is a multi site, then edit the settings.php file related to the site where you are experiencing the problem.

That line in settings.php should look similar to this:

```
ini_set('memory_limit', '100M');

```

The '100M' in it might be some other number. Whatever the number is, try to increase it with like 50%, or maybe even double it to see what happens after you do so (of course do not forget to save the file after increasing that number).

Another possibility that you may want to verify, is to "perform a clear cache" (it doesn't hurt, and occasionally helps solving various issues).

Curious to hear if that helps somehow ...

---
Tags: 7, debugging
---


title: Overriding user profile form

text:
# Question
Title: Overriding user profile form
So I have this function:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function my_module_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
  dsm($form);
}

```

What I want to do is to remove "Language settings" fieldset with all the radio buttons inside it. But for some reason I don't have any array element which is responsible for displaying this data. I've read that this should be $form\['locale'\] but it's not there for sure. What migght cause this kind of behaviour?

# Answer
It could be that your form\_alter happens before the locale field is added. Make sure your module runs last.
> 2 votes

---
Tags: users, i18n-l10n, forms
---


# Question
Title: How to programmatically remove a user from an organic group
I have found many examples about how to add a user to an organic group but I can't find any info on how to remove a user from an organic group programmatically. Does anyone have an example of how to do this?

# Answer
Part of me thinks that `og_membership_delete` would be a good option, you can pass the entity ID in as a parameter (and by "can", I really mean "need to"). Also, `og_ungroup` seems useful as well.

You can find more functions that OG defines at: http://www.drupalcontrib.org/api/drupal/contributions!og!og.module/7

Here's an example of `og_ungroup`:

```
og_ungroup('node', $gid, 'user', $uid);

```
> 4 votes

---
Tags: 7, organic-groups
---


# Question
Title: How to manage video content including chapter markers and CC
I'm building a site that has 46+ videos associated with it. I'm using Mediaelement.js. Each video has at least two language .srt files, a .vtt chapter marker file and two video sources, mp4 and WebM.

My project mananger says, "do it how ever is easier for you."

Part of me is tempted to upload all the files, then just copy-pasta the mediaelement code and change the file names. But this is laborous, time-consumming and prone to error.

As I'm writing this I think that I need to have a content type that has 5 or more "file upload" fields. How do I use the media module to my advantage?

# Answer
Here's the solution I'm working on:

new Content Type: Video.

This content type has file fields for each file, two video type, up to 10 closed caption files, and chapter markers.

Then I add a `node--video.tpl.php` Within the node template I'm then doing this:

```
 $mp4 = ltrim ($node->field_mp4_video[und][0][uri], 'public:/');
 $webm = ltrim ($node->field_webm_video[und][0][uri], 'public:/');
 $vtt = ltrim ($node->field_chapter_markers[und][0][uri], 'public:/');
 $encc = ltrim($node ->field_closed_captions[und][0][uri], 'public:/');
 $escc = ltrim($node ->field_closed_captions[und][1][uri], 'public:/');

```

ltrim trims the `public:/` from the front of the string and printing that inside the `video element`:

```
<video width="100%" height="100%" style="width:100%; height=100%;" id="player2" controls="controls" >
  <source src="../sites/default/files/<?php print $mp4 ?>" type="video/mp4">
  <source src="../sites/default/files/<?php print $webm ?>" type="video/webm">
  <track kind="subtitles" src="../sites/default/files/<?php print $encc ?>"  srclang="en" />
  <track kind="subtitles" src="../sites/default/files/<?php print $escc ?>"  srclang="es" />
  <track kind="chapters" src="../sites/default/files/<?php print $vtt ?>"  />
  <p>Unsupported in this browser.</p>
</video>

```

The un-solved issue is if there's more than the English and Spanish closed-captions. Certainly solvable, but probably outside of the scope of the project as currently budgeted.

Also, Drupal is throwing an error `Notice: Use of undefined constant...`. I'll tackle that in a separate question.
> 0 votes

---
Tags: media, files
---


# Question
Title: How can I return actual JSON using Drupal?
I'd like to implement a simple AJAX function locally that allows me to autocomplete node titles of already existing nodes as the user types. To that end, I need the ability to have an API that I can search on node titles. The problem is that when I output raw JSON, it comes surrounded by tags. So, no matter what I do, I keep getting...

```
<html>
    <head>
    </head>
    <body>
        <pre style="word-wrap: break-word; white-space: pre-wrap;"> {json here}</pre>
    </body>
</html>

```

I've tried implementing a custom page template that only outputs content already, that produced the same results. Here is how I am currently doing this, in my module file...

```
<?php

/**
 * Implementation of hook_menu()
 */
function content_relation_menu() {
    $items = array();
    $items['api'] = array(
        'title' => 'Search',
        'page callback' => 'content_relation_get',
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
    );

    return $items;
}

function content_relation_get($term = '') {
    drupal_add_http_header('Content-Type', 'application/javascript; utf-8');
    $var = json_encode(
        db_query("SELECT nid,title FROM {node} WHERE title LIKE :title LIMIT 5", array(":title" => $term.'%'))->fetchAll()
    );
    echo $var;
    exit(0);
}

```

How can I return JUST raw JSON?

# Answer
> 18 votes
For Drupal 6, you can use drupal\_json

```
function content_relation_get($term = '') {
    $result = db_query("SELECT nid,title FROM {node} WHERE title LIKE :title LIMIT 5", array(":title" => $term.'%'))->fetchAll()
    );
    drupal_json($result);
    exit;
}

```

For Drupal 7, change it to use drupal\_json\_output

```
function content_relation_get($term = '') {
    $result = db_query("SELECT nid,title FROM {node} WHERE title LIKE :title LIMIT 5", array(":title" => $term.'%'))->fetchAll()
    );
    drupal_json_output($result);
    drupal_exit();
}

```

It would also probably be safer to parse out the query to sanitize, error check, etc, instead of just trying to return the result.

# Answer
> 5 votes
I saw that there was no answer provided for Drupal 8.

In order to process JSON in Drupal 8, use the following code:

```
  <?php
     use Symfony\Component\HttpFoundation\JsonResponse;
     // ...
     $options = _menu_get_options(menu_get_menus(), $available_menus, array('mlid' => 0));
     return new JsonResponse($options);
  ?>

```

You can read more about it here

---
Tags: nodes, javascript
---


# Question
Title: How to make a Shortcuts menu that open with new window or tab?
In Drupal 7, I added the "IMCE" url(www.mydomain.com/imce) into the Shortcuts menu for user to upload file. How to make this menu to open in a new window or tab?

# Answer
Shortcuts are menu items, so you might be able to use Menu Attributes to set the target to `_blank`.
> 0 votes

---
Tags: files
---


# Question
Title: Views: Output field as a link with URL provided by another field?
So I have a content type with fields: image\_field and url\_field.

The view displays the field\_image for all items. Now I want the user to click this image and go to the link in url\_field on the same item.

If I try to write the output as a link it requires me set a path for field and it will always be the same URL for all items.

How do I tell it to display image\_field with URL from it's own url\_field?

# Answer
You can use replacement tokens. URL field first in the list, hide the field, rewrite the image to render with a link, use the replacement token for the URL field as the link.

Example: https://www.youtube.com/watch?v=fuNkaGOwnR0
> 1 votes

---
Tags: views
---


# Question
Title: Field names returned in search snippet. How to hide?
Field names are being returned in the search snippets on my search results page, like so:

> Academic Culture
>
> Body Text: The academic culture of your host country may be quite different from what you experience here at ...

The bit that reads "Body Text:" is the field name. What's weird is that the field name is only returned when the snippet is at the beginning of the field. So, depending on the search it could return something like this:

> Academic Culture
>
> ... academic culture of your host country may be quite different from what you experience here at ...

Note the absence of "Body Text:".

Is there a way to disable/hide field names in the search snippets?

# Answer
> 1 votes
There is usually a view mode for Search results, you can control the field label visibility settings there. See Admin \>\> Structure \>\> Content Types \>\> \[Content Type\] \>\> Manage Display \>\> Custom Display Settings. Activate the view modes for search and customize away.

---
Tags: entities, search
---


# Question
Title: how to show a view with one to many relations
I am using Entity Reference, what would be the best way to show the parent entity on the top (4 columns ) and then the children entities in horizontal rows below? Can Display suite be used?

# Answer
Yes, Display Suite would work for this. With the right modules and configuration, you may not even need to create a View.
> 1 votes

# Answer
Yes I did it with display suite without a view, by fiddling with the custom fields that you can add with display suite
> 0 votes

---
Tags: views
---


# Question
Title: How to manage text on my site that's not node content?
I have text on my site that isn't node content, such as:

* footer legal text
* "Subscribe to our newsletter"
* "Browse our categories"
* etc.

I need to save my development work as a **Feature** but I also need content editors to be able to edit the text. But I don't want to give them permission to edit all blocks. In the not too distant future, the site will be extended to another region so this content will also need to be translated.

Is there a technique / solution designed for housing this data?

I could create a new content type and create a new field for each piece of text. I could easily print the field in TPL files but it might be a little harder to print it in blocks. I also don't know if its performance inefficient to do this, does the whole node object get loaded when you print a single field?

I've heard about (but not used) the Nodeblock module. It looks like this would work but I don't know how easy it will be to work with the Features module (I don't think you can feature nodes).

One nice thing about the first method is that the field label could be descriptive eg "Footer legal text" which would make the translation side of things easier.

# Answer
Consider using the Bean module for this. Here is a quote about its project page:

> Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

If you'd **grant content editors** the appropriate **Bean permissions**, it appears to me that you might be close to a possible solution to what you're looking for.

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.

PS: This module only started as of D7, and is already integrated in core in D8 ...
> 5 votes

# Answer
You can make custom block (structure \> blocks \> add block), or you can make a new custom menu (structure \> menus \> add menu) and keep it in the region your want to by navigating to (structure \> blocks).

You can also make new regions if you doesnt want to use exixsting regions and print your content somewhere else and assign their display location by printing in .tpl file. and then allocate menu/block to it

**Printing block**

To create custom regions, visit: https://www.drupal.org/node/1088718#comment-4194802 How do I create custom regions in a theme?
> 1 votes

# Answer
I am suggesting to create one block.have you tried with the same.? Like, in block's body, just put the html of whatever you want to put throughout the site. and enable this block in footer or header which will be available through your site. I guess this will solve your problem.
> 1 votes

# Answer
From what I get you need to grant some privileges to a specific block not all of them to some users or rolls.

To do so I recommend you to use block\_access module.

> This module adds a set of global permissions for creating, viewing, moving, enabling, disabling and configuring blocks as well as permissions at the individual block level. These permissions only affect the admin interface, front-end view access is handled in core.

You also need to check the Patch against block\_access-7.x-1.x to allow configuration of access settings per block. more discussion of this module is in How to use Block Access with specific Block?
> 1 votes

# Answer
It sounds like you may have some Views titles you also want to manage. You can open up the Views title as a basic setting that site content managers can edit with this module: https://www.drupal.org/project/views\_ui\_basic
> 1 votes

# Answer
The NodeBlock module is very easy to use and easy to implement. So, content editor can easily edit the block same way as any other page.

You can apply Nodeblock in you content type which you wanted to make it as a block like showing in a picture.

**NodeBlock Setting in Content Type**

---

**NodeBlock in a page**

If you want to give editing access for just one page then you can use "Nodeaccess" module.
> -1 votes

---
Tags: 7, blocks, features
---


title: Domain context ignores domain aliases

text:
# Question
Title: Domain context ignores domain aliases
I'm using Drupal 7, Context and Multisites. A Context determines which Block to render based on the domain's URL. This works fine for the live site with the actual URL.

My dev environment uses Domain aliases to make it work. For sampledomain.com, I have an alias for sampledomain.local. Context seems to ignore this alias and skips rendering the block on my dev machine.

Is this a known bug with Context/Multisites? Or is there an additional configuration option to make this work?

# Answer
> 0 votes
I was able to use Context Debug All to determine that the context is actually being loaded. The error is related to a different issue.

---
Tags: multi-sites, 7
---


# Question
Title: How to disable edit their own profile per role?
In Drupal 7, How to disable the edit profile permission per role? I found the "Tab Tamer" module, but this does not apply the feature per role.

# Answer
> 5 votes
There is one module called "UserProtect" module. With this module you can hide edit account, edit password, email from based on user roles and for specific users too.

You can set permission by going **/admin/people/permissions** where you can see **User protect** and you can configure it **/admin/config/people/userprotect** here

**Protected Roles**

---

**User Protect Module Permission**

For example, I don't want to give permission to my Test One and Test Two Users for edit their profile. So, I wanted to hide it from **"Test One"** and **"Test Two"**.

Hope this helps!

---
Tags: 7
---


# Question
Title: How to set up salt hash while installing Drupal 7?
I am no expert in salt hash but while I was installing Acquia Dev, I noticed a variable `$drupal_hash_salt`, filled with a randomly generated string, in settings.php of newly installed Drupal 7 and a file called .hashlist under root drupal installation folder. Can someone help me understand the salting concepts in Drupal 7?

When I tried to import a new version of Drupal 7 site, I could not see any random string in that same variable and also no .hashlist file. I may be doing something wrong here. I tried googling around to see if I could find something useful but no luck.

So I have 3 questions

1. How to do salt hashing in Drupal 7 during/before installation process?
2. What kinds of data are being hashed (other than password)?
3. How can I extend this salting concept further?

Thanks a lot in advance.

# Answer
> 4 votes
I talk a bit about the new salts in my article on Improvements to Security in Drupal 7 which may help answer these questions.

Depending on when you need the salt you might be able to use drupal\_get\_hash\_salt or you may be able to leverage the code it uses to create your hash.

Can you expand on "extend this salting concept" ? What kind of extension do you want to do?

Salting is a standard part of hashing. You can read about salting on the php hashing pages. Changing your salt after the site is live may cause some problems in specific areas. My guess is that it depends on which modules you have installed and which features you are using. The one-time-login links are likely to stop working, but I'm not sure of other specific functionality that would stop.

# Answer
> 0 votes
@rfay the Wayback Machine has us covered: https://web.archive.org/web/20131018191043/http://drupalscout.com/knowledge-base/improvements-security-drupal-7

---
Tags: 7, security
---


# Question
Title: How to download files through IMCE file browser?
I found the IMCE has upload and delete buttons, but not download. Is there a way to add download feature, if so how?

# Answer
There isn't one built into the module. One work around is to use IMCE user file browser (**/user/\[uid\]/imce**) and click on the preview image. It will open up the image URL in a new tab/window where you can download it through your browser.
> 1 votes

---
Tags: 7, files
---


# Question
Title: Drupal 6 CCK date field is saving current time when the time field is left blank
I have a node type='event' that has a "text field with date popup calendar". The date format is "05/13/2015 - 7:02pm". On the edit page, the form renders as two fields: a calendar popup text field and a separate field for the time. This field is mandatory; but, it has been requested that the time value not be mandatory.

The problem occurs when the node is saved. It saves the date correctly; but, it inserts the current time if no time has been entered. Is there a way to have it not enter a time or just default to midnight if no time has been entered?

# Answer
Set your **Default value** for your event date field to **Blank**. This will make the date/time field empty upon default. A user has to enter date if it's a required field, but can leave the time field blank. If it's left blank it will default to 00:00.
> 0 votes

---
Tags: entities, datetime
---


title: Views block per node

text:
# Question
Title: Views block per node
I created a content type call Block. I want to use Views to display this Block content type per node. It means when I create a Block node, Views will create a block for me. So far I don't see any setting in Views allow me to do this. If it is possible I prefer using Views to do it instead of install another module like Nodeblock(nothing against it, just don't want to install another module when existing one can do it).

My original question is a bit confusing. To clear it up:

1. Is it possible for user to create a block by using a node? For example, user create a new node call 'My day' will automatically create a new block call 'My day'.
2. Is it possible to accomplish it by using Views module?

# Answer
In your edit view, click on Advanced (located on the right side) For **Contextual Filters** click add. Search for "nid" and select Content: Nid

Under When Filter Value is not available, select the 2nd one (provide default value). For Type, select Content ID from URL.

This will filter your view, and show you the fields only from the current "Block content type" node that you're viewing.
> 1 votes

# Answer
I don't know of any way to achieve what you're trying to do by only using the Views module. However, whenever you're ready to consider adding another module (such as the nodeblock you mentioned), I would start by looking at the Bean module (instead of nodeblock). Here is a quote about its project page:

> Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

Combined with the options available for granting the appropriate **Bean permissions**, it should give you a lot of flexibility about how exactly you want to use this (great) module in your specific case. As a bonus, the Bean module also works great in combination with the UUID and UUID Features Integration modules. On top of that, after you become familiar with the Bean module, you might find other cases in your site where you also want to use the Bean module (which somehow compensates the fact that you need to add another module).

Note: your question contains "Block node" and "block", which I find a bit hard to differentiate to correctly understand your question. Therefor consider editing your question by replacing "Block node" by something like "MyBlocktype node" (or anything different from just "Block").
> 1 votes

---
Tags: views
---


title: Immediate notifications dilema

text:
# Question
Title: Immediate notifications dilema
I want to notify users immediately when a node they’ve subscribed to is commented on, but then not send them any more notifications (from any other node either) until they’ve visited the site. This is because I want users to immediately know when a discussion has a reply, but not have their inbox filled up with unnecessary emails. As far as I know no module can do this.

Im more of a themer than developer but it occurred to me that maybe this could be done with the Rules module. It would work this this:

1) When a node is commented on, send an email to the user if the user doesn't have role of ‘no’, and then add a role of ‘no’ to user.

2) When the user logs in, wait until they log out or are timed out, and then remove the role of ‘no’.

My reason for waiting until the user logs out before removing the role is I don't want them to get emails of comments while they are on the site. These may be emails from a discussion they are replying to several times while still logged in.

One issue could be if a user closes down their browser or leaves it open without refreshing it, but doesn't log out. Then Rules won't send them an email until they are timed out but they won't be aware or any comments made before this. Is there a solution to this?

Does anyone know how other forum software deal with this situation of wanting to have immediate notifications but not send loads of pointless emails to users?

# Answer
Regarding the "... other forum software ..." near the end of your question: how about using the Flag module and its Rules integration?

Consider "somebody subscribing to some node" as the equivalent of "somebody flagging that node". And if your current technique to "send them notifications" is not flexible enough to do so in combination with the Rules and Flag module, then you may want to consider the Message module (which goes together with Rules and Flag very well also, and which is also used in some of the popular distributions).
> 1 votes

---
Tags: rules, nodes, notifications
---


# Question
Title: Display message instead of redirecting to Access Denied page
I'm using Commerce Auction module for an auction site. I want to display a message when the auction time out occurs for a certain product and at the same moment the user clicks on place bid tab.

Scenario:

1. Created an auction item
2. Started bidding with different users.
3. When auction time out just occurs and at the same moment any user clicks on Place Bid tab that user is redirected to Access Denied page.

Now instead of redirecting to access denied page, how to display a message on the same page?

I have set a rule for mailing purpose on the same event. I also tried using "display message" rule for this event. But still it is displaying Access Denied message. I want to show different message only for this event.

# Answer
> 0 votes
# 1st attempt

Maybe the Disable Messages module can help here? Here is an excerpt from its project page:

> Gives a site owner options to disable specific messages shown to end users. The core drupal message system as offered by drupal\_set\_message is an excellent way for modules to send out messages to the end users. However not all drupal site owners are keen to show all the messages sent out by drupal core and all modules to their users. This module gives site administrators a reasonably powerful way to filter out messages shown to the end users.

Some of its features which might help in this specific case:

> * Filter out messages that match a full text string exactly.
> * Filter out messages that match a regular expression.
> * Apply filtering only for specific paths.

# 2nd attempt

If the 1st attempt doesn't help, then you may want to try to expand the rule you already seem to have (as per your "*I have set a rule for mailing purpose on the same event*"). I.e by adding a rules action to flag the user (using the Flag module, with a flag you only use to indicate your scenario just happened to that user (let's say you label it "TimeOut").

Together with this, create an additional rule like so:

* Rules Event: Drupal is initializing
* Rules Conditions:
    + Current path matches your "no access" path (whatever that is in your case).
    + User is flagged with the "TimeOut"
* Rules Actions:
    + Remove the "timeOut" flag (=unflag) for the current user.
    + Set your message.
    + Perform a redirect to a path that fits your needs.

---
Tags: 7, users
---


# Question
Title: How to implement a set of images / diagrams in a website?
I am an experienced PHP developer but am just finding my feet with Drupal. I am creating a personal website using the Bootstrap theme and want to upload some images/diagrams as part of it. They will be publicly available.

My question is, should I just create a directory in the web root, ftp the images there, and put raw `<img>` tags in my pages? Or should I install a module and get it to do the work for me?

I am very happy to use the first (i.e. manual) method, but I'm thinking that there might be hidden advantages in letting a module handle it for me. For example, if a module does the uploading, it would presumably have particular css classes that it would apply to the `<img>`.

At this stage I will be the only one creating content.

# Answer
> 1 votes
To answer your question, I think it depends on how you plan to use those images ...

## Option 1: use individual images to beef up specific content pages

In this case you just upload those images to a folder such as sites/default/files, and then you could just use them (refer to them) with a typical `img` tag. To make sure that these images will actually also be rendered (when viewing the page), make sure that the "text format" used in the node does allow the img-tag. Typically for a node using the "Filtered HTML", it could well be that the img-tag is not allowed (yet) as one of the available HTML tags. In that case, your HTML code does include an 'img" tag, but when viewing the saved node the image is not rendered (visible). To resolve it, within admin you must enter the img-tag as one of the allowed HTML tags for the text format used in the node.

## Option 2: visualize them in the format of a Gallery

Talking Drupal #083 is a great podcast about this topic, and includes a lot of recommended modules in this areas. Just to mention a few of them (mentioned on the linked page):

>

---
Tags: 7, media, theming
---


title: Why drush needs a stage server

text:
# Question
Title: Why drush needs a stage server
I have seen a lot drush setups in the past and every setup had a stage server configuration Is there a reason why thay have

* a development server
* a *stage server* and
* a productive server

What are the advantages if you have a sage server and must there be such a server osr is this optional?

# Answer
There are a number of scenarios where having dev, stage and live are useful.

Example: minor updates.

1. Run `drush pm-update` on dev, test and make sure everything is okay.
2. Push your code to stage / test, run `drush updatedb`, and make sure everything is still okay.
3. Push your code to live, run `drush updatedb`, and confirm everything is still okay.

The point here is that the operation of 1. and 2. are slightly different; by testing your deployment on the stage server before bringing it live, you can confirm that the deploy will go okay (i.e. there are no uncommitted components on the dev machine, or all state needed for a successful deploy is part of the deployment process.) If you did not test this, then you'd break the live site if you forgot to commit an important file, or otherwise did not faithfully update the components used in deployment.
> 1 votes

---
Tags: drush
---


title: Get Div's Text in Drupal Forms API

text:
# Question
Title: Get Div's Text in Drupal Forms API
I have this code below:

```
$form['id']['mypreview_modal'] = array(
    '#type' => 'item',
    '#markup' =>
        '<div id="mypreview_modal" title="ID Preview">12345</div>'
);

$form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Save',
    '#ajax' => array(
        'event' => 'click',
        'callback' => 'myid_user_page_form_ajax_submit',
    ),
);

function myid_user_page_form_ajax_submit() {
     $myid_user = ; //Get mypreview_modal's text/innerHTML
}

```

I want to get `mypreview_modal` text and assign it to `myid_user`. How will I do that?

# Answer
An AJAX callback is not a submission callback; the submission callback is the usual one a form uses, independently from the form using AJAX or not.
An AJAX callback is given the `$form` and `$form_state` parameters, allowing it to produce a result, which it returns for rendering. Since it gets `$form` as parameter, accessing that value simply means parsing `$form['id']['mypreview_modal']['#markup']`.

```
function myid_user_page_form_ajax_submit($form, $form_state) {
  // Parse $form['id']['mypreview_modal']['#markup'].
}

```

Keep in mind that usually an AJAX callback just returns the part of the form that needs to be rendered. See `poll_choice_js()` as example.

```
function poll_choice_js($form, $form_state) {
  return $form ['choice_wrapper']['choice'];
}

```

The rest is done from the submission handler. (In the case of the Poll module, and for the form using the previous AJAX callback, this is `poll_more_choices_submit()`.)

```
  // If this is a Ajax POST, add 1, otherwise add 5 more choices to the form.
  if ($form_state ['values']['poll_more']) {
    $n = $_GET ['q'] == 'system/ajax' ? 1 : 5;
    $form_state ['choice_count'] = count($form_state ['values']['choice']) + $n;
  }
  // Renumber the choices. This invalidates the corresponding key/value
  // associations in $form_state['input'], so clear that out. This requires
  // poll_form() to rebuild the choices with the values in
  // $form_state['node']->choice, which it does.
  $form_state ['node']->choice = array_values($form_state ['values']['choice']);
  unset($form_state ['input']['choice']);
  $form_state ['rebuild'] = TRUE;

```
> 1 votes

# Answer
If you want to pass values you should just use one of the form api form elements. Doing something similar to this

```
// This shows a preview to the user but doesn't actually pass any values.
$form['mypreview_modal'] = array(
    '#type' => 'item',
    '#markup' =>
        '<div id="mypreview_modal" title="ID Preview">12345</div>'
);

// This passes the actual value (change this dynamically aswel).
$form['id'] = array(
    '#type' => 'hidden',
    '#value' => 12345
);

$form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Save',
    '#ajax' => array(
        'event' => 'click',
        'callback' => 'myid_user_page_form_ajax_submit',
    ),
);

```

After form submission you will be able to access all the user input via the `$form_state`, notice that 2 parameters have been added to the submit handler.

```
function myid_user_page_form_ajax_submit($form, &$form_state) {
    $myid_user = $form_state['input']['id']; // Gets the value of the hidden form element.
}

```

On a side note, any submit button automatically calls the submit handler. Wich is normally used to process the input of the form. As previously mentioned you should use that instead of your custom ajax callback for processing.
> 1 votes

---
Tags: 7, forms, ajax
---


# Question
Title: how to have conditional Help text for a listbox field
Remember the create password page of Drupal! While you are entering characters it tells you how strong your password is!

Now I want to have something like this in a list box but a bit different. I want to show an image and a text depend on the item which is selected in the list box! How can I do it? My first try was adding some code in help text of the field, but it doesn't work. What are your suggestions?

I can not use conditional field because I must add 60 conditions and it is illogical. Ao I need a programmatic way. The java script code and how to I make it dependent to two list boxes? I add a markup field to my content type but I don't know who to find which item is selected in the list box with ajax ind how to show an item depend on it.

# Answer
> 4 votes
You don't have to code for this. You can use Conditional Fields to achieve it.

You can then use "Manage Dependencies" section (alongside manage display) to set the dependencies:

Then you can see the different fields being enabled or disabled depending on the entered input:

List option "**No**" Result:

List option "**Yes**" Result:

---
Tags: ajax, theming, javascript
---


title: Unsubscribe module issue

text:
# Question
Title: Unsubscribe module issue
I installed the Unsubscribe module. I have also set this module's permissions for both authenticated and anonymous user.

.

Now the unsubscribe checkbox is appearing on the edit account form, but not yet on the user register form, where I want it to appear too.

Is there a way to do so? As an alternative, do you know any other module that provides a similar function/feature?

# Answer
> 0 votes
## Using module Unsubscribe

About the "not appearing in fields of user register form" in the question: it seems to me that the unsubscribe module ***might*** just be working as designed, and implemented. From its project page (I added some markup here):

> The module design is very basic. When a user unsubscribes, they are added to an "unsubscribe list," which is stored in the database. Whenever Drupal sends mail, the unsubscribe module will check to see if the recipient is on the unsubscribe list. If so, the email is blocked. **You can exempt specific modules from this blocking via the configuration page.** You can also use hooks to alter exemptions, or override the blocking.
>
> **Emails sent by the system and user modules are currently exempt by default**.

From the question it is not clear to me what you have done regarding the "exempts" (on the module's configuration page). If nothing yet, then that might be the explanation for why it is not appearing on the user register form, no?

## Using some other module

As per your "any other module that provides a similar function/feature": it appears to me that the Rules module should be worth considering, possibly combined with the Message module.

If you're not familiar enough with these 2 modules, then I suggest to review this great introduction to the Rules module: Rules for admin notifications, Part 1: New user registrations. Maybe also the related Rules for admin notifications, Part 2: New comments and content.

---
Tags: 7
---


title: Menu for mobile responsive

text:
# Question
Title: Menu for mobile responsive
Is there any recommended module for responsive menu?

Example the picture above, click on it and a list of menu appear.

Easy to configure.

This content is for: many content

Creating a responsive menu system for a site with a lot of content

Mine is simple. Basically the menu wont have a link. (It is just a scroll down function to specific height when I click the menu.) Just that when come to mobile, I wan it act like responsive menu according to the picture above. It wont have any sub-menu as well.

# Answer
> 2 votes
A good option is the Responsive Menus module.

> Responsify your menus! Just give me a CSS/jQuery style selector of your menu and I will make it mobile friendly (when the time is right).
>
> Technically you could set this to affect any element on the page... e.g. collapse a sidebar or content area at a certain screen width. (Using certain styles).

---
Tags: 7, routes
---


# Question
Title: How to show filtered content as suggestion of "reference autocomplete field" based on a field value of reference content
Say, one content type is "CONCEPT" and it has a field named 'STATUS'. Another content type is "Article" and it has a node-reference auto-complete field named 'CONCEPT FROM'.

Now I want to see only "CONCEPT" contents whose status value is "ACCEPTED" as a suggestion of "CONCEPT FROM" auto-complete field.

# Answer
> 2 votes
If you're using the entity reference module, what you can do is autocomplete from an entity reference view. You can add a filter on your entity reference view that filters nodes of type CONCEPT with a status field value of ACCEPTED. Once your view is created, you can select it under the **Entity selection** fieldset.

# Answer
> 3 votes
Thanks @shawn-conn His answer is perfect but I can't give vote because of minimum reputation. See following solution in details:

**Step 1:**
First create one entity reference view
*Note: In this view include referenced content type (e.g.: CONCEPT) and it's filter/condition field (e.g.: STATUS)*

**Step 2:**
From **MANAGE FIELDS** of the required content type (e.g.: PROJECT), Add field that **FIELD TYPE** will be Entity Reference and WIDGET will be **autocomplete** then click on the **SAVE** button.

Step 3:
Now choose **Views: Filter by an entity reference view** option in **MODE** field and choose your **views** that is created in **Step 1** in **View used to select the entities** field from ENTITY SELECTION section of the field settings page.

Step 4:
Click on the **Save settings** button to save changes.

---
Tags: ajax
---


# Question
Title: Is there any other way to create more secure link in a drupal_set_message?
Is there any other way to create more secure link in a drupal\_set\_message??

```
$loglink = l("bla bla", 'admin/config/services/blabla');
  drupal_set_message(t("You should not have empty or the default fields in $loglink. You have to fill your own information."), 'error');

```

# Answer
> 1 votes
No, there isn't a more secure way, especially when you are not outputting input coming from the user. Still, you should be using `t()`-placeholders.

Drupal core uses the following code, when outputting an URL.

```
// system_requirements()
$requirements ['php'] = array(
  'title' => $t('PHP'),
  'value' => $phpversion,
  'description' => $t('The phpinfo() function has been disabled for security reasons. To see your server\'s phpinfo() information, change your PHP settings or contact your server administrator. For more information, <a href="@phpinfo">Enabling and disabling phpinfo()</a> handbook page.', array('@phpinfo' => 'http://drupal.org/node/243993')),
  'severity' => REQUIREMENT_INFO,
);

```

```
  // action_synchronize()
  $link = l(t('Remove orphaned actions'), 'admin/config/system/actions/orphan');
  $count = count($actions_in_db);
  $orphans = implode(', ', $orphaned);
  watchdog('actions', '@count orphaned actions (%orphans) exist in the actions table. !link', array('@count' => $count, '%orphans' => $orphans, '!link' => $link), WATCHDOG_INFO);

```

The only difference is that, in the first case, the code is outputting an external URL while, in the other case, the URL is internal to the website.

---
Tags: security, status-messages
---


title: Translate Taxonomy menu items

text:
# Question
Title: Translate Taxonomy menu items
I have a vocabulary that I want to shows as menu. For this, I installed the taxonomy menu module and edit the vocabulary to hang from a menu item of Main Menu. The menu is shown perfectly.

The problem goes when I localize the terms of vocabulary, the menu is only shown in a default language. I have tried to rebuild the menu (by checking the "Select to rebuild the menu on submit." on vocabulary edit page and submitting), but the problem persists.

# Answer
Entity translation

> Allows (fieldable) entities to be translated into different languages, by introducing entity/field translation for the new translatable fields capability in Drupal 7. Maintained by the Drupal core i18n team.

together with Title module - (making the taxonmy terms translatable)

Title module

> After enabling the module as usual, visit the Manage fields page of the content type, taxonomy vocabulary or "comment type" which you wish to replace fields of and click the replace link. That's all.
> 2 votes

# Answer
You can: 1) Install Entity translation and enable taxonomy term in TRANSLATABLE ENTITY TYPES (admin/config/regional/entity\_translation).

2) Install Title and (admin/structure/taxonomy/YOUR\_VOCABULARY/fields) make "replace" title with title field.

3) Enable "Translate and Localize" option in your menu settings.

4) Install Taxonomy menu dev release.

5) Apply patch drupal.org/node/1665308.

6) Rebuild your taxonomy menu.
> 1 votes

---
Tags: 7, i18n-l10n, taxonomy-terms
---


title: Menu in Drupal8

text:
# Question
Title: Menu in Drupal8
I am currently using below code to generate routes:

```
foreach($this->hardcopyEntityManager->getHardcopyEntities() as $entity_type => $entity_definition)
 {

      $route = new Route(

        "/$entity_type/{entity}/hardcopy/{hardcopy_format}",

        array(
          '_controller' => 'Drupal\hardcopy\Controller\HardcopyController::showFormat',
          '_title' => 'Hardcopy',
        ),

        array(
          '_permission' => 'view printer friendly versions',
        ),

        array(
          'parameters' => array(
            'entity' => array('type' => 'entity:' . $entity_type),
          ),
        )
      );

      $collection->add('hardcopy.show_format.' . $entity_type, $route);
    }

```

But if now I want to make the same route using \*.routing.yml file then how will I be proceeding? Assuming the entity type to be node.

# Answer
> 0 votes
```
# This should be entity.node.hardcopy, also altering node link templates could be good idea
hardcopy.show_format.node:
  path: '/node/{node}/hardcopy/{hardcopy_format}'
  defaults:
    _controller: 'Drupal\hardcopy\Controller\HardcopyController::showFormat'
    _title: 'Hardcopy'
  requirements:
    _permission: 'view printer friendly versions'

```

---
Tags: 8, routes, navigation
---


title: Integrating external web application

text:
# Question
Title: Integrating external web application
I have an existing web application written in Flask. I want to create a Drupal site that integrates this existing web application, so that the existing webapp will just be a back end, and the Drupal site will contain all the forms that submit data to the web app and displays the results from the web app. I was thinking that Drupal Services could do that for me, but it looks like it is more for the reverse use case: to use an external web app as front end to Drupal..

So my question is: What is the best way of using Drupal as a front end to an existing web application?

Or is this even possible?

Some extra info about the web app:

* Web app is written in Python/Flask
* It is a web shop like application that allows users to search for products based on various criteria.
* Web app is highly modular and cleanly split into views, forms, model, so it would be fairly straight forward to change the web app in order to present data via another protocol/API. I figure it would be possible to create new views that present the data in JSON or something like that and I hope that Drupal can somehow pick that up and display it in its templates.
* Database is PostgreSQL
* Frameworks used: Flask, SQLAlchemy, WTForms

**Update 2015-05-15: More details**

I have considered using Drupal Services because it sounded like it was an API for this, however, it turned out that Services solves the reverse problem: Makes it possible to use an external app as front end for a Drupal site.

How I think this could be done: Make the existing Flask webapp into a REST server allowing the Drupal site to send requests to the app for search queries, product displays, etc. So the external app will respond with some JSON that contains all the content and URLs to images, etc. In Drupal there will have to be a template for each view on the external app. E.g.:

* Search form
* Search result
* Product display
* etc.

I have zero experience in doing this stuff from Drupal. I have some experience with using Drupal. But mostly vanilla Drupal.

I was hoping that there were either a plugin or framework or something that would make it easier to do this. that is something that will make it easy in Drupal to create the following kinds of elements:

* A form/template that upon submit sends request to REST service and displays results (e.g. serach)
* A template that renders a page according to some JSON data gotten from a RESTful service.

Regarding PDO, I am not sure what that is. I am using PostgreSQL. I was not planning on letting Drupal access the external web app's database directly. That would essentially require me to reimplement the entire application in Drupal.

As mentioned above, the external app is written in Flask. Flask is a Python framework for making web applications. For short introduction, see http://flask.pocoo.org/.

# Answer
> 0 votes
About ***What is the best way of using Drupal as a front end to an existing web application?***: I leave it to others to decide if it would be the "best" way, but "a" way to do so is to continue to use your existing web application for maintaining the data of it, and then use Drupal as a frontend to actually visualize those data (read only operations).

Assume the DBMS involved is some type of PDO compliant DBMS, e.g. MySql (the question currently does not provide details on that). So similar to what is described in Python Web Application Development Using Flask and MySQL. In that case the Forena module would be a perfect fit to get the job done, i.e. build reports and/or charts about data stored in your existing web application. Here is a quote about Forena:

> ... built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.

Possible DBMSs that could fit this approach are the Drupal DB itself (of course), but also MySQL, Oracle, MS SQL, Postgress, Sqite, anything PDO compliant.

The advantage of this approach is that you get lots of Drupal features avilable, while the "bacckend-part" of your application continues to be the applicationn you already have (you don't loose the investements made in that).

---
Tags: 8, ajax
---


title: Hook_search_execute();

text:
# Question
Title: Hook_search_execute();
i am using this hook in my custom module but getting a fatal error

> Fatal error: Cannot use object of type stdClass as array in C:\wamp\www\bid\includes\common.inc on line 5901

Anyone can help???

Below is my code, I have two conditions in it. In the second condition I want to search with taxonomy index because I have added a filter contains taxonomy parent term.

```
/**
 * Implements hook_search_execute
 * Override core node_search_execute here with custom implementation
 * Basically a clone of node_search_execute, but with limit variable available
 * See mymodule_module_implements_alter
 */
   function mymodule_search_execute($keys = NULL, $conditions = NULL) {
 // Add new limit conf variable
   $limit = variable_get('search_result_limit', 10);
 // Build matching conditions
  $prnt = (isset($_REQUEST['prnt'])) ? $_REQUEST['prnt'] : 'none';
  $site = (isset($_REQUEST['chld'])) ? $_REQUEST['chld'] : 'none';

  $query = db_select('search_index', 'i', array('target' => 'slave'))->extend('SearchQuery')->extend('PagerDefault');
    if (($prnt != 'none' && $site!= 'none') || ($prnt = 'none' && $site!= 'none')) {

        $query->leftjoin('node', 'n', 'n.nid = i.sid');
        $query->leftjoin('field_data_field_category', 'fdfc', ' fdfc.entity_id = i.sid ');
        $query->leftjoin('taxonomy_term_data', 'txd', 'txd.tid = fdfc.field_category_tid');
        $query->condition('txd.name', $site, '=');
    }

    if ($prnt != 'none' && $site = 'none') {

        $query= db_select('taxonomy_index', 'ti');
        $query->leftjoin('node', 'n', 'n.nid = ti.nid');
        $query->leftjoin('taxonomy_term_data', 'txd', 'txd.tid = ti.tid');
        $query->leftjoin('taxonomy_term_hierarchy', 'tth', 'tth.tid=txd.tid');
        $query->condition('tth.parent', '$prnt', '=');

    }

   $query->join('node', 'n', 'n.nid = i.sid');
   $query
         ->condition('n.status', 1)
         ->addTag('node_access')
         ->searchExpression($keys, 'node');

   // Insert special keywords.
   $query->setOption('type', 'n.type');
   $query->setOption('language', 'n.language');
   if ($query->setOption('term', 'ti.tid')) {
   $query->join('taxonomy_index', 'ti', 'n.nid = ti.nid');
 }
  // Only continue if the first pass query matches.
 if (!$query->executeFirstPass()) {
  return array();
  }

 // Add the ranking expressions.
  _node_rankings($query);

// Load results, use limit variable
  $find = $query
   ->limit($limit)
   ->execute();
 $results = array();
 foreach ($find as $item) {
  // Render the node.
  $node = node_load($item->sid);
  $build = node_view($node, 'search_result');
  unset($build['#theme']);
  $node->rendered = drupal_render($build);

  // Fetch comments for snippet.
  $node->rendered .= ' ' . module_invoke('comment', 'node_update_index', $node);

  $extra = module_invoke_all('node_search_result', $node);

   $uri = entity_uri('node', $node);
   $results[] = array(
  'link' => url($uri['path'], array_merge($uri['options'], array('absolute' => TRUE))),
  'type' => check_plain(node_type_get_name($node)),
  'title' => $node->title,
  'user' => theme('username', array('account' => $node)),
  'date' => $node->changed,
  'node' => $node,
  'extra' => $extra,
  'score' => $item->calculated_score,
  'snippet' => search_excerpt($keys, $node->rendered),
  'language' => entity_language('node', $node),
 );
}
  return $results;
}

```

# Answer
I don't question that the suggested answer (from NishantP) might answer the question. But the "*Goto ... & open taxonomy.module ...*" looks like hacking this module. If you just do that, then be prepared for the issue potentially coming back in the next module upgrade (because such upgrade might wipe out your edit).

As an alternative, how about filing an issue for this module (if such issue doesn't exist already), and attach a patch to it corresponding to the suggested edit (hack). It might (and probably will) get accepted to be committed to the module in the next reease of it). From then on no more issue with future upgrades of that module. And if it doesn't get accepted, you can still use that same patch to re-apply in further module upgrades (assuming you don't have to re-roll them then).

**Edit**: looks like NishantP's answer is no longer there (deleted?). Not sure (yet) if that implies that I should now also delete "my" answer. Since I'm sure there was something in it like that "*Goto ... & open taxonomy.module ...*", I'll leave my answer here for now, just in case anybody else ever has similar hacking-suggestions ...
> 0 votes

---
Tags: hooks, search, database
---


# Question
Title: Tokens causing incorrect text substitutions
I'm running Drupal 7 on Ubuntu 14.04 server, core and all modules up to date as of today (7th May). We have noticed today that zeros (0) are not displaying correctly in blocks that have a custom token. They are being substituted for the word 'custom'.

For example, "7,500" displays as "7,5customcustom".

I'm not sure how long it has been doing this, as we have only just noticed it today. In blocks without Custom Tokens, the zeros display correctly. This is a relatively recent issue, as it was not a problem a couple of months ago when our site was reviewed by our solicitors.

The source for the content is correct - so it appears to be a display issue. Any ideas?

As an aside, the zeros being replaced need not be in the Custom Token to be replaced (it happens whether they are part of the Custom Token, and when they are just plain text on the page).

# Answer
It appears to me that the explanation for your issue might be because of any of the following reasons

## Reason 1:

It could be related to what is described in https://www.drupal.org/node/390482, which states:

> The tokens available depends on what modules you have enabled on your Drupal site.

So could it be that you (accidently) disabled a module recently, which was actually the module related to the token that you now have an issue with?

Also, some more related considerations, based on what I read at comment #3 in the issue queue on D.O:

* What does that "00" in the "7,500" actually refer to? I want to better understand which module(s) are related to it.
* What result do you get if you (temporary) enable all of your currently disabled modules? FYI: if you only enabled the module that is causing this issue, and not uninstalled it, the problem might be resolved, at least for now. And then you can think of how to best resolved it permanently.

## Reason 2:

When you define a custom token, for "Text format" (under the "Content" box): verify what the text format is you use there. And also verify what the text format is of where you are trying to USE that custom token (as in the original question: in the block), or in your Webform, Email etc.

Because maybe something is wrong in the way you're using/mixing text formats. Refer to How to use the Custom Tokens module, especially to this part of it (bold markup added here):

> note that "Custom Token" sends what you put in the "Content" box to the page. **It doesn't evaluate it first** and then send it. Therefore, if your custom tokens include other tokens and/or PHP code, then the "Body" box in which you place your tokens **must use the same text format that you used to define them, so that the other tokens and/or PHP get evaluated**.

The question here might be a minor variation of the scenario described in that community page ...

## Other reasons worth verifying:

* Maybe the field "type" got changed somehow, and that is what's causing it?
* Something similar within the content type settings?
* Could it be related to something about some missing "permissions" (for those cases where there is this issue)?

Curious to hear if either of these 2 reasons are actually also a solution for what this question is about.
> 2 votes

---
Tags: 7, tokens
---


# Question
Title: Theme hook suggestion for nodes within a menu link?
I need nodes within a certain place in my menu to use a new node TPL file.

My menu is hierarchical like this.

```
link1
link2
link3
-linkA
-linkB

```

I need nodes whose menu link is link3, linkA or linkB to use these new TPL files.

I have 2 content types whose nodes can be in the menu and I need a different TPL file for each content type. These nodes can also be outside of the menu in which case they should use the normal TPL file.

So a node of content type A which has a menu link of link1, link2 or no menu link would use the default node--typeA.tpl.php.

A node of content type A which has a menu link of link3, linkA or linkB would use node--typeA--special.tpl.php

A node of content type B which has a menu link of link1, link2 or no menu link would use the default node--typeB.tpl.php

A node of content type B which has a menu link of link3, linkA or linkB would use node--typeB--special.tpl.php

As I'm extending the node not page TPL I started with this:

```
function MYTHEME_preprocess_node(&$variables) {
  $variables['theme_hook_suggestions'][] = 'node__SOMETHING';
  kpr($variables);
}

```

Im assuming I need an if statement around the 2nd line which checks if the node is typeA and also in the correct place in the menu? However I had a look at the $variables on the screen and I couldn't see anything I could use to find out the menu position.

I then looked at preprocess\_page to see if it had a variable I could use. There is an array called main\_menu which is the name of my menu. But it contains 0 elements.

```
function MYTHEME_preprocess_page(&$variables) {
  kpr($variables);
}

```

# Answer
> 0 votes
It might not be ideal but ive solved it by checking the URL:

```
function MYTHEME_preprocess_node(&$variables) {

  // Get the node URL
  $nodeUrl = $variables['node_url'];

  // Break up the string
  $urlParts = explode("/", $nodeUrl);

  // Get the first part of the string
  $urlBegin = $urlParts['1'];

  // Get the node type
  $nodeType = $variables['type'];

  // If the ULR starts with 'CUSTOMURL'
  if ($urlBegin === 'CUSTOMURL') {
    // Add theme hook suggestions based on node type as well as URL
    $variables['theme_hook_suggestions'][] = 'node__' . $nodeType . '__CUSTOMURL';
  }
}

```

# Answer
> 0 votes
As this requirement may get even more complex, I would suggest adding a taxonomy selection to the content types in question. You can use this to assign the proper theme suggestions as the value will be saved on the node object. You may also want to check out ThemeKey.

---
Tags: theming
---


# Question
Title: Geo field proximity distance for exact location
I'm tried this for a day,but i won't get the answers. I'm using geo field proximity for zip code searching, it's working with 5,25,30 miles search, but i want to search exact location of zip code.

eg In search zip code : 73301, all the record in 73301 will be show.

# Answer
Zip codes don't have exact location. A zip code is an area in which the coordinates are a point within it. In most cases it is probably the centroid.
> 0 votes

---
Tags: search, location
---


title: Search results for URL or Views Titles

text:
# Question
Title: Search results for URL or Views Titles
I have pages generated by Views with some page url: e.g. /testimonials. When I search the word 'testimonials' I want in results page to be shown the link to testimonials page.

How it can be done this feature?

I use Drupal 7.

# Answer
> 0 votes
It sounds like you're wanting to index a Views page in the search result. There's similar question been asked already if that's the case. A solution wasn't marked but the search by page module was mentioned. It has a submodule that allows you to index any arbitrary path on your site.

---
Tags: search
---


title: Using Php Filter with Ckeditor?

text:
# Question
Title: Using Php Filter with Ckeditor?
I need to use Php Filter with ckeditor. Problem is that Ckeditor change this:

> `<?php echo "hello";?>`

to

> `<p><?php echo "hello";?></p>`

How can I solve this?

I already added this:

```
config.allowedContent = true;

```

under **Custom JavaScript configuration** at: admin/config/content/ckeditor/edit/Full

But it didn't help.

I also make sure I checked **Php evaluator** under **Enabled filters** at admin/config/content/formats/full\_html

# Answer
Change the 'insertElement' function for 'insertHtml' function

```
editor.addCommand('phpcode', {
  exec : function() {
    editor.insertHtml('<div id="phpcode"><?php echo "hello"; ?></div>');
  }
});

```

Hope it will be work.
> 2 votes

# Answer
In /admin/config/content/formats/full\_html try unchecking the Correct faulty and chopped off HTML box. Maybe it thinks your php is html.
> 0 votes

---
Tags: wysiwyg, input-formats
---


title: Remove "Revision Information" Section?

text:
# Question
Title: Remove "Revision Information" Section?
For my use case, I don't need this Revision information section to appear on my page. (I am using revision, so it has to be enabled on the content type).

What options are there to 1) disable this seciton , or to 2) hide it?

# Answer
This can be done with the Simplify module. Here is a quote about it (from its project page):

> Simplify allows particular fields to be hidden from the user interface. This helps to de-clutter forms and present a more user-friendly experience to content editors.
> 2 votes

---
Tags: nodes
---


# Question
Title: Drupal Views Exposed filter ( Taxonomy )
I have 3 fields ( Exposed filter ) 1 Country 2 State 3 City

When a respective Country is selected in the 1st field, I want the second filter ( Dropdown or autocompete ) to display states of the country selected in the 1st field & when this is done based on the state selection , I want the 3rd field to show only the cities belonging to the state selected in the second field.

How can this be done ? any help ?

# Answer
If you have arranged your taxonomy in a hierarchical manner, then you can use the Hierarchical Select module:

https://www.drupal.org/project/hierarchical\_select
> 0 votes

---
Tags: taxonomy-terms, views
---


# Question
Title: Advise a Drupal Image gallery module with an option to put text nearby the image (for medical atlas)
Advise a Drupal Image gallery module with an option to put text nearby the image (for medical atlas). I could find a dozen of them, can\`t choose before installing and setting them up. Thank you.

# Answer
> 1 votes
Talking Drupal #083 is a great podcast about creating a Gallery, and includes a lot of recommended modules for it.

Just to mention a few of them (mentioned on the linked page):

>

---
Tags: media
---


# Question
Title: How to use tags for filtering images to be displayed using views?
I'm pretty new to Drupal (version 7). I'm trying to create multiple image galleries. I've created a content type called "Images" and use a view to display it like a gallery.

However, I wonder if there is some way to "tag" the images so that they go to different views. Ex.: I have an image tagged so that it will only appear in the "events view" and not the "projects view".

# Answer
I can almost guarantee that this question has been asked before, but still ...

If you did a standard Drupal 7 install, then you should already have a Tags taxonomy. Add that taxonomy to your content type.

In the view, you could do a couple of things.

1. Create more than one variation of the view. In each variation, filter the view to only contain the tag that you want.

OR

2. Use a Contextual Filter to grab the specific term from the URL. That way, you will have as many different views as taxonomy terms. This is more complicated, but it will help you learn a lot, and it is almost always the better way to do this sort of thing.
> 1 votes

# Answer
Just to avoid you're not aware of it yet, know that creating galleries is a common request, which can be solved in various ways ... (no need to reinvent the wheel).

Talking Drupal #083 is a great podcast about creating a Gallery, and includes a lot of recommended modules for it.

Just to mention a few of them (mentioned on the linked page):

>
> 0 votes

---
Tags: 7, nodes, views
---


# Question
Title: How do I know when Hooks are called and in what order?
I want to alter a HTTP header and I am looking for the appropriate hook to use. I can tell a general time of when some hooks are called but not exactly when. How do I know exactly when hooks are called, and what hook I should be using to change my header?

edit: I have managed to change my HTTP header. But something else is adding to my header and that is taking precedent over my header portion. Is there a way to know where this is coming from?

# Answer
You're looking for an event, not a hook to do this in 8.x

Specifically, you're looking for the RESPONSE event, see `\Drupal\Core\EventSubscriber\AnonymousUserResponseSubscriber` for an example. Create a class like that, register it in `yourmodule.services.yml` and then do whatever you want with the $response object.
> 2 votes

---
Tags: hooks, 8
---


# Question
Title: How do I populate an email field from a single user “Name” reference?
I have a content type in which I use an entity reference to reference a Name field in a user account. I am trying to populate an email field in the content type with the email of the entity referenced above. I have tried creating an entity reference view and can get it to show and save: Name, Email Address in the node. However, because of some rules I am using, I really need them to be saved to separate fields. So I tried the Entity Reference Autofill module which seems like it does exactly what I am looking for, but, it only works with existing fields, and for some reason, I can’t get the user account fields to show-up as existing fields when trying to add them to the content type.

So, is there a way for a single reference to populate more fields using the initial reference as a ‘key’?

Or…

Is there a way to get user account fields to show-up as existing fileds so I can just use the Entity Reference Autofill module?

Thanks so much.

# Answer
> 1 votes
Maybe I don't understand the need, but once you reference an entity what is the point of adding the values from the referenced entity into the referencing entity?

Is this a UI thing when creating a node? Or a display issue when displaying a node?

If it's a display issue, wouldn't you just create a new display for the reference user for when it is being referenced only showing the fields that you want shown?

To do what I am saying, you would need either https://www.drupal.org/project/ds Display Suite, or embed a view, or call the referenced user fields in a template or module.

---
Tags: entities
---


# Question
Title: Add button to teaser on specific content type
1. I have a custom content type for Real Estate
2. I have a custom view on the homepage that displays the 5 most recently added real estate properties and displays basic information about this property

This view is in a block on the home page.

I essentially want to put a button on these teasers that links to the full node for the user to view. I'm not sure what the easiest way to do this is?

Then, once in the full node I want to have a button that 1. Checks if the user is logged in (using php session or however that is handled with drupal) and then 2. if user is logged in it directs them to another page or if not logged in directs them to log in.

# Answer
> 0 votes
I would check out Display Suite's custom fields capability.

It allows you to create custom code "fields" that can be attached to nodes and other entities, and can be included in views. These fields can be, for example HTML code with tokens to create links that redirect user to the full node.

These fields also have the capability of accepting php code, which would allow you to evaluate if the user is logged in and include logic to redirect to the appropriate place. Check out the tutorial for custom fields here: https://drupalize.me/videos/display-suite-fields?p=1141

---
Tags: navigation, nodes
---


title: How can I add custom styling?

text:
# Question
Title: How can I add custom styling?
I am using the Quicktabs module, which has built-in styles for its tabs.

I would like to add my own custom styling. How can I do it?

# Answer
> 0 votes
You can do 1 of 2 things:

1. Patch the quicktabs module to include a css stylesheet for your custom style.
2. Select an already existing style that matches what you want the closest and then override the styles css. For example, if you select the arrows style, override the `.quicktabs-style-arrows` class with whatever you need.

The 2nd option would be the quickest and easiest.

---
Tags: blocks, theming
---


# Question
Title: How to access global variable from within Drupal content
I am trying to access a global variable I created using javascript within a content node i created. In an attached js file i have `var rootpath = "/clients/UMP/";`

Inside of my drupal page i have:

```
<script>document.write(window.rootpath);</script>

```

But it just shows the text: `undefined`

Am i doing something wrong? Is there a more better way to do it using php perhaps? Thank you for taking the time to read this and respond. I apologize for being such a noob with drupal. I have only been using it for a few weeks.

# Answer
> 0 votes
Based on your comments, you might want to try using Drupals built in functions to retrieve the correct path for your assets.

The 2 you could take a look at are `base_path()` and `path_to_theme()`.

For example:

`<img src="<?php print base_path(); print path_to_theme()?>/images/image1.jpg" />`

---
Tags: nodes, javascript
---


# Question
Title: set up social login for multiple drupal sites?
I intend to set up multiple independent drupal installations, each of which could benefit from social logins. I like HybridAuth, but it requires me to set up multiple "applications" (one for Google, one for Github, one for Facebook etc) for each site.

Any thoughts on how to automate creating these "applications"? Or maybe a different solution? I've tried OneAll but the Drupal module seems quite buggy.

# Answer
> 1 votes
I don't think you're going to find a way to automate the creation of application accounts. Facebook, Google, et. al have to deal with enough spam as is, without them opening up a pandora's box of spam application accounts that would come from exposing an API that could create application accounts on their respective platforms.

HybridAuth works well if you're looking to have flexible access to each social login platform (e.g. a FB app that can request multiple user permissions to the Graph API). If you're looking for just login delegation you might find more success with one the 3rd-party social login services like the LoginRadius or the Janrain modules (there might be more, those are the only ones I've heard of).

---
Tags: users, authentication-authorization
---


# Question
Title: How to force redirect user to www.domain or http://domain in a nginx environment?
I'm using drupal with nginx and i'm looking for a way to redirect users either to www.domain.tld or to http://domain.tld

Right now, if i log into the website using http://domain.tld, the website considers me as an anonymous user and i need to log in again when accessing www.domain.tld

I know drupal's .htaccess file manages this issue but it's ineffective with nginx

Thanks

# Answer
> 0 votes
I wouldn't think that Drupal would handle it any different that another setup, ie.. creating another entry for the non-www version with a redirect:

```
server {
  listen       80;
  server_name  example.com;
  return       301 http://www.example.com$request_uri;
}

server {
  listen       80;
  server_name  www.example.com;
}

```

---
Tags: 7, redirection
---


# Question
Title: How can I invalidate a cache on a specific View?
I am facing a situation where I need to invalidate a specific View in order to initiate clearing the cache on that View.

views\_invalidate\_cache() clears ALL cached Views data, for every View on the site.

How can I trigger a cache invalidation for a specific View from inside my module code?

# Answer
I believe the function you are looking for is cache\_flush from the views cache plugin.
> 3 votes

# Answer
If you know the name of the view that you want to clear, then you can clear the caches specific to that view by calling a function like the following:

```
/**
 * Function to invalidate selected views caches to enable the action forms to work
 */
function mymodule_invalidate_views_cache($view_name) {
  cache_clear_all('ctools_export:views_view:' . $view_name, 'cache_views', TRUE);
  cache_clear_all($view_name, 'cache_views_data', TRUE);
}

```

I needed this to allow VBO actions with configuration forms to be able to work while views caching was enabled (I am using content caching). I called this twice, once in the function mymodule\_myaction\_form() and again in the function mymodule\_myaction\_submit().
> 12 votes

# Answer
You might consider using views content cache.

It's normally used to automatically clear a views cache when related content is added or updated, however it provides a framework to monitor a cache segment. I haven't done this, but developer docs are available.
> 1 votes

# Answer
Take a look at the project Cache Actions. It does exactly what you want. If you are able to use rules in your situation, then you don't even need to write custom code, you can just use the module as-is and set up rules to clear the caches of certain views. Otherwise, check out the internals of how it works as a guide to clearing view caches programmatically.
> 1 votes

# Answer
Not to second-guess you too much, but have you considered a reverse-proxy caching system like varnish? Those things give incredible performance and make db caching of views, nodes, etc somewhat moot (unless you have a lot of logged-in users and need this caching for them).
> 0 votes

---
Tags: 7, views, caching, performance
---


title: Theme change by url

text:
# Question
Title: Theme change by url
Pretty new to drupal. I will have roughly seven themes and looking for the best way to change themes by url... xxxx.com/parents = one theme xxxxx.com/edu be another theme xxxx.com/daily will be another theme. There will be about 7 different themes all together. What is the best way to way to make this happen.

Thank you

# Answer
You can do this by using the following ways.

1. Use the ThemeKey module

> ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules.

2. Add the following code to your `settings.php`

```
 $theme_urls = array(
   array('/admin','garland'), // Drupal already supports admin theme, anyway
   array('/users','fancy_user_theme'),
   array('/forum','forums_theme'),
);

foreach ( $theme_urls as $info) {
  if (strpos($_SERVER['REQUEST_URI'], $info[0]) === 0) {
    $conf['theme_default'] = $info[1];
  }
}

```
> 1 votes

---
Tags: theming
---


# Question
Title: How to translate $value in the output code of a view?
I have created a view in which I'm retrieving a time format, whose output is printed by $value.

Here's my **Value Code:**

```
$node = node_load($data->nid);
$wrapper = entity_metadata_wrapper('node', $node);
$auction_timeout = $wrapper->auction_timeout->value();
$sub = $auction_timeout - time();
$dtF = new DateTime("@0");
$dtT = new DateTime("@$sub");
return $dtF->diff($dtT)->format('%a days, %h hours, %i minutes');

```

And the **Output code** is:

```
<?php
    print ($value);
?>

```

The output is in English which is something like:

> 35 days, 20 hours, 50 minutes

And I want it as

> 35日、20時間、50分

I couldn't find how to translate it. Can anybody help me?

# Answer
```
return $dtF->diff($dtT)->format('%a ' . t('days') . ', %h ' . t('hours') . ', %i ' . t('minutes'));

```
> 2 votes

---
Tags: 7, views, i18n-l10n
---


title: Commerce Paypal Confirm Pane missing

text:
# Question
Title: Commerce Paypal Confirm Pane missing
I have installed Drupal Commerce with latest version and also Commerce Paypal \+ Commerce Paypal Express Checkout.

EC is working so far, but I can´t find the Confirm-Pane on the checkout page/configuration.

Can somebody give me a tip what to do to make it visible on the checkout configuration.

It should be visible under "Confirm Order" and its called: "Express Checkout review and confirm (only to be used on the confirm order page)"

# Answer
I fixed it...

I had a similar module installed (commerce\_paypal\_ec) and it was conflicting with commerce\_paypal submodule for EC.

i misunderstood the concept, i tought i had to install submodules but those exist already in commerce\_paypal.

in case somebody run into the same problem.

kind regards, kevin
> 0 votes

---
Tags: commerce, payment-gateways
---


# Question
Title: How do I generate a list of "standard" clean URLs?
Is there a way to generate a list of "standard" clean URLs, like `/user/login`, \`/admin/content/comment', '/comment/NN' ? Perhaps for core modules, or for a specified set of modules?

# Answer
> 2 votes
Those are ***paths*** in Drupal lingo. Clean URLs come from a server configuration that rewrites the path query parameter away (e.g. `http://example.com/?q=user/login` vs `http://example.com/user/login` ).

To get at the heart of your question, registered paths can be found in the `menu_router` table of your Drupal installation. There is no one standard set of paths since any module can register a path. Thus, the "standard" result will vary based on what type of install you have (e.g. minimal vs standard vs contrib installation profile) plus other configurations.

For example, this code snippet will dump the list of paths that the 6 core modules are registering.

```
  $implementations = module_implements('menu');
  $core = array('field', 'field_sql_storage', 'filter', 'node', 'system', 'user');
  $paths = array();
  foreach($implementations as $implementation) {
    if(in_array($implementation, $core)) {
      $paths = array_merge(array_keys(call_user_func("${implementation}_menu")), $paths);
    }
  }
  var_dump($paths);

```

However, you'll find the node paths will vary across your installation based on the your defined node types (e.g. **node/add/NODE\_TYPE** ).

---
Tags: users, uri
---


# Question
Title: drupal_static() uses a FUNCTION variable,what does it mean?
```
function drupal_set_page_content($content = NULL) {
  $content_block = &drupal_static(__FUNCTION__, NULL);
  $main_content_display = &drupal_static('system_main_content_added', FALSE);

  if (!empty($content)) {
    $content_block = (is_array($content) ? $content : array('main' => array('#markup' => $content)));
  }
  else {
    $main_content_display = TRUE;
    return $content_block;
  }
}

```

This snippet is pasted from common.inc. We pass in a `__FUNCTION__` to `drupal_static()` but I do not know what this variable means. Does it mean a cache for the outer function itself? How does it work? I do not see any data handled inside the function before it returns `$content_block`.

# Answer
> 35 votes
`__FUNCTION__` is one of the so-called Magic Constants of PHP.

All it does is return a string with the name of the function that the constant is contained in.

For example:

```
function my_strangely_named_function() {
  print __FUNCTION__;
}

```

The above will print 'my\_strangely\_named\_function'.

Drupal uses this constant with its static cache so that each cache is identifiable from any other function, and as such can be identifiably cleared.

To use an abridged version of your code:

```
function drupal_set_page_content($content = NULL) {
  $content_block = &drupal_static(__FUNCTION__, NULL);
}

```

Any other function in the Drupal lifecycle can call:

```
drupal_static_reset('drupal_set_page_content');

```

And that will clear the cache for that specific function, so that next time it's called the data is built up as if from new.

That's just the basic use of the static cache pattern, you can find more information and examples on the documentation page for `drupal_static()` itself.

# Answer
> 3 votes
In depth information you will get at http://blogs.sourceallies.com/2012/02/static-caching-in-drupal/. Here is a quote from it:

> ... caching (of any kind, not just static caching) is to be done in a responsible manner. Overzealous usage of caching floods memory which can crash high traffic websites. Remember also that caching should be used for large data structures that are expensive to generate. Lastly, use caching only if you know for sure that what you cache will be needed again (e.g., menu data in Drupal). There’s no point caching a list of names or addresses or colors if that list will never be used again. That would be like saving your old car tires after you put new ones on.

---
Tags: caching
---


# Question
Title: Defining and manipulating help text for a path
Ok, this is a very basic question. If I create a 'page' in drupal using 'add content'. Does this new page (and the path defined for it, say, through 'pathauto') automatically get registered with a callback as a menu item so I can reference it's path in a custom module somehow?

For example, I tried the following code. Case #1 doesn't show anything on that page (a page created the typical way through the admin UI). The second case displays the help text correctly when I go to admin \> modules \> mymodule and click the 'help' link.

So what's going on here?

```
function mymodule_help($path, $arg) {
  switch ($path) {
    case 'services/software-training/webinars':
      // Help text for the simple page registered for this path.
      return t('This is help text for the simple page.');

    case 'admin/help#testmodule':
      // Help text for the admin section, using the module name in the path.
      return t("This is help text created in the page example's second case.");
  }
}

```

# Answer
> 2 votes
A quote from the documentation (subheading *Parameters*):

> $path: The router menu path, as defined in hook\_menu(), for the help that is being requested; e.g., 'admin/people' or 'user/register'. If the router path includes a wildcard, then this will appear in $path as %, even if it is a named %autoloader wildcard in the hook\_menu() implementation; **for example, node pages would have $path equal to 'node/%' or 'node/%/view'**. For the help page for the module as a whole, $path will have the value 'admin/help#module\_name', where 'module\_name" is the machine name of your module.

This means that the following should work for you:

```
    function mymodule_help($path, $arg) {
      switch ($path) {
        case 'node/YOUR_NODE_ID':
          // Help text for the simple page registered for this path.
          return t('This is help text for the simple page.');

        case 'admin/help#testmodule':
          // Help text for the admin section, using the module name in the path.
          return t("This is help text created in the page example's second case.");
      }
    }

```

---
Tags: 7
---


# Question
Title: Setting a date field via entitity_metadata_wrapper
I am trying to set a field of `date` type through usage of `entity_metadata_wrapper` but the although the field is created as datetime in mysql, and creating a node sets it with expected YYY-MM-DD HH:MM:SS format, when using `entity_metadata_wrapper` it fails. The only thing I have managed to insert is timestamps, I have tried both Iso date format and the standard one.

Here is the line I am trying to use to update:

```
   // sets reminder date in db
   $wrapper->field_event_reminder_date->set($reminder_date->format("Y-m-d H:i:s"));

```

Thanks!

# Answer
> 5 votes
I know this question was asked some time ago, but for those who come across this question, the answer appears to be given at http://drupal.org/node/1803286. There is no setter callback for date fields in the Entity API, so you cannot set date values using entity\_metadata\_wrapper. The d.o node referenced in this answer gives a workaround.

# Answer
> 8 votes
I was able to get this to work in a roundabout way. I may have been able to accomplish the same thing with `time()`, but this read better for me as I could follow exactly what I was doing if I ever came back to the code in the future.

```
// Update the Acceptance Date of Current Agreement.
$acceptance_date = new DateTime(date('Y-m-d 00:00:00'));
$company_wrapper->field_acceptance_date->set($acceptance_date->getTimestamp());

```

# Answer
> 5 votes
If the field does not collect end date set it with timestamp:

```
$entity_wrapper->field_date = 1431670535;

```

If it does:

```
$entity_wrapper->field_date = array(
  'value' => '2015-05-12 11:30:38',
  'value2' => '2015-05-25 21:45:33',
);

```

# Answer
> 3 votes
The examples posted did not work for me. I had a date field setup on the user entity, with only a start date and no time. The widget should not matter, but was just using the default text field.

Finally got it working using the entity metadata wrapper and only needed to use -\>set(time()). The code below shows setting a checkbox "boolean" field, a product reference field and the date field.

```
$wrapper = entity_metadata_wrapper('user', $account);
$wrapper->field_subscription_active = 1;
$wrapper->field_subscriptionplan->set($line_item->commerce_product[LANGUAGE_NONE][0]['product_id']);
$wrapper->field_subscription_signup_date->set(time());
$wrapper->save();

```

# Answer
> 2 votes
It appears that how the value is set depends on what type of date field it is. This worked for me when using a `Date` field type, that had a start and end date.

```
$product->field_course_event_date->set(array(
  'value' => "2013-12-09 00:00:00",
  'value2' => "2013-12-10 00:00:00",
));

```

Using a different example, this worked for me with a `Date` field, unlimited value, start time only:

```
$invitation->field_dates = array(1431670535);

```

---
Tags: 7, entities
---


# Question
Title: How to display legal link on registration page in colorbox node?
I have installed the module Legal and choose to have a checkbox on registration. On registration of a new user is then displayed:

* Accept Terms & Conditions of Use *

The Terms & Conditions are link to page `/legal` in the same window.

I want to show this link in colorbox node so a style should be appended. Probably I have to modify the code (which I do not prefer) or can implement a hook for this? If so, how?

Any other suggestion?

# Answer
> 0 votes
You will have to add the class `colorbox` to the Terms and Conditions link generated by the Legal module.

This is easily setup through a `theme_` function override.
Use the following code in your theme's `template.php` file:

```
    function YOUR_THEME_legal_accept_label($variables) {
      if ($variables['link']) {
        return t('<strong>Accept</strong> <a class="colorbox" href="@terms">Terms & Conditions</a> of Use', array('@terms' => url('legal')));
      }
      else {
        return t('<strong>Accept</strong> Terms & Conditions of Use');
      }
    }

```

Note: you might have to tweak the output in the popup, but that's outside of the scope I guess.

# Answer
> 0 votes
Adding something like `class="colorbox"` is a variation of adding `target="_blank"`.

So as an alternative to modifying your theme's template.php file (as in the previous answer), you may want to use some of the suggestions in issue #372721 on D.O. I.e.:

* via a **form alter**, similar to what is explained in comment #27.
* using **jQuery**, similar to what is explained in comment #24.

---
Tags: javascript
---


# Question
Title: How to theme a custom object from an external datasource?
I am building a Drupal 7 website that has several Content Types (CTs) like Page, Event, Blog etc. For each CT, the full node view mode has been heavily customized using Display Suite.

I am requested to display data (let's say articles) from an external datasource (remote json API) within my website. Each remote article should be displayed in a single page within my website (like full node view modes), should look like (similar if not the same HMTL markup) as in my normal Drupal nodes and should not be persisted.

In a custom module, I have implemented *hook\_menu* and defined a custom page callback, and within my callback, I perform the remote API request for a remote article (let's assume that remote article identifiers are available to me) and parse the json into a php object.

```
function my_custom_module_menu() {
  $items = array();
  $items['foo/bar/article/%'] = array(
    'title' => 'Remote article page',
    'page callback' => '_remote_article_display',
    'page arguments' => array(3),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function _remote_article_display($article_id) {
  // unrelated remote request and json parsing code
  $article = get_remote_article_by_id($article_id);
  $output = ''; // how to theme $article object?
  return $output;
}

```

How should I print the proper HTML markup for my $article object without hardcoding it? The fact that my normal nodes are using Display Suite is an additional overhead as at this point I am not even sure how to print the default Drupal html for fields.

# Answer
> 1 votes
You should use `hook_theme()` for that:

> Register a module (or theme's) theme implementations.
>
> The implementations declared by this hook have two purposes: either they specify how a particular render array is to be rendered as HTML (this is usually the case if the theme function is assigned to the render array's #theme property), or they return the HTML that should be returned by an invocation of theme(). See Using the theme layer Drupal 7.x for more information on how to implement theme hooks.

---
Tags: 7, theming, routes, database
---


title: Wrapping div around form

text:
# Question
Title: Wrapping div around form
```
 function gng_unsubscribe_form($form,&$form_state) {
 $form['email'] = array(
 '#title' => 'Email',

'#type' => 'textfield',
 );
 $form['submit']=array(
 '#type'=>'submit',
 '#value'=>t('Unsubscribe'),
 '#prefix' => '<div class="btn-area">',
 '#suffix' => '</div>'
 );
 return $form;
 }

```

For a particular field I can add custom class using `#prefix` and `#suffix`, is there a way to add wrapping div around whole form?

# Answer
According to the Form API Reference, #prefix & #suffix are valid properties of the form element, so you should be able to:

```
$form['#prefix'] = '<div class="some-class">';
$form['#suffix'] = '</div>';

```
> 2 votes

---
Tags: 7, forms
---


# Question
Title: How to find content that uses a File (File Entity)?
Want to be able to see what content has file field(s) that refer to a specific file.

Is this do-able using a View (with Relationships)? (had a go already, unsuccessful so far). Alternatively I'd query database tables (via the proper API) and relate that way, but just thought I'd ask if there is a generic solution before potentially re-inventing the wheel.

Searched a lot butn get a lot of unrelated search results. Search engine cannot seem to be told that I want my terms ordered in a certain way.

Ultimately I'd like to have a View that shows the Files and the content that uses each file. I would then be able to see the impact of deleting a file for example.

# Answer
> 2 votes
Create a view of type files:

Add a relationship to 'Content', make sure you set it as required:

Add any fields you wish to see of the file or the node.

---
Tags: 7, views, nodes, files
---


title: Term reference translation

text:
# Question
Title: Term reference translation
I am using term reference in "select list" configuration. I do not know how to translate them, I have Taxonomy translation and Entity translation activated, but none of them worked.

Even I have already done the Field display translation settings and also the taxonomy translation settings!

Can you please give a guide? thank you

# Answer
> 1 votes
While adding vocabulary, you need to select third option for translate your vocabulary and its terms. Ref. attached image.

After adding the terms and its translation, and configured term reference as a "select list", you can see there are both translated terms shows into select list while adding a content.

Hope it will be helpful.

---
Tags: 7, i18n-l10n, taxonomy-terms
---