# Question
Title: How can I see my drupal site as a anonymous user while logged in as admin?
I want to use Devel Themer to look at the "homepage" comment field, but it only shows up for anonymous users.

Is there anyway to see a page as a anonymous user would, and at the same time be logged in as an admin so that I can use the Devel Themer module?

# Answer
No that is impossible.

What you could do is give access to devel for all users. You shouldn't be using devel in a live environment anyways, so just make sure you remove devel and revoke permissions before staging to production environment.
> 13 votes

# Answer
The way I do this is simply have a different browser open with the site open as anonymous - Logged in on Firefox, anonymous on Chrome, for example.

EDIT Whoops, I didn't fully understand the question on that quick read - hmm. Devel should have a tool that you can 'switch user' - at least I know there is a module for it. I wonder if 'anonymous' is one of those users?
> 5 votes

# Answer
It says it's buggy, but you could try the https://www.drupal.org/project/masquerade module, which allows you to view a site as a different user.
> 0 votes

---
Tags: users, debugging
---


title: tableselect checkboxes

text:
# Question
Title: tableselect checkboxes
i want to change values of only checked elements on tableselect. How can i do that please ?

this is my tableselect :

```
$form['tab'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $rows,
    '#empty' => t('empty !'),

);
return $form;

```

i've also a submit button that makes changes (update database) on one column of the tableselect :

```
 $form['published'] = array(
        '#type' => 'submit',
        '#value' => t('Publish'),
        '#states' => array(
            'invisible' => array(
            ':input[name="select_list"]' => array('value' => 'Published'),
            )
            ),
        '#submit'=> array('publish_submit'),
    );

```

My function to make changes (to publish elements that aren't now) :

```
function publish_submit($form, &$form_state){
$check = $form_state['values']['tab'];
//$check = array_filter($form_state['values']['tab']);

$sql = db_update('field_data_field_books');
$sql->fields(array('field_books_value'=> 'Published'));
$sql->condition('entity_id',$check); //update only books i checked on the tableselect
$query = $sql->execute();
   }

```

this is what dsm($check) returns (when i check one or more elements on the tableselect )

this is dsm($rows) (6 elements are ok):

This is how i created the $rows :

```
$rows = array();

foreach ($result as $res){

    $rows [] = array(

            'book_title' => l($res-> field_title_value, 'node/'.$res->entity_id),
            'book_state' => $res-> field_state_value,
            'book_editor' => $res-> field_editor_value,
            'book_categories' => $res-> name,
            'edit_books'=>l(t('Details'), 'node/'.$res->entity_id.'/edit'),
          );

}

$form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $rows,
    '#multiple' => TRUE,
    '#empty' => t('nothing!'),

);

```

# Answer
> 2 votes
As beebee said on comments :

$rows should be indexed like this :

```
foreach ($result as $res){

    $rows [$res -> entity_id] = array(

```

and the condition of the publishing function :

```
function publishing_submit($form, &$form_state){

    $check = array_filter($form_state['values']['table']);
    $sql = db_update('field_data_field_state');
    $sql->fields(array('field_state_value'=> 'Published'));
    $sql->condition('entity_id', $check, 'IN');
    $sql->execute();
}

```

Thanx beebee

---
Tags: forms
---


title: PHP print in Basic page

text:
# Question
Title: PHP print in Basic page
I am facing what I think it is a strange behavior...

I have a Basic Page with PHP code in it. In this PHP code, I have some "Print".

Now, no matter the page I am displaying on the website, I got those prints in the bottom of my page...

Is that normal? How can I change that?

Regards!

# Answer
> 1 votes
This is working as intended.

> I have a Basic Page with PHP code in it. In this PHP code, I have some "Print".

You should *not* have any PHP (not "print" or anything else) as part of the *content* of a node. Drupal is designed to treat PHP in nodes as text, and will just output it verbatim. Anything else would create a huge security hole in your site.

Just delete those "print" statements, and they will no longer appear.

---
Tags: 7
---


# Question
Title: Webform live calculations in table/matrix
I am trying to create a work time allocation webform. My goal is to create a table (6 columns and addable rows) and get a **live** sum of all columns at the bottom. (edit: pardon my lacking terminology. With live I meant client side ajax or js that updates instantly when the user fills in the form, before submitting it)

I tried using a webform and webform matrix module, they allow for a table with addable rows. But I can't get the live sums to work. Is there another method or module I could use that would suite my case better?

TLDR; I need a webform with a table supporting x amount of rows and a live sum at the bottom. Any suggestions what modules to use?

The colored cells are buttons.

# Answer
> 1 votes
Refer to Filter form submission data by a field value with Views, Webform for a tutorial to display the data collected by Webform in a filterable, tabular format, using the Webform module (of course), and the Views module.

After you created an appropriate view, you could consider either of these approaches:

1. Add the "Views Calc" module to add the "live sums" that you're looking for. Here is an excerpt from its project page:

> This module adds simple calculations to a views table. Requires the Views module.
>
> You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns. A plug in theme makes the view look more spreadsheet-like (right justifies numeric fields, shades calculated columns and rows, and underlines calculated rows).

And this is a typical screenprint using the Views Calc module:

Refer to my answer to "Total count of two different content types in one View?" for more details about how to use the Views Calc module.

Disclosure: I'm a **co**-maintainer of this module,
I hope this does not violate the site's policy on self-promotion.
2. Use the Views Summarize module. Here is an excerpt from its project page:

> Enables an extra display style which displays summaries of a column on the last row.

There isn't a lot (any?) documentation available about actually using this module, but the "clue" is like so: Click on the "settings" icon for the display style, then enable a summarizer on one of the columns.

Refer to the project's home page for a screenprint of a view using this module.
3. Addd the calculation via custom logic in **views templates**, as explained in one of the answers to the question about "How can I add a summary row to a Drupal View?". Here is a quote from that answer:

> ... Create a `views-view.tpl.php` for your view, and then edit it calculate and print out the summary.
>
> Another option is to create another display for the same view, and then create a `views-view-unformatted.tpl.php` and calculate and print out the summary w/o doing a print $row; to avoid calling the fields template. Then add use view display where needed.

**Note**: the extra clarification (requirement?) about "live" only got added after I wrote most of my answer. I.e. via a comment like "*... something client side that updates as the user fills in the form without submitting it first*". So far I'm not aware of any module that ALSO supports that. Not sure if there is a way to do that using the "Views templates" approach described above (if there is such way, please add another answer related to that also).

# Answer
> 0 votes
I found some additional resources on AJAX and manipulating a webform before submitting it. It is not a complete solution but if anyone is on the same path it might be of use. Thanks to @Pierre.Vriens for pointing me in the right direction.

The tutorial is here.

---
Tags: 7, ajax, webforms, javascript
---


title: drupalchat with nodejs

text:
# Question
Title: drupalchat with nodejs
I need to run drupalchat with nodejs locally but I get error loading the socket.io.js client library (404 not found)

nodejs server is running

the file exist in that path :

> sites/all/modules/nodejs/node\_modules/socket.io/node\_modules/socket.io-client/socket.io.js

the request:

> http://localhost/drupal:8080/socket.io/socket.io.js

noddejs config:`settings = {
 scheme: 'http',
 port: 8282,
 host: 'localhost',
 resource: '/socket.io',
 serviceKey: '',
 backend: {
 port: 82,
 host: 'localhost',
 scheme: 'http',
 basePath: 'localhost/drupal',
 messagePath: '/nodejs/message'
 },
 debug: false,
 sslKeyPath: '',
 sslCertPath: '',
 sslCAPath: '',
 baseAuthPath: '/nodejs/',
 publishUrl: 'publish',
 kickUserUrl: 'user/kick/:uid',
 logoutUserUrl: 'user/logout/:authtoken',
 addUserToChannelUrl: 'user/channel/add/:channel/:uid',
 removeUserFromChannelUrl: 'user/channel/remove/:channel/:uid',
 addChannelUrl: 'channel/add/:channel',
 removeChannelUrl: 'channel/remove/:channel',
 setUserPresenceListUrl: 'user/presence-list/:uid/:uidList',
 addAuthTokenToChannelUrl: 'authtoken/channel/add/:channel/:uid',
 removeAuthTokenFromChannelUrl: 'authtoken/channel/remove/:channel/:uid',
 toggleDebugUrl: 'debug/toggle',
 contentTokenUrl: 'content/token',
 publishMessageToContentChannelUrl: 'content/token/message',
 extensions: [],
 clientsCanWriteToChannels: false,
 clientsCanWriteToClients: false,
 transports: ['websocket', 'flashsocket', 'htmlfile', 'xhr-polling', 'jsonp-polling'],
 jsMinification: true,
 jsEtag: true,
 logLevel: 1
};` what is wrong/missing config/permissions to run them together?

thanks in advance

# Answer
> 0 votes
I have created simple module to Integrate nodejs and build chat server for drupal users d7 nodejs chat

---
Tags: nodejs
---


# Question
Title: How to hide programmatically timezone and location on a custom user edit profile page in Drupal 7?
I need a custom user\_profile\_form in a page of my drupal site containing a subset of fields provided by the form. I created it and rendered it this way:

```
function mymodule_join_experiment_contr_strict_mode($exp_node, &$form, &$form_state) {
  module_load_include('inc', 'user', 'user.pages');
  global $user;
  $user = user_load($user->uid);
  $form = drupal_get_form('user_profile_form', $user, 'account', 'strict_mode');
  return $form;
}

```

Now in my custom function mymodule\_form\_user\_profile\_form\_alter(&$form, &$form\_state, $form\_id) i'm doing

```
$form['picture']['#access']=FALSE;

```

in order to hide the field 'picture' and any other field i need to hide. In the form i have two collapsible named 'location' and 'timezone', provided, i think, by 'location' or 'gmap' module. (I didn't realized all this site so i don't really know everything about it.) Now, even looking at $form i can't see the equivalent for timezone and location. I expected to find something that allowed me to do

```
$form['timezone']['#access']=FALSE;

```

but i cannot find timezone and location... What i am doing wrong?

EDIT: i'm trying to get what is the right way to do it in drupal, before to surrender and use a 'display:none' on css

# Answer
> 3 votes
Solved. I had to use the solution suggested #35

This is the code i used

```
<?php
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'MYNODETYPE_node_form') {
    $form['#after_build'][] = 'MYMODULE_SOMETHING_MEANINGFUL';
  }
}

function MYMODULE_SOMETHING_MEANINGFUL($form_element, &$form_state) {
  //note that I only have one location on this node type
  $form_element['locations']['#access']=FALSE;
  $form_element['timezone']['#access']=FALSE;

  return $form_element;
}
?>

```

I have not quite understood what is going on. An explanation about after\_build would be appreciated.

# Answer
> 0 votes
Timezone settings can be disabled on this page admin/config/regional/settings. And user pictures can be disabled on this page admin/config/people/accounts

---
Tags: 7, users
---


title: Drupal node_load display all fields

text:
# Question
Title: Drupal node_load display all fields
I have a template for a view in which I load a node. Is there a way to get the value of all fields from that node? Like, if I add another field in CCK it will appear automatically in the template.

Something like:

```
foreach $node->field
     print $value

```

Thanks!

# Answer
> 1 votes
Try `node_view`

```
<?php
  $node = node_load($nid);
  $node_view = node_view($node);
  $rendered_node = drupal_render($node_view);
  echo $rendered_node;
?>

```

Read: Rendering Drupal 7 fields (the right way)

---
Tags: views, nodes, theming, entities
---


# Question
Title: I could not access a page as administrator user
I just had a problem where a page created with a custom module caused an access denied error even when logged in as administrator user.

```
function cmis_play_menu() {
  $items['cmis_play'] = array(
    'title' => 'cmis_play',
    'page callback' => 'cmis_play_page',
  );

  return $items;
}

function cmis_play_page() {
  return 'boot';
}

```

I checked the following.

* The administrator user has all the privileges
* Cookies are disabled in settings.php
* The database username and password are correct

I tried the following (without success):

* Drush CC all
* Truncating the session table
* Accessing the page as a guest and as non administrator (but authenticated) user

I solved the problem by adding the following line:

```
$items['cmis_play'] = array(
  'access arguments' => array('administer news feeds'),
);

```

Why did I need to do this? How do I configure Drupal so that expressly setting access permissions for a page is not needed?

# Answer
From `hook_menu()`:

> "access callback": Defaults to user\_access() unless a value is inherited from the parent menu item; only MENU\_DEFAULT\_LOCAL\_TASK items can inherit access callbacks. **To use the user\_access() default callback, you must specify the permission to check as 'access arguments'**

Emphasis mine.

So if you don't provide an `access callback` explicitly, `user_access()` is used, which, unless you're logged in as user 1 which is a special case, returns `FALSE` if you don't provide it with any access arguments. That's why passing in `access arguments` fixed it.

You can't change this default behaviour without changing core Drupal files. Being explicit about your access is better than being implicit anyway - default should always be to deny.
> 0 votes

# Answer
The reason why your code causes an access denied error even if the currently logged-in user has the right permission is evident in `_menu_check_access()`, which is the function used to verify a user has access to a menu, and which contains the following code.

```
  // Determine access callback, which will decide whether or not the current
  // user has access to this path.
  $callback = empty($item['access_callback']) ? 0 : trim($item['access_callback']);
  // Check for a TRUE or FALSE value.
  if (is_numeric($callback)) {
    $item['access'] = (bool) $callback;
  }

```

Since you don't set an access callback, `empty($item['access_callback'])` will evaluate to `TRUE`and `$callback` will get 0 as value. Then `$item['access']` will get `FALSE` as value, which means that whomever user is currently logged-in, they will get an access denied error.

The reason why setting the access arguments makes your code work is that `_menu_router_build()` contains the following code.

```
if (!isset($item ['access callback']) && isset($item ['access arguments'])) {
  // Default callback.
  $item ['access callback'] = 'user_access';
}

```

In other words, setting the access arguments will automatically set the access callback to the default value (`'user_access'`), but not setting the access callback nor the access arguments will make the menu item no accessible from anybody.

As special case, setting the access callback to TRUE will cause the menu item to be accessible from every user, including the anonymous user. That is closer to *expressly setting access permissions for a page is not needed* I can think of, but it gives access to the menu to everybody, which is not what you normally want. Drupal uses this, but only in very limited cases.

```
  $items ['system/files'] = array(
    'title' => 'File download',
    'page callback' => 'file_download',
    'page arguments' => array('private'),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  $items ['system/temporary'] = array(
    'title' => 'Temporary files',
    'page callback' => 'file_download',
    'page arguments' => array('temporary'),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  $items ['system/ajax'] = array(
    'title' => 'AHAH callback',
    'page callback' => 'ajax_form_callback',
    'delivery callback' => 'ajax_deliver',
    'access callback' => TRUE,
    'theme callback' => 'ajax_base_page_theme',
    'type' => MENU_CALLBACK,
    'file path' => 'includes',
    'file' => 'form.inc',
  );
  $items ['system/timezone'] = array(
    'title' => 'Time zone',
    'page callback' => 'system_timezone',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
    'file' => 'system.admin.inc',
  );

```

A plain Drupal installation doesn't have a setting page where you can set which roles have access to specific pages. You need to set the access permission on each of the menu items your module sets.
> 0 votes

---
Tags: users
---


# Question
Title: How can I find all database schema changes introduced in a CiviCRM major version upgrade?
I'm using CiviCRM with Drupal. When upgrading a site to a new CiviCRM major version, it's very useful to know all the database schema changes introduced in the new version, so that any custom code referring to database fields can be amended accordingly.

A case in point is civicrm\_contribution\_recur.next\_sched\_contribution -\> next\_sched\_contribution\_date in 4.3 -\> 4.4 .

"You shouldn't be accessing database fields directly, you should be using the CiviCRM API", I hear someone say. Often that is the preferred approach but even so, API v3 is very closely tied to the database structure and the fields returned by an API call reflect the database field names, so the code would still need amending.

A really useful resource for CiviCRM would be an equivalent of Drupal's Converting n.x modules to (n+1).x documentation.

# Answer
I have now found a viable approach to identifying the changes, using mysqldbcompare. I've added a couple of pages to the CiviCRM Wiki, under Developer Resources -\> Reference Sheets -\> Database Reference:

Database Schema Changes: CiviCRM 4.4 to 4.5

Database Schema Changes: CiviCRM 4.5 to 4.6

Note that there is now a CiviCRM Stack Exchange site, currently in beta. Should this question move there?
> 2 votes

# Answer
One way to do it would be to pore through the CRM/Upgrade/ directory in the new version, looking for schema changes. However these are distributed across multiple files, depending on which alpha or beta version the change was introduced in. E.g. the next\_sched\_contribution\_date change was introduced in this file:

civicrm/CRM/Upgrade/Incremental/sql/4.4.alpha1.mysql.tpl
> 4 votes

# Answer
An easier way of doing it from a pure structural perspective is to use a mysql schema diff tool, something like:

http://adamspiers.org/computing/mysqldiff/

However that might not give you all the changes, but i suspect will catch most changes. A lot better to do it in an automated way, IMO :)
> 4 votes

