title: How to add a groupby to a view query

text:
# Question
Title: How to add a groupby to a view query
I have a view and I need to add a groupby at the end of the SQL query but, for some bugged module the interface do not save the 'Grouping field Nr.' option and I don't know how to achieve this view -.-

```
SELECT DISTINCT taxonomy_term_data.tid AS tid,
  field_testata_taxonomy_term_data.product_id AS field_testata_taxonomy_term_data_product_id,
  field_magazine_commerce_product.nid AS field_magazine_commerce_product_nid,
  field_magazine_commerce_product.LANGUAGE AS field_magazine_commerce_product_language,
  taxonomy_term_data.NAME AS taxonomy_term_data_name,
  taxonomy_term_data.vid AS taxonomy_term_data_vid,
  taxonomy_vocabulary.machine_name AS taxonomy_vocabulary_machine_name,
  'taxonomy_term' AS field_data_field_mondi_azzurra_taxonomy_term_entity_type,
  'taxonomy_term' AS field_data_field_avatar_taxonomy_term_entity_type,
  'taxonomy_term' AS field_data_field_logo_slider_taxonomy_term_entity_type,
  'taxonomy_term' AS field_data_field_image_taxonomy_term_entity_type,
  'commerce_product' AS field_data_field_image_commerce_product_entity_type,
  'taxonomy_term' AS field_data_field_call_to_action_taxonomy_term_entity_type
FROM {taxonomy_term_data} taxonomy_term_data
  LEFT JOIN {field_data_field_testata} field_data_field_testata ON taxonomy_term_data.tid = field_data_field_testata.field_testata_tid AND (field_data_field_testata.entity_type = 'commerce_product' AND field_data_field_testata.deleted = '0')
  LEFT JOIN {commerce_product} field_testata_taxonomy_term_data ON ield_data_field_testata.entity_id = field_testata_taxonomy_term_data.product_id
  LEFT JOIN {field_data_field_magazine} field_testata_taxonomy_term_data__field_data_field_magazine ON field_testata_taxonomy_term_data.product_id = field_testata_taxonomy_term_data__field_data_field_magazine.field_magazine_product_id
  LEFT JOIN {node} field_magazine_commerce_product ON field_testata_taxonomy_term_data__field_data_field_magazine.entity_id = field_magazine_commerce_product.nid
  LEFT JOIN {taxonomy_vocabulary} taxonomy_vocabulary ON taxonomy_term_data.vid = taxonomy_vocabulary.vid
WHERE (((taxonomy_vocabulary.machine_name IN ('testate'))))

```

I have to pick the last node connected to the taxonomy term \[connected to another taxonomy term filtered by context\] and now for each term and I have all the taxonomy-node coupple.

How can I achieve this?

There is a way to add 'Groupby tid' at the end of the query? Or I have to build the query diffrently?

UPDATE: If I active 'Use aggregation' I have this query

```
SELECT DISTINCT field_data_field_avatar. AS field_data_field_avatar_,
field_data_field_logo_slider. AS field_data_field_logo_slider_, field_data_field_image. AS field_data_field_image_, field_magazine_commerce_product.nid AS field_magazine_commerce_product_nid, field_magazine_commerce_product.language AS field_magazine_commerce_product_language, field_data_field_call_to_action.field_call_to_action_value AS field_data_field_call_to_action_field_call_to_action_value, taxonomy_term_data.name AS taxonomy_term_data_name, taxonomy_term_data.vid AS taxonomy_term_data_vid, taxonomy_term_data.tid AS tid_1, taxonomy_vocabulary.machine_name AS taxonomy_vocabulary_machine_name, COUNT(DISTINCT field_data_field_mondi_azzurra.field_mondi_azzurra_tid) AS field_data_field_mondi_azzurra_field_mondi_azzurra_tid, COUNT(DISTINCT field_data_field_mondi_azzurra.delta) AS field_data_field_mondi_azzurra_delta, COUNT(DISTINCT field_data_field_mondi_azzurra.language) AS field_data_field_mondi_azzurra_language, COUNT(DISTINCT field_data_field_mondi_azzurra.bundle) AS field_data_field_mondi_azzurra_bundle, MIN(taxonomy_term_data.tid) AS tid, 'taxonomy_term' AS field_data_field_avatar_taxonomy_term_entity_type, 'taxonomy_term' AS field_data_field_logo_slider_taxonomy_term_entity_type, 'taxonomy_term' AS field_data_field_image_taxonomy_term_entity_type, MIN(field_testata_taxonomy_term_data.product_id) AS field_testata_taxonomy_term_data_product_id, 'commerce_product' AS field_data_field_image_commerce_product_entity_type, MAX(field_testata_taxonomy_term_data__field_data_field_image.bundle) AS field_testata_taxonomy_term_data__field_data_field_image_bun, 'taxonomy_term' AS field_data_field_call_to_action_taxonomy_term_entity_type
FROM
{taxonomy_term_data} taxonomy_term_data
LEFT JOIN {field_data_field_testata} field_data_field_testata ON taxonomy_term_data.tid = field_data_field_testata.field_testata_tid AND (field_data_field_testata.entity_type = 'commerce_product' AND field_data_field_testata.deleted = '0')
LEFT JOIN {commerce_product} field_testata_taxonomy_term_data ON field_data_field_testata.entity_id = field_testata_taxonomy_term_data.product_id
LEFT JOIN {field_data_field_magazine} field_testata_taxonomy_term_data__field_data_field_magazine ON field_testata_taxonomy_term_data.product_id = field_testata_taxonomy_term_data__field_data_field_magazine.field_magazine_product_id
LEFT JOIN {node} field_magazine_commerce_product ON field_testata_taxonomy_term_data__field_data_field_magazine.entity_id = field_magazine_commerce_product.nid
LEFT JOIN {taxonomy_vocabulary} taxonomy_vocabulary ON taxonomy_term_data.vid = taxonomy_vocabulary.vid
LEFT JOIN {field_data_field_mondi_azzurra} field_data_field_mondi_azzurra ON taxonomy_term_data.tid = field_data_field_mondi_azzurra.entity_id AND (field_data_field_mondi_azzurra.entity_type = 'taxonomy_term' AND field_data_field_mondi_azzurra.deleted = '0')
LEFT JOIN {field_data_field_avatar} field_data_field_avatar ON taxonomy_term_data.tid = field_data_field_avatar.entity_id AND (field_data_field_avatar.entity_type = 'taxonomy_term' AND field_data_field_avatar.deleted = '0')
LEFT JOIN {field_data_field_logo_slider} field_data_field_logo_slider ON taxonomy_term_data.tid = field_data_field_logo_slider.entity_id AND (field_data_field_logo_slider.entity_type = 'taxonomy_term' AND field_data_field_logo_slider.deleted = '0')
LEFT JOIN {field_data_field_image} field_data_field_image ON taxonomy_term_data.tid = field_data_field_image.entity_id AND (field_data_field_image.entity_type = 'taxonomy_term' AND field_data_field_image.deleted = '0')
LEFT JOIN {field_data_field_image} field_testata_taxonomy_term_data__field_data_field_image ON field_testata_taxonomy_term_data.product_id = field_testata_taxonomy_term_data__field_data_field_image.entity_id AND (field_testata_taxonomy_term_data__field_data_field_image.entity_type = 'commerce_product' AND field_testata_taxonomy_term_data__field_data_field_image.deleted = '0')
LEFT JOIN {field_data_field_call_to_action} field_data_field_call_to_action ON taxonomy_term_data.tid = field_data_field_call_to_action.entity_id AND (field_data_field_call_to_action.entity_type = 'taxonomy_term' AND field_data_field_call_to_action.deleted = '0')
WHERE (( (taxonomy_vocabulary.machine_name IN  ('testate')) ))
GROUP BY field_data_field_avatar_taxonomy_term_entity_type, field_data_field_logo_slider_taxonomy_term_entity_type, field_data_field_image_taxonomy_term_entity_type, field_data_field_image_commerce_product_entity_type, field_data_field_call_to_action_taxonomy_term_entity_type

```

and this SQL error

```
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS field_data_field_avatar_, field_data_field_logo_slider. AS field_data_field_l' at line 1

```

As you can see this query is not correctly written by drupal: there are some dots after the fields name in the frist part of the query..

Do you think I can fix this Views's core error?

# Answer
> 3 votes
You need to enable aggregation under *Advanced \> Use aggregation*. You can then select how you want your data grouped using the settings under **Fields**, **Sort criteria** and **Filter criteria**.

---
Tags: views
---


# Question
Title: Convert db_query to db_select or EntityFieldQuery
Can anyone help me converting this query using *db\_query* to *db\_select* or *EntityFieldQuery*? I already tried a lot of things but always getting error. I am new with Drupal, my query works well but I think it's better converting this to *db\_select* or *EntityFieldQuery*, what you think?

**UPDATE**

My query:

```
function get_recent_videos($uid) {
  $query = db_query('SELECT * FROM {node} n, {field_data_field_video} v
         WHERE n.uid = :uid
         AND n.nid = v.entity_id
         AND v.field_video_value IS NOT NULL
         ORDER BY created DESC
         LIMIT 0, 4', array(':uid' => $uid));

  $result = $query->fetchAll();

  return $result;
}

```

How can I use a placeholder in the limit? I tried the same approach that I have used in *:uid* but didn't work.

Thanks a lot.

# Answer
You can use Entity Query here, with no need to make joins here is the sample code

```
function get_videos($limit = 4, $uid = 2508) {
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node');
    $query->entityCondition('bundle', 'your_content_type');
    $query->propertyCondition('uid',$uid);
    $query->fieldCondition('field_video','value', 'NULL', '!=');
    $query->propertyOrderBy('created', 'ASC');
    $query->range(0, $limit);
    $result = $query->execute();
    dpm($result);
  if (isset($result['node'])) {
    return $result;
  }
}

```

The db\_select for the same will be

```
function get_videos($uid, $limit = 4) {
    $query = db_select('node', 'n');
    $query->condition('n.type', 'your_content_type');
    $query->join('field_data_field_video', 'v', 'n.nid = v.entity_id');
    $query->condition('n.uid', $uid, '=');
    $nids = $query->fields('n', array('nid', 'uid','title'))
            ->fields('v', array('field_video_value'))
            ->isNotNull('v.field_video_value')
            ->orderBy('n.created', 'DESC')
            ->range(0, $limit)
            ->execute()
            ->fetchAll();
    return $nids;
}

```

