title: WYSIWYG with CK editor Profiles

text:
# Question
Title: WYSIWYG with CK editor Profiles
I am using WYSIWYG with CK editor library. The problem is its showing blank toolbar by default on WYSIWYG editor on node add/edit page. To make the buttons appear on the WYSIWYG toolbar I always have to goto admin/config/content/wysiwyg/profile/full\_html/edit

and have to select which buttons to appear on the WYSIWYG editor toolbar.

Is there a way we can select all check boxes at once

# Answer
> 1 votes
You can do that with Firebug or any other browser that has a console. You need to go to edit page of the WYSIWYG profile and on this page, open Firebug or your browser's web developer tool. And in the console enter this line and run:

```
jQuery('#edit-buttons input.form-checkbox').attr('checked', 'checked');

```

This will set all the checkboxes under 'Edit buttons' section and you can save your setings.

# Answer
> 0 votes
No, there is no way you can do that out of the box.

If you repeatedly need this functionality, you can write a small custom module that will add a checkbox on that page using `hook_form_alter()` and then through javascript enable all those checkboxes.

---
Tags: wysiwyg
---


title: Need a hand altering a theme

text:
# Question
Title: Need a hand altering a theme
I'm using a theme called Danland, and I want to change the Recent Posts block to show only post title and publication date. As it stands it shows 3 columns, one of which is post title, and the last two of which are blank when you are not logged in and say "edit" and "delete" when you are logged in. I also want to kill the table border.

I can't find the right css file to edit. Using firebug to ID the td and other tags to kill to get rid of the extra columns, but I can't find them in the theme files. Firebug IDs them as being in style.css, but there's nothing there. Where does this code live?

# Answer
> 0 votes
Please go to views admin interface and check the views name as Recent post(display type block), views gives you flexibility for adding any number of fields your content type has, also it will allow you to have custom classes to fields that you will be needing to theme.About classes and ids already there, they are coming from views theming you do not have to touch there all you have to do is add fields you want, while adding it will allow you to style it by adding wrapper divs or other html element.Once you finish with editing the view,check the block in firebug you will see your calsses and ids working there, then add css for it in your Danland theme .css file.

Key Points which may help you:

* how to add/remove fields from view
* how to add custom classes to the fields in views
* Once done style it using your theme css file.

---
Tags: blocks
---


# Question
Title: Form is not being rendered in template file
I have tried drupal\_render,drupal\_get\_form etc for rendering the form,but the form is not being rendered. Is there any error in code or else what else should i add to the code so that it works.

```
function questionnaire_template_form($form, &$form_state, $question) {
 print_r("in template function");

 $form_build = unserialize($question->criteria_data);

 foreach ($form_build as $key => $value) {

  $options = ($form_build[$key]['1']);
   $list = explode("\n", $options);

   $list = array_map('trim', $list);

   $list = array_filter($list, 'strlen');

   foreach ($list as $key => $value) {

    $new = explode('|',$value);
    $new_key = reset($new);
    $new_value = end($new);
    $new_list = array($new_key => $new_value);
    dsm($new_list);
   }
dsm('next');

   $fb = explode("_",$key);
   $type =reset($fb);

  if($type == 'radio') {

    if($form_build[$key]['0']) {
      $form['radio_form'] = array(
        '#type' => 'radios',
        '#options' => $list,
      );
    }
  }
   elseif($type == 'checkbox') {
    if($form_build[$key]['0']) {
     $form['checkbox_form'] = array(
       '#type' => 'checkboxes',
       '#options' => $list,
      );
    }
   }
   elseif($type == 'selectlist') {
    if($form_build[$key]['0']) {
      $form['selectlist_form'] = array(
        '#type' => 'select',
        '#options' => $list,
        );
   }
  }

}
return $form;
}

```

Above code is my form.

```
<div>
<?php
//print_r($variables['entity']->qid);?></br><?php
print_r($variables['entity']->title);?></br><?php
print_r($variables['entity']->text);?></br><?php
?></br><?php
?></br><?php
if($variables['entity']->criteria) {
  ?><br/><?php
  $form_template = drupal_get_form('questionnaire_template_form' , $variables['entity']);
  print(drupal_render($form_template));

}
?></br><?php

print_r(l( t("Yes"), 'questionnaire/' . $variables['entity']->yes_quid));?></br><?php
print_r(l( t("No"), 'questionnaire/' . $variables['entity']->no_quid));?></br><?php

?>
</div>

```

And this is the template where I am rendering the form. I am getting the form if I dsm the form

# Answer
> 0 votes
Drupal render will return the html

```
drupal_render(drupal_get_form('form_id'));

```

you have to print the returned html as well.

```
print drupal_render(drupal_get_form('form_id'));

```

in your case

```
$form_template = drupal_get_form('questionnaire_template_form' , $variables['entity']);
drupal_render($form_template);

```

change it to

```
$form_template = drupal_get_form('questionnaire_template_form' , $variables['entity']);
print drupal_render($form_template);

```

---
Tags: forms, theming
---


# Question
Title: How to find whether the term is first or last in a vocabulary?
I am using a vocabulary to get the list of terms in it. The tids for the terms are 1, 2, 3, 4, 5. I have no hierarchy in my taxonomy. Now I would like to find whether 1 is the first term in the vocabulary, similarly to find whether 5 is the last term in the vocabulary.

Is there any API way of doing this?

# Answer
> 5 votes
First, you need to obtain one level of your taxonomy terms. Use either `taxonomy_get_tree($vid, 0, 1);` for top level ones, or `taxonomy_get_children($tid)` for children of a known element.

It should be sorted the way you want it, as both functions contain this in their code:

```
$query->orderBy('t.weight');
$query->orderBy('t.name');

```

Now you can use standard PHP functions `reset(array &$array)` and `end(array &$array)` to get first and last object from that array for comparison. Note that this will move internal pointer around, so don't use them lightly on arrays you also use elsewhere already.

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


title: PHP Select options in CCK field

text:
# Question
Title: PHP Select options in CCK field
I want to create a CCK field with options determined by PHP. On the content admin page, in the `Allowed Values PHP code` the example it gave was

`return array(
 value_1 => label_1,
 value_2 => label_2
 ...
);`

However, I want one of the options to be the user's name, so I used something like:

```
global $user;
$name=$user=>$name;
return array( 'main_guy' => 'No', $name => 'yes' );

```

For some reason, it won't accept quotes or dollar signs. If I delete the first two lines, and remove the quotes and dollar signs (`return array(main_guy => No, name => yes);`), it works ok.

Any ideas? That would be the same as the standard, non-dynamic list options.

