# Question
Title: Get image width for a styled image in module
In hook\_node\_load I need to get the width and height of a styled image, for a given fid.

The image style has only height effect and the width is scaled and calculated by Drupal, so using image\_styles() is of no use.

My code so far is like this:

```
  $field_image = field_get_items('node', $node, 'field_image', LANGUAGE_NONE);
  $img_uri = file_load($field_image[0]['fid']);
  $img_url = image_style_url('mystyle', $img_uri->uri);
  $img_info = image_get_info ($img_url);

```

$img\_info gives me FALSE instead of the info. How to get the width?

# Answer
> 1 votes
according to documentation, you just need `image_style_path` instead of `image_style_url`

and finally

```
 $field_image = field_get_items('node', $node, 'field_image', LANGUAGE_NONE);
 $img_uri = file_load($field_image[0]['fid']);
 $img_url = image_style_path('mystyle', $img_uri->uri);
$img_info = image_get_info ($img_url);

```

---
Tags: 7, media
---


# Question
Title: How to add multiple value using autocomplete widget
We create a input field using user interface for add multiple languages .How i can add multiple language using comma separate so after comma they will populate other language.

# Answer
> -1 votes
You need to explode the string inside the `autocomplete` function.

```
function autocomplete_callback($string) {
  $explode_str = explode(',', $string);
  $last_str = drupal_strtolower(array_pop($explode_str));
  // use $last_str in the query
  $explode_str[] = $result;
  return implode($explode_str);
}

```

---
Tags: ajax
---


# Question
Title: Implement a pager for my table and navigate into it in ajax
I'm looking for a way to implement a pager for my table knowing that **I don't use a query** and **I can't use** that kind of solutions:

```
$query = db_select('node', 'n')
    ->condition('status', 1)
    ->extend('PagerDefault')
    ->limit(30)
    ->fields('n', array('nid'));
$results = $query->execute();
pager_default_initialize($total, $limit, $element = 0);

```

I searched the internet, found a clue and tried:

```
$limit = 25;
$page = pager_default_initialize(count($cells), $limit, 0);
$offset = $limit * $page;

$output = theme('table', array(
  'header'     => array('Nom', 'Prénom', 'Organisme', 'Catégories', 'Contextes', 'Fonctions', 'Voir', 'Modifier', 'Supprimer'),
  'rows'       => array_slice($cells, $offset, $limit),
  'attributes' => array('class' => array('table-bordered', 'table-hover', 'history-results')),
));
$output .= theme('pager', array('quantity', count($cells)));

```

The pager is displayed under my table, has the right number of pages, but if I want to navigate, the page is refreshed and my table is gone (that's normal, because of my custom code).

So, is there a way to navigate in the table in ajax **instead of refreshing** the page and passing a page parameter in the url?

I hope so, because I don't see anything else to do in my specific case :-)

# Answer
> 1 votes
You need the Ajax Framework of Drupal. An example that meets your need is here.

An overview of code :

Create a menu for your ajax call :

```
function MY_CUSTOM_MODULE_menu() {
  $items['my-custom-path/ajax'] = array(
    'title' => 'My custom ajax callback',
    'page callback' => 'MY_CUSTOM_MODULE_ajax_callback',
    'page arguments' => array('page number')
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

// Calback
function MY_CUSTOM_MODULE_ajax_callback($page_number) {

  $ajax_commands = array();

  // Create an $html = "do whatever you want".
  $ajax_commands[] = ajax_command_after('#table_id', $html); // html will be replaced in #table_id

  // $pager_html how you want
  $ajax_commands[] = ajax_command_after('#pager_id', $pager_html); // html will be replaced in #table_id

  ajax_deliver(array('#type' => 'ajax', '#commands' => $ajax_commands));
}

```

---
Tags: 7, ajax, paging
---


# Question
Title: send user registeration mail in html format
I want to send any email of my site in HTML format, I install `smtp , mimemail and mailsystem` modules, and `smpt` configured correctly and test it(I check `Allow to send e-mails formated as Html`), also this is a snapshot of Mailsystem settings ,also in Mimemail settings I set `E-mail format` in **FULL HTML** format,also I create `mimemail-message.tpl.php` in theme folder (and cleared cache).

it seems everything is ok,but when a user register in site, email not send in html format and is only plain text.

**How can I send any user email (registertion,canceling,approved,suspending ,...) in HTML format?**

# Answer
> 1 votes
I recommend using PHPMailer module. https://www.drupal.org/project/phpmailer

It is used to send HTML emails with Mime Mail.

---
Tags: users, theming, emails
---


# Question
Title: Devel issue - "Rebuild the theme registry on every page load" won't work
I use D7. My site is being hosted on a "Shared" Server at Siteground.com. My site doesn't have any CSS/JS aggregation what so ever (see attachment), and I'm sick and tired of clearing the cache after the smallest of the CSS changes.

Many people told me that **installing** Devel **and enabling** "Rebuild the theme registry on every page load" should solve the problem, and will let me see the CSS changes after a refresh (F5/ctrl+r/ctrl+f5), but the fact is that even after I did that and enabled the Theme registry rebuilding option, I still have to clear caches to see the CSS changes, so I'm still stuck with this, and it's indeed frustrating!.

So, why would "Rebuild the theme registry on every page load" won't work? Why do I still need to flush all caches to see the CSS changes?

# Answer
> 0 votes
Not a straight solution and not really the best one but it seems that the co-problem; clearing the cache after every css change, was mainly **server-sided**, rather than Drupal sided --- I store at siteground.com and it was a Cpanel tool named "Supercacher" that caused all this mess and apparent lifetime wasting (and yet it raises the chance for good SEO when you site is finished).

Anyway, When you develop, better turn it off in Cpanel.

Btw, this was enough by it's own for me... Neither Devel nor any other external module is needed for this solution to work... Just disable the tool at Cpanel.

---
Tags: theming, caching
---


# Question
Title: How can I avoid clearing caches when CSS changes are made?
Every time I make the slightest CSS change, I need to clear cache to see the changes.

What can be done about this?

# Answer
Install AdvAgg, go to `admin/config/development/performance/advagg` and set "AdvAgg Cache Settings" to "Development"

If you don't want to do that, go to `admin/config/development/performance` and uncheck "Aggregate and compress CSS files" as well as "Aggregate JavaScript files"

Another option is to install the admin menu module. That has an option to just clear the css/js cache.
> 6 votes

# Answer
The main problem of this specific case seems to be a server-side, and not a Drupal side one --- I store at Siteground.com and they automatically turn on the Cpanel tool named "Super cacher" that caused all this mess and apparent lifetime wasting (and yet it raises the chance for good SEO when you site needs no further touches).

Anyway, When you guys develop online and experiencing this forced Caching problem and nothing else helps - just turn the "Super cacher" **off** in Cpanel. It would be nice though to find a way to keep it on, but to edit witouht FAC. In other words - keep Mikey's solution on hand (See link above).

From the moment this was off, I no longer needed to click "Flush all caches" for every single CSS change and just F5 was enough.
> 0 votes

---
Tags: caching, performance
---


# Question
Title: Show oldest to newest of a date range field
I am trying to figure a way to show the oldest to the newest of a date range field that is attached to a taxonomy.

For example: Tax1 (1900-1920), Tax2 (1913-1950), Tax3 (1970-1980)

So how shall I printed like this: (1900-1980)?

# Answer
1) Split your taxonomy values by (-).

2) Store all the values into an array.

3) Find minimum & maximum value from that array.

Ex:

> $date = array(1900, 1920, 1913, 1950, 1970, 1980);
>
> $result = min($date) . ' - ' . max($date);
> 1 votes

---
Tags: 7, database
---


# Question
Title: Get a file URL from a custom entity referenced on a user profile
I have an entity called CV which is used to store uploaded CVs. The entity is created and referenced on the user profile using inline entity form. I need to get the fid for the cv so I can do this:

```
$uri = file_load($fid)->uri;
$file_name = file_load($fid)->filename;
$path = file_create_url($uri);

```

I've tried to use entity\_metadata\_wrapper, but I'm not sure how to actually access the correct field. This is an example of what I've been trying:

```
$wrapper = entity_metadata_wrapper('candidate_cv', $cv);
$cv_file = $wrapper->field_candidate_cv->value();

```

Which returns this error:

```
EntityMetadataWrapperException: Unknown data property field_candidate_cv.

```

Update: I have managed to get the title of the entity using this:

```
$cv_wrapper = entity_metadata_wrapper('user', $user);
$cv_upload = array();
foreach ($cv_wrapper->field_cv->value() as $index => $feature) {
    $cv_upload[] = $feature->title;
}
echo title[0];

```

But I can't get to the fid of the file field which is field\_candidate\_cv.

```
$cv_wrapper = entity_metadata_wrapper('user', $user);
   $cv_upload = array();
   foreach ($cv_wrapper->field_cv->value() as $index => $feature) {
        $cv_upload[] = $feature->field_candidate_cv;
    }
    $fid = $cv_upload[0]['fid'];

```

$fid prints nothing.

However, in this $fid prints Array:

```
 $fid = $cv_upload[0];

```

# Answer
Solution:

```
$cv_wrapper = entity_metadata_wrapper('user', $user);
$cv_upload = array();
foreach ($cv_wrapper->field_cv->value() as $feature) {
    $cv_upload[] = $feature->field_candidate_cv;
}
$fid = $cv_upload[0]['und'][0]['fid'];

```

Printed the array of $cv\_upload using:

```
drupal_set_message('<pre>'. print_r($cv_upload, TRUE) .'</pre>');

```
> 0 votes

---
Tags: entities
---


# Question
Title: Save a user field without calling hook_user_update
I'm building a module that has to sync users with another, non-drupal, db. When the hook\_user\_update is run I check to see if the user has an account in the other db. If they don't then it creates a record there and returns their id from that system. The problem I have is now I need to store that new id in a custom drupal field as well. I don't want to assign it and call user\_save inside of hook\_user\_update because I don't want to run another instance of hook\_user\_update before the other has finished running. So, is it possible to just save a single user field without having to call user\_save thus triggering hook\_user\_update?

# Answer
> 1 votes
field\_attach\_update() may do what you need

https://api.drupal.org/api/drupal/modules%21field%21field.attach.inc/function/field\_attach\_update/7

A comment on the API doc page mentions using it to update a node's fields without updating the node.

If your custom field isn't part of the user object, you may just need to use drupal\_write\_record to write your field data.

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


# Question
Title: How to add a class to the webform error message
When people fill in incorrectly in my webform, the error message will output as follow, e.g:

```
<div class="alert alert-block alert-danger">
  <a class="close" data-dismiss="alert" href="#">×</a>
<h4 class="element-invisible">Error message</h4>
 <ul>
  <li>Name* field is required.</li>
  <li>Email field is required.</li>
  <li>Contact No. field is required.</li>
  <li>Comment field is required.</li>
 </ul>
</div>

```

Now, I wonder is there way I can add a CSS class to this message so that I can target this particular message that fired by this particular webform. e.g

```
<div class="alert alert-block alert-danger webform">
 ........
</div>

```

or even more specific, add the ID to the message .e.g

```
<div class="alert alert-block alert-danger" id="message-webform-client-block-212">
  ....
</div>

```

# Answer
I think the short answer is no, since the errors set in the error message box could come from any source, meaning the errors in that `<div>` aren't necessarily just your webform errors. Since it looks like you're using your webform as a block I'm guessing you can't target a body class to check if you're on a particular page type either.

If you were setting your own error messages you could add a `<span>` around the message with your custom class, but that would mean bypassing the validation handling webforms provide.

One possible solution would be to use JavaScript to find `<li>` elements that have text matching the error messages you want to style and moving them to a custom container. Another could be creating a YOURTHEMENAME\_status\_messages() function in your theme's template.php and doing a regular expression or string comparison to output specific error messages in a separate container. This route would affect all error message using the same text though, so it could affect an error message that was not from your webform.
> 0 votes

---
Tags: webforms
---


# Question
Title: Using a vocabulary term as a panel wildcard
I want to create a frontpage **Panel Page** that shows **Views** according to a **Vocabulary Term Name** in the url, like so:

* *frontpage/persons*
* *frontpage/companies*
* *frontpage/institutions*

That way, I've configured my **Content Panel Views** to show content by that category.

The thing is, when I create my **Panel Page**, the only terms I can pass are:

* `Taxonomy term (multiple): ID`
* `Taxonomy term: ID`
* `Taxonomy vocabulary: ID`

And I need something like `taxonomy term: machine name`, but it doesn't appear within my options.

# Answer
> 0 votes
You can set a `validation rule` to *convert* your term name into a term id within your **view** as a `contextual filter`, and then pass the term name through the page.

---
Tags: panels, 7, chaos-tool-suite
---


# Question
Title: Replace frontpage to a page with wildcards
I've created a page that receives a term name argument and displays a panel with several views which serves content according to this term name.

The thing is, I want to make that page my default frontpage, with a default term, but everytime I try setting it Drupal sents an error message:

> You cannot make this page your site home page if it uses % placeholders.

I'm even trying to set the url manually, such as `myCustomPage/myCustomTerm` i.e. `customFrontPage/NaturalUser` and it shows the following error message:

> the url 'myCustomPage/myCustomTerm' is not valid or you don't have permission to access it.

Is there any other way to change this?

# Answer
Make the term context of your page optional using ! rather than %, then set up your views so the default argument (when no term is supplied) is the one you want.

Your page should then work with no argument, ie. at path "myCustomPage". When all OK, you can assign that path as the front page for your site.
> 3 votes

---
Tags: 7, panels
---


title: How to preprocess view accordion

text:
# Question
Title: How to preprocess view accordion
I'm using D7 and module Views Accordion (V 7.x-1.1) for my view. I've created my custom template (e.g `views-view-accordion--[name of my view].tpl.php`) for customize my view. However, when I want to add some variables in preprocess function, I created the function `mytheme_preprocess_views_view__[name of my view](&$vars)`, I cannot get into this function.

Am I doing something wrong? Thanks in advance.

# Answer
> 1 votes
You want to use template\_preprocess\_views\_view (see views theme functions)

```
function MYTHEME_preprocess_views_view(&$variables) {
  $view = $variables['view'];
  if ($view->name == 'my_view_name') {
    // add your variables here
    $variables['YOUR_VARIABLE'] = 'value';
  }
}

```

$YOUR\_VARIABLE should be available in your template file.

---
Tags: views, theming, navigation
---


# Question
Title: How to show a secondary vertical axis to the right of a chart when using charts module?
I have created a chart of two variables, using Charts module. To do so, I used the Views integration of the charts module, and selected 'Chart' as the views style.

The result I got so far is that the chart is shown using the same vertical axis (y-axis) on the left (one for each variable).

Question: Is it possible to use two vertical axes, so that the primary axis is shown on the left of the chart, and the secondary on the right?

# Answer
See the answer here: https://www.drupal.org/node/2208461 (Courtesy of Quicksketch)

It is now incorporated in the (brand new) Charts community documentation, within Use sub-charts to create dual-Y-axis charts, which details the 4 steps to create such charts.
> 2 votes

---
Tags: charts
---


title: So many users and their access

text:
# Question
Title: So many users and their access
I am developing a site which has around 46 departments and each dept has three Access types. Say `Dept Admin, Dept Lead, and Dept Agent`.

Site will use taxonomy terms `Confidential, Restricted, Private and Public`. Rules goes like this..

1. Dept Admin has access upto Confidential level records, Dept Lead-\>upto Restricted, Agents upto Private records.
2. dept records should be accessible by only that dept users and goes its content moderation I am planning to use taxonomy access control along with Workbench Moderation. But this requires me to set up 46 * 3 (138) roles for my site. I am a bit concerned that it might reach some php memory limit, not sure.

Any advice is appreciated.

# Answer
finally went with duo Organic Group + OG Taxonomy permission modules
> 0 votes

---
Tags: users, taxonomy-terms, workbench
---


title: prepend one div in body in .inc file

text:
# Question
Title: prepend one div in body in .inc file
I want prepend one div using `jQuery`, But the div has to be generated dynamically, so I can not add it in `html.tpl` file.

I have tried below code

```
drupal_add_js('jQuery(document).ready(function () { jQuery("body").prepend("'+download_list()+'"); });', 'inline');

function download_list(){
    $output = "I am testing my div prepend";

    return $output;
}

```

But it is not working , whats the correct way to do this, please help

I am using `Drupal 7`

Thanks

# Answer
> 0 votes
It looks like you were using JS string concatenation syntax in PHP. Try

```
drupal_add_js('jQuery(document).ready(function () { jQuery("body").prepend("' . download_list() . '"); });', 'inline');

function download_list(){
    $output = "I am testing my div prepend";

    return $output;
}

```

---
Tags: 7, javascript
---


# Question
Title: Metatags and Commerce - pass taxonomy metatags to commerce product view
I have a Commerce Product view that pulls in products based on a taxonomy term in the url (category/taxonomy-term). This is done using relationships. Ideally, I would be able to edit metatags for each individual term (which I can) and have those metatags populated on the view page (which I can't figure out).

If I create a metatag default for taxonomy term, it works correctly on /taxonomy/term/%tid, but not category/term-name. If I create a metatag default for that view, I don't have access to the metatags as token replacement values for the term being used. There is a \[metatags:description\] token, but it is empty when using it on the view.

Thanks for any direction/insight/help!

# Answer
> 1 votes
The short answer is that the metatag module will provide metatags entered for terms if your view path matches the core taxonomy path (taxonomy/term/%).

In metatag\_views\_post\_render(), metatags checks if your view display path matches the path from the entity's info before it will proceed.

This gives you a couple of options.

1) You can make sure your view uses the taxonomy/term/% path and use Pathauto to make the aliases for your terms for that vocabulary (or all terms) match the desired 'category/term-name' pattern.

2) You can mimic what the metatag module does for your specific view using a custom module and these hooks:

```
/**
 * Implements hook_views_post_render().
 */
function MYMODULE_views_post_render(&$view, &$output, &$cache) {
  // Build a shortcut to the current display object.
  $display = $view->display[$view->current_display];

  // Only proceed if this view is a full page, don't process block or other
  // Views display objects.
  if ($view->name == 'MY_VIEW_NAME' && $display->display_plugin == 'page') {
    // Check if this is an entity display page, if so trigger
    // hook_entity_view().
    foreach (entity_get_info() as $entity_type => $entity_info) {
      // Entity paths will include an auto-loader that matches the entity's
      // name, thus the path will be 'some/path/%entity_name'.
      if (isset($entity_info['path']) && $entity_info['path'] == 'taxonomy/term/%taxonomy_term') {
        // Only proceed if this entity type supports meta tags.
        if (metatag_entity_supports_metatags($entity_type)) {
          // There must be at least one argument and the first argument must be
          // numerical.
          if (!empty($view->args) && is_numeric($view->args[0])) {
            // Only the first argument is used.
            $entities = entity_load($entity_type, array($view->args[0]));
            // Only if the entity actually exists.
            if (!empty($entities)) {
              $entity = array_pop($entities);
              MYMODULE_entity_view($entity, $entity_type, 'full', NULL, TRUE);
            }
          }
        }
      }
    }
  }
}

/**
 * Implements hook_entity_view().
 *
 * Provides additional argument to allow the display to be forced, to work
 * around problems elsewhere in the APIs.
 */
function MYMODULE_entity_view($entity, $entity_type, $view_mode, $langcode, $force = FALSE) {
  // Only run this function once per page load.
  static $i_will_say_this_only_once = FALSE;

  // Only proceed if this entity object is the page being viewed.
  if ($entity_type == 'taxonomy_term' && $view_mode == 'full') {
    // Some API calls need to force the data loading.
    if (!$force) {
      // Only run this function once per page load.
      if ($i_will_say_this_only_once) {
        return;
      }
      $i_will_say_this_only_once = TRUE;
    }

    // CTools uses 'page_manager' view mode to indicate the full entity display
    // page rather than 'full', so streamline the internal processes.
    if ($view_mode == 'page_manager') {
      $view_mode = 'full';
    }

    // Generate metatags output.
    if ($output = metatag_generate_entity_metatags($entity, $entity_type, $langcode, $view_mode)) {
      list($entity_id, $revision_id, $bundle) = entity_extract_ids($entity_type, $entity);
      $instance = "{$entity_type}:{$bundle}";
      // We need to register the term's metatags, so we can later fetch them.
      // @see metatag_page_build().
      metatag_page_set_metatags($instance, $output);
    }
  }
}

```

---
Tags: 7, views, commerce, meta-tags
---


title: Label Prints multiple times

text:
# Question
Title: Label Prints multiple times
I have a list and I only want to print the label once. Right now, it prints for each variable.

```
if (isset($vocabularies));
$vocabularies = taxonomy_get_vocabularies();
if ($vocabularies) {
  foreach($vocabularies as $vocabulary) {
    if ($vocabulary->vid == 5) {
      $terms = taxonomy_node_get_terms_by_vocabulary($node, $vocabulary->vid);
      if ($terms) {
        foreach ($terms as $term) {
          print '<div class="vocab">Event Type: <br/><p>' .$term->name;  '</p></div>';
        }
      }
    }
  }
}

```

# Answer
Try this:

```
 $terms = taxonomy_node_get_terms_by_vocabulary($node, $vocabulary->vid);
 if ($terms) {
   print 'Event Type: ';
   foreach ($terms as $term) {
     print $term->name;
   }
 }

```
> 1 votes

---
Tags: taxonomy-terms, entities
---


# Question
Title: Use sites.php to point https and http to diffent sites
I've got several Drupal sites on different domains running on the same code using sites.php.

What I want to do is point the same domain to different sites depending on whether it's accessed via http or https.

For example, in sites.php $sites\['http://www.example.com'\]='site1'; $sites\['https://www.example.com'\]='site2';

However, the above doesn't work. It looks like you can't specify protocol in sites.php.

Thanks,

Robin

# Answer
> 2 votes
Please read through the default `example.sites.php` file again. A `protocol` is the same thing as a `port` (they have a 1-to-1 relationship when we talk about a webserver).

`http` is implied by default in the rule describing `www.example.com`. `http` is also implied to be Port 80, otherwise known as `:80` in a URI-scheme.

Your format is completely wrong for any subsite defined in `$sites`. From the documentation it would be:

```
$sites['www.example.com']='site1';   // Normal HTTP www.foo.com
$sites['443.www.example.com']='site2';  // SSL version (port 443 by default for www.foo.com)

```

---
Tags: multi-sites
---


# Question
Title: Adding referencing entities using hook_entity_property_info_alter
I have a custom entity "Matching" with a **multi** value field entity reference jobs that references a node of type job.

```
function custom_alters_entity_property_info_alter(&$info) {
  $info['node']['properties']['referencing_matching'] = array(
    'label' => t('Referencing matching'),
    'type' => "entities",
    'description' => t("Matchings referecing a job"),
    'getter callback' => 'get_referencing_matching'
  );
}

function referencing_matching($node) {
  if($node->type == "job"){
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'matching')
          ->fieldCondition('field_job_id', 'target_id', $node->nid, '=');
    $result = $query->execute();
    if ($result) {
      return $result;
    }
}

```

the "getter callback" isn't expecting an id rather than an array

# Answer
> 2 votes
It looks like you are trying to add a multi-valued entity reference property to a standard node entity. If that's the case, I think you first need to declare the property as multi-valued in hook\_entity\_info\_alter() via the 'type' entry:

```
$info['node']['properties']['referencing_matching'] = array(
  'label' => t('Referencing matching'),
  'type' => 'list<matching>',
  'description' => t("Matchings referecing a job"),
  'getter callback' => 'get_referencing_matching'
);

```

See the hook\_entity\_property\_info() notes for more on that.

Then, in the getter callback I believe you need to return a list of entity ids, something like:

```
if ($node->type == "job"){
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'matching')
        ->fieldCondition('field_job_id', 'target_id', $node->nid, '=');
  $result = $query->execute();
  if (!empty($result['matching'])) {
    return array_keys($result['matching']);
  }
}

```

I have not tested that specific code, but this was the pattern that I used in a similar example of my own.

---
Tags: entities, search
---


# Question
Title: Add fields to form dynamically with ajax and retrieve values
I am trying to add a combination of text field and a select box to a form dynamically using Drupal 7 Ajax, when i click on a button.

But i have 2 issues here:

1. I am not able to add more than 1 set of fields in the form with Ajax
2. After i submit the form, i am not able to retrieve the values of the form. They are empty. I have the fields as "name\_1", "select\_1", "name\_2", "select\_2", etc.

I want to know if there is any way to solve it, with / without using a fieldset.

My custom module code:

```
function my_form_form($form, &$form_state, $no_js_use = FALSE) {
  $form['#tree'] = TRUE;
  $form['add_more'] = array(
    '#type' => 'button',
    '#value' => t('Add More'),
    '#href' => '',
    '#ajax' => array(
    'callback' => 'ajax_simplest_callback',
    'wrapper' => 'names-fieldset-wrapper',
  );
  $form['names']['name_1'] = array(
    '#type' => 'textfield',
    '#title' => t('Name 1'),
    '#attributes'=>array('id'=>'name_1', 'name'=>'name_1'),
  );
  $form['names']['select_1'] = array(
    '#type' => 'select',
    '#title' => t('Select 1'),
    '#attributes'=>array('id'=>'select_1', 'name'=>'select_1'),
    '#options'=>array('1'=>'One', '2'=>'Two', '3'=>'Three'),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  $form['#submit'][] = 'my_form_add_more_submit';
  return $form;
}
function ajax_simplest_callback($form, &$form_state) {
  if (empty($form_state['num_names'])) {
    $form_state['num_names'] = 1;
  }
  else {
    $form_state['num_names']++;
    $form_state['rebuild'] = TRUE;
  }

  for ($i = 1; $i < $form_state['num_names']; $i++) {
    $form['names']['name_'.$i+1] = array(
      '#type' => 'textfield',
      '#title' => t('Name '.$i+1),
      '#attributes'=>array('id'=>'name_'.$i+1, 'name'=>'name_'.$i+1),
    );
    $form['names']['select_'.$i+1] = array(
      '#type' => 'select',
      '#title' => t('Select '.$i+1),
      '#attributes'=>array('id'=>'select_'.$i+1, 'name'=>'select_'.$i+1),
      '#options'=>array('1'=>'One', '2'=>'Two', '3'=>'Three'),
    );
  }
  return $form['names'];
}

function my_form_add_more_submit($form, &$form_state) {
  print_r($form_state['values']);
  exit();
}

```

# Answer
Dont set any field `#required` to true.

```
 $form['markup'] = array(
        '#type' => 'markup',
        '#prefix' => '<div id="my-wrapper">',
        '#suffix' => '</div>',
    );
 $form['markup']['myfield'] = array(
        '#type' => 'textfield',
        '#size' => 12,
    );

```
> 1 votes

# Answer
You need to rebuild your form in your form function so you values get integrated into the form. You also want to make use of fieldsets and their tree structure to make the data a bit more organized.

```
function my_form_form($form, &$form_state, $no_js_use = FALSE) {

        $form['add_more'] = array(
          '#type' => 'button',
          '#value' => t('Add More'),
          '#ajax' => array(
            'callback' => 'ajax_simplest_callback',
            'wrapper' => 'replace-this',
            'method' => 'replace',
           ),
        );

        $form['names'] = array(
          '#type' => 'fieldset',
          '#title' => 'Names',
          '#prefix' => '<div id="replace-this">',
          '#suffix' => '</div>',
          '#tree' => TRUE,
        );

        // build the initial field if this is not being rebuilt
        // from ajax request
        if (!array_key_exists('clicked_button', $form_state)) {
          $form['names'][0] = array('#type' => 'fieldset');
          $form['names'][0]['name'] = array(
            '#type' => 'textfield',
            '#title' => t('Name'),
            '#parent' => 'test',
          );
          $form['names'][0]['select'] = array(
            '#type' => 'select',
            '#title' => t('Select'),
            '#parent' => 'test',
            '#options'=>array('1'=>'One', '2'=>'Two', '3'=>'Three'),
          );
        } else {
          // otherwise add the fields for each existing value
          foreach ($form_state['input']['names'] as $i => $value) {
            $form['names'][$i] = array('#type' => 'fieldset');
            $form['names'][$i]['name'] = array(
              '#type' => 'textfield',
              '#title' => t('Name'),
              '#default_value' => $form_state['input']['names'][$i]['name'],
            );
            $form['names'][$i]['select'] = array(
              '#type' => 'select',
              '#title' => t('Select'),
              '#default_value' => $form_state['input']['names'][$i]['select'],
              '#options'=>array('1'=>'One', '2'=>'Two', '3'=>'Three'),
            );
          }

          // add the additional field for a new entry
          $last = count($form_state['input']['names']);
          $form['names'][$last] = array('#type' => 'fieldset');
          $form['names'][$last]['name'] = array(
              '#type' => 'textfield',
              '#title' => t('Name'),
          );
          $form['names'][$last]['select'] = array(
              '#type' => 'select',
              '#title' => t('Select'),
              '#options'=>array('1'=>'One', '2'=>'Two', '3'=>'Three'),
          );
        }

        $form['submit'] = array(
          '#type' => 'submit',
          '#value' => t('Submit'),
        );
        $form['#submit'][] = 'my_form_add_more_submit';

        return $form;
    }

    function ajax_simplest_callback($form, &$form_state) {
        return $form['names'];
    }

    function my_form_add_more_submit($form, &$form_state) {
        print_r($form_state['values']);
        exit();
    }

```
> 1 votes

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


title: +1 user field after comment is made

text:
# Question
Title: +1 user field after comment is made
I created a new user field to keep count of comments. I want to increase it by 1 after a user posts a comment and decrease it by 1 when comment is deleted.

Is there any way I can use rules to do this?

I know I can use views aggregation to get comment count, but I don't want to use this method.

# Answer
It's worth noting the comment table has a 'uid' column so you could potentially query that to get the comment count for a user.

e.g:

```
$user_comment_count = db_select('comment', 'c')
->condition('uid', $account->uid)
->countQuery()
->execute()
->fetchField();

```

However, if you want to increment a field on comment insert, you could use Rules or `hook_comment_insert`

e.g: Rules export (Increment field\_comment\_count for current logged in user on comment insert)

```
{ "rules_increment_comment_count" : {
    "LABEL" : "increment_comment_count",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "comment" ],
    "ON" : { "comment_insert" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "site:current-user" ], "field" : "field_comment_count" } }
    ],
    "DO" : [
      { "data_calc" : {
          "USING" : { "input_1" : [ "site:current-user:field-comment-count" ], "op" : "+", "input_2" : "1" },
          "PROVIDE" : { "result" : { "result" : "Calculation result" } }
        }
      },
      { "data_set" : {
          "data" : [ "site:current-user:field-comment-count" ],
          "value" : "[result:value]"
        }
      }
    ]
  }
}

```

You'll need to tweak the Rule to match your conf, but something like that should work.
> 1 votes

---
Tags: 7, rules
---


title: Create block in template.php

text:
# Question
Title: Create block in template.php
I have the feeling that I'm doing something stupid or missing something obvious... I want to create a block in template.php in my custom template but it is not showing in admin/structure/block The code i use is simple:

```
/**
 * Implements hook_block_info().
 */
function MYTHEMENAME_block_info() {
  $blocks = array();
  $blocks['eeeeeeee'] = array(
    // The name that will appear in the block list.
    'info' => t('eeeeeeeeeee'),
  );
  return $blocks;
}

```

Then i created a custom module, to see if a have a typo, with the same code. Just changed MYTHEMENAME with MYMODULENAME and I can see it in admin/structure/block

1. I tried changing MYTHEMENAME to phptemplate
2. Cleared the cache many times