**Please go with Entity Query The reason I can say is you do not need to**

> have advance database relationship to each other,as clear in the above example Entity Query looks pretty clean as simple object and attributes format while in db\_select you need to take care of joins.
> 1 votes

# Answer
Yes, if you're querying entity/field data you should pretty much always use an `EntityFieldQuery` in place of raw SQL. If you're not querying entity/field data, and need to build up a dynamic query, then `db_select()` is probably the way to go.

I'd also recommend reading the DB API docs and making sure you understand how to use `db_query()` properly - currently your code is likely to be susceptible to an SQL injection attack, as you're not using parameterized queries.
> 5 votes

# Answer
You could use EntityFieldQuery Extra Fields, there's also a good example included.

Here is a quote about it (from the module's project page):

> It allows you to use addField within an EntityFieldQueryExtraFields object (extends EntityFieldQuery objects). Initially EntityFieldQuery only gives you back the entity id, bundle and entity type. This module adds an extra layer on top of that without doing some extra entity\_loads! Important if you want to work with massive amounts of data and you want to reduce the sql queries. Since EFQ already queries the database for this information, why not alter that query to also give you some additional fields. This means that not a single extra query will be performed to get that data.
> 1 votes

---
Tags: 7, database
---


# Question
Title: Page Not Found for anonymous (clear cache fixes it)
I'm getting reports from users that clicking a link gives them Page Not Found.

* These are anonymous users.
* Page caching is turned on (but not aggressive)
* I log in, the page works. I log out, the page does not work.
* Three reports of unrelated pages in the past week (but all were different node types)
* Clearing All Caches fixes it.
* I could be wrong about this (because I didn't think to check until after I cleared caches), but I think it's returning error 406 in Recent Log Entries.

How can I begin to troubleshoot this?

# Answer
> 0 votes
Ask your sysadmin about the health and size of cache tables. Being logged in bypasses page cache. Clearing cache truncates them. Last time I've encountered similar effects, they were caused by a bad sector on server's HDD - when cache table grew enough to start using it, caches got all messed up. It was most visible with page cache.

---
Tags: 6, caching
---


# Question
Title: Confirmation email for newsletter signups drupal 7
Is it possible to send a confirmation email when someone signs up to my newsletter. When the user signs up an email should be sent to his mail conforming his subscripition and to await more info. Is this possible through the webform?

# Answer
This is absolutely possible.

1. Go to admin/content/webform
2. Click Edit for the webform you want to modify.
3. Click on the Webform tab
4. Click on the E-mails sub-tab
5. Add a new one.

Once in there you can set all of the options you need to send an email to the person signing up.
> 1 votes

---
Tags: emails
---


# Question
Title: Trying to import existing Drupal site to a Linux Mint VM - getting redirected to install.php
I have Apache/MySQL/PHP installed and working, I've imported the database and called it *stove* and have updated the settings.php file in sites/default/ to use my database's name, username, and password. The hosts and vhosts are all set up correctly as well, pointing to 127.0.0.1 and the proper directories.

Any ideas on why it keeps trying to re-direct me to the install.php

Here is the snippet of code from settings.php for the database:

```
/* Database configuration format:
 * @code
 *   $databases['default']['default'] = array(
 *     'driver' => 'mysql',
 *     'database' => 'databasename',
 *     'username' => 'username',
 *     'password' => 'password',
 *     'host' => 'localhost',
 *     'prefix' => '',
 *   );
 *   $databases['default']['default'] = array(
 *     'driver' => 'pgsql',
 *     'database' => 'databasename',
 *     'username' => 'username',
 *     'password' => 'password',
 *     'host' => 'localhost',
 *     'prefix' => '',
 *   );
 *   $databases['default']['default'] = array(
 *     'driver' => 'sqlite',
 *     'database' => '/path/to/databasefilename',
 *   );
 * @endcode
 */
$databases['default']['default'] = array(
    'driver' => 'mysql',
    'database' => 'stove',
    'username' => 'root',
    'password' => '',
    'host' => 'localhost',
    'prefix' => '',
);

```

# Answer
Some of what was said was correct for this issue. Going through the install process would have been correct, however the install.php page was not loading because when I had gone through the install process on the previous server, acquia dev desktop had deleted the install.php.

The fix was to take my sites folder and put it into a freshly extracted Drupal directory (so that the install pages were all there), update settings.php to correct database info, then go through the install process, and finally drop the tables and import the back up of the database with the information I needed.

Another note: Acquia dev desktop will add the database settings to the BOTTOM of settings.php which can be easily missed. If you're developing on Windows for whatever reason, I recommend using a virtual machine. WAMP is wonky with some Drupal modules and Acquia Dev Desktop can be hassle when trying to migrate Drupal sites so having a \*nix VM can be very useful.
> 1 votes

# Answer
I know it sounds dumb, but just try this. Go ahead and go through the installation process. When you get to the Database settings, enter in the info for the database. If the database is correct, you should get a screen that says, "There's seems to be a site already here. Either clear out the database and try again, or see your site now." with a link.
> 0 votes

---
Tags: redirection, installation, configuration
---


# Question
Title: Redirect to login page if login fails from a login block?
I have a login form block, when a user fail to login to the site I want to redirect him to the user/login page with the usual error message

# Answer
You can do this by form\_alter

```
function MODULE_NAME_form_alter(&$form, $form_state, $form_id) {
  switch ($form_id) {
    case 'user_login_block':
      $form['#validate'][] = 'my_custom_login_val';
      break;
    default:
      break;
  }
}

function my_custom_login_val($form, &$form_state) {
  $form = form_get_error($form['name']) . form_get_error($form['pass']);
  if($form != '') {
    $_GET['destination'] = 'user/login';
    drupal_goto('user/login');
  }
}

```

If you need like after the correct login redirect to a page use Login Destination
> 5 votes

# Answer
Here a slightly different answer using hook\_form\_alter

```
function MODULE_form_alter(&$form, &$form_state, $form_id)
{
    if ($form_id == "user_login_block")
    {
        $form["#validate"][] = "MODULE_validate_login";
    }
}

function MODULE_validate_login($form, &$form_state)
{
    // on successful login, the uid is set in form_state.
    if (empty($form_state["uid"]))
    {
        $_GET["destination"] = "user/login";
        drupal_goto("user/login");
    }
}

```
> 1 votes

# Answer
Got this to work in drupal 7, looks like you need to define both

$\_GET\['destination'\] = 'user';

AND

$GLOBALS\['destination'\] = 'user';

```
$_GET['destination'] = 'user';
$GLOBALS['destination'] = 'user';
drupal_goto('user');

```
> -1 votes

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


title: How to abort a cron run?

text:
# Question
Title: How to abort a cron run?
I would like to have the ability to prevent cron from running based on a variable set in the database. I have created a hook\_cron implementation in a module with an extremely low weight so it will presumably run before all other module's cron hooks. Within that function I then check the variable and call exit() to abort PHP's execution. This seems to work but is there a more elegant way to prevent cron from continuing? Calling exit() seems a bit harsh and I am concerned about unintended consequences. Example code below.

```
function ex1_cron() {
  if (variable_get('ex1_var', 1) === 1) {
    watchdog('ex1', 'Cron is being aborted.', array(), WATCHDOG_WARNING, NULL);
    exit();
  }
}

```

# Answer
> 3 votes
Calling exit() yes is a little bit too harsh and it does bring some consequences with it:

1. Typically when drupal\_cron\_run() finishes running all the cron jobs created with hook\_cron() it logs into the watchdog the message "Cron run completed". Aborting your cron cycle mid-execution leaves you with no traces of how or when your cron finished.
2. When the cron cycle begins, Drupal creates a cron lock by using `variable_set('cron_semaphore', time());`, which prevents further cron cycles from running until you release the sempahore (manually) or until 3600 seconds pass since the last time you aborted the cron.

When your abort condition is met, you should at least do the following:

```
// Call cleanup function.
drupal_cron_cleanup();

// Release cron semaphore
variable_del('cron_semaphore');

watchdog('name_of_yourmodule', 'Aborted because XYZ.', array(), WATCHDOG_ERROR);

```

Also like @wiifm mentioned in his answer, a lot of critical functions defined by core and contrib depend on cron running to keep your site working. Abort cron and your site suddenly stops running smoothly. I would really avoid doing this.

# Answer
> 0 votes
I would propose that not running cron is a bad thing on most drupal sites. Cron is used for a large number of critical functions e.g. sending emails, updating the search index, making new sitemaps etc.

Instead of stopping cron from running, why not address the issue that is happening on cron? BTW - what is happening on cron that you do not want?

The code you wrote above will technically work, but if you were a developer on my team, and I saw this code in the repo, there would be words had ;)

# Answer
> 0 votes
I don't know if its relevant to you, but you might wanna check Elysa cron module

It basically let you to determine which cron jobs will run and when. Maybe there is a way to do so within the code and not only by GUI(but i never checked it).

---
Tags: 6, cron
---


title: Altering search form

text:
# Question
Title: Altering search form
I am trying to alter my search form. I am following tutorial to learn drupal theming. I want to replace the search button with an image :

```
function mytheme_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'search_block_form') {
$form['actions']['submit']['#type']= 'image_button';
$form['actions']['submit']['#src']= drupal_get_path('theme','MYTHEME').'/images/search.png';
$form['actions']['submit']['#attributes']['class'] [] = 'btn';
}
}

```

What i get in my page is the following result :

```
<input class="btn form-submit" type="image" id="edit-submit" name="submit" value="Search" src="http://mysite.com/sites/mysite.com/themes/MYTHEME/images/search.png">

```

However i want :

```
class="btn"

```

And not

```
class="btn form-submit"

```

Did i miss something ?

Thanks !

# Answer
A much much easier way to do this is leave it at the default style and use CSS to replace it with an image. That is how it is done 9 times out of 10.

Now onto the question at hand, Drupal automatically adds certain classes based on the form type. The only way to remove the default classes is to override the `THEME_button` function and do it there, for more information see https://api.drupal.org/api/drupal/includes%21form.inc/function/theme\_button/6
> 3 votes

---
Tags: theming, forms, search
---


# Question
Title: How to show the count of members that belong to a group?
I have a view showing a list of nodes of type group. How do I set it up to show the count of members that belong to each group?

# Answer
I finally figured it out:

(enlarge image)

The steps are:

* create a view for "content" type "group". Use "fields" and show "content:title", that's the name of your group
* add relationship "Group: Node group" (required), then "(group) Organic groups group: OG membership" (required).
* add filter "(OG membership) OG membership: Entity\_type " and set to "is equal" to "user"
* "use aggregation"
* add field "(OG membership) OG membership: Entity id" and use "count distinct" option. That's your count of members.

If you want the count of nodes that are "linked" to a group you would just change the filter from "user" to "node".
> 16 votes

# Answer
I have discovered something that might help. In the header section of the view, click on "add" and choose "OG membership: Group membership overview". That single entry will add something that looks like the following:

```
Group overview

 - Group manager: admin
 - Total members: 4
 - Total content: 0

```

I desperately need those to be individually available in the "fields" section of the view where if can be displayed with more flexibility ... and per row.

I will dig into the code and add those views fields. Hopefully things go well. If so, I will post the code back here, and a patch on the OG project page, or an custom module.

I am starting to think that Drupal module builders seriously need to organize focus groups regarding the usability and the necessity of some new features. The OG seems so disconnected from the end users needs that I am starting to have serious doubt about using it. Unfortunately, there is no alternative that I know of.

(Note from different user: Had this exact same problem, and comment #62 on this issue worked for me: https://drupal.org/node/1101102#comment-7404856)
> 2 votes

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


# Question
Title: Filling compound field programatically fails with EntityMetadataWrapperException
I followed the instruction in the post from here to create a compound field and it work like a charm. Now I am trying to fill each of the 3 "columns" that make the compound field programmatically and I can figure it out how.

I am using the entity API to create the node see the code below:

```
$node = entity_create('node', array('type' => 'MY-CONTENT-TYPE'));
$entity = entity_metadata_wrapper('node',  $node);

$data = array('column_1'=>'value 1', 'column_2'=>'value 2', 'column_3'=>'value 3');

$entity->field_custom_compound_field = $data;

$entity->save();

```

But it does not work. What am I missing?

Note: I keep getting the error:

> EntityMetadataWrapperException: Unknown data property field\_custom\_compound\_field.

# Answer
> 1 votes
I am posting this here in case someone is having the same issue:

I use the tutorial located here to create my compound custom field with multiple columns what I didn't noticed was in the hook\_fields\_field\_info() implementation I should define the type of data the entity will take. To make things worse in the tutorial the author use the example where all the fields he created are text fields, but in my case I have date, decimal and text fields so I had to define each type. I found the solution in this post.

In a nutshell in my hook\_fields\_field\_info() implementation I have to declare the entity property type, but since I am using multiple columns on the field I have to implement a call back function that will allow me to define the property type for each of my columns.

```
/**
* Implements hook_field_info().
*
* Provides the description of the field.
*/
function field_example_field_info() {
  return array(
  // We name our field as the associative name of the array.
    'field_example_rgb' => array(
      'label' => t('Example Color RGB'),
      'description' => t('Demonstrates a field composed of an RGB color.'),
      'default_widget' => 'field_example_3text',
      'default_formatter' => 'field_example_simple_text',
      'property_type' => 'field_example_rgb', // we add the propert type here
      'property_callbacks' => array('field_example_rgb_property_info_callback'), // we add the callback
    ),
  );
}

```

Call back function to define each columns type:

```
function field_example_rgb_property_info_callback(&$info, $entity_type, $field, $instance, $field_type) {
  $property = &$info[$entity_type]['bundles'][$instance['bundle']]['properties'][$field['field_name']];

  $property['getter callback'] = 'entity_metadata_field_verbatim_get';
  $property['setter callback'] = 'entity_metadata_field_verbatim_set';
  unset($property['query callback']);

  $property['property info']['rgb'] = array(
    'type' => 'text',
    'label' => t('RGB'),
    'setter callback' => 'entity_property_verbatim_set',
  );
  $property['property info']['someothervalue'] = array(
    'type' => 'text',
    'label' => t('Some other value'),
    'setter callback' => 'entity_property_verbatim_set',
  );
}

```

After doing that the following code:

```
$node = entity_create('node', array('type' => 'MY-CONTENT-TYPE'));
$entity = entity_metadata_wrapper('node',  $node);

$data = array('column_1'=>'value 1', 'column_2'=>'value 2', 'column_3'=>'value 3');

$entity->field_custom_compound_field = $data;

$entity->save();

```

Worked like a charm.

---
Tags: 7, entities
---


title: Hide the required sign

text:
# Question
Title: Hide the required sign
I need to hide the red "required" star sign, but I can't understand how to hide this red star mark using `hook_form_alter()`.
I know this can be done using CSS, but I want to know if it is possible to do it using `hook_form_alter()`, or if there is any other way to hide it programmatically.

# Answer
> 2 votes
You can use themename\_form\_element() to remove asterik as given in the link.

```
function YOURTHEMENAME_form_element($element, $value) {
  $output  = '<div class="form-item"';
  if (!empty($element['#id'])) {
    $output .= ' id="' . $element['#id'] . '-wrapper"';
  }
  $output .= ">\n";

  //REPLACE THIS
  //$required = !empty($element['#required']) ? '<span class="form-required" title="' . t('This field is required.') . '">*</span>' : '';
//WITH THIS

  if (!empty($element['#title'])) {
    $title = $element['#title'];
    if (!empty($element['#id'])) {
      $output .= ' <label for="' . $element['#id'] . '">' . t('!title: !required', array('!title' => filter_xss_admin($title), '!required' => $required)) . "</label>\n";
    }
    else {
      $output .= ' <label>' . t('!title: !required', array('!title' => filter_xss_admin($title), '!required' => $required)) . "</label>\n";
    }
  }

  $output .= " $value\n";

  if (!empty($element['#description'])) {
    $output .= ' <div class="description">' . $element['#description'] . "</div>\n";
  }

  $output .= "</div>\n";

  return $output;
}

```

# Answer
> 2 votes
You can use the theme\_form\_required\_maker to change the asterisk to whatever

```
function theme_form_required_marker($variables) {
  // This is also used in the installer, pre-database setup.
  $t = get_t();
  $attributes = array(
    'class' => 'form-required',
    'title' => $t('This field is required.'),
  );
  return '<span' . drupal_attributes($attributes) . '>*</span>';
  }

```

https://api.drupal.org/api/drupal/includes%21form.inc/function/theme\_form\_required\_marker/7

---
Tags: forms
---


# Question
Title: How to make an editable catalog on Drupal?
I'm trying to make something like an catalog (e.g. an address book) on my site, in which the user can interact with the fields, like adding, editing and removing entries, I'm thinking about putting each of those entries as a content type node and then using views to display and modify them... Is there any known problem with this approach? could you suggest another one?

I want it to be dynamic, on click the selected entry expands allowing for editing and automatically saves the content...

# Answer
The simplest thing todo is to make a View thats lists your catalog entries. In the `Header` area of the view add a `global text area` in which you create a link such as `<a href="/node/add/YOUR_CATALOG_ENTRY_NODE_TYPE">Add New Entry</a>`.

Then also install the Editable Views module:

> Editable Views lets you create Views where the fields can be edited. Fields show both the current value and a form to edit it. A 'Save' button allows saving of all the entities shown in the View.
>
> Editable fields can be added on the base entity as well as on entities brought into the View by a relationship. Other, non-editable fields may be added to the View, in which case they function normally.

From the project page you can see a screencast on how to use the Editable Views module.
> 2 votes

---
Tags: views, nodes
---


# Question
Title: How to check if the problem is of clean url when migrating the database from one server to another?
After uploading the my local db on server my site was not working and what I was getting was white screen of death. After few hours of struggling I found that as the server was not configured for clean url and the in the database the clean url settings was ON that was causing the problem.

Is there any way we can come to know if the problem is of the clean url in such scenario.

Also I can't use the backup and migrate module as the database size was too large.

# Answer
> 1 votes
It is advised to **turn off** the **CLEAN URLs** before migrating the database from one server to server.

Reason behind you were not able to see errors on white screen of death may be error reporting being turned off, if that is the case than you may try adding the following lines in setting.php to turn on error reporting:

```
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

```

> Also check the entry's of "watchdog" table if you are getting white screen of death upon migration.

---
Tags: 7, database, migrations, uri
---


# Question
Title: How do I add a <div> after every field element on the node edit form?
There are two approaches that have failed:

1. In the theme, add a theme hook for the node edit form. Then, create a template file for the node edit form. This won't work for my case, because the form is rendered in the template file with drupal\_render\_children, and therefore the contents of the form are not reachable within the template file--I need to add the divs in between the form elements.
2. Use hook\_form\_alter. This won't work for my case, because you have to target a specific form item. The users may, for example, add a new node field after I hand it off to them, and my existing hook\_form\_alter wouldn't have a way to catch it.

What I want to do is simple; in between every element on the node edit form, insert a `<div class="clearfix"></div>` to separate them.

Or, I could add the "clearfix" class to the existing div containers around the form elements.

Do we have a solution for either method?

\[EDIT\] Here is the solution using hook\_form\_alter():

```
<?php
/**
 * Implements hook_form_alter()
 */
function mytheme_form_alter(&$form, &$form_state, $form_id) {
  if (preg_match('/node_form$/', $form_id)) {
    $language = $form['language']['#value'];
    foreach ($form_state['field'] as $field => $field_contents) {
      $form[$field][$language]['#suffix'] = '<div class="clearfix></div>';
    }
  }
}
?>

```

# Answer
> 1 votes
The easiest way is using `hook_form_alter` for each Field add `#suffix => '<div class="clearfix"></div>"` to the existing FAPI array for the Field. I would just hard code it per field.

If you need to you could make a for loop and walk through the FIELDs so you dont hardcode the fields by hand ... If you were more crazy you could use an `#after_build` function too on the `$form` or set 1 per Field element as needed if you run into problems.

---
Tags: theming, forms
---


# Question
Title: Listing Active Members of Current Group in View pane (OG 7.x-2.3)
I am relatively new to Drupal and somewhat boggled by the new version of Organic Groups. We recently migrated our site from OG 7.x-1.4 to OG 7.x-2.3. Everything went fine except certain view panes no longer work. We had one view content pane that listed the members of the group in a page based on the context. We created a panel page for the group home page layout when the content pane was embedded in that page it would show the members for that group. However, the contextual filter for that view was broken after the import.

I tried to copy the view settings from a clean install of the latest OG code but that didn't work. The view is one of users but I cannot figure out how I should set the contextual filters or the relationships of that view to show only the members of the group. I just can't seem to wrap my head around how the OG\_Membership object works.

Any help would be greatly appreciated.

# Answer
> 0 votes
In retrospect the answer was rather obvious. When you migrate from OG 1.x to OG 2.x, the views associated with OG do not get updated. So they have "missing/broken relationships." For most of the view panes it was easy to fix by going to the view page and under the "edit view name/description" drop down, there is an option to "Revert View". Choosing this fixes the views that come with OG because it "reverts" the view to the updated OG 2.x code. Custom views have to be rebuilt.

---
Tags: views, organic-groups
---


# Question
Title: Callback on 'save' on 'new node form' doesn't fire
**UPDATE:** Approach showed bellow has the same results -\> doesn't work.

```
$new_form['#submit'][] = '_fmu_new_firm_under_user';

```

Separate button with only that callback doesn't work either. And what's weird, even if it has only the '\_fmu\_new\_firm\_under\_user' callback it actually works the same way as 'save' button -\> it saves the node and doesn't fire my callback.

```
$new_form['actions']['submit_and_create'] = array(
    '#type' => 'submit',
    '#value' => t('Vytvořit firmu'),
    '#submit' => array('_fmu_new_firm_under_user'),
  );

```

**Original message**

I've created a page with a 'myContentType\_node\_form' and attached a callback to the save button. The problem is that the callback is not fired when I press the button. To be more specific the default callback is fired - the node is saved - but my callback is not fired.

```
function _fmu_register_new_user_firm_callback($uid, $control_hash) { //a callback function for a menu item
      include_once(drupal_get_path('module', 'node') . '/node.pages.inc' );
      $new_form = node_add('fm_firm');
      $new_form['uid']['#value'][] = $uid;

      $new_form['actions']['preview']['#access'] = false;
      $new_form['actions']['submit']['#submit'][] = '_fmu_new_firm_under_user';

      dsm($new_form);
      return $new_form;
  }

function _fmu_new_firm_under_user($form, &$form_state) {

  $user = user_load($form['uid']['#value']);
  $user->fmu_users_firm[LANGUAGE_NONE][0]['target_id'] = $form->nid;
  user_save($user);

  dsm($user);
}

```

DSM of the form before returning it:

```
actions (Array, 16 elements)

    #type (String, 7 characters ) actions
    submit (Array, 23 elements)
        #type (String, 6 characters ) submit
        #access (Boolean) TRUE
        #value (String, 4 characters ) Save
        #weight (Integer) 5
        #submit (Array, 2 elements)
            0 (String, 16 characters ) node_form_submit | (Callback) node_form_submit();
            1 (String, 24 characters ) _fmu_new_firm_under_user | (Callback) _fmu_new_firm_under_user();
        #input (Boolean) TRUE
        #name (String, 2 characters ) op
        #button_type (String, 6 characters ) submit
        #executes_submit_callback (Boolean) TRUE
        #limit_validation_errors (Boolean) FALSE
        #process (Array, 1 element)
        #theme_wrappers (Array, 1 element)
        #defaults_loaded (Boolean) TRUE
        #tree (Boolean) FALSE
        #parents (Array, 1 element)
        #array_parents (Array, 2 elements)
        #processed (Boolean) TRUE
        #required (Boolean) FALSE
        #attributes (Array, 0 elements)
        #title_display (String, 6 characters ) before
        #id (String, 11 characters ) edit-submit
        #ajax_processed (Boolean) FALSE
        #sorted (Boolean) TRUE
    preview (Array, 23 elements)
    #theme_wrappers (Array, 1 element)
    #process (Array, 2 elements)
    #weight (Integer) 100
    #defaults_loaded (Boolean) TRUE
    #tree (Boolean) FALSE
    #parents (Array, 1 element)
    #array_parents (Array, 1 element)
    #processed (Boolean) TRUE
    #required (Boolean) FALSE
    #attributes (Array, 1 element)
    #title_display (String, 6 characters ) before
    #id (String, 12 characters ) edit-actions
    submit_and_create (Array, 3 elements)
        #type (String, 6 characters ) submit
        #value (String, 15 characters ) Vytvořit firmu
        #submit (Array, 1 element)
            0 (String, 24 characters ) _fmu_new_firm_under_user | (Callback) _fmu_new_firm_under_user();

```

# Answer
> 2 votes
You would be better off using hook\_node\_submit which would fire when any node is submitted.

You can make it specific to your node by the following:

```
function MODULE_node_submit($node, $form, &$form_state)
{
    if ($node->type == "NODE-TYPE")
    {
        //do stuff
    }
}

```

# Answer
> 0 votes
You don't add the callback to the actions, you add it directly to the `['#submit']`

Soo

```
$new_form['#submit'][] = '_fmu_new_firm_under_user';

```

If you are trying to add it to a button you would do something like

```
$new_form['buttons']['continue']['#submit'][]

```

---
Tags: 7, nodes, forms
---


# Question
Title: adding all children node flag count to sort parent
i have created two content type parent and child. a parent has children. and each child has own flag count value. like:

under Parent A child1 had flag count=5 child2 had flag count=2 child3 had flag count=0

under Parent B child1 had flag count=3 child2 had flag count=1 child3 had flag count=0 child4 had flag count=6.

now sort the parent according to all children's flag count value.Like here Parent B should come first because he has his children flag count value is 10..

please help me to short out this scenario...

# Answer
Is it possible to have a hidden field on parent node value for which updates as per the flag counter on referenced node changes.In that case it will be easier to build custom query or even if you use views you can sort by the hidden field value.

**Updated:**

> * Child node 1 has a node reference to Parent Node.
> * Keep flag count as hidden field on parent content type
> * The time flag is updated on Child node, you can grab all parent nodes on the updated child node.
> * Change the hidden field value on parent node from hidden field value to +1.

Code that can be used to update parent node field \- you will have all parent node id in child node object, grab the ids. \- Use the following code to update the parent fields.

```
  $node = node_load($nid);
  $node->field_flag_count['und'][0]['value'] += 1;
  field_attach_presave('node', $node);
  field_attach_update('node', $node);

```

> This will save lot more node save processing and unnecessary node revisions

SO this way the total flag count will all be present on parent node and sorting will be lot more easier that way!.
> 0 votes

---
Tags: 7
---


# Question
Title: Conditionally load JS based on whether or not a field has data?
I'd like to load a javascript file only if a specific field has data. Can this be done with a preprocess function in template.php? Something like:

```
if this field is not empty
  add the js to the page footer
else do nothing

```

Is there a more efficient way?

# Answer
> 2 votes
If a field within a specific content type has some content, load some javascript, if there's nothing in the field, do nothing.

```
function THEME_NAME_preprocess_page(&$variables) {
  if(isset($variables['node']) && $variables['node']->type == "CONTENT_TYPE") {
    if(!empty($variables['node']->FIELD_NAME)) {
      drupal_add_js(drupal_get_path('theme', 'THEME_NAME') . 'PATH-TO-JS.js', array('type' => 'file', 'scope' => 'footer'));

    }
  }
}

```

# Answer
> 1 votes
yes, doable at your template.php file

not the exact code but should be pretty close.

```
function mythemename_preprocess_page(&$variables) {
  if(isset($variables['node']) && $variables['node']->type == "your_content_type") {
     dpm($variables['node']); // to check debugg inside your node(devel module needed)
     if($variables['node']->yourfieldname != "") {
      drupal_add_js(drupal_get_path('theme', 'mytheme') .'/mytheme.js', 'file');
    }
  }
}

```

# Answer
> 1 votes
I'm assuming that it's a node page, you can do it in your template.php as follows:

```
function YOURTHEME_preprocess_node(&$variables) {
  $node = $variables['node'];
  $content = $variables['content'];
  if ($node->type == 'YOUR_CONTENT_TYPE') {
    if ($content['YOUR_FIELD']) {
      $js_path = drupal_get_path('theme', 'YOURTHEME') . '/yourjs.js';
      drupal_add_js($js_path, array('scope' => 'footer'));
    }
  }
}

```

---
Tags: theming, javascript
---


# Question
Title: How to add rel=author when you have "multiple authors" in one site?
I would like to use Google rel=author meta tag, but I do have several authors writing in one site. I have a Drupal 7 site. Should I add a different authorship for each author? How should I manage in that case?

I was planning to use meta tags module, (as explained here) but the only way it seems to modify all urls in order to affect different url with different meta tags. ie: /authorname/title that way, with different urls I could create different meta tags.

Could that be a normal procedure? Or there´s another way to add the author´s context? Or maybe you just should use one single author and avoid multiplying authorship altogether?

**Ps. I don´t think this is a duplicated post**, because this one refers about multiple authors, instead of just asking how to implement rel=author in D7.

# Answer
This is simple.

* Add a text field to the user profile at /admin/config/people/accounts/fields and call it Google Profile (or similar).
* Go to the Metatag configuration page and look up the token for Google Profile.
* Add this token to the Author Metatag for the relevent content type(s). The token for my setup is: \[node:author:field\_google\_profile\]
* Have every author load their Google+ profile to this field in their user profile.

\[EDIT\] It's worth noting that Google no longer uses rel=author as a ranking factor, so this discussion is now purely academic.

Regards

David
> 1 votes

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


# Question
Title: Do something after submit the form at hook_form_alter
I want to do something after I submit the node. How can I do that?

I use hook\_form\_form\_id\_alter(),but I dont know how to use callback function called after the user submit the form

```
function mymodule_form_node_form_alter(&$form,&$form_state,$form_id)
{
     if($form['#node']->type=="my_content_type")
     {
          $form['actions']['submit']['#submit'][]=my_callback_function;
     }
}

function my_callback_function($form,$form_state)
{
     //my code here!!
     //execute after the user submit the node form
     //and then redirect user to another place,after executing the code above

}

```

it doesn't work! and I don't know why? Please tell me how can I do that?

# Answer
Sorry about that! My problem is fixed.

the code belowed is the anwser

```
function mymodule_form_node_form_alter(&$form,&$form_state,$form_id)
{
     if($form['#node']->type=="my_content_type")
     {
          $form['actions']['submit']['#submit'][]='my_callback_function';
     }
}

function my_callback_function($form, &$form_state)
{
     //my code here!!
     //execute after the user submit the node form
     //and then redirect user to another place,after executing the code above

}

```

\[Edit\] For me, the callback would not fire unless form\_state was declared as &$form\_state (pass by reference)
> 7 votes

# Answer
For other that are struggling with a similar issue. You could use rules if you need to redirect after form submission. Rules can react on form events, and you can easily attach the actions you want to it.
> 0 votes

---
Tags: 7, forms
---


title: Render menu in custom form-api module

text:
# Question
Title: Render menu in custom form-api module
I've created a custom menu from the drupal admin panel, and have a custom module that uses drupal's form API. I'd like to render the custom menu in this module. Since this is using form API, I don't think it makes sense to use a template file, but I can't find any way to render a menu from the .module file itself. Not only would I like to render it, but I'd like to have control over which page region it's rendered in...How can this be done?

# Answer
> 0 votes
I am not sure if I got you right,but if you want to call a form on a menu item.Here is view for that Implement

> hook\_menu() \- to build custom page page callback - return your custom form here

Some sample code

```
function mymodulename_menu() {
  $items = array();
  $items['custom-menu'] = array(
    'title' => 'Your Custom Form',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodulename_custom_form'),
    'access callback' => TRUE,
    'access arguments' => array('access content'),
  );
  return $items;
}

function mymodulename_custom_form() {
  $form = array();
  // your custom form code goes here
  return $form;
}

```

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


# Question
Title: Slow page loads - unable to determine the cause
I am experiencing ~ 6 second page loads on every page of my Drupal 7 site. All of my scripts are loading from cache and relatively quickly except one, which will take 5.6-5.9 seconds to load (I am using FireBug to monitor):

Originally it looked to be the overlay.js javascript file, so I disabled the module. Then it was contextual.js with the exact same load time with everything else being quick. When I disabled that module it was yet another js library taking the same amount of time. This leads me to believe it has nothing to do with the libraries and is some other issue with the pages / rendering. I tried aggregating the JS and CSS, but the same issue was happening. All the queries showing up in my MySQL logs are executing relatively quickly (total of all query execution time is less than .5 seconds).

I am honestly at a loss for what to try. I suspect there is some problem here unrelated to loading any of the js files and that firebug is just reporting the delay as part of the last loaded file. This happens on both my custom pages and core drupal pages (like the modules and people screens). Is there any way to tell what is causing the long delay if it is not the javascript library?

**EDIT:** Details from the header for the script:

```
Request Headersview source
Accept  */*
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Connection  keep-alive
Cookie  Drupal.toolbar.collapsed=0; __utma=163199651.1343774579.1355785168.1378243005.1379453429.30; __utmz=163199651.1378243005.29.5.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); _ga=GA1.2.360149903.1357234390; SESSb5e5274d127f94079db0dc72d78d2200=AnQQv9Tp-NQT-b3YcVfOKzEnVSL-3cBexxbp2jY70D0; has_js=1
DNT 1
Host    example.com
If-Modified-Since   Wed, 03 Apr 2013 21:29:52 GMT
If-None-Match   "bcc-4d97b8dea7400"
Referer http://example.com/drupal/?q=peopleace/form/14172
User-Agent  Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0

Response Headers From Cache
Accept-Ranges   bytes
Content-Length  3020
Content-Type    application/javascript
Date    Wed, 02 Oct 2013 19:26:36 GMT
Etag    "bcc-4d97b8dea7400"
Last-Modified   Wed, 03 Apr 2013 21:29:52 GMT
Server  Apache

```

# Answer
> 2 votes
If a 304 is taking 5+ seconds that means you webserver (most likely Apache) is being very slow. The ONLY other thing that could be causing this is if you have Far-Future enabled with the CDN module (and that's a stretch). Aggregating should help, as this will reduce the # of requests hitting Apache.

What web server are you using? Also noticed that Clean-URLs is disabled so I would bet that the webserver needs to be configured.

---
Tags: performance
---


# Question
Title: Output block in particular region from custom module drupal 7
I have a custom module that spits out a form using the drupal form API. What I'd like to do is output a block (a custom menu) in a particular region of the page (using block regions would be the best way I'm guessing.) As of now, the block renders in the top left everytime. How can I output the menu block in a particular region of the page?

```
function client_menu(){

 $items=array();

 $items['campaign']=array(

   'title'=>'Campaign Manager',
   'description'=>'Area for clients to manage their campaigns',
   'page callback'=>'drupal_get_form',
   'page arguments'=>array('client_campaign'),
   'access arguments'=>array('access client administration'),
   'type'=>MENU_NORMAL_ITEM
 );

 return $items;

}

function client_campaign(){

$block = module_invoke('menu', 'block_view', 'menu-client-admin');
print render($block);

//a bunch of form API stuff...

}

```

# Answer
The way you are trying wouldn't work as you are creating a page by creating a menu item. Rather you should visit your block administration page at www.example.com/admin/structure/block. Here you will see the list of all your blocks and available regions in your theme to assign the blocks.

Here is a screenshot:

In the screenshot where you are seeing the select list with `none` as selected. This list will let you place your block in the available region.
> 0 votes

---
Tags: 7, blocks
---


title: test abitrary url against current page

text:
# Question
Title: test abitrary url against current page
I need to test a series of links to see if any of them match the page that is being processed. I'm having trouble finding a solution that will match **all** possible pages (a node, a view page, a page created by a module, etc) and will consider path aliases.

(It would be convenient to start with all parameters of `$test_url` stripped of the domain name and leading/following slashes.)

```
function _is_current_page($test_url){
   $test = FALSE;
   ...
   return $test;
}

```

Test case 1:

```
// current Url: domain.com/blog/year/month/article_name
// current Nid: 1234
// alias for above: domain.com/popular_article_name

_is_current_page("blog/year/month/article_name") -> true
_is_current_page("node/1234") -> true
_is_current_page("popular_article_name") -> true

```

Test case 2:

```
// current Url: domain.com/blog/calendar
// current Nid: _none_ (generated by view or module)
// alias for above: domain.com/blog-calendar

_is_current_page("blog/calendar") -> true
_is_current_page("blog-calendar") -> true

```

Help greatly appreciated : )

# Answer
> 0 votes
Excluding edge cases (querystring, hash tags, etc), this seems to work for all my test cases:

```
/**
 * Determine whether a given url matches the current page.
 *
 * @param string $test_path     A file path (no domain, no querystring, etc)
 * @return boolean
 */
function _nwr1_is_current_url($test_path){
    $test_path = trim($test_path, '/');
    $test_norm_path = drupal_lookup_path('source', $test_path);
    $this_nid = (arg(0) == 'node' && is_numeric(arg(1))) ? arg(1) : FALSE;
    $this_norm_path = ($this_nid) ? "node/$this_nid" : FALSE;
    $success = FALSE;

    // test by source (eg node/XXXX - preferred)
    if($test_norm_path && $this_norm_path && ($test_norm_path==$this_norm_path) ){
        $success = TRUE;

    // test by path
    }else if($test_path && current_path() && ($test_path==current_path()) ){
        $success = TRUE;
    }
    return $success;
}

```

---
Tags: 7, uri
---


title: Dropdown navigation for calendar view

text:
# Question
Title: Dropdown navigation for calendar view
It's not a "new" issue, but I'd like to implement a year + month dropdown selector to navigate a standard calendar view's display, as this particular calendar shows historical entries spanning many years, all of which need to be directly accessible.

I understand it's possible to specify an argument via URL to control the calendar view's current display through its contextual filter. However, I don't know how to supply this argument via a dropdown, either in the block itself or another (similar to an exposed filter), in a way that would function properly in all cases.

Working without a solution, I created my own views style plugin, added an exposed filter, and am now going to look for a way to display the easily filtered-by-month results in a custom calendar implementation through my code.

Hopefully there's a way to make use of the existing calendar module via "inspired" filtering, instead of my custom plugin route?

Any guidance would be appreciated.

# Answer
I had the same requirement a few time ago.You are right the key is date pager in url to navigate through date/month/year

here is a workaround I did,might be helpfull in your case too.

As in brief I created custom form with field as month and year.Submission of the form navigates passing the selected month and year in url using drupal\_goto() and we are calling this form in views header.
> 0 votes

---
Tags: views, datetime
---


# Question
Title: Using maintenance.css to maintenance-page.tpl.php
I followed the link below so I can customize Maintenance Mode.

https://drupal.org/node/195435

How can I customize Maintenance Mode css? I tried to link the style sheet: maintenance.css to `maintenance-page.tpl.php` but I am getting nothing(no error) Used this site for reference:https://drupal.org/node/1171800

Here is my code for `maintenance-page.tpl.php` I am using to link stylesheet:

```
<?php
/**
 * @file
 * Returns the HTML for a single Drupal page.
 *
 * Complete documentation for this file is available online.
 * @see https://drupal.org/node/1728148
 */
?>
<head> <link rel="stylesheet" href="/sites/all/themes/RAW_Gallery/css/maintenance.css" /> test</head>
<div id="page">

  <header class="header" id="header" role="banner">

    <?php if ($logo): ?>
      <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home" class="header__logo" id="logo"><img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" class="header__logo-image" /></a>
    <?php endif; ?>

    <?php if ($site_name || $site_slogan): ?>
      <div class="header__name-and-slogan" id="name-and-slogan">
        <?php if ($site_name): ?>
          <h1 class="header__site-name" id="site-name">
            <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" class="header__site-link" rel="home"><span><?php print $site_name; ?></span></a>
          </h1>
        <?php endif; ?>

        <?php if ($site_slogan): ?>
          <div class="header__site-slogan" id="site-slogan"><?php print $site_slogan; ?></div>
        <?php endif; ?>
      </div>
    <?php endif; ?>

    <?php if ($secondary_menu): ?>
      <nav class="header__secondary-menu" id="secondary-menu" role="navigation">
        <?php print theme('links__system_secondary_menu', array(
          'links' => $secondary_menu,
          'attributes' => array(
            'class' => array('links', 'inline', 'clearfix'),
          ),
          'heading' => array(
            'text' => $secondary_menu_heading,
            'level' => 'h2',
            'class' => array('element-invisible'),
          ),
        )); ?>
      </nav>
    <?php endif; ?>

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

  </header>

  <div id="main">

    <div id="content" class="column" role="main">
      <?php print render($page['highlighted']); ?>
      <?php print $breadcrumb; ?>
      <a id="main-content"></a>
      <?php print render($title_prefix); ?>
      <?php if ($title): ?>
        <h1 class="page__title title" id="page-title"><?php print $title; ?></h1>
      <?php endif; ?>
      <?php print render($title_suffix); ?>
      <?php print $messages; ?>
      <?php print render($tabs); ?>
      <?php print render($page['help']); ?>

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

    <div id="navigation">

      <?php if ($main_menu): ?>
        <nav id="main-menu" role="navigation" tabindex="-1">
          <?php
          // This code snippet is hard to modify. We recommend turning off the
          // "Main menu" on your sub-theme's settings form, deleting this PHP
          // code block, and, instead, using the "Menu block" module.
          // @see https://drupal.org/project/menu_block
          print theme('links__system_main_menu', array(
            'links' => $main_menu,
            'attributes' => array(
              'class' => array('links', 'inline', 'clearfix'),
            ),
            'heading' => array(
              'text' => t('Main menu'),
              'level' => 'h2',
              'class' => array('element-invisible'),
            ),
          )); ?>
        </nav>
      <?php endif; ?>

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

    </div>

    <?php
      // Render the sidebars to see if there's anything in them.
      $sidebar_first  = render($page['sidebar_first']);
      $sidebar_second = render($page['sidebar_second']);
    ?>

    <?php if ($sidebar_first || $sidebar_second): ?>
      <aside class="sidebars">
        <?php print $sidebar_first; ?>
        <?php print $sidebar_second; ?>
      </aside>
    <?php endif; ?>

  </div>

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

</div>

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

```

I know the custom Maintenance Mode is correct because I type "hello" between in `maintenance-page.tpl.php`, login to my drupal theme and not see "hello."

So why can't I see maintenance.css ?

# Answer
> 1 votes
I created a maintenance-page.tpl.php and copied in your html from above.

I changed the href in the `<link>` tag to my main theme css, so from /sites/all/themes/RAW\_Gallery/css/maintenance.css to /sites/all/themes/THEME/css/common.css. I then cleared the cache and everything worked.

Could it be the path to your CSS file is wrong? Or, perhaps it was not uploaded to the server, or perhaps you didn't clear the cache?

# Answer
> 0 votes
Add the CSS file using drupal\_add\_css() as below:

```
<?php drupal_add_css(drupal_get_path('theme', 'RAW_Gallery') . '/css/maintenance.css'); ?>

```

---
Tags: theming, maintenance-mode
---


# Question
Title: Does drush have built-in variables or macros?
Does `drush` have built-in or predefined variables or macros?

An example would be like the base directory of the Drupal installation, database name, passwords etc? Something like the values displayed in `drush status`

# Answer
If you source the file examples/example.bashrc from your ~/.bashrc file, then you can do useful things like `cd %root` or `cd @site:%root`. Without sourcing that file, you can use `cd $(drush dd %root)`. If you want to go to a module or theme directory, `cd $(drush dd %devel)` also works. Using the %path aliases without qualifying them with a @site alias does, of course, require that your cwd be inside some Drupal site (or $options\['root'\] must be set in some drushrc.php file).
> 1 votes

---
Tags: drush
---


# Question
Title: Remove child elements from Taxonomy List Exposed Filters
I have a view with (Taxonomy Reference Field) as Exposed Filter, The vocabulary contain parent terms and some child terms, I want to see the first level terms only and remove any children if any.

Currently It look like this

I want to remove the Keyboard Type 1, Type 2 and so on.

I was thinking of using a `hook_form_alter`, but not sure about the exact usage to remove any child term.

# Answer
Here is my solution which I think is quite a bit simpler. Simply remove the entries from the form if they start with a '-'. Note that you must have the 'Show hierarchy in dropdown' option selected for the children to begin with a '-' hyphen.

```
/**
* Implements hook_form_alter().
*/
function mymodule_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {

  if($form['#id'] == 'views-exposed-form-[your-view-here]') {

    foreach ($form['tid']['#options'] as $term_key => $term) {

      // Check if this isn't the 'ANY' option
      if($term_key !== 'All') {
        // Check if this is a child by looking for '-' as first char in string
        $term_value = reset($term->option);
        if($term_value[0] == '-') {
          unset($form['tid']['#options'][$term_key]);
        }
      }

    }

  }

}

```
> 3 votes

# Answer
A bit late answer but you can use **hook\_form\_alter** as you stated.

```
$localities = get_all_localities($term_id);
$localities_tids = array();

foreach ($localities as $tid => $name){
    $localities_tids[] = $tid;
}

//alter the available options in the exposed filters
foreach ($form['term_node_tid_depth_i18n']['#options'] as $tid => $term){
    if ( !in_array($tid, $localities_tids) ){
        if ( $tid != 0 && !empty($tid) ) {
            unset($form['term_node_tid_depth_i18n']['#options'][$tid]);
        }
    }
}

```

In this example I get all the localities (child elements) with parent **$term\_id**, after that just compare the new tid's list with the id present on the form element and remove what u don't need using **unset()**

Will also leave you my example to get the child localities from the region parent id ($term\_id).

```
function get_all_localities($regiao_selecionada) {
    $lang_code = get_site_lang();
    $loc_list = array();

    if ( !empty( $regiao_selecionada ) && $regiao_selecionada != '0' ) {
        $locs = db_query("
            SELECT td.tid,
            COALESCE((SELECT lt.translation FROM locales_source ls, locales_target lt WHERE ls.lid = lt.lid AND ls.context LIKE CONCAT('term:',td.tid,':name') AND lt.language LIKE '$lang_code' LIMIT 1), td.name) as 'name', th.*
            FROM taxonomy_term_data td, taxonomy_term_hierarchy th
            WHERE th.tid = td.tid AND td.vid = 5 AND th.parent = $regiao_selecionada AND td.name <> 'Foreign' AND td.name <> 'Nenhuma' AND td.tid NOT IN (select tid from taxonomy_term_hierarchy where parent IN (select tid from taxonomy_term_data td where td.name = 'Foreign' OR td.name = 'Nenhuma'))
            ORDER BY td.name ASC
        ");
    } else {
        $locs = db_query("
            SELECT td.tid,
            COALESCE((SELECT lt.translation FROM locales_source ls, locales_target lt WHERE ls.lid = lt.lid AND ls.context LIKE CONCAT('term:',td.tid,':name') AND lt.language LIKE '$lang_code' LIMIT 1), td.name) as 'name', th.*
            FROM taxonomy_term_data td, taxonomy_term_hierarchy th
            WHERE th.tid = td.tid AND td.vid = 5 AND th.parent <> 0 AND td.name <> 'Foreign' AND td.name <> 'Nenhuma' AND td.tid NOT IN (select tid from taxonomy_term_hierarchy where parent IN (select tid from taxonomy_term_data td where td.name = 'Foreign' OR td.name = 'Nenhuma'))
            ORDER BY td.name ASC
        ");

    }

    foreach ($locs as $id => $loc) {
        $loc_list[$loc->tid] = $loc->name;
    }

    return $loc_list;
}

```

Hope this can help you out.
> 0 votes

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


# Question
Title: Clear (not reset) Views Exposed Filter Values
I know i'm looking at this wrong and am running into a wall over and over again on this.

I have a view with an exposed filter in a block. I am looking to clear / reset the values in the block without reseting the view, so the default reset button in views doesn't cut it. Any Opinions?

# Answer
I'm pretty sure that the better exposed filters module has an option for a reset button, but it may reset the view too.

You could also add some javascript that listens for the click event on the button and resets the fields you want.
> 2 votes

# Answer
Create a custom form , submit handler will execute some jquery codes to reset all form fields This link can be helpful for building such a form.

and in your views header add a php field and simply call the custom form with(mymodule\_clear\_filters is the name of function returning the custom form).

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

```
> 0 votes

---
Tags: 7, views
---


title: Save commerce price component

text:
# Question
Title: Save commerce price component
I'm building simple VAT-module for commerce. The only thing it should do is to add a price component to the order total. I use a rules action to add the component and save it. The action it self works fine, but the component won't be saved or displayed. `hook_commerce_price_component_type_info()` is implemented and works. So what's wrong?

The code of the rule:

```
$order_total = $order->commerce_order_total['und'][0];
$tax_amount = round($order_total['amount'] / 1.19 * 0.19);
$tax_component = array (
                'amount' => $tax_amount,
                'currency_code' => 'EUR',
                'data' => array ()
                );
$order_total = commerce_price_component_add($order_total, 'tax', $tax_component, true ,  false);
$order->commerce_order_total['und'][0]['data'] = $order_total;

```

`debug()` returns this for the order total:

```
'commerce_order_total' =>
  array (
   'und' =>
    array (
      0 =>
      array (
        'amount' => 32600,
        'currency_code' => 'EUR',
        'data' =>
        array (
          'components' =>
          array (
            0 =>
            array (
              'name' => 'base_price',
              'price' =>
              array (
                'amount' => 30000,
                'currency_code' => 'EUR',
                'data' =>
                array (
                ),
              ),
              'included' => true,
            ),
            1 =>
            array (
              'name' => 'flat_rate_versand_6_5',
              'price' =>
              array (
                'amount' => 2600,
                'currency_code' => 'EUR',
                'data' =>
                array (
                ),
              ),
              'included' => true,
            ),
            2 =>
            array (
              'name' => 'tax',
              'price' =>
              array (
                'amount' => 5205,
                'currency_code' => 'EUR',
                'data' =>
                array (
                ),
              ),
              'included' => true,
            ),
          ),
        ),
      ),
    ),
  ),

```

# Answer
> 0 votes
Have a look at the commerce\_tax module, part of the Commerce suite.

It provides a VAT tax type with the associated price component information.

You can use it for code examples, or as the module itself to provide that functionality.

---
Tags: commerce, rules
---


title: Managing groups of users

text:
# Question
Title: Managing groups of users
Please help find the modules that allows me to create the following scenario

1. Admin can create a User-A a. User-A will receive an activation email
2. After activation User-A will be able to: a. create User-B with another permissions, which will also recieve an activation email b. create groups of Users-B c. assign Users-B to the selected group d. managing and see only Users-B which he created e. assign content to the selected group
3. After activation User-B will have access to the content of the group to which he is assigned.

I will be grateful for an any help.

# Answer
You want to use Organic Groups, and if needed, Role Delegation. I think you can get by with just Organic Groups maybe ... Drupal core can send out notifications of new accounts by itself upon account creation.

Orangic Groups is a contrib module:

> Enable users to create and manage their own 'groups'. Each group can have subscribers, and maintains a group home page where subscribers communicate amongst themselves.
>
> They do so by posting the usual node types: blog, story, page, etc. A block is shown on the group home page which facilitates these posts. The block also provides summary information about the group.
>
> Groups may be selective or not. Selective groups require approval in order to become a member, or even invitation -only groups. There are lots of preferences to configure groups as you need.

A synopsis from Role Delegation project page is:

> This module allows site administrators to grant some roles the authority to assign selected roles to users, without them needing the administer permissions permission.
>
> For each role, Role Delegation provides a new assign ROLE role permission to allow the assignment of that role.

Fully understanding and leveraging these modules to fit your workflow, business logic, etc is a task I leave up to you. Your question is far from simple.
> 1 votes

---
Tags: users
---


title: Incorrect paths for admin and others

text:
# Question
Title: Incorrect paths for admin and others
I have to comment out the .htaccess file to login, but then the paths to my admin and other virtual directories won't work?

```
#
# Apache/PHP/Drupal settings:
#

# Protect files and directories from prying eyes.
<FilesMatch "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)$|^(\..*|Entries.*|Repository|Root|Tag|Template)$">
  Order allow,deny
</FilesMatch>

# Don't show directory listings for URLs which map to a directory.
Options -Indexes

# Follow symbolic links in this directory.
Options +FollowSymLinks

# Make Drupal handle any 404 errors.
ErrorDocument 404 /index.php

# Set the default handler.
DirectoryIndex index.php index.html index.htm

# Override PHP settings that cannot be changed at runtime. See
# sites/default/default.settings.php and drupal_environment_initialize() in
# includes/bootstrap.inc for settings that can be changed at runtime.

# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
  php_flag magic_quotes_gpc                 off
  php_flag magic_quotes_sybase              off
  php_flag register_globals                 off
  php_flag session.auto_start               off
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_flag mbstring.encoding_translation    off
</IfModule>

# Requires mod_expires to be enabled.
<IfModule mod_expires.c>
  # Enable expirations.
  ExpiresActive On

  # Cache all files for 2 weeks after access (A).
  ExpiresDefault A1209600

  <FilesMatch \.php$>
    # Do not allow PHP scripts to be cached unless they explicitly send cache
    # headers themselves. Otherwise all scripts would have to overwrite the
    # headers set by mod_expires if they want another caching behavior. This may
    # fail if an error occurs early in the bootstrap process, and it may cause
    # problems if a non-Drupal PHP file is installed in a subdirectory.
    ExpiresActive Off
  </FilesMatch>
</IfModule>

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on

  # Block access to "hidden" directories whose names begin with a period. This
  # includes directories used by version control systems such as Subversion or
  # Git to store control files. Files whose names begin with a period, as well
  # as the control files used by CVS, are protected by the FilesMatch directive
  # above.
  #
  # NOTE: This only works when mod_rewrite is loaded. Without mod_rewrite, it is
  # not possible to block access to entire directories from .htaccess, because
  # <DirectoryMatch> is not allowed here.
  #
  # If you do not have mod_rewrite installed, you should remove these
  # directories from your webroot or otherwise protect them from being
  # downloaded.
  RewriteRule "(^|/)\." - [F]

  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  RewriteBase /cdf/
  #
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  # RewriteBase /

  # Pass all requests not referring directly to files in the filesystem to
  # index.php. Clean URLs are handled in drupal_environment_initialize().
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

  # Rules to correctly serve gzip compressed CSS and JS files.
  # Requires both mod_rewrite and mod_headers to be enabled.
  <IfModule mod_headers.c>
    # Serve gzip compressed CSS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.css $1\.css\.gz [QSA]

    # Serve gzip compressed JS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.js $1\.js\.gz [QSA]

    # Serve correct content types, and prevent mod_deflate double gzip.
    RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
    RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]

    <FilesMatch "(\.js\.gz|\.css\.gz)$">
      # Serve correct encoding type.
      Header set Content-Encoding gzip
      # Force proxies to cache gzipped & non-gzipped css/js files separately.
      Header append Vary Accept-Encoding
    </FilesMatch>
  </IfModule>