# Answer
Your PHP is incorrect :(

The second line should read `$name = $user->name;`.
> 4 votes

---
Tags: entities
---


title: Unflagging a node with Rules Scheduler

text:
# Question
Title: Unflagging a node with Rules Scheduler
I have got an issue unflagging a node with Rules scheduler when triggering it with cron. The node gets unflagged just fine if we execute the component manually, however, if I schedule it to unflag the node like 2 minutes after triggering the Rule, it doesn't unflag the node. I ran cron multiple times, refreshed the page, but nothing.

I have done some preliminary testing and found out that flag\_rules\_action\_info() is just not being called at all when executing this through cron. I have checked permissions and every thing looks good there. Would appreciate it if you guys could give me some input as to what might be the problem when triggering it with cron. I have included the rules debug info below and an export of the rule and the component. Thanks.

Debug Info:

```
0 ms Scheduled evaluation of action set my component, task Unbookmark 10..
90.748 ms Evaluating the action component_rules_my_component. [edit]
0 ms Evaluating action set my component.
0.473 ms Evaluating the action component_rules_my_component. [edit]
0.528 ms Not evaluating action set my component to prevent recursion. [edit]
1.07 ms Evaluating the action flag_unflagnode. [edit]
5.439 ms Evaluating the action add_badge_by_name. [edit]
7.16 ms Finished evaluation of action set my component.
98.707 ms Evaluating the action flag_unflagnode. [edit]
98.982 ms Evaluating the action add_badge_by_name. [edit]
116.401 ms Finished evaluation of action set my component, task Unbookmark 10..

```

Component Export:

```
{ "rules_my_component" : {
"LABEL" : "my component",
"PLUGIN" : "action set",
"REQUIRES" : [ "rules", "flag", "user_badges" ],
"ACCESS_EXPOSED" : "1",
"USES VARIABLES" : { "node" : { "label" : "node", "type" : "node" } },
"ACTION SET" : [
{ "component_rules_my_component" : [ ] },
{ "flag_unflagnode" : {
"flag" : "bookmarks",
"node" : "10",
"flagging_user" : [ "site:current-user" ],
"permission_check" : 1
}
},
{ "add_badge_by_name" : { "badge" : "4", "user" : [ "node:author" ] } }
]
}
}

```

Rules Export:

```
{ "rules_test_scheduler" : {
"LABEL" : "test scheduler",
"PLUGIN" : "reaction rule",
"REQUIRES" : [ "rules", "rules_scheduler", "flag" ],
"ON" : [ "flag_flagged_bookmarks" ],
"IF" : [
{ "entity_is_of_type" : { "entity" : [ "flagged-node" ], "type" : "node" } },
{ "node_is_of_type" : {
"node" : [ "flagged-node" ],
"type" : { "value" : { "blog" : "blog" } }
}
}
],
"DO" : [
{ "drupal_message" : { "message" : "this works" } },
{ "schedule" : {
"component" : "rules_my_component",
"date" : "+2 minutes",
"identifier" : "Unbookmark [flagged-node:nid].",
"param_node" : [ "flagged-node" ]
}
}
]
}
}

```

# Answer
I have figured this out myself. Please refer to Comment #5 in Issue 2094541 for the answer, located at the following link: https://drupal.org/node/2094541#comment-7955705

Here is what it says:

> Finally, figured this out! The problem is, we're not supplying the required parameters to the Rules component. If you have given it only 'node' as the parameter, then, when you add the action to 'Unflag a Node', you must give the 'User on whose behalf to flag' a data selector such as 'node:author'. You can't do something like 'site:current-user' because that parameter is not available to the component when run through Cron.
>
> Once you give it the required parameters, it should unflag the node through Cron.
> 1 votes

---
Tags: cron, flags, rules
---


# Question
Title: Improving UX with views exposed filters: automatically selecting certain options based on a profile value
**Background**

On my site, users input their birthday, from which I use a computed field to calculate their age. Then, based on that age, I use rules to add a taxonomy term to their profile to classify them into one of the following age groups:

* 20s
* 30s
* 40s
* 50s
* 60s
* 70+

I have a view that allows members to search other members' profiles, and on this view I have an exposed filter for the taxonomy vocabulary **age group**. The exposed filter widget is converted from a dropdown box to a list of checkboxes using the Better Exposed Filters module.

**What I want to do**

This works well, but I want to further improve the UX by automatically checking boxes based on the user's age when he or she visits the page. Ideally, I want to automatically check the box for the user's own age group (e.g., a user in his/her 20s will automatically have the 20s box checked, while a user in his/her 40s will have the 40s box checked).

**What I tried**

I have no way how to implement this smartly. One possibility that entered my mind is creating a panel with variants for each age group and then cloning a view once per age group and then using views rewriting functionality to rewrite the query strings for all of the views to check the appropriate boxes... but this would lead to a huge amount of duplication and be very difficult to maintain.

# Answer
> 1 votes
As a huge fan of direct approach and writing own helper modules, I would make it happen mostly with jQuery.

1. Outputting user's age or age category in a hidden `<div>` is easy. You can append it to view's form with `hook_form_alter`, or simply output it as a block that will never really be seen.
2. Attach your JS library to views form (or again - simply load it and make it see if form is on page)
3. In behavior, read user's age from `<div>` created in 1. and based on that check checkboxes. Invoke `click()` on them for full emulation of user interaction (i.e. to reload what would get reloaded if it was user who selected it).

---
Tags: views
---


# Question
Title: How do I alter a message in the message queue independent of site language?
I want to programatically alter a message in the message queue. The message I want to alter is set in the message queue by `function comment_form_submit()` in `comment.module`, i.e.:

```
if ($comment->status == COMMENT_NOT_PUBLISHED) {
  if (!user_access('administer comments')) {
    drupal_set_message(t('Your comment has been queued for review by site administrators and will be published after approval.'));
  }
}

```

Instead of this, I want the call to `drupal_set_message()` to be this:

```
drupal_set_message(t('Your comment will be published when you validate your e-mail address.'));

```

How do I do this?

**Postscript:** Based on the answer below by Topsitemakers, I got this working for any language by using `array_search()` inside a custom `MYMODULE_comment_submit` to search the message array, and then compare the *translated* strings to identify the key of the string to alter.

This is the working code I ended up with:

```
$mm = drupal_get_messages('status', TRUE);
$key = array_search(t('Your comment has been queued for review by site administrators and will be published after approval.'), $mm['status']);
if (FALSE !== $key) {
  $mm['status'][$key] = t('Your comment will be published when you validate your e-mail address.');
}
foreach ($mm['status'] as $msg) {
  drupal_set_message($msg, 'status');
}

```

# Answer
> 4 votes
You can compare messages using the `t()` function, as it will localize both messages and compare them.
Just use the original text in English you want to find and wrap it in `t()` function. E.g.:

```
if ($message == t('This is a sample message')) {
  // Alter the message/perform additional processing.
}

```

---
Tags: status-messages
---


# Question
Title: add value to cck select list using hook_form_alter
I have a cck list(text) field. Widget: select I already have data in the database and I want to add a few more options to the select list. I've tried using hook\_form\_alter but I can't seem to change the options. Here is my code:

```
function color_cats_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == "cats_node_form") {
        $form['#after_build'][] = 'color_cats_after_build';
    }
}

function color_cats_after_build($form, &$form_state) {
    dsm($form);
    $form['field_color_cat']['und']['#options']['brown'] ='Brown';
    $form['field_color_cat']['und']['#options']['white'] ='White';
    $form['field_color_cat']['und']['#options']['gold'] ='Gold';
    $form['field_color_cat']['und']['#options']['grey'] ='Grey';
    $form['field_color_cat']['und']['#options']['tabby'] ='Tabby';
    $form['field_color_cat']['und']['#options']['ginger'] ='Ginger';
    $form['field_color_cat']['und']['#options']['multi-colored'] ='Multi Colored';
    return $form;
}

```

`dsm($form)` is showing so the function `color_cats_after_build` is being called. The issue is `$form['field_color_cat']['und']['#options']['brown'] ='Brown';` is not affecting the select list. `dsm($form)` shows

```
field_color_cat (Array, 17 elements)
    #type (String, 9 characters ) container
    #attributes (Array, 1 element)
    #weight (String, 2 characters ) 16
    #tree (Boolean) TRUE
    #language (String, 3 characters ) und
    und (Array, 38 elements)
        #entity (Object) stdClass
        #entity_type (String, 4 characters ) node
        #bundle (String, 4 characters ) cats
        #field_name (String, 15 characters ) field_color_cat
        #language (String, 3 characters ) und
        #field_parents (Array, 0 elements)
        #columns (Array, 1 element)
        #title (String, 5 characters ) Color
        #description (String, 56 characters ) This is the old color selection and SHOULD NOT ...
        #required (Boolean) FALSE
        #delta (Integer) 0
        #type (String, 6 characters ) select
        #default_value (Array, 0 elements)
        #multiple (Boolean) FALSE
        #options (Array, 6 elements)
            _none (String, 8 characters ) - None -
            Black (String, 5 characters ) Black
            Brown (String, 5 characters ) Brown
            Gold (String, 4 characters ) Gold
            White (String, 5 characters ) White
            Multi Colored (String, 13 characters ) Multi Colored
        #value_key (String, 5 characters ) value
        #element_validate (Array, 1 element)
        #properties (Array, 4 elements)
        #after_build (Array, 1 element)
        #input (Boolean) TRUE
        #process (Array, 2 elements)
        #theme (String, 6 characters ) select
        #theme_wrappers (Array, 1 element)
        #pre_render (Array, 1 element)
        #defaults_loaded (Boolean) TRUE
        #tree (Boolean) TRUE
        #parents (Array, 2 elements)
        #array_parents (Array, 2 elements)
        #weight (Integer) 0
        #processed (Boolean) TRUE
        #attributes (Array, 0 elements)
        #title_display (String, 6 characters ) before
        #id (String, 24 characters ) edit-field-color-cat-und
        #name (String, 20 characters ) field_color_cat[und]
        #value (Array, 0 elements)
        #ajax_processed (Boolean) FALSE
        #sorted (Boolean) TRUE
        #after_build_done (Boolean) TRUE
    #access (Boolean) TRUE
    #theme_wrappers (Array, 1 element)
    #process (Array, 1 element)
    #defaults_loaded (Boolean) TRUE
    #parents (Array, 1 element)
    #array_parents (Array, 1 element)
    #processed (Boolean) TRUE
    #required (Boolean) FALSE
    #title_display (String, 6 characters ) before
    #id (String, 20 characters ) edit-field-color-cat
    #sorted (Boolean) TRUE

```

How do I add values to my select list?

Thanks

This is my code just using the hook\_form\_alter:

```
function color_cats_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == "cats_node_form") {
$form['field_color_cat']['und']['#options'] = array(
     'All' => t('- Any -'),
        'Black' => t('Black'),
        'Brown' => t('Brown'),
        'White' => t('White'),
        'Gold' => t('Gold'),
        'Grey' => t('Grey'),
        'Tabby' => t('Tabby'),
        'Ginger' => t('Ginger'),
        'Multi Colored' => t('Multi Colored')
       ); }}

```

The select list is showing all the values and it works if I select an old value, but if I select a new value that I added eg ginger then I can the error message: color:illegal value.

# Answer
> 1 votes
There are couple of ways to achieve this.

If you always want the options to come from the code then don't bother adding the allowed values field. Once you add this it would check to make sure that the values you enter is with in this allowed values field. so if you dont give the allowed values field and then use the form alter hook to populate the field as given below it should work fine without giving the "illegal value" error.

```
function color_cats_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == "cats_node_form") {
        $form['field_color_cat']['und']['#options'] = array(
            'All' => t('- Any -'),
               'Black' => t('Black'),
               'Brown' => t('Brown'),
               'White' => t('White'),
              'Gold' => t('Gold'),
               'Grey' => t('Grey'),
              'Tabby' => t('Tabby'),
             'Ginger' => t('Ginger'),
             'Multi Colored' => t('Multi Colored')
               );
        }
}

```

If you are particular about adding the allowed values field then the way is a bit more complicated. Here again I have found two way to go about it.

One is to use the php filter for the allowed values. For this you might have to add the CCK module just the core fields module might not cut it as the php filter option is not yet there in the core.

You can follow the below steps

1. Enable Core module PHP Filter
2. Set/Check user permissions: admin/people/permissions#module-php
3. Set/Check Text Formats: admin/config/content/formats
4. Enable CCK Module. Without CCK Module enabled you wont be able to enter (and thus execute) PHP-code in the Allowed-Values-List window as mentioned above.

Now you can add the options array with in the window and return the options array.

Something like given below

```
<?php
  $options = get_my_options();
  //(...);
  return $options;
?>

```

Above method was suggested by clivesj on drupal forum

The second method is to directly edit the database. The allowed values are stored in the database table field\_config. the column is data. This is a serialized array of settings. so you could read this and then add the additional values and then update the database as given below.

```
$sql = "SELECT id, data FROM {field_config} WHERE id=29";
$result = db_query($sql);
    // retrieve recordset
    while($data = $result->fetchObject()){
    $rev = unserialize($data->data);  // this becomes the string containing the BLOB data
}

$rev['settings']['allowed_values']['Multi Colored']=t('Multi Colored'); // add all the additional options here.

$rev=serialize($rev);
$db_in = db_update('field_config')
     -> fields(array(
                'data' => $rev
         ))
     ->condition('id', 29, '=')
     ->execute();
     cache_clear_all();

```

You would need to clear the cache to show the options. hence you would need to call the `cache_clear_all();` function to clear the cache. you could also target the exact cache you want to clear that way the entire cache is not cleared.

This is a database intensive method hence you might want to read the allowed values and make sure that the values you are about to enter is not already there in the options list. if it is already there then you can skip adding that option and hence avoid reading and writing into the db.

# Answer
> 0 votes
Try this, adding it to the hook\_form\_alter rather than your #after\_build function, since (and I took this directly from the Form API) "An array of function names which will be called after the form or element is built." and it's hard to modify a form after it's been built.

```
function color_cats_form_alter(&$form, &$form_state, $form_id)
{
    if ($form_id == "cats_node_form")
    {
        $form['field_color_cat']['und']['#options']['brown'] ='Brown';
        $form['field_color_cat']['und']['#options']['white'] ='White';
        $form['field_color_cat']['und']['#options']['gold'] ='Gold';
        $form['field_color_cat']['und']['#options']['grey'] ='Grey';
        $form['field_color_cat']['und']['#options']['tabby'] ='Tabby';
        $form['field_color_cat']['und']['#options']['ginger'] ='Ginger';
        $form['field_color_cat']['und']['#options']['multi-colored'] ='Multi Colored';
    }
}

```

---
Tags: entities
---


# Question
Title: Changing number of values on a field in installation profile
I am creating an installation profile with multiple fields. For a 'file' field I want to change the number of values. I have two questions about this.

Is this an field setting or an instance setting? and what is the right way of changing this setting I tried these:

```
'number_values' => '2',
'max_value' => '2',
'max_values' => '2',
'values' => '2',
'value' => '2',

```

I can't find any of this on the internet. Any help and tips would be appreciated.

# Answer
> 1 votes
It's a field setting (`cardinality`), so assuming you're using `field_create_field()` to create it...

```
$field = array(
  'entity_types' => array('node'),
  'cardinality' => 2,
  'translatable' => FALSE,
  'locked' => FALSE,
  // etc...
);
field_create_field($field);

```

For unlimited values you can use the `FIELD_CARDINALITY_UNLIMITED` constant.

---
Tags: entities, installation
---


title: Modifying download behaviour of drush

text:
# Question
Title: Modifying download behaviour of drush
By default the command:

```
drush dl <drupal-version>

```

will download the specified version of drupal from the internet. Is it possible to reconfigure drush so that dl looks to a local repo for the require drupal version?

# Answer
You can use the `--source` flag to provide your own xml release history file containing paths to your own gzips. (`drush dl drupal` defaults to http://updates.drupal.org/release-history/drupal/7.x.)

Sadly I don't think you can specify a local repo, or even a remote repo as the source of a project for dl. Drush expects a gzip file to download and unpack. You could however write your own drush command that takes a local repo path, gzips it, and passes the gzip to dl.
> 1 votes

---
Tags: drush
---


# Question
Title: how to check whether an error occurs due to a specific field in drupal?
Inside a validate function how can I disallow errors for a specific field and allow errors for a specific field.
Like if I get errors for a field\_abc I would like to clear that specific error and allow the form to submit.
But if I get error for a field\_def I would like to restrict the submission.

# Answer
This is what you are looking for:

https://api.drupal.org/comment/28464#comment-28464

**Edit**: Code excerpt from link:

```
/**
 * Custom Form Validation.
 * Removes all form validation errors caused by a 'foo][bar' form element.
 */
function my_module_form_validate($form, &$form_state) {
  $errors = form_get_errors();
  if ($errors) {
    // Clear errors.
    form_clear_error();
    // Clear error messages.
    $error_messages = drupal_get_messages('error');
    // Initialize an array where removed error messages are stored.
    $removed_messages = array();

// Remove all errors originated by the 'foo][bar' element.
    foreach ($errors as $name => $error_message) {
      if ($name == 'foo][bar') {
        $removed_messages[] = $error_message;
        unset($errors[$name]);
      }
    }

// Reinstate remaining errors.
    foreach ($errors as $name => $error) {
      form_set_error($name, $error);
      // form_set_error() calls drupal_set_message(), so we have to filter out
      // these from the error messages as well.
      $removed_messages[] = $error;
    }

// Reinstate remaining error messages (which, at this point, are messages that
    // were originated outside of the validation process).
    foreach (array_diff($error_messages['error'], $removed_messages) as $message) {
      drupal_set_message($message, 'error');
    }
  }
}

```
> 3 votes

---
Tags: 7, forms
---


# Question
Title: How can I have a node with the URL /themes
I've created a node and have given it the URL /themes. In full: http://site-name.com/themes.

Permissions on the Drupal system folder 'themes' mean that the URL /themes gives: 403 forbidden.

Is there anyway to have a node with /themes? I'd prefer if possible to keep my current file structure as I think it would be difficult to change with my current host (Pantheon).

# Answer
In your .htaccess file, the URL re-write has the a code to point the path to the respective folder, if present.. you can change that!
> -3 votes

---
Tags: uri
---


title: Dynamic field based on nid

text:
# Question
Title: Dynamic field based on nid
I'm building a website for ads. Every ad will have an option to become a VIP ad and will be displayed in a blocks with better position. The users will be able to make their ad into VIP ad by sending an SMS with prefix and their ad nid.

The idea is when a user clicks on the link "Make this ad VIP" will be displaying a field with details how to make the regular ad into VIP content. Let's say the ad node has nid 100, so when the user clicks on "Make this ad VIP" a info will be displayed like this: Send a text message "Prefix100" to the number 2xxx..where 100 will be the node id. On other ad if the node ID is 200, after clicking on "Make this ad VIP" the display text should be: Send a text message "Prefix200" to the number 2xxx. The module for SMS service is already created.

The field with details will be hidden and "Make this ad VIP" will be a toggle, so I'll use jQuery for that, but how can I set the node id on every node?

# Answer
OK, I've just figured out how to achieve this. I'm using Display suite and I've created a custom field like this: Send a text message SPORT\[node:nid\] to number 2xxx .... The key was the token \[node:nid\]. It's working great.
> 0 votes

---
Tags: nodes
---


# Question
Title: Add a form between shipping method selection and order review
I'm coding a custom module to make shipping by a delivery enterprise which is not having a module compatible with Drupal commerce.

So, I give the customers a choice between 2 shipping methods:

* colissimo (a French official delivery method) using an existing module
* exapaq using the custom module I am trying to create

This is working, but exapaq doesn't deliver to customer's home; it delivers to stores where customers can have their order.

So, after customers select the shipping method, I would like to test which is selected and, if this is exapaq, add a new form to allow customers select the store to take the order.

The problem is that I don't have any idea on where can I do this test and how I can insert a new form before to go on order review page.

# Answer
> 0 votes
The payment panes makes this kind of interaction possible through a "details form" that open when you select the payment method that has this configured, and this is great because everything happens on the same page via ajax. But i don't know if Commerce Shipping has this too. If not, i think that the best way for you to make this is to create a Checkout Page specific for your Shipping Method and create a Checkout Pane with your form to be in this page.

You can take a look at how https://drupal.org/project/commerce\_correios handle this situation, because it's a Shipping Method too, so the API should have a lot in common with what you need.

---
Tags: commerce
---


# Question
Title: Views block: Displaying a content block on profile page (/user) with user's chosen tags as contextual filter
I have a block on the user's profile page that filters content based on the supplied tag as an argument/contextual filter. Users on my site can add tags to their profile (with an autofill field pulling from the free-tag taxonomy) -- these tags are topics that they want to "follow." I would like this block to display content that is tagged with the tags they've personally chosen. thanks in advance!

# Answer
I have found a solution to this. Using a user view instead of a content view was the way to go for me. Then adding appropriate relationships on the teaxonomy term.

I used the these directions:

* Create a user view.
* Add a contextual filter on user: uid. If no filter value is present, build a default value using the currently logged in user. (This will give you exactly one user object in your view -- the logged in user.)
* Add a relationship, using the relevant taxonomy reference field on the user accounts. This will bring you information about the "interest" term for the logged in user.
* Add another relationship, called "term: nodes marked with term" (or something like that). This will bring you information about all nodes marked with the interest term for the logged in user.

From this article: https://drupal.org/node/1111722

Hope it helps!
> 1 votes

# Answer
I have not done this before, but I would try doing the following first:

1. Define a View. Make sure the type of View is "user" and not the default "node".
2. Define fields. If you are using Drupal seven, read the article on working with content types and fields:
> Fields on user accounts are defined on a site-wide basis on the Manage fields tab of the Account settings page. When you define a field for user accounts, each user account will have that field added to it. For example, you could add a long text field to allow users to include a biography.
3. Once you've defined those fields, add them to your View and create a block display within your View. Save your View.
4. Add your View block to any of the regions appearing on your /user page.
> 0 votes

# Answer
You should use hook\_user\_load

You load the user variables with the array of the tags.

Then you need view\_embed\_view to print the view in the block.

```
print views_embed_view('my_contents', $display_id = 'page', HERE THE CONTEXTUAL FILTERS )

```
> 0 votes

---
Tags: 7, views, taxonomy-terms, users
---


title: “Illegal Choice has been detected”

text:
# Question
Title: “Illegal Choice has been detected”
I want to prevent validation check on the field\_abc ?
How can I prevent validation for a field\_abc

```
  function test_mail_menu() {
         $items['test-mail-1'] = array(
            'page callback' => 'drupal_get_form',
            'page arguments' => array('test_mail1_form'),
            'type' => MENU_CALLBACK,
            'access arguments' => array('access content'),
          );

    return $items;
    }
    function test_mail1_form ($form,$form_state) {
      $form = array();
      $form['field_abc'] = array(
        '#type' => 'textfield',
        '#title' => t('ABC'),
        '#validated' => TRUE,
     );

      $form['submit-button'] = array(
        '#type' => 'button',
        '#title' => t('sub'),
      );

      $form['#submit'][] = 'test_mail1_submit';
      $form['#validate'][] = 'test_mail1_validate';
      return $form;
    }

    function test_mail1_submit($form,&$form_submit) {

    }

    function test_mail1_validate($form, &$form_state) {

      if (!(is_numeric($form_state['input']['field_abc']))) {

        form_set_error('field_abc','ERROR');

      }
    }

```

# Answer
> 0 votes
If you don't want to validate that field, then remove the following function

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

  if (!(is_numeric($form_state['input']['field_abc']))) {

    form_set_error('field_abc','ERROR');

  }
}

```

And remove the following line from `test_mail1_form`

```
$form['#validate'][] = 'test_mail1_validate';

```

# Answer
> -1 votes
Are you asking for validation. If so please use this code, else explain your question clearly

```
function test_mail1_form($form, &$form_state) {
  $form = array();
      $form['field_abc'] = array(
        '#type' => 'textfield',
        '#title' => t('ABC'),
     );

      $form['submit-button'] = array(
        '#type' => 'submit',
        '#value' => t('sub'),
      );

      $form['#submit'][] = 'test_mail1_submit';
  return $form;
}

function test_mail1_submit($form, &$form_state) {
print_r($form);
exit;
}

```

---
Tags: 7, forms
---


# Question
Title: Content Type with Tabular Data to be Input
I'm building a content type that is going to require tabular data to be input. Here's a mockup of what the table should look like: Rows 1 and 2 are fixed headers, 3-6 are data.

I am at a total loss as to how I should build this. I've experiemented with a few modules (like TableField... which is not really what I'm looking for).

Am I approaching this the wrong way? Is there a module that I'm not aware of that can do this?

# Answer
> 1 votes
did you try to use field\_collection? (separate the E.Coli in 2 fields EColiB and EColiE ... and maybe some CSS to style it) - perhaps this is not a solution, I am posting it here since I am couple of points short and cannot leave comments for additional info under the original post

---
Tags: forms, nodes, theming
---


# Question
Title: Block content returns no results for anonymus user only
I've setup View Block that renders a custom content type. The issue is that block content shows up for logged users only. I ensured that anonymus user has "view published content" permission. No permission restrictions are set for that specific block.

any ideas what is wrong here? Could I use a Devel to inspect that somehow? thx!

# Answer
> 2 votes
There are multiple layers of permissions which might responsible for this,trying to cover some of them if that helps you.

* Check right in the views configuration page and check "access" should be set to "view publish content".
* Ensure you are not having contrib module like block\_access or custom code which is putting a check the block view on user role basis.
* Ensure if you are using contentaccess module or nodeaccess module and they are not letting the block visible to anonymous user.

---
Tags: views, users
---


# Question
Title: How to inject text into the beginning of a textfield?
I have a multilingual site with 3 languages where only 1 field (Description) is really multilingual, everything else is a translated interface and strings.

For the Description field, it has been my aim to replicate the functionality of Wordpress's "qTranslate" plugin so that the UI looks something like this:

I have almost managed to achieve this using Fieldgroup module, 3 description fields, and Language Sections module (because I found no better way to assign each field to its language).

So far so good. But at the top of each field I have to put in default texts (=fr =en= =el=) so that Language Sections module knows which field is which language and displays the correct text depending on which is the current language. If the end-users delete those =en= and =fr= tags, then the whole thing falls apart.

So I need a module that will inject those =fr= and =en= tags at the beginning of each textfield's entered text, in a way that's completely transparent to the user. Is there such a module? Can Rules achieve a functionality like this?

Alternatively, if there is no such module, how would one go about creating one? Which function or which hook to use?

---

**UPDATE** I made this module called language\_markers based on the answer given by *Beebee* ,but it didn't work. Can you pleasetellmewhat I'mdoing wrong? :

```
<?php

function language_markers_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'property_for_sale_node_form' || $form_id == 'property_to_rent_node_form') {
    $form['#submit'][] = 'language_markers_submit_handler_function';
  }
}