# Answer
Another option would be to diff the xml schema between versions. The xml schema files are not shipped in the tar.gz releases, only in git, so it's not exactly the most user-friendly method, but it could be a good starting point.

You could also try:

```
git log -w -p tag1..tag2 xml/schema

```

For example:

```
git log -w -p 4.4.5..4.5.2 xml/schema

```

Not perfect, but semi-comprehensible.
> 4 votes

---
Tags: upgrading, civicrm
---


# Question
Title: Do I have to move contributed modules to "sites/all/modules" for upgrading?
In Drupal 6, I have placed my contributed modules inside the *modules* directory in the Drupal root directory (not in sites/all/modules). I need to upgrade my site to Drupal 7.

Do I have to move the contributed modules inside sites/all/modules before upgrading to Drupal 7?

# Answer
> 1 votes
You don't have to, but it is highly recommended. It greatly ease identification of the files to keep while upgrading (and following the upgrade documentation).

# Answer
> 0 votes
Apart from the previous answer, here are some extra suggestions related to moving your contributed modules:

1. Technically there is no real "need" to move those modules (Drupal can also work if you store contributed modules in the root's subfolder "modules", as you have noticed in your "old" D6 site). However it is NOT considered as a good practise to store contributed modules there, since it's not compliant with typical instructions to update (not upgrade) from one D6 version to another D6 version. During such update, you typically replace the entire 'modules' directory (and only keep your 'sites') folder. If you'd do that during such update, you wipe out all your contributed modules (which is ot what you'd want to happen).
2. If apart from "contributed" modules you also have "custom" modules (which are home written, not downloaded from Drupal.org), then you should consider storing contributed modules in something like `sites/all/modules/contrib`. And if you then also store your "custom" modules in something like `sites/all/modules/custom`. That way it is more easy to differentate the contributed modules from custom modules, something you'll typically want to know about when "upgrading" to a new Drupal version, like from D6 to D7.
3. If you're actually moving modules from one directory to another, you can (should!) use the Registry Rebuild module to rebuild the system table (to get the modules in the right place).

---
Tags: 7, upgrading
---


# Question
Title: FieldCollection/PLUpload - Recurring error when uploading images on PROD - "No file by that name exists"
TL;DR Pantheon's distributed file system can't handle modules that refer to the temp file system across multiple requests, which messes up the Plupload module. What alternatives are there?

The error occurs when users upload images to the site using PLUpload, and it only occurs in the LIVE environment. Our discussions with pantheon support indicate that this is likely something to do with our code not playing nicely with the load balancing in the live environment. At this point though, we're pretty stumped on how to proceed. I was hoping someone here may have encountered it and could provide some insight on how to proceed.

In case the screenshots do not share correctly, I have included a link to a google doc

Here's an example of the error message.

Some notes:

* We uploaded 5 images here. 2 were rejected as you see in the pink notification below. The number of failed images appears to be entirely random - sometimes all will work. Sometimes just 1, sometimes none.
* We have tried changing the path from temporary:// to public:// - this error appears to occur regardless of where the temp space is pointed. Only occurs in the live environment due to the load balancing in use with our hosting provider
* Cloud-based hosting, so we do not have access to make changes to the load balancer.

Steps we've taken:

1. Insert watchdog in file.inc where we see this error
2. Enable dblog and try to reproduce the error you see above.
3. Identify the failure point in the debug log. Here's what we see:
4. Watchdog is showing that the file in question does not exist
5. We check the SFTP, and it's definitely there.

In our discussions with the hosting provider, here's what we learned:

* This is likely a fringe case that the load balancer doesn't have the ability to handle.
* It sounds like the module is making a number of requests with the assumption that they can share a tmp directory.
* and this comment:

> Do you know if the PLUpload file issues multiple HTTP requests (via AJAX maybe?) when doing the uploads? If so, it may be that it's assuming that the temporary filesystem is shared between all requests.
>
> This is a common flaw in a lot of contributed modules or plugins: they assume that there's only one place the code is executing, and that the "temp" filesystem space is available consistently across N requests.
>
> This isn't what temporary filesystems are really for, but in a legacy single machine architecture it will rarely cause failures. Once you are distributed that assumption will fail quite reliably.

Now for the part that has us stumped:

* It seems that PLupload might not be our best approach. If we want to get it to work, we'd have to figure out how it's handling temporary file requests.
* Our site was originally built with PLupload and Field Collection working together. I'm curious if there's other modules we can look into that will allow us to get the functionality of both within the confines of the hosting environment.

# Answer
> 0 votes
This is a note for people who face this problem. Maybe it can help them.

I had this error on a project. I see that it occurs on a plupload widget with a limit of file number set to 1. I replaced this field by a classic upload and the problem gone.

---
Tags: entities, files
---


title: Why does node/%node/random/stuff work?

text:
# Question
Title: Why does node/%node/random/stuff work?
I just noticed this, and I can't find an explanation.

I can go to node/1/45645645/klzkelfkzlef/47z4e5fz56e4f/etc and it'll just show node/1 instead of a 404 page.

The same happens with taxonomy/term/%term/stuff

Somehow, if it doesn't match a valid path (/edit for example) it falls back to just a view of the entity. How? Like, where does this happen?

Is this normal hook\_menu behavior? node/%node exists and node/%node/edit exists, so node/%node/random may not exist but it'll use the callback for node/%node anyway?

# Answer
Ah, just found it in pretty much the first few lines of menu.inc. It does indeed look one level higher until it finds a match.
> 0 votes

---
Tags: routes, entities, redirection, debugging
---


title: #states with effects (fade, slide)

text:
# Question
Title: #states with effects (fade, slide)
I'm using the form API #states feature to show and hide fields based on the value of other inputs. This is working great; however, I would like to have the option to fade or slide the inputs as they are shown and hidden.

I realise the conditional fields module offers this functionality, but I found it too buggy to use.

I am using this code.

```
$form['more_info'] = array(
  '#type' => 'fieldset',
  '#title' => t('Additional Information'),
  '#collapsible' => TRUE,
  '#collapsed' => TRUE,

  // Expand the expand_more_info fieldset if the box is checked.
  '#states' => array(
    'expanded' => array(
      ':input[name="expand_more_info"]' => array('checked' => TRUE),
    ),
  ),
);

```

This made me think using 'expanded' instead of 'visible' would make the element slide and not just appear however this is not working for me.

I am editing a node form using hook\_form\_alter so my working code (but with no effect) looks like this.

```
$form['field_full_name'][LANGUAGE_NONE][0]['value']['#states'] = array(
    'visible' => array(
        ':input[name="field_person_type[und]"]'=> array(
            array('value' => 'Contractor'),
            array('value' => 'ICM'),
            array('value' => 'Member of public'),
        ),
    ),
);

```

Replacing visible with expanded or collapsed has no effect so I guess these properties only apply to fieldsets, not elements. A full list of possible states can be found here.

So, is is possible to fade or slide form elements using #states?

# Answer
> 1 votes
Please try this. may be it will help you.

```
**Your Code:**
$form['more_info'] = array(
  '#type' => 'fieldset',
  '#title' => t('Additional Information'),
  '#collapsible' => TRUE,
  '#collapsed' => TRUE,

  // Expand the expand_more_info fieldset if the box is checked.
  '#states' => array(
    'expanded' => array(
      ':input[name="expand_more_info"]' => array('checked' => TRUE),
    ),
  ),
);

```

Instead of that you can try it in another way which is mentioned below in hook\_form\_alter() function.

Example:

```
$form['more_info'] = array(
                          '#type' => 'fieldset',
                          '#title' => t('Additional Information'),
                          '#collapsible' => TRUE,
                          '#collapsed' => TRUE,
                     );

**$form['more_info']['und']['#states']**= array(
                                'expanded' => array(
                                 ':input[**name="expand_more_info[und]**"]' => array('checked' => TRUE),
                                ),
                             );

```

Note: you can use 'visible' instead of 'expanded'. you can try this in your custom module or template.php

# Answer
> 0 votes
You miss understand this concept, I think, In your code

```
$form['field_full_name'][LANGUAGE_NONE][0]['value']['#states'] = array(
    'visible' => array(
        ':input[name="field_person_type[und]"]'=> array(
            array('value' => 'Contractor'),
            array('value' => 'ICM'),
            array('value' => 'Member of public'),
        ),
    ),
);

```

you have written for, It means when the field "field\_persion\_type\[und\]" value is "Contractor or ICM or Member of public" then only the $form\['field\_full\_name'\]\[LANGUAGE\_NONE\]\[0\]\['value'\] field will be visible

```
$form['field_persion_type']['und'] = array(
  '#states' = array(
    'expanded' => array(
      // we could set with field id
      // '#id-of-field' => array('checked' => TRUE),
      ':input[name="field_full_name"]' => array('checked' => TRUE),
     ),
   ),
);

```

So now if the field\_full\_name selected the field\_persion\_type field will be expand..

---
Tags: javascript
---


title: Translate interface (export/import)

text:
# Question
Title: Translate interface (export/import)
I have two languages:

* french
* arabic

I want to completely translate the arabic interface. If there a way to export the englisch translations, add the arabic one and reimport the file?

# Answer
> 0 votes
It can be done using Translation template extractor module

> If you are a translator, install the module on a Drupal site as you would with any other module. Once potx module is turned on, you can go to the "Extract strings" tab on the Locale administration interface, select the module or theme you want to have a translation template for, and submit the form. You will get one single template file generated.

# Answer
> 0 votes
I didn't get you! You need to completely translate the Arabic interface? Add the Arabic language to your website then simply, download it's translation file and import it into `admin/config/regional/translate/import` . What is the problem?

# Answer
> 0 votes
Completely translating the Drupal "interface" in another language is a bit bizarre/strange (as confirmed also by some of the other answers already). Therefor it may help to correctly understand the various Drupal components related to 'translation', as further explained below.

Drupal's translation system consists of 2 basic components: the translation of the **interface** and the translation of the **content** of a site.

The **translation of the interface** is about the translation of various text strings used throughout the site, like labels used on buttons such as submit, or on tabs such as view or edit. They are the same on all sites (no matter what actual content is contained in a site).

The **translation of the content** is about the translation of nodes and entities. It requires a place to actually store the translated versions of the content (in multiple languages) and a system to choose which content is to be displayed where. The systems available for translation of content are:

* **Content translation** (used in earlier versions of Drupal, and still available in D7), which translates entire nodes in multiple languages.
* **Entity translation** (its API was first introduced in Drupal version 7, though there is no UI for it yet), which translates fields attached to the same entity.

Typical (often used) modules related to translations:

Modules to actually manage translations of nodes and/or entities:

---
Tags: i18n-l10n
---


# Question
Title: Pre-Built Theme, how to transfer header to blocks
I am moving at a glacial pace at theming, even following guides, because I think I am having trouble understanding the relationship between all parts of drupal theming. If someone can help me with the following issue, it should make me better understand how I am to configure everything else

Basically, I want to know the ideal way to theme this header which is static html to transfer into a block or a region so that I can theme it. I initially just included it using php include statements, but realize this is not good practice in drupal, and am looking for the proper way to do it.

```
        <div class="dropdown animated fadeInDown animation-delay-11">
            <a href="user" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-user"></i> Login</a>
            <div class="dropdown-menu dropdown-menu-right dropdown-login-box animated fadeInUp">
                <form role="form">
                    <h4>Login Form</h4>

                    <div class="form-group">
                        <div class="input-group login-input">
                            <span class="input-group-addon"><i class="fa fa-user"></i></span>
                            <input type="text" class="form-control" placeholder="Username">
                        </div>
                        <br>
                        <div class="input-group login-input">
                            <span class="input-group-addon"><i class="fa fa-lock"></i></span>
                            <input type="password" class="form-control" placeholder="Password">
                        </div>
                        <div class="checkbox pull-left">
                            <label>
                                <input type="checkbox"> Remember me
                            </label>
                        </div>
                        <button type="submit" class="btn btn-ar btn-primary pull-right">Login</button>
                        <div class="clearfix"></div>
                    </div>
                </form>
            </div>
        </div> <!-- dropdown -->

        <div class="dropdown animated fadeInDown animation-delay-13">
            <a href="/search/node" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-search"></i></a>
            <div class="dropdown-menu dropdown-menu-right dropdown-search-box animated fadeInUp">
                <form role="form">
                    <div class="input-group">
                        <input type="text" class="form-control" placeholder="Search...">
                        <span class="input-group-btn">
                            <button class="btn btn-ar btn-primary" type="button">Go!</button>
                        </span>
                    </div><!-- /input-group -->
                </form>
            </div>
        </div> <!-- dropdown -->
    </nav>
</div> <!-- container -->

```

Thanks for the help,

Matthew Beal

# Answer
Essentially you have the User Login & Search Form blocks so you could add the following to your themes' .info file:

```
regions[login] = Login
regions[search] = Search

```

Clear the site cache and visit your Blocks page (admin/structure/block) and you should see 2 additional regions. Place the User Login block in the Login region and the Search Form block in the Search region.

In `page.tpl.php` in your theme, use the following code:

```
<?php if (!empty($page['login'])): ?>
<div class="dropdown animated fadeInDown animation-delay-11">
  <a href="user" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-user"></i> Login</a>
  <div class="dropdown-menu dropdown-menu-right dropdown-login-box animated fadeInUp">
    <?php print render($page['login']); ?>
  </div>
</div> <!-- dropdown -->
<?php endif; ?>

<?php if (!empty($page['search'])): ?>
<div class="dropdown animated fadeInDown animation-delay-13">
  <a href="/search/node" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-search"></i></a>
  <div class="dropdown-menu dropdown-menu-right dropdown-search-box animated fadeInUp">
    <?php print render($page['search']); ?>
  </div>
</div> <!-- dropdown -->
<?php endif; ?>

```

This will give you a starting point and you can start overriding output in your theme by using functions and templates. It should be possible to achieve almost the exact code you're looking for.

You're obviously using Bootstrap, have you tried using the Drupal Bootstrap theme as a starting point?
> 0 votes

---
Tags: theming
---


# Question
Title: How can I consolidate the views that are auto generated by nodequeue
I'm using the nodequeue module to potentially create a large number of queues. With each new queue I create, a view is auto generated for that queue. Ultimately, I want to be able to access each queue as a view, but I'm wondering two things.

