title: entityform email multilingual

text:
# Question
Title: entityform email multilingual
I am using drupal 7 and entityform module and also using this : https://www.drupal.org/node/1679794 instruction to sending email after submitting form. the only problem I have is I want my email body to be translatable in different languages. I already translated form labels here :

admin/config/regional/translate/translate

I also should add my form is a custom form not user sign up form ! I already know that I can change email body of sign up email here : admin/config/regional/i18n/variable

using rules module and After saving a new entityform submission event was also useless. it's like the event is not equal to form submission event . happens nothing after form submission. I also thought it would be helpful if I just could add some varibles to drupal default variables ! but I don't know how .

# Answer
> 0 votes
This is not answer to your question - but a tip on the way...

There is a good possibility to use Rules + some rules contrib module to do this, maybe in a better way because rules is also able to send node-fields-values trough Tokens id, and also capable to act on site-current-user:language from the users own default language and send mail in preferred user language. Rules can be triggered on different actions at the site. One of my Rules setting sending mail, where all fields-name are translated together with the fields value, based on user-default-language settings.

---
Tags: forms, rules, emails, i18n-l10n
---


# Question
Title: Reference to an Image of a different content type
here is my question:

I have two content types, **Events** and **City**.
The goal here is to "connect" content of type "Events" with a city, so that, when i publish content of type "City", to include the logo (image field) of the referenced city.
*What i have done till now:*
I have used the field reference module, creating a "field\_reference" field on Content Type "Events". At its configuration, i chose the desired "logo\_field" from the "City" content Type, but only the name of the city logo appears, and not the logo itself (on node page). The same appears when i want to use this field in a view.

Any ideas?

# Answer
> 1 votes
Have you tried to use Entity Reference?

With this module, you can first add a connection between to entities, and then you may be able to create a contextual view of selected field of the connected entity where needed.

# Answer
> 0 votes
This would be a great case for creating a taxonomy vocabulary. An event begins and ends but a "city" can be considered pretty solid.

What you would do:

* Create a new taxonomy vocabulary called cities.
* Add your cities to it as items
* In your EVENTS create a term reference field for cities - this will list all the cities in your taxonomy as you have entered them before. So when you create an event you can select the city it is happening in.

Now, taxonomies kind of work like nodes; you can add fields to them such as an image field - so if you add an image field to your taxonomy vocabulary (ie. Statue of Liberty image for New York; Eifel Tower image for Paris), this means that you would always have that standard image for a particular city.

Finally, using Views, you can now control the output of a node based on it's taxonomy (the city) and hence include that image every time - based on your event's location. It is going to take a little research in achieving this, but it is the way you would do it - especially if your find yourself constantly listing events - this would end up automating this process for you.

# Answer
> 0 votes
On this page is a good example on your question https://www.drupal.org/node/1841004

The examples is "Using Views Contextual Filter and Relationship to display reference on referenced node"

---
Tags: 7, views, entities, media
---


# Question
Title: How to auto redirect link with node/id to /name?
I'm using Pathauto to generates all node url. There are many pages and blocks containing links with "node/id" instead of the "urlpath". When user click one of those link, it actually direct to the "node/id", not "urlpath" generated by Pathauto. How can I fix this?

PS: I dont wanna use "Redirect" and add them one by one

# Answer
> 3 votes
You are probably looking for Global Redirect. That module does what you want it to do, it checks to see if there is a path alias for things like node/1 and if there is it will redirect to that URL.

> GlobalRedirect is a simple module which…
>
> 1. Checks the current URL for an alias and does a 301 redirect to it if it is not being used.
> 2. Checks the current URL for a trailing slash, removes it if present and repeats check 1 with the new request.
> 3. Checks if the current URL is the same as the site\_frontpage and redirects to the frontpage if there is a match.
> 4. Checks if the Clean URLs feature is enabled and then checks the current URL is being accessed using the clean method rather than the 'unclean' method.
> 5. Checks access to the URL. If the user does not have access to the path, then no redirects are done. This helps avoid exposing private aliased node's.
> 6. Make sure the case of the URL being accessed is the same as the one set by the author/administrator. For example, if you set the alias "articles/cake-making" to node/123, then the user can access the alias with any combination of case.
>
> Most of the above options are configurable in the settings page. In Drupal 5 you can access this after enabling the globalredirect\_admin module. In Drupal 6, the settings page is bundled into the module.

**Note**: That is straight from the module page, they haven't updated that Drupal 5-6 statement to include D7 I don't guess but I use this module in D7 and it works also.

---
Tags: 7, redirection
---


# Question
Title: Internet Explorer 11 Overlay does not close
I am experiencing an issue where the overlay wont close when saving a piece of content. This only happens on Internet Explorer 11. I've tested it on Chrome Firefox and IE 10 and it is working fine.

The problem is when I save content, the overlay modal disappears and I'm left with a grayed out page and cant click or do anything. Also when I save a setting everything saves but I cant exit the modal and if I click another admin link the site forces itself to non-overlay mode. Weird stuff! Anyone ever experience this problem? Again its only on Internet Explorer 11.

I thought it might be jQuery related so I checked every version of jQuery that I use with the jQuery update module and it didn't fix it.

# Answer
> 1 votes
I fixed it yay! It was a problem with jquery update. I updated the module to the alpha3 release which adds support for jquery version 1.11 and it works fine now.

---
Tags: modal-dialogs
---


# Question
Title: How can I remove the descriptions from the registration page programatically?
Using the custom module mentioned here https://www.drupal.org/node/754542#comment-2775706 I was able to remove the descriptions from the user login page.

```
function alterlogin_form_user_login_alter(&$form, &$form_state) {
  $form['name']['#description'] = t('');
  $form['pass'] = array('#type'  => 'password',
                        '#title' => t('Password'),
                        '#description' => t(''),
                        '#required' => TRUE,
                       );
}

```

however when I try

```
function alterlogin_form_user_register_form_alter(&$form, &$form_state) {
  $form['name']['#description'] = t('');
}

```

the description stays the same. I know it's targetting the page because

```
function alterlogin_form_user_register_form_alter(&$form, &$form_state) {
  $form['name']['#description'] = t('');
  $form['pass'] = array('#type'  => 'password',
                        '#title' => t('Password'),
                        '#description' => t(''),
                        '#required' => TRUE,
                       );
}

```

creates a password field on the registration page (that I assume does nothing).

# Answer
Your structure is just a bit off.

```
$form['name']['#description'] = t('');

```

Should be:

```
$form['account']['name']['#description'] = t('');

```

If your ever unsure of what an array looks like, always a good idea to download devel and dpm item so you can see what the structure looks like.
> 0 votes

---
Tags: 7, forms, theming
---


title: view with nested relationships

text:
# Question
Title: view with nested relationships
I have 3 node types. A, B and C.

A has an entity reference to B. B has an entity reference to C.

A has a list field. One of the values is "4". I need to display all node of type C where the top parent of type A has the value 4 in this list field.

I created a 'relationship referencing entity:field\_in\_type\_a\_reference\_to\_type\_b'. And I created a context filter 'provide default value:4' with the relationship.

This part works. Only nodes of type B with parent nodes with list value '4' are displayed.

But I need the filter for one reference level deeper, for nodes of type C. I created one more relationship referencing entity:field\_in\_type\_b\_reference\_to\_type\_c with the relationship. I tried this relationship with and without the other relationship.

But with no success. Nodes of type C aren't displayed.

How can I get the relationship from C to A?

# Answer
It sounds like you're starting with node type B, whereas you should be starting with node type C.