function language_markers_submit_handler_function($form, &$form_state) {
  foreach($form_state['values'] as $field_name => $value) {
    switch($field_name) {
      case 'field_description_fr':
        $value = '=fr= '.$value;
        break;
      case 'field_description_nl':
        $value = '=nl= '.$value;
        break;
      case 'field_description_en':
        $value = '=en= '.$value;
        break;
    }
  }
}

```

---

**UPDATE 2:** I have managed to get this to work with Rules module:

***Event:*** After updating existing content of type Property for Sale

***Condition:*** none

***Action:*** Set a data value Parameter: Data: \[node:field-description-en..., Value: =en= \[node:field-description-en:value\]

It works,but when the end-user comes back to edit the node, he sees "=en=" in front of his text. That's a BAD User-Experience. This is a work-around, not a solution. I still need a solution.

# Answer
> 2 votes
Do your fields have a different field name per language? For example, maybe they follow some sort of convention like `field_description_en`, `field_description_cn`, `field_description_de`?

If so, then perhaps you can use `hook_form_alter` and add your own submit handler into the form like so :

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'mytype_node_form') {
    $form['#submit'][] = 'my_custom_submit_handler_function';
  }
}

```

Then create a function `my_custom_submit_handler_function($form, &$form_state)`. Inside the function you'll need to loop through `$form_state['values']` like so and just append your language strings before the values:

```
function my_custom_submit_handler_function($form, &$form_state) {
  foreach($form_state['values'] as $field_name => &$value) { // <-- forgot the & here... oops
    switch($field_name) {
      case 'description_en':
        $value = '=en='.$value;
        break;
      case 'description_cn':
        $value = '=cn='.$value;
        break;
      case 'description_de':
        $value = '=de='.$value;
        break;
    }
  }
}

```

There's probably better ways to do it though.

---

**Update**

@drupalina I forgot to put the ampersand on the submit handler function which would have updated $form\_state. Here's your code with a working version:

```
<?php

function language_markers_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'property_for_sale_node_form' || $form_id == 'property_to_rent_node_form') {
    // You can remove the texts here too. Below is just an example.
    // Path inside $form may not be correct, so
    // do a var_dump($form) or dpm($form, 'form'); to check the array
    // To use dpm() you need to install "devel" module and enable it.
    #dpm($form, 'form');

    // Trim =fr= string from left side of the #value
    $form['field_description_fr']['#value'] = ltrim($form['field_description_fr']['#value'], '=fr=');
    // You might need to set the #default_value too
    $form['field_description_fr']['#default_value'] = ltrim($form['field_description_fr']['#default_value'], '=fr=');

    // Do this for each language...
    // $form['field_description_de']['#value'] = .......

    $form['#submit'][] = 'language_markers_submit_handler_function';
  }
}

function language_markers_submit_handler_function($form, &$form_state) {
  // Note the ampersand before $value below, which allows the
  // modifications on $value to persist into $form_state
  foreach($form_state['values'] as $field_name => &$value) {
    switch($field_name) {
      case 'field_description_fr':
        $value = '=fr= '.$value;
        break;
      case 'field_description_nl':
        $value = '=nl= '.$value;
        break;
      case 'field_description_en':
        $value = '=en= '.$value;
        break;
    }
  }
}

```

In my opinion, this would quickly turn very unmaintainable as you get more and more fields & languages combinations. So if you are planning to have more than these description fields, I would suggest to use more general ways to find these fields and automatically remove/add the language strings. For example, using `hook_field_attach_presave`

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


# Question
Title: Views: Use like operator in exposed search filter (Search: Search Terms)
In a view, I am using an exposed filter of keyword search (Search: Search Terms). The default behavior of the filter is to select exact matches. I need to have similar words also selected. For instance when the visitor searches for "paint", she should see "painting" or "painter" too.

Similar to the "LIKE" operator in mysql.

# Answer
> 4 votes
When you set a new filter in views on a field (for example node title), you can set the Operator to `contains` which is the equivalent of SQL `LIKE`. You can also expose the filter and the operator to the visitor. If you want to see the SQL query in the preview, check the option *Show the SQL query* in view setting.

Instead of *Search: Search Terms*, use *Global: Combine fields filter*; it will allow you to search multiple fields using the operator you want.

---
Tags: views
---


title: form and answer in the same URL

text:
# Question
Title: form and answer in the same URL
I'm working my way around Drupal API with limited success.

I want to have a URL with a form in it, so that when I "GET" that URL I get the form (have that), when I input a wrong "code" into that form and POST that same URL I get the same form with an error message (have that too), but when I POST that **same URL** with the right "code" I get a different code, no longer displaying the previous form.

No redirects, all the requests (posts and gets) should be targeted to domain.com/entry

This is a code I have (simplified):

```
function entry_menu() {
    $items['entry'] = array(
        'page callback' => 'entry_handler',
        'access arguments' => array('access entry'),
        type => MENU_CALLBACK,
    );

    return $items;
}

function entry_handler() {
    return drupal_get_form('entry_daily_code');
}

function entry_daily_code($form, &$form_state) {
    $form['code'] = array(
        '#type' => 'textfield',
        '#title' => 'Code for Today',
    );

    form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Access',
    );

    return $form;
}

function entry_daily_code_submit($form, &$form_state) {
    if (isset($form_state['values']['code']) && $form_state['values'] == "1234") {
        drupal_set_message(t('Success'));
    }
    else {
        drupal_set_message(t('Fail'));
    }
}

```

I imagine that what I want to do should happen in "entry\_handler".

It needs to know the status returned by the form, and to either return the form, or a different content, but I'm failing at that.

Made a diagram to illustrate my point, in case it wasn't coming across:

Thanks for any pointers in the right direction.

# Answer
> 2 votes
When your visitor send the form, Drupal process the input, executing the validate and submit handlers (you have only provided your submit handler).

