title: How to Get the Value of field_code_file

text:
# Question
Title: How to Get the Value of field_code_file
Considering that I know the NID of the node, how can I get the value of one of the field that belongs to that NID?

I tried everything I can to get the value of field\_code\_file with the following code:

```
$node = node_load($_GET['nid']);
$wrapper = entity_metadata_wrapper('node', $node);
$file = $wrapper->field_code_file->value();

```

The value returned by $file is "array". Here's the value:

```
Array ( [#theme] => field [#weight] => 0 [#title] => Code File [#access] => 1 [#label_display] => above [#view_mode] => _custom_display [#language] => und [#field_name] => field_code_file [#field_type] => file [#field_translatable] => 0 [#entity_type] => node [#bundle] => source_code [#object] => stdClass Object ( [vid] => 71 [uid] => 1 [title] => Billing Software [log] => You can now download the installer for Billing System. This is important if you don't have crystal reports v8.5 in your machine. [status] => 1 [comment] => 2 [promote] => 1 [sticky] => 0 [ds_switch] => [nid] => 29 [type] => source_code [language] => und [created] => 1227189989 [changed] => 1260934297 [tnid] => 0 [translate] => 0 [revision_timestamp] => 1260934297 [revision_uid] => 1 [body] => Array ( [und] => Array ( [0] => Array ( [value] =>

) ) ) [field_screenshot] => Array ( [und] => Array ( [0] => Array ( [fid] => 36 [alt] => [title] => [width] => [height] => [uid] => 1 [filename] => Billing Screenshot.jpg [uri] => public://images/admin/Billing Screenshot.jpg [filemime] => image/jpeg [filesize] => 35357 [status] => 1 [timestamp] => 1227589659 ) ) ) [field_code_file] => Array ( [und] => Array ( [0] => Array ( [fid] => 37 [display] => 1 [description] => [uid] => 1 [filename] => Billing System.zip [uri] => public://download/admin/Billing System.zip [filemime] => application/zip [filesize] => 864517 [status] => 1 [timestamp] => 1227589659 ) ) ) [field_terms_and_conditions] => Array ( [und] => Array ( [0] => Array ( [value] => 1 ) ) ) [field_language] => Array ( [und] => Array ( [0] => Array ( [tid] => 7 [taxonomy_term] => stdClass Object ( [tid] => 7 [vid] => 5 [name] => Visual Basic [description] => [format] => [weight] => 0 [vocabulary_machine_name] => vocabulary_5 [metatags] => Array ( ) ) ) ) ) [field_tags] => Array ( [und] => Array ( [0] => Array ( [tid] => 52 [taxonomy_term] => stdClass Object ( [tid] => 52 [vid] => 10 [name] => visual basic [description] => [format] => [weight] => 0 [vocabulary_machine_name] => vocabulary_10 [metatags] => Array ( ) ) ) [1] => Array ( [tid] => 55 [taxonomy_term] => stdClass Object ( [tid] => 55 [vid] => 10 [name] => billing [description] => [format] => [weight] => 0 [vocabulary_machine_name] => vocabulary_10 [metatags] => Array ( ) ) ) [2] => Array ( [tid] => 323 [taxonomy_term] => stdClass Object ( [tid] => 323 [vid] => 10 [name] => cable tv [description] => [format] => [weight] => 0 [vocabulary_machine_name] => vocabulary_10 [metatags] => Array ( ) ) ) ) ) [metatags] => Array ( ) [cid] => 75722 [last_comment_timestamp] => 1386138557 [last_comment_name] => Legendx [last_comment_uid] => 0 [comment_count] => 442 [name] => admin [picture] => 1 [data] => a:7:{s:14:"picture_delete";i:0;s:14:"picture_upload";s:0:"";s:7:"contact";i:1;s:13:"form_build_id";s:37:"form-df16b3b26332f9a4dd7de12c3f483943";s:9:"nodewords";a:9:{s:8:"abstract";a:1:{s:5:"value";s:0:"";}s:9:"canonical";a:1:{s:5:"value";s:0:"";}s:9:"copyright";a:1:{s:5:"value";s:0:"";}s:11:"description";a:1:{s:5:"value";s:0:"";}s:8:"keywords";a:1:{s:5:"value";s:0:"";}s:13:"revisit-after";a:1:{s:5:"value";s:1:"1";}s:6:"robots";a:2:{s:5:"value";a:6:{s:9:"noarchive";i:0;s:8:"nofollow";i:0;s:7:"noindex";i:0;s:5:"noodp";i:0;s:9:"nosnippet";i:0;s:6:"noydir";i:0;}s:11:"use_default";i:0;}s:8:"dc.title";a:1:{s:5:"value";s:0:"";}s:8:"location";a:2:{s:8:"latitude";s:0:"";s:9:"longitude";s:0:"";}}s:4:"info";s:106:"To receive an update on your email please enter your email at Feed subscription at the right of this page.";s:6:"format";s:1:"2";} [_field_view_prepared] => 1 [entity_view_prepared] => 1 [content] => Array ( ) ) [#items] => Array ( [0] => Array ( [fid] => 37 [display] => 1 [description] => [uid] => 1 [filename] => Billing System.zip [uri] => public://download/admin/Billing System.zip [filemime] => application/zip [filesize] => 864517 [status] => 1 [timestamp] => 1227589659 ) ) [#formatter] => file_default [0] => Array ( [#theme] => file_link [#file] => stdClass Object ( [fid] => 37 [display] => 1 [description] => [uid] => 1 [filename] => Billing System.zip [uri] => public://download/admin/Billing System.zip [filemime] => application/zip [filesize] => 864517 [status] => 1 [timestamp] => 1227589659 ) ) )

```

I am expecting a value like this:

```
http://www.mysite.com/sites/default/files/download/admin/Billing%20System.zip

```

I'm using this code in my simple module that I created.

For Jeet:

Thanks. When I use this command print\_r($file), it returns this value:

```
Array ( [0] => Array ( [fid] => 37 [display] => 1 [description] => [uid] => 1 [filename] => Billing System.zip [uri] => public://download/admin/Billing System.zip [filemime] => application/zip [filesize] => 864517 [status] => 1 [timestamp] => 1227589659 ) )

```

Now how can I get the full url like:

```
http://www.mysite.com/sites/default/files/download/admin/Billing%20System.zip

```

I'm trying to understand what you mean by `file_create_url($uri)`, but I can't crack my head on it.

Can you please explain it to me further?

Thank you

# Answer
Assuming the field is a file type.

```
$node = node_load($_GET['nid']);
$file = field_get_items('node', $node, 'field_code_file');

```

Print the `$file`. you will get a URI index. To get your full path to file use function `file_create_url($uri)`

Let me know if this doesn't get you the result.
> 3 votes

---
Tags: 7
---


title: ownership drupal directories

text:
# Question
Title: ownership drupal directories
Would it be safe to say only the files directory should be owned by apache user ?

I have mine set files `apache:root`

And all other drupal directories `root:root` ?

My permissions are set to 755 for everything excepting 444 on settings.php

Actually my files I've set to 775 and have in www `chown -R root:apache html`

then `chown -R apache:root files`

# Answer
It would be safe with all folders being in 0775 and settings.php in 444. However, if you would use FTP/SFTP to edit either the themes or any module files You may need to login with the "Owner" user, which may or may not be possible in a shared hosting environment.

So., depending on that you may choose. However, if you use SSh it will be not an issue.
> 1 votes

---
Tags: files
---


title: Skip to Main Content link not working?

text:
# Question
Title: Skip to Main Content link not working?
The theme I'm using (AT Panels Everywhere subtheme for Adaptivetheme) has the following skip navigation link:

```
<div id="skip-link">
<a href="#content" class="element-invisible element-focusable">Skip to main content</a>
</div>

```

but that link goes nowhere when I hit Enter when that div becomes focused as I tab through on the keyboard.

I tried adding the "content" anchor tag like this:

```
<div id="content" class="region">
<span style="width: 100%;" tabindex="0"><a name="content"></a></span>
<?php print $content; ?>
</div>

```

but it still doesn't work. I'm still forced to tab through every link on the page.

What am I doing wrong?

# Answer
Try changing your code like this

```
<div id="content" class="region">
<span style="width: 100%;" tabindex="0"><a href="#content">Skip</a></span>
<?php print $content; ?>
</div>

```
> -1 votes

---
Tags: theming
---


title: Create more than 1 advanced topic types

text:
# Question
Title: Create more than 1 advanced topic types
I have a **content type** called advanced forum topic, which is created from the Advanced Forum module.

I would like to have 3 different kinds of topics(General, Player, Team). Each of this has different fields. My thought was to organize these into **Field collections**. Is there a way that I can choose the topic type with a dropdown menu and then the rest of the fields in the collection would pop up dynamically?

# Answer
> 1 votes
You can easily do your requirement with Conditional Fields module. You can show different fields depend on the select list of topics.

> Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.
>
> When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API.

---
Tags: nodes
---


# Question
Title: Store array of ids in a field programmatically?
Devel noob here. I am writing a module where I need to stash a list of entity ids in a field on a different entity. I've created a field on an entity type programmatically and have it set as field type list(integer), but I'm stuck at actually working with the field data.

How can I add/edit entity ids in the field list programmatically?

For context, this is a Commerce submodule and I am adding to a field on the line item created after submitting an add to cart form. Using `dsm($form_data)` in a submit handler I added to the add to cart form, I see that the line item object is already stored in `$form_data['line_item']` and the data I need to get to would be stored at `$form_data['line_item']->field_entity_ids`. By this point, I already have my array of ids, I just need some guidance on how to store them properly in the field.

Thanks in advance! :)

# Answer
> 0 votes
Consider using `hook_entity_presave()` to populate any auto-generated fields.

In your case, you could do something like:

```
/**
 * Implements hook_entity_presave().
 */
function example_product_entity_presave($entity, $type) {
  // Set the values for our computed fields.
  switch ($type) {
    case 'commerce_line_item':
      // @todo: get the value for $foo_ids.
      foreach ($foo_ids as $foo_id) {
        $entity->field_entity_ids[LANGUAGE_NONE][] = array(
          'value' => $foo_id,
        );
      }
      break;
  }
}

```

If you intend to reference any existing entity, you might want to use the Entity Reference module and use an entity reference field instead of an integer field.

---
Tags: entities, commerce
---


# Question
Title: Display user list with number of comments and forum posts
I want to create blocks to display a list of all users with their number of comments and number of post on forum.

In SQL, something like that :

```
SELECT u.name as user, COUNT( n1.nid ) as 'number of post', COUNT( n2.nid ) as 'number of comment', COUNT( c.cid ) as 'total'
FROM users u
LEFT JOIN comment c ON u.uid = c.uid
LEFT JOIN users_roles ur ON u.uid = ur.uid
LEFT JOIN ( SELECT n.nid, n.type FROM node n WHERE n.type = 'forum' ) n1 ON c.nid = n1.nid
LEFT JOIN ( SELECT n.nid, n.type FROM node n WHERE n.type <> 'forum' ) n2 ON c.nid = n2.nid
WHERE u.uid <> 0 AND ur.rid IS NULL
GROUP BY u.name

```