* Create your view with appropriate filters so that you only see nodes of type C
* Add a "Entity Reference: Referenc*ing* entity" (not "Referenc*ed* entity) relationship for the B-\>C entity reference field, give it an identifier of something like "Entity B", tick "Require this relationship
* Add another "Entity Reference: Referenc*ing* entity" relationship for the A-\>B entity reference field, use relationship "Entity B", give it an identifier of "Entity A", tick "Require this relationship
* Add a filter (a regular filter, not a contextual one) requiring that your field has a value of "4", use relationship "Entity A"
> 2 votes

# Answer
Follow these steps in view.

1. First add Entity Relationship "A bridge to the Content entity that is referencing Content via field\_a\_refer" i.e content type A which is referred in content type B.
2. Then add Entity Relationship "A bridge to the Content entity that is referencing Content via field\_b\_refer".In relationship dropdown of this select "Content referencing Content from field\_a\_refer".
3. For each fields that you want to display, select from Relationship "Content referencing Content from field\_b\_refer".
4. In Filter add filter for value 4.
> 0 votes

# Answer
Here is also a good explanation with structured pictures, related to your problem. http://atendesigngroup.com/blog/making-sense-drupal-views-relationships-and-entity-references

By reason below i will add this. On this site you get a good lead on the difference between REFERENCING and REFERENCED when adding an Entity Reference as as a Relationsship in VIEWS. The example adding relations and walking up-streams and down-streams in three related Nodes-content-types crelation, to get the right Node related to the Views relation. The trick is to understand the Entity relations "two way relations" and use it in Views.
> 0 votes

---
Tags: entities, views
---


# Question
Title: Adaptivethemes and panels - how to create custom layout?
I am building my site using panels , mini panels on every page. In addition, I am using the panels everywhere modules. The theme I am using is: "Adaptivetheme".

I every page I built (using page manager and panels), I chose a panels layout of "AT responsive panels" 3 or 2 columns, depends on the page.

can I change the ratio of the columns of the layouts, so it will be, for examples 20/55/25, instead of the default 25/50/25?

# Answer
> 2 votes
> Panels - how to create custom layout?

In Panels, (or Adaptive), find the directory `layouts` directory.

In it, each layout has it's own directory with a couple of files in it.

Copy any of these directories, rename all the files to the new name of the directory, and you have a new plugin.

Also see the comment for the function `at_get_plugins` which provides `Ctools` specific integration so you can subtheme AT and have new layouts in your subtheme.

# Answer
> 0 votes
If you are referring to panel layouts specifically for Adaptivetheme, you should refer to this drupal.org discussion.

---
Tags: panels, theming
---


# Question
Title: How can I prevent user pages being created for users with a specific role?
I have various users on a Drupal site.

Internally, I differentiate between users by user role (e.g. 'member', 'non-member').

Is it possible that if a user has a certain user role, that I prevent them from having a user page that is visible to the public?

E.g., if user 10018 has user role 'non-member', how can I prevent user page (site.com/user/10018/) from being visible to the public and users of role 'member'?

Basically, I don't want to delete 'non-member' users unless it's absolutely necessary - but I don't want them to have user pages that are visible to anyone other than site admins.

Thank you!

# Answer
I suppose you could use the Rules module to create a redirect (possibly to 404) when someone tries to view the user page of a user with a specified role.
> 1 votes

# Answer
I would work with hook\_node\_access.

Something like, if user we are viewing does not have role Member or user looking isn't admin, prevent access.
> 0 votes

# Answer
You could use hook\_page\_build(&$page)

1. get user id from url
2. load user object using user\_load()
3. check the user role
4. change the page content as you need
> 0 votes

---
Tags: users
---


# Question
Title: How to remove inner div from create block in drupal 7
Here, i struggling to remove inner div from create block in drupal 7.Here my working code with wrong result:

```
 <div class="ft_bottom">
<div class="container">
<div class="col-md-7">
<?php  if($page['footer_bottom_left']){ print render($page['footer_bottom_left']);} ?>
</div>
<div class="col-md-5">
  <?php  if($page['footer_bottom_left']){ print render($page['footer_bottom_right']);} ?>
</div>
</div>
</div>

```

I used `string_tags` before render it remove entire html tags. But i need to remove only block div and content div.Here my wrong result:

```
<div class="col-md-5">
  <div class="region region-footer-bottom-right">
    <div class="block block-block" id="block-block-5">
      <div class="content">
    <ul>
    <li><a href="#">Plan du site</a></li>
    <li><a href="#">Acessibilite</a></li>
    <li><a href="#">Credits</a></li>
    <li><a href="#">Mentions legales</a></li>
</ul>  </div>
</div>
  </div>
</div>

```

Correct format:

```
<div class="col-md-5">

        <ul>
        <li><a href="#">Plan du site</a></li>
        <li><a href="#">Acessibilite</a></li>
        <li><a href="#">Credits</a></li>
        <li><a href="#">Mentions legales</a></li>
    </ul>
    </div>

```

How to remove inner div from custom block in drupal 7.Kindly guide me..?

# Answer
> 1 votes
The markup you require removing comes from one or more template files. While i have no idea what theme you are using, ill assume its one that hasn't overidden the default template files..

If you go and get the file modules/system/region.tpl.php and copy it to your theme folder you can remove the markup you do not require. e.g. delete `<div class="region region-footer-bottom-right">`

To get rid of the rest of the markup you will have to override the block template in the same fashion, to only remove the markup from 1 specific block you can use naming suggestions here https://www.drupal.org/node/1089656

note: Flush the caches for the theme to pick up the presence of any new template files.

---
Tags: 7, blocks
---


title: The 'to' date field not updating

text:
# Question
Title: The 'to' date field not updating
Out of the box the date field can accept a 'from' and 'to' date parameters and the 'to' date field will auto update when the 'from' field changes. As work has progressed on my site the field no longer automatically updates. Any idea as to why this would happen?

# Answer
> 1 votes
I recreated the date field settings on a clean install of drupal. I installed/enabled views, ctools, and the date api. I enabled the date popup widget and created a dummy content type. The popup and textfield widgets for the date field do NOT auto update but the select list does. I guess this is how it is designed. Back to the drawing board on this one. the popup module could possibly be modified to allow auto updating.

---
Tags: entities, datetime
---


# Question
Title: Drupal Views field handler: how to unserialize an additional field data?
I'm developing custom Views field handler, which renders a "Reorder" button on Commerce Line Item View. I need to access to the 'data' field, which is a serialized array. What is the best way to get serialized field data?

```
/**
 * Implements Reorder Line Item button field.
 */
class commerce_reorder_lineitem_handler_field_commerce_reorder_lineitem_button extends views_handler_field {

       ...

          function construct() {
            parent::construct();
            $this->real_field = 'line_item_id';
            $this->additional_fields['line_item_id'] = 'line_item_id';
            $this->additional_fields['order_id'] = 'order_id';
            $this->additional_fields['data'] = 'data';
          }

          /**
           * Render form element placeholder.
           */
          function render($values) {
            return '<!--form-item-' . $this->options['id'] . '--' . $this->view->row_index . '-->';
          }

       ...

```

}

# Answer
The views data can be altered in the handler's render() method.

```
  function render($values) {
    $values->commerce_line_item_data = unserialize($values->commerce_line_item_data);
    return '<!--form-item-' . $this->options['id'] . '--' . $this->view->row_index . '-->';
  }

```
> 0 votes

---
Tags: views
---


# Question
Title: Node reference + i18n - How to display only referenced nodes for the current language?
I have two content types with multilingual content (French/English), Publications and Profils.

I have set up a node reference on Publication content type to link any Publication with the concerned Profil.

Unfortunately all Profils appear in listing, which is very confusing for the user. I would like to only display french Profiles when editing/creating a french Publication (and same for english content).

I just discovered the module i18n node reference synch (https://www.drupal.org/project/i18n\_node\_reference), but unfortunately this module doens't provide this kind of feature.

# Answer
> 0 votes
**If** it would be an option for you to switch from using node reference to entity reference, **then** you could try to use the Translated Entity Reference module. From its project page:

> ... brings better i18n support to Entity Reference field selection widget.

---
Tags: i18n-l10n, nodes
---


title: A Module which describes other modules

text:
# Question
Title: A Module which describes other modules
I am working on a module which is able to **automatically generate a developer document** based on the hooks, menus, files and other attributes it holds.

Often when we install a new module, We need to search for the configuration options provided by it. So by automatically generating a document, this issue will be solved.

* I started working on this based on clive's suggestion in the post (Get a particular module's information programmatically)
* I could retrieve the menu links created by a module as clive suggested in that post.
* To retrieve hooks used in a module, I used the PHP function `token_get_all()` to get all function used in a file and checked whether its a hook.

> *Now, I need some suggestions about what can you know by looking through a modules file. What else in a module file can help one understand a newly installed module better?*
>
> *Is there any API's to get information about a hook from drupal.org?*

# Answer
Now there is a module for that ;) It's the Developer Docs module.

Here's a brief description about it (from its project page):

> Developer Docs is a module specially made for drupal developers (amateur). When a new module is installed, it is hard to find what changes it does unless we look into the code. This module provides an overview of "what it does" without looking into the code.
>
> This Module generates a document automatically based on the drupal elements used in the module such as:
>
> * Administration menu
> * Hooks
> * Database Schemas
> * Themes
> * Variables
> * Blocks
> * Node types
> * Entity Types
> * Fields (Formatter, Widget)
> * Field Formatters
> * Field Widgets
> * Hooks Created
>
> After enabling this module, list of installed modules will be available at admin/reports/developer-docs/
> 2 votes

# Answer
Check out d.o's API page. It exposes various node types they should let you do some meta analysis of module. I'm not sure if api.drupal.org has an exposed API to get info about each hook. That sounds like exactly what you're looking for.

Sounds like an ambitious and useful module! If it works out, it sounds like something that would be useful in Devel. You should take its modules' code to get some ideas. Perhaps ask its maintainers too.
> 1 votes

---
Tags: 7
---


# Question
Title: Get a particular module's information programmatically
1. Is there any function to retrieve all the hook used by a particular module and also
2. A function to return all menu links (along with its description) created by a particular module

> I looked into module\_hook and module\_implements but both were used to find whether a particular hook is used in a module. But what I need is vice versa.

I need it because configuration options for a particular module can be easily found by getting menu links in a page as a overview.

# Answer
> 1 votes
1. No - as you've already discovered, the association is the other way around (i.e. a list of modules against each hook, not a list of hooks against each module). Nothing in Drupal's core needs to know a list of all hooks a module implements, so no such function exists. As there's no requirement for a module to declare which hooks it provides (though they can through `hook_hook_info()`), such a function would be difficult or impossible to implement reliably.

If you can trust that all the modules you have installed are well documented, you could write something that looks in the comment block of each function for *Implements hook\_*, and build a list yourself that way. Or you could compile a list of all the hooks you're interested in knowing about, run each of them through `module_implements`, and build your list.
2. Assuming by "menu link" you mean a path provided by a module that has the default menu type, and will subsequently appear in a menu automatically, something like this will do it for all modules:

```
$menu_items = array();
foreach (module_implements('menu') as $module) {
  $func = $module . '_menu';
  if (function_exists($func)) {
    foreach ($func() as $router_path => $item) {
      if ($item['type'] == MENU_NORMAL_ITEM) {
        $menu_items[$module][$router_path] = $item['title'];
      }
    }
  }
}

```

That will probably need to be be tweaked for your requirements.

# Answer
> 0 votes
**@clive:** Thanks for your Ideas. Based on your Ideas I started working on it and now its a full project on drupal.org. I also thought that it might answer the question.

Developer Docs Module page brief description:

> Developer Docs is a module specially made for drupal developers (amateur). When a new module is installed, it is hard to find what changes it does unless we look into the code. This module provides an overview of "what it does" without looking into the code.

---
Tags: 7
---


title: Error after migrating site

text:
# Question
Title: Error after migrating site
I get this error after I have migrated my site from local to live.

> Notice: unserialize() \[function.unserialize\]: Error at offset 718 of 1340 bytes in views\_db\_object-\>load\_row() (line 2251 of /storage/content/16/184116/.com/public\_html/sites/all/modules/views/includes/view.inc)

And this results in my site not showing my views. I suspect that this could have something to do with me changing "mylocalsitedirectory" to "mylivesite" in DB before importing DB to live site and ending up having a different serialization in Views than what it expects. But how do I solve this?

# Answer
> 1 votes
You don't have to delete everything. Using database viewing/querying software (phpMyAdmin, dbForge Express, etc.), you can identify exactly which view is causing problems allowing you to remove only one view or attempt to fix it.

It is detailed in this answer: https://drupal.stackexchange.com/a/105393/8506

# Answer
> 0 votes
This is a painful process, but gets the job done.

* Delete the two tables views\_display and views\_views
* Export all views manually using Drupal export view from development environment
* Import all views manually using Drupal import view in production environment

# Answer
> 0 votes
I've had some success with this script:

http://davidcoveney.com/782/mysql-database-search-replace-with-serialized-php/

---
Tags: views, migrations
---