Once handlers are executed, Drupal needs to send a page to the user (the answer), so, if no redirection is made (in $form\_state\['redirect'\]), Drupal renders the content for the current URL, so Drupal renders your form again (because is a new HTTP petition, there's no memory of past petitions).

You must do something in the submit handler to let Drupal know your visitor can see the protected content.

For example, you can set a flag in the $\_SESSION data. Then, in the entry\_handler check for that value: if it's there the content is rendered, if not then the form is rendered.

Something like this (I've also divided your submit handler into validate and submit handlers):

```
function entry_daily_code_validate($form, &$form_state) {
    if (isset($form_state['values']['code']) && $form_state['values'] != "1234") {
   form_set_error('code', 'Invalid code!');
}

function entry_daily_code_submit($form, &$form_state) {
  $_SESSION['code_validated'] = TRUE;
}

function entry_handler() {
  if ($_SESSION['code_validated' == TRUE) {
    return 'Arbitrary content';
  }
  else {
    return drupal_get_form('entry_daily_code');
  }
}

```

If your visitors are registered users you can edit the user account or whatever merthod you like. Remember that session data can be lost.

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


# Question
Title: How do I retrieve node data for a referenced node in a template file?
I have two content types, Event and Gallery. Each Event has a node-reference field to a gallery. I am now trying to style the gallery node page from inside the template file. I need to have a way of creating a link which links back to its parent, the Event.

How can I find this information?

# Answer
> 2 votes
it seems you need to know value of node which is referring the current node. I am assuming machine name for the refernce field you have on event content type as "field\_event\_gallery"

In your custom module or template.php // function to get backrefernce value.

```
function mymodulename_get_back_refernce_value($current_nid) {
  $nids = array();
  $results = db_select('field_data_field_event_gallery','n')
            ->fields('n',array('entity_id'))
            ->condition('field_event_gallery_nid',$current_nid)
            ->execute()
            ->fetchAll();
  if(is_array($results) && count($results) > 0) {
    foreach($results as $result) {
      $nids[] = $result->entity_id
    }
  }
  return $nids;
}

```

Now in your theme template.php use template\_preprocess\_node(),something like below

```
function MYTHEME_preprocess_node(&$variables) {
  $node = $variables['node'];
  if ($node->type == 'gallery') {
    //get referring nids
    $referring_nids = mymodulename_get_back_refernce_value($variables['node']->nid);
   if(count($referring_nids) > 0) {
     foreach($referring_nids as $referring_nid) {
       $referring_node = node_load($referring_nid);
       $variables['parent_event_link'][$referring_nid] = l(t('View parent event: @event_title', array('@event_title' => $referring_node->title)), 'node/' . $referring_nid);
   }
  }
}

```

finally in your template loop through $variables\['parent\_event\_link'\] and print it.

**My codes are not tested, you have to debug to make them workign for you**

# Answer
> 0 votes
The best way to prepare this for template is through `hook_preprocess_node()` implementation.

This code should be in your theme's `template.php` file:

```
function MYTHEME_preprocess_node(&$variables) {
  $node = $variables['node'];
  if ($node->type == 'gallery') {
    // You can add new attributes to the $variables variable and they will be
    // available automatically in the node template file as direct variables.
    $variables['parent_event_link'] = l(t('View parent event: @event_title', array('@event_title' => $variables['field_gallery_event'][0]['node']->title)), 'node/' . $variables['field_gallery_event'][0]['nid']);
  }
}

```

And in your `node.tpl.php` or `node--gallery.tpl.php` file you can use:

```
<?php print $parent_event_link; ?>

```

---
Tags: nodes
---


# Question
Title: Can I make interaction between views relations and views arguments?
I'm running into the problem where I have to join a node and a registration. The nodes are of type 'event' and the registration is available for some, but not all of them.

So basically I have a list of event nodes, and I left join the registrations on them, giving me some extra information where available.

The problem is I want to list only my registrations. So a contextual filter has to be added somewhere. The problem; The default filter applies after the join, filtering also all nodes for which I have not yet registered. But I want to show those.

Therefor I am looking for a custom handler that allows me to add an 'extra' statement to the views join clause. I've looked for it, but started t doubt where such a thing is actually possible. Had anyone ever tried such a thing?

I suppose I need to make a custom hander, it's not a problem. But can handers 'communicate', or is there something like a hybrid handler of some sort?

**Wrong query**

```
SELECT ...
FROM
{node} node
LEFT JOIN {node_registration} node_registration_node ON node.nid = node_registration_node.nid
WHERE (( (node_registration_node.uid = '1' )

```

**Working query, but non contextual**

```
SELECT ...
FROM
{node} node
LEFT JOIN {node_registration} node_registration_node ON node.nid = node_registration_node.nid AND node_registration_node.uid = '1'

```

# Answer
> 0 votes
Thanks for the suggestions Andrew, I ended up creating a custom argument-handler. It adds one (or more) extra conditions to the join. `LEFT JOIN ... AND ...`.

```
function query($group_by = FALSE) {
  $this->ensure_my_table();

    $this->query->table_queue[$this->table_alias]['join']->extra = array(
      array('table' => $this->table_alias, 'field' => $this->real_field, 'value' => $this->argument),
    );
  }
}

```

---
Tags: views, nodes
---


title: Entity query to select current dates

text:
# Question
Title: Entity query to select current dates
The situation: I have a drupal 7 node which has a date field. This uses the date module and it has multiple values each with a start and end date.

The problem is that I want to query drupal for all nodes where the current date is between the start and end dates of a single delta.

The entity query I have at the moment doesn't check the same value for both start and end dates.

For example if the first date value started 1/1/2013 and ended 30/1/2013 and if there was a second value which started 1/12/2013 and ended 30/12/2013. Using the current date of today 11/10/2013 this node should NOT be fetched. However under the query below it is because there is a start date in the past and an end date in the future, even though they're not from the same field delta.

```
  $current_date = date("Y-m-d");

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', RD_PRIZE_DRAW_NODE_TYPE);
    ->fieldCondition('field_rd_prize_draw_dates', 'value', $current_date, '<=')
    ->fieldCondition('field_rd_prize_draw_dates', 'value2', $current_date, '>=');
    ->execute();

```

# Answer
Having actually read the fieldCondition documentation the fourth property turns out to be $delta\_group which allows specifying dependent conditions. So it turns out all I needed was the below:

```
$current_date = date("Y-m-d H:i:s");
$query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', RD_PRIZE_DRAW_NODE_TYPE);
    ->fieldCondition('field_rd_prize_draw_dates', 'value', $current_date, '<=', 1)
    ->fieldCondition('field_rd_prize_draw_dates', 'value2', $current_date, '>=', 1);
    ->execute();

```
> 4 votes

---
Tags: 7, datetime, database
---


# Question
Title: Images not appearing into sites/default/files
I designed and set up a site for a client at Gregory Lamberson.com, and for some reason when he tries to create new content, the images are not uploading to the correct directory. The old images that I put on the site are showing up fine at /sites/default/files, but when he tries to add a new image, it writes the image into /?q=sites/default/files, and that directory doesn't exist, so the images are not showing up into the site.

Clean URLs are not enabled, so I was thinking that if I do enable them it might solve the problem. However, I am just starting out in front-end development and I could use a second (professional) opinion.

The nodes in question are in Storm Demon & AfterLife Project.

Thanks!

# Answer
I fixed this problem. Apparently it was a permissions issue with the default directory. I set it recursively to 777 and the client was able to post images without a problem. I just had to make sure to reset the permissions on the settings.php file.
> 4 votes

# Answer
777 grants full access for anyone to write and execute files on your server! I know 777 makes everything work, but you'll be happy until someone hacks your server.

Use CHMOD instead and apply the server username. Once you transfer from local to remote, the ownership is carried over if you use a tarball and that can cause this issue. 770 would be much better than 777.
> 1 votes

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


# Question
Title: Is there a way to switch the Search form (used in the block) to do a Facet Search instead?
I am using Faceted Navigation for Search and I want to switch the standard Search block to do a faceted search directly rather than the current situation where I have to switch to faceted search after the standard block shows up.

Is there a module for that, or can it be fixed somewhere in the options?

# Answer
> 1 votes
As stated below I originally understood your question. Here is how you change the default search page to the one with faceted navigation: In admin/config/search/settings you can turn off default node search and make faceted your default as shown in the below screen shot.

The Search API module allows you to choose other search methods, including using something like SOLR server for search, which also does faceted queries.

---
Tags: search
---


# Question
Title: Drupal cron will unserialize array and add extra characters
I am working in an application using Drupal. Thru the UI I upload a text file that is then parse and each line store in the DB as a serialized array. So far so good until there.

I have setup a module using queue and the hook\_cron that will check each of the serialize arrays from the DB and make a node out of it.

I was getting some odd errors like the cron was not able to parse the serialized array and I noticed something odd the array keys were been serialize with extra characters (invisible characters).

While looking in the DB imports I notice that something like the word "comunique" that when serialize should be like:

```
s:9:"comunique"

```

instead it was showing like:

```
s:12:"comunique"

```

also a print\_r show me the following:

```
[comunique ] => Array (...)

```

I even test changing the word and there are always 3 characters extra. I tested locally in my computer and it is all good.

What am I missing? is this a server config issue or a code issue?

# Answer
> 0 votes
Thank you for your input. I open the PHP file with Notepad++ and there was the hidden tilde character. I remove it an everything started to work again like a charm.

For people having a similar issue, I will recommend opening the file in a different text editor.

---
Tags: 7, cron
---


# Question
Title: Problems with moving my site to another server - WSOD with unfamiliar errors
I've transferred a site from one server to another (both using Webmin's backup and restore facility).

Everything appears to have transferred across fine, except for when I try to access my site, I get the WSOD. I enabled error reporting and get the following error. Unfortunately, I'm unable to comprehend what it's telling me.

> Warning: Table 'id0063\_BTG.users' doesn't exist query: SELECT u.*, s.* FROM users u INNER JOIN sessions s ON u.uid = s.uid WHERE s.sid = 'dc0n9e93lvckbmskv5frobirn2' in /home/id0063/public\_html/includes/database.mysqli.inc on line 128
>
> Warning: Table 'id0063\_BTG.system' doesn't exist query: SELECT name, filename, throttle FROM system WHERE type = 'module' AND status = 1 AND bootstrap = 1 ORDER BY weight ASC, filename ASC in /home/id0063/public\_html/includes/database.mysqli.inc on line 128
>
> Warning: Table 'id0063\_BTG.url\_alias' doesn't exist query: SELECT COUNT(pid) FROM url\_alias in /home/id0063/public\_html/includes/database.mysqli.inc on line 128

I checked the Apache error log and found this:

> \[Tue Jul 19 16:40:24 2011\] \[notice\] mod\_fcgid: call /home/id0063/public\_html/index.php with wrapper /home/id0063/fcgi-bin/php5.fcgi PHP Warning: PHP Startup: Unable to load dynamic library '/usr/lib/php/modules/intl.so' - /usr/lib/php/modules/intl.so: cannot open shared object file: No such file or directory in Unknown on line 0

Any ideas where I can start?

# Answer
> 1 votes
When I'm migrating websites I use the Backup & Migrate module. You should give it a try.

If the problem persists, look for differences between the two servers: PHP version, Apache version, MySQL version, etc. Also check your user permissions on the new server.

# Answer
> 0 votes
That message indicates your new server is missing the database (or at least some tables, but more likely all of them).

You'll need to copy the database from your old site to the new one. Step-by-step migration instructions are in the d.o. handbook.

---
Tags: migrations
---


# Question
Title: How do I fix a site after I removed a module?
I deleted a module without disabling and uninstalling it first. Now I just get a blank white screen, but I don't see any error messages. What can I try to fix this?

# Answer
> 3 votes
Run the following query.

```
select info from system where name = 'module_name';

```

You will get a blob. Within this blob look out for text after `version`. You can find the version of the module here.

Download this version of the module. Place it in `sites/all/modules` folder(you can also find out the previous location from the file-name field in system table), uninstall the module. Now delete the module.

# Answer
> 1 votes
Put the exact same version of the module back into your modules folder, disable and then uninstall it the correct way.

# Answer
> 0 votes
From SQL console or PHPMyAdmin:

> update system set status = 0 where name = 'MYMISSINGMODULE';

Clear cache and stay calm.

# Answer
> 0 votes
If you put it back and then disable it and uninstall it again.

You need to supply some additional information:

* The version of Drupal (5,6,7,8?)
* The name and version of the module

I've previously restored the database of Drupal 6 to a site without all the modules and never got a blank page so it must of been a pretty important part of the site.

Are you sure you can't access the ?q=/admin page? Even if you can't access the rest of the site these pages maybe unaffected.

---
Tags: wsod
---


# Question
Title: How can I use the unapproved comments list as a block?
The unapproved comments list (available at `/admin/content/comment/approval`) allows me to perform bulk operations on comments such as deletion (which also gives me the option of reporting to Mollom) and publishing. I'd really like to have this on the dashboard itself — is there a way to replicate this admin page as a block so I can do so?

This is under Drupal 7.12.

# Answer
> 1 votes
I would just use Views to list unpublished comments. That wouldn't provide batch operations, but it doesn't seem like there would be a simple way to do exactly what you're asking.

# Answer
> 0 votes
As @nkorth suggested, you can use Views to list the unpublished comments. And using Views Bulk Operations module you can add the same functionality on the comments administration page.

---
Tags: blocks, comments
---


# Question
Title: How can I use tab_parent/tab_root in hook_menu to have one router item appear as a local task for another router item with a different path?
Say I have the path `widget/123` to view a widget, and have another path to edit some properties of this widget at `admin/acme/widget/123/edit`. In `hook_menu` it looks like I can still have the admin path appear as a local task (tab) by setting the `tab_parent` and `tab_root` properties in `hook_menu()`, but I can't seem to get it to work. I know how to setup `widget/%/edit` as a local task, but in this case I'm only interested in setting a different "root" path as a local task.

Here's my code:

```
<?php

function acme_menu() {

  // View a widget.
  $items['widget/%'] = array(
    'type' => MENU_CALLBACK,
    'page callback' => 'acme_widget_view',
    'page arguments' => array(1),
    'access callback' => 'acme_widget_access',
    'access arguments' => array(1, 'view'),
    'file' => 'includes/widget.view.inc',
  );

  // Edit a widget.
  $items['admin/acme/widget/%/edit'] = array(
    'type' => MENU_LOCAL_TASK,
    'tab_parent' => 'widget/%',
    'tab_root' => 'widget/%',
    'title' => 'Edit Widget',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('acme_widget_edit', 3),
    'access callback' => 'acme_widget_access',
    'access arguments' => array(1, 'edit'),
    'file' => 'includes/widget.edit.inc',
  );

  return $items;
}

?>

```

Am I misunderstanding tab\_parent/root, or can this be done?

**Update:** I was missing a `MENU_DEFAULT_LOCAK_TASK`. Adding

```
$items['widget/%/view'] = array(
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'title' => 'View'
);

```

allows the tabs to appear. However, they don't share the same argument position and so the argument (the widget ID) isn't passed between the two. The 'Edit' tab, for example, links to `admin/acme/widget//edit`. Is there a way to have different routes like this and pass the argument position around?

# Answer
If I'm not mistaken the `tab_root` and `tab_parent` properties need to point to a path prefix of the router item in question - at least if there are wildcards on the path. The code responsible for this restriction is somewhat convoluted, but what you find when stepping through it is the following:

When generating the tab-links, the `_menu_translate` function is responsible for replacing the %-wildcards with actual values (node-id, etc). However the replacement values are not computed from the actual object-ids but are derived from the current URL. For example when accessing `widget/5`, the object-id is on position 1 and therefore when generating tab-links, the value 5 is only injected into paths having the %-wildcard at position 1.

This also leads to another consequence. When navigating to `admin/acme/widget/5/edit`, you will find that there are no tabs on this page - even if widget number 5 actually exists. This is because when generating the URLs for the other tabs, they will start with `widget/acme` instead of `widget/5` because the value `acme` is at position 1 in the current path.

If you like to provide tabs on your widget page as well as have it in the backend, then simply duplicate the router item. E.g:

```
function acme_menu() {

  // View a widget.
  $items['widget/%'] = array(
    'type' => MENU_CALLBACK,
    'page callback' => 'acme_widget_view',
    'page arguments' => array(1),
    'access callback' => 'acme_widget_access',
    'access arguments' => array(1, 'view'),
    'file' => 'includes/widget.view.inc',
  );

  $items['widget/%/view'] = array(
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'title' => 'View'
  );

  // Edit a widget - frontend
  $items['widget/%/edit'] = array(
    'type' => MENU_LOCAL_TASK,
    'title' => 'Edit Widget',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('acme_widget_edit', 1),
    'access callback' => 'acme_widget_access',
    'access arguments' => array(1, 'edit'),
    'file' => 'includes/widget.edit.inc',
  );

  // Edit a widget - backend
  $items['admin/acme/widget/%/edit'] = array(
    'type' => MENU_LOCAL_TASK,
    'title' => 'Edit Widget',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('acme_widget_edit', 3),
    'access callback' => 'acme_widget_access',
    'access arguments' => array(3, 'edit'),
    'file' => 'includes/widget.edit.inc',
  );

  return $items;
}

```

If you like to move around stuff from a third-party module, you still can implement additional router-items on behalf of it in a custom module - or even move them using `hook_menu_alter`.
> 3 votes

---
Tags: 7, routes
---


title: User defined domains

text:
# Question
Title: User defined domains
how can I create a user defined domain? E.g. user one will select for his shop the domain "shop1.example.com". User two will select "shop2.example.com" etc. How can I do this?I was thinking of Domain Access module but I am not sure which submodule to use. thanks

# Answer
Drupal can handle multiple sites very well. In a raw way without any modules you can use the multisite features of drupal. This can be done by creating submodules under sites for each of the sites.

When it comes to modules there are couple of them that deals with subdomains and multiple sites.

1. Virtual Sites This kind of automates the Multisite configuration for drupal. You can create additional domains and subdomains.
2. Subdomain This one is mainly used to create a subdomain and place contents under that subdomains. For example all contents of a group can be placed under the groups subdomain.
3. Domain Access Domain access is used in scenarios where you want to share contents between your domains and subdomains. You can assign contents specific to a domain or have the same content appear in multiple domains. Assign admins per domain etc. This is used for affiliates sites. A use case would be a main rental site with subdomains for each city.
4. Aegir This is not a module. This is a complete hosting solution build for drupal. This is a hosting profile. You would install it on a dedicated or virtual servers. You can create multiple sites from with in Aegir some thing similar to what you do on a reseller control panel. If you want to restrict the subdomains to a single domain then you can use the module Hosting Subdomains

So it ultimately depends on your use case.
> 2 votes

# Answer
I think I found the answer on this This is the module https://drupal.org/project/domain\_rules So a user can select a name and a new domain with this name will be created.
> 0 votes

---
Tags: domain-access, subsites
---


# Question
Title: Save the #default_value of custom fields when editing comments
I added a field select list comments in a hook\_form\_alter. When you select and save the comment, I do not know how to preserve the value of this field when editing this comment. My Code

```
function comment_author_form_comment_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'comment_node_zayavka_form') {
    $query = db_select('node', 'n')
      ->fields('n', array('type', 'uid', 'title', 'nid'))
      ->condition('n.type', 'brigada_type', '=');
    $result = $query->execute();
    $brigade_list = array();
    foreach ($result as $value) {
      if ($user->uid != 1) {
        if ($value->uid == $user->uid) {
          $brigade_list[$value->nid] = $value->title;
        }
      }
      else {
        $brigade_list[$value->nid] = $value->title;
      }
    }
    $form['select_brigade'] = array(
      '#type' => 'select',
      '#title' => t('Select brigade'),
      '#options' => $brigade_list,
      '#description' => t('Please select the team that was sent to you with reference to this application.'),
      '#required' => TRUE,
      '#default_value' => variable_get('comment_field_brigade_selection', 0),
    );
  }
}

```

# Answer
> 0 votes
I finally solved my problem, has created a field using field\_create\_field and attached it to the essence of my comment present the type of material My code for the solutions in the Custom Module:

```
/**
 * Реализация hook_enable().
 */
function comment_author_enable() {
    foreach (_comment_author_select_field_create() as $field) {
        field_create_field($field);
    }
    foreach (_comment_author_select_field_instances() as $instance) {
        $instance['entity_type'] = 'comment';
        $instance['bundle'] = 'comment_node_zayavka';
        field_create_instance($instance);
    }
}
function _comment_author_select_field_create(){
  $fields['brigade_select'] = array(
    'field_name' => 'brigade_select',
    'label' => t('Select an option from the list'),
    'type' => 'list_text',
    'cardinality' => '1', // change this to -1 to enable ctrl+select
    'foreign keys' => array(),
    'indexes' => array(
      'value' => array(
        0 => 'value',
      ),
    ),
    'module' => 'list',
    'settings' => array(
      'allowed_values_function' => '_comment_author_options_list',
    ),
  );

  return $fields;
}
function _comment_author_select_field_instances()  {
    $instances['brigade_select'] = array(
    'field_name' => 'brigade_select',
    'label' => t('Select brigade'),
    'description' => t('Please select the team that was sent to you with reference to this application.'),
    'default_value' => NULL,    // add a default value here that matches your key => index values
    'display' => array(
      'default' => array(
        'label' => 'above',
        'module' => 'list',
        'settings' => array(),
        'type' => 'list_default',
        'weight' => -1,
      ),
      'teaser' => array(
        'label' => 'above',
        'settings' => array(),
        'type' => 'hidden',
        'weight' => -1,
      ),
    ),
    'required' => 1,
    'settings' => array(
      'user_register_form' => FALSE,
    ),
    'widget' => array(
      'active' => 1,
      'module' => 'options',
      'settings' => array(),
      'type' => 'options_select',
      'weight' => '-1',
    ),
  );
  return $instances;
}
function _comment_author_options_list(){
global $user;
$query = db_select('node', 'n')
    ->fields('n', array('type', 'uid', 'title', 'nid'))
    ->condition('n.type', 'brigada_type', '=');
 $result = $query->execute();
 $brigade_list = array();
    foreach($result as $value){
        if($user->uid != 1){
            if($value->uid == $user->uid){
             $brigade_list[$value->nid] = $value->title;
            }
        }else{
        $brigade_list[$value->nid] = $value->title;
        }
    }
    return $brigade_list;
}

```

---
Tags: comments, forms
---


# Question
Title: How to create a block that shows recently viewed products/nodes for users?
I want to make a block that shows last viewed products for users (logged and anonymous), using Drupal 7 with Ubercart 3.

First, I tried to use the Recently read module. I don't why, but it's not working! Any changing in admin options (number of showing products and type of nodes) doesn't have any effect. And this block always shows ALL of my pages and products for all users.

Then I tried to do this using modules Flag \+ Rules \+ Session API. I found only a manual for Drupal 6. But in section "Select the condition to add - Check a truth value" and Views configure it's not similar to Drupal 7.

Can anybody help me to implement this functionality? Maybe you know, why the Recently read module seems to not be working in my case, or maybe it causes some conflict? Or how to configure modules Flag \+ Rules in Drupal 7?

# Answer
> 1 votes
* recently\_read seems to have evolved
* or do it with flag module (although not described in the linked tutorial, flag can also handle anonymous users)

---
Tags: views, rules, ubercart, flags
---


# Question
Title: Moving content fields to different theme regions with display suite
I am trying to output node fields in different theme regions, particularly a node reference field into my theme's right sidebar region. I have read this is possible with display suite and display suite extra modules, but I only see display suite regions (left, right...) and doesn't seem to be aware of my theme regions. How can I accomplish this?

# Answer
Try the cck\_blocks module. Once installed, you can enable field blocks per field via the field settings page.

Then in the display settings, hide the field in the default/full view and show it in the cck blocks view mode.
> 2 votes

# Answer
There's a few ways, but one reasonably simple way, still using theme regions, is with Views.

1. Add a "Block" display to a View
2. Add a "Contextual filter" for "Node ID"
3. Set contextual filter "Default value" to "Content ID from URL".
4. Add your entity reference fields etc.. to the View display and save.
5. Set the block visibility on your node page.

The View will then pickup the node id and show the relevant fields from that node.
> 1 votes

# Answer
Information on how to do this can be found in the Add fields to a block page of the Display Suite documentation
> 1 votes

---
Tags: theming, display-suite
---


title: Calendar view CSS

text:
# Question
Title: Calendar view CSS
I have a rather silly CSS issue with my multi- and single-day calendar events. The multi-day calendar events display fine, however there appears to be white space between the border and yellow background for single-day calendar events (see image.)

Here's **(some)** of my override CSS code which I think is responsible. I'd very much appreciate some guidance on how to get rid of the white space!

```
.calendar-calendar .item {
  color:#333333;
  border:1px solid #C2C2C2;
  border-radius:10px;
}

```

I've tried adding `padding: 0;` to no avail.

# Answer
The inspector definitely helped, Scott...I'm nearly there now:

```
.calendar-calendar .month-view .full .inner .monthview, .calendar-calendar .week-view .full .inner .weekview, .calendar-calendar .day-view .full .inner .dayview {
  border-radius:10px;
}
.calendar-calendar .month-view .full td.single-day div.monthview, .calendar-calendar .week-view .full td.single-day div.weekview, .calendar-calendar .day-view .full td.single-day div.dayview {
  padding-top: 0;
  padding-bottom: 0;
  padding-right: 0;
}
.calendar-calendar .month-view .full .inner .monthview, .calendar-calendar .week-view .full .inner .weekview, .calendar-calendar .day-view .full .inner .dayview {
  margin: 0;
}

```

Thanks for everyone's help.
> 0 votes

---
Tags: views, theming, datetime
---


# Question
Title: Undefined index errors only on one subdomain
On only one of my four registered domain names (foo.com, www.foo.com, foo.fr and www.foo.fr) am I'm getting undefined index errors such as:

Notice: Undefined index: vignettes in custom\_page\_preprocess\_charger\_accueil() (line 978 of /homez.119/retronom/www/sites/all/modules/custom/custom\_page/custom\_page.module).

The www.foo.com subdomain spits out these errors and is set up as a CNAME to foo.com. I'm really stumped as to how this could affect only one of the subdomains. What could cause these kinds of errors only on one?

Code setting up $varTemp:

```
//Vignette
if ($node->field_type['und']['0']['value'] == 1 && $node->language == $GLOBALS['language_url']->language) {
  $varTemp['vignettes'][$j]['image'] = theme('image_style', array (
    'style_name' => 'quick_link',
    'path'       => $node->field_image['und']['0']['filename'],
    'alt'        => $node->field_image['und']['0']['alt'],
    'title'      => $node->field_image['und']['0']['title'],
  ));

  $varTemp['vignettes'][$j]['link'] = $node->field_lien_site['und']['0']['value'];

```

Code that is failing:

```
While ($j != count($varTemp['vignettes'])) {  <-- Line 978
  if ($varTemp['vignettes'][$i]) {
    if ($varTemp['vignettes'][$i]['column'] == 'A') {
      $vars['vignettes']['A'][$a]['image'] = $varTemp['vignettes'][$i]['image'];
      $vars['vignettes']['A'][$a]['link'] = $varTemp['vignettes'][$i]['link'];
      $vars['vignettes']['A'][$a]['ombre'] = $varTemp['vignettes'][$i]['ombre'];
      $vars['vignettes']['A'][$a]['title_link'] = $varTemp['vignettes'][$i]['title_link'];
      if (isset($varTemp['vignettes'][$i]['body'])) {
        $vars['vignettes']['A'][$a]['body'] = $varTemp['vignettes'][$i]['body'];
      }
      $a++;
    ...
    snip
    ...
}

```

# Answer
Since you don't say anything about any debugging effort, it's hard to say, but one thing repeatedly stands out as clearly wrong

```
$node->field_X['und']['0']

```

which should always be

```
field_get_items($node, 'field_X);

```

Since your domains are `foo.com, www.foo.com, foo.fr and www.foo.fr`, this might indicate that you use more than one language, which is exactly when `['und']['0']` is likely to break for you. Notice that field\_get\_items() will return an array instead of a single value, so you will need to amend your code to deal with that.
> 0 votes

---
Tags: subsites
---


# Question
Title: Cannot install Search API pages module, due to database errors?
Trying to install search\_api\_page created repeated database errors about the search\_api\_page table not being available.

Is it a known problem known to happen?

# Answer
I have had a similar issue. I resolved it by installing search api on a fresh drupal install and exporting the databases then importing to the original database. I would **not** recommend doing this first however.

First you should uncheck search api module in your modules list, then click the uninstall tab and uninstall it. Grab a new copy of the search api module to make sure you didn't have corrupt files and install it again. If this doesn't work, then you may want to try what I had to do.
> 1 votes

---
Tags: installation, search
---


# Question
Title: Profile fields shown during registration
I want to have one profile with some fields shown during registration and other fields not shown during registration. I can't seem to do this.

I am using the Profile2 module (drupal.org/project/profile2)

From what I can see, a profile selected to "Show during user account registration" will show all fields associated with that profile during registration. And a profile that is not selected to show during registration will not show any fields during registration.

I am not seeing any options within a profile to make a given field override the selected setting for the profile.

So currently I have two profiles for the users - one with the fields I want shown during registration and a second profile with the fields I don't want shown during registration.

The result is two profile links for the user, which is not what I want.

How can I make a given profile field override the profile's registration setting?

---

Thanks for your answer, CR47. I am currently unable to select your response as the answer or even add comments because of a JavaScript problem. I will select your answer as soon as the error is resolved.

https://meta.stackexchange.com/questions/188125/dreaded-error-stack-overflow-requires-external-javascript-from-another-domain

# Answer
The field permissions module should help with this. You can set individual permissions on fields of user and node entities. If you set a field permission to be visible to only authenticated users, then it won't show on the sign up page.

Here is an example with screenshots:

These are the fields I have in Profile 2

When editing the field for "Will not be visible" I scroll to Field visiblity and permissions and select custom. Then check the types of users that can see/edit values for themselves and others. By default everything is only checked for admin.

Then when going to create an account you can see the "Will not be visible" field is not visible.
> 4 votes

---
Tags: users
---


# Question
Title: Is there an existing module to bulk delete user content but not user?
I have a user role that is meant for pseudo-anonymous usage and each account of this role-type will be shared in a pool of users. Whenever a user of this role logs out, I'd like to delete all their associated content to prepare for the next possible user using this account. This sounds like a job for hook\_logout, but it also seems like there should be a module for this already, right? I searched but maybe I'm not using the right keywords.

# Answer
I'd suggest to try out Rules module for this, you've got an event: "User has logout", grab the entities from that user, loop them and delete them.

Here's a exported rule that would do it (change the number of entities to suit your needs)

```
{ "rules_test_logout" : {
"LABEL" : "test_logout",
"PLUGIN" : "reaction rule",
"REQUIRES" : [ "rules" ],
"ON" : [ "user_logout" ],
"DO" : [
  { "entity_query" : {
      "USING" : { "type" : "node", "property" : "author", "value" : [ "account" ] },
      "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
    }
  },
  { "LOOP" : {
      "USING" : { "list" : [ "entity-fetched" ] },
      "ITEM" : { "list_item" : "Current list item" },
      "DO" : [ { "entity_delete" : { "data" : [ "list-item" ] } } ]
    }
  }
]

```

} }
> 2 votes