</IfModule>

```

# Answer
> 0 votes
You will only need `RewriteBase /cdf/` if your Drupal install is in a subfolder, else can comment that out, or use /

e.g

```
  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  # RewriteBase /cdf/
  #
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  RewriteBase /

```

---
Tags: 7
---


# Question
Title: View/Page with form to insert data and display it
I need to create a View/Page or whatever to display a form. This form only could be viewed by registered users, and on it, the user could insert different data (text, images, etc) and then this data need to be displayed on another view/page/section of the web.

I think this is very simple to do it with Drupal, but I'm a little lost, and I need a guide or some advice to go ahead.

# Answer
> 1 votes
Sounds like you need to create a content type and add some fields to it.

After that configure permissions so authenticated users can create that content.

The follow up display of that content can probably most easily be done with the Views module.

---
Tags: views
---


# Question
Title: How to grant user User Points equal to certain field's value / calculated value?
I've a content type 'Content' with the field 'Value' (an integer). Every time a **Content has been published**, I'd like to **grant the Content's author some User Points, equal to the value in the 'Value' field**.

I tried solving the first part of my problem with the Rules module like this:

```
*Event: A node has been published

*Conditions: Content is of type 'Content'

*Actions: Grant points to a user: ...

```

However, it's impossible to pick `node:field-value` in the Points section. I also tried:

```
*Event: A node has been published