# Question
Title: Drupal Feed importers: Update Node values without needing to include all values in Feed
Currently when I try to import data through a feed, importer, if any field from the mappings is missing then the data for that field gets overwritten. This is despite of selecting

> Update existing nodes

or

> Replace existing nodes

Thus how can I ensure the data does not get overwritten with blank even though those mappings are provided but the column is not included in the csv.

Thanks.

# Answer
You want to stick with the *Update existing nodes* to retain your existing content fields here.

The simplest way to prevent overwriting is to remove whatever mappings that aren't available in your CSV. If you have different CSVs with different available columns, cloning your current CSV feed importer and remove the columns from the new importer should accommodate different data update sources.
> 1 votes

---
Tags: 7, feeds, importing-exporting
---


# Question
Title: Email field on registration page not working
When I try to register a new account using the standard settings for my site no matter what I put in the email field it gets highlighted in red and I can't register a new user. Has anyone experienced this before or know any solutions to this?

# Answer
1. There you must receive a message with the error. If you don't see it, please, check if your theme have enable the messages.
2. Check if the mail is not register in the site. Just try to reset the password using that email address and you will see if was registered or not.
> 0 votes

---
Tags: users, emails
---


title: Shortened Drush option

text:
# Question
Title: Shortened Drush option
I am trying to write a shortened Drush option - we want to have an option for both `--force` as well as `-f`

I'm searching everywhere and not seeing any documentation, but it seems like something like it is supported based on this page:

```
https://groups.drupal.org/drush/commands

```

What I've got so far:

```
function parsexml_drush_command() {

  $items['parsexml'] = array(
    'description' => 'Parses XML from an XML feed.',
    'aliases' => array('pxml'),
    'arguments' => array(
      'path' => 'Path to the XML file.',
    ),
    'options' => array(
      'force' => 'Flag to force processing of previously processed XML files.',
      'f' => 'Shortened flag to force processing of previously processed XML files.',
    ),
  );

  return $items;
}

```

But my guess is that that isn't correct.

What is the correct way to have multiple aliases per option? I can only find how to set the alias for a given drush command.

# Answer
> 1 votes
Sorry, Drush reserves all short (-f) options for use exclusively by Drush core. You cannot define them in contrib extensions.

See the function drush\_get\_global\_options for an example of how to define options that have attributes; the short option is 'short-form', although this does not work right for non-Core commands.

---
Tags: drush
---


title: Block in Drupal 8

text:
# Question
Title: Block in Drupal 8
I have coded a plugin in my module which extends block base and generates labels for block in /admin/structure/block page under Place block. These block are being generated for different entities. The creation of block for different entities is dynamic and depend on configuration setting of module.I am facing two problem related to this:Firstly,suppose in the configuration form I have selected comment and user so label for these two entities are created in the Place block section but when I deselect comment then the label for comment remains still remains in block section.And when I clear the cache the label for comment is removed from Place block section.The code which I am using in `build()` function is:

```
public function build() {
  return array(
    '#theme' => 'links__entity__module',
    '#links' => $this->linkBuilder->buildLinks($this->request->attributes->get($entity_type)),
  );
}

```

What changes should I make so that configuration changes are immediately reflected in the /admin/structure/block page?

For the other problem I am facing I asked it over here:All instances of block are not getting removed. Thanks.

# Answer
Answering the first part.

Do I read this correctly that you are saying that you are using block plugin derivates, one for each enabled entity type?

This has nothing to do with build()/displaying output in the block. That can't be solved with cache tags, you need to explicitly clear block plugin cache.

More often than not, D8 core has a similar or identical problem that it needs to solve, so what you should try to do is identify similar cases in Core and then try to find out how the problem was solved there.

In this case, it's custom block/block content entities. The list needs to be updated whenever a new one is created, the code you're looking for is in `BlockContent::postSave()`:

```
// Invalidate the block cache to update custom block-based derivatives.
\Drupal::service('plugin.manager.block')->clearCachedDefinitions();

```

PS: You can find the solution for your second question in the same class, although the way it's implemented there is actually a bit wrong, that however doesn't matter for you, since you need to do it in a different way anyway. Feel free to open a new question to get a more detailed answer.
> 1 votes

---
Tags: 8, blocks, caching, configuration
---


# Question
Title: Drupal gives `Notice: Undefined index: highlighted in include ..` error during theme creation
So, I have a fresh instal of Drupal 7.34 and decide to create a simple theme.

I created a folder in `/sites/all/themes/samayo` and in it, I placed a `screenshot.png, style.css, samayo.info` inside `samayo.info` I pasted these settings.

```
name = samayo
description = samayo theme
version = 0.2.1
core = 7.x
engine = phptemplate

screenshot = screenshot.png

regions[left] = Left sidebar
regions[right] = Right sidebar
regions[content] = Content
regions[header] = Header
regions[footer] = Footer
regions[footer_content_1] = Footer Content 1
regions[footer_content_2] = Footer Content 2
regions[footer_content_3] = Footer Content 3

stylesheets[all][] = style.css

```

Went to drupa and chose this them as default, and I am getting this error for the past 2 hours.

```
Notice: Undefined index: highlighted in include() (line 126 of /var/www/public/dev.samayo/modules/system/page.tpl.php).
Notice: Undefined index: sidebar_first in include() (line 138 of /var/www/public/dev.samayo/modules/system/page.tpl.php).
Notice: Undefined index: sidebar_second in include() (line 144 of /var/www/public/dev.samayo/modules/system/page.tpl.php).
Warning: include_once(/var/www/public/dev.samayo): failed to open stream: No such file or directory in _drupal_theme_initialize() (line 209 of /var/www/public/dev.samayo/includes/theme.inc).
Warning: include_once(): Failed opening '/var/www/public/dev.samayo/' for inclusion (include_path='.:/usr/share/pear:/usr/share/php') in _drupal_theme_initialize() (line 209 of /var/www/public/dev.samayo/includes/theme.inc).

```

All the answer I checked do not seem to affect anything, including this which suggested placing

```
regions[highlighted] = Highlighted

```

in the `samayo.info` file, but even this could not change anything.

# Answer
this is probably stemming from the default page.tpl.php which is expecting to find a region `highlighted`. The best approach IMHO would be to create a custom page tpl that excludes the regions you don't use, and includes the regions you do.

You can find the default page.tpl.php under modules/system - just copy the file to your theme directory (or sub folder templates) make the changes you want, and then clear the cache
> 1 votes

---
Tags: theming
---


# Question
Title: How can I tell Guzzle to safely ignore ssl.certificate_authority in Behat testing? (Development server)
On a sandbox install of Drupal running behat under the Behat Drupal Extension, I'm trying to fun the following feature:

```
@api
  Scenario: Logged in User
    Given I am logged in as a user with the "administrator" role
    And I am on '/user'
    Then I should see the heading "User"

```

**Inital cURL error**

I get this error complaining about the SSL certificate.

```
cURL error 60: Issuer certificate is invalid. (GuzzleHttp\Exception\RequestException)

```

**My first attempt to ignore fails**

This makes sense. This is a sandbox on RHEL 7 where I just activated mod\_ssl. In order to try to ignore this, I added the `ssl.certificate_authority: false` to behat.yml. Since that I now see this...

> No method can handle the ssl.certificate\_authority config key (InvalidArgumentException)

**behat.yml set up**

```
 default:
      suites:
        default:
          contexts:
            - FeatureContext
            - Drupal\DrupalExtension\Context\DrupalContext
            - Drupal\DrupalExtension\Context\MinkContext
      extensions:
        Behat\MinkExtension:
          goutte: ~
          sessions:
            my_session:
              goutte:
                guzzle_parameters:
                  ssl.certificate_authority: false
          selenium2: ~
          base_url: http://localhost
        Drupal\DrupalExtension:
          blackbox: ~
          api_driver: 'drupal'
          drush:
            alias: 'local'
          drupal:
            drupal_root: '/var/www/html'

```

**Update** Based on information from the Github issue queue, I have changed my

# Answer
> 2 votes
After reading on https://github.com/Behat/MinkExtension/blob/master/doc/index.rst#drivers, I tried the following in the behat.yml file.

```
default:
  suites:
    default:
      contexts:
        - FeatureContext
        - Drupal\DrupalExtension\Context\DrupalContext
        - Drupal\DrupalExtension\Context\MinkContext
  extensions:
    Behat\MinkExtension:
      goutte:
        guzzle_parameters:
          verify: false
      selenium2: ~
      base_url: http://localhost
    Drupal\DrupalExtension:
      blackbox: ~
      api_driver: 'drupal'
      drush:
        alias: 'local'
      drupal:
        drupal_root: '/var/www/html'

```

It worked.

I needed to find out *how* to tell Guzzle/cURL to not worry about validating any CERT. Again, I would not do this under a production server, but for the sake of a local development environment, I'd give it a go.

---
Tags: 8, testing
---


title: Admin menu sometimes doesn't show up

text:
# Question
Title: Admin menu sometimes doesn't show up
I'm having some strange issues with the Drupal admin menu system. I can't reproduce it reliably, but these are the steps that usually cause the problem:

1. Go to `/user` and log in. This works as expected and redirects me to the user page, where I see the admin menu.
2. Navigate to the front page, either by clicking a link on the page or by manually entering the `/` address.
3. Observe that there is no admin menu.
4. Refresh the home page (possibly a couple of times), and the admin menu may eventually appear.

I've tried both Firefox and Chrome in private browsing sessions, as well as clearing the Drupal admin menu cache. I'm completely thrown by this, as checking in Firebug/Chrome developer tools reveals the `SESSxxxx` cookie properly set and not changing between when the menu is shown and when it isn't.

Related questions refer to CSS/JS aggregation issues as well as permissions errors. It seems unlikely that at least the latter problem would be so unreliable.

I have Drupal 7 running on PHP 5.4.39/Apache 2.2.22 under Debian wheezy.

# Answer
> 1 votes
The few times i have had a similar issue i have resolved it by turning off 'Cache menu in client-side browser' on this page admin/config/administration/admin\_menu

# Answer
> 0 votes
I have had this in the past with differing causes:

* if you have jQuery Update installed - I found this occasionally caused an issue where the admin menu would not show - the trick was finding a version that still produced what I wanted while maintaining the admin menu visibility - this can be confirmed if you have jQuery update installed, by temporarily disabling it
* when developing custom modules, adding functions to template.php or otherwise making changes to tpl files I have found on rare occasions that an error in one of those files will cause the admin menu to stop showing - this can be confirmed by disabling any custom modules and changing the theme to Bartik temporarily