---
Tags: 7, hooks, users
---


# Question
Title: diffrent theme for admin without use theme appearance config
by default Drupal(7) use "page.tpl.php" for all(front and admin) pages.but I want use another file for example "page-admin.tpl.php" for admin layout.i don't want change admin theme in config/appearance.

# Answer
Copy `page.tpl.php` to `page--admin.tpl.php` (note two hyphens) clear theme registry / all caches and should be good to go.
> 3 votes

---
Tags: theming
---


# Question
Title: How do I stop HTML entities appearing in an e-mail client's subject header?
If I send an email with `drupal_mail` with the subject header:

```
Let's go

```

It appears in my email client:

```
Let's go

```

This is okay:

```
Let’s go

```

The most convincing explanation I've read is:

> The behavior you are seeing is because the subject line is being run through check\_plain() (via t()), which calls the PHP function htmlspecialchars().

Here's the link.

What changes should I make to my hook\_mail code to correct my header in the email client:

```
$message['subject'] = t('Let's go');

```

**Code that threw the error:**

```
$message['subject'] = t('@responder has responded to: @title', array(
  '@responder' => $params['responder'],
  '@title' => $params['title'],
));

```

# Answer
you can use **!responder** and **!title** instead of **@responder** and **@title** in your code (by using ! instead @ or % it tells drupal to use the string as is ; by using @responder Drupal will run the string through check\_plain to escape html characters).
> 2 votes