Using views I'm using this patch to have relationship between users and comments and filters to test if the node type related to comment is 'forum' or not.

There is an export of my display on views :

```
<?php
    $view = new view();
    $view->name = 'utilisateurs';
    $view->description = 'liste les utilisateurs du site';
    $view->tag = 'default';
    $view->base_table = 'users';
    $view->human_name = 'utilisateurs';
    $view->core = 7;
    $view->api_version = '3.0';
    $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

    /* Display: Master */
    $handler = $view->new_display('default', 'Master', 'default');
    $handler->display->display_options['title'] = 'utilisateurs';
    $handler->display->display_options['use_more_always'] = FALSE;
    $handler->display->display_options['use_more_text'] = 'plus';
    $handler->display->display_options['group_by'] = TRUE;
    $handler->display->display_options['access']['type'] = 'perm';
    $handler->display->display_options['access']['perm'] = 'access user profiles';
    $handler->display->display_options['cache']['type'] = 'none';
    $handler->display->display_options['query']['type'] = 'views_query';
    $handler->display->display_options['exposed_form']['type'] = 'basic';
    $handler->display->display_options['exposed_form']['options']['submit_button'] = 'Appliquer';
    $handler->display->display_options['exposed_form']['options']['reset_button_label'] = 'Réinitialiser';
    $handler->display->display_options['exposed_form']['options']['exposed_sorts_label'] = 'Trier par';
    $handler->display->display_options['pager']['type'] = 'some';
    $handler->display->display_options['pager']['options']['items_per_page'] = '10';
    $handler->display->display_options['pager']['options']['offset'] = '0';
    $handler->display->display_options['style_plugin'] = 'default';
    $handler->display->display_options['row_plugin'] = 'fields';
    /* Relationship: comments and posts */
    $handler->display->display_options['relationships']['uid_comment']['id'] = 'uid_comment';
    $handler->display->display_options['relationships']['uid_comment']['table'] = 'users';
    $handler->display->display_options['relationships']['uid_comment']['field'] = 'uid_comment';
    $handler->display->display_options['relationships']['uid_comment']['ui_name'] = 'comments and posts';
    $handler->display->display_options['relationships']['uid_comment']['label'] = 'comments and posts';
    /* Relationship: comments only */
    $handler->display->display_options['relationships']['uid_comment_1']['id'] = 'uid_comment_1';
    $handler->display->display_options['relationships']['uid_comment_1']['table'] = 'users';
    $handler->display->display_options['relationships']['uid_comment_1']['field'] = 'uid_comment';
    $handler->display->display_options['relationships']['uid_comment_1']['ui_name'] = 'comments only';
    /* Relationship: comments_nid */
    $handler->display->display_options['relationships']['nid']['id'] = 'nid';
    $handler->display->display_options['relationships']['nid']['table'] = 'comment';
    $handler->display->display_options['relationships']['nid']['field'] = 'nid';
    $handler->display->display_options['relationships']['nid']['relationship'] = 'uid_comment_1';
    $handler->display->display_options['relationships']['nid']['ui_name'] = 'comments_nid';
    $handler->display->display_options['relationships']['nid']['label'] = 'comments_nid';
    /* Relationship: posts only */
    $handler->display->display_options['relationships']['uid_comment_2']['id'] = 'uid_comment_2';
    $handler->display->display_options['relationships']['uid_comment_2']['table'] = 'users';
    $handler->display->display_options['relationships']['uid_comment_2']['field'] = 'uid_comment';
    $handler->display->display_options['relationships']['uid_comment_2']['ui_name'] = 'posts only';
    $handler->display->display_options['relationships']['uid_comment_2']['label'] = 'posts';
    /* Relationship: posts_nid */
    $handler->display->display_options['relationships']['nid_1']['id'] = 'nid_1';
    $handler->display->display_options['relationships']['nid_1']['table'] = 'comment';
    $handler->display->display_options['relationships']['nid_1']['field'] = 'nid';
    $handler->display->display_options['relationships']['nid_1']['relationship'] = 'uid_comment_2';
    $handler->display->display_options['relationships']['nid_1']['ui_name'] = 'posts_nid';
    $handler->display->display_options['relationships']['nid_1']['label'] = 'posts_nid';
    /* Champ: Utilisateur: Image */
    $handler->display->display_options['fields']['picture']['id'] = 'picture';
    $handler->display->display_options['fields']['picture']['table'] = 'users';
    $handler->display->display_options['fields']['picture']['field'] = 'picture';
    $handler->display->display_options['fields']['picture']['label'] = '';
    $handler->display->display_options['fields']['picture']['element_label_colon'] = FALSE;
    $handler->display->display_options['fields']['picture']['image_style'] = 'thumbnail';
    /* Champ: Utilisateur: Nom */
    $handler->display->display_options['fields']['name']['id'] = 'name';
    $handler->display->display_options['fields']['name']['table'] = 'users';
    $handler->display->display_options['fields']['name']['field'] = 'name';
    $handler->display->display_options['fields']['name']['label'] = '';
    $handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
    $handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
    /* Champ: COUNT(DISTINCT Commentaire: Identifiant (ID)) */
    $handler->display->display_options['fields']['cid']['id'] = 'cid';
    $handler->display->display_options['fields']['cid']['table'] = 'comment';
    $handler->display->display_options['fields']['cid']['field'] = 'cid';
    $handler->display->display_options['fields']['cid']['relationship'] = 'uid_comment';
    $handler->display->display_options['fields']['cid']['group_type'] = 'count_distinct';
    $handler->display->display_options['fields']['cid']['label'] = '';
    $handler->display->display_options['fields']['cid']['exclude'] = TRUE;
    $handler->display->display_options['fields']['cid']['element_label_colon'] = FALSE;
    $handler->display->display_options['fields']['cid']['prefix'] = 'Total (commentaires et posts) :';
    /* Champ: COUNT(DISTINCT Commentaire: Identifiant (ID)) */
    $handler->display->display_options['fields']['cid_2']['id'] = 'cid_2';
    $handler->display->display_options['fields']['cid_2']['table'] = 'comment';
    $handler->display->display_options['fields']['cid_2']['field'] = 'cid';
    $handler->display->display_options['fields']['cid_2']['relationship'] = 'uid_comment_2';
    $handler->display->display_options['fields']['cid_2']['group_type'] = 'count_distinct';
    $handler->display->display_options['fields']['cid_2']['label'] = '';
    $handler->display->display_options['fields']['cid_2']['element_label_colon'] = FALSE;
    $handler->display->display_options['fields']['cid_2']['suffix'] = ' posts sur le forum';
    /* Champ: COUNT(DISTINCT Commentaire: Identifiant (ID)) */
    $handler->display->display_options['fields']['cid_1']['id'] = 'cid_1';
    $handler->display->display_options['fields']['cid_1']['table'] = 'comment';
    $handler->display->display_options['fields']['cid_1']['field'] = 'cid';
    $handler->display->display_options['fields']['cid_1']['relationship'] = 'uid_comment_1';
    $handler->display->display_options['fields']['cid_1']['group_type'] = 'count_distinct';
    $handler->display->display_options['fields']['cid_1']['label'] = '';
    $handler->display->display_options['fields']['cid_1']['element_label_colon'] = FALSE;
    $handler->display->display_options['fields']['cid_1']['suffix'] = ' avis postés';
    /* Sort criterion: Utilisateur: Date de création */
    $handler->display->display_options['sorts']['created']['id'] = 'created';
    $handler->display->display_options['sorts']['created']['table'] = 'users';
    $handler->display->display_options['sorts']['created']['field'] = 'created';
    $handler->display->display_options['sorts']['created']['order'] = 'DESC';
    /* Filter criterion: Utilisateur: Actif */
    $handler->display->display_options['filters']['status']['id'] = 'status';
    $handler->display->display_options['filters']['status']['table'] = 'users';
    $handler->display->display_options['filters']['status']['field'] = 'status';
    $handler->display->display_options['filters']['status']['value'] = '1';
    $handler->display->display_options['filters']['status']['group'] = 1;
    $handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
    /* Filter criterion: Utilisateur: Rôles */
    $handler->display->display_options['filters']['rid']['id'] = 'rid';
    $handler->display->display_options['filters']['rid']['table'] = 'users_roles';
    $handler->display->display_options['filters']['rid']['field'] = 'rid';
    $handler->display->display_options['filters']['rid']['operator'] = 'not';
    $handler->display->display_options['filters']['rid']['value'] = array(
      3 => '3',
    );
    /* Filter criterion: Contenu: Type */
    $handler->display->display_options['filters']['type']['id'] = 'type';
    $handler->display->display_options['filters']['type']['table'] = 'node';
    $handler->display->display_options['filters']['type']['field'] = 'type';
    $handler->display->display_options['filters']['type']['relationship'] = 'nid';
    $handler->display->display_options['filters']['type']['operator'] = 'not in';
    $handler->display->display_options['filters']['type']['value'] = array(
      'forum' => 'forum',
    );
    /* Filter criterion: Contenu: Type */
    $handler->display->display_options['filters']['type_1']['id'] = 'type_1';
    $handler->display->display_options['filters']['type_1']['table'] = 'node';
    $handler->display->display_options['filters']['type_1']['field'] = 'type';
    $handler->display->display_options['filters']['type_1']['relationship'] = 'nid_1';
    $handler->display->display_options['filters']['type_1']['value'] = array(
      'forum' => 'forum',
    );

    /* Display: 10 derniers membres */
    $handler = $view->new_display('block', '10 derniers membres', 'last_members');
    $handler->display->display_options['defaults']['title'] = FALSE;
    $handler->display->display_options['title'] = 'Les derniers inscrits';
    $handler->display->display_options['display_description'] = 'les 10 derniers utilisateurs a s\'être inscrit sur le site';
    $handler->display->display_options['defaults']['use_more'] = FALSE;
    $handler->display->display_options['defaults']['use_more_always'] = FALSE;
    $handler->display->display_options['defaults']['use_more_always'] = FALSE;
    $handler->display->display_options['use_more_always'] = TRUE;
    $handler->display->display_options['defaults']['use_more_text'] = FALSE;
    $handler->display->display_options['use_more_text'] = 'voir tout les membres';
    $handler->display->display_options['block_description'] = '10 derniers membres';

    /* Display: 10 membres les plus actifs */
    $handler = $view->new_display('block', '10 membres les plus actifs', 'active_members');
    $handler->display->display_options['defaults']['title'] = FALSE;
    $handler->display->display_options['title'] = 'Les plus actifs';
    $handler->display->display_options['display_description'] = 'les 10 utilisateurs qui ont poster le plus de commentaire ou de post sur le forum';
    $handler->display->display_options['defaults']['sorts'] = FALSE;
    /* Sort criterion: COUNT(DISTINCT Commentaire: Identifiant (ID)) */
    $handler->display->display_options['sorts']['cid']['id'] = 'cid';
    $handler->display->display_options['sorts']['cid']['table'] = 'comment';
    $handler->display->display_options['sorts']['cid']['field'] = 'cid';
    $handler->display->display_options['sorts']['cid']['relationship'] = 'uid_comment';
    $handler->display->display_options['sorts']['cid']['group_type'] = 'count_distinct';
    $handler->display->display_options['sorts']['cid']['order'] = 'DESC';
    $handler->display->display_options['block_description'] = '10 membres les plus actifs';

    /* Display: tous les membres */
    $handler = $view->new_display('block', 'tous les membres', 'all_members');
    $handler->display->display_options['defaults']['title'] = FALSE;
    $handler->display->display_options['title'] = 'Tous les membres du club BBchoo';
    $handler->display->display_options['display_description'] = 'tous les membres par ordre alphabetique';
    $handler->display->display_options['defaults']['pager'] = FALSE;
    $handler->display->display_options['pager']['type'] = 'full';
    $handler->display->display_options['pager']['options']['items_per_page'] = '10';
    $handler->display->display_options['pager']['options']['offset'] = '0';
    $handler->display->display_options['pager']['options']['id'] = '0';
    $handler->display->display_options['pager']['options']['quantity'] = '9';
    $handler->display->display_options['pager']['options']['expose']['items_per_page_label'] = 'Éléments par page';
    $handler->display->display_options['pager']['options']['expose']['items_per_page_options_all_label'] = '- Tout -';
    $handler->display->display_options['pager']['options']['expose']['offset_label'] = 'Décalage';
    $handler->display->display_options['pager']['options']['tags']['first'] = '« premier';
    $handler->display->display_options['pager']['options']['tags']['previous'] = '‹ précédent';
    $handler->display->display_options['pager']['options']['tags']['next'] = 'suivant ›';
    $handler->display->display_options['pager']['options']['tags']['last'] = 'dernier »';
    $handler->display->display_options['defaults']['sorts'] = FALSE;
    /* Sort criterion: Utilisateur: Nom */
    $handler->display->display_options['sorts']['name']['id'] = 'name';
    $handler->display->display_options['sorts']['name']['table'] = 'users';
    $handler->display->display_options['sorts']['name']['field'] = 'name';
    $handler->display->display_options['block_description'] = 'tous les membres';
    $translatables['utilisateurs'] = array(
      t('Master'),
      t('utilisateurs'),
      t('plus'),
      t('Appliquer'),
      t('Réinitialiser'),
      t('Trier par'),
      t('Asc'),
      t('Desc'),
      t('comments and posts'),
      t('comments'),
      t('comments_nid'),
      t('posts'),
      t('posts_nid'),
      t('10 derniers membres'),
      t('Les derniers inscrits'),
      t('les 10 derniers utilisateurs a s\'être inscrit sur le site'),
      t('voir tout les membres'),
      t('10 membres les plus actifs'),
      t('Les plus actifs'),
      t('les 10 utilisateurs qui ont poster le plus de commentaire ou de post sur le forum'),
      t('tous les membres'),
      t('Tous les membres du club BBchoo'),
      t('tous les membres par ordre alphabetique'),
      t('Éléments par page'),
      t('- Tout -'),
      t('Décalage'),
      t('« premier'),
      t('‹ précédent'),
      t('suivant ›'),
      t('dernier »'),
    );
?>

```