Is it even possible to create a block in template.php?

# Answer
I'm not sure this is possible. You would create the custom block in a module, add content to it there as well. Then you can theme it or call it in various places inside your theme as well as theme the actual block. That is the usual use scenario for blocks. I will try to add some links in just a bit with more explanation.
> 1 votes

---
Tags: theming
---


# Question
Title: Hide a region from a specific node? (Without CSS)
I can hide a region from a specific node via CSS but this is problematic since the `Display: none` attribute doesn't really clear the space... Any other way to do so?

# Answer
Try doing it via hook\_page\_alter

> Perform alterations before a page is rendered.
>
> Use this hook when you want to remove or alter elements at the page level, or add elements at the page level that depend on an other module's elements (this hook runs after hook\_page\_build().

You can then get the page you are on by calling menu\_get\_object without parameters and inspect the returned node object.

Add this code to your theme's template.php file:

```
function MYTHEME_page_alter(&$page){
  //dpm($page);
  if ($node = menu_get_object()) {
    if ($node->nid == 72) { // pick your node or add a condition to your liking
      // remove sidebar first region
      unset($page['sidebar_first']); // remove the regeion here
    }
  }
}

```

If your theme depends on it, and depending on the region you are removing, you should also implement template\_preprocess\_html and adjust your body classes so that they are in sync.

As to the CSS, `dispay:none` as a css rule should remove the element from display, whereas `visibility:hidden` hides an element, but it will still take up the same space as before. CSS Display and Visibility
> 3 votes

---
Tags: theming
---


# Question
Title: add field in admin>content that show if entity is translated
I'm looking for a field that i can add in the admin\>content view. I want to know if the entity (News items) is translated or not. (Dutch(default) and English) Now i always have to click edit article to see if the article is translated.

Search for hours on the internet but no result. (i did installed the admin view module so i could edit the admin\>content view)

Hopefully someone could help me out with this.

# Answer
> 0 votes
You can install the Admin Views module and override the view on /admin/content by adding a field that shows if the node has been translated or not.

---
Tags: views, entities, i18n-l10n
---


# Question
Title: Modify values that are received via Feeds_ex
I've setup Feeds\_ex module using JSONPath. One of the value I import is language code and it has next format: \[language-country\], i.e. \[en-US\] or \[en-UK\].

Right now I do import full value 'en-US', however I need to get only 'en' and get ridd of '-US'.

What is the good/best practice to modify value that I receive from Feed?

Thanks.

# Answer
Try hook\_feeds\_presave().

Just explore $entity object. You will get some idea.

Below is a example code.

```
$entity->lang_country[LANGUAGE_NONE][0]['value'] = 'en';
// After split [language-country] store your lang here.

```

**Update**: Also check feeds\_tamper
> 0 votes

---
Tags: feeds
---


# Question
Title: Correct way to disable /node in Drupal 7?
I find going to /node as being very useful to pinpoint exactly what content non-authorized users can see. But for two reasons I don't want anyone to access "/node".

1. I don't want that to end up in Google Search Results.
2. I don't want prying eyes to go through each and every content in case something should accidentally not have been made public.

So my question is: what is the most correct way to block /node? Or should I keep it open and rather let robots.txt avoid that path?

**UPDATE**

To make matters worse, it seems I have set everywhere in my permissions that certain content types must not be viewable by certain roles. However, those pages are still showing up under /node ?

# Answer
You can probably use this code with your custom module:

```
function hook_menu_alter(&$items) {
 $items['node']['access callback'] = FALSE;
}

```

Note: If you want specific people to access this page, you can set "access arguments" declared with hook\_permission
> 0 votes

---
Tags: nodes
---


# Question
Title: Custom form set error for user login validate
I have used a custom validate function.

```
function user_information_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_login' || 'user_login_block') {
    array_unshift($form['#validate'],'user_information_user_login_form_validate');
  }
}

function user_information_user_login_form_validate(&$form, &$form_state) {
  // print_r($form_state);
  form_set_error('name', t('Password invalid'));
}

```

But I am unable to log in to the site any more.

# Answer
> 1 votes
you cant submit your form because you have set the error.

**the form set error should be applied inside some condition**

```
 function user_information_user_login_form_validate(&$form, &$form_state) {
    //print_r($form_state);
    //set some condition
     if($form_state["some_field"] != "somevalue")// only when the condition satisfies the form set error should display. if not all the time your from set error will be called
      form_set_error('name', t('Password invalid'));
    }

```

above condition is a sample condition you have to replace it with your own condition for validating your password.

---
Tags: hooks
---


# Question
Title: Can't set view title in hook_views_views_pre_view
I am trying to change the title of the view based on some conditions view object. I figured that I could simply run

```
drupal_set_title('New title');

```

from inside the hook\_views\_views\_pre\_view, but its not changing the title. I tried it in hook\_views\_query\_alter too, but it wouldn't change. I've confirmed that its actually entering the hook by doing a printout of the view object.

Should I be able to set the title from these hooks?

# Answer
> 0 votes
It's probably the Views module is calling `drupal_set_title()` right after invoking those hooks, so calling `drupal_set_title()` in those hook doesn't have the effect you are expecting. You could eventually use `view::set_title` in `hook_views_pre_view()` or `hook_views_pre_render()`.

```
function mymodule_views_pre_view(&$view) {
  if ($view->name == 'the view you need to alter') {
    $view->set_title(t('New title'));
  }
}

```

You cannot assume those hooks are invoked when a view page is being rendered; it could be the view is embedded in a page for which the title change is not desired. This is similar as assuming `hook_node_view()` is being invoked when a node is rendered in its own page, and then calling `drupal_goto()` from that hook.

---
Tags: views
---


# Question
Title: How can I append date and time to node titles?
I want to append the date and time to node titles. For example, If the title is *Test*, I want to change it to *Test\_DDMMYY\_hhmmss*.

How can I achieve this?

# Answer
> 3 votes
This will do for you

```
function modulename_node_presave($node) {
      if($node->type == 'node_type_machine_name') {
        $new_date = date("DMY_hms", time());
        $node->title = $node->title."_".$new_date;
      }
}

```

# Answer
> 3 votes
Check out the Automatic Nodetitles module to do it without code. In combination with the Token module you can build complex patterns.

# Answer
> 2 votes
I think you want to use `hook_node_presave()`. This should get you started.

```
function mymodule_node_presave($node){
  if ($node->type == "my_content_type") {
    $node->title = $node->title . "_" . date('dmy_his');
  }
}

```

Though I am only inferring that you want date and time of when the node was saved.

---
Tags: nodes
---


# Question
Title: How can I set up a Drupal rules action to play a specific sound?
I would like set a sound alert as a Drupal rules action- for Drupal to play a specific sound file eg in audiofield. How can I do that?

# Answer
> 0 votes
I would redirect to the node with the audiofield and set it to autoplay. This way you can have only one audio field per node of course.

---
Tags: rules, files
---


title: Commerce module in not drupal commerce

text:
# Question
Title: Commerce module in not drupal commerce
I have a website, built as a non Drupal commerce website. I want to add functionality to my website so customers can buy books, and add checkout page and cart. I mean add commerce functionality in a not Drupal commerce site.

Can I do that?

# Answer
Yes that is possible. Download the modules from: https://www.drupal.org/project/commerce