# Answer
If still an issue after upgrading, you can use

`hook_mail_alter`

e.g:

```
/**
 * Implements hook_mail_alter
 */
function MODULE_mail_alter(&$message) {
  // Sanitize and decode HTML entities in email subject
  $message['subject'] = decode_entities(filter_xss($message['subject']));
}

```
> 0 votes

---
Tags: emails
---


# Question
Title: how can I make a welcome popup window upon visiting the website
Some clients I have may want a popup when a user visits the site if they have special events going on, and display maybe a flyer in a popup.

How can I force a popup upon a user visiting the site? Is there a module that can accomplish this? If not, what kind of edits am I looking at doing?

# Answer
> 3 votes
You are looking for Splashify module, it also have the option to popup on any page.

> Display a splash page anywhere on your site by redirecting the user, showing a lightbox, or displaying a popup. This module is designed to be search engine friendly, mobile device friendly and offers multiple configuration options.

**or**

You can try TinyBox (Simple Splash). see the demo

> The main purpose of this module is to provide Splash Screen/Window as simple as possible.

**or**

take a look at Splash Offer module

> Allows the management of one or more "splash offers", which are modal popups with an accept or reject form. If a user accepts the offer then a new page will open with a provided accept url. If they reject the offer, the modal will close.

# Answer
> 1 votes
To make this more maintainable I would load some jquery that just targets a particular piece of content via selector and uses ui.dialog.

# Answer
> 0 votes
I would write it in the template files with a cookie; it is not pretty, but it gets it done.

For example, in every page.tpl.php

# Answer
> 0 votes
Creating a custom action/trigger. On front page content view, load the flyer/event page in a lightbox (or shadowbox) popup, and redirect them to an alternate front page that doesn't set off that trigger.

---
Tags: 7
---


# Question
Title: Implementing a callback after user registration
I want to run a database query in another CRM database after a user has registered. I have the following function in my sugar\_crm module eg:

```
function sugar_crm_user_register_submit($form, &$form_state)
{
    // some code to run a database query in SugarCRM
    ddl("User registration form submitted to CRM");

}

```