*Conditions: Content is of type 'Content'

*Actions:

 - Calculate a value: `[node:field-value]` "+" 0. (Variable name = result)

 - Grant points to a user: ...

```

But then, the variable 'result' is not available. How can I solve this issue?

# Answer
I finally found a solution! I completed the second scenario (the amount of User Points is calculated) successfuly! Apparently, the User Points module didn't know that the calculation was an integer. Therefore, I had to add an extra action **Convert data type**: *Target type: Integer, Value to convert: \[result\], Rounding behavior: Always down*. I called it 'total' and granted the user this amount of User Points.
> 2 votes

# Answer
Same you can achieve using the **Userpoint module**: userpoint module provides an API for users to gain or lose points for performing certain actions on your site.

The User Points and userpoints\_basic modules provide the ability for users to gain points when they perform certain actions, such as:

* posting a node (different points can be awarded for different node types, e.g. page, story, forum, image, ...etc.)
* posting a comment
* moderating a comment

When the nodes or comments are deleted the previously gained points are subtracted. If a node or comment author is changed the points are transferred respectively.

The number of points for each of the above actions is configurable by the site administrator and a transaction log is created for each point (similar to a bank account.

Uerpoints module doc: https://drupal.org/documentation/modules/userpoints

User point rules integration doc: https://drupal.org/node/873386

Link for configuring the `rules` as per your requirement: https://drupal.org/node/874390
> 0 votes

---
Tags: 7, rules, userpoints
---


# Question
Title: How to limit the amount of User Points users get?
I've a content type 'Content' with the field 'Value' (an integer) and a flag called 'Publish Content and grant points to user'. Every time a Content is flagged with this flag, I'd like to grant the Content's author some User Points, equal to the value in the 'Value' field, but with a maximum of 5.

I've got a question about the 'maximum 5' condition. I made 2 seperate rules with an extra condition 'Data comparison': one with \[flagged-node:field-value is lower than 6\] and another with \[flagged-node:field-value is greater than 5\]. (Note that I can choose "field-value" here!) Isn't it possible to do this in just 1 single rule?

**Note:** I also have a problem with the 'Value' field. See: Grant user User Points equal to value of certain field.

# Answer
I found a solution for my question; maybe it can help others too. I actually created a 'correction' Rule that's activated after a user was awarded userpoints and a 'Content' node was flagged with 'Publish Content and grant points to user'. This is how I set up the Rule:

**EVENT**

* User was awarded userpoints
* A node has been flagged, under 'Publish Content and grant points to user'

Then, I checked whether the amount of points is higher than 5.

**CONDITIONS**

* Data comparison: `[userpoints-transaction:points]` is greater than `5`

Finally, I calculated the difference between the added userpoints and 5 and substracted this value from the user's userpoints.

**ACTIONS**

* Calculate a value: `[userpoints-transaction:points]` "-" `5` (variable name: difference)
* Calculate a value: `[difference]` "\*" `-1` (variable name: substract)
* Grant points to a user: grant `[userpoints-transaction:user]` `substract` points

I had to insert the second calculation, because otherwise, I couldn't substract the 'difference' from the user's userpoints.
> 0 votes

---
Tags: 7, rules, flags, userpoints
---


# Question
Title: How to associate programatically the translation of new term to the original existing term?
I've terms which share the same id in stored in field and I'd like to associate translation between them, so they're grouped on the same page at /taxonomy/term/%/translate

So I've existing original English term, then I'm creating manually term with different language, so I'm expecting this term to associate with the original one.

Not sure which hook would be the best, or it doesn't matter:

* hook\_taxonomy\_term\_presave
* hook\_taxonomy\_term\_insert

So in example I've:

```
/**
 * Implements hook_taxonomy_term_presave().
 */