---
Tags: 7
---


# Question
Title: Add all related content from entity reference with views
I really hope someone can help me, because it's the last thing I have to do in this site, and I thought it would be more or less easy, but I can't get this to work. Not even sure if this is the wright question, and sorry for some English.

My situation it's this one: I have two content types: Books and Authors. Books as a **entity reference** to authors.

In the node type Books, I want to display the book authors plus all their books.

As I use panels, I can do this simple or making a view.

But **what I can't do**, it's **to display all the author's books in that node**.

I can create a view with the authors and all their books, using views merge rows, to merge the books.

But if in the contextual filters I use the nid, all I get it's the same book from the node.

So I'm trying to create a attachment to display just the books titles from those authors, but honestly, I'm completely lost !

Perhaps someone could give me some examples how to achieve this.

Thanks

# Answer
Click the "More" link in the contextual filter. That fieldset is collapsed by default but you'll find the option to make exclusions there. You may have to exclude the current node ID separately--not sure about that.
> 0 votes

---
Tags: entities, views
---


# Question
Title: Views-based search not returning expected results
I've got a Views-based search interface for my Drupal 7 site. I'm noticing when I do a text-based search using the 'search terms' (Search: search terms) field it's only returning partial results.

I've already ensured the search index was rebuilt and cron was run.

My View is set to show all records by default. My other drop-down filters work fine.

It's just the search terms field that only returns partial results. Specifically if you search for a phrase it returns only results from one value of a field list...