1. Are there performance implications to have in potentially hundreds of views created?
2. Isn't there a better way to display nodequeues in a view? why does there have to be a different view for each nodequeue ? isn't there a way to pass the relationship in through a contextual filter?

# Answer
> Are there performance implications to have in potentially hundreds of views created?

Views are just queries. If you're concerned about performance use `caching` in Views under the `advanced settings` for each view. There are contrib modules that enable caching for all views.

> Isn't there a better way to display nodequeues in a view? why does there have to be a different view for each nodequeue ? isn't there a way to pass the relationship in through a contextual filter?

Possibly, but then your view(s) would only be accessible from say 1 url via the contextual filter ... a freedom of the Page view provided by the nodequeue is that as a site builder you can define unique url routes per view.
> 0 votes

---
Tags: views, nodes
---


# Question
Title: Create marker from NID using IP Geolocation Views & Maps that is not affected by exposed filters
I'm using the IP Geolocation Views & Maps module to create a map for visitors to see different geotagged locations in a particular city. I am using the Leaflet display as I cannot use Open Layers due to the server using an older version of PHP.

The site is using 1 content type for "locations" and then uses taxonomy to separate the "types" ie - food, drink, car rental, etc.

I need to create an individualized reference point depending on the current node someone is looking at. If someone is looking at car rentals I need a pin for only that car rental location then show all other "types" around it with an exposed filter (food, drinks, etc) giving the user the ability to filter to see only food or only drink.

The view itself is a views page with a wildcard set in the url. I have a second view passing the node ID's for each location.

The issue I'm running into is when someone uses the filter I lose the existing node pin as it isn't part of the filtered content.

I've looked into changing the session variables for the "get my location" block via the current nodes longitude and latitude but ran into a problem with caching.

Is there a way to add a new marker to the existing IP Geolocation Leaflet map (via Jquery or otherwise) that would exist on a different layer and no longer be susceptible to any applied exposed filter?