function foo_taxonomy_term_presave($term) {
  $bundle = 'countries'; // Example bundle name
  $vid = ($voc = taxonomy_vocabulary_machine_name_load($bundle)) ? $voc->vid : NULL;
  if ($term->vid == $vid && module_exists('i18n_string') && $term->language <> 'en') {

    if ($shared_id = $term->field_shared_id[key($term->field_shared_id)][0]['value']) {

      // Find term which points to the same country, but in English
      $query = new EntityFieldQuery();
      $org_term_res = $query
        ->entityCondition('entity_type', 'taxonomy_term')
        ->entityCondition('bundle', $bundle)
        ->propertyCondition('vid', $vid)
        ->fieldCondition('field_shared_id', 'value', $shared_id, '=')
        ->propertyCondition('language', 'en')
        ->execute();

      // Load term in the main language
      if ($org_term = taxonomy_term_load(reset(reset($org_term_res))->tid)) {
        // If original term is loaded, continue translation
        $langcode = $term->language;
        $key = i18n_object_info('taxonomy_term', 'key');

        $result_translation = i18n_string_translation_update(
          array('taxonomy', 'term', $term->{$key}, 'name'), // Array or string concatenated with ':' that contains textgroup and string context where to store source and translation.
          $term->name,      // Translation string for this language code.
          $langcode,        // The language code to translate to a language other than what is used to display the page.
          $org_term->name   // Optional source string, just in case it needs to be created.
        );
        watchdog('foo', "Added !source translation: !translated in !lang (key: !key)", array('!source' => $org_term->name, '!translated' => $term->name, '!lang' => $term->language, '!key' => $term->{$key}), WATCHDOG_NOTICE);

      } // end: if

      i18n_string_object_update('taxonomy_term', $term); // not sure if it's needed for something

    } // end: if
  } // end: if

}