The problem is it returns only users who have ever posted comments and forum messages, not users who posted nothing, not users who posted only comments and not users who posted only forum messages.

How can I configure my view display to fix it ?

# Answer
> 0 votes
Finally I succeed to solve my problem myself.

The solution has been the module views field view. With it, I can configure sql subrequest equivalent displays.

---
Tags: views, users, comments
---


# Question
Title: How to embed user photo upload form in a page of Drupal 7 site
I want to embed user photo(avatar) upload form in a node page like this: node--37.tpl.php so a user can change or upload their profile picture by visiting a particular node.
Can't understand what to do, reading some api documentation like function form\_load\_include with no luck.
Also i found an amazing snippet here but how to use it as a form?

```
$uid = 3;
$account = user_load($uid);

// suppose that a source user picture is located in the 'sites/default/files/upics'     directory.
// get image information
$image_path = 'public://upics/userpic.jpg';
$image_info = image_get_info($image_path);

// create file object
$file = new StdClass();
$file->uid = $uid;
$file->uri = $image_path;
$file->filemime = $image_info['mime_type'];
$file->status = 0; // Yes! Set status to 0 in order to save temporary file.
$file->filesize = $image_info['file_size'];

// standard Drupal validators for user pictures
$validators = array(
  'file_validate_is_image' => array(),
  'file_validate_image_resolution' => array(variable_get('user_picture_dimensions',     '85x85')),
  'file_validate_size' => array(variable_get('user_picture_file_size', '30') * 1024),
);

// here all the magic :)
$errors = file_validate($file, $validators);
if (empty($errors)) {
  file_save($file);
  $edit['picture'] = $file;
  user_save($account, $edit);
}

```

Please give me some ideas to get started, your help is really appreciated. Thanks

# Answer
> 0 votes
You can do it like this:

* Open node--37.tpl.php
* locate the container(div) where should be placed a form and use drupal\_get\_form() function.

example:

```
<div class="some-class">
<?php print render(drupal_get_form('MY_FORM_ID')); ?>
</div>

```

---
Tags: 7, nodes, users
---


title: What is an entity URI?

text:
# Question
Title: What is an entity URI?
What are entity URIs? What are they used for?

Every answer I see is like *Just define in your `hook_entity_info()` a URI callback.* Why, if we are able to define entities and make them work without a custom URI? What is the benefit of the custom URI? Does it bring additional custom, cool functionality to our table that we can exploit?

Some examples of things out there on the web that mention Entity URIs, but don't leave me the wiser: Do entities need to have URIs?, Developing a custom Drupal entity, path(), uri(), defaultUri(), entity\_class\_uri, what to use?

In a nutshell: Why go through the hassle of defining an entity URI callback in your `hook_entity_info()`, if you can live without it?

# Answer
> 9 votes
> Why go through the hassle of defining an entity URI callback?

To allow other modules to override the entity URI and / or provide a default one.

For instance, I have a *student* entity defined by the *student module*. The entity URI is student/%student and is defined from the following hook.

```
/**
 * Implements hook_entity_info().
 */
function student_entity_info() {
  $return = array(
    'student' => array(
      'label' => t('Student'),
      ...
      'uri callback' => 'student_uri',
      ...
    ),
  );
  return $return;
}

/**
 * Entity uri callback: gives modules a chance to specify a path for a student.
 */
function student_uri($student) {
  return array(
    'path' => 'student/' . $student->student_id,
  );
}

```

Now, let's say I have another module, *student\_special*, which provides a different URI depending on a property in the student object. I can override the URI by implementing `hook_entity_info_alter()`.

```
/**
 * Implements hook_entity_info_alter().
 */
function student_special_entity_info_alter(&$entity_info) {
  // Add a URI callback to the student entity.
  $entity_info['student']['uri callback'] = 'student_special_uri';
}

/**
 * Entity uri callback: points to a unique URI if the given student is awesome.
 */
function student_special_uri($student) {
  // First look for a return value in the default entity uri callback.
  $default_uri = student_uri($student);

  if ($student->is_awesome) {
    return array(
      'path' => 'awesome-student/' . $student->student_id,
    );
  }
  return $default_uri;
}

```

We can then use the student URI for a variety of things like creating links or redirecting users to the student entity's view page. For example, if we want to redirect the user to the newly created student after submitting a form.

```
/**
 * Submit handler for the student create/edit form.
 */
function student_form_submit($form, &$form_state) {

  ...

  // Save the student entity.
  student_save($student);

  // Redirect the user to the student URI.
  $student_uri = entity_uri('student', $student);
  $form_state['redirect'] = $student_uri['path'];
  drupal_set_message(t('Student %title saved.', array('%title' => entity_label('student', $student))));
}

```

This ensures that we get the correct URI, especially if there are modules that overrides the default URI.

> Does it bring additional custom, cool functionality to our table that we can exploit?

Alas, there are no lucky charms at the end of the rainbow. Like @googletorp mentions, you still need to define a menu callback for the URI to work, otherwise the URI is just a string that does not map to an existing Drupal menu callback.

There are two ways that you can go about mapping custom Entity URIs to menu callback items: via a standard implementation of `hook_menu()`, or by overriding the `hook_menu()` method in your controller, in case you're using Entity API with custom admin ui controllers.

---
Tags: 7, entities, uri
---


# Question
Title: How to show html <input> marks to Views Custom text - field?
I need to put \< input \> - html tag to my Views Custom text field, but it wont show up? Somehow these codes will be disabled? What I need to do?

I tried to find solutions from web, but I didnt find anything for this. But I really need to put these html to Views custom text - field.

Text format settings is fine, but no help.

This works when I put \< input \> tag to Views "Header" and "Footer" section with "Custom text" field, but why not in section "fields"?

I hope there is a simple solution for this. Thanks.

# Answer
> 2 votes
I've had similar problems trying to show a tag. The only way I've been able to get around it is to install the Views PHP module - https://drupal.org/project/views\_php \- and add the HTML through that

Hope this helps you!

---
Tags: views, entities, input-formats, theming
---


# Question
Title: Search & replace serialized data after moving the files directory
A drupal 6 content\_field\_video table holds serialized data with URLs pointing to the old site location - `sites/default/files/thumb.png`. Moving to the otherwise amazing Aegir-based omega8 hosting platform, we moved to a new files directory, `sites/MYSITE.COM/files/thumb.png`, so we need to convert to URLs to a new scheme. Most of the URLs are corrected by the omega8 import process, but video thumbnails are hardcoded.

What's the easiest way to do it?

# Answer
> 0 votes
The scanner module scans all CCK fields - Since this is a CCK field, it should correct this kind of problem, if this is a small database. But for large database it may suffer from performance issues.

You can also do it with PHP or SQL.

---
Tags: 6, migrations
---


# Question
Title: add condition in apache solr serch query
I want to alter apache solr search query with my custom filed.

I have custom content type called "Restaurant" and in this content type i have 1 field called "country". Now I want to add condition that display search result only those restaurant which is belong to "Jamaica" and display facet as per this condition.

So,how can I alter query with apache solr serach?

# Answer
You can use `hook_apachesolr_query_alter()`

> Alter the query after it's prepared and cached.

Example from the docs page

```
function hook_apachesolr_query_alter($query) {
  // I only want to see articles by the admin.
  //
  // NOTE: this "is_uid" filter does NOT refer to the English word "is"
  // It is a combination of flags representing Integer-Single, which is
  // abbreviated with the letters i and s.
  //
  // @see the <dynamicField> definitions in schema.xml or schema-solr3.xml
  $query->addFilter("is_uid", 1);

  // Only search titles.
  $query->replaceParam('qf', 'label');
}

```
> 2 votes

---
Tags: 7, search
---


# Question
Title: Programmatically attach an image to a node using Storage API to store image in the Database
I am building a site where I need to store encrypted images in the database.

I'm using the module Storage API as it supports saving images to the database. I modified the db.inc file to just add an encrypt and decrypt function directly before writing to / reading from the DB.

This works perfectly however now I need to programmatically import thousands of photos.