# Answer
There is a hook provided in the ip\_geoloc.api.php file of the IP Geolocation module that allows you to make modifications (such as adding a point that doesn't exist in your query) to your current view.

The following would load your current nid, query for the particular longitude and latitude fields, then add the marker to the map.

```
function my_custom_module_ip_geoloc_marker_locations_alter(&$marker_locations, &$view) {

  // Need to get current node id to use longitude and latitude
  $param = arg(1);
  $node = node_load($param);
  $field_items = field_get_items('node', $node, 'field_geofield');
  $location = $field_items[0];

  // Machine name of your view goes in the line below.
  if ($view->name == 'map') {
    $curpos = new stdClass();
    $curpos->latitude = floatval($location['lat']);
    $curpos->longitude = floatval($location['lon']);
    $curpos->balloon_text = t('Your current location');
    $curpos->marker_color = 'white';

    array_unshift($marker_locations, $curpos);
  }
}

```
> 0 votes

---
Tags: views
---


# Question
Title: How can I exclude content older than... with Views
I'm trying to get my head around a Views setting, I can't find how to exclude older than two years old content from Views. I know it has to be somewhere in the Filter section. I would expect this to work, but it doesn't...

Content: Date (field\_publication\_date) - From date \<= now + 2 year

I'm doing something wrong, can someone please help me out?

Thanks a lot!

PS: I'm on Drupal 6...

# Answer
The Show nodes relative to a date with Views page explains how to do it. Did you try post date on *Filter criteria* with the following configuration?

?
> 1 votes

---
Tags: views, datetime
---


# Question
Title: How to export Panels Everywhere template code to a module
I would like to export a Panels Everywhere site template to code. I know you get some configuration code when you select the export tab, but I'm not sure how you turn that into a module that will generate the template with it's variants and layout on another environment.

# Answer
> 0 votes
You can try features module.

> The features module enables the capture and management of features in Drupal. A feature is a collection of Drupal entities which taken together satisfy a certain use-case.
>
> Features provides a UI and API for taking different site building components from modules with exportables and bundling them together in a single feature module. A feature module is like any other Drupal module except that it declares its components (e.g. views, contexts, CCK fields, etc.) in its .info file so that it can be checked, updated, or reverted programmatically.

the features module converts every entity (views, content types, ...) in to a module and it can easily be installed and modified every where.

# Answer
> 0 votes
Actually there are 2 ways to do that.

1. You can featurize your panel and realted plugins(mini panels, snippets, custom content etc.) into it using features module. By this method you will get a module which you can place anywhere in your other instance and you will get all the things which you have added to it. More specifically when you create a new feature there are configuration on RHS (page manager, minipanels etc.)
2. Direct export the panel page and other things which are in your panel page. using the export feature in your panel page itself. Click on export tab and copy the code and go to structure -\> pages -\> import page and paste the code there. You will have that panel page create in your another instance.

But the best practice I will recommend you should use features module on other side if you have to things quickly use the second approach.

---
Tags: panels
---


# Question
Title: how to implement facet search api on content types feilds?
Is it necessary to build taxonomy for each field of content type to show it in search option in sidebar in facet search api ?

# Answer
> 0 votes
Just follow the steps here and you will be done. https://beautiful7mind.wordpress.com/2013/03/10/step-by-step-how-to-implement-facet-search-on-data-in-drupal-7/

---
Tags: taxonomy-terms, nodes, search
---


# Question
Title: How to disable the number that the Email Registration module puts on peoples username on registration
I'm working with the email registration module and everywhere I look it says that it just uses everything before the @ sign for the username. However it adds and underscore and some number to every username. I'm not very familiar with php so if someone could tell me to disable this it would be much appreciated.

# Answer
I have figured out my own problem. The module has a double fail safe for there not being duplicate usernames. Every time a new account is created it adds the uid to the end of the username so that there would be no duplicates, but if there was still a duplicate it will append a 1 or 2 on the end. Since the odds of there being 2 identical usernames from emails I am just commenting out where it adds the uid and going with just the appending a number if it ever does happen. Here is the code I commented out:

```
/* 070715 AS commented this out so the user id is not concatenated to the end of the user name,
this is just guaranteeing that no 2 people have the same username which has odds so small
we aren't going to worry about it.
  if (!empty($uid)) {
    // Put uid on the end of the name.
    $name = $name . '_' . $uid;
  }*/

```
> 1 votes

# Answer
I missed that, I remember from your question that you were removing numbers as well. BTW rather hacking this contrib module you can implement a simple hook exposed by this module i.e. hook\_email\_registration\_name,an example would be

```
function my_modulename_email_registration_name($edit, $account) {
  // Logic to return username, an example would be following.
  return 'u' . $account->uid;
}

```

replace my\_modulename with your actual module name.
> 0 votes

---
Tags: 7
---


# Question
Title: Drupal 7 Commerce - How would you increase or decrease a checkout total price depending on payment type?
I want to be able to provide alternative payment methods during checkout, but I also want to be able to discount or add on top of the total checkout price by a percentage depending on what the user chooses to pay with. How can this be done? I know you would use rules, but which sections would i need to edit?

\** edit - I was able to edit up the the "pricing rules" page, but now i get an error for Order Total. I want to be able to mutltiply the order total as seen below. I'm not sure what to put after the colon : of order total.

# Answer
> 0 votes
In the checkout methods rules you should be able to add an action that decreases the total or subtotal cost. So when a certain payment method is used, the subtotal will decrease.

If one of those rules actions isn't available you might need to look at some other modules like Commerce Rules Extra.

Another option would be to apply coupons automatically to orders with those selected payment methods with the Commerce Coupon and Commerce Coupon Fixed Amount modules. That might give you better control over how many times a user or how many users can use a discount like this.

# Answer
> 0 votes
With Commerce Fees, you can add fees to a order, use the event and action that the module provides.

---
Tags: 7, commerce
---


title: Term reference redirect after node save

text:
# Question
Title: Term reference redirect after node save
i am new to Drupal. I have few nodes with term reference. After creating nodes with term reference, i want to redirect user not on created node, but on term page. Is this possible?

# Answer
> 0 votes
You can set redirect state for your node form. For example

```
function my_module_form_alter( &$form, &$form_state, $form_id ){
  if($form_id == 'your_node_form_id') {
    $form['actions']['submit']['#submit'][] = '_mymodule_node_redirect';
  }
}

/**
 * Custom Submit Handler to set conditional redirection rule.
 */
function _mymodule_node_redirect($form, &$form_state) {
  // If terms are already in the system.
  if($form_state['values]['your_taxonomy_field']['und'][0]['tid'] ==  'tid_to_compare_with') {
    $form_state['redirect'] = 'whereever you want';
 }
}

```

---
Tags: redirection, taxonomy-terms
---


# Question
Title: How can I allow users to send private messages without revealing sender's address?
I have a community application which allows users to send private messages and it is built using 'Private Message' module. When a message is sent, the recipient sees the sender's original email address which he has used to register with the system. I would like to use a system generated email address without revealing sender's original email address.

# Answer
The 7.x-1.x branch of Private Message has this setting in the PM Email Notify submodule. When enabled, there is a *E-mail notify* tab on the settings page (**/admin/config/messaging/privatemsg**) that allows you to configure the email's from header.

By default, if this is blank, it will use the site's default system email. It sounds like the module is configured with another token that's referencing the sender's init email.
> 2 votes

---
Tags: privatemsg
---


# Question
Title: Migrate fields with content from drupal 6 from different DB
Can't understand how migrate node fields from different DB (I mean migration to clear drupal 7 site). At first, I migrate fields by content migrate module but in this case db contain too much garbage. Tried to it by migrate module but didn't find how to do this. Then I used migrate\_d2d module, but it doesn't help at all.

Is there way to migrate fields and content without writing by hand each field migration?

# Answer
If by "writing by hand" you mean writing PHP code, then the answer is no. The migration module is a migration framework; it provides the tools (API, PHP classes, etc) to migrate data but it doesn't do it for you. Migrate D2D (built off the Migration framework) *provides some support* with "out of the box" importing (e.g. User Roles, Pics, Taxonomy, etc.), but it doesn't do it all for you.

The key thing to understand is complexity of the problem; content in Drupal can be configured in a myriad of different ways. As such, one module that can handle all the different permutations of sources (e.g. CSV, WordPress site, various DB's, & an old Drupal install), field configurations (e.g. ints, floats, text, custom objects, custom fields, module create fields), & destinations (e.g. custom node types, module-create node types, custom entities, etc.) is a mammoth task for an open-source project.

Instead, the Migration & Migrate D2D maintainers have made the problem more tractable. They've provided some common tools that are likely to be used in *any Drupal migration*. Filling in the last bit of details (e.g. should a phone field be mapped to an address field or as a text field) is up to you because only you can possible know that information and how it's used.
> 0 votes

---
Tags: 7, migrations
---


title: Drupal and node.js configuration

text:
# Question
Title: Drupal and node.js configuration
I have a problem with *Nodejs* and *Rules action with node.js* modules

First, I have installed node.js on my server following the README.txt instructions and then configured the node.config.js file as the sample file and had no problem connecting Drupal with node.js. But after creating a rule of new nodes, I checked messages like this in the debugger:

```
Started http server.
   info  - socket.io started
publishMessageToContentChannel: message { uniqid: '520d016b52adc',
  markup: '<div class="rules-message">\n  <div class="close-button"></div>\n
<div class="body">\n    <div class="subject">\n      TEST TITLE    </div>\n
value of body action message  </div>\n</div>\n',
  callback: 'nodejsAction',
  messageAuthorUid: '1',
  channel: 'rules_nodejs_role_2',
  clientSocketId: '' }
publishMessageToContentChannel: message { uniqid: '520d016b52adc',
  markup: '<div class="rules-message">\n  <div class="close-button"></div>\n
<div class="body">\n    <div class="subject">\n      TEST TITLE    </div>\n
value of body action message  </div>\n</div>\n',
  callback: 'nodejsAction',
  messageAuthorUid: '1',
  channel: 'rules_nodejs_user_3',
  clientSocketId: '' }
publishMessageToContentChannel: The channel "rules_nodejs_user_3" doesn't exist.
publishMessageToContentChannel: message { channel: 'watchdog_dblog',
  commands:
   [ { command: 'insert',
       method: 'before',
       selector: '#admin-dblog tr:eq(1)',
       data: '<tr class="dblog-content dblog-notice"><td class="icon"></td><td>content</td><td>08/15/2013 - 12:27</td>
          <td>page: added <em class="placeholder">node 18</em>.</td><td><a href="/user/1" title="View user profile." class="username"
          xml:lang="" about="/user/1" typeof="sioc:UserAccount" property="foaf:name" datatype="">admin</a></td><td><a
          href="/node/18">view</a></td></tr>',
       settings: null } ],
  callback: 'nodejsWatchdog',
  clientSocketId: '' }
publishMessageToContentChannel: The channel "watchdog_dblog" doesn't exist.
setContentToken: message { token: 'Xx0RmC36fXFTnyH_goIX21fP-2iDJMhTk_u-iWBpcM4',
  channel: 'rules_nodejs_user_1',
  notifyOnDisconnect: false }
setContentToken Xx0RmC36fXFTnyH_goIX21fP-2iDJMhTk_u-iWBpcM4 for channel rules_nodejs_user_1
setContentToken: message { token: 'u3EbOVHjEdIiL6mlGbN8p4T5CifL2Gt-tZc2jfqfbCE',
  channel: 'rules_nodejs_role_2',
  notifyOnDisconnect: false }
setContentToken u3EbOVHjEdIiL6mlGbN8p4T5CifL2Gt-tZc2jfqfbCE for channel rules_nodejs_role_2
setContentToken: message { token: '9WLPPJWOr7XlMXLYbhhiuBvMwN4Bd4o9_6exS-_cspU',
  channel: 'rules_nodejs_role_3',
  notifyOnDisconnect: false }
setContentToken 9WLPPJWOr7XlMXLYbhhiuBvMwN4Bd4o9_6exS-_cspU for channel rules_nodejs_role_3

```

However, I couldn't get the notifications on my browser and I don't know if I'm missing some extra configuration for it.

# Answer
> 0 votes
noddejs module is hard to configure and make it work as it is under development and not stable yet (I tried personally)

take a look at tha sandbox project it may help nodejs-chat-d7

---
Tags: rules, notifications
---


# Question
Title: Is necessary any sanitization functions if I use the database layer correctly
In Writing secure code said:

> Use the database abstraction layer to avoid SQL injection attacks

Then, my question:

When I get value for a user form is necessary pass to check\_plain() or others sanitization functions, before I use the database layer correctly.

# Answer
> 0 votes
The db abstraction layer, as you noted, should prevent SQL injection attacks.

Check\_plain is actually used to make sure text is html safe. If your printing out user submitted data to the screen, it should (at some point) be run through check plain to guard against cross site scripting attacks.

---
Tags: database, security
---


title: Create Entity bundles programmatically

text:
# Question
Title: Create Entity bundles programmatically
The Paragraphs module seems great, but it does not provide any API (I looked at the source). So I think that will be enough to use Drupal API and/or Entity API.

About this module: it provides a new entity type 'Paragraph' and field with same name. User can create via UI 'Paragraph types' (bundles) with fields and view display settings like node entity.

**My question**: What's the right way to define bundle type for this entity type with custom fields in a custom module?

I think I must create fields first, using field\_create\_field() and field\_create\_instance() in hook\_enable(). But what's next?

I must create bundle for paragraphs entity and attach created field, but I don't know how and any searches always send me to documentation about how programmatically create entity itself.

# Answer
There is more easy way to do this: Use the module functions.

paragraphs.module contain these functions:

```
/**
 * Implements hook_install().
 */
function MYMODULE_install() {
  // Create new Bundle.
  $bundle = new stdClass();
  $bundle->name = 'Test Bundle'; // user friendly label
  $bundle->bundle = 'paragraphy_test'; // machine name
  $bundle->locked = 0;
  $status = paragraphs_bundle_save($bundle);
}

```
> 3 votes

---
Tags: entities
---


# Question
Title: Connecting to external oracle database using db_set_active in settings.php not working
In DRUPAL7 i am trying to connect to oracle external db using `db_set_active('ora_db')`. here is my code snippet in settings.php. i am not sure where i am going wrong. when i try `oci_connect('uname','pass','db_name/service_name')` it works fine in my drupal page. but when i try using drupal way to connect oracle db it's not working.

Note: just for database connect i don't want to use other modules

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'db_name1',
      'username' => 'xxxx',
      'password' => 'xxxx',
      'host' => 'host1',
      'port' => '3306',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  'mportal' =>
  array(
    'default' =>
    array (
      'database' => 'db_name2',
      'username' => 'zzzzz',
      'password' => 'zzzzz',
      'host' => 'host2',
      'port' => '3306',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
'ora_db' =>
    array(
    'default' =>
        array (
        'database' => 'ora_dbname',
                'username' => 'yyyyyy',
                'password' => 'yyyyyy',
                'host' => 'ora_db_host_name/service_name',
                'port' => '1521',
                'driver' => 'oracle',
                'prefix' => '',
            ),
    ),
);

```

Thanks in Advance.

# Answer
> 0 votes
Drupal core doesn't have an Oracle driver, so you can't use the API with an Oracle database unless you install a module (or find another way to introduce the code, but it would be counter-intuitive not to use a module).

The Oracle Driver module provides what you need, if you don't want to install it you're stuck using `oci_connect` etc.

---
Tags: 7, configuration, database
---


# Question
Title: Pre-select language (instead of "Language neutral") when creating a node?
With core's *Locale* module you can enable *Multilingual support* for a content type. When creating/editing a node, this gives you a *Language* select list with all enabled languages and "Language neutral" as options.

The default (resp. first) value for this select list is always "Language neutral".

Is it possible to have a certain language as default value instead?

At best it would be a per-content-type setting, but I'm fine with a global one, too (e.g. always using the site-wide default language as default value).

# Answer
> 2 votes
The option for it is available in **admin/config/regional/entity\_translation**

* The Entity Translation configuration page provide an interface to select default language for all content types separately

# Answer
> 0 votes
Of course you can do what you want. You should install the next module: internacionalization. This module will give you a better support for the content translation.

Instructions:

1. You will have to enable the following modules in the packet internazionalization:

* Internationalition module
    * String translation
    * Multilingual content.
2. You will find in the content types a new vertical tab called multilingual settings. There you can configure the content type like you want.

# Answer
> 0 votes
We have different environments we push our configurations through, so I chose to codify this into the hook\_enable() of one of my modules like this:

```
// Implements hook_enable().
function MY_MODULE_enable() {
    // Ensure that "entity translation" is setup so that my content item defaults to "EN"
    // instead of "Language Neutral" @see /admin/config/regional/entity_translation
    if (module_exists('entity_translation')) {
        $variable_for_entity_trans_nodes = 'entity_translation_settings_node__CONTENT_TYPE';
        $trans_settings = variable_get($variable_for_entity_trans_nodes);
        $trans_settings['default_language'] = 'en';
        variable_set($variable_for_entity_trans_nodes, $trans_settings);
        watchdog("MY MODULE NAME", "Setting 'default_language' of '@variable' to 'en' at /admin/config/regional/entity_translation", array("@variable" => $variable_for_entity_trans_nodes), WATCHDOG_DEBUG);
    }
}

```

You'll need to update the things CAPITALIZED to suit.

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


title: Stop TinyMCE from applying styles

text:
# Question
Title: Stop TinyMCE from applying styles
I am building a Drupal 7 boostrap subtheme. I don't want users to be able to add their own fonts and styles to content. I want to force them to use the paragraph and heading tags as defined in my site's CSS.

When users paste in from other sources (eg word) I do not want the styles brought in. Additionally, our site uses Open Sans. This is not appearing in the TinyMCE font list, can this be fixed?

How does one do this with TinyMCE?

# Answer
> 0 votes
I had the same issue with CKEditor. the `h1,h2,h3,h4,h5,p` tags and color picker were available to the user But we wanted every available tag to has a custom color. To do so I put the CKEditor output which was `body` inside a `DIV` with some ID,say `node-body-wrapper`, then added styles like this

```
#node-body-wrapper h1{
     color : red !important;
}

...

```

In this way I solved the problem. I recommend you to do the same.

---
Tags: 7, wysiwyg
---


# Question
Title: How do I programmatically add a field to a Transaction in Drupal Commerce?
I am attempting to add a field to the entity commerce\_payment\_transaction. However, when I check the database after installation which should create the field, there is no field\_data\_ created, nor is there any field on the entity commerce\_payment\_transaction. I have successfully used code similar to the following to create field on the Commerce Order. Do I have the bundle wrong for the instance?

Here is my code.

During the install, I create the field and its instance.

```
function commerce_stripe_connect_c_install_install() {

$field_info = field_info_field('tr_vendor_user_reference');

$field = array(
        'field_name' => 'tr_vendor_user_reference',
        'type' => 'user_reference',
        'cardinality' => 1,
        'entity_types' => array('commerce_payment_transaction'),
        'translatable' => FALSE,
        'settings' => array(
                //must have the referenceable_status defined or the user reference won't work
                'referenceable_status' => array(
                        0 => 0,
                        1 => '1',
                ),
        ),

);

if (empty($field_info)) {
    field_create_field($field);
}

$instance = field_info_instance('commerce_payment_transaction', 'tr_vendor_user_reference', 'payment_method');

//I check if the vendor_user_reference has already been created on the commerce_product
if (empty($instance)) {
    $new_instance = array(
            'field_name' => 'tr_vendor_user_reference',
            'entity_type' => 'commerce_payment_transaction',
            'bundle' => 'payment_method',

            'label' => t('Transaction Vendor User Reference'),
            'required' => TRUE,
            'settings' => array(
                    //This is required so that vendors will be available for programmatically selecting
                    //for a product
                    'referenceable_status' => array(
                            0 => 0,
                            1 => '1',
                    ),

                    'view' => array(
                            'args' => array(),
                            'display_name' => '',
                            'view_name' => '',
                    ),

            ),
            //The widget will not show up because it is hidden later on, but this is needed so that
            //a default value can be chosen
            'widget' => array(
                    'active' => 1,
                    'module' => 'options',
                    'settings' => array(
                            'apply_chosen' => '',
                    ),
                    'type' => 'options_select',
                    'weight' => '40',
            ),

            'display' => array(),
    );
    field_create_instance($new_instance);
}

```

# Answer
The payment transaction entity type isn't field-able (see commerce\_payment\_entity\_info()).

But you can change that with hook\_entity\_info\_alter():

```
function MYMODULE_entity_info_alter(&$info) {
  $info['commerce_payment_transaction']['fieldable'] = TRUE;
}

```
> 2 votes

# Answer
There are a few things that you need to do to add a field to a transaction

1) set the `commerce_payment_transaction` to fieldable as mentioned above by Clive.

2) You will need to separate the the implementation of `function MYMODULE_entity_info_alter(&$info)` from your field definition if you put your field definition in the `.install` file. This is because the install function is run before the `.module` file

3) When defining your field in `hook_install`, you will need to set the bundle on the instance to the payment method id that you are using. In my code above, I had used `'bundle' => 'payment_method'`. It needs to be the payment\_method identifier. This is the same value you use when creating a new transaction using `commerce_payment_transaction_new`

As an aside, in my above example I used a user\_reference type. If you are using this on your transaction, when you want to set the value for the transaction, you do the following:

```
$transaction->tr_vendor_user_reference['und']['0']['uid'] = $your_uid_as_integer

```
> 1 votes

---
Tags: commerce
---


# Question
Title: Installing and Running Drupal in Subfolder - Beginner
I am trying to do a redesign on a drupal site. I added a subfolder via an ftp client (example.com/devsite) and manually uploaded the extracted drupal7 files. One would think that going to example.com/devsite or example.com/devsite/install.php would be the next step in accessing the subfolder files, but im only getting 404/page not found error messages when i navigate to this URL.

I'm new to drupal and feel like this should be an easy fix...but dang is it frustrating. HELP!

I have read "How to get Drupal 7 installed in a sub-folder / sub-directory properly?" already - i'm having a difficult time deciphering what steps to take from this post. I need the original site example.com to be live, but example.com/devsite to be viewable as well.

# Answer
> 0 votes
> I have read "How to get Drupal 7 installed in a sub-folder / sub-directory properly?" already - i'm having a difficult time deciphering what steps to take from this post.

Your problem is not a Drupal problem. It is a file permissions problem. It is probably caused by you using ftp to create the sub-direactory to hold Drupal.

> but im only getting 404/page not found error messages when i navigate to this URL.

This means that the the directory you've created with ftp, and/or the files you've uploaded in that directory is *not readable* by the webserver user.

If you have access to the command line interface (CLI), you may need to use *chown* to make sure the Drupal directory and files are owned by the webserver user, or at least use *chmod* to make sure they're readable by the webserver user.

However, since you use ftp, I assume that you have not CLI access to your installation? In that case, you need to contact customer support at your hosting provider to learn what tools exist to change the read permissions of files and directories to be readable by the webserver user.

> this post lost me at " I already modified the .htaccess in the parent drupal installation to ignore the sub-folder and i also set the $base\_url in the sub-directory drupal installation."

That is just noise in the question. You need to read the *upvoted answer* to that question for the solution.

In fact, you should ignore *all* the stuff about modifying `.htaccess` in the duplicate issue. I am no idea why the person who wrote it believes this is relevant. Each Drupal installation has its own `.htaccess` in its own directory, and the one that comes with Drupal is fine provided you do a clean install. The simple fact is that there is *nothing* special about installing Drupal in a subfolder. You need to get the directory and file permissions correct tho' - and using ftp to set things up may have caused the permissions to be wrong.

---
Tags: installation
---


title: Naming a template file

text:
# Question
Title: Naming a template file
D7, bartik. A comment form is created by an .inc file *(modulename.page.inc)*.

This comment form is to comment on existing comments.

To create the comment form, the inc page says:

```
function _modulename_comment_post_form($form_state, $args, $nid, $uid) {
global $base_url;
// Comment display form.
...
}

```

Assuming this is the proper way to create the form, how do I select a name for a template file to theme it?

***comment.tpl.php*** and ***comment-wrapper.tpl.php*** have no effect on it. Themer devel and theme\_debug do not suggest any name for it either.

Thanks. :)

**UPDATE:**

Here is what I have now in my *template.php* file:

```
function stella_theme($existing, $type, $theme, $path) {
$item = array();
// Comment form.
$item['profile_wall_post_comment_form'] = array(
   'arguments' => array('form' => NULL),
   'render element' => 'form',
   'template' => 'templates/profile-wall-post-comment-form',
   'preprocess functions' => array(
      'stella_preprocess_profile_wall_comment_form'
      ),
   );
return $item;
}

```

Then, I have a *profile-wall-post-comment-form.tpl.php* file in my templates directory.

Regardless of what I put in the template file, it doesn't show on the comment form. And theme\_debug does not pick up the form. All caches have been cleared (more than once.)

A problem with the path? I tried:

```
'path' => drupal_get_path('theme', 'stella') . '/templates',
'template' => 'profile-wall-post-comment-form',

```

But to no avail.

What am I doing wrong? Any other idea? Thanks. :)

# Answer
You need to understand hook\_theme().

```
function stella_theme($existing, $type, $theme, $path) {
  $theme = array();
// Comment form.
//key comment_form is mean exited function theme
// if key is exited this array will overwrite it.
// You can replace key comment_form with comment_form____node_[CONTENTYPE]
  $theme['comment_form'] = array(
    'arguments' => array('form' => NULL),
    'render element' => 'form',
    'template' => 'templates/profile-wall-post-comment-form',
  );
  return $theme;
}

```

What Niklan means is that you can replace the template with the name you want, but I think it is better you create a comment-form--node-\[content-type\].tpl.php file. When you see file you know theme for comment form. And in file tpl use can user this function to show struct your form.

```
<?php
dpm($form)
?>

```

after you can print with function drupal\_render for element form.

```
<?php print drupal_render($form['author']['name']); ?>

```

end file you need print this function

```
<?php print drupal_render_children($form); ?>

```
> 1 votes

# Answer
* **comment.tpl.php** \- for comments itself.
* **comment-wrapper.tpl.php** \- wrapper for comments.

You can also use hook\_theme() and define template for comment form. F.e. in template.php

```
/**
 * Implements hook_theme().
 */
function THEMENAME_theme() {
  $theme = array();
  // Comment form.
  $theme['comment_form'] = array(
    'arguments' => array('form' => NULL),
    'render element' => 'form',
    'template' => 'templates/comment-form',
  );

  return $theme;
}

```

Then in templates create file **comment-form.tpl.php** and you'll be able to theme form for comments like you want. P.s. you can name it as you like.

If you done see any effect after create this files, make sure you cleared all caches.
> 1 votes

---
Tags: theming
---


title: call external form in ajax callback

text:
# Question
Title: call external form in ajax callback
I have two forms (A & B) in custom module. Form A containing three fields(each field is dependent drop down) and Form B containing only one field (markup field to show data). The problem is that when I change either field from Form A then its dependent fields within form A an also markup field from Form B should be updated via ajax.

Here is the callback function used in FORM A. After calling, it returns fields from Form A. But I want it also return field of FORM B. (One Callback to render two forms at a time)

```
<?php
 function mymodule_ajax_callback($form, $form_state) {
     return array(
        '#type' => 'ajax',
        '#commands' => array(
            ajax_command_replace("#key_wrapper", render($form['keys'])),
            ajax_command_replace("#display_wrapper", render($form['display'])),
        ),
     );
 }
?>

```

# Answer
I have solved the problem with help of little js snippet. I attached a js file to form and got my charming work.

```
(function($, Drupal)
 {
  function selectAListener()
   {
   // $("edit-term") is our select element in form A
    $("#edit-term").once("select-a-listener", function()
     {
     // $(this) refers to $("edit-term")
      $(this).change(function()
       {
        // $("edit-termh") is our select element in form B
        // $(this) refers to $("edit-term")
        // We need to set the value of the select element in
        // form B, then call $.change() which will trigger the #ajax
        $("#edit-termh").val($(this).val()).change();
       });
     });
   }

   function selectBListener()
   {
    $("#edit-chld").once("select-b-listener", function()
     {
      // $(this) refers to $("edit-select-a")
      $(this).change(function()
       {
        // $("edit-chldh") is our select element in form B
        // $(this) refers to $("edit-chld")
        // We need to set the value of the select element in
        // form B, then call $.change() which will trigger the #ajax
        $("#edit-chldh").val($(this).val()).change();
       });
     });
    }
Drupal.behaviors.formExample = {
      attach:function()
      {
       selectAListener();
       selectBListener();
       }

}}(jQuery, Drupal));

```
> 0 votes

# Answer
You can use..

```
function custom_conditional_form($form, &$form_state) {
  $form['form1']['drupal_love'] = array(
    '#title' => t('Do you love Drupal?'),
    '#type' => 'radios',
    '#options' => array('yes' => t('Yes'), 'no' => t('No')),
  );
  $form['form1']['how_much_love'] = array(
    '#title' => t('Great! Tell us more:'),
    '#type' => 'textfield',
    '#states' => array(
      'visible' => array(
        ':input[name="drupal_love"]' => array('value' => 'yes'),
      ),
      'required' => array(
        ':input[name="drupal_love"]' => array('value' => 'yes'),
      ),
    ),
  );
  $form['form1']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
  );

  return $form;
}

```
> 0 votes

# Answer
you could look at implementing something like Block Refresh

```
Block Refresh allows an administrator to configure a block to refresh it's content via 3 different methods: automatically via a timer (eg every 30 seconds) , manually via a 'refresh' link, and once on page load.

Block Refresh uses jQuery/AJAX so the refresh happens "behind-the-scenes".

Block refresh can be handy to serve fresh content in certain blocks on otherwise cached pages. You can opt to bypass drupal's cache for the refresh callbacks for each block.

```

I have used this with a bit of jQuery like this:

* set it up to use a link
* a link will appear on the block which is ugly, use some css to hide it (display:none)
* use a simple jQuery onChange() to force the link to activate

```
jQuery('#selector').onChange(function(){ jQuery('#refresh').click(); });

```

The specifics would depend on block names, etc.
> 0 votes

---
Tags: forms, blocks, ajax
---


# Question
Title: How to set value to auto-complete field after form submission?
I have a dependent auto-complete form field in my custom module. After submission the form the auto-complete field shows above the result output. Now I want that submitted value should become default value after form submission. I tried like this:

```
'#default_value' => isset($form_state['values']['keys']) ? $form_state['values']['keys'] : '',

```

but not getting any value. I also tried like this:

```
'#default_value' => isset($_REQUEST['keys']) ? $_REQUEST['keys'] : '',

```

but still unable to get any value. someone please help.

# Answer
> 1 votes
Finally I found the solution myself. I simply got a value from URL like this:

```
'#default_value' => (arg(3)!= 'none') ? arg(3) : '',

```

---
Tags: forms, ajax
---


# Question
Title: Move timezone field in user/%/edit field
I want to move timezone field in `user/%/edit` form. I have used`$form['#weight']` in `hook_form_alter()` and `$page['#weight']` in `hook_page_alter()`, but not working.

# Answer
The next snippet should work

```
<?php

function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_profile_form') {
    $form['#after_build'][] = 'MYMODULE_user_profile_form_pre_render';
  }
}

