# Question
Title: File structure for custom modules in Drupal 7
I want to organize *non-core* (modules that are not bundled with core) modules in Drupal 7. This is my proposed structure:

1. Contributed modules - downloaded modules that are untouched
2. Custom modules - downloaded modules that are modified to suit the requirement
3. local modules - self-developed modules

I GUESS, the best approach for this is to make three folders within `sites/all/modules` like below:

1. `sites/all/modules/contrib`
2. `sites/all/modules/custom`
3. `sites/all/modules/local`

Now, there are two ways to install a module:

1. Manually
2. From the admin panel

While installing the new module manually, everything is fine. I can just go to the directory and place the module there.

But **how to install a newly downloaded module in `sites/all/modules/contrib` from admin-panel?<br>Moreover, is there any better approach for organizing non-core modules?**

# Answer
Keeping your modules folder clear is important part of development. This is my common structure:

* `contrib` — modules from Drupal.org
* `custom` — modules developed for this project
* `features` — exported features for Features-driven development
* `unstable` — sandbox, forked, unstable, patched modules

Here are some examples how to organize patches/forks:

> But how to install a newly downloaded module in \`sites/all/modules/contrib from admin-panel.

## Use Drush please.

```
drush dl views rules # will download Views and Rules into sites/all/modules/contrib automatically if contrib folder exists.

```

You also can specify `--destination` where to download project.
> 6 votes

# Answer
The structure you suggest will work.

However, you should, as a general rule, not modify contributed modules that you download. By forking a module, your local copy will be an island, and it will difficult for you to benefit from future bug fixes and other improvements added to the contributed module.

The usual way is to have *two* subdirectories below `sites/all/modules/` \- `contrib` for downloaded modules and `custom` for self-developed modules. Use *drush* instead of the admin panel to download and install in order to place downloaded modules in `contrib`.

However, sometimes you need to tweak a contributed module.

Instead of just forking a custom version, you should present your use case and requirements in the module's issue queue on Drupal.org, and upload a patch to extend the module's features to cover your use case. By doing this, you will contribute to the Drupal community, and benefit from reviews and suggestions about your proposed patch made by other users of the module.

It may, however, take some time before your patch is incorporated in the module's official code base. In the meantime, just keep a copy of the patch file, and use *git* to apply it to new versions of the module that are released by the module's maintainer. If you're unlucky, you may need to reroll the patch if the module is radically changes, but this is still a better alternative than maintaining a local fork by yourself.
> 3 votes

# Answer
There is the module\_install module, that allows you to choose which subdirectory within /sites/all/modules to install a module to, when using the admin module installer:

https://www.drupal.org/project/module\_install

Just create whichever subdirectories you want, install the module (manually put it in /sites/all/modules/contrib if you want to follow best practise!), and then enable it.
> 0 votes

---
Tags: 7, installation, version-control, files
---


# Question
Title: How to alter cck field title using hook_form_alter?
I want to change #weight, #prefix, #title for a cck field.

First I tried the following code.

```
function test_form_taxonomy_form_term_alter(&$form, &$form_state, $form_id) {
    //Working
    $form['field_test1']['#weight'] = -5;
    $form['field_test1']['#prefix'] = 'This text will rule them all!';

    //Not working
    $form['field_test1']['#title'] =  'test title';
    $form['field_test1']['und']['#title'] = 'test title';
    $form['field_test1']['und'][0]['#title'] = 'test title';
}

```

It is working good with #weight, #prefix elements.

```
//Working
$form['field_test1']['#weight'] = -5;
$form['field_test1']['#prefix'] = 'This text will rule them all!';

```

But not working for #title element in anyways.

```
$form['field_test1']['#title'] =  'test title'; //Not working
$form['field_test1']['und']['#title'] = 'test title'; //Not working
$form['field_test1']['und'][0]['#title'] = 'test title'; //Not working

```

I tried with **#after\_build** as well but no luck.

```
function test_form_taxonomy_form_term_alter(&$form, &$form_state, $form_id) {
    $form['#after_build'][] = 'test_after_build';
}
function test_after_build($form, &$form_state) {
    //Working
    $form['field_test1']['#weight'] = -5;
    $form['field_test1']['#prefix'] = 'This text will rule them all!';

    $form['field_test1']['#title'] =  'test title'; //Not working
    $form['field_test1']['und']['#title'] = 'test title'; //Not working
    $form['field_test1']['und'][0]['#title'] = 'test title'; //Not working

    return $form;
}

```

Please give me the solution for alter cck field title through form\_alter.

*Thanks in advance, Logan*

# Answer
First, you may check the exact field array with `dsm()`

```
function MODULE_form_taxonomy_form_term_alter(&$form, &$form_state, $form_id) {
  dsm($form);
}

```

In the result returned by `dsm()`, *#title* is set in 2 places. So just try :

```
$form['field_bibliographie']['#title']= t('Foo');//doesn't work
$form['field_bibliographie']['und'][0]['#title']= t('Foo');//correct one