I'm using this code to attach images to nodes:

```
$nid = 100;
$node = node_load($nid);
$image_path = '/var/www/coach/htdocs/photos/test.jpg';
$file = (object) array(
    'uid' => 1,
    'uri' => $image_path,
    'filemime' => file_get_mimetype($image_path),
    'status' => 1,
    'display' => 1
);
$destination = 'private://';
$file = file_copy($file, $destination, FILE_EXISTS_REPLACE);
$node->field_passport_photo[LANGUAGE_NONE][0] = (array) $file;
node_save($node);

```

However the destination here is wrong - I don't want to use the private scheme - I want to save the file to the database using the Storage API.

The documentation says that $destination is "*A string containing the destination that $source should be copied to. This must be a stream wrapper URI.*"

After manually adding an image to a node and inspecting the $form item on the edit form page I can see that the #upload\_location of the image is "storage-field-passport-photo://", however just passing this string into file\_copy as a destination does not work as a valid file object is not returned.

So, **what is the stream wrapper URI to get the file to be saved to the database?**

# Answer
> 1 votes
You can get a list of the stream wrappers implemented by the storage\_core\_bridge module with the `storage_core_bridge_stream_wrappers()` function:

```
$wrappers = storage_core_bridge_stream_wrappers();

```

The name will correspond to the name of the field in which the image data is stored, so `storage-field-passport-photo://` doesn't exactly sound unreasonable. You can use the above function to check for definite, though.

If it still doesn't work after you've determined the correct stream schema, you've most likely hit a bug, which you can get help for in the module's issue queue.

# Answer
> 1 votes
Though trial and error I've eventually found solution that works.

Clive's solution confirmed I had the correct stream wrapper but it still wasn't working.

I found I needed to add the filename to the end of the stream wrapper to pass into the file\_copy function.

So the final code that worked was:

```
$file = file_copy($file, 'storage-field-passport-photo://'.filename, FILE_EXISTS_REPLACE);

```

This is odd as it is behaving differently to if it was public:// or private:// which don't require the filename.

---
Tags: uri, stream-wrappers, files
---


# Question
Title: Entity Field Query - Most efficient way to get authors of nodes
I have a content type which contains fields which I am filtering my results on. Of these results, I wish to get the email address of the user who authored the node.

Currently I am using an Entity Field Query to get the list of nids. There can be thousands of matching nodes.

To get the email addresses of the authors of the nodes I do a `node_load_multiple` with the nids of my EFQ, and then a `user_load_multiple` with the uids of those nodes.

Is there a way to cut out a few of those steps with EFQ? Or will performance not be as big of an issue as I think it is?

Here is a code example:

```
$query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
        ->entityCondition('bundle', 'application')
        ->propertyCondition('status', 1)
        ->fieldCondition('field_one', 'value', $value1)
        ->fieldCondition('field_two', 'tid', $value2)
        ->fieldCondition('field_three', 'tid', NULL, 'IS NOT NULL');
  $result = $query->execute();

  if (isset($result['node'])) {
    $nodes = node_load_multiple(array_keys($result['node']));
    $uids = array();
    foreach ($nodes as $node) {
      $uids[$node->uid] = $node->uid;
    }
    $users = user_load_multiple(array_keys($uids));
  }

```

# Answer
> 2 votes
You are doing a lot of potentially unnecessary loads. Unless you need those nodes at some point on the page request, you will be doing a lot of unnecessary database reads.

I would EFQ to get the node list, and then do another query to just get the `$uids`. This example will retrieve the node list you're looking for:

```
$efq = new EntityFieldQuery();
$efq->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'application')
  ->propertyCondition('status', 1)
  ->fieldCondition('field_one', 'value', $value1)
  ->fieldCondition('field_two', 'tid', $value2)
  ->fieldCondition('field_three', 'tid', NULL, 'IS NOT NULL');
$result = $efq->execute();

if (isset($result['node'])) {
  $query = db_query('SELECT DISTINCT uid FROM {node} WHERE nid IN :nids',
    array(':nids', array_keys($result['node'])));

  $uids = $query->execute->fetchCol();
  $users = user_load_multiple($uids);
}

```

---
Tags: database
---


# Question
Title: How to delete true orphaned taxonomy terms
I have a taxonomy vocabulary that contains a large number (5000+) of orphaned taxonomy terms. By *orphaned* I mean that they refer to parent terms that no longer exist, or refer to parents who are themselves orphans (grand-orphans ?). I am **not** talking about unused terms.

I do not see these terms in the Drupal interface as they are no longer connected to the main hierarchy. I can however still see them in the database, and I can open them directly using the tid in the Drupal interface.

I can't bulk delete them using any module because modules get the entire tree of the vocab to delete - and they are no longer part of the tree. I think I will have to delete them manually in the database. I can delete the terms from the taxonomy\_term\_data and taxonomy\_term\_hierarchy tables:

```
DELETE FROM taxonomy_term_hierarchy WHERE parent NOT IN (SELECT tid FROM taxonomy_term_hierarchy) // or something like it

```

Are there any other tables I need to think of though, in order to not end up with a database that's messed up worse than it already is?

# Answer
I wouldn't advise doing that - taxonomy terms are entities and need to be cleaned up with `taxonomy_term_delete()`. Otherwise you'll potentially leave a lot of orphaned data in field tables/contrib module tables/etc.

However, if you know your `DELETE` query will get you the correct terms, just convert it to a `SELECT` and you can do things the proper way:

```
$tids = db_query('SELECT tid FROM taxonomy_term_hierarchy WHERE parent NOT IN (SELECT tid FROM taxonomy_term_hierarchy)')->fetchCol();

foreach ($tids as $tid) {
  taxonomy_term_delete($tid);
}

```

Be wary that you don't delete top-level terms that have a parent of `0`, since that record will not appear in your sub-query. It'll probably need a bit more thought, but the above code won't be too far off what you end up using.
> 4 votes

# Answer
The query I ended up using for selecting the orphaned children tid's was the following:

```
SELECT T1.tid
FROM
taxonomy_term_hierarchy AS T1 INNER JOIN
taxonomy_term_data ON
T1.tid = taxonomy_term_data.tid LEFT JOIN
taxonomy_term_hierarchy AS T2 ON
T1.parent = T2.tid LEFT JOIN
taxonomy_term_hierarchy AS T3 ON
T2.parent = T3.tid LEFT JOIN
taxonomy_term_hierarchy AS T4 ON
T3.parent = T4.tid LEFT JOIN
taxonomy_term_hierarchy AS T5 ON
T4.parent = T5.tid
WHERE
((T1.parent NOT IN (SELECT tid FROM taxonomy_term_hierarchy) AND T1.parent != 0) OR
(T2.parent NOT IN (SELECT tid FROM taxonomy_term_hierarchy) AND T2.parent != 0) OR
(T3.parent NOT IN (SELECT tid FROM taxonomy_term_hierarchy) AND T3.parent != 0) OR
(T4.parent NOT IN (SELECT tid FROM taxonomy_term_hierarchy) AND T4.parent != 0) OR
(T5.parent NOT IN (SELECT tid FROM taxonomy_term_hierarchy) AND T5.parent != 0)) AND
taxonomy_term_data.vid = 5

```

Because I was sure no hierarchy deeper than 5 levels existed in my list. For deeper hierarchies you would add more joins. Obviously the vid is situation specific as well.
> 1 votes

---
Tags: taxonomy-terms, database
---


# Question
Title: How can you print the field class you entered in a View 's style settings?
So in Views you can add a CSS class (under style settings) to your field. I need to print the same class in a parent div of the calendar module.

The fields are rendered to calendar content with the calendar-item.tpl.php That file looks like this:

```
$index = 0;
?>
<div class="<?php print !empty($item->class) ? $item->class : 'item'; ?>">
  <div class="view-item view-item-<?php print $view->name ?>">
  <div class="calendar <?php print $item->granularity; ?>view">
    <?php print theme('calendar_stripe_stripe', array('item' => $item)); ?>
    <div class="<?php print $item->date_id ?> contents">
      <?php foreach ($rendered_fields as $field): ?>
        <?php if ($index++ == 0 && (isset($item->continuation) && $item->continuation)) : ?>
        <div class="continuation">«</div>
        <?php endif;?>
        <?php print $field; ?>
      <?php endforeach; ?>
    </div>
    <?php if (isset($item->continues) && $item->continues) : ?>
    <div class="continues">»</div>
    <?php else : ?>
    <div class="cutoff"> </div>
    <?php endif;?>
  </div>
  </div>
</div>

```

So I need to get that class in the first DIV

```
<div class="<?php print !empty($item->class) ? $item->class : 'item' . ENTER-FIELDCLASS-HERE; ?>">

```

I've been looking in the VIEWS module and the code taht checks if you entered a CSS class should be this part in the THEME.inc file:

```
if ($classes = $object->handler->element_classes($view->row_index)) {
          if ($class) {
            $class .= ' ';
          }
          $class .=  $classes;
        }

```

A more complete part:

```
$previous_inline = FALSE;
  $vars['fields'] = array(); // ensure it's at least an empty array.
  foreach ($view->field as $id => $field) {
    // render this even if set to exclude so it can be used elsewhere.
    $field_output = $view->style_plugin->get_field($view->row_index, $id);
    $empty = $field->is_value_empty($field_output, $field->options['empty_zero']);
    if (empty($field->options['exclude']) && (!$empty || (empty($field->options['hide_empty']) && empty($vars['options']['hide_empty'])))) {
      $object = new stdClass();
      $object->handler = &$view->field[$id];
      $object->inline = !empty($vars['options']['inline'][$id]);

      $object->element_type = $object->handler->element_type(TRUE, !$vars['options']['default_field_elements'], $object->inline);
      if ($object->element_type) {
        $class = '';
        if ($object->handler->options['element_default_classes']) {
          $class = 'field-content';
        }

        if ($classes = $object->handler->element_classes($view->row_index)) {
          if ($class) {
            $class .= ' ';
          }
          $class .=  $classes;
        }

        $pre = '<' . $object->element_type;
        if ($class) {
          $pre .= ' class="' . $class . '"';
        }
        $field_output = $pre . '>' . $field_output . '</' . $object->element_type . '>';
      }

```

Not the most clear code to me. It can't be that hard. If only something like $field-\>class would work!

Thanks in advance!

# Answer
> 0 votes
You can add a class through the views interface:

1. Go to views ui
2. Under "Fields", click on the field you want to change
3. Click on "Style Setting"
4. Choose "Customize Field HTML"
5. Click "CSS Class" and enter your new css class

Alternatively, you can also achieve this through theme pre rendering.

* View machine name: "your\_view\_name"
* Field machine name: 'yourfield'
* New class: "your\_new\_css\_class"

Add to the file template.php in your theme directory:

```
function yourtheme_views_pre_render(&$view) {

  if ($view->name == "your_view_name") {
     $view->field['yourfield']->options['element_class'] = "your_new_css_class";
  }

}

```