Example: if I type 'the grantsmanship center' (without single quotes) it does NOT return all the correct results. However, if I type just 'grantsmanship' (without quotes) it does return the results correctly. Also if I type 'grantsmanship center' without quotes it returns the correct results. If I type "the grantsmanship center" (with quotes) it returns the correct results but puts only 2 items per page (for some reason I don't understand)...it's set to return 10 items per page. All the others return those results paged correctly.

Anyone know what might be going on here?

# Answer
> 1 votes
May depend on your version of Views, as there appear to be some known issues, depending on the Drupal Views version.

---
Tags: views
---


# Question
Title: How to redirect a page to the custom location after form validation?
I have a form with comment section. when the comment is given as empty it redirects to the page called /comment/reply. I have to change it to my custom path. how can i do this

# Answer
You shouldn't really do it in validator. Redirect in submit handler, with code like:

```
$form_state['redirect'] = 'comment/reply';

```

For more details of form redirecting consult official documentation.
> 1 votes

# Answer
This worked for me:

```
mymodule_form_comment_form_alter(&$form, &$form_state) {
    $form['#action'] = "my/path";
}

```

An empty string will mean the form doesn't redirect.
> 0 votes

---
Tags: comments, redirection, navigation
---


# Question
Title: Why node/*/track appears as Referrer to node/*?
I have the Statistics core module turned on in my Drupal 7 site.

When I visit the 'Track' tab of a node (node/X/track), the table shows that same page – node/X/track – listed several times as the 'Referrer' to the page itself – node/X. These visits are made by 'Anonymous (not verified)' users.

How can that happen if only the admin (myself) has the permission to view the 'Track' tab??

However, if I click on 'Details' for one of these anonymous visits (/admin/reports/access/\*), the "Referrer' information is blank.

Is there some misconfiguration in my site or I did not understand how the Statistics module works?

# Answer
The issue is with the `_statistics_link()` function and no referral data; this function relies on `drupal_get_path_alias()` and when an empty path (i.e. the referrer) is passed to it, it returns the current path which is `node/%node/track`.

So in other words, those are not anonymous users viewing the tracking page, rather it's anonymous users browsing directly to the page (or not sending referrer data).
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: How to let view display selected field content according to nid
I have a content type "banner" with Field Collection Fieldset, each fieldset is having a image upload field and a text field to enter node ID.

Eg output:

* Image A, nid=1
* Image B, nid=2
* Image C, nid=3

I would like to have a view block, appearing in every page, and shows Image A when the page nid is 1, shows Image B when nid is 2.

I know this should be something related to filter or contextual filter, but I can't get the correct steps to configure. Is there any way to do it?

# Answer
> 0 votes
I think this is what you're looking for

Add a **contextual filter** of

> content: nid

then do as the picture below.

---
Tags: 7, views
---


# Question
Title: Can DS manage "admin tabs" placement for a node?
Is there an existing sub-module or someplace i'm not looking for Display Suite to allow me to arbitrarily place the `View, Edit, Revisions, Manage Display, Devel` tabs that appear when viewing a Node... say I want to move them to a different place in any DS template like Right or Left.

# Answer
> 0 votes
After some looking around, I've found the following two approaches:

1. Use DS's 'dynamic field'
2. Use DS's 'preprocessor field'

**Dynamic Field**

* Create a Dynamic Field (in /admin/structure/ds/fields) for Node entities.
* Go to the 'manage display' of your content type and place the dynamic field somewhere.
* Click 'Select Content' on the field settings (through manage display)
* Select 'Page Elements'
* Select Tabs, and save

**Preprocessor Field**

Not 100% working for me right now, however just to give the basic idea:

* Create a preprocessor field in DS and add the field to your content type.
* In your template.php file, instantiate the field:

function YOURTHEME\_preprocess\_node(&$vars) { $vars\['nameoffield'\] = print render(menu\_local\_tabs()); }

I'm currently getting some errors with the preproccessor approach, however the dynamic field approach is working fine.

---
Tags: 7, display-suite, entities
---


# Question
Title: how to Add new Role employer also display in url like user/employer?
the default roles anonymous user, authenticated user, administrator and i want to add new role employer i did it people -\> permissions -\> roles -\> add roles. i want to create new sign up **web form** that employer user ? and i want URL like user/employer

# Answer
> 0 votes
You can do this by using any of below module :

1. Registration role module. After register your self by user can directly assign the role.

> Registration role lets an administrator select a role to automatically assign to new users. The selected role will be assigned to new registrants.

2. Webform Rules module.

> This module adds rules integration on webforms. Webform Rules makes it possible to catch webform submissions by rules and do whatever you'd like to do with it.

3. Auto Assign Role \- This module definitely solve your both the issues i.e assigning role after registration & passing role on URL.

> The Auto Assign Role serves three primary purposes :
>
> 1. Provide an automatic assignment of roles when a new account is created.
> 2. Allow the end user the option of choosing their own role or roles when they create their account.
> 3. Provide paths that will trigger a specific role when an account is created.

4. For the user/employer url you also do this by using Path Auto module.

> The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias. This allows you to have URL aliases like /category/my-node-title instead of /node/123. The aliases are based upon a "pattern" system that uses tokens which the administrator can change.

5. Multiforms module.

> The Multiforms module is designed for the collection of data from users. It can be used to easily author multi-page forms which are published as nodes. The data collected by the forms can then be exported. It was originally designed to handle contest.

---
Tags: users
---


# Question
Title: How to find the count of items in a block?
I have a block named *views-view-fields--our-services--block.tpl.php* i need to find the no of nodes under this block.How do find the total no of nodes displaying inside a block?

# Answer
> 0 votes
In your view, for **HEADER** (located in the middle of the edit view screen) **Add a Global Result Summary**. Then just use the **@total** token like in the picture below. This will count the number of rows in your view.

---
Tags: nodes, blocks
---


title: How to translate Organic Groups Menu?

text:
# Question
Title: How to translate Organic Groups Menu?
I can translate a normal menu easily, but how do I translate an Organic Groups Menu?

# Answer
> 0 votes
Good question (+1) but be aware that this is a known issue about the OG Menu module.

There are a few issues related to it, and issue 2348821 contains a great summary of these (related) issues. It also includes some patches (the patch in #9 seems to be the recommended one to consider).

The issue is sill in status "needs review", so maybe you want to consider participating in that review? I.e. check if that patch works for you, and update the issue with your review results?

---
Tags: routes, organic-groups, i18n-l10n
---


# Question
Title: AJAX form - replacing #default_value not working
I have an AJAX form. I want to update the text of a textfield when a button is triggered. But this does not work. My form is below:

```
<?php
function my_form($form, &$form_state) {
  $form['ask_first_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Ask me my first name'),
    '#default_value' => 'I LOVE chickens',
    '#prefix' => '<div id="textfields">',
    '#suffix' => '</div>',
  );
  $form['update'] = array(
    '#type' => 'button',
    '#value' => t('Update'),
    '#ajax' => array(
      'callback' => 'ajax_example_autotextfields_callback',
      'wrapper' => 'textfields',
      'effect' => 'fade',
    ),
  );

  // shouldn't this update the default value when the button is pressed??
  if (isset($form_state['values'])) {
    $form['ask_first_name']['#default_value'] = 'I HATE chickens';
  }

  return $form;
}
?>

```

When I press the 'update' button I'm expecting the field text to change, but it doesn't. If I use `#value` instead of `#default_value` it works, but I know I shouldn't use that because I still want the user to be able to change it again.

```
<?php
// using #value works - but should I use that?
$form['ask_first_name']['#value'] = 'I HATE chickens';
?>

```

What is the recommended Drupal way to change the field value after AJAX is triggered?

NOTE: This answer solved the problem in my case, but as mentioned in the comments there is not access to the values in $form\_state\['values'\] after submit. However, I'm storing the data in $form\_state\['storage'\] so I can still access the data, though I'll probably implement ctools object cache in the end.

# Answer
This is taken from the description of #default\_value in the form api documentation:

> The value of the form element that will be displayed or selected initially if the form has not been submitted yet

Because your form has been submitted, it wont be using #default\_value. Just use #value, the user will still be able to change it.

**2021 edit.....**
As people have pointed out, the above is wrong as although it will allow you to set the value, it wont allow the user to submit an altered value.

Now using Drupal 9, in a form alter, I needed to set some default field values when an ajax button (which I inserted) was clicked.
I needed to set default values on the node "body" field and "field\_url" link field.
I removed the user input for these fields before setting a default value.

```
$userInput = $form_state->getUserInput();
unset($userInput['body']);
unset($userInput['field_url']);
$form_state->setUserInput($userInput);

$form['body']['widget'][0]['#default_value'] = 'my default value set after ajax callback';
$form['field_url']['widget'][0]['uri']['#default_value'] = 'my default value';

```

To be honest, I am not 100% sure it is the correct way, but it does work.
> 5 votes

# Answer
I made it the quick and dirty way. In my ajax callback, I set the

```
$form['inputfield']['#value'] = $form['inputfield']['#default_value'];

```

The I changed the value in the input field manually to test if the value can be changed by user and is then submitted. After checking the $form\_state\['values'\]\['inputfield'\] I realized, that the value was correctly submitted, although the field got a '#value' attribute in the ajax callback.

But I think you have to be careful: Only set the '#value' attribute in the ajax callback, not in the form declaration!

Hope that helps, although a little bit late.
> 2 votes

# Answer
As 2pha pointed out `#default_value` cannot be changed once the form has been submitted. However the array in `$form_state['input']` can be manipulated at any time.

To update the example you gave:

```
if (isset($form_state['values'])) {
  $form_state['input']['ask_first_name'] = 'I HATE chickens';
}

```

When the actual html for your form is built the value we set in `$form_state['input']` will be used as the default value.
> 2 votes

# Answer
2pha's answer did not work for me - if I set values with um, value, ie `$form['myfield']['#value']` then sure the value changed - **but it then ignored further user input!**

So this is how I achieved setting values dynamically in my form builder function during ajax call backs and still let the user amend the values (within the `if` at end).

Note in my case, I'm updating 3 fields whenever the user changes a couple of other fields.

```
 $form['ld']['letterdrop_allocations'] += array(
     '#type' => 'textfield',
     '#title' => t('Letterdrop allocations for %contact in drop %letterdrop',
       $tokens),
     '#description' => 'blah.'
     );

 $form['ld']['letterdrop_notes'] = array(
     '#type' => 'textfield',
     '#title' => 'Notes',
     '#description' => t('notes for all allocations %contact in drop %letterdrop',
       $tokens));

 $form['ld']['letterdrop_kitstate'] = array(
     '#type' => 'select',
     '#title' => 'Kit state',
     '#options' => AgcLetterDrop::kitstates(),
     '#description' => 'some words for here');

 if ($letterdrop_allocations_changed) { // overwrite field values
   unset($form_state['input']['letterdrop_allocations']);
   unset($form_state['input']['letterdrop_notes']);
   unset($form_state['input']['letterdrop_kitstate']);

   $form['ld']['letterdrop_notes']['#default_value'] =
     $ldallocations['notes'];
   $form['ld']['letterdrop_allocations']['#default_value'] =
     $ldallocations['lda_id'];
   $form['ld']['letterdrop_kitstate']['#default_value'] =
     $ldallocations['kit_state'];

 }

```

hope that helps - i've lost about ten hours on this!
> 1 votes

# Answer
I believe the proper way to change the user input or a submitted form value is by calling `form_set_value`.

This comment explains how to use this.

```
// form_set_value requires that #parents be set on the field
$form['field_your_field']['#parents'] = array('field_your_field');
// set the value by calling form_set_value($element, $value, $form_state)
form_set_value($form['field_your_field'], array('und' => array(0 => array('value' => 'WORKS'))), $form_state);

```

`$form_state` is passed by reference so the actual user input is changed and this will be reflected when the form is rebuilt and passed back by ajax callback. Therefore I think it's best to call this function during a `form_validate` function.
> 0 votes

---
Tags: forms, ajax
---


title: Should I Unset PHP variables in Drupal?

text:
# Question
Title: Should I Unset PHP variables in Drupal?
We all know php's variables(array, integer,string) would be taking large memory. So PHP recommend to unset the variables to optimize the memory.

Should I do that in Drupal too ? or Is Drupal internally handling such a things ?

# Answer
> 1 votes
No, Drupal is not doing anything to handle this; the very fact you're asking might suggest you're not totally sure how this works, as Drupal has no power over the efficiency of the code you write.

GC runs every time a function finishes, so unless you've identified an actual problem in one specific function, clearing up every single variable after you've used it, even though you theoretically can, would surely be considered premature optimisation.

Bottom line: Drupal cannot help you to write efficient code, you need to apply what you know from PHP. Whether you want or need to free the memory for every single variable manually depends on your requirements and specific code.

I would personally say you're over-thinking this a bit, as in an ideal world your functions should be small and modularised enough for this not to be an issue anyway. React to real problems, not perceived or potential ones, when it comes to optimisation.

---
Tags: 7
---


# Question
Title: Drupal 7 treat html 5 data attributes as text
First I wound like to clarity i am not asking for code.

This code work on html 5.

I create basic page in drupal and implement same code:

```
<div data-top="opacity: 1" data--400-top="opacity: 0" class="abc"></div>

```

Drupal treat data as text and print this:

data-top="opacity: 1" data--400-top="opacity: 0" class="abc"

Do I need any module to enable html5 data attributes?

I am using FULL HTML and I have no idea how to solve.

Many Thanks.

# Answer
I am not using this module. Try once this module, hope you will get some configuration settings.

1. HTML5

> This theme will be the official back-port of the theme-related work done in the Drupal 8 HTML5 initiative. We want everyone to be able to preview what's coming in Drupal 8 from a markup and CSS perspective. We want anyone to be able to easily review our progress without needing to create another install of an unstable, or unfamiliar version of Drupal.

2. HTML5 Tools

> HTML5 Tools is a module that allows Drupal sites to be built using HTML5 ... smartly.
>
> One of our goals is to provide as much support for HTML5 markup in a set of Tools provided by a module so that you can use this module with any HTML5 theme you'd like.

3. HTML5 Media

> This project has one goal. To bring a standardized, Open Source GPL front end media solution to Drupal core. This project is completely open and has no other intentions other than to provide a standard front end media solution that will benefit the entire Drupal community, so therefore, whoever would like to help in this initiative is welcome to contribute!
> -1 votes

---
Tags: 7
---


# Question
Title: Get display name from hook_preprocess_views_view
I want to use hook\_preprocess\_views\_view in order for several views to share the same template, by adding theme\_hook\_suggestions as described in this article: http://greenash.net.au/thoughts/2014/04/sharing-templates-between-multiple-drupal-views/

```
function mytheme_preprocess_views_view(&$vars) {

  if (in_array(
    $vars['view']->name, array(
      'whatever'))) {
    $vars['theme_hook_suggestions'][] =
      'whatever';
  }
}

```

Problem is, I need to specify which display of the particular view it should apply to, rather than the whole view itself. I've tried printing the $vars out which results in a huge recurring array which doesn't seem to include the display name anywhere.

I'm also aware you do this via tagging in the views UI. The same problem occurs though - I can't add a tag to a particular display of a view.

If there is another way I can accomplish this I'm all ears!

# Answer
> 18 votes
You can get the display ID through the `current_display` property of the View object, e.g.

```
$view = $vars['view'];
if ($view->name == 'foo' && $view->current_display == 'bar') {
  // ...
}

```

---
Tags: 7, views, hooks
---


# Question
Title: Using menu tokens (or similar?) to create "invite user link" on OG Group page
I am new to tokens but was planning to use the menu to token to create a simple menu allowing group administrators to easily invite users without going to the Group administration menu.

The default Organic Groups (7.2x) link for inviting members is: http://www.example.org/group/node/GID/admin/people/invite-users

As the Group ID (GID) is the same as the Node ID (NID) I thought that the \[current-page:url:args\] would work well. so I created a menu link with the path

group/node/\[current-page:url:args\]/admin/people/invite-users

Which crashes all group pages and also makes it impossible to delete the link in the menu as "the website suffered a temporary issues". Uninstalling the Menu token modules solves the issue but I am wondering how to make the menu link work as I intended.

For anyone interested in the bug this seem to be a known issue (see: https://www.drupal.org/node/1205086).

# Answer
> 1 votes
I was having similar trouble as you, due to the bug in menu-token.

The way I would go about is, as a work-around, is to create a views-block relative to your groups, adding your node id or gid as a field that is not displayed (you'll have to move this to the top of your fields list in views for it to work).

Then you add a "global text" -field with a value like "Invite", re-writing the output as a link that includes the node id/gid as a token in the URL. This must be located below the node id/gid in the field order(!).

Finally, you will have to set your views filter to restrict the output to the page a user is currently on, this way the Node id/gid field will return only the correct value. Also set your pager to a single result as measure of ensuring only one value is passed through.

Hope this helped!

# Answer
> 0 votes
So what I did following limecakes advice:

1. Create a view as a block.
2. Create a field with Content:NID, Check the "exclude it from display" box.
3. Create the link by adding another field with Global:Custom text. Unceck the create label box, in the text box add the text you want in the link (ex Invite). Under "rewrite results" check "output this field as a link". Write the link path you want to use with the \[nid\] token. In my case: group/node/\[nid\]/admin/people/invite-users
4. Add filter criteria "Content type = Group".
5. Change block settings for access to: OG Permission and the permission "unsubscribe from group". This mean that only group members will see the block.
6. Create a contextual filter Content: Nid. Under "When the filter value is not available", select Provide default value and the type "Content ID from URL". For when the filter value is available I used Specify validation Criteria with validator "content" of content type Group (my group content type) and filter value format Node ID.
7. Add the block to your Group content type where you want the link to be shown.

I suspect that only one of the contextual filter selections actually is necessary but I am not very good with them and this works.

---
Tags: organic-groups, tokens
---


# Question
Title: Apply settings to all display overridden and default in views 3
I want to add a field to a views having around 10 displays, I want to apply it for all display but I get two option 1) this page 2) all display except override! How can apply it for all display either overridden or not?

Note, If I apply it all display it only applies to default displays and I still have to do this for overridden displays. I need a quick way to add a field to all displays whether its overridden or not.

Thanks

# Answer
> 1 votes
Once its overridden there is nothing you can do to affect it globally.

I guess you could export the view and just add the field to the export code and then import the code.

---
Tags: views
---


# Question
Title: Organic Groups: how to add an invite link?
I'm using Organic Groups (og) and Organic Groups Invite (og\_invite) on a D7 site, and see a way to invite a user to the group, but only through the admin panel - enabling the permission for a group member to invite others does not add a link to the group page to send an invite - what am I missing?

# Answer
> 2 votes
I have recently used Organic Groups Invite module to add this functionality to a site. It will give you a "OG Invite Button" block that you can place on the user view page.

**Edit:** Sorry the block wasnt included I had added it with a custom module here is the code:

```
/**
 * Implements hook_block_info().
 */
function og_invite_button_block_info() {
  $blocks['og_invite_button'] = array(
    // The name that will appear in the block list.
    'info' => t('OG Invite Button'),
    // Default setting.
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 *
 * Prepares the contents of the block.
 */
function og_invite_button_block_view($delta = '') {
  switch ($delta) {
    case 'og_invite_button':
      $block = array(
        'subject' => t('OG Connect Button'),
        'content' => og_invite_button_block_content()
      );
    return $block;
  }
}

function og_invite_button_block_content() {
  //Get user from profile page
  $user_viewed = arg(1);
  $user_viewed_fields = user_load($user_viewed);

  global $user;
  $output = '';

  $query = db_select('node', 'n')
  ->fields('n',array('nid'))
  ->condition('type', 'group')
  ->condition('uid', $user->uid);

  $result = $query->execute();

  foreach ($result as $row) {

    // Check if the user is already an existing member.
    $exists = db_select('og_membership', 'ogm')
      ->fields('ogm', array('id'))
      ->condition('gid', $row->nid)
      ->condition('etid', $user_viewed)
      ->execute()
      ->fetchField();
    if (empty($exists)) {
      $name = $user_viewed_fields->field_name['und']['0']['value'];
      $output .=  '<a class="orange_btn" href="/group/node/' . $row->nid . '/admin/people/invite-users/' . $name . '/' . $user_viewed . '">Invite To Your Group</a>';
    }
  }
  return $output;
}

```

Some improvements could definitely be made like theming the link.

You will also want to add the name of the group to the button if the logged in user is the owner of more than one group.

# Answer
> 0 votes
I did this in a non-coding way by using a block view instead.

1. Create a view as a block.
2. Create a field with Content:NID, Check the "exclude it from display" box.
3. Create the link by adding another field with Global:Custom text. Unceck the create label box, in the text box add the text you want in the link (ex Invite). Under "rewrite results" check "output this field as a link". Write the link path you want to use with the \[nid\] token. In my case: group/node/\[nid\]/admin/people/invite-users
4. Add filter criteria "Content type = Group".
5. Change block settings for access to: OG Permission and the permission "unsubscribe from group". This mean that only group members will see the block.
6. Create a contextual filter Content: Nid. Under "When the filter value is not available", select Provide default value and the type "Content ID from URL". For when the filter value is available I used Specify validation Criteria with validator "content" of content type Group (my group content type) and filter value format Node ID.
7. Add the block to your Group content type where you want the link to be shown.

I suspect that only one of the contextual filter selections actually is necessary but I am not very good with them and this works.

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


title: How to enable the Views UI module?

text:
# Question
Title: How to enable the Views UI module?
I have the Views UI module on my Drupal site, and I would like to enable if but I can't.

How can I enable the Views UI module?

When I try to enable this module by using admin panel I am not able to enable because that

check-box itself disabled and I am not able to check that check-box

# Answer
> 3 votes
Make sure that you have the required modules installed and enabled. Your most probalby missing Chaos Tools

Module filter is also a easier way to manage modules

# Answer
> 1 votes
In addition to Chapabu's answer, if you have access to the drush command line. use

```
drush en views_ui -y

```

# Answer
> 1 votes
Try this by using drush command line:

> drush en -y views\_ui

# Answer
> 0 votes
Go to *admin/modules*, scroll down to the Views section (it'll be near the bottom as the list is ordered alphabetically), click the checkbox next to Views UI and then click *Save Configuration*.

# Answer
> 0 votes
Make sure that all the dependencies of View Module are enabled. After that 'Clear Cache' and then retry. I hope it will work now.

---
Tags: views
---


# Question
Title: how to wrap drupals taxonomy term node list in a div
i need to wrap the nodes teaser in a div for my taxonomy term page but cant figure out how.

this is my page , this is a list of nodes for the `products` taxonomy term, using `node--product.tpl.php` i warped the individual node in `<div class="col-md-4 col-sm-6 col-xs-12"></div>` but now i need to wrap the list of nodes in `<div class='row'></div>` and just for the `products` taxonomy term page listing ...

how can i do this ???

# Answer
> 0 votes
One option you have is to override **page.tpl.php** and wrap the "content" render:

```
      <div class="row">
        <?php print render($page['content']); ?>
      </div>

```

This will encapsulate your whole **taxonomy-term.tpl.php**, where your node list is.

---
Tags: theming, taxonomy-terms, nodes
---


# Question
Title: Drush make: "Found makefile: myfile.make. Aborting"
I have a custom drush make file and custom drupal installation file for a new site. Both work fine on my local VM, and the local VM's of the three other developers who have tried it. However, when I try to run it on our test server, it chokes:

```
sudo drush -y make stub.make
Make new site in the current directory? (y/n): y
Beginning to build stub.make.                                       [ok]
drupal-7.37 downloaded.                                             [ok]
drupal patched with 1093420-22.patch.                               [ok]
drupal patched with comment-node-type-delete-1565892-3.patch.       [ok]
Generated PATCHES.txt file for drupal                               [ok]
MYPROFILE cloned from git://github.com/MYPROFILE.                   [ok]
Checked out branch development.                                     [ok]
Found makefile: MYPROFILE.make                                      [ok]
Aborting.

```

The first time this error occurred, my investigation uncovered a permissions issue. However, that is fixed, and I'm still getting the error.

The MYPROFILE.make begins with:

```
api = 2
core = 7.37

```

And continues with a bunch of

```
project[MODULE_NAME][subdir] = contrib

```

As well as

```
projects[CUSTOM_MODULE][type] = module
projects[CUSTOM_MODULE][download][type] = git
projects[CUSTOM_MODULE][download][url] = git://github.com/CUSTOM_MODULE
projects[CUSTOM_MODULE][download][branch] = development
projects[CUSTOM_MODULE][download[branch][working-copy] = TRUE

projects[CUSTOM_THEME][type] = theme
projects[CUSTOM_THEME][download][type] = git
projects[CUSTOM_THEME][download][url] = git://github.com/CUSTOM_THEME
projects[CUSTOM_THEME][download][branch] = development
projects[CUSTOM_THEME][download][working-copy] = TRUE

```

Everything works fine on the Vagrant for Drupal Development box downloadable from Drupal.org, and also on a custom Vagrant box another of the developers set up that integrates better with components beyond the website. But on the dev server, it chokes without giving a reason why. Googling for `drush make found makefile aborted` didn't turn up anything.

**Is there some sort of diagnostic tool that I can use to get a more helpful message than 'Aborting'?**

Forgot to add:

Before posting this, I tried running drush make directly on the MYPROFILE.make:

```
sudo drush -y make profiles/MYPROFILE/MYPROFILE.make
Make new site in the current directory? (y/n): y
Beginning to build profiles/MYPROFILE/MYPROFILE.make.              [ok]
No core project specified.                                           [error]

```

But as you can see from my excerpt of the make file above, it does specify a core. And again, it works on two different VMs. -- Since MYPROFILE.make was designed to be called by stub.make, the above error is the expected reaction when running it alone.

# Answer
Have you tried this recently? It's hard to tell from the info you posted above, but your problem could very well have been caused by the ssl certificate problem on updates.drupal.org. Since sometime yesterday until a few hours ago, https connections to updates.drupal.org were failing due to a limitation of the new CDN they are using now. This caused drush dl and drush make to fail. (n.b. Drush caches update information, so things likely continued to work from the cache on systems that were working before the cert problem started.)

The drupal.org team has things patched up now, so try doing everything again from the beginning, and see if it starts working again. If that does not clear up the problem, try running `drush make` again with the --debug option, and post the results.
> 1 votes

# Answer
The reason the Make file was failing was because one Contrib module that I was downloading no longer had a "recommended release" for 7.x. Fortunately, that module was non-essential, and removing it fixed the problem. (Had it been essential, the solution would have been to request the specific version, rather than defaulting to the latest recommended release, which is good practice anyway.)
> 1 votes

---
Tags: drush, installation-profiles
---


# Question
Title: How do I customize an article URL alias?
In Drupal 6 there is a possibility to customize URL alias by the help of *\[AUTOMATED ALIAS SETTINGS\]*, but this will affect all the articles. I need to restructure my URL alias only for few paid articles.

Can we able to add /pro/ somewhere in the url only for few articles like as follows,

**Original article url parameters:**

www.example.com/{article}/{channel}/{year}/{month}/{nid}/{article\_title}

**Customised article URL:**

www.example.com/pro/{article}/{channel}/{year}/{month}/{nid}/{article\_title}

# Answer
> 0 votes
There are so many module for this you can check

Pathauto

Path redirect

Global Redirect

---
Tags: 6, path-aliases
---


# Question
Title: Module to cache URLs commonly request by bots?
Open the logs of a dozen Drupal sites and you will see some patterns for non-Drupal packages in the http requests that received a 404 response. Requests like /postnuke/article.php, /exchange/logon.asp, /awstats.pl, /wp-content/, /mailman/, /phpBB/page\_header.php, etc, etc.

Nearly 100% of these are bots scanning for exploits. I know there are several modules to block these requests based on IP, http header, or some other key piece of data.

I've been mulling over the idea of writing a module that approaches this differently.

Instead of trying to block the request, just cache the response. For sites using a reverse-proxy layer cache like Varnish, set the max-age for a ridiculously long time (1 year). The module would simply generate menu entries for common packages that a Drupal site is very unlikely to have installed. I would include the option to exclude a specific package so if you really did want to run Drupal and phpBB in the same web root, you could... but may require you to install https://www.drupal.org/project/bad\_judgement to do that :)

I realize that this type of configuration can also be done at the .htaccess level, but maintaining that for all of the packages bots are trying to exploit is beyond the skill set of many people.

Does something like this already exist?

Am I missing some obvious reason this wouldn't work. It seems like this would improve performance of a site by simply never letting a 2nd request hit the php/mysql level for another year (or until you cleared the Varnish cache)?

# Answer
> 4 votes
You can alter the fast404 code inside of setting.php to handle this. It will handle `*.asp` & `*.pl`; changing the regex so it handles paths like

```
/postnuke/article.php
/wp-content/
/mailman/
/phpBB/page_header.php

```

Can be done by replacing this

```
$conf['404_fast_paths'] = '/\.(?:txt|png|gif|jpe?g|css|js|ico|swf|flv|cgi|bat|pl|dll|exe|asp)$/i';

```

with this

```
$conf['404_fast_paths'] = '/^(postnuke|wp-content|mailman|phpBB)|\.(?:txt|png|gif|jpe?g|css|js|ico|swf|flv|cgi|bat|pl|dll|exe|asp)$/i';

```

All i did was add `^(postnuke|wp-content|mailman|phpBB)|` to the start of the string, right after the first `/`. This means that if any path starts with any of these strings we'll skip booting drupal and 404 right here taking very little server resources.

To enable fast404

> Go to the sites/default directory. Open up to the setting.php file. Around line 500 uncomment this drupal\_fast\_404(); by removing #

Source: https://docs.google.com/presentation/d/1AgnurTWsWdMAFjfFmSU7mk2zfJu8jG\_KmVdZ7-o6Pok/edit#slide=id.g385c64257\_0178

If you have dblog enabled you can run this query to find what paths are the worst offenders

```
SELECT
  COUNT(*) AS count,
  watchdog.*
FROM watchdog AS watchdog
WHERE type = 'page not found'
AND message NOT LIKE 'sites/all/%'
AND message NOT LIKE 'sites/default/%'
AND message NOT LIKE '%/styles/%'
GROUP BY message
ORDER BY
  count DESC,
  wid ASC

```

# Answer
> 0 votes
It would be preferable to catch these request at the outermost part of your server, Varnish. By adding a line like the following to your VCL:

```
     if (req.url ~ "/wp-admin/" || req.url ~ "/fckeditor*" || req.url ~ "/wp-login.php" || req.url ~ "/pma/scripts/" || req.url ~ "/myadmin/scripts/" || req.url ~ "/MyAdmin/scripts/" || req.url ~ "/wp-content/plugins/" || req.url ~ "/blog/wp-i*") {
        return (synth(403, "Forbidden"));
  }

```

you catch the troublesome requests and do what you want with them, give the a forbidden or a redirect somewhere else.

I think(...) it would be possible to create a VMOD that would be able to read a list of 'banned URLs' which was kept updated by a Drupal module.

---
Tags: performance, proxies
---


# Question
Title: How to navigate URL after moving drupal site from one server to other server?
I have just moved my drupal 7 website from one server to other server. But after moving it i am not bale to see any css effect and not able to open naviagte any link. I am using linux server.

Can somebody suggest how to do this.

# Answer
> 0 votes
These kinds of problems (after transfer to a new host) might be caused by some type of permission problems. Some of the extra comments from the OPer in the question makes me believe that is the case here also.

So I'd verify that the userid of your webserver has appropriate file permissions.

Another option is to verify the various items mentioned in the community documentation about Migrating a site. One of the typical issues is (as mentioned in this link):

> Attempt to log on to the new site. You will probably find that you are locked out by a combination of site maintenance mode and the non-clean URLs. In that case navigate to newsite/?q=user to login, then turn on clean URLs.

---
Tags: migrations
---


# Question
Title: How to redirect a newly registered user to a custom URL after signing up?
By default after a new user signs up, a redirect to the home page happens.

But in such case I want to redirect such user to another page like node/35.

In this node/35 I then want to display some content.

# Answer
> 1 votes
Consider using the Rules module to do this.

Here is how such (fairly basic) rule would look like, based on your extra comment in my answer (= new users that register do NOT need admin approval):

* **Event**: After saving a new user account.
* **Condition**: None
* **Action**: Page redirect (with value = Node/35 in your case).

The above is just a basic rule. You might want to enhance it in various ways. E.g. add a 2nd action to the very same rule to just set a special welcome message (near the top of the main content of your pages).

# Answer
> 0 votes
You can do this by using LoginToboggan module.

> The LoginToboggan module offers several modifications of the Drupal login system in an external module by offering the many features and usability improvements.

**OR**

```
<?php
function custom_form_alter(&$form, &$form_state,$form_id) {
  switch ($form_id) {
    case 'user_register_form':
          $form['#submit'][] = 'custom_user_register_submit';
      break;
  }
}

function custom_user_register_submit($form, &$form_state) {
  $form_state['redirect'] = 'node/add/business';
}
?>

```

---
Tags: 7, users, redirection, theming
---


# Question
Title: Creating line item of specific type programmatically
Is there a way to create a line item of specific type (different from the default "Product" type) programmatically? The function `commerce_product_line_item_new()`creates a line item of type Product. I can't find a function that let's you specify an existing line item type other than the default Product one.

EDIT: Never mind. I just realized that the `commerce_product_line_item_new()` function has a $type parameter that defaults to Product. Not sure how to delete the question, but maybe it will help someone else.

# Answer
> 0 votes
Never mind. I just realized that the commerce\_product\_line\_item\_new() function has a $type parameter that defaults to Product. Not sure how to delete the question, but maybe it will help someone else.

---
Tags: commerce
---


# Question
Title: how to show all alphabates in glossary block in drupal 7?
I have a glossary view in drupal 7 with attachment. These attachment missing some alphabates. showing like a|c|d|h|m etc. But I need a|b|c|d|e|f etc like this.

# Answer
Did you check this module?

https://www.drupal.org/project/views\_glossary

It provides exact same functionality.
> 0 votes

---
Tags: views
---


# Question
Title: How to add a complete menu as an item in other menus?
Let say I have 3 MENUS:

**MENU 1** with these items:

```
item menu 1 - a
item menu 1 - b
item menu 1 - c

```

**MENU 2** with these items:

```
item menu 2 - a
item menu 2 - b
item menu 2 - c

```

**MENU 3** with these items:

```
item menu 3 - a
item menu 3 - b
item menu 3 - c

```

I need to add **MENU 1** as a clild in **MENU 2** and **MENU 3** to get this:

**MENU 2** with these items:

```
item menu 2 - a
item menu 2 - b
--item menu 1 - a
--item menu 1 - b
--item menu 1 - c
item menu 2 - c

```

**MENU 3** with these items:

```
item menu 3 - a
item menu 3 - b
--item menu 1 - a
--item menu 1 - b
--item menu 1 - c
item menu 3 - c

```

Is there any way to get this?

# Answer
There is a sandbox project for combining menus: https://www.drupal.org/sandbox/klickreflex/1989788

Someone with a similar issue found code that was of value.

The poster also suggests Advanced Menu which has some merging capabilities.
> 1 votes

---
Tags: routes
---


title: Updating multiple node fields

text:
# Question
Title: Updating multiple node fields
Is there a module that allows the user to update multiple node fields in one page?

I found a method using Views (http://eureka.ykyuen.info/2012/12/13/drupal-7-update-multiple-nodes-at-once-in-a-views/), but I prefer to use module approach. Probably something that utilizes function `node_mass_update` (https://api.drupal.org/api/drupal/modules!node!node.admin.inc/function/node\_mass\_update/7)

# Answer
> 1 votes
I guess my first question is *how* many nodes are you looking to update. If it's a relatively small amount, you should just use VBO (per the article you referenced). That is the easiest *contributed* module method of updating multiple nodes.

However, it is possible for you to create your own module (i.e. `custom_node_update`) and run the `node_mass_update` upon form submission (as recommended by the API documentation). This will be especially useful if you are updating a large number of nodes because it will batch it appropriately, however, you'll be required to write some custom code.

Does this answer your question?

---
Tags: nodes
---


# Question
Title: How to upgrade module table scheme for entity
I've written a module that uses entities functionality. It has the following table scheme in .install file:

```
$schema['transaction'] = array(
    //fields
    'fields' => array(
        'id' => array(
            'type' => 'serial',
            'unsigned' => TRUE,
            'not null' => TRUE),
        'name' => array(
            'type' => 'varchar',
            'length' => 50,
            'not null' => TRUE,
            ),
        'random_id' => array(
            'type' => 'varchar',
            'length' => 11,
            'not null' => TRUE,
            ),
        ),
    //additional properties
    'primary key' => array('id'),
    'unique keys' => array(
        'random_id' => array('random_id'),
        ),
    );

```

Entity description:

```
function transaction_entity_info() {
  //song entity
  $entity_info['transaction'] = array(
    'label' => t('Transaction'),
    'label callback' => 'transaction_label_callback',
    'base table' => 'transaction',
    'fieldable' => TRUE,
    'entity keys' => array(
      'id' => 'id',
    ),
    'uri callback' => 'transaction_class_uri',
    'static cache' => TRUE,
    'admin ui' => array(
      'path' => 'admin/content/transaction',
      'controller class' => 'transactionUIController',
      'file' => 'includes/transaction.admin.inc',
    ),
    'module' => 'transaction',
    'access callback' => 'transaction_access_callback',
    'bundles' => array(
      'transaction' => array(
        'label' => 'Transaction',
        'admin' => array(
          'path' => 'admin/structure/transaction/manage',
          'access arguments' => array('administer transaction'),
        ),
      ),
    ),
    'entity class' => 'Transaction',
    'controller class' => 'transactionController',
    'views controller class' => 'EntityDefaultViewsController',
  );

  return $entity_info;
}

```

Now I need to add a new property into the table:

```
    'output' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0),

```

I can use fields, and add it through the admin panel, but I want to learn, how to upgrade the tables directly.

How can tell Drupal to reload the table scheme for this module, add attribute into the table and use it when loading the entity?

# Answer
> 1 votes
@Clive is correct (in the comments). You'll just want to add the new definition to the schema hook and then create an update script in the .install file (`hook_update_N`) to add in that definition for sites/installations that have already created your new entity.

---
Tags: upgrading, database, entities
---


# Question
Title: How does the Drupal LDAP module manage passwords?
I'm currently configuring the LDAP module for my Drupal site (7.37) and I wanted to know if it's my AD password that is stored in my database (table users).

If it's not my AD password, is it just a random string? What it is and how does it works?

Thank you.

PS: I haven't configured anything to store the password.

# Answer
> 2 votes
This is all explained in the documentation and help text provided in the admin screens of the module.

Drupal supports multiple login sources. When a user logs in an entry for the type of login used for the person is stored in `user_auth` as an example.

By default LDAP does not store for example the AD password of the user within Drupal. It stores a dummy password and passes login info to LDAP from the login form upon a login attempt.

If you configure LDAP to `sync` drupal account information to and from Drupal then Drupal may store the password your LDAP accounts -- but this depends on how you've configured your LDAP service, and how you want the drupal ldap module to interact with it.

---
Tags: 7, authentication-authorization
---


title: Alter Fieldable Panels Pane form

text:
# Question
Title: Alter Fieldable Panels Pane form
Im using Panopoly, and have created a new Fieldable Panels Pane (FPP) bundle for a specific content type.

I notice that all preset Panopoly FPP's have a check box labelled 'Make title a link' inside a fieldset called 'General Options', which is also automatically added to my new bundle, and I can't for the life of me work out how to disable it!

For reference, this field is visible through the Panels IPE as well as the traditional /admin/structure/fieldable-panels-panes/manage/BUNDLE-NAME/add.

Does anyone know how I can isolate and disable this option on a per-bundle level?

Thanks!

# Answer
> 2 votes
Almost all Drupal forms can be edited using `hook_form_alter()`, specifying the form using its id:

Hide "Make title a link" for all fieldable panels panes:

```
/**
 * Implements hook_form_alter().
 *
 * Simplify form for fpp.
 */
function your_module_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'fieldable_panels_panes_fieldable_panels_pane_content_type_edit_form') {
    $form['link']['#access'] = FALSE;
  }
}

```

Hide "Make title a link" for all fieldable panels panes of the type "your\_bundle":

```
/**
 * Implements hook_form_alter().
 *
 * Simplify form for 'your_bundle' fpp.
 */
function your_module_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'fieldable_panels_panes_fieldable_panels_pane_content_type_edit_form') {
    if ($form['#bundle'] == 'your_bundle') {
      $form['link']['#access'] = FALSE;
    }
  }
}