```

I see no reason for which it would not take the correct value if you set the exact field array
> 0 votes

---
Tags: forms
---


# Question
Title: Media module and views. Cannot make video image linked to node
Using drupal 7.20, Media 7.x-2.0-unstable7, Media Youtube 7.x-2.0-rc2, File Entity 7.x-2.0-unstable7, Entity View Modes latest version.

Created new content type called "video", added video field type "Multimedia asset", Allowed remote media types "Video", Allowed URI schemes "youtube:// (YouTube videos)", "public:// (Public files)"

With Views 3 i am displaying Content: Video, File view mode "video\_preset" (preset i created with Entity View modes module). But it only displaying an image, is there any working way to make that image a link?

Already tried "rewriting output of this field" thing, that not working at all.

# Answer
Maybe you could try the File Entity Link module? Here is a quote about it (from the module's project page):

> Out of the box, the Media and File Entity modules attach media to entities using Fields but they provide no way to then display media in those fields as links to the parent entity. A common use-case for this would be a teaser view of a node showing an image linked to the node.
>
> This very simple module adds an option to the "File Types" view mode settings to accomplish this (at admin/config/media/file-types/manage/image/file-display for images).
> 0 votes

# Answer
I was using Mutlimedia Asset field type thats why file entity link didn't worked. So i changed my video field type to file -\> media selector and link worked!
> 0 votes

# Answer
@Heihachi file\_entity\_link module worked for me...

I too was facing the same issue. This module is very simple to configure. You just need to go to admin/structure/file-types/manage/video/file-display/ Scroll down and next to Save button you have  **Link file to Referencing entity**....

Just click the save button and your video images would become linkable...!!!
> 0 votes

# Answer
You need to add the File Entity Link module, then the above answers will work. Here is a quote about it (from the module's project page):

> Out of the box, the Media and File Entity modules attach media to entities using Fields but they provide no way to then display media in those fields as links to the parent entity. A common use-case for this would be a teaser view of a node showing an image linked to the node.
>
> This very simple module adds an option to the "File Types" view mode settings to accomplish this (at admin/config/media/file-types/manage/image/file-display for images).
> 0 votes

---
Tags: entities, media
---


# Question
Title: Drush dl not working on Ubuntu with postgresql backend
**modules can be added manually, but drush dl or drush en produce errors and will not download a module**

**database section from settings.php**

```
$databases['default']['default'] = array(
    'driver' => 'pgsql',
    'database' => 'drupal7',
    'username' => 'drupal7',
    'password' => 'secretpw',
    'host' => 'localhost',
    'port' => '',
    'prefix' => ''

```

**also, when I run drush sql-cli it ask for a password**

**results of a module download attempt: "drush dl"**

```
root@list:/usr/share/ilterweb# drush dl admin_menu -vd
Bootstrap to phase 0. [0 sec, 1.88 MB]                               [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drush() [0.01 sec, 1.99 MB] [bootstrap]
Cache MISS cid: 6.5.0-alias-path--42baa7de58f511c1e70f7cbef941324c [0.01 sec, 2      [debug]
MB]
Cache HIT cid: 6.5.0-commandfiles-0-17d9338540482247f3d013b718aae478 [0.01 sec,      [debug]
2.01 MB]
Bootstrap to phase 0. [0.08 sec, 5.38 MB]                                        [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_root() [0.13 sec, 6.24 MB]       [bootstrap]
Initialized Drupal 7.26 root directory at /usr/share/ilterweb [0.14 sec, 6.24 MB]   [notice]
Drush bootstrap phase : _drush_bootstrap_drupal_site() [0.14 sec, 6.25 MB]       [bootstrap]
Initialized Drupal site default at sites/default [0.14 sec, 6.25 MB]                [notice]
Cache HIT cid: 6.5.0-commandfiles-2-062e26fa8ebdd8c444d688ab9447c986 [0.14 sec,      [debug]
6.25 MB]
Drush bootstrap phase : _drush_bootstrap_drupal_configuration() [0.14 sec, 6.25  [bootstrap]
MB]
Drush bootstrap phase : _drush_bootstrap_drupal_database() [0.16 sec, 6.27 MB]   [bootstrap]
Successfully connected to the Drupal database. [0.16 sec, 6.27 MB]               [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_full() [0.18 sec, 6.78 MB]       [bootstrap]
Cache HIT cid: 6.5.0-install_profile-66ecfeb9791a023150773849f1550c5d [0.37 sec,     [debug]
16.57 MB]
Cache HIT cid: 6.5.0-install_profile-66ecfeb9791a023150773849f1550c5d [0.37 sec,     [debug]
16.57 MB]
Cache HIT cid: 6.5.0-commandfiles-5-d366cec34f20f219c93d2cf7b993082d [0.37 sec,      [debug]
16.58 MB]
Drush bootstrap phase : _drush_bootstrap_drupal_login() [0.37 sec, 16.57 MB]     [bootstrap]
Successfully logged into Drupal as Anonymous (uid=0) [0.38 sec, 16.68 MB]        [bootstrap]
Found command: pm-download (commandfile=pm) [0.38 sec, 16.68 MB]                 [bootstrap]
Loading version_control engine. [0.46 sec, 16.71 MB]                                [notice]
Loading package_handler engine. [0.46 sec, 16.72 MB]                                [notice]
Executing: wget --version
Loading release_info engine. [0.47 sec, 16.75 MB]                                   [notice]
Including /home/ubuntu/.composer/vendor/drush/drush/commands/pm/download.pm.inc  [bootstrap]
[0.48 sec, 16.84 MB]
Calling hook drush_pm_download_validate [0.48 sec, 16.91 MB]                         [debug]
Returned from hook drush_pm_download_validate [0.48 sec, 16.91 MB]                   [debug]
Calling hook drush_pm_download [0.48 sec, 16.93 MB]                                  [debug]
Downloading release history from                                                    [notice]
http://updates.drupal.org/release-history/admin_menu/7.x [0.48 sec, 16.93 MB]
Executing: wget --version
  GNU Wget 1.15 built on linux-gnu.

  +digest +https +ipv6 +iri +large-file +nls +ntlm +opie +ssl/openssl

  Wgetrc:
      /etc/wgetrc (system)
  Locale:
      /usr/share/locale
  Compile:
      gcc -DHAVE_CONFIG_H -DSYSTEM_WGETRC="/etc/wgetrc"
      -DLOCALEDIR="/usr/share/locale" -I. -I../../src -I../lib
      -I../../lib -D_FORTIFY_SOURCE=2 -I/usr/include -g -O2
      -fstack-protector --param=ssp-buffer-size=4 -Wformat
      -Werror=format-security -DNO_SSLv2 -D_FILE_OFFSET_BITS=64 -g -Wall
  Link:
      gcc -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat
      -Werror=format-security -DNO_SSLv2 -D_FILE_OFFSET_BITS=64 -g -Wall
      -Wl,-Bsymbolic-functions -Wl,-z,relro -L/usr/lib -lssl -lcrypto
      -ldl -lz -lidn -luuid ftp-opie.o openssl.o http-ntlm.o
      ../lib/libgnu.a

  Originally written by Hrvoje Niksic <hniksic@xemacs.org>.
  Please send bug reports and questions to <bug-wget@gnu.org>.
Executing: wget -q --timeout=30 -O /tmp/download_filen1hmBh url for admin_menu/7.x
Undefined variable: xml updatexml.inc:475 [1.49 sec, 16.93 MB]                      [notice]
Could not download project status information from                               [error]
(url admin_menu/7.x [1.49 sec, 16.93 MB]
Could not download requested project(s). [1.49 sec, 16.93 MB]                    [error]
Returned from hook drush_pm_download [1.49 sec, 16.93 MB]                            [debug]
Command dispatch complete [1.49 sec, 16.9 MB]                                       [notice]
 Timer  Cum (sec)  Count  Avg (msec)
 page   1.352      1      1351.72
Peak memory usage was 18.55 MB [1.49 sec, 16.91 MB]

```

# Answer
Is `drush status` working?

If so, go to desire path like `sites/all/modules/contrib` & try `drush dl admin_menu`

I think drush expecting higher bootstrap level.

> If drush status it's not working, check your drush installation.
> 0 votes

# Answer
The easiest way to get Postgres working with Drush is to set up a pgpass file in your home directory.

`$ cat $HOME/.pgpass
localhost:5432:*:user:secretpassword`

Replace 'user' with the user account that is calling Drush. That should clear up your problems with sql-cli and pm-enable.

Your problem with pm-download is a separate issue. When I run the command you show above, the key difference in my log output is:

`Executing: wget -q --timeout=30 -O /private/tmp/download_fileoPH7NZ https://updates.drupal.org/release-history/admin_menu/7.x`

Note that your line has "url " where it should say "https://updates.drupal.org/release-history/". Drush gets this information from the option --source. Maybe you have define `$options['source'] = "url";` somewhere in one of your drushrc.php files? If so, take that out, and it should behave correctly again.
> 0 votes

---
Tags: drush
---


# Question
Title: Limit the search to only one content type
I'm trying to setup a search for only one content type; I've tried to google it and I saw so many stuff that I don't know which one to test and as I don't want to install too many modules just to test things. I'm not actually even sure that I have to install something else to achieve that.

Do you have any hint or best implementation example please?

# Answer
These instructions by selvam on KnackForge worked for me. Basically, you can use the `MODULE_search_apachesolr_query_prepare` hook to add a filter to the query before it's run.

```
<?php
function MODULE_search_apachesolr_query_prepare($query) {
  if (/* not correct page */)
    return;
  $compiled_filter = new SolrFilterSubQuery('AND');
  $compiled_filter->addFilter('bundle', 'TARGET_CONTENT_TYPE');
  $query->addFilterSubQuery($compiled_filter);
}

```

I haven't actually tried the hook, but I did use the filter and apply it to a query in a different context (API) and it worked as expected.
> 1 votes

# Answer
If your SOLR server is up and running and connected you can simply uncheck the content types you wish to exclude in the /admin/config/search/apachesolr under the configuration fieldgroup. If you are looking to exclude specific nodes for some reason look at the Apache Solr Exclude Node
> 0 votes

# Answer
Judging by your comment on @chadpeppers answer you might find it useful to use Facet API, it allows you to narrow down your search by content type.

You could probably then write a custom module to provide a block that shows on each content type with a particular facet shown, and you wouldn't have to create separate indexes for all of your content types.
> 0 votes

---
Tags: nodes, search
---


title: Drush Update to a patched module?

text:
# Question
Title: Drush Update to a patched module?
What happen when you `drush up` update a module with Drush because of security issue and the module contain few patches for other features?

The reason why I'm asking is because I have patched few modules and now they have security update which does not contain the features that I wanted.

What is the best practice to update a module that have a security updated and you have patch this module ?

# Answer
The best practice is to find some way to implement your feature that does not require patching the original module. Sometimes this is not possible due to lack of available hooks to provide the functionality that you want.

In these instances, you can try out some of the patch-management solutions, such as bandaid or drush-patchfile, which might help you out here.

Sometimes, though, the changes made in the security update will prevent your patch from applying cleanly; in this case, you have no choice but to re-roll the patch, and figure out what changes need to be made to get it working again. This makes your site maintenance much less convenient, so it's always best to try to work with the module maintainer, and see if you can get your feature added as a standard part of the module, or, failing that, perhaps get the maintainer to add the hooks that would be needed to add in the feature without patching.
> 3 votes

---
Tags: drush, updating, version-control
---


# Question
Title: User can change `Moderation State` on content without having permissions to do so - Workbench
I am using Workbench, Workbench Moderation and Workbench access.

I have a content manager role, who should be able to only create unpublished content, edit content that is flagged as `Needs review` and change the moderation state from `Needs review to Draft`. But as i'm testing the role, the manager can go into the draft and change the moderation state to `published`, or even `needs review`, and I do not have the permissions set for the user to change the moderation state.

At least I think. I've followed a couple tutorials and my site is configured the same, but when they go to change the moderation state their drop down select list only has the options they specified, while mine has all states available regardless of permissions.

I've tested back and forth between the roles and there is differences in the permissions and what each user role can do, but I can't set the role to allow users to moderate specific state transitions.

I literally can turn off all workbench moderate state permissions and they still have access to change the moderation state to anything they want.

As you can see in the bottom right hand corner of the image, the permissions for `Moderate all content from ___ to ____` is turned off for my content manager role, and I still have permissions to moderate all content from either state. If i sign is as the `reviewer` role, I can also turn off all permissions and still be able to moderate the content and change the states without permissions.

No I do not have another role enabled for this user, I have cleared every cache and used different machines, same issue.

My questions are:

**if I have a setting on that allow the user to moderate the states of content, what is it?**

**If I do not have the correct permissions enabled, what should I do to correct it?**

**If the issue does not lie within the workbench permissions then what should I be looking for?**

Thank you regardless.

# Answer
> 0 votes
in order to display the moderation states i wanted for a specific role I had to make sure `Administer Workbench Moderation` and `Bypass Moderation restrictions` were turned off.

---
Tags: users, workbench
---


title: Update payment method pane with ajax

text:
# Question
Title: Update payment method pane with ajax
I have the coupon pane, the order review and the payment info panes all on the same checkout page. When I add a coupon, an ajax callback is fired and the order summary is automatically updated to reflect the coupon, but the payment info pane is not updated.

I have a rule for two payment methods. One for non-zero order totals, and one for zero total orders. If I add a coupon that brings the total to zero, and then refresh the whole page, the rule action does apply and enab;es my 'free' payment method. However, it only works with a full refresh.

Is there a way to get the payment info pane to refresh during the coupon add ajax callback?

Otherwise, my customers see a zero total and they still see the payment info that requires them to put in a credit card to finish the order.

# Answer
You may need to trigger a page refresh from the ajax? I'm not entirely sure if you would be able to load the individual pane.
> 0 votes

---
Tags: commerce, ajax
---


# Question
Title: Permission base on the administration menu?
I have used hook\_permission to limit user for some places and to created a permission rule. However, I have not combine two permission from another modules for my custom module.

I'm working on a module that would allow user to used the Administration Menu when user are on a Desktop and used the Mobile Friendly Navigation Toolbar when the user is on a mobile.

I'm using the hook\_page\_build to hide the css from mobile or desktop display.

So now I'm trying to limited the hook\_page\_build to user that only have access to the Administration Menu and the Mobile Friendly Navigation Toolbar.

To be more specific here is the permission that I want user to have enable before this module is been load.

Access administration menu

And the another permission that user need to have is Use the administration navbar.

Once these two permission have been granted the my custom module is going to be able load. How can I do this ?

# Answer
> 0 votes
I found the solution here is how is done....

```
function my_custom_module_page_build(&$page) {

    // Check if user have access to the administration menu
    if (!user_access('access administration menu')) return false;

    // Check if user have access to navbar.
    if (!user_access('access navbar')) return false;

     drupal_add_css(drupal_get_path('module', 'my_custom_module') . '/css/mobile.css');

}

```

---
Tags: routes, users, toolbar
---


# Question
Title: After Creating A new User inside RULES, I can not access to UID
In my rule, I have an action that is "create new entity" with "user" bundle.

every thing works fine a new user create with provided information (user and email)

it's variable name is **new\_user**

in next action, I unblock the **new user** and it works correctly.

but in next action when I tried to debug "new user" via devel action, It seems it doesn't collect the information of new user

I have attached the devel result. I see no UID and no other information from new user. Also send welcome messages actions don't work and no email is sent to new created user.

Please tell me what my mistakes are.

Thanks a lot

# Answer
> 2 votes
Use the action to save the entity. The user only gets the UID when saved, not when created.

---
Tags: rules, users
---


# Question
Title: Is it possible to disable CSS and Javascript aggregation by role?
Is it possible to disable CSS and Javascript aggregation by role?

That way during content editiong or administration stages the user is not affected and can check the CSS alright, while end users received cache values as usual. If the cache lifetimes are long enough the editing can be completed before it any changes interfere with the other users.

# Answer
To do exactly what you want; using hook\_css\_alter & hook\_js\_alter is how to do it. Set the preprocess key to FALSE for everything.

For an out of the box solution that is fairly close to what you want https://www.drupal.org/project/advagg/ can do it. Give that role the "bypass advanced aggregation" permission and then they can add `?advagg=-1` to the end of the URL to see the change.

Will also mention that using a dev environment when altering css/js is ideal.
> 2 votes

---
Tags: users, css-js-aggregation
---


# Question
Title: Autocalculated price field depending on language
I need field for my own content type that will show price in currency depending on chosen language (from i18n module) calculated by currency exchange rate from currency module.

I've installed money field, but how to connect this to currency exchange?

I need some advice. I'm newbie.

Thanks for any hints, maybe I try to go wrong way?

# Answer
Ok, I managed that with computed field. Money field was not needed.

In computed field I've posted code:

```
 $exchange_rate = CurrencyExchanger::load('PLN', 'EUR');
 $netto_price = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_name')));
 $entity_field[0]['value'] = bcmul($exchange_rate, $netto_price, 2);

```

It calculates currency in fly from currency module.
> 0 votes

---
Tags: entities
---


# Question
Title: How do I set the fixed amount of values to 11?
I'm setting up a field with multiple values. The maximum fixed amount of values I can configure is 10.

If I want more I have to set this to unlimited.

Is there a way tho set the fixed amount of values on a field to 11 values?

# Answer
> 20 votes
The cardinality options are hard-coded into the `field_ui_field_edit_form()` function using these lines of code:

```
$form['field']['cardinality'] = array(
  '#type' => 'select',
  '#title' => t('Number of values'),
  '#options' => array(FIELD_CARDINALITY_UNLIMITED => t('Unlimited')) + drupal_map_assoc(range(1, 10)),
  '#default_value' => $field['cardinality'],
  '#description' => $description,
);

```

It's the `drupal_map_assoc(range(1, 10))` line which is limiting the number to 10.

It doesn't seem that the maximum cardinality is validated (or further limited) anywhere else, though (at least not by core), so it would be pretty easy to offer more options for that value using a form alter hook:

```
function MYMODULE_form_field_ui_field_edit_form_alter(&$form, &$form_state, $form_id) {
  // Increase the max cardinality to 20
  $range = drupal_map_assoc(range(1, 20));
  $new_options =  array(FIELD_CARDINALITY_UNLIMITED => t('Unlimited')) + $range;

  // Change the options
  $form['field']['cardinality']['#options'] = $new_options;
}

```

I've just tried this out and it seems to have no side-effects at all. The field system respects any cardinality you set that's higher than 10, and saves it without problem when you edit the field in the admin UI.

# Answer
> 0 votes
I've used this sandbox project to solve the same issue: https://www.drupal.org/sandbox/ydahi/2421885

It provides a UI to set the range for the number of values.

---
Tags: 7, entities
---


# Question
Title: How can I increase the number of allowed values on an image field?
I need to increase the allowed number of image uploads to 15. Is there anyway to do this in a module or other means without hacking core files as suggested here - http://drupal.org/node/680546#comment-4126378?

This is Drupal 7.

Thanks, Tim

# Answer
You could also change the cardinality setting of your field instance without doing a direct query. The key function would be field\_update\_instance() and here is an example of how to modify your field: http://sivaji.drupalgardens.com/how-programmatically-change-field-instance-properties
> 2 votes

# Answer
You can simply change the cardinality of the field in field\_config table:

```
UPDATE field_config SET cardinality = 15 WHERE field_name = 'field_my_field_name'

```

Afterwards, clear your cache.
> 1 votes

# Answer
With a simple form alter you can allow arbitrary high cardinality settings. See this answer

.
> 0 votes

# Answer
You can do this fairly simply using hook\_form\_alter. Check out the code here:

https://www.drupal.org/sandbox/ydahi/2421885

```
/**
* Using hook_form_alter to change the field cardinality.
*/
function custom_number_of_values_form_alter(&$form, &$form_state, $form_id) {
// Set the range using the user supplied values.
$lowerlimit = variable_get('custom_number_of_values_minimum', '1');
$upperlimit = variable_get('custom_number_of_values_maximum', '20');
$range = drupal_map_assoc(range($lowerlimit, $upperlimit));
$new_options = array(FIELD_CARDINALITY_UNLIMITED => t('Unlimited')) + $range;
// Change the options.
$form['field']['cardinality']['#options'] = $new_options;
}

```
> 0 votes

---
Tags: entities
---


title: Issues with Zen subtheme

text:
# Question
Title: Issues with Zen subtheme
I am running a Zen subtheme for another drupal instance and it all worked fine. However, when I copied the folders across to my new Drupal instance, all I see is

The name of the site and

User menu :

```
My account
Log out

```

There is no Add content link... or the administration menu along the top... also no styles are applied... I am pretty sure I changed all the site specific instances in the code (.info file etc)... What am I doing wrong?

Ok, so I can navigate through the admin menu by changing the url path... admin/appearance

I have cleared the cache, but the styles for the zen sub theme are still not being picked up and I cannot see the Add Content link on the front page.

I've tried changing the theme to Bartik, and it looks fine. The styles are being picked up and everything.

So why is it not working for the Zen subtheme?

In the logs, I am seeing this message:

> Notice: Undefined property: stdClass::$prefix in system\_theme\_settings() (line 547 of /home/mysite/public\_html/modules/system/system.admin.inc).

Does this explain the wsod problem?

# Answer
You need to copy over The Zen theme as well, A sub-theme requires both the sub theme and its parent theme in order for it to work
> 0 votes

# Answer
These are the steps you need to follow to use zen sub theme.

1. Download the zen theme from https://www.drupal.org/project/zen and extract the zip file in to your "\`sitename/sites/all/themes/"

now your theme folder will look like `"sitename/sites/all/themes/zen"` you zen base theme.

2. move inside zen theme folder you will find `STATRETKIT` folder that is the sub theme you need to inherit, just copy that folder and paste it out site the folder

now in your themes folder you have two folder "zen" and "`STATRETKIT`" -\> rename the folder to your desired theme name. lets say "`samplesite`"

3. modify your info file name to "samplesite.info" please check if the file format is in `.info` or text file because in `starterkit` the info file is text you need to change the extention by saving it as info file.
4. modify and `create your css and js file`s as specified in the info file.

and if you have old site you want to copy that themes here dont copy full theme files here only replace the css and js file and your template.php and template folder alone.

5. clear the cache in configuration -\> performance . and check if its working.

if you have any issues still read this https://www.drupal.org/node/873778 installing zen

https://www.drupal.org/node/1549668 subtheme steps

Note: Always read the README.txt file for all modules and themes installation will help you install easily and understand quickly.

hope these steps will help
> 0 votes

---
Tags: theming
---


title: Alternate title replacing Product Title

text:
# Question
Title: Alternate title replacing Product Title
This is a combobox showing a group of product referenced.

I have created an extra field in product list, short\_title. How do I replace the Product Title with short\_title? i.e. Chicken, Turkey, Pork, … Is this possible?

I’ve also tried Inline Form Entity. The YouTube tutorial: http://youtu.be/glRM\_NzNVTA?t=5m3s : When the host edited the Variation Title, the Product Title remained unchanged. However, when I do it, the Product Title changed. Is this by design or the host was using an older version of Inline Entity Form?

I know that we can create attributes, but having a variety of product types complicates the form. All I wanted: one product type and just reference a group of product in product display.

The Product Title is too long in combo, but I can't shortened that because it's important as line-item title.

Any idea or workaround?

# Answer
> 0 votes
Instead of 'simple' selection, use a view for your entity reference. Here you can decide yourself how the title is shown.

---
Tags: commerce, entities
---


# Question
Title: Why doesn't $query->hasTag() work with this view?
Below I have a View. I have the following hook. I'm hoping to modify the WHERE clause of the view, but the following code seems not to be called.

```
function jch_utilities_query_alter(QueryAlterableInterface $the_query) {
  if ($the_query->hasTag('jch')) {
    dsm('Found it!');
    dsm($the_query);
  }
}

```

I wanted to use `hook_views_query_alter()` but I read that it doesn't work with indexed content. So I was trying this. I also couldn't get Views PHP to work (bug with `$row`).

I just want a way to modify `$query->where` and I keep getting blocked at every turn. Any suggestions?

```
$view = new view();
$view->name = 'collection_products';
$view->description = '';
$view->tag = 'jch';
$view->base_table = 'search_api_index_product_display';
$view->human_name = 'Collection products';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = '%1';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'list';
$handler->display->display_options['style_options']['grouping'] = array(
  0 => array(
    'field' => 'name',
    'rendered' => 1,
    'rendered_strip' => 0,
  ),
);
$handler->display->display_options['style_options']['class'] = 'products-per-collection';
$handler->display->display_options['row_plugin'] = 'fields';
/* Header: Global: View area */
$handler->display->display_options['header']['view']['id'] = 'view';
$handler->display->display_options['header']['view']['table'] = 'views';
$handler->display->display_options['header']['view']['field'] = 'view';
$handler->display->display_options['header']['view']['view_to_insert'] = 'collection_products:block_1';
$handler->display->display_options['header']['view']['inherit_arguments'] = TRUE;
/* Relationship: Category */
$handler->display->display_options['relationships']['field_category']['id'] = 'field_category';
$handler->display->display_options['relationships']['field_category']['table'] = 'search_api_index_product_display';
$handler->display->display_options['relationships']['field_category']['field'] = 'field_category';
$handler->display->display_options['relationships']['field_category']['ui_name'] = 'Category';
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'entity_taxonomy_term';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'field_category';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['exclude'] = TRUE;
$handler->display->display_options['fields']['name']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['name']['link_to_entity'] = 0;
/* Field: Content: Rendered Content */
$handler->display->display_options['fields']['rendered_entity']['id'] = 'rendered_entity';
$handler->display->display_options['fields']['rendered_entity']['table'] = 'views_entity_node';
$handler->display->display_options['fields']['rendered_entity']['field'] = 'rendered_entity';
$handler->display->display_options['fields']['rendered_entity']['label'] = '';
$handler->display->display_options['fields']['rendered_entity']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['rendered_entity']['link_to_entity'] = 1;
$handler->display->display_options['fields']['rendered_entity']['display'] = 'view';
$handler->display->display_options['fields']['rendered_entity']['view_mode'] = 'product_list';
/* Sort criterion: Category: Search Rank (indexed) */
$handler->display->display_options['sorts']['field_category_field_search_rank']['id'] = 'field_category_field_search_rank';
$handler->display->display_options['sorts']['field_category_field_search_rank']['table'] = 'search_api_index_product_display';
$handler->display->display_options['sorts']['field_category_field_search_rank']['field'] = 'field_category_field_search_rank';
/* Contextual filter: Indexed Content: Collection */
$handler->display->display_options['arguments']['field_collection']['id'] = 'field_collection';
$handler->display->display_options['arguments']['field_collection']['table'] = 'search_api_index_product_display';
$handler->display->display_options['arguments']['field_collection']['field'] = 'field_collection';
$handler->display->display_options['arguments']['field_collection']['default_action'] = 'not found';
$handler->display->display_options['arguments']['field_collection']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['field_collection']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['field_collection']['summary_options']['grouping'] = array(
  0 => array(
    'field' => 'name',
    'rendered' => 1,
    'rendered_strip' => 0,
  ),
);
$handler->display->display_options['arguments']['field_collection']['specify_validation'] = TRUE;
$handler->display->display_options['arguments']['field_collection']['validate']['type'] = 'taxonomy_term';
$handler->display->display_options['arguments']['field_collection']['validate_options']['vocabularies'] = array(
  'collection' => 'collection',
);
$handler->display->display_options['arguments']['field_collection']['break_phrase'] = 0;
/* Filter criterion: Indexed Content: Status */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'search_api_index_product_display';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = array(
  1 => '1',
);
$handler->display->display_options['filters']['status']['group'] = 1;
/* Filter criterion: Indexed Content: Content type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'search_api_index_product_display';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'bags_cases' => 'bags_cases',
  'basic_products' => 'basic_products',
);
$handler->display->display_options['filters']['type']['group'] = 1;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['defaults']['title'] = FALSE;
$handler->display->display_options['title'] = '%1';
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name_1']['id'] = 'name_1';
$handler->display->display_options['fields']['name_1']['table'] = 'entity_taxonomy_term';
$handler->display->display_options['fields']['name_1']['field'] = 'name';
$handler->display->display_options['fields']['name_1']['relationship'] = 'field_category';
$handler->display->display_options['fields']['name_1']['label'] = '';
$handler->display->display_options['fields']['name_1']['exclude'] = TRUE;
$handler->display->display_options['fields']['name_1']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['name_1']['link_to_entity'] = 0;
$handler->display->display_options['fields']['name_1']['replace_spaces'] = TRUE;
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'entity_taxonomy_term';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'field_category';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['exclude'] = TRUE;
$handler->display->display_options['fields']['name']['alter']['alter_text'] = TRUE;
$handler->display->display_options['fields']['name']['alter']['text'] = '<span id="[name_1]"></span><div class="collection"><a>[name]</a></div>';
$handler->display->display_options['fields']['name']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['name']['link_to_entity'] = 0;
/* Field: Content: Rendered Content */
$handler->display->display_options['fields']['rendered_entity']['id'] = 'rendered_entity';
$handler->display->display_options['fields']['rendered_entity']['table'] = 'views_entity_node';
$handler->display->display_options['fields']['rendered_entity']['field'] = 'rendered_entity';
$handler->display->display_options['fields']['rendered_entity']['label'] = '';
$handler->display->display_options['fields']['rendered_entity']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['rendered_entity']['link_to_entity'] = 0;
$handler->display->display_options['fields']['rendered_entity']['display'] = 'view';
$handler->display->display_options['fields']['rendered_entity']['view_mode'] = 'product_list';
/* Field: Collection: Description (indexed) */
$handler->display->display_options['fields']['field_collection_description']['id'] = 'field_collection_description';
$handler->display->display_options['fields']['field_collection_description']['table'] = 'search_api_index_product_display';
$handler->display->display_options['fields']['field_collection_description']['field'] = 'field_collection_description';
$handler->display->display_options['fields']['field_collection_description']['label'] = '';
$handler->display->display_options['fields']['field_collection_description']['exclude'] = TRUE;
$handler->display->display_options['fields']['field_collection_description']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_collection_description']['link_to_entity'] = 0;
/* Field: Category: Search Rank (indexed) */
$handler->display->display_options['fields']['field_category_field_search_rank']['id'] = 'field_category_field_search_rank';
$handler->display->display_options['fields']['field_category_field_search_rank']['table'] = 'search_api_index_product_display';
$handler->display->display_options['fields']['field_category_field_search_rank']['field'] = 'field_category_field_search_rank';
$handler->display->display_options['fields']['field_category_field_search_rank']['label'] = '';
$handler->display->display_options['fields']['field_category_field_search_rank']['exclude'] = TRUE;
$handler->display->display_options['fields']['field_category_field_search_rank']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_category_field_search_rank']['settings'] = array(
  'thousand_separator' => ' ',
  'prefix_suffix' => 1,
);
/* Field: Indexed Content: Collection */
$handler->display->display_options['fields']['field_collection']['id'] = 'field_collection';
$handler->display->display_options['fields']['field_collection']['table'] = 'search_api_index_product_display';
$handler->display->display_options['fields']['field_collection']['field'] = 'field_collection';
$handler->display->display_options['fields']['field_collection']['label'] = '';
$handler->display->display_options['fields']['field_collection']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_collection']['link_to_entity'] = 0;
$handler->display->display_options['fields']['field_collection']['display'] = 'id';
$handler->display->display_options['fields']['field_collection']['view_mode'] = 'full';
$handler->display->display_options['fields']['field_collection']['bypass_access'] = 0;
$handler->display->display_options['defaults']['filter_groups'] = FALSE;
$handler->display->display_options['defaults']['filters'] = FALSE;
/* Filter criterion: Indexed Content: Status */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'search_api_index_product_display';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = array(
  1 => '1',
);
$handler->display->display_options['filters']['status']['group'] = 1;
/* Filter criterion: Indexed Content: Content type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'search_api_index_product_display';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'bags_cases' => 'bags_cases',
  'basic_products' => 'basic_products',
);
$handler->display->display_options['filters']['type']['group'] = 1;
$handler->display->display_options['path'] = 'collection/%';

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block_1');
$handler->display->display_options['defaults']['title'] = FALSE;
$handler->display->display_options['defaults']['css_class'] = FALSE;
$handler->display->display_options['css_class'] = 'collection-terms';
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'list';
$handler->display->display_options['style_options']['grouping'] = array(
  0 => array(
    'field' => 'name_1',
    'rendered' => 0,
    'rendered_strip' => 1,
  ),
);
$handler->display->display_options['style_options']['default_row_class'] = FALSE;
$handler->display->display_options['style_options']['row_class_special'] = FALSE;
$handler->display->display_options['style_options']['class'] = 'head-test';
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['row_plugin'] = 'fields';
$handler->display->display_options['defaults']['row_options'] = FALSE;
$handler->display->display_options['defaults']['header'] = FALSE;
/* Header: Global: Text area */
$handler->display->display_options['header']['area']['id'] = 'area';
$handler->display->display_options['header']['area']['table'] = 'views';
$handler->display->display_options['header']['area']['field'] = 'area';
$handler->display->display_options['header']['area']['content'] = '<h2>On This Page</h2>';
$handler->display->display_options['header']['area']['format'] = 'full_html';
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'entity_taxonomy_term';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'field_category';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['exclude'] = TRUE;
$handler->display->display_options['fields']['name']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['name']['link_to_entity'] = 0;
$handler->display->display_options['fields']['name']['replace_spaces'] = TRUE;
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name_1']['id'] = 'name_1';
$handler->display->display_options['fields']['name_1']['table'] = 'entity_taxonomy_term';
$handler->display->display_options['fields']['name_1']['field'] = 'name';
$handler->display->display_options['fields']['name_1']['relationship'] = 'field_category';
$handler->display->display_options['fields']['name_1']['label'] = '';
$handler->display->display_options['fields']['name_1']['exclude'] = TRUE;
$handler->display->display_options['fields']['name_1']['alter']['alter_text'] = TRUE;
$handler->display->display_options['fields']['name_1']['alter']['text'] = '<a href="#[name]">[name_1]</a>';
$handler->display->display_options['fields']['name_1']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['name_1']['link_to_entity'] = 0;
/* Field: Global: Custom text */
$handler->display->display_options['fields']['nothing']['id'] = 'nothing';
$handler->display->display_options['fields']['nothing']['table'] = 'views';
$handler->display->display_options['fields']['nothing']['field'] = 'nothing';
$handler->display->display_options['fields']['nothing']['label'] = '';
$handler->display->display_options['fields']['nothing']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['nothing']['hide_empty'] = TRUE;
/* Field: Collection: Description (indexed) */
$handler->display->display_options['fields']['field_collection_description']['id'] = 'field_collection_description';
$handler->display->display_options['fields']['field_collection_description']['table'] = 'search_api_index_product_display';
$handler->display->display_options['fields']['field_collection_description']['field'] = 'field_collection_description';
$handler->display->display_options['fields']['field_collection_description']['label'] = '';
$handler->display->display_options['fields']['field_collection_description']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_collection_description']['link_to_entity'] = 0;
/* Field: Category: Search Rank (indexed) */
$handler->display->display_options['fields']['field_category_field_search_rank']['id'] = 'field_category_field_search_rank';
$handler->display->display_options['fields']['field_category_field_search_rank']['table'] = 'search_api_index_product_display';
$handler->display->display_options['fields']['field_category_field_search_rank']['field'] = 'field_category_field_search_rank';
$handler->display->display_options['fields']['field_category_field_search_rank']['label'] = '';
$handler->display->display_options['fields']['field_category_field_search_rank']['exclude'] = TRUE;
$handler->display->display_options['fields']['field_category_field_search_rank']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_category_field_search_rank']['settings'] = array(
  'thousand_separator' => '',
  'prefix_suffix' => 1,
);
$translatables['collection_products'] = array(
  t('Master'),
  t('%1'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Category'),
  t('All'),
  t('Page'),
  t('<span id="[name_1]"></span><div class="collection"><a>[name]</a></div>'),
  t('Block'),
  t('<h2>On This Page</h2>'),
  t('<a href="#[name]">[name_1]</a>'),
);

```

# Answer
> 0 votes
I've never used tag but it should work, name works and that's usually where I change mine.

```
/**
 * Implements hook_views_query_alter().
 */
function MODULENAME_views_query_alter(&$view, &$query) {
  // Alter query for 'OR'.
  if ($view->name === 'VIEW_NAME') {
    $query->where[0]['type'] = 'OR';
  }
}

```

For reference: hook\_views\_query\_alter()

**edit**

I guess I should have read closer, the view is integrated with search API. So you have to use hook\_search\_api\_query\_alter() I believe.

```
function hook_search_api_query_alter(SearchApiQueryInterface $query) {
  $info = entity_get_info($index->item_type);
  $query->condition($info['entity keys']['id'], 0, '!=');
}

```

More info

---
Tags: 7, views, commerce, database
---


# Question
Title: passing a user id to user_is_logged_in function
I want to use the user\_is\_logged\_in function to determine if a user is logged in but i want to determine if that user is logged in from a cron job/ module.

Essentially i have an array of user id's that i want to loop through to see if the corresponding user is logged in and if so execute some code.

My question is how does one pass an integer to the function to get a true or false from the function? all examples i have seen use the function on a page where the user is viewing to show them content or send message to them. Nothing i can see shows how to use it from a script.

Hope this makes sense.

Madmilner

# Answer
If you look at the docs you'll see the function comment:

> Determines if the **current user** is logged in.

Emphasis mine.

So the function simply isn't supposed to do what you want to use it for, you'll need to write something custom

It's pretty easy though, see Get all logged in users in Drupal for some inspiration.
> 0 votes

---
Tags: 7, users
---


# Question
Title: How to show contextual links buttons in templates with minimal markup?
I want to get rid of the most markup in Drupal 8 templates, but still want to have working contextual links. How to do this?

# Answer
In Drupal 8 the contextual links markup is still printed via the {{ title\_suffix }} variable (D7: print render($title\_suffix);).

block.html.twig (default):

```
{%
  set classes = [
    'block',
    'block-' ~ configuration.provider|clean_class,
  ]
%}
<div{{ attributes.addClass(classes) }}>
  {{ title_prefix }}
  {% if label %}
    <h2{{ title_attributes }}>{{ label }}</h2>
  {% endif %}
  {{ title_suffix }}
  {% block content %}
    {{ content }}
  {% endblock %}
</div>

```

So a minimal version would still work:

```
{{ title_suffix }}
{{ content) }}

```

Printed result for user without the permission "Use contextual links"

```
<div data-contextual-id="block:block=foo:|block_content:block_content=1:changed=1423224125"></div>
BlaBlaBlaContent

```

Printed result for user with the permission "Use contextual links"

```
<div data-contextual-id="block:block=foo:|block_content:block_content=1:changed=1423224125" class="contextual-render-processed contextual" role="form">
    <button type="button" class="trigger focusable visually-hidden" aria-pressed="false">Open configuration options</button>
    <ul hidden="" class="contextual-links">
        <li class="block-configure"><a href="/admin/structure/block/manage/foo?destination=node/4">Configure block</a></li>
        <li class="block-contentblock-edit"><a href="/block/4?destination=node/4">Edit</a></li>
        <li class="block-contentblock-delete"><a href="/block/4/delete?destination=node/4">Delete</a></li>
    </ul>
</div>
BlaBlaBlaContent

```

The default formatting will be destroyed because the outer class .contextual-region is missing and it's defined like this in contextual.theme.css:

```
.contextual-region .contextual .contextual-links {...}
.contextual-region .contextual .contextual-links li {...}
...

```

So you have to overwrite (https://www.drupal.org/node/1876600) this file or copy the definitions in one of your theme css files and change for example like:

```
.contextual-region .contextual .contextual-links, .contextual .contextual-links {...}
.contextual-region .contextual .contextual-links li, .contextual .contextual-links li {...}

```

Or you place manually in the template or via JS ".contextual-region" into an outer dom element or print {{ attributes }} there.

Printed result:

```
<div class="block block--classic contextual-region">
    <div data-contextual-id="block:block=foo:|block_content:block_content=5:changed=1423308445" class="contextual-render-processed contextual" role="form">
        <button type="button" class="trigger focusable" aria-pressed="false">Open configuration options</button>
        <ul hidden="" class="contextual-links">
            <li class="block-configure"><a href="/admin/structure/block/manage/callforproposalsblock?destination=node/4">Configure block</a></li><li class="block-contentblock-edit"><a href="/block/5?destination=node/4">Edit</a></li>
            <li class="block-contentblock-delete"><a href="/block/5/delete?destination=node/4">Delete</a></li>
        </ul>
    </div>
    BlaBlaBlaContent
</div>

```

Remark: Without the upper .contextual-region the mouseover visibility of the contextual links icon is not working ...

Note: Current version of Drupal 8 is Beta 6 - so things may still change!
> 11 votes

---
Tags: 8, navigation
---


title: Hide html / code based on content type

text:
# Question
Title: Hide html / code based on content type
I'm using a block of code that shouldn't be displayed on certain content types (not blocks, but actual code). When I use this approach, I'm getting *undefined variable* and *trying to get property of non-object* errors:

```
<?php
    if(function_exists('views_get_page_view') && views_get_page_view() ||  arg(0) == 'user') {
      $showpage = "yes";
    }
?>

<?php if (((!empty($node)) || (!empty($showpage))) && (($node->type != 'article') && ($node->type != 'basic_page'))): ?>

(Show all this)

<?php endif; ?>

```

It's the check if the visitor is on a user related page that causes the errors, but I have no idea how to fix this. Can someone help me out?

# Answer
The intention of this all is to hide the main-container div on those content types. The setup I was trying was actually a bit looked too far. In fact, other pages that weren't nodes, but no views pages either (user, 404, sent-pages, module-related pages, ...) got trapped in the hidden container as well.

By breaking up the conditions (thanks for the tip @calebtr), I came up with this working solution:

```
<?php if ((!empty($node) && in_array($node->type, array('article', basic_page')))): ?>

  (Nothingness)

  <?php else: ?>

  (Show all content)

<?php endif; ?>

```

I'm having no "undefined" errors so far.
> 0 votes

# Answer
`$node` isn't available on user pages. But when `$showpage` is set, you are checking a property on the `$node` object. This gets the two errors you are describing.

I'm not sure what you are trying to do but you can troubleshoot by breaking out your booleans. I find it helpful to break logic onto multiple lines whenever possible, so that other people (and I) can read it later.

From:

```
if (((!empty($node)) || (!empty($showpage))) && (($node->type != 'article') && ($node->type != 'basic_page'))):

```

To:

```
if (!empty($node) || !empty($showpage)) {
  if ($node->type != 'article' && $node->type !='basic_page') {
    // do that stuff
  }
}

```

So - when `$showpage` is not empty but `$node` is, as on a user page, $node is undefined.

I'm not exactly sure what you are trying to do but I think it is along the lines of "show this stuff on node pages that are not basic page and not article, or when the $showpage variable is present.

In which case:

```
if ((!empty($node) && !in_array($node->type, array('article', 'basic_page'))) || !empty($showpage))

```

Or more readably,

```
if(function_exists('views_get_page_view') && views_get_page_view() ||  arg(0) == 'user') {
  $showpage = 'yes';
}
elseif (!empty($node) && !in_array($node->type, array('article', 'basic_page'))) {
  $showpage = 'yes';
}

if (!empty($showpage)) {
  // do that stuff
}

```

It isn't a one-liner, but the longer code is easier to read, troubleshoot, and prevent errors.
> 1 votes

# Answer
The easiest way to find the user is in user page or not is as follows

```
$ARG0 = arg(0);
$ARG1 = arg(1);
if($ARG0 == "user" && is_numeric($ARG1) ){
echo "user page";
}else{
echo "not user page";
}

```

Check this link if any queries

How to check if this page is user Profile Page
> 0 votes

---
Tags: theming, users
---


# Question
Title: Does the Full HTML format allow all tags, and is there an Input Filter without built-in restrictions?
Does the *Full HTML* format allow all tags, without any restrictions at all? I am not quite sure, but it seems some input filters have other restrictions in addition to what their options dialogs allow.

# Answer
> 2 votes
I believe that Full Html by default allows all tags (hence the name). To see how yours is currently setup, go to /admin/config/content/formats/full\_html. Under Enabled Filters, see if you have "Limit Allowed HTML Tags" checked. If you do, you will also have a vertical tab at the bottom of the form labeled "Limit Allowed HTML Tags", on which you can configure which tags are enabled.

If you want to add your own format, you can do so on /admin/config/content/formats and configure it however you would like.

---
Tags: 7, input-formats
---


# Question
Title: Media module is bring contextual links with it into the middle of WYSIWYG content - how to remove?
Is there anyway to remove these links from the output of the media module? I suspect that they're responsible for breaking the link tag I have wrapped around the Media image in the WYSIWYG editor.

On the rendered template of the page this looks like

How can I prevent these links from being embedded by the media module? They even appear to show when I am not logged into the Drupal administration too.

# Answer
I posted this as an issue on the media\_wysiwyg module bug tracker over at https://www.drupal.org/node/2357993 and have been working my way through it since. Here is the best result I have managed to achieve so far copied from my responses to that issue.

---

This issue is mostly caused by the file\_entity module. To work round this I have restricted the view modes available to media\_wysiwyg in /admin/config/media/wysiwyg-view-mode. I have set images to only allow the WYSIWYG view mode like so:

I have then created an override template for the file entity called `file--image--wysiwyg.tpl.php` (see https://www.drupal.org/node/1793548) and I have the following code in it:

```
<?php

hide($content['links']);
print render($content);

```

This has now removed all the annoying links, headers and wrapping `<div>`s from the output EXCEPT for the media\_wysiwyg wrapping  mentioned in comment #4.

As this is just one wrapping `<div>` and the page is HTML this now no longer breaks the link, but it would still be preferable to be able to remove this annoying wrapping `<div>`.
> 0 votes

# Answer
You'll have to change the sort order of filtering within your text format, admin/config/content/formats/full\_html (for Full HTML text format). Just place the "Convert media tags into markup" before the "CKeditor Link filter".
> 1 votes

# Answer
There is a patch here https://www.drupal.org/node/2401811

This behavior is a regression introduced by another patch that may well get rolled back.
> 1 votes

---
Tags: media, navigation
---


# Question
Title: How can I implement a required disclaimer page?
Whenever a user enters the site I would like a page with a disclaimer to appear, and only when you agree to the conditions can you enter the site.

What can I use to do this?

# Answer
I'm assuming that once someone "Agrees" to your terms, you do not want them to have to agree on subsequent visits?

I'd like to recommend a forced registration. You can restrict the contents of your website to authenticated users only. To do this - go to admin/people/permissions and uncheck all permissions for anonymous users.

If you do not want to mess with site permissions, you can check out a great module: https://www.drupal.org/project/anonymous\_login Anonymous Login will redirect anonymous users to the login page whenever they reach any admin-specified page paths.

Then I would customize your user registration process accordingly. Make it as lightweight as you want. I would check out the Site Disclaimer module to add your site terms functionality: https://www.drupal.org/project/site\_disclaimer

Also - if you're looking for a quick way to make the login/registration pages nicer - check out the "Better Login" module.

Depending on your version of Drupal - check out the "Agreement" module. The Agreement module allows the administrator to present a text-based agreement (think "Terms of Service") that users of a particular role must accept before they are allowed to access the site.

Let me know if you would like more clarification. I hope this helps put you in the right direction, but you didn't provide much background info for me to help. (i.e what have you done so far, etc).

-Wrench
> 2 votes

---
Tags: 7
---


title: Hide page title on specific path

text:
# Question
Title: Hide page title on specific path
I want to hide page title on a specific path, but I want to retain the page title between "title" tags in the header. I want the title to be exist in title bar of the browser, but that should not be displayed in the page for specific paths.

Is that could be done using `theme_preprocess_page` Or any other specific hooks out there ?

Is there any module?

What else could be done to prevent page title from displaying on the page in specific paths?

# Answer
There are a number of ways to do this, but this answer focuses on the considerations for handling things programmatically in custom code.

The `<title>` variable (for the browser title bar) is calculated as part of the "html" theme template, while the `<h1>` title variable (printed at the top of the page) is calculated as part of the "page" theme template. So in this regard if you implement some preprocess logic on the "page" output, you can remove the title from the page display while still keeping it intact for the browser bar. This is of course in contrast to more heavy-handed approaches, like calling `drupal_set_title()`, which impact static variables that may apply on a more global scope.

The trick to this is that, in most cases, your "page" template title is not actually initiated as a theme variable until template\_process\_page(), which runs **after** any preprocess functions. So you may not see a "title" variable within the scope of your own theme\_preprocess\_page(). The appropriate snippet from template\_process\_page(), where the title is added, is just:

```
if (!isset($variables['title'])) {
  $variables['title'] = drupal_get_title();
}

```

Given this background, you could manipulate the title variable direct by either:

1. Setting $variables\['title'\] to an empty string within your theme\_preprocess\_page() (based on whatever conditions your desire). This way it will be set and therefore won't get filled-in via the template\_process\_page() code that runs later, but it will still be empty when page.tpl.php template renders things.
2. Implementing a theme\_process\_page() function, which will run after template\_process\_page(), that unsets/nullifies the title variable set there.

You could also avoid touching the title variable itself altogether by just setting a boolean flag, like $show\_title, in a (pre)process function. Then you would need to modify your page.tpl.php template with a **very** basic boolean check of $show\_title that only prints the title `<h1>` if TRUE. That method is discussed in this post.

With any of these options you isolate your primary conditional logic, which can be as detailed as you want (should you discover new title visibility needs later), within the theme preprocessing layer. This will help keep things more maintainable for the long run.
> 2 votes

# Answer
I recommend checking out the "Exclude Node Title" module. https://www.drupal.org/project/exclude\_node\_title

I think it can do exactly what you're asking. -Wrench
> 1 votes

# Answer
I suggest you another way, in your `page.tpl.php` do something like this

```
<h2 class="node_title"><span class="node-page-title">
<?php
if(current_path()!='yourpath'){ // or any condtion you want
 print $title;
}
?>
</span></div></h2>

```
> 0 votes

---
Tags: theming, 7
---


title: Field template not being rendered

text:
# Question
Title: Field template not being rendered
On our company website we have a people page which amongst others has an image field called 'field\_photo'

This is being rendered using the following:

```
<?php print render($content['field_photo']); ?>

```

However I need to be able to add some attributes to the img tag outputted, to do this I figured I would have to use a custom template and add in the required bits like so:

```
$item['#item']['attributes']['class'] = 'photo';

```

Problem I am having is no matter what I do, I don't seem to be able to get this to work no matter what I name the template (eg field--field\_photo--image.tpl.php). I'm not used to working with Drupal at all, so any help would be great!

Ta

# Answer
> 0 votes
Can you try:

```
$item['#attributes'] = array('class' => 'photo');

```

---
Tags: 7, entities, theming
---


title: Make webform submissions non-editable?

text:
# Question
Title: Make webform submissions non-editable?
I have created a web site with a bunch of Webforms used to collect data from surveyors. My client is interested in having the ability to make individual submissions non-editable by the surveyor while not removing the ability for surveyors to edit their own submissions generally. In other words, she wants the surveyors to be able to edit their submissions at her direction, but once she considers the submission complete, she wants to lock it down and prevent further editing, partly to prevent confusion if the surveyor perhaps has two or three different webforms they are working on.

Do you know any way to do this? Thanks!

# Answer
> 0 votes
Checkout the "Content Access" module: https://www.drupal.org/project/content\_access

Once your client wants to "Lock down" the webform, she can do so within the Role Based and Per Content Node access control settings.

Hope this helps. -Wrench

---
Tags: webforms
---


# Question
Title: Insert my files inside a custom table after upload?
How to insert my uploaded files inside a custom table (as managed\_file) after upload inside a custom form on DRupal 8 please ?

For moment, I have :

```
$form['images']['new']['local'] = array(
  '#title' => t('Upload Images'),
  '#type' => 'managed_file',

```

I need to use jquery, element\_validate ? Other ? Thanks.

# Answer
> 0 votes
Don't. It's a fundamentally bad idea to store data in custom table in Drupal 8. There are enough APIs and no support for that. Of course, hooks are still there so you can implement `hook_entity_presave` and then take the field data and write it out... but just say no :)

---
Tags: forms, 8, media
---


title: Image field, how add title field?

text:
# Question
Title: Image field, how add title field?
Here drupal have a field for set a description for each images:

How I can add a custom field for each image please ? By example a "Title" or "Author" field ? Thanks.

# Answer
Have you tried "ImageField Extended"? Alternatively, you could create a new content type which consists of an image and any number of fields that you want.
> -3 votes

---
Tags: 8, media
---


title: Removing field wrapper in a form

text:
# Question
Title: Removing field wrapper in a form
I would like to theme a form, and the div wrapping my text input element prevents me from doing what i want. So i got this right now :

```
<div class="form-item form-type-textfield form-item-email">
 <input type="text" id="edit-email" name="email" value="mail@msn.com" size="20" maxlength="128" class="form-text required">
</div>
</div>

```

I would like to have this :

```
 <input type="text" id="edit-email" name="email" value="mail@msn.com" size="20" maxlength="128" class="form-text required">

```

# Answer
You can set `#theme_wrappers` of the element to empty array so the element will not have any wrapper at all.

```
$form['email']['#theme_wrappers'] = array();

```
> 10 votes

---
Tags: forms
---


# Question
Title: How can I update webform_submission uid in the table, after which the anonymous user has registered?
I'm a graphic design, and I just started using Drupal 7.

I have a form created with webform, which collects data entered by the user, after sending, the user is directed to the purchase page. The stages of the purchase is successful if both the user and logged in, whether the user is anonymous.

Here's my problem, from the control panel of Drupal 7 when I go to see the results of the webform, if the form has been sent by the user logged in, see the user's name, is so I know who did it then submitting the form. While it has been the anonymous user, in the results I see anonymous user even after the user has registered and recognized.

For clarity I describe what it does with this form, these are the steps that the user to fill out the form webform:

1) Fill out the form webform (in this form there two fields of the form "webform commerce") 2) after sending the form you will be directed during the cart / checkout, at this stage the user enters the email for the registration, if it is anonymous. Everything works perfectly.

I noticed that the field in the table webform\_submission uid inside the database remains at 0 even after the user has registered.

Browsing around the net in the blog / forum / drupal.org I left this tutorials: example tutorial so I'm starting to use hook\_webform\_submission\_presave in a custom form. So how do I fill the uid after the form has been sent?

This is the code:

```
            <?php
/**
 * @file
 * Questo modulo server per collegare utente anonimo con il webform inviato.
 */
// hook per ottenere l'ID dell'utente che ha inviato il modulo webform
function mio_modulo_webform_submission_presave($node, &$submission) {
  // Ottengo l'id dell'utente.
  //$user = user_load($submission->uid);
  global $user;

  $user->uid;

}
?>

```

Sorry for my english Thanks in advance for the help

# Answer
> 0 votes
It sounds like your webform has already been submitted by the time they reach checkout. So essentially, you may need to "Update" the submission with the new user ID.

Check out webform\_submission\_update: http://drupalcontrib.org/api/drupal/contributions!webform!includes!webform.submissions.inc/function/webform\_submission\_update/7

---
Tags: 7, users, webforms
---


# Question
Title: Impossible to enable modules in SimpleTest
I am building SimpleTests for my modules:

It seems like the standard procedure for enabling modules it doesn't work for me:

```
function setUp() {
    parent::setUp('mymodule');
 }

```

I constantly get a stupid error code: `Duplicate entry 'bartik-system-main' for key 'tmd': INSERT INTO {block}`

As I am using profiles I used the $profile variable:

```
protected $profile = 'myprofilename';

```

I have forced this by using a Drupal function:

```
module_enable(array('mymodule'), $enable_dependencies = TRUE);

```

In this final case the error that persists is

```
Undefined property: stdClass::$name

```

Here below is a sample of my code:

```
class mymoduleWebTestCase extends DrupalWebTestCase {

  protected $privileged_user;

  protected $profile = 'myprofile';

  public static function getInfo() {
    return array(
        'name' => 'mymodule',
        'description' => 'mydescription.',
        'group' => 'mygroup',
    );
  }

  function setUp() {
    $this->privileged_user = new stdClass();
    parent::setUp();
   // Login a user that has access to the content sync server admin settings
    $this->privileged_user = $this->drupalCreate();
    $this->drupalLogin($this->privileged_user);
  }

  function testMyModule() {

    //Create content of community type
    $settings = array(
      'type' => 'mycontenttype',
      'title' => 'Sample Content',
      'link' => 'http://www.google.com',
      'body' => array(LANGUAGE_NONE => array(array('body'))),
      'moderate' => 1,
      'status' => 1,
      'revisions' => NULL,
      'taxonomy' => NULL,
    );
    $node = $this->drupalCreateNode($settings);
    $this->drupalGet('mymodule/sample-content');
    $this->assertRaw('Sample Content', t('Content created.'));

    $node = $this->drupalCreateNode($settings);

   //This if we have a valid link inside
    $this->clickLink(t('http://www.google.com'));

  }

```

# Answer
> 3 votes
You should make triple-sure that your module declares all of its dependencies properly. Even if it does, Simpletest struggles with dependencies and you may have luck if you enable them explicitly in `setUp()` before your module.

Also, not sure if it's the contributing your error, but instead of `$this->privileged_user = new stdClass();` I would use `DrupalWebTestCase::drupalCreateUser` like so: `$this->privileged_user = $this->drupalCreateUser()`. I might also declare it after `setup()` but I'm not sure that's significant.

# Answer
> 0 votes
The `Duplicate entry 'bartik-system-main' for key 'tmd'` seems to be the same as an error caused by using fe\_block module, reported here Simpletest: database exception during setUp

The solution proposed for that question was to enable modules after the main setup was complete. It worked for me when I had the same exception. Using an installation profile makes it more difficult, but assuming it is the same case, perhaps there is a way to make a simplified test profile with the features module disabled, and re-enable it manually?

---
Tags: testing
---


# Question
Title: Can't delete entities using entity_delete_multiple()
I was studying how to work with entities following http://www.bluespark.com/blog/drupal-entities-part-3-programming-hello-drupal-entity.

I downloaded the module, created by the author of that article. Then I wanted to delete entities, using the following code.

```
entity_delete_multiple('basic', array(1,4) );

```

But it didn't delete anything. I though that the `delete` method should be implemented, and added it into the class.

```
class BasicController extends DrupalDefaultEntityController{

  public function delete($basic) {
    var_dump(1);exit;
    db_delete('basic')
      ->condition('basic_id', $basic->basic_id, '=')
      ->execute();
    field_attach_update('basic', $basic);
    module_invoke_all('entity_delete', 'basic', $basic);
  }
};

```

It doesn't work: `1` is not printed.

How do I delete an entity with fields?

# Answer
> 1 votes
`entity_delete_multiple()` is implemented by the Entity API module, which is not part of Drupal.

In order to be able to delete entities with `entity_delete_multiple()` you need to do one of two things.

* Define a deletion callback for your entity
* Use a controller class that implements `EntityAPIControllerInterface`

In fact, this is the code used by `entity_delete_multiple()`.

```
function entity_delete_multiple($entity_type, $ids) {
  $info = entity_get_info($entity_type);
  if (isset($info['deletion callback'])) {
    foreach ($ids as $id) {
      $info['deletion callback']($id);
    }
  }
  elseif (in_array('EntityAPIControllerInterface', class_implements($info['controller class']))) {
    entity_get_controller($entity_type)->delete($ids);
  }
  else {
    return FALSE;
  }
}

```

In the first case, you simply define a function similar to the following.

```
function basic_delete_entity($id) {
  // Delete the entity whose ID is $id.
}

```

You can use any name for the delete callback, as long as you refer it in your `hook_entity_info()`.

In the second case, you normally sub class `EntityAPIController`. `EntityAPIController::delete()` should normally be sufficient.

# Answer
> 0 votes
The latter part of your post isn't relevant, but your syntax for entity\_delete\_multiple() is correct. The first argument is the entity type and the second is an array of numeric IDs.

Be sure the first argument is the entity type and not the bundle name. Also ensure the IDs are valid. That's all there is to it.

---
Tags: 7, entities
---


# Question
Title: page tpl pattern for a page with contextual parameter
I create a views with contextual filter and it's path is `prodcuts/%`, I know I can create a tpl for views but I need some more, I want to create a `page tpl` for this,( I want do another thing in that page ), what is pattern file name for this page?

# Answer
I write down my answer because maybe this help another guys in future,I found out that there is not related to url parameters,and it work according to current path, then accroding the tpl file name pattern accroding to the pattern ( `page--path.tpl.php`) the answer is `page--products.tpl.php` and work for any address according this pattern `products/%` .
> 1 votes

---
Tags: theming
---


# Question
Title: Access item url in views-view-fields.tpl.php
I'm using views-view-fields.tpl.php to theme the output of a content type.

What I need to do is the below, except I don't know how to get 'url\_for\_this\_item' without either printing all the variables and referencing it in a long array lookup, ie like $fields\[smth\]\[ddd\]\[0\]\[44\]\[ui\]\[uri\].

Is there a simple, clean way to get the url in the template? I have tried outputting a link but then views still insists on giving the full link with an closing tag on the end. Of course, I can parse this and remove the closing tag but it just seems too hacky. Is there not a better way?

```
print '<a href="' . $fields[url_for_this_item] . '">';
    print $fields['title']->content;
    print $fields['field_this']->content;
    print $fields['field_that']->content;
print '</a>';

```

I want to to get the url for

# Answer
If I understood it right, you can simply add a new field in Views which holds the URL to the item. And then in the template file you can print this field as you described in you question.
> 1 votes

# Answer
use `<?php print $fields['uri']->content; ?>` to print the URL of the particular field. However this works when you have the File:path field added in your views
> 1 votes

---
Tags: 7, views, theming
---


# Question
Title: Placing a drupal menu on an external site
I have a drupal install (latest 7.x version at the time of writing). It is in the root directory of my domain.

In a non drupal sub-directory, called 'member' so at /member, I have 3rd party script which enables my site to have membership functionality.

The script inside of /member is not drupal, although it does connect to the drupal database to write to the users table to enable single sign-on.

I was wondering if it is possible to display a drupal menu (the main navigation) inside the script in /member? I want to be able to alter the menu in drupal and then have those alterations automatically updated in the /member script.

I would certainly appreciate any advise as to whether this is in fact possible, and some advice about how I might get started.

Thanks.

# Answer
Yes, it is possible. In your drupal website:

* Render the main menu block on a custom made (module) page for example /main-menu-external
* Strip all the sections but the content section, so that no header, footer, ... is rendered, only the menu.
* With context load a blank theme on the page "main-menu-external"
* At this point "main-menu-external" will be a blanco page with only the main menu rendered on it AND will use a different theme from the rest of your website so you can configure it for that page only.

In your /members website:

* Just put an `<iframe>` with source "yourdrupalwebsite.be/main-menu-external"

Et voila, there is your drupal menu on an external website :)
> 0 votes

---
Tags: routes, external-scripts
---


# Question
Title: View Mode not showing up under Manage Display
I created a view mode let's call as my\_node\_view for content type under display type settings, I was expecting it to show along with default and teaser tabs as default|teaser|my\_node\_view in manage display section, but it did not show up. I have ensured my\_node\_view is checked under custom display settings for Use `custom display settings for the following modes`. Am I missing anything?

# Answer
> 3 votes
Writing out my comment as an answer.

This apparently needs a manual cache clear right now to work.

---
Tags: 8, entities
---


# Question
Title: How to programmatically create forums and containers (not forum topics)?
I need to create containers and forums using rules.

If I use the action "Create new entity" -\> "Taxonomy term" I got that by default the new term created is treated as a forum, not a container. How can I either convert it to be a container or, using a custom PHP script, create directly a container ?

I tought it was some variable of the term to make the difference, but if I use Devel over both containers or forums they looks the same.

I found http://www.unibia.com/unibianet/drupal/how-create-drupal-forums-and-containers-programmatically but it refers to D6, and in D7 I don't know what to pass as $form and $form\_state to the forum\_form\_container() function.

# Answer
I think I got it.. not in some fields, not (directly) in some DB table.. the difference between forum and containers is in the variables:

$containers = variable\_get('forum\_containers', array()); $containers\[\] = 14; variable\_set('forum\_containers', $containers);
> 0 votes

---
Tags: 7, nodes, rules
---


# Question
Title: How to correctly add meta tags to custom menu items?
I want to be able to use the meta tag module for everything my site, but currently I have no idea how to add meta tags to custom pages. For example, I have this page:

```
function mymodule_menu()
{
    $items = array();
    $items['home'] = array(
      'title' => 'Home',
      'page callback' => 'mymodule_home_page',
      'access callback' => TRUE,
    );
    return $items;
}

function mymodule()
{
    $o = '';
    $o .= 'hello world';
    return $o;
}

```

Such a page doesn't get meta tags as it is a custom page. What is the best way to get meta tags on the page in this case? Or what is wrong with my strategy?

# Answer
You can do this manually by using drupal\_add\_html\_head(); in your menu's callback function

```
<?php

function mymodule_home_page() {

  $element = array(
    '#tag' => 'meta',
    '#attributes' => array(
      'name' => 'custom meta info',
      'content' => 'test content',
      'attributes' => 'D7',
    ),
  );
  drupal_add_html_head($element, 'Test');

  return 'hello';
}
?>

```

or some modules will allow you to add custom paths.
> 1 votes

---
Tags: 7, meta-tags
---


title: Roles Machine name instead of role id

text:
# Question
Title: Roles Machine name instead of role id
I have custom module code that check the user role and based on user role, user fields updated,

for example

```
if(array_key_exists(12,$user->roles)) {
    //Manger
    $role =  array(8=>8);
} elseif (array_key_exists(13,$user->roles) ) {
    // super Manger
    $role =  array(14=>14);
} elseif (array_key_exists(11,$user->roles)) {
    //section manager
    $role =  array(14=>14,8=>8);
}

```

so when I want to move this module to other site and import roles using feature, the ids will changed.

so how can I use machine name for roles instead of ids.

Regard,

# Answer
just make sure when you move your roles that you spell them the same! then you can use the traditional

```
// Load the currently logged in user.
global $user;

// Check if the user has the 'editor' role.
if (in_array('editor', $user->roles)) {
  // do fancy stuff
}

```

or the more flamboyant

```
function user_has_role($roles) {
    //checks if user has role/roles
    return !!count(array_intersect(is_array($roles)? $roles : array($roles), array_values($GLOBALS['user']->roles)));
};

if (user_has_role(array('moderator', 'administrator'))) {
  // $user is admin or moderator
}

```

see here for more answers to the simple question Check if a user has a role
> 1 votes

---
Tags: users
---


title: Simpletest fatal error without message

text:
# Question
Title: Simpletest fatal error without message
locally my unit tests run just fine. On my online dev server, they fail and I don't get any error message despite "The test did not complete due to a fatal error." in the test messages and "An internal server error occurred. Please try again later." as return text of the batch process. No entry in the default error log, no error log file in the temporary simpletest public directory.

Is there any way to debug this and get the stack trace etc?

When I run the tests via Drush, they work just fine. This issue occurs only with the testing user interface and might be related to the PHP memory\_limit as I run on a shared host.

The point where the test fails seems to be arbitrary: Sometimes it comes as far as 200 asserts before failing, sometimes the fatal error occurs after only 40 assertions. Also the test function from which the error is thrown differs, but they all belong to the same class.

# Answer
> 1 votes
Figured it out ... The hoster I use (uberspace.de) has a timeout for script execution time. Some Simpletest tests do not respond for several minutes, which triggered the timeout.

---
Tags: testing
---


# Question
Title: CSS\JS Aggregation "Shuts down" Firebug indication
I have CSS\JS Aggregation on, and I've installed the AdvAgg module and set it for **Development** mode. The site works fine, but now I can't really use Firebug...

Firebug no longer shows me, for example "Style.css, line 50", but rather something like "fdn\_jkfdk\_aaahjfdh.CSS, line 500". I guess it's the aggregated file...

Anyways, Is there any way to get "Style.css, line#" appearing again without disabling aggregation? I can't sacrifice the option to make CSS edits in the site just for aggregation... I guess no one can!

# Answer
Advagg has a built in feature to bypass aggregation for a single request. You can append `?advagg=0` to the query string to load the page without aggregation. I haven't personally used this feature, but it seems it could be useful in your situation.

From the module description:

> Url query string to turn off aggregation for that request. ?advagg=0 will turn off file aggregation if the user has the "bypass advanced aggregation" permission. ?advagg=-1 will completely bypass all of Advanced CSS/JS Aggregations modules and submodules.

This would help with your problem of having readable css in firebug, but any changes you make to your sites css would still need a cache clear to take effect.
> 2 votes

---
Tags: css-js-aggregation
---


title: Fatal error: require_once()

text:
# Question
Title: Fatal error: require_once()
I tried to update my installation, but now I'm getting this fatal error:

> Fatal error: require\_once() \[function.require\]: Failed opening required '/home/abel/www/lmwep/massteri/sites/all/modules/views/includes/admin.inc' (include\_path='.:/usr/local/PEAR:/usr/local/share/pear:/usr/local/lib/php') in /home/abel/www/lmwep/massteri/sites/all/modules/views/views\_ui.module on line 175

I have no clue what this means. Any help is appreciated.

# Answer
> 3 votes
It means that the file `admin.inc` (part of the *Views* project) is not found.

This file is supposed to be on the following path below your Drupal root `sites/all/modules/views/includes/`. If you check, I'm sure that you'll find that it is no longer there.

Why this happens is more difficult to say. I presume that you had the *Views* module installed on your site in `sites/all/modules/views/` as indicated by the path (for the record: this is the right place), but that after the upgrade, it is no longer there? Again, please check?

When upgrading, the `sites` subdirectory from the pre-upgrade site is supposed to be the `sites` subdirectory in the upgraded site. If this, for some reason, in not the case, the contributed modules you've installed (such as *Views*) will be lost.

Please check if the files are missing (as I belive they are). If they are missing, the solution is to make sure that the entire `sites` subdirectory hierarchy is properly moved into the upgraded site file hierarchy.

# Answer
> 0 votes
please first clear your cache by drush cc all or clear your cache table from database then run your site.

# Answer
> 0 votes
Try re-installing `views` module or the module which causes this issue. It worked for me.

Hope it would help someone running with this kind of issues.

---
Tags: updating
---


# Question
Title: Unable to get all the sub-menu's in the data compare
I am trying to add a rule for comment view for which under the actions I click on data compare.As per the tutorial, I have to click the drop down list and choose node.

Whereas when I repeat the exact same steps from the *Conditions-\>data* compare I got some lesser menu option :

Now my problem is that as I don't have the node option to choose how am I supposed to complete the tutorial.

This kind of missing options appear quite frequently (when I tried to add an action/replacement patterns/ I had to choose the node type whereas in the options list there was no `[node:type]`. Again after 24 hours when I re-try this I get the `[node:type]`)

I don't get the reason which is causing this problem. After doing the troubleshooting steps like re-login, clear browser cache, flush cache the options list is still the same.

# Answer
As a temporary way around I have done the reinstall of 7.34 and installed all the modules from the start.This got me back the menu but I cannot do the un-install every time this problem comes. I will be losing a lot of time
> 0 votes

---
Tags: routes, navigation
---


# Question
Title: Change drupal language from neutral to en
i have a huge drupal website(nodes) and i have to implement a multi language system now it has only one language.

I have installed the i18n module, and set another language but o can\`t update the existing nodes from neutral language to EN or RO.

How can i update all the existing nodes from neutral language to EN.

Thanks

# Answer
> 0 votes
You should use Language Assign to easily update all the languages of your nodes.

---
Tags: i18n-l10n
---


# Question
Title: Multiselect values not getting saved in hook_settings()?
This is the code I have implemented in my module which is working fine!

```
/*
 * This is a helper()
 */
function MYMODULE_feeds($page_id = '') {
  foreach($pagefeed['data'] as $feedval) {
    $post_type[] = $feedval['type'];
    if ($feedval['type'] == 'photo') {
      if(array_key_exists('message',$feedval)) {
          $messageFeed[] =  $feedval['message'];
          if ($timeshow == 1) {
            $created_statmp = $feedval['created_time'];
          }
          $i++;
      }
      if($i == variable_get('no_feeds')) {
          break;
      }
    }
  }
  $post_type_unique = array_unique($post_type);
  $post_type_unique_serial = array_values($post_type_unique);
  variable_set('post_type_unique_serial', $post_type_unique_serial);
  return theme('MYMODULE_feed_theme', array('pagefeeds' => $messageFeed, 'time_stamp' => $created_statmp));
}

```

After that I have done this in my module's `admin.inc` file

```
/*
 * Implements hook_settings()
 */
function MYMODULE_settings($form, &$form_state) {
  $form['MYMODULE']['post_type'] = array(
    '#type' => 'select',
    '#title' => 'Select your post type(s) to show',
    '#default_value' => variable_get('post_type_unique_serial'),
    '#options' => variable_get('post_type_unique_serial'),
    '#multiple' => TRUE,
  );
  return system_settings_form($form);
}

```

Problem is that, I'm getting the values there, but when I'm saving that every field is saving the updated values, expect this field.

I'm not getting where I've made the mistake?

# Answer
> 0 votes
I had a very similar issue some while ago, here is the solution which should work for you:

```
/*
 * Implements hook_settings()
 */
function MYMODULE_settings($form, &$form_state) {
  $form['MYMODULE']['post_type'] = array(
    '#type' => 'select',
    '#title' => 'Select your post type(s) to show',
    '#default_value' => variable_get('post_type', 0), // Here instead of 'post_type_unique_serial', you should use 'post_type'
    '#options' => variable_get('post_type_unique_serial'),
    '#multiple' => TRUE,
  );
  return system_settings_form($form);
}

```

Cheers!

# Answer
> 0 votes
1) If `variable_get('post_type_unique_serial')` returns an array to populate the options, then it can not also be used for setting the default value, as this should be a single key within the array.

2) Generally it is good practice to use the same name for the variable as the form element if it is being used to set the default value eg `$form['MYMODULE']['post_type']` and `'#default_value' => variable_get('post_type'),`

# Answer
> 0 votes
You are doing it in wrong way. Check my comment in front of `#default_value` and `#options`.

```
/*
 * Implements hook_settings()
 */
function MYMODULE_settings($form, &$form_state) {
  $form['MYMODULE']['post_type'] = array(
    '#type' => 'select',
    '#title' => 'Select your post type(s) to show',
    '#default_value' => variable_get('post_type', array()), // Selected value will saved as a variable with same name as field's name
    '#options' => $option_array, // Here paas the options list which should be same as default value
    '#multiple' => TRUE,
  );
  return system_settings_form($form);
}

```

---
Tags: forms, hooks
---


title: Adding class to nested UL in menu

text:
# Question
Title: Adding class to nested UL in menu
I'm creating my menu using view along with Bootstrap to create a mega menu style navigation.

I'm having a problem with the nav showing expanded at times when you come to the site and or refresh. not all the time but more than I'd like.

I am using: \_menu\_link like such:

```
function MYTHEME_menu_link(array $vars) {
  if ( $vars['element']['#theme'] == 'menu_link__user_menu' ) {
    $vars['element']['#attributes']['class'][] = '';
  }
  elseif ( $vars['element']['#theme'] == 'menu_link__main_menu' ) {
    $vars['element']['#attributes']['class'][] = 'dropdown mm-menu-fw';
    $vars['element']['#localized_options']['attributes']['class'][] = 'url-link';
  }
  return theme_menu_link($vars);
}

```

This gives me the following HTML markup.

```
<ul class="dropdown mm-menu-fw">
  <li>
    <a href="#" class="url-link">MY LINK</a>
    <ul class="NEED-TO-ADD-CLASS"></ul>
  </li>
</ul>

```

# Answer
You might get into the sub menu element with the \['#below'\] object. not tested.

```
<?php

   /**
    * Implements theme_menu_link__[MENU NAME].
    */
   function YOURTHEME_menu_link__main_menu(&$variables) {

        $element = $variables['element'];
        $sub_menu = '';

        $element['#attributes']['class'][] = 'dropdown mm-menu-fw';
        $element['#localized_options']['attributes']['class'][] = 'url-link';

        if ($element['#below'])
        {
         $sub_menu = $element['#below']['#attributes']['class'][]= 'NEED-TO-ADD-CLASS';
         drupal_render($sub_menu);
        }

       $output = l($element['#title'], $element['#href'], $element['#localized_options']);

       return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";

 }
?>

```
> 0 votes

---
Tags: 7, theming, navigation
---