To debug, download and enable the devel module (http://drupal.org/project/devel), and write out the variables:

```
function yourtheme_views_pre_render(&$view) {
    if ($view->name == "your_view_name") {
        drupal_debug($view->field['yourfield']->options['element_class']);
    }
}

```

The output will appear in tmp/drupal\_debug.txt (depending on how you configured your tmp directory).

# Answer
> 0 votes
So I found the solution:

```
$item->entity->YOUR_FIELD['und'][0]['value']

```

After a month of digging trough thousands of lines of codes, I just had to add this simple line.

I don't know if it's best practice, but in my case it'll do the job. If you try to print a value from Views and need the path, try `print_r $item` for a change. It gave me a better view to define the path than `print_r $view`.

Cheers!

---
Tags: theming, datetime
---


# Question
Title: how to change taxonomy term fields before being created first time
I'm trying to copy parent's image field to a "goint to be created" taxonomy term using this code but it isn't working:

```
function my_module_taxonomy_term_insert($term) {
    if ($term->vid == 29) {

        //if any of parents have logo then copy it
            foreach ($term->parent as $p) {

            if (isset($p->field_image[LANGUAGE_NONE][0]['fid'])) {
                //copy the image
                $filepath = drupal_realpath($p->field_image[LANGUAGE_NONE][0]['uri']);

                // Create managed File object and associate with Image field.
                $file = (object) array(
                            'uid' => 1,
                            'uri' => $filepath,
                            'filemime' => file_get_mimetype($filepath),
                            'status' => 1,
                );

                $term->field_image[LANGUAGE_NONE][0] = (array) $file;
            }
        }
    }
}

```

How to do this?

# Answer
> 2 votes
In Drupal 7, you can achieve this by using the following taxonomy APIs

```

/**
 * Implementing hook_taxonomy_term_insert
 */
function hook_taxonomy_term_insert($term) {
  $vid = 2; //User your vid
  if (is_object($term) && $term->vid == $vid && isset($term->parent)) {
    //get parent tid using $term->parent array
    foreach ($term->parent as $ptid) {//check image for each parent, if image exist assign and exit
      if ($ptid > 0) {//except root
        //get parent image WHERE field_data_field_image_vocab_image is the parent image field
        $pfid = db_select('field_data_field_image_vocab_image', 'pimg')//change field_data_field_image_vocab_image with your field name
            ->condition('pimg.entity_id', $ptid, '=')
            ->fields('pimg', array('field_image_vocab_image_fid'))//change field_image_vocab_image_fid with your image fid name
            ->execute()->fetchField();
        $update_taxo = taxonomy_term_load($term->tid); //load created taxonomy
        if ($pfid > 0 && empty($update_taxo->field_image_vocab_image)) {//image exist for this parent $ptid and image is not assigned yet
          $update_taxo->field_image_vocab_image[LANGUAGE_NONE][0]['fid'] = $pfid;
          taxonomy_term_save($update_taxo); //update taxonomy after assigning image
          break; //break after saving the image
        }
      }
    }
  }
}

```

Note :

* Change the field names
* Go through the comments for explanation.

# Answer
> 0 votes
I doubt in `$parents = taxonomy_get_parents($term->tid);`since this is presave hook, so you might not be getting the term id. Presave hooks are suppose to call before the taxonomy is actually created so might be no tid, so instead of persave you can go for hook\_taxonomy\_term\_insert(),this hook get invoked after term is created.

# Answer
> 0 votes
You can add your own submit handler and change term properties while it's not saved.

You can add your custom form submit handler before term\_insert. Look at hook\_form\_alter and add your custom submit function before taxonomy\_form\_term\_submit.

---
Tags: 7, taxonomy-terms
---


# Question
Title: How to have separated enabled modules in multisite based on Domain Access?
I have installed 'Domain Access' module to handle some sub-domains on a multisite installation based on Drupal 7.

This module share users, nodes and modules. But I want to have separated modules enabled on each sub-domain. But it seems if I enable a module it will be accessible on all the sub-domains.

Is the any way to bypass it? Sharing users and nodes are good points of this module and I need them but sharing modules ... no.

# Answer
It's been a year or two since I have used the Domain Access module on a site, but I don't think this is possible.

Domain Access runs all of the affiliate sites out of the same database, so there is a single `{system}` table, which is where all of the module info it. Essentially, the module provides some content access rules based on domain (ie, `node_access()` based controls), along some helpers for other site-specific tasks and integration with other modules. In the end, though, you still have a single database which means you have a single site.
> 2 votes

# Answer
I think you need to install them by hand (not using the back-office) inside the correct folder in "DRUPAL\_ROOT/sites/mysubdomain.com/modules". Some tutorials mentionning the folder structure you should use: here and here
> 0 votes

---
Tags: 7, domain-access
---


title: Cron Run and Cache

text:
# Question
Title: Cron Run and Cache
I'm running Drupal 7.25 on my Ubuntu server. I have a process that is kicked off by user interaction (form) that needs to run in the background. I currently have cron.php being run every minute via crontab. I read this article:

http://www.metaltoad.com/blog/how-drupals-cron-killing-you-your-sleep-simple-cache-warmer

Does running cron.php still clear cache in D7?

# Answer
> 3 votes
Yes, running cron.php still clear cache, as running the cron will call system\_cron which calls "cache\_clear\_all" method:

```
$cache_tables = array_merge(module_invoke_all('flush_caches'), $core);
foreach ($cache_tables as $table) {
  cache_clear_all(NULL, $table);
}

```

# Answer
> 10 votes
If you take a look at `system_cron()`, you will see

```
$cache_tables = array_merge(module_invoke_all('flush_caches'), $core);
foreach ($cache_tables as $table) {
  cache_clear_all(NULL, $table);
}

```

Reading the docs for `cache_clear_all($cid, $bin)`:

> **$cid**: If set, the cache ID or an array of cache IDs. Otherwise, all cache entries that can expire are deleted. The $wildcard argument will be ignored if set to NULL.

This means that a full cache clear won't be done, but entries that are older than their TTL are removed from the cache.

However, `{cache_page}` uses `CACHE_TEMPORARY` for the TTL (see `drupal_page_set_cache()`, so these will be removed each cron run. Though the code support it, I have never seen anything other that a `-1` in the exipres column in `{cache_page}`, no matter what the TTLs on the performance settings are.

---
Tags: 7, caching, cron
---


# Question
Title: How to show Content Titles only in Entity Reference drop down list, but restrict general access to the Content Type?
Drupal 7.25

I have a list of "Locations" (content type) and need people to select an item from this list when they register on the site.

However, I do not want anonymous or authenticated users to view the detailed contents of these locations.

When I restrict the permissions on the content type, this removes all the values from the entity reference list for anonymous users when they try and register.

So is there an easy way to show ONLY the content Title field in the list, without people being able to then see all the other fields for the content type?

Thanks for any help!

# Answer
> 0 votes
OK, so the only way I found to do this was install the field\_permisssions module and restrict access to all the custom fields for specific roles.

Not ideal, but achieves the objectives. There are a lot of fields and it took quite a while. Also need to remember to restrict fields when creating new ones.

---
Tags: 7, entities, users
---


# Question
Title: How to conditionally display field contents in Views
**I want to edit my View so that it only displays a certain contents if some field in my content type had been set.** I installed the Views PHP plugin, but it's currently not producing the desired results.

This is the current example I have - using the custom php field, where `field_link_to_page` is a checkbox field in my content type that decides what contents are to be displayed:

```
<?php
// Field is configured to return "1" if it's checked, or "0" if it's unchecked.
if ($row->field_link_to_page =="1") {
    echo $row->body."<a href=\"node/"

?>
[NID]
<?php
echo "\">more...</a>";
}
else
{
    echo $row->body;
}
?>

```

Removing this code, and doing a `var_dump()` on the field, returns something like this:

```
object(stdClass)#250 (7) { ["field_year"]=> string(3) "113" ["field_month"]=>
string(3) "113" ["field_day"]=> string(3) "113" ["title"]=> string(73)
"Forecast opening day for Talking Rock Golf Course (conditions permitting)"
["body"]=> string(3) "113" ["field_link_to_page"]=> string(3) "113" ["php"]=>
NULL } 113

```

which is confusing because the contents get rendered nicely by Views but here it only looks like it's handles to something (113). How can I render the contents correctly in php?

# Answer
I have figured out a way to do what I want without the Views PHP module: I added the link to my fields as well and rewrite the link token in my checkbox field (field\_link\_to\_page) only if it isn't empty. That seems to have worked out well.
> 2 votes

# Answer
Views has an option to see the value 0 as an empty result. And you can disable rewriting for empty results (thus 0 value too).

Then you can use a simple rewrite like `[body]<a href="node/[nid]">more</a>`.

I do think you don't need php here to accomplish what you want.
> 1 votes

# Answer
The second line of code in your example has a typo, you're missing a semicolon. Also, this number you're doing here feels squishy:

```
<?php
// code ...
?>[NID]<?php
// code ...
?>

```

Is that even working? **Wouldn't it be better to just `var_dump()` the whole `$row` object, find where the node nid for the current row is present, and create a link using l()**?

You should always use the Drupal API when creating links, unless for a very specific reason.
> 0 votes

---
Tags: views
---


# Question
Title: title_prefix override to h1 instead of h2
How do I override the $title\_prefix that is inherited from the value of

```
    <h2<?php print $title_attributes; ?>><?php print $title; ?></h2>

```

in panels-pane.tpl.php page. This is normally output in the page.tpl.php but since i'm using panels it becomes the above.

My stating attempt is to write a template.php preprocess function, but this adds the code to every title in the template, and just adds the h1 to the page; it does not replace the h2 with the h1 for each page title. I don't want to touch the `$title` value which is h2 but change `$title_prefix`.

```
// Preprocess title prefix override. h1 instead of default h2
function at_panels_everywhere_preprocess(&$vars) {
  $vars['title_prefix'] = array(
    '#type' => 'markup',
    '#markup' => '<h1></h1>',
  );
}

```

I need to replace the `$title_prefix` ouput to be h1 not h2 and only for the title\_prefix while within the #content region.

# Answer
> 1 votes
Potential solutions that didn't work:

http://drupal.org/project/panel\_variant\_page\_title Changing panels-pane-tpl.php h2 to h1 as this changes all panels not the 1 page panel that needs to be h1.

Eventual solution:

Turning off Page panel titles and just hardcoded h1 tag into body field. Not ideal but there really is no working solution apparently.

# Answer
> 0 votes
You can't use `_preprocess` hook function if you are using panels to replace h2 with h1 because h2 is hard coded in the template file.

You need to copy `panels-pane.tpl.php` template file from `sites/all/modules/panels/templates` folder to your Drupal custom theme `sites/all/themes/CUSTOM_THEME/templates`.

Then edit `panels-pane.tpl.php` and change h2 to h1

```
<h2<?php print $title_attributes; ?>><?php print $title; ?></h2>

```

to

```
<h1<?php print $title_attributes; ?>><?php print $title; ?></h1>

```

# Answer
> 0 votes
I haven't tried it yet but it looks like a good approach:

```
<?php if ($title): ?><?php if($display->title_pane == $pane->pid) : ?>
<h1 class="pane-title"><?php print $title; ?></h1>
<?php else : ?>
<h2 class="pane-title"><?php print $title; ?></h2>
<?php endif; ?>
<?php endif; ?>

```

https://drupal.org/comment/4004824#comment-4004824

---
Tags: panels, 7
---


title: Ordering of referenced entity

text:
# Question
Title: Ordering of referenced entity
I have created one content type named "collection", where I will be grouping the related articles into collection. The content type itself has other fields like title, tags etc.

To add article into collection, I have created field of type referenced entity and is working fine. Also use can add multiple articles into collection.

Now I wanted to provide the user to manage order of the articles in the collection, so that article can be arranged in proper order.

So at the time of selecting article, user also decides its order/weight.

Is there any drupal module that helps in achieving this or how can I achieve it if no module is there.

-- Thanks for your time

# Answer
> 5 votes
If you are using Entity reference has the option to sort. I will give you three choices.

**1. Manually:**

Go to the /node/nodenumber/edit and you can specify the order that you want Manually seems to be your best choice because it is your user who decides the order

**2. Programatically**

If want to order by descending (Ascending is the default). The only it worked for me was to use array\_reverse:

```
$value -> field_reference_field_to_reference['und']=array_reverse($value -> field_reference_field_to_reference['und']);
$value -> field_reference_field_to_reference['und'][]['target_id'] = $node -> nid;
$value -> field_reference_field_to_reference['und']=array_reverse($value -> field_reference_field_to_reference['und']);
node_save($value);

```

**3. Fields settigs in the entity reference**

There is another option of sorting in your content type field settings:

/admin/structure/types/manage/volunteer-profile/fields/field\_reference

and then you can tell it to sort by

However, to be honest the last method number 3 has not worked for me for some reason. If you made it work. Please let me know your solution. I would love to know what am I doing wrong. :)

# Answer
> 6 votes
To add detail to Solution #1, above, for folks coming afterwards looking for the same answer:

When creating the Entity Reference field on the main content type (whichever Content Type will display the referenced entity) under "Widget" select "autocomplete", as mentioned. Under "Number of Values", select "unlimited" (or more than one). Save that Content Type.

Then, when you create or edit the node that is made from that Content Type, you will see the Entity Reference autocomplete option towards the bottom of the content entry form. To the upper right of that part of the form, you will see "Hide Row Weights" or "Show Row Weights" as a small text link. Once you show the row weights you can give your results a sort order.

Small aside: Once you have enabled "Show Row Weights", this choice will persist in your control panel. So if you want to be able to sort menu items (for example) by dragging, you'll have to toggle this link back to "Hide Row Weights".

# Answer
> 2 votes
There is an option to do what Cayerdis recommends in option 1 without using the Autocomplete option. The multiple selects widget is "a fairly simple rework that turns a single multiple value select list into a series of single value select lists, with an 'Add more' button. It's very easy to set up, just enable the module and choose the 'Multiple Selects List' widget as the widget." (-- from lullabot article).

https://drupal.org/project/multiple\_selects

See this article for several options to extend the functionality -\> http://www.lullabot.com/blog/article/entityreference-multiselectors

# Answer
> 0 votes
Please see if this solution would work for you.

Create a group field one with the entity and the other with an order field of the type text where the user can enter a number to represent the order. then you can use this field to order the article.

---
Tags: 7, nodes, entities
---


# Question
Title: Checking if personal contact form exists
I am using a custom user-profile.tpl and I want to add a 'contact user' link to the viewed users personal contact page.

How can I check that the user in question has a contact page enabled? Is there a variable I can look at, or maybe a db query that can be run?

I am not using tabs on the user profile page.

Thanks, Paul.

# Answer
This is taken from contact.module:

```
function _contact_personal_tab_access($account) {
  global $user;

***snip***

  // If the requested user has disabled their contact form, or this preference
  // has not yet been saved, do not allow users to contact them.
  if (empty($account->data['contact'])) {
    return FALSE;
  }

***snip***

  return user_access('access user contact forms');
}

```

You should be able to see in the user object whether or not they have they are allowing people to contact them. This will also be empty if they don't have a contact form.
> 1 votes

---
Tags: 7, emails
---


# Question
Title: Use webform submission id in custom content type
I am working on a patient/doctor kind of project where by the patient fills a questionnaire and then the doctor provides a prescription.

I have used webform module to create the questionnaire which the patients would fill, and i have created a custom content type for the prescription.

I need to be able to relate the submission Id of the questionnaire to the prescription but I am not sure how to do it.

Please note that a patient can fill various questionnaires so it is quite important that I use the submission id as it seem as the only unique id available.

I have tried the node reference module but that only gives me access to the questionnaire not submission id of the questionnaire.

# Answer
You're right - you can't use references with the webform submissions, because webform submissions are stored in their own special way - they're not actually proper Drupal entities, so they are not properly exposed to other modules expecting to interact with entities.

One thing you can try if you're not too far along in your project is to use the alternative Entityform project. That should expose form submissions to be referenced.

Let us know if it works! I haven't used the module myself, I've just heard of it.
> 1 votes

---
Tags: 7, nodes, webforms
---


# Question
Title: #ajax-processed not added on a form inside a custom callback (MY_MODULE_deliver_html_page)
Ok, a lot of things on the title so I'll try to explain everything on the question.

I'm trying to create a logic inside Drupal 7 to enable modal forms with AJAX.

This is the pipeline:

* Render a form with an #ajax callback in a modal (foundation reveal)
* Send a form via AJAX and receive Drupal ajax commands.

In order to print the form without the whole themed template I used a custom callback to render plain html.

```
$items['statusupdate/%statusupdate/delete'] = array(
        'title' => 'Delete',
        'page callback' => 'statusupdate_delete_confirm',
        'page arguments' => array(1),
        'access arguments' => array('delete statusupdates'),
        'weight' => 1,
        'type' => MENU_LOCAL_TASK,
        'context' => MENU_CONTEXT_INLINE,
        'delivery callback' => 'MY_MODULE_deliver_ajax_html_page',
    );

```

Attempt 1 - not working

```
function MY_MODULE_deliver_ajax_html_page($page_callback_result) {
    print $page_callback_result;
    return null;
}

```

Attempt 2 - Create a custom template to load javascript, not working (the logic is on the php side)

```
function MY_MODULE_deliver_ajax_html_page($page_callback_result) {
    print theme('page-ajax-html', array('page' => $page_callback_result, 'styles' =>'', 'scripts' =>drupal_get_js()));
    return null;
}

```

This works fine to render only the form in plain HTML but by doing so no ajax logic is applied to the form.

**Drupal\_render($form) renders the form, but is not adding #ajax-processed.**

**I tried to render the $form inside the page.tpl.php and AJAX works**, so my guess is that rendering the $form in plain HTML some ajax preprocess logic.

Form:

```
function statusupdate_confirm_form($form, &$form_state, $data)
{
    $form['#id'] = 'statusupdate-confirm-form';

    $form['submit'] = array(
        '#type' => 'submit',

        '#value' => t('Delete'),
        "#ajax" => array(
            "callback" => "delete_statusupdate_callback",
            "effect" => "fade",
        ),
    );
    return $form;
}

```

Form rendering:

```
function statusupdate_delete_confirm($statusupdate) {
    $form = drupal_get_form('statusupdate_confirm_form', array());
    $form['submit'] = ajax_pre_render_element($form['submit']);
    $html = '<div class="">'.t('Careful').'!</div>';
    $html .= '<div class="">'.t('Are you sure you want to delete %status_id?', array('%status_id' => $statusupdate->status_id)).'</div>';
    $html .= '<a class="close-reveal-modal">×</a>';
    $html .= drupal_render($form, '');
    return $html;
}

```

HTML Result

```
<form action="/statusupdate/12/delete" method="post" id="statusupdate-confirm-form" accept-charset="UTF-8"><div><input type="submit" id="edit-submit" name="op" value="Delete" class="form-submit"><input type="hidden" name="form_build_id" value="form-muOSqaoWicTDGYZ-IAp149QAmMpsOPKNsq8WXH2XSLI">
<input type="hidden" name="form_token" value="ckXsiTcF2_sINFfKdNj3uK6L9FiJv3krg1jnhKh0Vsk">
<input type="hidden" name="form_id" value="statusupdate_confirm_form">

```

Any idea?

# Answer
The problem why the ajax is not working with loaded forms through ajax is because of the missing javascript behaviors attached to the form. These provides all client side code (and which adds the `.ajax-processed` class on the element).

To be able to add these needed behaviors, you need to make used of the `ajax_pre_render_element` and `attaching` these to the page. Also important, is that you print out the JS code by calling `drupal_get_js()`.

This is how I managed to get it working.

```
function YOURMODULE_form($form, &$form_state)
{
    // Same form build as your example
    $form = array();

    $form['#id'] = 'statusupdate-confirm-form';
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Delete'),
        "#ajax" => array(
            "callback" => 'delete_statusupdate_callback',
            "effect" => "fade",
        ),
    );

    return $form;
}

// Menu callback used to only how the form (standalone) without the theme HTML
function YOURMODULE_page()
{
    // Get the form
    $form = drupal_get_form('YOURMODULE_form');

    // Process the submit button which uses ajax
    $form['submit'] = ajax_pre_render_element($form['submit']);

    // Build renderable array
    $build = array(
        'form' => $form,
        '#attached' => $form['submit']['#attached'], // This will attach all needed JS behaviors onto the page
    );

    // Print $form
    print drupal_render($build);

    // Print JS
    print drupal_get_js();

    return null;
}

```
> 4 votes

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


# Question
Title: Views Slideshow with numbered navigation disappears
So a little background on my current setup. The views slideshow having issues is on the homepage: http://pacificwhale.org

I am running Drupal 6, and using Views slideshow 2.4 with nodequeue to feed 6 nodes that are of the photo content type. The slideshow that I am working closely with sits on the homepage of my website. Sometimes it works, sometimes it doesn't. When it stops working, the numbered navigation disappears from the page, and in the source code, I'm noticing that the jQuery.extend function call in the html page header is missing this code:

> "viewsSlideshowSingleFrame": { "#views\_slideshow\_singleframe\_main\_nodequeue\_1-block": { "num\_divs": 6, "id\_prefix": "#views\_slideshow\_singleframe\_main\_", "div\_prefix": "#views\_slideshow\_singleframe\_div\_", "vss\_id": "nodequeue\_1-block", "timeout": 5000, "sort": 1, "effect": "fade", "speed": 700, "start\_paused": 0, "delay": 0, "fixed\_height": 1, "random": 0, "pause": 2, "pause\_on\_click": 0, "pause\_when\_hidden": 0, "pause\_when\_hidden\_type": "full", "amount\_allowed\_visible": "", "remember\_slide": 0, "remember\_slide\_days": 1, "controls": 0, "items\_per\_slide": 1, "pager": 2, "pager\_type": "Numbered", "pager\_hover": 1, "pager\_click\_to\_page": 0, "image\_count": 0, "nowrap": 0, "sync": 1, "advanced": "", "ie": { "cleartype": "true", "cleartypenobg": "false" } } } });