```

# Answer
> 0 votes
There is a new sandbox Simplify Extra which has integration with Fieldable Panels Panes.

---
Tags: 7, panels, forms, distributions
---


# Question
Title: How to require revision logging for certain users
In Drupal 7, if a specific role modifies any content, I want to require that the user add message explaining the changes. How can this be accomplished, either through an existing contrib module or custom code?

# Answer
> 0 votes
there is a Enforce Revision Log that will do this https://www.drupal.org/project/enforce\_revlog module

---
Tags: 7, workflows, nodes
---


title: Localized Taxonomy terms in a View

text:
# Question
Title: Localized Taxonomy terms in a View
Localized taxonomy terms are not displayed in a View. Only the default language term is shown. I solved this issue writing a small module according to this article.

Perfect. But in one View i have two `fields: term ID` and `Global PHP code`. My question is: what needs to be changed in the Global PHP code below to have the localized terms displayed?

```
$term = taxonomy_term_load($data->tid);
//print l($term->name,"voices", array('query' => array('type' => $term->tid)));
print l($term->name,"voices", array('query' => array('f[0]' => 'field_production_type_:'.$term->tid), 'attributes' => array('class' => array($term->name))));

/*
  $url = drupal_get_path_alias('taxonomy/term/'. $term->tid);
  $url_part = explode('/', $url);
  print l($term->name ,"voices/voiceovers/".$url_part[1], array('attributes' => array('class' => array($term->name))));
*/