```

So the main translate part is in `i18n_string_translation_update()`. But it simply doesn't work as expected. The $result\_translation returns the right data, but the association is not visible in UI at taxonomy/term/%/translate

There is no much documentation about it apart of Using the i18n API from other modules

So I'm using the right function in the right way?

Related:

how to get the translated taxonomy term programmatically?

# Answer
Here is the function which takes $term as current term and $org\_term which is original/source term.

```
<?php
/**
 * Custom function to add term translations.
 */
function foo_add_term_translation($term, $org_term) {
  if ($org_term->i18n_tsid) {
    // Already part of a set, grab that set.
    $i18n_tsid = $org_term->i18n_tsid;
    $translation_set = i18n_translation_set_load($org_term->i18n_tsid);
    $translation_set->add_item($term);
    $translation_set->save_translations();
    watchdog('foo', "Added !source translation: !translated in !lang.", array('!source' => $org_term->name, '!translated' => $term->name, '!lang' => $term->language), WATCHDOG_NOTICE);
  }
  else {
    // We have no translation source nid, this could be a new set.
  }
}

```

More code examples you'll find in i18n\_translation module.

This could be called either during insert or update as below:

```
/**
 * Implements hook_taxonomy_term_insert().
 */
function foo_taxonomy_term_insert($term) {
  foo_add_term_translation_wrapper($term);
}