To view the html for the slideshow you can do a view source from our homepage.

To make the numbered navigation work, I must from the admin area of drupal6 perform a "flush all caches" from a page *other than* the homepage. After doing this, if I navigate to the homepage while logged into the admin area, the slideshow will not work, and there will be no numbered navigation. However, if I log out of the admin area and then navigate to the homepage and view the slideshow, I notice that the numbers are working and the slideshow automatically rotates through my images.

An interesting oddity, is that if I am logged into the admin area and I perform a "flush all caches" from the homepage, then the slideshow will display navigation and work inside the admin area, but if I log out of the admin area, it will not display the numbered menu, and for me or any other viewer of the website the slideshow is broken with no navigation, and the jQuery.extend function is missing the viewsSlideshowSingleFrame variable settings.

Another interesting oddity is that the slideshow navigation once fixed by flush all caches, later on it will revert back to not working, and I must go through the steps again to get it to work, and I'm in a hopeless cycle to get it to work again.

I've attached a screen capture of my views setting for nodequeue\_1. You'll notice that I've turned off caching for this view/nodequeue, so I don't understand why flushing all caches makes a difference in fixing the slideshow navigation.

# Answer
> 1 votes
Hi I don't normally post replies but I had a similar issue to you where my Carousel module with slide show stopped working in December 2013