You can not install the install profile (https://www.drupal.org/project/commerce\_kickstart) on top of an existing Drupal website.
> 4 votes

# Answer
You can just install commerce on top of a non-commerce drupal site in the beginning. Commerce for drupal core it is just another module that adds fields, views, rules, content types, functionality and so on.
> 3 votes

---
Tags: commerce
---


title: views filter show node only one time?

text:
# Question
Title: views filter show node only one time?
I have a view, and i filter the nodes based on a list of tags. If one node has more than one matching tag, it's displayed more than once. Can you filter those out? Want to display them only once...

# Answer
> 0 votes
In your view under "advanced", next to "query settings" click "settings" and check "Distinct". This option makes sure every node only gets displayed once.

# Answer
> 0 votes
Click SQL settings in your view:

Select Distinct:

---
Tags: views
---


# Question
Title: How to programmatically use the "between" operator in Drupal Views
I have a price field and I want to see if the value of this field is between multiple price segments.

E.g.: `(price BETWEEN 0 AND 100) OR (price BETWEEN 150 AND 200)`

So how can I use the "between" operator in Drupal Views to programmatically alter a query?

# Answer
> 0 votes
I managed to do it like this:

```
$where = array(
    'conditions' => array(
         array(
              'field' => $field,
              'value' => array(0, 100),
              'operator' => 'BETWEEN',
         ),
         array(
              'field' => $field,
              'value' => array(150, 200),
              'operator' => 'BETWEEN',
         ),
    ),
    'args' => array(),
    'type' => 'OR',
);
$query->where[] = $where;

```

# Answer
> 1 votes
I believe you are using hook\_views\_query\_alter. So see the example to add `OR` in condition. Check out code :

```
$this->query->add_where(
  $this->options['group'],
    db_or()
      ->condition($field, array(0, 100), 'BETWEEN')
      ->condition($field, array(150, 200), 'BETWEEN')
  );

```

---
Tags: views
---


title: Image crop for touch devices

text:
# Question
Title: Image crop for touch devices
I am using imagecrop module for imagecrop field. but it is not working in touch deveices like ( ipad ). There is any best module for image crop in touch devices?. please help me.

# Answer
I use the SimpleCrop module, hope it fits your needs.

> SimpleCrop provides the simplest workflow for manual crop of images. Basically, you can crop image in three steps: upload image =\> select area =\> save content. Functionality of this module covers more than 90% needs of manual image crops.
>
> One of the key feature of this module is that this crop can be used as-is for the end users. So you don't need to theme or to add a workarounds to show this image crop to someone else. It has minimalistic and usable UI.
> 5 votes

---
Tags: 7, media
---


# Question
Title: How to load a taxonomy term (or entity) by field value?
To load a taxonomy term programatically you can use `EntityFieldQuery`.

```
<?php

// Get taxonomy term by field value
$section_vocab = taxonomy_vocabulary_machine_name_load('section');

if($section_vocab) {
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'taxonomy_term')
    ->propertyCondition('vid', $section_vocab->vid);
  $result = $query->execute();

  ...

}

```

However, that doesn't load the taxonomy term fields. Adding a field condition to the query`$query->fieldCondition('field_id', 'value', '123');` to the query doesn't work as the result is always empty.

## Bad solution

So the solution using EntityFieldQuery that I found here https://www.drupal.org/node/1517744 works, but it requires looping through all the terms in the vocabulary (in the worst case) which has a high cost.

```
<?php

// Get taxonomy term by field value
$section_vocab = taxonomy_vocabulary_machine_name_load('section');

$sectionID = NULL;

if($section_vocab) {
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'taxonomy_term')
    ->propertyCondition('vid', $section_vocab->vid)
  $result = $query->execute();

  if (!empty($result['taxonomy_term'])) {
    // To load all terms.
    $terms = taxonomy_term_load_multiple(array_keys($result['taxonomy_term']));

    // Look up for the first term with the field value that we want.
    foreach ($terms as $term) {
      // Stop looking if we find it
      $value = $term->field_id['und'][0]['value'];
      if ($value == $IDtoFind){
        $termID = $term->tid;
        break;
      }
    }

  }
}

```

If the taxonomy term has a field with machine `field_id`, how can you load the taxonomy terms with a specific value for it?

# Answer
As specified in the `EntityFieldQuery` documentation. It is not possible to query across multiple entity types. It is no possible to query all the terms with a specific field value as this would require querying both `vocabulary->vid` and `field_id->value`.

To load a taxonomy term by field value is possible to get all the entities that have that value:

```
  $query->entityCondition('entity_type', 'taxonomy_term')
    ->fieldCondition('field_id', 'value', $IDtoFind, '=');

```

Using `->fieldCondition('field_id', 'value', $IDtoFind, '=')` and `->propertyCondition('vid', $section_vocab->vid)` in the same query would produce an empty result.

## Solution

For the code in the question this would work, based on that `field_id` is used only one vocabulary and it value is unique.

```
<?php
// Get taxonomy term by field value
$section_vocab = taxonomy_vocabulary_machine_name_load('section');

$sectionID = NULL;

if($section_vocab) {
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'taxonomy_term')
    ->fieldCondition('field_id', 'value', $IDtoFind, '=');
  $result = $query->execute();

  if (!empty($result['taxonomy_term'])) {
    // Set the internal pointer of an array to its first element
    reset($result['taxonomy_term']);
    // Get the key value for the first item
    $termID = key($result['taxonomy_term']);

  }
}

```
> 2 votes

# Answer
You have to use https://api.drupal.org/api/drupal/modules%21taxonomy%21taxonomy.module/function/taxonomy\_get\_tree/7

In your case you have to set "load\_entities" to TRUE

```
taxonomy_get_tree($vid, $parent = 0, $max_depth = NULL, $load_entities = FALSE);

```
> 1 votes

---
Tags: 7, taxonomy-terms, entities, database
---


title: Add #states in a webform

text:
# Question
Title: Add #states in a webform
I have a webform in my site in that am trying to make toggle for a radio button but the field i require do not have #states .How to add the attribute #states in a webform component using form alter?

# Answer
> 0 votes
Try Webform conditional module, it provides you the same thing.

# Answer
> 0 votes
The Webform Conditional module may be of use here. However, the Webform Conditional module is now included in Webform:

> As of Webform version 7.x-4.0-alpha2 this module has been merged into Webform and is no longer necessary.

It appears the latest version of the Webform module does support `#states`. Here are a few related links with more information about `#states` and Webforms:

---
Tags: 7
---


# Question
Title: Content display based on user preferences
I'm new to Drupal, so I don't know if what I want to do is even possible. I want to create six checkboxes that represent different languages - let's call them A,B,C,D,E,F so that every user can check as many as he/she wants during registration and change it later (I already did that by adding field in account settings). Moreover, on one page I'd like to have six blocks of text (one for each language) but only show the checked ones (so each user would see different content). Finally, I want to enable users to create their own content which would be published after administrator's review - difficult part is that every administrator should have language/-es that he/she specializes in and be able to accept/edit content only in that language/-es.

If I am not being specific enough please let me know and I will try to elaborate.

Thanks for you help! Dominik

# Answer
You can accomplish the first by enabling PHP in modules, and making a check in the block configuration / Pages - using php you can check each block for the appropriate $user field and whether or not its set for that particular language. You could also create a module to build each block programmatically, and then show/hide depending on the field value.

The second can be done with something like this:

Content Type * create a hidden field called language

* using Rules set an event (After Saving New Content - ), event - set data value - node-\>language equal to user-\>language. This will assign a language to each node created
* create a view with the relevant fields/information you want presented, and filter on current user:language - in this way each user who sees this view will only see the entries that match their own language settings
> 0 votes

---
Tags: views, 7
---


title: Migrate class not registering properly

text:
# Question
Title: Migrate class not registering properly
I am having trouble creating and registering migrate modules. At the moment, when I go to the UI screen, it says 'Class X no longer exists' (so, at least its being picked up) and wont show in the list of migrations on the page. At the moment, I have only implemented one class and had this issue (when I figure this out, I will create everything else). Here is my code:

```
function migrate_rcmd_migrate_api() {
  $api = array(
    'api' => 2,
    'groups' => array(
      'Test' => array(
        'title' => t('Test Migrations'),
      ),
    ),
    'migrations' => array(
      'EventNode' => array(
        'class_name' => 'EventNodeMigration',
        'group_name' => 'Test',
      ),
      'CareerNode' => array(
        'class_name' => 'CareerNodeMigration',
        'group_name' => 'Test',
      ),
      'NodeRegistrationEntity' => array(
        'class_name' => 'NodeRegistrationEntityMigration',
        'group_name' => 'Test',
      ),
      'JobPostingEntity' => array(
        'class_name' => 'JobPostingEntityMigration',
        'group_name' => 'Test',
      ),
      'CoverLetterFileEntity' =>array(  //may only need one file entity migration class
        'class_name' => 'CoverLetterFileEntityMigration',
        'group_name' => 'Test',
      ),
      'ResumeFileEntity' => array(
        'class_name' => 'ResumeFileEntityMigration',
        'group_name' => 'Test',
      ),
    ),
  );
  return $api;
}
```

and

```
abstract class Test_Migration extends DynamicMigration {
  public function __construct() {
    // Always call the parent constructor first for basic setup
    parent::__construct();

    // With migrate_ui enabled, migration pages will indicate people involved in
    // the particular migration, with their role and contact info. We default the
    // list in the shared class; it can be overridden for specific migrations.
    $this->team = array(
      new MigrateTeamMember('Liz Taster', 'ltaster@example.com', t('Product Owner')),
      new MigrateTeamMember('Larry Brewer', 'lbrewer@example.com', t('Implementor')),
    );

    // Individual mappings in a migration can be linked to a ticket or issue
    // in an external tracking system. Define the URL pattern here in the shared
    // class with ':id:' representing the position of the issue number, then add
    // ->issueNumber(1234) to a mapping.
    $this->issuePattern = 'http://drupal.org/node/:id:';
  }
}

class EventNodeMigration extends Test_Migration {
  public function __construct($arguments) {
    parent::__construct($arguments);
    //WE WILL NEED THIS
    //$this->dependencies = array('BeerTerm', 'BeerUser');

    $this->map = new MigrateSQLMap($this->machineName,
      array(
        'nid' => array(
          'type' => 'int',
          'not null' => TRUE,
          'description' => 'The primary identifier for a node.',
          'alias' => 'n',
        )
      ),
      MigrateDestinationNode::getKeySchema()
    );
    //example
    $query = Database::getConnection('default', 'legacy')
             ->select('node', 'n')
             ->fields('n', array('nid','vid','type','language','title','uid','status','created', 'changed','comment','promote','sticky','tnid','translate','uuid'))
              ->condition('type', 'events','=');
              //ADD JOINS TO FIELD TABLES HERE
    $this->source = new MigrateSourceSQL($query);
    $this->destination = new MigrateDestinationNode('events');

    $this->addSimpleMappings(array('nid','vid','type','language','title','uid','status','created', 'changed','comment','promote','sticky','tnid','translate','uuid'));
    //$this->addFieldMapping('title', 'page_title');
    //$this->addFieldMapping('body', 'page_body');
  }
}
```

# Answer
> 1 votes
Be sure:

1. your migrate\_rcmd\_migrate\_api function is in the file migrate\_rcmd.migrate.inc.
2. your Classes are included in .inc files defined in your modules .info file. See this documentation page on Migrate: https://drupal.org/node/1006982
3. Lastly in Migrate \> 2.5 (i think thats the right version) migration auto discovery is now gone. You can use `drush migrate-register` to register your migrations and classes. See `drush help migrate-register` as needed.
4. when in doubt clear your caches: `drush cc all` to be sure the .inc files are registered in drupals code registry.

# Answer
> -1 votes
Add this code your module hook\_enable().

```
/**
* Implements hook_enable().
*/
function MODULENAME_enable() {
  Migration::registerMigration('MigrationClassName');
  $migration = Migration::getInstance('MigrationClassName');
  $result = $migration->processImport();
}

```

---
Tags: migrations
---


# Question
Title: Display block after some action (saved node)
I want to display block after an action. My user will create new content (node). After he save it, the content is shown with a specific block (only once, no further).

I was looking on trigger module, but I do not see this option.

I am using Drupal 6

Thank you for help!

# Answer
> 1 votes
You can use Rules \+ Rules Bonus Pack for this. The Rules Bonus Pack module has actions for enabling and disabling blocks upon a certain event (e.g. save a node). See this screencast for an explanation.

*Note; Rules Bonus Pack is a testing ground for new functionality for the Rules module, so test thoroughly. However, the linked screencast above was published in 2011, so perhaps the code had some test mileage already.*

---
Tags: blocks, rules
---


# Question
Title: node:menu tokens not working in Pathauto
I can't get any node:menu-based tokens to work in my Pathauto replacement patterns. Other tokens, such as *\[current-user:name\]* or *\[node:language\]*, work fine. But the token I am trying to use, a menu-based token, specifically *\[node:menu-link:parents:join:/\]* does not. I've tried a slew of the node:menu-link tokens, such as *\[node:menu-link:parent:url:path\]*, and they're all being skipped.

When I bulk delete all Content aliases, then bulk update them, I do not get any error messages. The resulting aliases from my pattern *\[node:menu-link:parents:join:/\]/\[node:title\]* just ends up being the node title. git status

I've been banging my head against this for days, and in trying to fix it have:

* installed Token Tweaks and set the depth to 2
* run drush *@test ev "token\_clear\_cache();* incessantly
* disabled Menu Firstchild, then when that didn't help...
* updated Menu Firstchild to the dev version and applied this patch
* applied this Token patch
* applied this core (!) patch

Now I'm running:

* Pathauto 7.x-1.2+21-dev
* Token 7.x-1.5+4-dev
* Token Tweaks 7.x-1.x-dev
* Menu Firstchild 7.x-1.1+1-dev

An additional detail: Going to node/\[nid\]/devel/token for any given page hangs for a while, then displays a blank screen. It produces three errors like this:

```
Notice: Undefined property: stdClass::$field_studio_location in addressfield_tokens() (line 219 of /var/www/html/test/sites/all/modules/contrib/addressfield/addressfield.tokens.inc).

```

This doesn't seem particularly serious, but maybe relevant.

Any ideas? Even pointers on how to debug would be great.

# Answer
> 0 votes
FWIW, this was actually caused by the menu not being selected in the Menu Settings of this particular content type. Thanks for the help!

# Answer
> 1 votes
Just encountered that, after a full debug, it seems that `menu_tokens()` is not called at all.

```
  // There is a huge bug with menu tokens not being detected, to fix that, load
  // token include file and force repicking the menu_tokens() function as
  // implementation of hook_tokens()
  module_load_include('inc', 'token', 'token.tokens');
  module_implements('tokens', FALSE, TRUE);

```

That crappy hack fixed my problem but Why... just WHY ?

So yeah, after a deeper investigation, in `module_implements()`:

```
  $include_file = isset($hook_info[$hook]['group']) && module_load_include('inc', $module, $module . '.' . $hook_info[$hook]['group']);
  // Since module_hook() may needlessly try to load the include file again,
  // function_exists() is used directly here.
  if (function_exists($module . '_' . $hook)) {
    $implementations[$hook][$module] = $include_file ? $hook_info[$hook]['group'] : FALSE;
  }

```

Okay, so the only thing that is preventing menu from being picked is the sorting:

* if menu is processed before token in this `module_implements()`, the `menu.tokens.inc` include file will not be picked as it doesn't exist
* if token is before menu, the `token.tokens.inc` thus `menu_tokens()` function will be discovered and picked up after

So if you don't want any code, just alter the weight of token and menu so that menu's is higher than token's.

**But NO**, there is a `token_module_implements_alter()` that just does that, but it is not called, and that is the thing I couldn't figure out. So the final hack was:

```
  // Rebuild implementation cache
  cache_set('module_implements', array(), 'cache_bootstrap');
  cache_clear_all('hook_info', 'cache_bootstrap');

```

---
Tags: tokens, path-aliases
---


# Question
Title: How to proceed after update.php fails due to memory limit?
Sometimes i have a "Fatal error: Allowed memory size exhausted" on certain drupal installations with low php memory limit during module or core updates. After such an error i regularly increase this value with the help of my webhoster to avoid this for future updates...

But on the drupal side i'm lost a bit. The system report shows no indication that the update has to be done again and doing it manually shows that there's nothing to update. But this process failed before...

How do i find out if something went wrong during the update.php process?

# Answer
# Short Answer

You can't. Though comment F0ns's comment is a good start, depending on your PHP skills you may find this frustrating to impossible.

# Long Answer

I am not sure that the easiest resolution is to deal with the (possible) problem after the event.

I would not normally suggest this as an answer except that you begin your question with 'Sometimes', implying that this a is a workflow consideration rather than a specific bugfix.

You should consider your upgrade process in general. Ideally you would put the site into maintenance mode if you absolutely must perform the upgrades on a live site, so there would be no changes to the site during the process. You should always take a database backup before performing core or contrib updates, and this is made easy using backup\_migrate module. If you are updating core backup the files as well (if it is contrib simpler to just download previous version)

As long as you know which updates you are applying (I do not recommend applying many at the same time), and what version of core/module you are upgrading from, then you can now easily return to your pre-upgrade state by overwriting the db and files, rather than trying to pick apart potential problems caused by a failed upgrade.

Depending on the usage of your site, it might be preferable preferable to limit administrative access to the site temporarily (or put it into maintenance mode), perform updates on a local clone of the site, and overwrite the live version with the tested, working local version, restoring administrative access.
> 3 votes

---
Tags: 7, updating
---


# Question
Title: What to do when a module is uninstalled but leaves some features enabled?
I just disabled and uninstalled a module. Problem is that I still see some features that were created by this module at: "admin/structure/features"

How can I delete these features? I don't see any "features" table in the database.

**UPDATE** I think I wasn't clear enough, sorry. It is not a feature module, it is standar module called "md\_portfolio". This module creates the features you can see in the capture.

There are not any modules with the names you see in the capture in **sites/all/modules**

**Update2** the features are shown as "enabled" in the capture but NOW they are disabled (I took this capture when I had them enabled)

# Answer
> 0 votes
If the feature is creating some items that you no longer wish to have on your site (content type, maybe) you can always uninstall that feature. Remember features are basically modules, so you uninstall them the same way (go to mysite/admin/modules/uninstall). That may start to remove some of the items the feature was responsible for (depending on the feature's uninstall script)

Also, as features are basically mini modules, they won't fully go away (or stop showing up on your features page) without removing them first. They should be located in your site/all/modules folder. Remove the feature from the file system.

---
Tags: features
---


# Question
Title: How to use the stomp module to send and receive a queue?
Hello everyone,

I downloaded the stomp module for drupal and I just can't find any tutorial on how to use it.

I'd like to send and receive queues to and from activemq. I've an MQConsumer.php class and an MQProducer.Php class which use the fusesource stomp library and I'd like to integrate it to drupal.

I mean I've installed the module and there's like no feedback from the system. Like no UI.

Can anyone tell me how it works? I'd like to test and extend it's functionality. Thanks

# Answer
> 1 votes
Drupal supports its own Queue interface out the box. See https://api.drupal.org/api/drupal/modules%21system%21system.queue.inc/group/queue/7 The stomp module when configured simply moves the queue infrastructure out of Drupal and into a 3rd party system.

See the readme on this integration settings http://cgit.drupalcode.org/stomp/tree/README.txt

---
Tags: 7
---


# Question
Title: How do I add CSS & JavaScript to <head>?
I want to add the following code in my section of the front page using a Drupal 8 sub theme of Bartik.

Can anybody help how to do it? What is the best way to do it in this new twig version of theme? Where is page.tpl?

```
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="stepcarousel.js"></script>

```

# Answer
> 10 votes
On you THEME.libraries.yml:

```
global-styling:
  version: VERSION
  header: true // <--- To the header!!!
  css:
    theme:
      css/mystyle.css: {} // if you want add custom css
  js:
    js/stepcarousel.js: {}
  dependencies:
    - core/drupal // for use drupal.js
    - core/jquery

```

On you THEME.info.yml:

```
name: THEME
base theme: Bartik
...
libraries:
  - THEME/global-styling
...

```

and **Clear Cache**

> Where is page.tpl?

Here: core/modules/system/templates/page.html.twig

If you want use it, copy to theme folder inside templates, like this:

```
 THEME
   templates
     page.html.twig

```

Change all you want and **Clear Cache**

# Answer
> 7 votes
In Drupal 8, stylesheets and JavaScript files are attached as libraries:

You add a yourtheme.libraries.info to your theme (or custom module) folder:

```
power-slider:
  version: 1.x
  js:
    js/power-slider.js: {}
  css:
    theme:
      css/power-slider.css: {}
  dependencies:
    - core/jquery

```

And then attach the library to a render array. For example, this attaches the library to all pages:

```
function yourtheme_page_attachments_alter(&$page) {
  $page['#attached']['library'][] = 'yourtheme/power-slider';
}

```

This approach has the advantage of being reusable. You define the necessary paths once and you can re-use them in different places in your code.

See:

*This answer was very much inspired by berliner's answer.*

# Answer
> 2 votes
In Drupal 8 client resources like CSS and JavaScript files are attached to render arrays:

```
$element['#attached'] = array('js' => array(PATH_TO_JS));

```

Where `$element`can be an output render array or a form element.

Alternatively, you can register a library by defining it in a \*.libraries.info file

```
power-slider:
  version: 1.x
  js:
    js/power-slider.js: {}
  dependencies:
    - core/jquery

```

and then attach the library to a render array like this:

```
$element['#attached']['library'][] = 'NAMEOFTHEMODULE/power-slider';

```

The latter approach has the advantage of being reusable. You define the necessary paths once and you can re-use them in different places in your code.

---
Tags: 8, javascript
---


# Question
Title: How to do autocomplete in a Bootstrap modal form?
I've got a D7 page that constructs a Twitter Bootstrap modal form; it appears in response to a click on a button on the page. I'd like to have in that form a textfield that uses the standard Drupal autocomplete mechanism; the problem is that the textfield isn't getting properly hooked into the autocomplete system. I'm loading the Bootstrap versions of misc/ajax.js and misc/autocomplete.js into the page with drupal\_add\_js() so that they'll be around if the modal is invoked, but all the attached behaviors in autocomplete.js aren't getting invoked when the modal form is constructed and presented, and so the textfield stays a regular textfield. Or so I think, anyway -- I'm kinda out of my depth here.

I suppose I could roll my own ajax code for the field, but the basic autocomplete behavior is so obviously the right thing that it ought to be used. Any advice out there? Thanks!

# Answer
> 1 votes
Drupal's JS is powered by behaviors. If you find yourself in a situation where you need to poke the system into life, you can manually attach the behaviors like so:

```
Drupal.attachBehaviors();

```

---
Tags: 7, forms, javascript, ajax, theming
---


# Question
Title: Why is the fivestar rating displaying/suggesting 4 out of 5 stars when no votes have been made?
When adding a node which has a fivestar field and there are no votes yet, it shows 4 out of 5 stars as "on". Is this intended/ normal?

In my `preprocess_page` hook:

```
<?php
if (isset($node->field_rating)) {
                $field = field_view_field('node', $node, 'field_rating', array('label' => 'hidden'));
                $rating = render($field);
                $vars['title_rating'] = $rating;
            }

```

which gets rendered like this (with no votes made yet):

```
<div class="fivestar-widget clearfix fivestar-widget-5">
    <div class="cancel">
            <a href="#0" title="Cancel rating">Cancel rating</a>
    </div>
    <div class="star star-1 odd star-first on">
            <a href="#20" title="Give it 1/5">Give it 1/5</a>
    </div>
    <div class="star star-2 even on">
            <a href="#40" title="Give it 2/5">Give it 2/5</a>
    </div>
    <div class="star star-3 odd on">
            <a href="#60" title="Give it 3/5">Give it 3/5</a>
    </div>
    <div class="star star-4 even on">
            <a href="#80" title="Give it 4/5">Give it 4/5</a>
    </div>
    <div class="star star-5 odd star-last">
            <a href="#100" title="Give it 5/5">Give it 5/5</a>
    </div>
</div>

```

# Answer
Same problem here. I've made a workaround putting a class and set "display: none" in it.
> 0 votes

---
Tags: rating
---


# Question
Title: Apache Solr integration on shared hosting with cpanel
If I do not have any other access to my site's remote server other than file manager via CPanel, is there a way I can get Apache Solr up and running on my Drupal 7 site? The remote host does not provide me with shell access. Does anyone know a tutorial link for this?

# Answer
> 3 votes
No, in this case, you cannot do put Apache Solr on your server. I just had a client who had the same problem. You have 2 options:

1. Setup a second server that has shell access, and will index you site for you
2. Use someone else's preconfigured Apache Solr already, such as Acquia Search (not free)

# Answer
> 1 votes
You can transfer your site to such hosting services, which offer Apache Solr Search together with Drupal like http://drupion.com

# Answer
> 1 votes
Another cheap option is Midwestern Mac's hosted search service (just to throw out another option): there are already many other people using it in tandem with shared hosting to help make search faster and better.

See http://hostedapachesolr.com/

(Disclaimer: I'm the owner of Midwestern Mac).

# Answer
> 0 votes
Do not get hosted on a cPanel server with SOLR. That is a bad idea.

Host your SOLR index(es) with a solr hosting provider that'll give you the solr hostname, port and path, and use it on your cPanel server using the php-solr-client if you're using php.

Such SOLR host would be: http://www.opensolr.com

# Answer
> 0 votes
Some shared hosting companies allow you to get access to shell, but you've to send them a special form (e.g. HeartInternet).

Alternatively may try to use PHP Shell (if it's allowed) to download solr sources and set-up on your user account. Which is downloading sources via `curl` and run `java -jar start.jar` from your solr example folder.

If this won't work (e.g. they don't have `java`), you have to either use temporary db search (Search API DB), set-up solr on external host or upgrade your hosting into VPS or dedicated one.

# Answer
> 0 votes
I'm afraid that you cannot install Apache Solr without shell access. You'll need a vps for this. I would recommend rosehosting. They offer free migration, so they will migrate your website and install Drupal and Solr on your vps.

---
Tags: database, search
---


title: Views field for content access?

text:
# Question
Title: Views field for content access?
I'm building a membership site and I'm trying to find the best way to tease content that's only available to subscribers but show it in the same view as content available to all.

I'm currently using the content access module and while I'm able to generate the view that includes both open and restricted content I need a way to attach a lock icon to the rows who have restricted access. My thought was to have the view output the content access permission as a field but content access doesn't appear to have anything currently exposed to views.

Has anyone done something like this before? I'm open to using a different access control module as long as I can set permissions on a per-node basis.

# Answer
> 0 votes
I haven't used this in a while (2 years), but it did what you described back then!

https://www.drupal.org/project/field\_permissions

---
Tags: views, users
---


title: Contextual Filter / Relationship

text:
# Question
Title: Contextual Filter / Relationship
I'm having difficulty with setting up a view in Drupal 7. I'm going to use a sports example as a way to illustrate my problem:

I have three content types: 1. Team 2. Roster 3. Player

On the ROSTER editing page, I select which TEAM this roster belongs to, via Entity Reference.

On the PLAYER editing page, I select which TEAM this player belongs to, via the SAME entity reference field.

I've created a view, specifically a block, that lists the players on the roster page. However, right now, it's displaying ALL players. I know this is what contextual filters/relationships are for.

However, I get lost in the contextual filter and relationship settings. I've read a lot of documentation about each, impressed by all the different explanations and demos, but can't seem to find the right configuration that works for my problem.

I'm trying to filter the players on the ROSTER page, based on the TEAM that is selected both in the ROSTER and PLAYER content types.

Any help, suggestions, advice is appreciated. Thank you.

# Answer
a roster lists the players on 1 team, correct? If the view is at a url like `roster/TEAMNAME` you want a listing of players where the contextual filter on teamname provided by argument 1 in the URL, or else 404 or hide the view.

If the roster is not on a URL but say a block on 1 players page (showing the rest of the player roster for his team) then I would add a Views Field View to the player content type that uses the player's own team as the argument to the View I describe above.

Contextual filters are good when you provide the context for the view (like a URL, or another field). relationships just help you to get more information into your view (like additional fields).
> 0 votes

---
Tags: 7, views
---


title: CleanURL issues even after disabling it

text:
# Question
Title: CleanURL issues even after disabling it
So I recently transferred my site to a new server and disabled cleanURLs because of facing many errors. But due to this, I'm facing multiple issues:

1. Sometimes (not all the time)- when I save a form in the admin (editing user profiles/nodes/content etc.), the page redirects to a cleanurl (even though it's disabled) - for example www.example.com/admin/people instaed of www.example.com/?q=admin/people - I have no idea why this randomly keeps happening
2. When I upload user pictures for users and set Image style as thumbnail, the original image gets uploaded properly, but the thumbnail never gets generated adding to the fact that the image path generated for the user is absurdly as follows: www.example.com/?q=sites/default/files/styles/thumbnail/public/pictures/example.jpg - Is this because of cleanURLs again?
3. Moreover, I can't even re-enable cleanURLs since it gives me a negative test result.

I tried replacing the .htaccess file and it didn't solve the issue. Maybe it's my server configuration?

Even yet, I don't want cleanURLs enabled at all. So how do I fully disable it? Or is disabled anyway and this is some other issue?

Please help! Thanks.

# Answer
> 0 votes
You can force clean urls to be `Off` with the following line in your `settings.php` file. Add the following to the end -- this settings overrides even whatever is in your database; be sure to remove it later.

```
/* Turn off clean urls */
$conf['clean_url'] = 0;

```

Whether or not your webserver supports Clean Urls depends on its' configuration. I recommend reviewing the Getting Started with Clean URLs Guide.

# Answer
> 0 votes
it's not solved issues with drupal core

after panic search i use this module

https://www.drupal.org/project/imageinfo\_cache

---
Tags: users, media, .htaccess, uri
---


# Question
Title: Cannot post new content after installing varnish
Our drupal 7 site was running so slow it was almost unresponsive, so I had to install varnish 2.1.5 this weekend. I got it up and running, and everything is now lightning fast, users can login and everything else is good... except that none of our authors can post new content.

When new content is posted, whether it's from the admin overlay or the actual `node/add/news` path, the URL just reloads and nothing happens. The form data is all in the Request Payload, the SESSION cookie is set, Varnish supposedly isn't caching... and yet nothing happens. I even installed the varnish module for drupal, but that only seems to handle reporting, and not actually doing anything.

Here's my default.vcl file.

I'm not seeing anything suspect in the vcl, but it certainly seems to be screwing something up.

**Edit**: I should point out that I don't have any issues changing settings in admin, or doing anything else, other than posting content, so it's not like all forms are broken. It might have something to do with ckeditor which is only present on the new content pages, but that seems like a stretch to me.

**Edit 2**: Realized I can create new blocks as admin, which uses the ckeditor which means that doesn't have anything to do with it. No new entries are getting put inserted into the `node` table and there's nothing suspicious in the watchdog logs.

# Answer
> 1 votes
I finally found a solution. Inside my `default.vcl` file I added the following block at the top of `sub vcl_recv`:

```
sub vcl_recv {

  # forward request directly to Apache if SESSION cookie is set.
  if (req.http.Cookie ~ "(SESS[a-zA-Z0-9]*)=") {
    return (pass);
  }

  ... # whatever else you need to do in vcl_recv
}

```

Basically I'm just checking to see if my session cookie is set (anyone else reading this might have one formatted differently) and if so, forwarding it to Apache. This seems to have fixed the problems as new content can be posted again. Not really sure why the elaborate cookie filtering I had in place (and which was working in every other case except posting new node content) didn't work, but this seems to be the solution, even if it feels a little heavy handed.

# Answer
> 0 votes
Not sure if these will help you at all, but I've had my share of tangling with varnish and a few things that have helped me are:

Install the Varnish module if you haven' yet.

You might want to also look into using secure pages to force drupal to grab any admin or node forms in https (note you will need to enable ssl on your server if you haven't done so already). I had an issue myself with bots trying to login to my site. I discovered that by using https I could bypass the cache servers. Might be worth a try to see if that clears up your issues.

---
Tags: 7, proxies
---


# Question
Title: Feed Import Products ( Commerce ) and Products Category ( Node Page )
I need to create a CSV feed importer to **import both Commerce products and products category node using single table** and I am using Commerce Feed Module... when I create it using two different tables I can easily achieve it using Feeds Tamper Module (using explode plug in)

But when I implement single table structure as mentioned in the image... since the title is not unique it creates multiple nodes for each product... Is there any other table structure to implement this..

But what I actually need is:

**Display1- A, SKU1|SKU2|SKU3**

**Display2- B, SKU4|SKU5|SKU6**

**Display3- C, SKU7|SKU8|SKU9**

**Is there no one familiar with this or done this before.. ?? or else I have to refine the question.. ??**

# Answer
> 3 votes
The following CSV template and Feed Import settings will import 1 Product Node with multiple Product Entities being referenced.

**Step 1 - Creating The CSV**

The following example provides the title and product\_variation headers...

**title**: Mapped to the Node Title field in Feed Import

**product\_variation**: Mapped to the Commerce Product Referenced field. Field limit should be greater then 1, so multiple entities can be imported.

```
title,product_variation

Product Example,"product_sku-1|product_sku-2"

```

**Step 2 -Import Node**

The "|" is used to create a **unique entry** using the Feeds Import **Explode** plugin.

The Feed Tamper product\_variation field should have a single Plugin called Explode with the String separator set to "|".

Essentially, the Feeds Tamper Module will prepare the column values into an array, so Drupal can handle the request all awesome like :)

# Answer
> 2 votes
Using Feed to import product into Drupal Commerce is not the best approach. Instead you should use Commerce Migrate which add Commerce Product support for Migrate. Many helpers are available to support for example taxonomy terms, files ...

Many tutorials explain how to use Migrate which is a wonderfull module, but a quite huge.

But here is a sample workflow :

1. Import Category into Taxonomy
2. Import Product Ref
3. Import Product Display and link them to previous imported elements (category and product ref)

To do the last thing, you have to specify the previous source used. Like that, Migrate will be able to "convert" SKU and categories codes to the drupal corresponding elements.

Modules to use :

* Migrate
* Commerce Migrate
* Migrate Extras

---
Tags: commerce, importing-exporting, feeds
---


# Question
Title: Creating a Drupal user with user_save doesn't automatically join an existing CiviCRM contact record
I have a custom module that will create a Drupal user programmatically using `user_save` as follows:

```
  //set up the user fields
  $fields = array(
    'mail' => $email,
    'pass' => $password,
    'name' => $username,
    'status' => 1,
    'init' => $email,
    'access' => REQUEST_TIME,
    'roles' => array(2 => 'authenticated user'),
  );

  //the first parameter is left blank so a new user is created
  $account = user_save('', $fields);

```

I have first done a check using the CiviCRM API to make sure that if an existing contact is already in the database and has a Drupal account associated with it, we don't create a new one. Also I check to make sure the email address isn't registered from the Drupal side.

The problem is, when I create a new user, it is not linking up to an existing CiviCRM contact record that uses the same email address and I'm ending up with a duplicate contact record.

How can I force the site to link to an existing record if the email address is a match?

# Answer
> 1 votes
The function to synchronize Drupal users and CiviCRM contacts is `CRM_Core_BAO_UFMatch::synchronize()`.

Since you're calling `user_save()`, CiviCRM's `hook_user_insert` implementation should get triggered (from `user_module_invoke('insert', $edit, $account, $category);` in `user_save()`.

CiviCRM's `civicrm_user_insert()` checks whether it thinks you are on a CiviCRM callback already, then calls either `civicrm_register_data()` which will in turn call `CRM_Core_BAO_UFMatch::synchronize()`, or `CRM_Core_BAO_UFMatch::synchronize()` directly.

To deal with this you could trace your way through CiviCRM's code (drupal/civicrm.module, drupal/civicrm\_user.inc, CRM/Core/BAO/UFMatch.php) and work out which path your code is triggering; ultimately you want to end up with a call to `CRM_Core_BAO_UFMatch::synchronize()` which passes in the parameters for CiviCRM to correctly match the existing and new data.

You *could* also just call that function directly from your custom code; that might be less robust as in future you might end up triggering the synchronize call twice ...

---
Tags: 7, civicrm, users
---


# Question
Title: Give non-administrator users acces to node-class
I have installed "node-class" on my drupal webiste. As an administrator, i can assign a class now to a node, but other verified users can't...?

# Answer
> 0 votes
Here is a framework for a module to add that permission:

In your contrib module folder, add the folder `node_class_perms` and add these files within that folder:

```
node_class_perms.info
node_class_perms.module

```

in `node_class_perms.info` add this:

```
name = Node Class Perms
description = Alters permissions for Node Class.
core = 7.x
dependencies[] = node_class

```

in `node_class_perms.module` add this:

```
<?php

function node_class_perms_permission(){
  return array(
    'administer node classes' => array(
      'title' => t('Administer Node Classes'),
      'description' => t('Allows node classes to be added to nodes.'),
    ),
  );
}

function node_class_perms_form_alter(&$form, &$form_state, $form_id) {
  // Check form type && if user_access is ok
  if (isset($form['#node']) && ($form_id == $form['#node']->type . '_node_form') &&
    user_access('administer node classes')) {
    // Add form elements in vertical tab to node settings.
    if (!isset($form['node_class'])) {
      $form['node_class'] = array(
        '#type' => 'fieldset',
        '#title' => t('Node Class settings'),
        '#description' => t('Assign CSS classes to the node.'),
        '#collapsible' => TRUE,
        '#collapsed' => TRUE,
        '#access' => user_access('administer node classes'),
        '#weight' => 80,
        '#tree' => TRUE,
        '#group' => 'additional_settings',
        '#tree' => TRUE,
        '#attributes' => array('class' => array('node-class-form'))
      );
    }

    // Get css attribute information
    $attributes = node_class_attributes($form['#node']);

    // Check CSS exists in DB to prepare SQL update
    if ($attributes) {
      $form['node_class']['existing_css'] = array(
        '#type' => 'hidden',
        '#value' => '1');
    }

    $form['node_class']['css_class'] = array(
      '#type' => 'textfield',
      '#title' => t('CSS class(es)'),
      '#default_value' => $attributes,
      '#description' => t('Separate classes with a space.'));
  }
}

```

Now install the module, then add the permission 'Administer Node Classes' to the role you want.

You can tighten the permissions if you want, but as the node edit form has already gone through a basic node-edit permission it really is not necessary.

---
Tags: nodes
---


title: Making Panel-Col-last the first

text:
# Question
Title: Making Panel-Col-last the first
I have a 2-column panel (Regular, not stacked). I've made it responsive and it appears allright in mobile view `@media screen and (max-width: 519px) {width: 100%;}`.

The only problem is that my site is a **Right to left** one, and therefore, What you guys call "Panel-col-first" appears last in mobile view and it's seems Illogical... What is the way to change it, specifically for that particular panel?

Btw, CSS games (Float) didn't help one bit, so I'm looking for a another way, may it be customization of other files.

# Answer
The control over the Panel-col's (Panel columns) can be maid manually via the relevant TPL file (each one of the natural Panels' layouts has it's own TPL).

The TPL files are stored at `sites\all\modules\panels\plugins\layouts`. Check there for the layout you use for your panel.

At my case, I've edited the layout "twocol". It's TPL is inside it's directory (also named "twocol").

There I've changed:

```
  <div class="panel-panel panel-col-first">
    <div class="inside"><?php print $content['left']; ?></div>
  </div>

  <div class="panel-panel panel-col-last">
    <div class="inside"><?php print $content['right']; ?></div>
  </div>
</div>

```

To:

```
<div class="panel-panel panel-col-last">
    <div class="inside"><?php print $content['right']; ?></div>
  </div>

  <div class="panel-panel panel-col-first">
    <div class="inside"><?php print $content['left']; ?></div>
  </div>
</div>

```

After I did this flip, I still haven't seen the change in responsive mode... This is because a change had to be made in the CSS file also... The CSS change is basically comprised of a `float:` change, and a `media screen and ()` change. Inspect each Panel-pane to get more info on the float and width and then make these, and any other needed changes, in the CSS file.

This manual editing seems to me to be the only way for RTLization\flipping the layouts. I hope the developers of the module would make a more "friendly" option for RTLization.

Note: Better make a backup of the **edited** versions of your files and store them outside the sites\all\modules\Panels folder - This could save time in case a Panels update would delete them; Even though this action is relatively short.
> 1 votes

---
Tags: theming, panels
---


# Question
Title: Drupal 7 - Output taxonomy terms on a node?
Currently I want to output the taxonomy term of the current node I'm viewing. I have an Article content type and I created a view block placed it in the footer. Now in this view I'm using PHP Field and I want to output the taxonomy terms on the current page. Right now I know menu\_get\_object() can get you the node ID of the page, but I'm not sure how would one get the taxonomy terms of the current page?

I was thinking of doing a node\_load() on the nid of the page and then parse the taxonomy array then fetch the TID then do another function to grab the Taxonomy name. Any other easier way of doing this?

# Answer
You don't need php field for this.

On the right side click on Advanced, under RELATIONSHIPS add "Content: Taxonomy terms on node".

On the left side add a new field. Search for taxonomy and you should see a Taxonomy term name field that is now available thanks to the relationship.
> 4 votes

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


# Question
Title: Views to use currentlylogged in UID or override via URL
I have followed this:

Drupal 7 views, filter by owner

I have a situation where I want the view to show only results by author UID of currently logged in user and/or have the URI explicitly provide the UID.

I can get one or the other to work but not both -- the URI scheme I have is:

http://mydomain.local/myproject/%/test/test.html

I was thinking the placement of the % might affect the results -- it does not.

Ideally when someone access the page:

http://mydomain.local/myproject/test/

And they are logged in the see the results specific to them

When someone accesses the page:

http://mydomain.local/myproject/3/test

The see only the results for the specific user UID = 3

Any ideas???

# Answer
> 1 votes
I think what you're going to need to do is clone your display. One display using path 'myproject/test' where you contextual filter uses 'Provide default value' when the filter is not in the URL, with 'User ID from the logged in user' as the type.

The other display will use the path 'myproject/%/test' and since the filter in this case IS provided by the URL, you can do something like 'Show "Page not Found"' if the filter value is not provided by the URL. You'll probably also want to specify a validation criteria using the numeric validator with 'Show "Page not found"' as the action to take if it doesn't validate.

# Answer
> 1 votes
Here is how I would do it.

You need views php for this https://www.drupal.org/project/views\_php

1) On your page view add a block.

2) click on your contextual filter and scroll all the way down. You will see a blue "**MORE**" button. Click on it and scroll all the way down again. You will see a check box that says, "**Allow multiple values**" check mark it and **click APPLY**.

3) **If you want to test it**, put your contextual filter on "Provide default value" then "fix value" and type two user uid with a + in between them. Ex: 1+2. After seeing that it works, put it back on **Display all results for the specified field**.

4) Now **go back to your page view**. Add user uid as field. It should show the user uid based on the % value, exclude this field from display.

5) Add a new field, Global: PHP.