```

# Answer
From the question details provided, I'm not sure if the i18nviews module is enabled (make sure it is).

Probably the best option might be to use `i18n_taxonomy_term_get_translation` as explained also in the questions:

Something else you may want to try to get the terms translated, is to use the setting (for Translation mode) `Translate. Different terms will be allowed for each language and they can be translated` (instead of 'Localize'). This setting can be found within `admin/structure/taxonomy/<YourTaxonomy>/edit`.
> 0 votes

# Answer
$term = taxonomy\_term\_load($tid); $translated\_term = i18n\_taxonomy\_term\_get\_translation($term, $langcode);
> 0 votes

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


# Question
Title: How to alter field values on a display page?
I am trying to alter field values in a page display. I can get the field values easily using field\_get\_items(), but depending on the values of other fields, I may need to manipulate the text and/or display based on some PHP logic in my template file. I am trying to do it using either hook\_page\_alter() or hook\_preprocess\_HOOK().

I cannot get the text to be altered when the page is displayed using `hook_page_alter()` or `hook_preprocess_HOOK()`. I can confirm those 2 functions are working and that I can pull the values from the DB (`$page['content']`), but I cannot override the variable to set them. For example:

```
function standard_submission_page_alter(&$page) {
    $node = menu_get_object();
    $page['content']['system_main']['nodes'][$node->nid]['field_title_nickname']['#items'][0]['value'] = 'A new nickname title!';
}