Only when logged in as admin would I see the correct view

I was sure this has stopped about the time i updated some modules

After a bit of trial an error I noticed that the upgrade from 1.3 on 1.4 on Responsive Menus Module caused the issue

By using a 1.3 module the problem went away

Check which version you are using under 'Modules' and 'USER INTERFACE' section of administrator menu

---
Tags: 6, javascript, views, nodes
---


# Question
Title: Followed the How can I link an image of a jCarousel to a certain link? page but need further help
I followed the instructions on linking hyperlinks in jcarousel found here: How can I link an image of a jCarousel to a certain link?

The problem is that I don't have the Formatter drop down field in my view.

Attached is a screenshot of what I see.

These are the choice I have when adding a link to the view. It appears to be the same link as what is in the original instruction:

# Answer
> 0 votes
The field 'link' you have added is configured as a simple `Text` field from Content type field manager.

You need to choose Field Type as `'Link'` while creating it. Then only you can find those options in views.

My suggestion would be to create a new field 'link' and add it to views.

Let me know if you still find issues. :)

---
Tags: entities
---


# Question
Title: Advanced sorting question about drupal views
I have a content type with latitude and longitude coordinate fields. i have a view that is displayed on each page with this content type, and a google map plotting the location. Is there any way to sort a view using the distance between points?

distance=( ( current\_page\_lat - view\_item\_lat) + ( current\_page\_lng - view\_item\_lng ) )

# Answer
> 0 votes
You will need help of views\_php module. This module will help to sort views rows with a calculation. You need to go through.

But in your case, The calculation has a value from current page. So you have to get the current page value (lang, lat) in sorting field, may be you can use it as a global variable or call a function from inside the php field.

Hope this helps you. :)

---
Tags: views
---


# Question
Title: Member for - how Drupal 7 calculaties and formats duration?
Drupal 7 has ability to show since how long someone is member, like this:

> Member for 2 months 21 hours

What date field it uses to save the registration date/time? How it calculates and displays this duration? And can't we use same module / method to calculate duration from our date (in node) and display in our views?

I am really in need of this functionality of calculating of duration, I am using views Calc and subtracting end-date from start-date and dividing it with number of seconds in day to get number of days between two days. but not satisfy besides don't know why can't subtract `now()` from a given date field in views calculations.

# Answer
> 4 votes
```
$account->content['summary']['member_for'] = array(
  '#type' => 'user_profile_item',
  '#title' => t('Member for'),
  '#markup' => format_interval(REQUEST_TIME - $account->created),
);

```

It's in `function user_user_view($account)`. And yes, of course you can use `format_interval($interval)` function in other places.

---
Tags: views, datetime
---


title: Calculating duration between two dates

text:
# Question
Title: Calculating duration between two dates
I am using Views Calc for Drupal 7 to calculate duration. I have some questions:

If use Date (Unix timestamp) and subtract end date from start date of my date field with time it gives me seconds then I divide it with 86400 (the seconds in a day) it gives me number of days.

My code in Views Calc:

```
( %field_data_field_we_from_date.field_we_from_date_value2 -
  %field_data_field_we_from_date.field_we_from_date_value ) / 86400

```

which is great;

however:

1. If I use date (not UNIX time stamp) and with no time only year, month, and day then it gives me a number which I don't understand what it represents. If I divide it with 86400, the answer does not look correct. My problem is that we don't need to add time in the field. The end-user doesn't like to see time field with date.
2. When I try to use `NOW()` it give error in Views Calc setting which says `NOW value is not allowed here!` I need `NOW()` \- my\_date\_field to get age and other duration which do not have end date field.
3. `ROUND()` function also doesn't seem to be working.

Any help would be highly appreciated.

# Answer
You can do a little tweak.

After you get the only date in `YYYY-MM-DD` string format, concate `00:00:00` as time to the string. then you can get unix time format by using function `strtotime()` that takes a string date format and returns an integer of time format (unix).

Hopefully this helps you getting the correct duration.
> -1 votes

---
Tags: views
---


title: Mini-site on Sub-Domain

text:
# Question
Title: Mini-site on Sub-Domain
I'm about to start a Drupal project for a client who has a large site currently set up on Drupal. The project will be a mini-site on a subdomain and will be totally different from the main website.

The mini-site will probably be a one-page website and the client wants to be able to easily edit the test on there. The one-page website will be fairly long and will need custom HTML.

My initial thought was to just code the HTML directly into a new page via Drupal and enable 'Full HTML' as the content type - my only worry is that I don't want the client to see/edit the HTML code, I only want them to be able to edit the text content.

So my question is quite simple - what would be the best way to go about doing this?

# Answer
> 0 votes
What I would do is create a new content type "Specific page" (id: specificpage).

In the content type, put all the "fields" / content that your client can edit. You don't want your client to break your HTML structure, but he probably wants to edit the title, the content, the background color, etc. Define all the fields he could want to edit and create them in your content type.

Use this code to theme the "page.tpl.php" for this specific content type:

```
function phptemplate_preprocess_page(&$vars) {
  if (arg(0) == 'node') {
    $vars['theme_hook_suggestions'][]  = 'page__' . $vars['node']->type;
  }
}

```

Then create a page--specificpage.tpl.php based on the original page.tpl.php, put it in your theme folder, structure your HTML content and display the fields defined by your client in the back-office.

\[Edited the answer bc I did a mistake in the code and template suggestion\]

---
Tags: nodes, theming, subsites
---


title: Views complex sort

text:
# Question
Title: Views complex sort
I have a Drupal view which displays 10 items. I have 3 items which need to remain at the top of the list, which i have done by making them sticky. These need to be in a particular order. The the rest of the list then needs to be in alphabetical order. How can I do this?

Here are my current view settings:

```
Title
Title: None
Format
Format: Unformatted list | Settings
Show: Fields | Settings
open

    Add

Fields
Content: thumb
Content: Title
Content: Body
Content: Link
open

    Add

Filter criteria

Content: Published (Yes)
Content: Type (= Mineral)
Content: Title (!= others)
open

    Add

Sort criteria
Content: Sticky (desc)
Content: Title (asc)
Block settings
Block name: minerals
Access: Permission | View published content

    Add

Header

    Add

Footer
Pager
Use pager: Display a specified number of items |  items
More link: No
Advanced

    Add

Contextual filters

    Add

Relationships

    Add

No results behavior
Exposed form
Exposed form style: Basic | Settings
Other
Machine Name: block
Comment: No comment
Use AJAX: No
Hide attachments in summary: No
Hide contextual links: No
Use aggregation: No
Query settings: Settings
Field Language: Current user's language
Caching: None
Link display: None
CSS class: None
Theme: Information
Block caching: Do not cache

```

# Answer
If you ask about how to show the sticky ones in a particular order, you can add anonther custom field (e.g. "position") to the content-type. Define a number for the position and add another filter criteria for this custom field.

The sort criteria for the position should be set before the other sort filters.
> 2 votes

---
Tags: 7, views
---


# Question
Title: External login , in case internal login fail
I have a website which needs to authenticate users using drupal **users** table.

If authentication fails, then I want to run the authentication against users table from another database.

lf authentication is successful , then I want to register this user inside drupal, so the next this user next time he logs in , he get authenticated from drupal users table , not the external users table.

I wish to get a complete solution for that.

the following code is my attempt :

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

$form['#validate'] = array( 'user_login_name_validate' );
user_login_authenticate_validate( $form, $form_state );
if(!empty($form_state['uid'])){

db_set_active('barakah');
$result=db_query('select username,password from users where username= :name   and password= :pass',array(':name' =>$form_state['input']['name'],':pass'=>$form_state['input']['pass']));
db_set_active('default');
if(!empty($result)){
$username = $form_state['input']['name'];
user_external_login_register($username, 'external_auth');

}

}

}

```

but as if the code doesn't exist, nothing happens

# Answer
You can use:

`drupal_external_login_register`

> Helper function for authentication modules. Either logs in or registers the current user

An example implementation is detailed here:

https://api.drupal.org/comment/13434#comment-13434
> 0 votes

# Answer
Try something like this :

```
function custom_user_validate_login_validate(&$form,$form_state){
    $form['#validate'][] = 'custom_user_validate_login_validate';
}

function custom_user_validate_form_user_login_alter($form, &$form_state) {
    drupal_set_message("Custom Validation"); //Just to check if the hook_validate is called
    user_login_authenticate_validate( $form, $form_state );
    if(empty($form_state['uid'])){ // remove the ! here
        db_set_active('barakah');
        $result=db_query('select username,password from users where username= :name   and password= :pass',array(':name' =>$form_state['input']['name'],':pass'=>$form_state['input']['pass']));
        db_set_active('default');
        if(!empty($result)){
        $username = $form_state['input']['name'];
        user_external_login_register($username, 'external_auth');
        }
    }
}

```

\[Edit\] Need to remove \['submit'\] from hook\_form\_alter

\[Edit2\] Renaming the function names: replace custom\_user\_validate by your module name

\[Edit3\] Updating the name of hook\_validate to match function names
> 0 votes

---
Tags: users
---


title: Base table missing on Database Restore

text:
# Question
Title: Base table missing on Database Restore
**Problem**

I just tried to revert to a recent backup and got a very strange error.

* Wiped database.
* Deleted drupal base folder.
* Copied in new Drupal folder (from backup).
* Ran install.php

Re-installing was successful (except for the failure to send an email), but on loading the site I got the following error:

`PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'mysite2.languages' doesn't exist: SELECT * FROM {languages} ORDER BY weight ASC, name ASC; Array ( ) in language_list() (line 2727 of /srv/www/mysite2/public/includes/bootstrap.inc).`

Any idea what could've caused this?

**My Thoughts**

I've not restored the the database yet so I don't quite understand what could cause this? None of the modules that I have in my build should begin enabled after a basic install.