Leave value code empty and **under output code type**

> NOTE: We are going to use the global user variable to get the current logged in user info. We are also going to use print views\_embed\_view('my\_view', 'block\_1', $arg1, $arg2); to render the view.

```
<?php
global $user;
print views_embed_view('my_view', 'block_1', $user->uid+$row->uid);
?>

```

> NOTES:
>
> make sure the block\_1 matches the machine name, which is found under **OTHER** of your block view.
>
> $user-\>uid is from the logged in user and $row-\>uid is the uid of the % which we excluded

If you are not able to follow this let me know and I can provide you with an export view example.

---
Tags: views
---


# Question
Title: Is there an existing D7 UI solution to control the content of emails sent by the system?
On most of the projects I am working on, I have set up several different emails with the HOOK\_mail. On top of that you have the default user emails provided by Drupal.

What I am looking for, is an admin UI that would list existing emails and allow admins to edit their content. A bit like what you can do with the default user emails except that I want to be able to use the wysiwyg editor as well.

I started building something custom, but I wonder if there is already something out there. I guess the Message module could potentially do the trick for custom emails but I have never seen it implemented this way.

# Answer
Try out the **Mail Editor** and see if that's what you are looking for
> 1 votes

---
Tags: 7, emails
---


# Question
Title: How to register multiple member in one civicrm membership sign up form?
I have a special promotion price set for member: Register 1 new member is USD 500, register 2 new members in one-time is USD 800.

In my membership sign up form (created using contribution page), I would like the user to enter 2 member details during sign up.

I found this function in event page, where user can register multiple participants in one event, and make payment. But, the payment can't extend the membership period and can't create new membership.

I tried to adjust my price set setting by changing "used for" option, but it shows error of "If you plan on using this price set for membership signup and renewal, you can not also use it for Events or Contribution."

By selecting it using for membership, I can choose the price option to have different number of terms. But, this can't be used in event page which allow multiple registration of participant / member.

Is there any way I can register multiple member in one membership sign up form?

# Answer
I don't think you can do this directly within CiviCRM via the user interface. I get around this problem by using the webform (https://www.drupal.org/project/webform) and webform\_civicrm (https://www.drupal.org/project/webform\_civicrm) modules. Using this you have a far more flexible approach, and can produce a sign-up form that can create memberships for multiple contacts.

I've never understood why CiviCRM, which has a membership management as a core function, does not provide this functionality itself.
> 3 votes

---
Tags: 7, civicrm
---