function MYMODULE_user_profile_form_pre_render($form) {
  $form['timezone']['#weight'] = -10;
  return $form;
}

```
> 0 votes

---
Tags: users, forms, theming
---


title: Edit theme login page

text:
# Question
Title: Edit theme login page
I'm using a theme called Nexus.

Now in the login page, /?q=user, it looks somewhat like this:

All I want to do is change the order of the tabs, where "Log in" is in front, number one, then Request new password, then lastly Create new account.

Aka: \[Log in\]\[Request new password\]\[Create new account\]

I've tried looking in the theme's folder, including page.tpl.php, and in the user module files to see if I could find where it was defined/rendered but I couldn't find anything. This also did not seem to be what I wanted.

Sorry for being such a noob.

# Answer
You may use hook\_menu\_alter function to do it

```
/**
 * Implements hook_menu_alter.
 */
 function MYMODULE_menu_alter(&$items) {
   $items['user/login']['weight'] = 0;
   $items['user/password']['weight'] = 1;
   $items['user/register']['weight'] = 2;
 }

```
> 1 votes

---
Tags: 7, users
---


# Question
Title: Taxonomy drag and drop for only 2 levels
I've created a vocabulary, I can add terms but I want to "configure" this taxonomy to add terms with only 2 levels.

I'm talking about the default table that show my vocabulary terms (drag and drop system). How can I make it set only a term and sub-terms (disable sub-sub-...-subterms)?

I've tested the select module but as long as I can add multiple hierarchic terms, the select module add them as well, so it's not the solution

Thank you all

# Answer
> 2 votes
The theme function `theme_taxonomy_overview_terms()` drives the taxonomy overview table you're describing. The Drupal API function `drupal_add_tabledrag()` has an 8th parameter `$limit` that specifies the maximum depth of hierarchy. If it's set to 1, it will do what you describe.

In your theme, you can override `theme_taxonomy_overview_terms()` so the `$limit` is to 1. In order to do this.

1. Copy `theme_taxonomy_overview_terms()` to your theme's **template.php**.
2. Rename the function to `MYTHEME_taxonomy_overview_terms` in your **template.php**.
3. Alter the line `drupal_add_tabledrag('taxonomy', 'match', 'parent', 'term-parent', 'term-parent', 'term-id', FALSE);` so that the 8th parameter is 1 (i.e. change it to `drupal_add_tabledrag('taxonomy', 'match', 'parent', 'term-parent', 'term-parent', 'term-id', FALSE, 1);` )
4. Flush your theme cache to pickup the updated taxonomy overview page.

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


# Question
Title: Unable to retrieve node object in a block without access permission to said node
I'm trying to do a little statistics on nodes and display it on a block. I utilized `menu_get_object('node', 1, $path)` to get the node object of those nodes with the properties that I want.

So my problem is, in admin accounts, this works fine and well. however, in a normal user account, `menu_get_object('node', 1, $path)` returns null for any node that the normal user has no access to. is there any way to circumvent this?

So far I've tried using `node_load()`, and I also tried putting all the data analysis code inside a `hook_cron()`. Neither worked.

Using `db_query()` is not an easy task either, as I'm trying to obtain the node's parent node,and that parent's node parent node. That data is serialized. If it matters, I'm using Open Atrium, and I'm trying to obtain the topmost Space for a particular node.

# Answer
What you can do is impersonate another user for a while. More details here https://www.drupal.org/node/218104

At the start of the function:

```
$session_prev_status = drupal_save_session();
drupal_save_session(FALSE);
global $user;
$actual_user = $user;
$impersonated_user = user_load(1); // This will impersonate user 1, an administrator.
$user = $impersonated_user;