function standard_submission_preprocess_page(&$vars) {
    $vars['node']->field_title_nickname['und'][0]['value'] = 'A new nickname title 2x';
}

```

Any ideas on why my altering of this `field_title_nickname` text field value isn't being accepted and displayed? It keeps reverting back to whatever is originally in the database.

# Answer
If I need to manipulate the text and/or display based on some PHP logic, I would do it using hook\_node\_view() in a custom module, not in a template file.

```
function MYMODULE_node_view($node, $view_mode = 'full', $langcode = NULL) {
    if( $view_mode == 'full' ){
        if( some conditions here ){
            $node->content['field_title_nickname'] = array(
                '#markup' => '<div>A new nickname title 2x</div>'
            );
        }
    }
}

```
> 9 votes

# Answer
You can do that by implementing template\_preprocess\_field(&$variables, $hook) in your template.php

```
function THEMENAME_preprocess_field(&$variables, $hook) {
  if ($node = menu_get_object()) {
    if ($node->type == 'car') {
      if($variables['element']['#field_name'] == 'field_price') {
        $variables['items']['0']['#markup'] = $new_value; //new value;
      }
    }
  }
}

```

Check here: http://tassaf.moriamedia.com/change-field-value-in-node-view/
> 3 votes

# Answer
If use Display Suite implement hook\_ds\_pre\_render\_alter() to alter entity render array.

Example:

```
/**
 * Implements hook_ds_pre_render_alter().
 */
function MYMODULE_ds_pre_render_alter(&$layout_render_array, $context, &$vars) {
  $entity_type = $context['entity_type'];
  if ($entity_type == 'node') {
    $layout_render_array['ds_content']['Foo']['#markup'] = 'Bar';
  }
}

```
> 2 votes

---
Tags: 7, hooks, theming
---


# Question
Title: Why does deleting a node ALSO invoke hook_node_update?
I need to respond to an update event and regenerate a file, but when the node is deleted, the file should also be deleted. However, the problem is, everytime a node is deleted, the hook\_node\_update is ALSO called, which regenerates the file.

How can I differentiate between a node being updated (NOT deleted) and a node being deleted?

# Answer
Thanks for your answers, much appreciated!

I finally managed to find the cause. The "problem" is caused by the module https://www.drupal.org/project/field\_collection. My node has a field that is a field\_collection, and apparently, when deleting a node, the field\_collection items are first deleted from the node, which is then saved (which causes the update hook to fire), and only then the node itself is actually deleted.

It's pretty easy to workaround this issue once you actually KNOW what is causing it, in my case I modified the update hook to check for field\_collection items in the node, if there were none it means the node is about to be deleted...
> 4 votes

# Answer
Following are the set of hooks which are invoked from node\_delete function, which shows update hook will not be invoked.

```
    node_invoke($node, 'delete');
    module_invoke_all('node_delete', $node);
    module_invoke_all('entity_delete', $node, 'node');
    field_attach_delete('node', $node);

```

Make sure you are not updating any other node when action is delete of node, something like

```
   function my_module_node_delete($node) {
     node_save('any_node_id');
   }

```
> 1 votes

# Answer
No more workarounds needed. This issue has been fixed in the latest dev version of **Field collection**: https://www.drupal.org/node/2385985
> 0 votes

# Answer
Good question and good point!

But this is not just apply when you have field\_collection but also any attached entity may have the same effect (hook node update may be called when field\_attach\_delete is called in node\_delete\_multiple function), this can include the attached entity files (if you enabled file entity for example) and referenced nodes when you have chosen the option for deleting a parent node delete a child node!

Drupal automatically first delete attached entities and save the node each time (and hook node update will be called) and then continue the process (for example if you three field\_collection fields, you will have three calls of hook node update (each time it deletes a field\_collection from your node)!

In my case, my hook node update must react to deletion of a field\_collection and I can't find any simple solution to determine the difference between an update of the node (when it is deleting a field\_collection) and deleting the node (when again first it is deleting a field\_collection and call node update)!

Anyway great question and mentioning an important point!
> 0 votes

---
Tags: nodes
---


# Question
Title: How to expand trimmed body text to full body text in the same Views page?
I have a view in Drupal 7 where I am showing the node title and its body as trimmed text, as shown in this screenprint:

I need to show full body text after click on the ***Read more*** link, but in the same page. How can I do so?

# Answer
Consider using the Views Accordion module. Here is an excerpt from its project page:

> ... provides a display style plugin for the Views module. It will take the results and display them as a JQuery accordion, using the first field as the header for the accordion rows.
>
> For Drupal 7 the module integrates the jQuery UI Accordion plugin as a views style plugin. You can configure the options provided by the jQuery UI plugin.
> 1 votes

# Answer
You can use the module `Read More` https://www.drupal.org/project/readmore The field formatter expands the body text using JS when the `Read More` link is clicked.
> 1 votes

---
Tags: views, 7
---


# Question
Title: Creating module can display map in page or block in drupal
I have two days I'm trying to develop my custom module. I want to display map in block but nothing happened. how i can called css an js file and show them in page or block?

```
function exemple_init() {
  drupal_add_js('http://maps.googleapis.com/maps/api/js?sensor=false', 'external');
}

function exemple_block_info() {
  $blocks['exemple'] = array(
    'info' => t('Google Map Exemple'),
    'cache' => DRUPAL_NO_CACHE
  );
  return $blocks;
}

function exemple_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'exemple':
        $block['content'] = '';
  }
  return $block;
}

```

# Answer
> 1 votes
Firstly adding a JS file globally in `hook_init` function is wrong unless you want the file to be loaded on each page of your site. To add a JS file to a block use the `#attached` property in `hook_block_view`

eg:

```

'#attached' => array(
      'css' => array(
        drupal_get_path('module', 'mymodule') . '/css/mymodule.css',
      ),
      'js' => array(
        drupal_get_path('module', 'mymodule') . '/js/mymodule.js',
    ),
  ),

```

Secondly, I assume you want to show an address from Google Maps in your block. In that case pull the embed code from Google Maps https://support.google.com/maps/answer/3544418?hl=en and use that embed code in the block.

Sample Code for it: http://pastebin.com/5h1c2SBU

Though still curious about the JS file.

---
Tags: 7, hooks, routes, blocks
---