However, the function doesn't appear ever to be called. What am I doing wrong here?

# Answer
> 5 votes
A way is add a `submit` function to `user_register_form` submits in form alter.

```
yourmodule_form_alter(&$from,$form_state,$form_id) {
  if ($form_id == 'user_register_form ) {
       $form['#submit'][] = 'sugar_crm_user_register_submit';
       }
 }

```

but I think the better way is setup your custom function in `hook_user_insert`.this hook triggered when a user registered . you can implement it in your custom module.

```
  function yourmodule_user_insert(&$edit, $account, $category) {
   // some code to run a database query in SugarCRM
  ddl("User registration form submitted to CRM");
  }

```

# Answer
> 2 votes
```
function sugar_crm_user_insert(&$edit, $account, $category) {

  // some code to run a database query in SugarCRM

    ddl("User registration form submitted to CRM");
}

```

This code worked for me in D7.

For D6,

```
function scrm_user($op, &$edit, &$account, $category = NULL) {

  if ($op == 'insert' || $op == 'update' )  {

  // some code to run a database query in SugarCRM

    ddl("User registration form submitted to CRM");
  }
}

```

# Answer
> 1 votes
Do you have the '#submit' property inside your hook\_form\_alter() ? E.g

```
 <?php
    function sugar_crm_form_alter(){
// Call the  submit handler
$form['#submit'][] = 'sugar_crm_user_register_submit';
    }
    ?>

```

---
Tags: 7, users
---


# Question
Title: Define a specific page.tpl for a page create from a module
I have a module witch generates a custom page:

```
function my_module_basket_menu() {
  $items["my-basket"] = array(
    "title"=>"My basket",
    "page callback" => "_my_basket_page",
    "access arguments" => array("access my_module_basket content"),
  );

  return $items;
}

function my_module_basket_theme($existing, $type, $theme, $path) {
  return array(
    'my_module_basket_page' => array(
      'template'  =>"my_module_basket_page",
      'render element' => 'page',
      'arguments' => array("listeProducts" => NULL, "key" => $key),
    ),
  );
}

function my_module_basket_theme_registry_alter(&$theme_registry) {
  $hooks = array('page');

  foreach ($hooks as $h) {
    // Add the module path on top in the array of paths
    array_unshift($theme_registry[$h]['theme paths'], drupal_get_path('module', 'my_module_basket'));
  }
}

function _my_basket_page() {
  // ...some treatment

  return theme("my_module_basket_page", $liste_produits, $key);
}

```

All works fine, but the problems start here: I want also to have a specific page.tpl, for example `page_my_basket.tpl.php`.

I tried to create a function `my_module_basket_preprocess_page` and change the theme there but the URL path I catch is the node of the page 404. Impossible to catch "my-basket". Any ideas? A different suggestion on how i can make it work?

**EDIT**

As suggested, i changed the name of my registry\_alter function. From here when i look at the url (with a dsm()), i catch the good one, not the 404. So that part is ok.

So now i have to theme two page tpl, one for the page create in the module and a second one to replace the page.tpl.php The problem is this second page i add a function preprocess in my module :

```
function my_module_basket_preprocess_page(&$variables, $hook){

    $alias = drupal_get_path_alias($_GET['q']);

    if ($alias == "my-basket") {
      $variables['template_files'][]  = 'page_my_basket';
    }
}

```

In my hook\_theme function, i have that :

```
function oxo_wedze_basket_theme($existing, $type, $theme, $path){

  return array(
    'my_module_basket_page' => array(
      'template'  =>"my_module_basket_page",
      'arguments' => array("listeProducts" => NULL, "key" => $key)
    ),
    'page-my-basket' => array(
      'template'  =>"page_my_basket",
      'render element' => 'page'
    ),
  );
}

```

And that don't work, i still get the standard page.tpl.php

# Answer
Page templates have overrides already available based on path.

If you see template\_preprocess\_page() it has this code:

```
// Populate the page template suggestions.
if ($suggestions = theme_get_suggestions(arg(), 'page')) {
  $variables['theme_hook_suggestions'] = $suggestions;
}

```

and you can see that theme\_get\_suggestions() looks at the path and generates the template suggestions.

This means that if you have hook\_menu() generate the path "my-basket" then you will be able to override its page template in your theme by naming it **page--my-basket.tpl.php** without having to do anything else, like use hook\_theme() or manually add a template suggestion in the preprocessor, or alter the theme registry.
> 5 votes

# Answer
In order to have a different `page.tpl.php` for your page rendering, you can use the `YOURMODULE_preprocess_page` hook and add `theme_hook_suggestion`.

```
function my_module_basket_preprocess_page(&$variables)
{
    $variables['theme_hook_suggestions'][] = 'page__my_basket';
}

```

The template file should be part of your theme and is located under the `/templates` folder using `page--my-basket.tpl.php` as filename. Don't forget to clear the Drupal cache.
> 1 votes

---
Tags: theming, 7
---


# Question
Title: Attaching a view with exposed filters block to user profile in D7
Here's a riddle:

I want to create a user profile page that will display some user info at the top (from Profile2) and a tabbed view of that user's nodes. Pretty similar to Twitter's profile page, with the only exception being that on the right side I want to put an exposed filter block so as to filter the contents of this view.

Sounds simple? It was simple in D6, but in D7 it's a mystery. In D7 in order to attach a view to user profile you have to use the EVA module, which does not allow for "Filters Exposed in Block" option. If you create an exposed filters block from the Master, it returns the default "all" argument even though you are on user/# page and theoretically passing the correct argument to the Views.

By contrast, exposing the filters inside EVA and placing them above the View works and passes the correct arguments, but then the profile page looks ugly.

So how does one resolve this riddle? How can I have a View on user-profile page and have a functioning Exposed Filters Block on the side?

# Answer
> 0 votes
Having exposed filters in a block is really only meant for page views.

There is a work around for creating a block view that will work with an exposed filters block at https://drupal.stackexchange.com/a/38994/10729 \- Note also the comment below the answer, which talks about creating a custom module for the block, which is much better than using the PHP input filter if you don't mind making modules.

Then you can assign the block to show on the profile page.

A potential downside is that you cannot reorder the view via the profile fields display admin area like you can with EVA. This may or may not be an issue depending on wheere exactly you are positioning the view.

You could also instead print the block manually in your theme on that page exactly where you want it, or you could even put the views\_embed\_view() line directly in your theme and not worry about the block at all.

---
Tags: users, views
---


# Question
Title: Programmatically display user names according to the user profile type
This is a Drupal 7 site. I have a profile2 module installed with several profile types for different users. The user name should be displayed according to the profile type:

* For personal users - the user name should be build from the first and last name fields.
* For business users, the user name should be taken from the business name field.

How do I display user names programmatically?

# Answer
> 1 votes
I've put the following code on a module:

```
<?
// Find the type of the current user
function mymodule_get_usertype(&$user) {
  $usertype = 'other';
  if (is_array($user->roles) &&
      in_array('authenticated user', array_values($user->roles))) {
    $usertype = 'individual';
  }
  elseif (is_array($user->roles) &&
          in_array('non authenticated user', array_values($user->roles))) {
    $usertype = 'individual';
  }
  elseif (is_array($user->roles) &&
          in_array('business', array_values($user->roles))) {
    $usertype = 'business';
  }
  return $usertype;
}

// Implements hook_username_alter,
// to display the user name according to the profile type
function mymodule_username_alter(&$name, $account) {

  $profile_type = mymodule_get_usertype($account);
  if (!empty($profile_type)) :
    $profiledata = profile2_by_uid_load($account->uid, $profile_type);
  endif;

  if ($profiledata) :

    switch ($profile_type) {
      case 'individual':
        $firstname = field_get_items('profile2', $profiledata, 'field_first_name');
        $firstname = $firstname[0]['safe_value'];
        $lastname = field_get_items('profile2', $profiledata, 'field_last_name');
        $lastname = $lastname[0]['safe_value'];
        $name = "$firstname $lastname" ;
        break;

      case 'business':
        $bizname = field_get_items('profile2', $profiledata, 'field_biz_name');
        $bizname = $bizname[0]['safe_value'];
        $name = $bizname;
        break;

      default:
        // For admin users, no change
    }
  endif;
}
?>

```

The result is that the new name is displayed whenever a user name is displayed (e.g. on the menus, on the user page, or on the user listing pages)

---
Tags: 7, users
---


# Question
Title: How to create block with unapproved comments for dashboard?
I have a question similar to this one: I'd like to add a block with an overview of unapproved comments on nodes to my dashboard and simply have the possibility to publish them (via a link or button).

How can I do that?

# Answer
If you need a simple solution, such as a link for approving a comment (no bulk operations), you can achieve this simply with Views.

Add a new field to your view of comments and select 'Comment: Approve link'. This will provide a link for approving the comment.
> 0 votes

---
Tags: 7, comments, dashboard
---


# Question
Title: Having different theme elements for different pages
I am trying to wrap up an HTML theme into a drupal template and I cannot get right idea on how to do this.

I am having a front page, that is unique in it's elements. Then, I am having another page that only keeps the header from the front page, and footer. On this page, I am having some boxes, in witch the content should be nodes. How can I do this?

After that, I am having different pages where I need to add their elements from the admin panel as content. So, there will be more categories, and I need to list the elements from each category into some pages that have different style.

Also, there are regions like footer, where I have some logos ( images ) that again, they need to be nodes and added/edited from the admin panel as content.

Can someone point me to the right direction?

I have tried to create some pages from the admin panel, and tried to use files like page--.tpl.php to have a page in witch I should add nodes/content as the page elements but it is not rendering. Neither if I try lie page--node--.tpl.php or things like that.

I have searched on google for a few hours but I haven't mnaged to get the propper solution.

Thank you in advice!

Best regards, Alex

# Answer
> 0 votes
Check out Context module - it will allow you to structure the website based on the node type, URL or other parameters. Depending on this, you can have different blocks displayed, or use different layouts.

See also Display Suite and Panels modules for even more possibilities.

If you want to avoid using additional modules, you can achieve similar functionality through code and `preprocess_html` or `preprocess_page` implementations. You can specify special templates that will be selected dynamically, e.g.:

```
function MYTHEME_preprocess_page(&$variables) {
  // Make sure we are on the single node page.
  if (arg(0) == 'node' && arg(1) && !arg(2)) {
    // This will allow you to have separate page.tpl.php template used only
    // for single nodes. You should have page--single-node.tpl.php file in
    // your theme to see this in action. You can combine this with any
    // additional number of conditions, e.g. node type, user role etc.
    $variables['theme_hook_suggestions'][] = 'page__single_node';
  }
}

```

---
Tags: theming
---