/**
 * Implements hook_taxonomy_term_update().
 */
function foo_taxonomy_term_update($term) {
  foo_add_term_translation_wrapper($term);
}

```

Here is helpful wrapper function with example to load the original term where two terms share the same field value:

```
/**
 * Custom wrapper to update term translation.
 */
function foo_add_term_translation_wrapper($term) {

  $bundle = 'countries'; // Example bundle name
  $vid = ($voc = taxonomy_vocabulary_machine_name_load($bundle)) ? $voc->vid : NULL;
  if ($term->vid == $vid && module_exists('i18n_taxonomy') && $term->language <> 'en' && empty($term->translation_set)) {

    if ($shared_id = $term->field_shared_id[key($term->field_shared_id)][0]['value']) {

      // Find term which points to the same country, but in English
      $query = new EntityFieldQuery();
      $org_term_res = $query
        ->entityCondition('entity_type', 'taxonomy_term')
        ->entityCondition('bundle', $bundle)
        ->propertyCondition('vid', $vid)
        ->fieldCondition('field_shared_id', 'value', $shared_id, '=')
        ->propertyCondition('language', 'en')
        ->execute();

      // Load term in the main language
      if ($org_term = taxonomy_term_load(reset(reset($org_term_res))->tid)) {
        foo_add_term_translation($term, $org_term);
      } // end: if

    } // end: if
  } // end: if

}