But it does seem as if some part of my folders or modules are interfering with a basic drupal install, calling something which doesn't exist yet and blocking me. Even though they shouldn't be enabled.

# Answer
Solved by Clive. I had memcached running. It had stored chunks of the code from my original site and tried to run them on the new version. Clearing or restarting memcached solved the problem.

Edit:

An overly simplified explanation of memcached for anyone who's unsure what I'm talking about.

Memcached caches chunks of code. It's best illustrated by a contrast. Varnish caches a static picture of a page and sends that to people when it's requested. It will bypass PHP processing completely.

Memcached won't stop the processing for the page happening each time, but it will remember chunks of the processing and deliver the result straight from the cache.

When I wiped my server and reverted to a backup I forgot to restart memcached. This means that memcached had still remembered chunks of my PHP code. This code didn't fit in with the older revert of my website so I got a horrible error. Restarting memcached or flushing the memcached cache will solve this.
> 2 votes

---
Tags: 7, installation, backups
---


# Question
Title: How to replace I18nVariableLanguageRealm controller?
I have done custom module with .class.inc and .module file. Class file is added in module info file.

Inside class file:

```
/**
 * Controller for Language realms.
 */
class MyModuleI18nVariableLanguageRealm extends I18nVariableLanguageRealm {
  public function getKey() {
    return isset($this->current_key) ? $this->current_key : FALSE;
  }
}

```

Inside module file:

```
/**
 * Implements hook_variable_realm_info
 */
function mymodule_i18n_variable_variable_realm_info() {
  $realm['language'] = array(
    'title' => t('Language'),
    'weight' => 1,
    'controller class' => 'MyModuleI18nVariableLanguageRealm',
    'store class' => 'VariableStoreRealmStore',
    // Variables for this realm can be selected from a list.
    'select' => TRUE,
    'select path' => 'admin/config/regional/i18n/variable',
    // Name for variables that belong to this realm: 'multilingual' variable/s
    'variable name' => t('multilingual'),
    'variable class' => 'i18n-variable',
    // Automatically handle these variables in system settings forms.
    'form settings' => TRUE,
    'form switcher' => TRUE,
  );
  return $realm;
}

```

but debugging shows that custom controller isn't in use. What am I doing wrong here?

# Answer
In the Drupal world 'replace' in your context is usually synonymous with 'alter'.

Try this:

```
function mymodule_i18n_variable_variable_realm_info_alter(&$realm) {
  $realm['language']['controller class'] = 'MyModuleI18nVariableLanguageRealm';
}

```
> 2 votes

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


# Question
Title: How to change operator in schema.xml and configure site for AND search
I am using Solr search with drupal.Its working fine on my site but the problem is i needed the search to be a specific to the searched content. If i searched for "assembly and key",the search result showing all results which is having the world assembly and key also.

But I needed the result like wherever this particular word is found not the separate. when i search for "assembly and key" it is giving me around 55 results and when i am searching "assembly+and+key", it is giving only 1 result which is i want. So please let me know how to do it.

I have tried to change solr/conf/schema.xml for AND operator also tried to add code in apachesolr module file for changing the mm parameter but it doesn't work.

# Answer
You need not to edit the Solr\_Base\_Query.php file just add the following line of the code in your module

```
function modulename_apachesolr_query_prepare($query){
$query -> addParam('q.op', 'OR');

```

}
> 0 votes

---
Tags: search
---


# Question
Title: Adding an 'Add more' button to a settings form in the backend
For my module I need a settings form where administrators should be able to enter an arbitrary number of variables.

I have tried setting up an AJAX 'Add more' button, analogous to the example found in the AJAX example module. When I click the button, it doesnt add an extra field and I don't get any errors.

Can anyone help me out?

Example code, and my code: https://gist.github.com/Tagini/8282034

# Answer
It turns out I had two problems:

1. I have jquery\_update installed, which included a version too recent for the backend. I configured a previous version and I got a whole step further.
2. I did not have my $form and $form\_state as input parameters in my main form function and as such the field count was not updated.
> 0 votes

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


# Question
Title: in multi-site do you set base url for each sites settings?
Have just enabled security review module and it's alerting to base url not being uncommented and set. This is a multi-site so do I need to set the base url in each settings file for each site? I set the base url in settings for the root site but the alert still came up for subdomain of multisite where have not changed its settings file.

# Answer
To be more secure you should set the base url for each site, yes.

Setting this helps protect against a phishing attack where a malicious user manipulates Drupal's use of the host request header to make the site provide incorrect links.
> 1 votes

---
Tags: security, uri
---


title: Hook for removing product from cart

text:
# Question
Title: Hook for removing product from cart
I am removing products from cart programmatically using such a code:

```
commerce_line_item_delete($line_item_id)

```

The problem is, I cannot find any hook, that would be invoked after removing product from cart. I have tried hook\_commerce\_cart\_product\_remove, but this hook is not called when removing product with commerce\_line\_item\_delete function.

How can I remove product from cart programatically, so I can use hook after it happen?

# Answer
> 1 votes
If you want to remove product programatically, and still allow other modules to interact with this event, you should invoke hooks explicitly just after deletion using `module_invoke_all`:

```
module_invoke_all('commerce_cart_product_remove', $order, $product, $quantity, $line_item);

```

That way you have a choice - you can call it and emulate regular deletion, or you can omit it, and prevent any marketing interactions etc that your user did not trigger.

Alternatively, because line items are entities, you should be able to hook into their deletion with generic `hook_entity_delete`, without any modifications to the way you invoke deletion.

---
Tags: 7, hooks, commerce
---


# Question
Title: What's the correct format for submitting a null value to an integer field using metadata wrapper?
**Problem**

Whenever I submit a nothing to an integer field using the EntityMetadataWrapper I get the following error.

What's the correct format for submitting a null value to an integer field? (I don't want 0, but a blank value).

> *EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. in EntityMetadataWrapper-\>set() (line 122 of C:\XAMPP\htdocs\drupal\sites\all\modules\entity\includes\entity.wrapper.inc).*

How do you clear a field value with entity\_metadata\_wrapper()?

The post above implies I should be able to use:

```
$wrapper->title = '';

```

However this still throws the error.

**Example**

I have an integer field Salary added to a custom node type. (Along with several other fields which work as expected.)

Properties:

* Not required
* Has no minimum value
* No default value
* Can only hold one value.

I have a custom form which looks like this. This is the entry field:

```
$form['field_salary'] = array(
    '#type' => 'textfield',
    '#title' => t('Salary'),
    '#size' => 10,
    '#maxlength' => 10,
    '#description' => t('Please enter a valid number'),

```

This is the submit function taken from here:

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

 $values = array(
      'type' => 'job_advert',
      'uid' => $user->uid,
      'status' => 1,
      'comment' => 1,
      'promote' => 0,
    );
    $entity = entity_create('node', $values);

    $ewrapper = entity_metadata_wrapper('node', $entity);

    //.... (other fields in the form are here)
    $ewrapper->field_salary->set($form_state['values']['field_salary']);

    $ref_nid = 15;

    $my_date = new DateTime('January 1, 2013');
    $entity->field_my_date[LANGUAGE_NONE][0] = array(
       'value' => date_format($my_date, 'Y-m-d'),
       'timezone' => 'UTC',
       'timezone_db' => 'UTC',
     );

    $ewrapper->save(true);
    entity_save('node', $entity);

}

```

My guess is that it can't hold nothing? But that seems weird because it's not required.

I can for example create the node using the drupal default form with no errors and it works fine.

EDIT:

The solution from Wayne, removes the error but what I was hoping for was the ability to submit a blank value without it throwing an error. Unfortunately the following doesn't work.

```
'#default_value' => NULL,

```

I've considered using a string field instead of an integer one and then validating only for numbers, but this means I'll lose the ability to use the numeric range search facets, again not ideal.

# Answer
> 2 votes
Have you tried to check if the value exists before setting it?

```
//.... (other fields in the form are here)
if (!empty($form_state['values']['field_salary'])) {
  $ewrapper->field_salary->set($form_state['values']['field_salary']);
}

```

This way you're not touching the value if it's not set.

# Answer
> 0 votes
Try setting the #default\_value of the textfield. If the field is left blank no value is submitted with the form for that name (ie. $form\_state\['values'\]\['field\_salary'\]), so essentially attempting to apply a NULL value to the metadata.

Optionally, you could cast the value to an int:

```
(int) $form_state['values']['field_salary']; // OR
intval($form_state['values']['field_salary']); // both => 0 (zero) when NULL

```

which may not be a bad idea besides to ensure only numerical values are applied. This is, of course, assuming that you do not validate that before hand.

---
Tags: 7, entities
---


# Question
Title: How to place the pager for a view in page.tpl.php?
I have a view on my front page showing the latest posts, but the design of the website implicates the pager to be located outside the content area of the view (way across in the sidebar). Is there a way I can place the pager in the sidebar in page.tpl.php? I'm using my own custom theme. Any help is greatly appreciated, otherwise I'll have to hack up some CSS positioning but I'd rather learn more about drupal 7!

Thanks!

# Answer
The following steps might help you to extract the pager out of a view conatiner with a help of small css fix,

1 : Override the view template file I have created a view called extract pager and created a custom tpl for the same views-view--extract-pagertpl.php

2 : The data-members for pager will be available in the above tpl file copy and place the code into to a sepearte div container

```
<div class="pager-extract">
  <?php if ($pager): ?>
    <?php print $pager; ?>
  <?php endif; ?>
</div>

```

3 : Rescan the template files in the views and save the view.

4 : The above steps will help you to bring out the pager up to the view content block, use few css styles to theme your pager as per your requirements.
> 4 votes

# Answer
Separating pieces of content in Drupal is easy if the module returns render arrays instead of actual markup: just use `hook_page_alter`. Unfortunately, that's not the case for Views :/

Another trivial solution would be to print your view twice: once in the main content, again in a block (a separate display). Then, when it comes to theme the block, override the template and remove everything but the pager. Done! (see http://www.adesignforlife.net/articles/drupal-tutorials/solution-how-print-pager-drupal-views-block for more details).
> 0 votes

---
Tags: 7, views, paging
---


# Question
Title: Tagging of multiple content items at once
I'm very new to Drupal, so please be gentle.

My company is in the process of setting up Drupal as a learning portal, which will have various content types (videos, pdfs, blogs, basic pages) that we will tag for ease of searching and offer 'suggested learning materials'.

While we will try to get our taxonomy defined perfectly up front, we know we'll miss something.

I came across two related questions here, but neither are exactly what I am asking

I'll certainly use these questions and answers in the future, but for now my question is:

if we add a new term (rather than change one), is there a way to select multiple content items and add the new terms to the selection in a single action, rather than have to go to each content item individually and add the new tag?

# Answer
> 2 votes
You can create and customize a vbo view, which would allow you select multiple content items and add a taxonomy term to all the selected items at once.

Jason

# Answer
> 1 votes
You could use an Entity reference on the terms.

Then implement hook\_entity\_insert, drop the data from the entity reference so it doesn't get saved, and instead used it to load up the referenced entities, tag them, and save them back.

---
Tags: taxonomy-terms
---