```

Then, at the end of the function:

```
$user = $actual_user;
drupal_save_session($session_prev_status);

```
> 1 votes

---
Tags: users
---


# Question
Title: Creating a shortcut to a listing of a specific content type or a set of specific nodes
I want to create a shortcut that acts similar as when you click the "Content" link. But I want to be able to display only a specific content-type or probably a specific set of nodes.

Is this possible weather by coding or through a module?

# Answer
You can do it with the Views module and some additional extensions.

The easiest way to do it is to install the Administration Views module (and all of its dependencies). It provides administrative lists just like you get from Drupal core, except they're built using Views.

Once you have that installed, go to /admin/structure/views. Clone the "Administration: Nodes" view provided by Administration Views, change the node type filter to be fixed instead of exposed, change the system path setting (eg. /admin/content/my-node-type) and save it.

That should be all - let me know if I messed a step or if something is unclear.
> 2 votes

# Answer
The Views module will facilitate what you're asking. You want to create a page view of nodes, in a table format, filtered by the criteria you want (e.g. node type), and set with page path. Once you have page path, you can add a shortcut to that path.
> 0 votes

---
Tags: nodes, users
---


# Question
Title: Site Down for few minutes after clearing cache
My site is going down every time whenever I am clearing the cache. Site will works again in 5-10 minutes after refreshing web page 2-3 times. Also I am getting 500 internal server error after clearing the cache. After refreshing web page 2-3 times site is working fine as before. Additional information as follow.

* Drupal 7
* Boost
* APC
* Apache web server

Can any one put some light on above issue.

# **Edited**

**Apache error logs** \[Tue Jul 07 08:51:12 2015\] \[warn\] mod\_fcgid: read data timeout in 40 seconds, referer: xxxxxxxxx.com

\[Tue Jul 07 08:51:12 2015\] \[error\] \[client xx.xx.xx.xx\] Premature end of script headers: index.php, referer: xxxxxxxxx.com PHP Warning: Module 'apc' already loaded in Unknown on line 0

\[Tue Jul 07 08:51:18 2015\] \[warn\] mod\_fcgid: process 26541 graceful kill fail, sending SIGKILL PHP Warning: Module 'apc' already loaded in Unknown on line 0 PHP Warning: Module 'apc' already loaded in Unknown on line 0

# Answer
Have you installed "**Memcache**" module ? If no then :

First of all, check mysql slow query log. Also install "Memcache" module which will help you to reduce mysql server load.

Please refer this link for Drupal Memcache installation.
> 1 votes

---
Tags: caching
---


# Question
Title: Content type which contains a content creation as a slip form
I'm quite new to Drupal and I've encountered a quite complicated problem.

I've created a role called "**Event coordinator**" authorized to create a content type entitle "**Events**" that has a title and and a description, and for which comments are disabled. Here is a sample of it:

* Title: "Join Our Club".
* Description: "It will be fun".

I've also created another role called "**Audience**" which will be used by the user who will attempt to join the event detailed in the content created by the "Event coordinator".

The "Audience" should create a "**Slip**" content which will have a request message. And it should be sent to the targetted "Events".

A "Slip" that gets created will be put (somehow) in another content which is the "Events". The "Event coordinator" then will choose whom will join an event based on the "Slips" that were created.

Only the "Event coordinator" and the owner of a slip (created by "audience") will be able to see a "Slip".

I've tried to use the "entity-registration" but it's not that flexible. I mean as an "Event coordinator" I'm not able to see all the "Slips" from all "Events" I created. It will just show the "Slips" when you view the content of a single "Event".

Any suggestions about which module(s) I could use to implement this?

# Answer
> 0 votes
Consider using a combination of the Rules and Flag modules. Some more details about how to use these modules in this case:

* To create a "slip", just implement that using a "flag" (used for content type = "Event"), via which "Audience" can indicated something like "I would like to attend".
* Whenever an Event gets flagged by a user, use the Rules module to notify the Event coordinator, by sending an appropriate eMail. As an alterative, create a view (using the Views module), that lists all "flagged events".
* "Event Coordinators" should be authorized to see all "flagged" Events, while a user who flagged an event can only see which events that user flagged (not which events were flagged by some other user).
* After the "Event Coordinator" reviews a flagged event (= Request to attend) and decides to approve it, create a "relationship" between that user and the event, via a field like "Attendees" added to the "Event" (of type "user reference", with multiple (unlimited or not?) possible values).

Voilà, just some basic Rules/Flag stuff, right?

# Answer
> 0 votes
You may use Organic groups module

> Enable users to create and manage their own 'groups'. Each group can have subscribers, and maintains a group home page where subscribers communicate amongst themselves.

"event-coordinator" will be group administrator and he will create and edit any content in the group. "audience" will be usual group member and he will edit only own content in the group

---
Tags: entities, nodes, users
---


title: Issue with CSS on Home Page

text:
# Question
Title: Issue with CSS on Home Page
I have a vexing issue. I'm using the equal heights module to ensure two blocks are of equal height on the home page of my site. Inside each block, at the bottom of each block, is a read more link. I need the read more links to be spaced so that they are both at the bottom of each block, positioned identically on the page (within their respective blocks). When I'm logged in to the site as an ADMIN the CSS I'm using is working fine (see first screenshot below for the orange read more links showing on each side). However, when I log OUT of the site (or login as another user) and view the home page the 'read more' links are collapsing together at the top of the page in the middle for some reason (see the second screenshot). They are using the exact same CSS so I don't know why it's doing this.

Note: I tried giving another user all the same permissions as the admin to see if that fixed it and it did NOT fix the problem, so I don't think it's a permissions issue.

Ok, so here's the CSS (for one of the blocks - they are the same) I'm using to position the elements:

```
#block-views-featured-resource-block .views-field-view-node {
position: absolute;
margin-bottom: 8px;
padding-bottom: 5px;
text-align: center;
left: 20%;
width: 50%;
bottom: 0;
@media screen and (max-width: 959px) {
    position: absolute;
}
}