```

See also:

https://drupal.org/node/2102933
> 0 votes

---
Tags: taxonomy-terms, i18n-l10n
---


# Question
Title: Which of the following is better in terms of performance and speed?
1. I am creating a view and then using views\_get\_view\_result() function to get the query and print a csv file or
2. Creating a query using db\_select and then using it to print the csv. Which of the above would give me quicker results

# Answer
> 0 votes
views\_get\_view\_result() will be slower as compared to the `db_query` as the `views_get_view_result()` calls all the views api functions to get the result but it is the recommended method to get result.

However if your query result changes rarely than you may cache the result and it would be better in terms of performance, Views already has built-in Views has caching system and can be configured in your view, or otherwise you can cache the `db_query` result as well.

References of caching:

# Answer
> 3 votes
db\_select would give quicker results as it doesn't invoke the entire Views API to get that database result set. However, Views will give you the benefit of a highly configurable user interface to adjust your query which may save on development time.

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


title: Only front page shown?

text:
# Question
Title: Only front page shown?
I designed my site with Acquia Dev Desktop on my PC and now it's finished and I uploaded folder of my site to public\_html folder in cpanel. I export my database on my computer and import it to my host. but now when I enter my url in address bar of a browser only front page shown, for example when I click on other content of my site it gos to a white page and nothing will loaded. what should I do? pleas help me. which command of setting.php file should change after importing database on server? this is my site: http://www.setareonline.ir

# Answer
> 1 votes
A possible reason can be missing .htaccess file in the drupal root directory or if it is present than possibly your web server is not able to read it. For example web server apache reads .htaccess file with help of mod\_rewrite module or even if mod\_rewrite module is installed on Apache , Apache server do not have Allow override all permissions. One of the way to check issue is related to .htaccess or not can be accessing internal pages with query parameter, for example www.yoursite.com?q=user and see if it works! then chances are issues with .htaccess file.just check you have shared the URL, for me reason looks like to be .htaccess file check your drupal install is having .htaccess file or not if so ask your web master to let your web server to read your .htacccess

# Answer
> 0 votes
You should go through the list WSOD (White screen of death) WSOD Drupal

Put this into your index.php file

```
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

```

it should be able to tell you whats wrong.

In your case, I can see that the URLS are not following. So you should look into your .htaccess file and check if the URLS are the same. Check out `RewriteBase /`

---
Tags: configuration
---


# Question
Title: How to make the autocomplete term widget (tagging) case-sensitive?
I notice that although the Autocomplete term widget (tagging) happily autocompletes terms with their right letter case, after saving the terms are changed to lower case. E.g. I have two tags "Drupal" and "drupal" and although I autocomplete "Drupal" and save the node, what gets saved is "drupal".

Is there a way to force case-sensitivity for this widget -- or vocabulary?

# Answer
You are looking for Termcase module, It will do that.

> It prevents users to use different cases on terms. With termcase you can make sure all terms in a vocabulary begin with an uppercase or that they are all formatted to lowercase.

There are five options available:

* No formatting
* Ucfirst: convert the first character of the term to uppercase
* Lowercase: convert all characters of the term to lowercase
* Uppercase: convert all characters of the term to uppercase
* Propercase: convert the first character of earch word to uppercase

You can define these settings per vocabulary. The module even enables you to **update** all existing terms in a vocabulary and select whether or not you want to convert synonyms as well.
> 1 votes

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


# Question
Title: drupal 7, paths and urls are not working properly
I'm developing a website on my localhost. I have a problem with urls.

for a url like this

```
http://localhost:81/my_website/library

```

I should output image src this way :

```
<img src="<?php print $directory; ?>/image/header/headerR.png"/>

```

but when the above url is changed to this

```
http://localhost:81/my_website/library/

```

I should output image src this way :

```
<img src="../<?php print $directory; ?>/image/header/headerR.png"/>

```

I mean it should refer to the parent. my website has also contextual filter which must be inserted after **library/** .is there any general solution for handling such thing?

# Answer
> 3 votes
Use the global variables for resolving the issue of path of files as below:

1. Use base\_path if your fine with domain name not to be included: It will return path respect to the drupal root.
Eg: "/" for drupal root(`http://localhost:81/my_website`), and
"/images/header" for `http://localhost:81/my_website/image/header/header`

Example:

> ```
> /*Assuming image path: http://localhost:81/my_website/image/header/headerR.png*/
> global $base_path; /* will return "/" for http://localhost:81/my_website*/
> $image_path = $base_path . 'image/header/headerR.png';
>
> ```

**Note**: Don't use trailing slash `/` for adding path of files with **$base\_path** as it adds a "/" to the beginning and end of the returned path.
2. Use base\_url if you want to get the full path: It will return base URL of the Drupal installation.

Example:

> ```
> /*Assuming image path: http://localhost:81/my_website/image/header/headerR.png*/
> global $base_url; /* will return http://localhost:81/my_website in you case*/
> $image_path = $base_url . '/image/header/headerR.png';
>
> ```

---
Tags: uri
---


# Question
Title: Simplenews send mail when specific content is created
Required: Simplenews module in drupal7.

I have a content type student on my site. The student can be from department: Engineering, Management,....

What I want to do is whenever I add a student who is from engineering, a mail is sent automatically to subscribed users. I read about the simplenews module and already tried to send some mails which were received successfully.

What I can't do and am not finding information about is how to 'link' the term engineering in department to newsletter and then send a mail.

# Answer
> 1 votes
One reasonably straightforward way of doing that is with the Rules module.

Assuming there's only a few recipients, not hundreds...

You can use a *"Send email"* action to conditionally send an email to specified recipients.

Here's some example Rules that can be imported.

**1. Basic "Send email" rule**

```
{ "rules_send_email_notification_engineering" : {
    "LABEL" : "Send email notification (engineering)",
    "PLUGIN" : "reaction rule",
    "TAGS" : [ "Mail" ],
    "REQUIRES" : [ "rules" ],
    "ON" : [ "node_insert" ],
    "IF" : [
      { "AND" : [
          { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_department" } },
          { "data_is" : { "data" : [ "node:field-department" ], "value" : "engineering" } }
        ]
      }
    ],
    "DO" : [
      { "mail" : {
          "to" : "example@example.com,example2@example.com",
          "subject" : "New student record created [engineering]",
          "message" : "Sample message"
        }
      }
    ]
  }
}

```

You could also use the *"Send mail to all users of a role"* action in Rules to send to all users assigned to the *"Engineering department"* role, if such a role existed.

Update:

**2. Create and send a simplenews newsletter with Rules**

Here's how to create and send a newsletter with Rules:

```
{ "rules_send_email_notification_engineering" : {
    "LABEL" : "Send email notification (engineering)",
    "PLUGIN" : "reaction rule",
    "TAGS" : [ "Mail" ],
    "REQUIRES" : [ "rules", "simplenews_rules" ],
    "ON" : [ "node_insert" ],
    "IF" : [
      { "AND" : [
          { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_department" } },
          { "data_is" : { "data" : [ "node:field-department" ], "value" : "engineering" } }
        ]
      }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "node",
            "param_type" : "simplenews",
            "param_title" : "New engineering student record created.",
            "param_author" : [ "site:current-user" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : { "data" : [ "entity-created:status" ], "value" : "1" } },
      { "entity_save" : { "data" : [ "entity-created" ] } },
      { "simplenews_rules_action_send" : { "node" : [ "entity-created" ] } }
    ]
  }
}

```

You can set other field values on the newsletter node as required with the `data_set` action.

---
Tags: emails
---