```

And here's the page--front.tpl.php file:

```
<div id="page">

```

```
<?php if ($logo): ?>
    <a href="<?php print $front_page; ?>" title="<?php print t('Home');
?>" rel="home" id="logo">
    <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />
    </a>
<?php endif; ?>
<?php print render($page['top_navigation']); ?>
<?php print render($page['user_menu']); ?>

```

```
<div id="content" class="column" role="main">

  <?php /** print $breadcrumb; */ ?>

  <a id="main-content"></a>

  <?php print render($page['pathfinder_header']); ?>
  <?php print render($page['introduction']); ?>
  <?php print render($tabs); ?>
  <?php print render($page['help']); ?>

  <?php if ($action_links): ?>
    <ul class="action-links"><?php print render($action_links); ?></ul>
  <?php endif; ?>

  <div class="feat-container">
  <?php print render($page['featured_resource']); ?>
  <?php print render($page['hp_video']); ?>
  <?php print render($page['whats_new']); ?>
  </div>

  <?php print render($page['find_your_path']); ?>
  <?php print render($page['search_library']); ?>
  <?php print render($page['browse_library']); ?>

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

  <?php print $feed_icons; ?>
</div>

```

The items in question are within the 'feat-container' in the page.tpl above.

Anyone have ideas why when I'm logged in as an admin user they work but not for any other user? It makes no sense to me. I tried clearing the cache...that didn't help. I flushed with drush. That didn't help either.

# Answer
> 1 votes
Have you tried disabling the equalheights module, perhaps it maybe causing this issue? You don't need a module to give blocks equal heights, when you can easily do that with css.

I noticed on the top screenshot there is no video, while the bottom has a video.

Anyhow, based on your screenshot, it seems that you can fix this by adding a `position: relative;` to the div id or class that is wrapping the blocks. Which would be #block-views-featured-resource-block and what ever the name the Grand station Resource block id is.

---
Tags: theming
---


# Question
Title: Apply hook_menu to all nodes except node593
I have 2 separate hook\_menu callbacks going on in my code.

I want to apply a function to all nodes and then for node593, I want to apply it's own function but I can't seem to do this.

The function for the % wildcard seems to work for all nodes, including 593.

Anyone know how I can get past this ?

# Answer
You're probably overthinking it; making that decision in the page callback seems like the easiest solution:

```
function MYMODULE_menu_alter(&$items) {
  $items['node/%node']['page callback'] = 'MYMODULE_node_page';
}

function MYMODULE_node_page($node) {
  if ($node->nid == 593) {
    return node_page_view($node);
  }
  else {
    // ...
  }
}

```
> 0 votes

---
Tags: nodes, routes
---


# Question
Title: Content types with a field that get data from my custom table
as it said on the title, I've create a custom table named : writers (contains name,books..of writers)

To add a book, I've created also a content type that contains a form, with many textfields (book title, editor, number of pages..ect),now I want to have a list of writers (that are stored on my table : writers) to be sure that the book I'm adding is a book written by one of the writers I've on my table

I'm working on it for 2 days and I don't know how to do it, please if anyone can helps me it would be great

P.S. I don't want to let the user write the name of the writer on the form (content type) I want to let him choose on a list

Thank you

This is my book.module (to get an item to access to the form book):

```
<?php

function book_menu (){

$items['admin/books'] = array(
    'title' => 'books',
    'description' => 'books form',
    'title callback' => 'book_title_callback',
    'page callback' => 'system_admin_menu_block_page',
    'access arguments' => array('administer books'),
    'file' => 'system.admin.inc',
    'file path' => drupal_get_path('module', 'system'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('book_form')
);

  return $items;
 }

function book_permission(){
  return array(
   'administer books' => array(
   'title' => t('permissions to deal with books'),
   'description' => t('permissions to deal with books'),
 ),
  );
  }

```

and I have some functions..

Here we have the new function hook\_update\_7001 :

```
function book_update_7001(&$sandbox){
$info = field_info_field('field_data_field_writer'); //the select list on the content type

  $result = db_query("SELECT name_writer, uid FROM {writers} ");

  $res = $result->execute();
  $options = array();
   foreach($res as $sql){
    $options[] = array(
        'uid' => $sql-> uid,
        'name' => $sql-> name_writer,
        );
   }
$info['settings']['allowed_values'] = $options;
field_update_field($info);
 }

```

# Answer
Did you already try the Entity reference module? If I understand your question correctly, you could create a content type `Writer` and add a reference field on your `Book` content type. This reference field can be used to select (i.e., use the 'Select list' widget) the appropriate `Writer` for your `Book`. No need to create a custom table yourself.

With permissions you can control who's allowed to create/edit/delete each of the content types.
> 0 votes

# Answer
You can add new field to "Book" content type with type "Select list". And then using hook\_update\_n add options to this field.

```
function mymodule_update_7001(&$sandbox) {
  // Get the field info
  $info = field_info_field('field_some_field');

  $options = array();
  //Make a select from your 'writers' table and prepare an array with writers.
  $query = db_select('writers');
  ...

  // Save the field
  $info['settings']['allowed_values'] = $options;
  field_update_field($info);
}

```
> 0 votes

---
Tags: nodes
---


# Question
Title: Boostrap dropdown menu only working on parent page
I have a question, which I want to solve for a really long time now. I'm creating my own boostrap sub-theme.

I 3 links in my drupal menu:

I want this menu to be available on every page, and it should be possible to access every link on every page. My code in page.tpl.php:

```
<div class="<?php print $navbar_classes ?>">
    <div class="container">
        <?php if (!empty($primary_nav) || !empty($secondary_nav) || !empty($page['navigation'])): ?>
            <div class="navbar-collapse collapse">
                <nav role="navigation">
                    <?php print render($primary_nav) ?>
                    <?php print render($secondary_nav) ?>
                    <?php print render($page['navigation']) ?>
                </nav>
            </div>
        <?php endif ?>
    </div>
</div>

```

However I can only go to the sub (e.g. /info/sub) when I'm on the parent (e.g. info). I have tried to use superfirsh but then I loose all advantages of boostrap.

Home page, there isn't a caret:

Info page, there is a caret:

Note that the HTML code for the dropdown menu isn't available on the home page.

I know this is possible, but how? Thanks!

# Answer
Can you please try this:

1. Go to structure and then open your menu link
2. Enabled the "Show as expanded" option for your parent menu item.(in your case it is info menu item).

I hope it will work for you.
> 3 votes

---
Tags: navigation, theming
---


# Question
Title: How to extend a test class of dependent module
I am creating a module with dependency on another contrib module. When I am trying to extend the test class in dependent module, it works fine locally(using test UI). However when I try to test my new module in qa.drupal.org it throws error saying that the 'Class not found' as the dependency module is not enabled.

# Answer
You can use function module\_load\_include to include file in your module. Class not found because main class not include in your case.
> 0 votes

---
Tags: 6
---


# Question
Title: Prevent drupal from adding a favicon from default directory in custom theme
I want Drupal to look for a favicon in a specific directory dynamically. This is mainly because I'm using the domain access module and I'd like the favicon based off the subdomain that is being used. For example if the url is

```
example.url.com

```

I want drupal to look for the favicon in

```
sites/all/themes/mytheme/example/favicon.ico

```

If the subdomain is example2 I want it to look for the favicon here

```
sites/all/themes/mytheme/examples2/favicon.ico

```

I think I have a handle of how to grab the url and base the location on that but right after I have added the favicon, drupal adds it's own. For example I see this in the header

```
<link rel="shortcut icon" href="sites/all/themes/mytheme/examples2/favicon.ico" type="image/x-icon">
<link rel="shortcut icon" href="http://example.url.com/misc/favicon.ico" type="image/vnd.microsoft.icon">

```

I've accomplished adding my own favicon but it doesn't matter since it is added before anything else. I'm currently using preprocess\_html to do this

```
function mytheme_preprocess_html(&$variables) {
    $favicon = 'sites/all/themes/mytheme/example/favicon.ico';
    $type = 'image/x-icon';
    drupal_add_html_head_link(array('rel' => 'shortcut icon', 'href' => drupal_strip_dangerous_protocols($favicon), 'type' => $type));
}

```

(It does not yet have the logic to grab the url) I'm assuming that it is at the top based on the term preprocess. Is there a way to give it weight? Or is there another function I should be using?

# Answer
I found a solution. in Appearance\>Mytheme\>Settings, there is an option to uncheck shortcut settings.

After unchecking that option the link provided in mytheme\_preprocess\_html was able to display the favicon unopposed.
> 2 votes

---
Tags: theming, hooks
---


# Question
Title: How to limit entity and/or field translation permissions to selected languages only?
Is it possible to give some user/role the permission to translate only one language?

I've seen these permissions:

* `Translate any entity`.
* `Translate field content for any fieldable entity`.

But these permissions allow users to translate all languages.

I have one user that has to translate to English and another user who translates to German ...

# Answer
Interesting (valid!) question. But to my knowledge, and assuming this is for D7 (not D8), this is NOT possible ... yet.

Refer to (active) issue # 1829630 for more details, which also references (fixed) issue # 1807776 related to D8 (and contains a lot of interesting details ...).
> 2 votes

---
Tags: 7, users, entities, i18n-l10n
---