# Question
Title: Better exposed filters override -any- only working on one filter at a time
I have a view on a Drupal 7 site which brings in all content from 3 content types, which all have 3 different entity reference fields attached to them in order to relate them to specific areas of the site. On the view, I need to beable to filter by the 3 content types, which i have done by creating a filter on type with the 3 options. For the 3 enitity reference fields I also need to be able to filter on all the references but also have an "Any" option to enable it to show all. Due to the design of the website I need the "Any" option to have a friendly title rather than any, which I have implementing using Better Exposed Filters. For some reason the Override any feature of BEF will only override 1 field. And completely ignores the other 2.

It is working on the final filter. If i remove this filter it will work on another one, but never more than one at a time. Is there a setting I'm missing or is this a bug?

# Answer
The issue has been fixed and patched, it hasn't been added to a release though https://www.drupal.org/node/2260691
> 2 votes

# Answer
I tried this kind of configuration with more then one exposed filter, yes its only overriding label for last exposed filter. May be a bug, Why not simply modify **-Any-** option label with `hook_form_BASE_FORM_ID_alter()`

```
function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'YOUR_VIEWS_MACHINE_NAME') {
    $form['FIRST_EXPOSED_FILTER_']['#options']['All'] = t('-NEW ANY LABEL');
    $form['SECOND_EXPOSED_FILTER_']['#options']['All'] = t('-NEW ANY LABEL');
    // and so on.
  }
}

```
> 2 votes

# Answer
It's a bug described here and there is a patch that resolves the issue here.
> 1 votes

# Answer
Here is the temporary JavaScript solution I applied which takes the first child of the select list and changes its HTML.

```
$('.form-item-field-client-target-id select option:first-child').html('Who we work with');
$('.form-item-field-services-target-id select option:first-child').html('Services');

```
> 0 votes

# Answer
More generic JS solution:

```
$('#SELECT-ID option[value="All"]').text('Whatever you want');

```

This will ensure that only the '- Any -' option will get changed and works on a case-by-case basis when you want to use a label in place of the '- Any -' text.
> 0 votes

---
Tags: views
---


title: Finding out template

text:
# Question
Title: Finding out template
I'm working on this web site which I need to make changes to the heading part and I need to know which template or file is generating it so that I can add a slogan. My first attempt was using theme developer. However, it crashed the site so I had to disable it. Is there any other way I can track down the responsible template?

Drupal 7.0

# Answer
You are looking for Theme developer module:

> Firebug for Drupal themeing. See the screenshot and screencast. Note that this module injects markers into the DOM to do its magic. This may cause some themes to behave erratically and less capable browsers may make it worse (especially IE)/. Enable it when needed, and disable it afterwards.

---

# If it is crashing your website

You need to upgrade. You are at 7.0, current version is 7.31. You are **31** minor **versions behind**. And some of them was **security updates**. So you probably should upgrade anyway.
> 1 votes

---
Tags: theming
---


# Question
Title: Smart quotes creating a problem with anonymos user role
I have create a view. The content of the view loads fine when logged in as admin. But in some of the content when you copy paste from MS Work, certain characters changes.

For e.g. `"` becomes

Now the content which contains such characters is not displayed in that view.

But when logged in as admin, I see those content. What could be the problem ?

I checked using devel. The number of results which are fetch is different. Those with special characters are not fetched when viewing as anonymous user.

# Answer
> 1 votes
Without more information it's hard to tell exactly's going on but there's a couple things that come to mind:

* Copying and pasting from MS Word/other rich text editors is notoriously problematic and both TinyMCE and CKEditor have built-in settings for pasting data from Word & stripping the extra formatting
* In case you're not using any WYSIWYG you should always paste your code in Notepad or another plain-text editor and then re-copy it to lose the extra formatting
* Finally, I don't really think it applies to viewing content at all but the visibility thing might have to do with the text-format used in the body field, it's common to edit content using Full HTML and then users without access to it (only Filtered HTML for example) can't edit it

---
Tags: views
---


# Question
Title: How to integrate JS / CSS only on specified Pages / custom content types
I would like embed my module JS / CSS files only in specified cases. Like on a /url/ or if a custom content type is rendered?

# Answer
The concept given by Molot is good. Because url can be changed any time.

Still you can add the css and js file using hook\_preprocess\_page or yourtheme\_preprocess\_node in your template.php of active theme.

```
function yourtheme_preprocess_node(&$vars) {
// Add JS & CSS by node type
if( $vars['type'] == "your-node-type") {
drupal_add_js( /* parameters */ );
drupal_add_css( /* parameters */ );
}

```

where **yourtheme** need to be replaced by the name of the your active theme. Please clear cache for changes to reflect.

Hope it will work for you.
> 2 votes

# Answer
You can use hook\_form\_alter(if you're changing the form for the content type) and put it in your theme's template file to target specific node types.

You can also target theming(from the official documentation) for certain node types by adding templates for them.

As a rule, you should avoid injecting JS/CSS into pages.

Lastly, I would use the theme's CSS or SASS files to add your CSS for caching and aggregating purposes.

Clear your Drupal and browser caches, for the changes to take effect.
> 0 votes

---
Tags: javascript, theming
---


# Question
Title: prepare() function doesn't work well in migrate module
This is my code to move a few records from a table to a Drupal content type (called CT1)

```
<?php
class CT1Migration extends Migration {
    public function __construct() {
        parent::__construct(MigrateGroup::getInstance());
        $this->description = 'Imports CT1';
        $fields = array(
                'id',
                'subject',
                'content',
        );

        $query = db_select('tbl', 'qf')
        ->fields('qf', $fields);

        $this->source = new MigrateSourceSQL($query);

        $this->destination = new MigrateDestinationNode('porseman');

        $pkmap = array('id' => array('type'  => 'int',
                'unsigned'  => TRUE,
                'not null'  => TRUE,
                'alias'     => 'qf'));

        $this->map = new MigrateSQLMap($this->machineName, $pkmap, MigrateDestinationNode::getKeySchema());
        $this->addFieldMapping('title','subject');
        $this->addFieldMapping('field_CT_body', 'content')->arguments(array('format' => 'full_html'));
    }

    public function prepare($row) {
        $row->title = "This is title 1";
        $row->field_CT_body = t("This is body");
    }
}
?>

```

CT1 has two fields, `title` and `body`. I need to perform some settings before the migration so I use `prepare()` function. From `function prepare($row)` function I expect the values of `title` and `field_CT_body` of all of the imported records to be `This is title 1` and `This is body` while after the migration the `title` correctly gets this string (`This is title 1`) as its value but `field_CT_body` has no value at all.

if I remove the `prepare` function it migrates the records successfully.

# Answer
> 1 votes
Unfortunately you can't set the value directly like that, you need to reference the language and delta in the classic, hated method:

```
public function prepare($entity, stdClass $row) {
  $row->title = "This is title 1";
  $row->field_CT_body[LANGUAGE_NONE][0]['value'] = t("This is body");
}

```

Note: This function takes 2 params, the entity object being built and the source row. So, since we're altering the entity object, we gotta manipulate it as such. (I'm not sure, but you might be able to wrap that object in a metadata wrapper in order to use the cleaner API)

Also, please note that the "value" key will depend on the field type in use.

Note: untested code but it should be fine! :)

---
Tags: nodes, migrations
---


title: CiviCRM Membership form with login

text:
# Question
Title: CiviCRM Membership form with login
I would like to sell subscriptions on a site and have the person logged in automatically.

I have setup the contribution page and it works fine. The person at the end of the process doesn't get a drupal account or become logged in. We created a custom module to create the person's account at the end of the process. We haven't found a way to log them in though.

Ideally the person can register/pay/be logged in as one step. We are afraid that if we get them to register a drupal account, confirm the account and then pay the membership we will lose a lot of people as it is 'too complicated'.

# Answer
> 1 votes
To programatically user from code, you need to replicate what `user_login_submit` and `user_login_finalize` are doing:

```
function user_login_submit($form, &$form_state) {
  global $user;
  $user = user_load($form_state['uid']);
  $form_state['redirect'] = 'user/' . $user->uid;

  user_login_finalize($form_state);
}

function user_login_finalize(&$edit = array()) {
  global $user;
  watchdog('user', 'Session opened for %name.', array('%name' => $user->name));
  // Update the user table timestamp noting user has logged in.
  // This is also used to invalidate one-time login links.
  $user->login = REQUEST_TIME;
  db_update('users')->fields(array('login' => $user->login))->condition('uid', $user->uid)->execute();

  // Regenerate the session ID to prevent against session fixation attacks.
  // This is called before hook_user in case one of those functions fails
  // or incorrectly does a redirect which would leave the old session in place.
  drupal_session_regenerate();

  user_module_invoke('login', $edit, $user);
}

```

Just replace `$form_state['uid']` with UID you generated in earlier step, and maybe use other way to redirect.

---
Tags: users, civicrm
---


# Question
Title: How to add data to a message type custom field that's inherited by all message instances?
I'm using the Message module, and I have some message types. Each message type needs to have a node reference field on it whose value would not change for the entire message type. But different values per message type.

Right now I can create a new message type with a field on it, but the instances of messages are generated programmatically on demand as sent.

What I ultimately need to do is generate a token based on the value of this field.

So how would I go about creating a value that would be inherited by all instances of a message type? Ideas?

Any advice useful. Sort of don't know what functions would be useful here and the docs really don't address this use case.

# Answer
I didn't actually figure this out. I probably could have by looking at the way commerce orders get attached via entity reference to messages and done that. Instead, I used the commerce order that was attached to the message, which had the commerce store ID, to load the field on the organic group that was referencing the store and then add that field as a token.
> 0 votes

---
Tags: entities, tokens, message-subscribe
---


# Question
Title: Drupal Registration Module Email Registrants tab
The character count for the subject field in email registrants is 40 characters and that is hard coded into the module.

I need some guidance for figuring out how to change that. I am not a hard core developer and do not know the best way to change that without going into the module code.

Can anyone help guid me to what could be done?

Thanks Tim

EDIT\*** I am in Drupal 7 Registration module 7.x-1.3. Under Manage Registration/Email Registrants/ - there is a subject field. In the modules registration.forms.inc file on line 354 it the character limit size set to 40.

I am trying to figure out how to change it without editing the module code.

Thanks

# Answer
> 0 votes
Not being a developer I had to figure this out using hook\_form\_alter. Too some digging and a little help.

```
function ecg_registration_form_registration_registrations_broadcast_form_alter(&$form, &$form_state) {
  //dpm($form);
  $form['subject'] = array(
    '#type' => 'textfield',
    '#title' => t('Subject'),
    '#description' => t('The subject of the message.'),
    '#required' => TRUE,
    '#size' => 80,
    '#maxlength' => 80,
  );
}

```

Hope that helps someone.

---
Tags: users
---


# Question
Title: Rules Custom Condition for registration capacity
I am trying to learn Rules and adding a custom condition. I need help to figure out what I am doing wrong.

My Condiiton set up:

```
function rules_example_capacity_condition_info() {
   $conditions = array(
     'rules_example_action_count_capacity' => array(
       'label' => t('Print capacity count on page'),
       'group' => t('Rules examples'),
       'parameters' => array(
         'count' => array('type' => 'value', 'label' => t('registration event count')),
         'capacity' => array('type' => 'value', 'label' => t('registration event capacity')),
         ),
       ),
     );
     return $conditions;
 }

```

and the function that calls it...

```
function rules_example_action_count_capacity($count, $capacity) {
    $reg_count = reg_count_load($count);
    return($reg_count->capacity == $capacity) ? true : false;
}

```

I am trying to determine the count (how many people have registered so far) and the capacity. When the count and capacity are the same send an email.

I am not a developer so this is a little bit of a struggle. I found this series (http://nodeone.se/node/28) which is helpful, however there are so many smaller things I might be missing. Please help if you can. I am hoping that this will help more then just myself.

Thanks Tim

# Answer
> 1 votes
Looking at your function, I believe you need to rename it to something like mymodule\_rules\_condition\_info. The hook you are trying to implement is `hook_rules_condition_info()`. Did you find that your custom condition was showing up when you were editing a rule?

```
function MYMODULE_rules_condition_info() {
   $conditions = array(
     'mymodule_event_is_at_capacity' => array(
       'label' => t('Event has reached maximum registrations'),
       'group' => t('MY MODULE'),
       'parameters' => array(
         'registration' => array(
            'type' => 'registration',
            'label' => t('The registration event'),
           ),
         ),
       ),
     );
     return $conditions;
 }

```

Semantically you may want to call your condition 'mymodule\_event\_is\_at\_capacity' and it should only need one parameter which is the capacity that you will provide in the Rules UI.

The function you will be writing `mymodule_event_is_at_capacity($capacity)` will query for the number of (active) users in Drupal, and if it is greater than or equal to $capacity, it will return TRUE.

All of this can be kicked off by add a new Rule that reacts on the "After saving a new user account" event.

# Answer
> 0 votes
Al Gorgeous Thank you for you help. Below is the final working example.

So, I had a lot to learn here. I have some help figuring this out.

I had to create a custom condition for Rules and then figure out the true/false statement to trigger the email. The hard part was having to figure out how to bring in the entity\_id. I found this hacked way and it worked.

Hacked way to to grab the entity\_id - How do I get entity\_type and entity\_id from any entity page?

```
function ecg_registration_rules_condition_info() {
  $conditions = array(
  'ecg_registration_event_is_at_capacity' => array(
       'label' => t('Event has reached maximum registrations'),
       'group' => t('MY MODULE'),
       'parameters' => array(
         'registration' => array(
            'type' => 'registration',
            'label' => t('The registration event capacity'),
           ),
         ),
       ),
}

```

The function that tracks and triggers the capacity count.

```
function ecg_registration_event_is_at_capacity($registration) {
  $backtrace = debug_backtrace();
  foreach ($backtrace as $caller) {
    if ($caller['function'] == 'field_attach_view') {
      $entity_type = $caller['args'][0];
      $entity = $caller['args'][1];
      // do stuff with entity
      break;
    }
  }
  $entity_id = $entity->{'nid'};
  $count =  registration_event_count($entity_type, $entity_id);
  $settings = registration_entity_settings($entity_type, $entity_id);
  if ($settings['capacity'] == 0) {
    return FALSE;
    break;
  }
  if ($count >= $settings['capacity']) {
      return TRUE;
  }
  return FALSE;
}

```

Hope this helps someone else.

---
Tags: rules, database
---


title: Splitting up a Drupal database

text:
# Question
Title: Splitting up a Drupal database
Is it possible to split the Drupal database into multiple databases. For example I have one database having the watchdog table and another database having all the other tables?

I know if I created my own tables I could store them in a separate database and use the following:

How to connect to multiple Databases in Drupal 7?

```
db_set_active('your_second_db_alias');
$query = db_query("SELECT * FROM your_table");
db_set_active();

```

# Answer
> 0 votes
For watchdog specifically, you could use hook\_watchdog to route the message where you need it, and don't use the dblog module (dblog's hook\_watchdog) if you don't want it logged to the default database.

For other (core or 3rd party) data, it depends on whether there is an appropriate hook to interrupt the intended functionality.

# Answer
> 0 votes
I think you'd be better served using Syslog for logging without cluttering your database.

---
Tags: 7, database
---


title: Trying to send a <div> with webform

text:
# Question
Title: Trying to send a <div> with webform
I have a Webform that does some calculations (javascript) based on user selections, which i would like to send along with the user-selectable fields to a user's email.

Is it possible to append these div's to the HTML email along with the fields?

# Answer
You could add a regular webform field to capture the calculation result, filling it via Javascript. Then you hide the field via CSS.

Storing a bunch of html has a security risk though.
> 0 votes

# Answer
You can create a custom module with the next hook:

`function yourmodulename_webform_submission_presave($node, &$submission){
 ...
}`

var $node contains the webform node on which this submission was made and submission contains the webform submission that is about to be saved to the database. So, that way you can get the values from submission and alter them.
> 0 votes

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


# Question
Title: Running an "is all of" filter on a field collection
I'm currently working with a field collection lets call it Certificates. Certificates contains the following fields... Certificate Type, Certificate Number, Expiration Date, Etc. I have a content type called Applicant that contains the field collection Certificates. Ideally, I'm trying create a view that allows for a "is all of" filter for the various certificates. We are trying to filter candidates by multiple certificates at the same time. To complicate this further, I've been asked to do this in a single multiselect drop down using chosen. By adding the field-collection as a relationship, I am able to add a Chosen multiselect that works correctly with the "is one of" operator, but it won't work with the "is all of". I think that the reason for this is that it seems like the certificate type is overriding the actual field-collection in order to display the certificate. Looking for suggestions. Any help will be greatly appreciated!!!!

# Answer
I have a solution that's a bit of a work around, but seems to work fine. I ended up using the same relationship multiple times and increasing the delta value by 1 with each new relationship which pulled in each option in the subcategory (think first field in the field collection). I then grouped the fields and used a combine filter to run the "is all of" search. Seems to work great and isn't overly resource intensive. This will give you a 1 to 1 result based on whatever is in the the field collection field item you build the relationship off of.

Hope this helps.

Best, Shawn
> 0 votes

---
Tags: views, entities
---


# Question
Title: Preprocessing function for specific view by name
I'm using drupal 7.29 . I'm trying to write the preprocess function for a specific view named front-page. I have written the following functions in my template.php file:

```
function bartik_sub_preprocess_views_view__front_page(&$variables) {

  kpr($variables);
}

```

The function for preprocessing view works normally (without the \__front\_page at the end), but the above function isn't being called. I did create the corresponding .tpl.php (views-view--front-page.tpl.php) file which is used but the function still isn't being called. I watched a couple of tutorials where the preprocessing function for a specific view was written like this and it worked, any ideas why this isn't working?

# Answer
> 0 votes
you have to implement `hook_theme` function to make views aware of your custom preprocess theme function. You can find a tutorial on this here: http://www.appnovation.com/blog/theming-view-within-your-module

# Answer
> 0 votes
I have been trying for a couple of days and this solution is not working. The function

```
function bartik_sub_theme($existing, $type, $theme, $path) {
  kpr($theme);
}

```

isn't being called. In a tutorial I watched (https://www.youtube.com/watch?v=1Cfc11\_sb5M) the guy just defines the preprocessing function and that is it. Even the Devel modul is suggesting

```
theme_hook_suggestion (String, 22 characters ) views_view__front_page

```

I really don't know what I am doing wrong. Any idea?

---
Tags: views, theming
---


title: Drush: how to set access to MySQL

text:
# Question
Title: Drush: how to set access to MySQL
When I run command "drush status" I cannot see any MySQL settings (user, password or database).

I cannot use commands like "core-quick-drupal" because it requires access to MySQL, before /sites/default/settings.php is created.

How can I set such MySQL connection?

I have installed drush in linux in directory /user/share/php

When I install Drupal from web browser interface, I can see that database support is enabled. I have problem only when installing drupal via drush

# Answer
core-quick-drupal doesn't require mysql, it would use something like sqlite. drush site-install allows you to specify config options like the mysql connection. For example:

```
drush site-install mysite --db-url=mysql://user:pass@server/dbname

```
> 2 votes

---
Tags: 7, drush, database
---


# Question
Title: how can I make date fields come out in other languages in webform with drupal 7
using drupal 7 , and Webform 7.x-3.18 + 3-dev I need my date field to come out in spanish, mes/dia/ano

but it keeps on coming out with month/day/year

How can I fix this? thanks

# Answer
> 0 votes
fixed, I was logged in as an admin and had admin language set to english

---
Tags: webforms
---


title: Class 'views_plugin_display' not found

text:
# Question
Title: Class 'views_plugin_display' not found
Getting this

PHP Fatal error: Class 'views\_plugin\_display' not found in ../sites/all/modules/contrib/media/includes/media\_views\_plugin\_display\_media\_browser.inc on line 18, referer: ..

Any ideas how I can fix that?

Thanks, Dmytro

# Answer
> 0 votes
If you have Views enabled, this might be an issue with Media. This has been previously reported the issue queue for the project, and there it was suggested to reinstall the latest version of the Media module, in case the files had become corrupt.

---
Tags: media
---


title: Hiding Field(s) if Date is Expired

text:
# Question
Title: Hiding Field(s) if Date is Expired
I'm using Drupal 7 date field. Using views, when the date has expired, the page goes to a section labeled 'past events.' In the template page, the date and time are both separated for instance. $date\_output and $time\_output. I need to hide the time field after the date has expired. any ideas?

# Answer
> 0 votes
If your date is in one of the supported date/time formats, you can use strtotime() and date() to compare. Wrap the printing of $time\_output in an if statement. For example:

```
if ( strtotime($date_output) > date() ) {
  // $date_output is greater than now, eg, not expired
  print($time_output);
}

```

If $date\_output is already a timestamp, no need to use strtotime()

---
Tags: javascript, datetime
---


# Question
Title: Troubleshoot hook_library_alter() not being called for the jQuery Update module
I have the jQuery Update's development shapshot version 7.x-2.x-dev installed and enabled. The version jQuery configured in UI is not being imported. As result, it is importing version 1.4.4 instead of the version I specified. Debugging, I noticed that `jquery_update_library_alter()` is not being called. In meanwhile, my custom `hook_library_alter()` is called, and I use that as temporary solution until I figure out why the hook implemented by the jQuery Update module is not called.

```
function MODULE-NAME_library_alter(&$javascript, $module) {
  module_load_include('module', 'jquery_update');
  jquery_update_library_alter($javascript, $module);
}

```

This is first time I encounter a situation where hooks are not called. Where are hooks attached to and where are they called from? How would you approach to troubleshoot hooks? Where can I check all registered hooks?

# Answer
> 1 votes
I had this problem as well and I tracked it down to a custom module calling `drupal_add_js()` right at the top of the module file. This meant that `drupal_get_library(system, jquery)` and in turn `module_implements(library_alter)` were getting called before the `jquery_update.module` file had a chance to get loaded and hence `jquery_update_library_alter` wasn't defined yet.

To find this I put the following lines into `drupal/include/module.inc` and cleared the cache.

```
...
function module_implements($hook, $sort = FALSE, $reset = FALSE) {
    if ($hook == 'library_alter') { debug_print_backtrace(); exit; }
...

```

You might have some other problem, but a call to `drupal_add_js` to early in execution was my issue.

---
Tags: hooks, javascript
---


title: global variable for path

text:
# Question
Title: global variable for path
In my project I want to provide path of some files from root directory. Path has repeated 4 to 5 time in one module so I am thinking that put one global variable and access that variable in same module?

I have try `(dirname(__FILE__).'\sound\new'); realpath; drupal_realpath ; pathinfo;` .

# Answer
> 0 votes
In Drupal 7 you can use variable\_set and variable\_get to make the variable global.

> * **Set the variable**
>     + variable\_set('MYMODULE\_PATH', base\_path() . drupal\_get\_path('module','YOUR\_MODULE\_NAME'));
> * **Get the variable**
>     + variable\_get('MYMODULE\_PATH');

Also you can assign multiple values the variable, if you dont want to create multiple variables

```
  variable_set('MYMODULE_PATHS',
    array(
      'm1' => base_path() . drupal_get_path('module','YOUR_MODULE_NAME'),
      'm2' => base_path() . drupal_get_path('module','YOUR_MODULE_NAME'),
      ...
    )
  );
  $values = variable_get('MYMODULE_PATHS');
  //Read as $values['m1'], $values['m2'] ..

```

# Answer
> 0 votes
You can get the path using drupal default function **drupal\_get\_path()**;

It return path to any module or theme from root of installation.

If i want to access path of any module e.g. **mymodule**

Then i just need to use,

```
$path = drupal_get_path('module','mymodule');   //path to module directory

```

If i want to access path of my theme e.g. **mytheme**

```
$path =  drupal_get_path('theme','mytheme');   //path to theme directory

```

Now you can make the path variable global..

# Answer
> 0 votes
You can declare your global variables with multiple ways: for ex: in settings.php file - `$conf['some_name'] = 'some_value'`, or with variable\_set and variable\_get (these functions store variable in db instead of defining them as global), or with builtin `$GLOBALS` array, etc..

But as Raj10 mentioned above, `drupal_get_path($type, $name)` is the best way to get the path to modules or themes..

---
Tags: uri
---


title: How to add SUM() in Views

text:
# Question
Title: How to add SUM() in Views
Like in the given picture

I would like to find and print the sum along with view results. How can I do that?

# Answer
> 2 votes
Try the Views Calc module

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

Image from module page

# Answer
> 0 votes
You can also "Use aggregation:". This link present in the advanced section of view.

---
Tags: views
---


title: Simple jQuery Slider

text:
# Question
Title: Simple jQuery Slider
I have to create simple image slider WITHOUT Views and other modules. I can use only custom post type slides.

How can I do that?

# Answer
> 2 votes
You need to follow the following steps

* Download the **Slider Plugin** and paste required files in your active custom module(*sites/all/modules/custom/yourmodule/js OR sites/all/modules/custom/yourmodule/css*) OR in theme(*sites/all/theme/yourtheme/js OR sites/all/theme/yourtheme/css*) folder.
* Create a new block in youmoudle using **hook\_block\_info** and **hook\_block\_view** functions.
* Inside **hook\_block\_view()** call a function
```
$block['content'] = 'get_slider';
```
* **get\_slider()** will return the html for the slider. Make sure that the html returned follow the proper structure as mentioned in the Slider Plugin you have chosen. You can find the html example for each slider Plugin, follow the same html structure.
* Add the corresponding JS files using **drupal\_add\_js** and CSS files using **drupal\_add\_css**
* JS file is used to initialize the Slider to run.
* Check your browser console to check errors

# Answer
> -1 votes
Just download any slider script, and use how it is using its images to make it slider.

Just follow through these steps:-

1. First paste the html of slider directly on the page
2. Include the necessary files (js/css)
3. Now fetch the images only of custom post type from database to make it dynamic

Slider will automatically start working. There can be issues with drupal js and slider js files, so avoid including unnecessary files.

---
Tags: javascript
---


title: update drush 6.0 to 6.5

text:
# Question
Title: update drush 6.0 to 6.5
I have drush 6.0 and recently installed drush7 as well with composer. Now i would like to update drush 6.0 to latest release in drush version 6. Is there any work around to achieve?

Thanks, Swaroop.

# Answer
As the instructions say:

> To install Drush 6.x (stable):
>
> ```
> composer global require drush/drush:6.*
>
> ```

Assuming you installed drush that way (using composer):

> To update to a newer version (what you get depends on your specification in ~/.composer/composer.json):
>
> ```
> composer global update
>
> ```
> 1 votes

---
Tags: drush
---


# Question
Title: How to make a non-Drupal page and where to place it?
I need to create a page (it's receipt) which is not drupal-page. How it should work:

1. User clicks the link in "User Menu" or in "User Profile"
2. This link is made from link to custom page itself and user's $POST parameters (name and address fields, for example).
3. This page consists of HTML tags, CCS styles and PHP $POST-parameters and finally creates a PDF (to print).

I know how to make modules and use Hooks (I made custom registration), and I can use Drupal database (normal and fields entries). But how I should realize this task? And where I should place my custom page's file?

# Answer
You need to create a custom module and implement hook\_menu() for you custom page. Here you get details about hook\_menu "https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook\_menu/7".

To get this link on user menu tab use type as 'type' =\> MENU\_DEFAULT\_LOCAL\_TASK And write your page code by calling a function 'page callback' =\> 'user\_details',

create user\_details function and write code for custom page.
> 2 votes

---
Tags: users, 7
---


# Question
Title: Stop rendering custom entity label in view mode
I have declared a custom entity with a schema with a few fields on which is all working as I expect.

I want to remove the label when rendering the entity so have tried the following.

Added some view modes to the entity info hook and although I can see that they exist when I go to manage display none of my entity fields appear. Not sure if this is how it should work or not.

Any ideas?

# Answer
> 0 votes
The below function stops a custom entity label from being rendered based on the view mode.

```
function HOOK_entity_view_alter(&$build, $type) {
  if($type == 'YOUR_ENTITY_TYPE' && $build['#entity_view_mode']['view_mode'] == 'YOUR_VIEW_MODE'){
    $build['#page'] = TRUE;
  }
}

```

---
Tags: entities
---


title: How to join three entities in a view?

text:
# Question
Title: How to join three entities in a view?
I have a Drupal schema where I want a view to display node 'item' results based on fields from an associated 'catalogue' node. Each associated 'catalogue' has a 'catalogue\_ranking' node which is used to order 'item' results. So the join I am looking for is:

items \<== LEFT JOIN catalogue \<== LEFT JOIN catalogue\_ranking

I can manually construct the SQL I need to produce the results as follows:

```
SELECT node.nid, substring(node.title, 1, 20) AS title, field_data_field_catalogue.field_catalogue_nid,
       node_catalogue.nid AS cat_nid, substring(node_catalogue.title, 1, 20) AS cat_title,
       field_data_field_ref_catalogue.field_ref_catalogue_nid, node_cat_ranking.nid AS rank_nid, field_data_field_priority.field_priority_value
  FROM node node LEFT JOIN field_data_field_catalogue field_data_field_catalogue ON node.nid = field_data_field_catalogue.entity_id
                 LEFT JOIN node node_catalogue ON node_catalogue.nid = field_data_field_catalogue.field_catalogue_nid
                 LEFT JOIN field_data_field_ref_catalogue field_data_field_ref_catalogue ON node_catalogue.nid = field_data_field_ref_catalogue.field_ref_catalogue_nid
                 LEFT JOIN node node_cat_ranking ON node_cat_ranking.nid=field_data_field_ref_catalogue.entity_id
                 LEFT JOIN field_data_field_priority field_data_field_priority ON node_cat_ranking.nid = field_data_field_priority.entity_id
  WHERE LENGTH(node.title) > 1 ORDER BY IFNULL(field_data_field_priority.field_priority_value, 0) DESC LIMIT 5;

```

However, I've been going bananas trying to figure out the exact forward or reverse relationships needed to produce the same results using the Drupal view UI. The "Priority" field remains stubbornly blank no matter what combinations I try! What am I doing wrong?

# Answer
You can implement custom relationship using hook\_views\_data\_alter() and define exactly in this hook which fields to use for JOIN - https://api.drupal.org/api/views/views.api.php/function/hook\_views\_data\_alter/7

Example:

```
/**
 * Implements hook_views_data_alter().
 */
function custom_log_views_data_alter(&$data) {
  // Expose uid as a relationship to users.
  $data['custom_log']['uid'] = array(
    'title' => t('User information.'),
    'help' => t('Information related to user who triggered the event.'),
    'relationship' => array(
      'base' => 'users',
      'base field' => 'uid',
      'relationship field' => 'uid',
      'handler' => 'views_handler_relationship',
      'label' => t('User information.'),
    ),
  );
}

```
> 0 votes

---
Tags: views
---


# Question
Title: set specific time to cron for specific php script
Actually i want all unpublish nodes to be delete automatically whose created date is 2 days ago. I can write php script for that and also include that code in **hook\_cron api**.

but i am confused that my site is set to be run cron after every 3 hours and i want that php script to be run after 24 hours. can i set specific cron time for specific job. i dont want change the site cron job time.

# Answer
> 2 votes
Set system cron to every 5 minutes, and use Elysia Cron to manage particular tasks:

> Elysia Cron extends Drupal standard cron, allowing a fine grain control over each task and several ways to add custom cron jobs to your site.
>
> * \[NEW IN 2.0\] **Set the timings and frequencies of each cron task** (you can run some jobs every day at a specified hour, other only monthly and so on...). For each task you can simply choose between some frequently used options ("once a day", "once a month" ...), or use a powerful "linux crontab"-like syntax to set the accurate timings. You can even define your frequently used options to speed up site configuration.

# Answer
> 0 votes
I would suggest you to do it by including condition in your code whether to execute particular part or not in each run.

On first run enter time value in database then in each run check if current time and db time has difference of 24 hrs or more then only execute that part, otherwise just skip it.

Hope it works for you.

---
Tags: nodes, cron
---


# Question
Title: Does creating multiple tpl files affect site performance?
I am creating different tpl file for each and every content type. (Including every view)

Is it a good practice? And does it affect site performance?

Any suggestions?

thanks

# Answer
> 2 votes
It won't make a noticeable difference as long as you disable rebuilding the theme registry on production, enable caching, and follow best practices (e.g. don't execute logic or queries in your templates, and never ever save PHP code in the database). There are quite a few other, more noticeable things you can tweak to improve performance and load time before you get to the level of worrying about the number of templates.

# Answer
> 0 votes
That level of theming is something I've tried to move away from as it can get quite messy in terms of organisation. Also I believe there is a performance hit for loading a lot of templates - this below is specific to `field.tpl.php` but clearly applies more widely:

> However, it takes longer for the server to process templates than to call a function, so for websites with many fields displayed on a page, this can result in a noticeable slowdown of the website.

theme\_field Drupal API

But like @betherwisser says there will be a lot of other things you can look at first.

To summarise: for content types I would think twice about going the tpl route because the Drupal 7 display options are generally powerful enough with a few tweaks in preprocess functions, that way the display is kept in the CMS which makes it more accessible and you avoid the performance hit (however marginal).

Views though I'd probably template as they can be a pain to get looking right any other way, though I'd always try to start with a preprocess function in template.php as it can be really hard to wade through a load of views `tpl` files to find the one that is actually relevant.

---
Tags: theming
---


# Question
Title: Can view file list in IMCE but can't load files
I'm setting up a Drupal 7 multisite. Already have another site running with no problem on same server. I can access IMCE browser (see image below), and can upload but not insert images; clicking on image does nothing. When I hard code link to image into a text field, I get 404 'file not found' error.

Setup is standard:

/www/d7 \[drupal core\]

/www/multisite1 \[symlink to ../d7\]

/www/multisite2 \[symlink to ../d7\]

Within /www/d7, also standard setup: sites/multisite1/files, etc. Everything else including Clean URLs is working correctly, and I've set all permissions per usual. I'm stumped, have tried various mod\_rewrite directives and none have changed anything. Any possibility there's some path corruption in database? Any other suggestions?

# Answer
I know your question is 6 months old and you have probably solved it or found a workaround... but I had exactly the same problem and wanted to share what has worked for me, in case it could help others.

At the beginning I had a default single site and IMCE worked perfectly, a few months later I set up another site in multisite configuration, and IMCE didn't work on the second site : no upload, insert, suppress buttons in the top bar, and no possibility to view images or insert them.

In fact it was not a multisite problem, it was due to a jQuery incompatibility.

Both sites use the jQuery Update module :

* for the default site, the default version is jQuery 1.7
* for the second one, the default is jQuery 1.9 for the front theme (and 1.7 for the admin theme, but IMCE uses the default version).

If I tried to use 1.7 version for the second site, IMCE get to work.

So, in order to still use jQuery 1.9 or newer (needed by the front theme) and have IMCE working, you can use jQuery Migrate Plugin to resolve incompatibilities.

There is a patch for jQuery Update here, I applied it, get to jQuery Update config page, selected "Enable jQuery Migrate Plugin" (with or without the CDN), and it worked perfectly !
> 1 votes

---
Tags: multi-sites, files
---


# Question
Title: View filter - Show content that has 1 field matching another field in current node
I have a content type called **Specifications** which has 4 fields

* *Engine Specifications*
* *Features Specifications*
* *Variation* (exposable filter)
* *Model*

I also have another content type called **Cars** which has 1 field called *Model* too.

I am created a SpecificationsView which displays the content-type **Specifications** as a block in **Cars**.

Is it possible to show in each **Car** the **Specifications** whose *model* matches the current ''**Car**'' node's *model*?

# Answer
> 0 votes
I have done it using entity reference module and some php code in views. All you need to do is use entity reference module make a view that list model taxonomy terms as entity reference display.

Then you need to add a er(entity reference) field in both content type and input in that view you just made then make another view that list specification fields add a relationship to add entity reference model field add a contextual filter taxonomy term id in provide a default value choose PHP code and paste this code :

```
$nid = arg(1);
$node = node_load($nid);
$term  = $node->field_model['und']['0']['entity']->tid;
return $term;

```

Or refine this code by yourself.

---
Tags: views
---


# Question
Title: Import soap webservice xml to node with Feeds?
I have a soap web service which requires authentication to access its various function. I want to call one function of this web service and import that XML to node in Drupal with feeds module.

I am not finding any example of authentication from the Feeds module.

# Answer
I assume you have no access to change the feed provider.

There are couple of additional contributed modules which handle different types of authentication for the feeds module.

This handles regular http authentication, which is more likely with soap: https://www.drupal.org/project/feeds\_httpfetcher\_aa

and this one is for oauth which ia also possible with soap: https://www.drupal.org/project/feeds\_oauth
> 0 votes

---
Tags: 7, importing-exporting, feeds
---


# Question
Title: Set the Contextual Filter: Author uid. to a default user?
I have a view called Map Items showing a list of map markers in a chart.

Info: I have 3 Accounts in my drupal installation called person1, person2, and admin.

I've set the contextual filter to Author uid: User ID from Logged in user. and its working perfectly, but what I want some additional setting that when there is no logged in user I could set person1's map item to show. Right now when there is no logged in user the view shows the map item of admin user and not person1.

How am I going to accomplish this?

# Answer
In contextual filters instead of selecting User ID from Logged in user select php code and write some code like

```
global $user;
if($user->uid > 0){
$uid = user_load($user->uid);

$roles = $uid->roles;
if(in_array('administrator', $roles)){
return 'uid of the logged in user';
//print_r($uid->roles['3']);exit;
}
else{
return FALSE;
}
}
else {
return 'return here person1 uid';
}

```
> 0 votes

---
Tags: views
---


# Question
Title: Is there a way to load the content types using DrupalWebTestCase?
I'm trying to learn how to do testing in Drupal. I'm pretty new with it so maybe i didn't got it right. well, I'm trying to test some views of content types, but to test those views i need to have that content type created when im testing. actually with drupalWebTestCase it's seems it doesn't load the content types that i would have in my normal drupal(except for the basics).

I tried to use simpletest clone but it doesn't work,don't know why, and I don't need all the database for it, just the content types and views.

So... Is there a way to load that content type WITHOUT having to create everything by code? I've a lot of content types some with some complicated fields and loading one by one sounds too harsh to be done.

# Answer
Export your content types and fields using Features. Features creates modules which you can then enable in your Simpletest setUp step.

When you create a feature you are offered the opportunity to add components to it including content types. Features tries to detect related components such as fields that you will require. When your feature is complete you then download it and add it to your project like any other module.

You may need to add on extra Features-related modules such as Strongarm, to help further with initializing your test environment.
> 0 votes

# Answer
Try the SimpleTest Clone module.

SimpleTest performs the test on a clean Drupal installation, so if you have created Content Types they will not be available.

SimpleTest Clone craetes a copy of the database (using a table prefix) and performs the tests over those tables, so all config you have done is present.

Once the tests are donde the extra tables are deleted.

The drawback fo this method is that is a little slower than standard SimpleTest because the table copy operation.

To use SimpleTest Clone just subclass your test class form SimpleTestCloneTestCase class instead of DrupalWebTestCase class.
> 0 votes

---
Tags: 7, nodes, testing
---


# Question
Title: Moving SQLite-D7 Installation to other Server throws Uncaught exception in shutdown function
When I move my Drupal7-Website (with SQLite Database) from my XAMP to another Computer also running XAMP I got the following error message.

> Uncaught exception thrown in shutdown function.
>
> PDOException: SQLSTATE\[HY000\]: General error: 8 attempt to write a readonly database: DELETE FROM {semaphore} WHERE (value = :db\_condition\_placeholder\_0) ; Array ( \[:db\_condition\_placeholder\_0\] =\> 192200923514edf6a15a484.46864520 ) in lock\_release\_all() (line 269 of /Applications/XAMPP/xamppfiles/htdocs/myd7site/includes/lock.inc).

How comes? And how to fix? Thnx!

# Answer
> 2 votes
It seems that the PDO SQLite driver requires that if you are going to do a write operation (INSERT,UPDATE,DELETE,DROP, etc), then the folder the database resides in must have write permissions, as well as the actual database file.

The above information is taken from another answer: https://stackoverflow.com/a/3330616/2171489

I don't use SQLite, but given the error from the PDO driver and the fact that you moved to a different server, it does seem like it could be a file permission problem.

# Answer
> 0 votes
1. Go to database bin folder in xamp (xampp\mysql\bin)
2. Open my.ini
3. Change value of `"max_allowed_packet"` to "256m" (or larger)
4. Save my.ini Now restart MySql through the XAMPP control panel.

---
Tags: 7, database
---


title: Adding drop-down and radio buttons

text:
# Question
Title: Adding drop-down and radio buttons
Is there any module that will help me create a `drop-down menu` and `list` as shown in the following picture ?

I want to connect this with registration page.

# Answer
> 2 votes
Try the Double field module

> Double field is a small module written to provide extensions to Drupal's core Fields. By this module you can split your fields up into two separate parts.
>
> For the moment it includes the following sub-widget types:
>
> * Textfield
> * Select list
> * Single checkbox
> * Textarea
>
> Consequently, in all there are 4 x 4 = 16 widget types.

---
Tags: 7, forms
---


# Question
Title: Anonymous users cannot see listed Commerce products in a View with a relationship to product
Commerce products when listed in a View with a relatioinship to Commerce Products cannot be seen by anonymous users. I am using the Views Reference module in the product display and the View is not showing up when logged out. I cannot seem to find any permissions relating to this setup.

# Answer
By default commerce products do not give anonymous permissions to be viewable. This is the reason when a View contains Commerce product relationships it will show nothing when your logged out. You will have to give users the permission setting:

--- **View any product of any type** ---
> 3 votes

# Answer
You can change your view to disable node\_access() checks. In you view, click on the Query settings:

Then check the Disable SQL rewriting checkbox.

Disabling node\_access() may introduce security issues, but I think it should be ok for a acrefully constructed view.
> 0 votes

---
Tags: 7, commerce, views
---


# Question
Title: how to make a custom module that has three forms on one page
I know how to make a module that has one form : http://www.wdtutorials.com/2012/04/26/drupal-7-how-create-forms#.U\_YI1WNab3s

But how can I make a module that contains three different forms on the same page?

# Answer
Yes you can create as many as forms in one page. One method is using drupal render function. Example:

```
$f = drupal_get_form('call_your_form');
$f1 = drupal_get_form('call_your_form1');
echo  drupal_render($f).drupal_render($f1);

```

Like this you can display any number of from in one page.
> 0 votes

---
Tags: 7, forms
---


title: People page redirect to the homepage

text:
# Question
Title: People page redirect to the homepage
I am having a peculiar error where whenever I click on the People tab on the admin bar it is redirecting me to the homepage.

Could someone please shed some light on this? This is on the live server for a while now, but this issue just recently started occurring.

Cheers.

P.S. I am superadmin, so I should have all the privileges.

# Answer
> 0 votes
No idea what was causing this but clearing the browser and site caches seemed to have fixed this issue.

Thanks to all those that replied.

---
Tags: users, redirection
---


title: Listing entity fields

text:
# Question
Title: Listing entity fields
I wonder if there is a good, and easy way to get all fields of an entity.

I have a taxonomy vocabulary. Its terms have a special field I want to make list in a select box in one of my modules, so that users can select a special value of the term. Therefore, I need a way to list the possible fields for this term.

# Answer
The function you are looking for is field\_info\_instances().

> Retrieves information about field instances.
> 12 votes

# Answer
**Drupal 7**

You may try:

```
  $info = entity_get_property_info($entity_type);
  $info += array(
    'properties' => array(),
    'bundles' => array(),
  );
  // Add all bundle properties.
  foreach ($info['bundles'] as $bundle => $bundle_info) {
    $bundle_info += array('properties' => array());
    $info['properties'] += $bundle_info['properties'];
  }
  var_dump($info['properties']);

```

Or if you have Entity module installed, then try:

```
entity_get_all_property_info('node');

```

Drush commands (one of these):

```
drush eval "var_dump(entity_get_all_property_info('node'));"
drush eval "print var_export(array_keys(entity_get_all_property_info('node')));"

```
> 4 votes

# Answer
Can also use the function : field\_info\_field\_map()

In place of returning entities going down to fields, it starts from field and go down to entities. That second one is fine to see where fields are going, whereas *field\_info\_instances()* shows how entities are built.
> 2 votes

---
Tags: 7, entities
---


# Question
Title: Auto-complete show everything by default
I have an field of "User reference" on a content type -- using an auto-complete control. This works but our user list is in the order of 300+ and it's difficult to remember who all should be selected for various tasks.

Auto-complete by default shows a list only once you have entered a single character -- is it possible to have the list show everyone the minute you click the text field???

# Answer
> 1 votes
Mabye you can use the Chosen module :

* Install, enable and configure the Chosen module
* change the widget type of your field to "Select list"
* in the field settings screen, check "apply chosen on this field" :

Now in your content edit form, you should see something like this, where the entire list appears in the dropdown, but where you can also type an autocomplete request :

---
Tags: ajax
---


# Question
Title: Image uploading button is not appearing for authenticated users,only for admin
When using Filtered HTML on a body text, the image uploading button is only appearing for admin users under Tinymce, but not for authenticated users.

How can I fix that?

# Answer
> 1 votes
I just had the same issue and this is what I found to fix it.

If you have IMCE to control your file browser you must create a profile for each user role. For example, the website administrator (owner of the website) will have access to the file browser no matter what, but if you have another authenticated user with the administrator role, they will not have access to the file browser unless you add a profile to the administrator role. So to do this go to 'admin/config/media/imce' or if you would prefer the interface way, log in as administrator and click on "Configuration" -\> "Media" -\> "IMCE".

Create a new profile by clicking on "Add New Profile" link and configure the profile to your needs. Save the profile.

Then next to the administrator role (or whatever role you need this for), select that profile you just created and click save.

Now test on a sample administrator (or whatever role you configured) account.

# Answer
> 0 votes
This sounds like a simple Permissions issue. Check your Role Permissions and verify they can Upload Files, and possibly View Uploaded Files.

---
Tags: wysiwyg
---


# Question
Title: How to Restrict Content OVerview to certain content types for user roles
I have a user role called Athletics and I have given these users access to add, edit or delete the content type Athletes. However when the content type is created it just creates a node not a URL alias so the Athletics users can not navigate to a page to edit or delete. I tried giving access to the content overview but I think that would confuse my non-technical users. Is there a way to make it so they can ONLY see the content they can edit or delete within the content overview?

# Answer
Administration Views will replace the admin listing pages with views, and then you can tweak it.

But looking at your question in the greater context what you really need is Contextual Admnistration. With it you can create a admin UI for your athletics role to manage content. There is a video tutorial series on Youtube.
> 0 votes

---
Tags: nodes
---


title: Services custom GET operation

text:
# Question
Title: Services custom GET operation
How to create custom GET resource operation? I tried many variants in `hook_services_resources()` but didn't find the solution. Is there way to do this? I want get some data from url rest/coaching/objectives-info and it should be GET request.

# Answer
I solve this problem by adding new resource with index operation. So the path became 'rest/objectives-info', not he same but suitable.
> 0 votes

---
Tags: 7, services
---


# Question
Title: How can I translate the checkout system?
I have been translating my Commerce Kickstart site with no ease although with success until now. Have translated content, taxonomy, product fields etc, following some tutorials and Drupal own documentation. Have installed a variety of modules for localization.

But now as regarding checkout system. I'm calling checkout system all screens starting by clicking on "checkout" in shopping cart block that appear in above and right corner of Kickstart demo store.

To translate checkout system, I went in https://localize.drupal.org/translate/downloads?project=commerce and downloaded my translation (Portuguese, Brazil). Then I imported that with /admin/config/regional/translate/import. In Overview tab all the 1222 expressions (100%) are translated. In Translate tab I searched for some strings that appear in that checkout system screens, like "Payment", "Checkout complete", and indeed there are already translations in Portuguese Brazil.

In /admin/config/regional/language/configure, on Detection and selection tab I enabled URL and Session as Detection methods.

So, are there more configurations that I need to do to have checkout system translated?

# Answer
> 0 votes
In importing translation page /admin/config/regional/translate/import I have chosen "Drupal commerce"in Text group section. The process went fine, but the words to translate were indeed in Bult-in interface. So I imported the same file again but now choosing "Bult-in interface" in Text group section. Now I have checkout system translated at some degree.

I think perhaps because I installed Commerce Kickstart 2 and Drupal Commerce comes all in Built-in interface.

---
Tags: commerce, i18n-l10n
---


# Question
Title: Moving functions in block module to inc file
I have searched *everywhere* for an answer to this question, and have found little to no help on the subject.

The closest question to my own would be this, but the answer for it is a bit different than what I'm looking for: How to move block functions into .inc file?

Here is my code for the most part (everything removed that wasn't necessary):

```
<?php

function custom_giggity_block_info(){
  $block['custom_giggity'] = array(
    'info' => t('Custom giggity'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $block;
}

function custom_giggity_block_view($delta = ''){
  $block = array();
  if($delta == 'custom_giggity'){
    $block['content'] = custom_giggity_contents($delta);
  }
  return $block;
}

function custom_giggity_contents($delta){
  //Code that generates what goes into $block['content']
  return $output;
}

```

And I need to use something like this, and don't know how to incorporate it:

```
function giggity_contents() {
  $items['giggity'] = array(
    'title' => "Giggity",
    'page callback' => "show_giggity", //or custom_giggity_contents ;)
    'access arguments' => array('access content'),
    'file' => 'giggity.inc',
    'type' => MENU_CALLBACK
  );
  return $items;
}

```

Now I realize that the second block of code there might completely off, but I'm just using it as an example as to what I need to accomplish.

Edit: So this is what I'd like to accomplish, but I'm not sure how the $items callbacks work. I took this piece of code from a hook\_menu() and replaced it with giggity\_contents.

```
<?php

function custom_giggity_block_info(){
  $block['custom_giggity'] = array(
    'info' => t('Custom giggity'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $block;
}

function custom_giggity_block_view($delta = ''){
  $block = array();
  if($delta == 'custom_giggity'){
    $block['content'] = giggity_contents($delta);
  }
  return $block;
}

function giggity_contents() {
  $items['giggity'] = array(
    'title' => "Giggity",
    'page callback' => "custom_giggity_contents",
    'access arguments' => array('access content'),
    'file' => 'giggity.inc',
    'type' => MENU_CALLBACK
  );
 return $items;
}

```

giggity.inc file:

```
 function custom_giggity_contents($delta){
  //Code that generates what goes into $block['content']
  return $output;
 }

```

# Answer
Like tenken said, use include\_once at the top of the ".module" file like this:

```
<php
include_once drupal_get_path('module', 'module_name') . '/module_name.functions.inc';
?>

```
> 1 votes

---
Tags: 7, hooks, blocks
---


# Question
Title: Auto Post to Google + from RSS Feed Content
I am using Drupal 7. I used Feeds module for content from the RSS. So i can get the content from RSS Feeds. Now **Feed** Content types automatically saved with RSS Feeds content. So now I want to auto Post the **Feeds** content to the twitter,linkedin and facebook.I am using Twitter module.

So i can Auto post the content using rules module to Facebook. Same Time I Can Auto Post the content using rules module to twitter..

Now I want to auto post the content to Google + also.I am using Google plus for Google+ connect to my drupal site. After saving my new node display the google+ icon and sharing option also. Same time I want to Auto post the the new node to Google+ Page.

# Answer
> 1 votes
Edit: google+ does have an api, but this module is old, and doesn't implement it.

You can't post using this module.

This link night give you some more information: https://stackoverflow.com/questions/7570327/how-to-post-in-google-plus-wall

---
Tags: 7, nodes, feeds
---


# Question
Title: Handling shared content without multisite?
Are there any good solutions out there for this? We have a couple of sites that share content (news, events, etc.) and they are not part of a multisite and we don't plan to make them a multisite. We need people to be able to edit them on each different site.

# Answer
> 1 votes
You could have a look at the Feeds module. You should set up one site as master (where news and events are entered) and use the Views module to publish an RSS feed of the content you want to share. Now on the other sites, you install the Feeds module and configure it to pull in the RSS feed and import the content from the master site.

Downsides to this approach:

* There will be a delay between the publishing on the master site and the import on the other sites.
* This especially works well when all content is entered on site. If you need content to be entered on all sites, things quickly get more complex.
* Once the content is distributed from the master site to the other sites, it can be edited on all sites, but the changes will not be synchronized across all sites.

---
Tags: nodes
---


# Question
Title: How can I create unique path alias for image styles?
`image_style_url` returns the public url of an image in the `files/styles` folder. Is it possible to create alias to that? What I want is the following:

Call `image_style_url` from the image style and the uri, which gives me typical public url `/sites/default/files/style/[style_name]/path/to/image/[image_file_name]`. I want to serve simple url like `/image/[randomized_number]` to the user that will internally alias to the aforementioned public url. This is similar to asking what pathauto module does for `/node/[nid]`, but for image styles.

Note that I do not want custom url to individual images per se, but rather a way to programmatically create unique unpredictable url aliases for image styles.

# Answer
Is a little difficult because image\_style\_url() uses internally image\_style\_path() who creates the path /sites/default/files/style/\[style\_name\]/path/to/...

Maybe you can use File (Field) Paths module:

> The File (Field) Paths module extends the default functionality of Drupal's core Upload module, the FileField module and many other File Upload modules by adding the ability to use node tokens in destination paths and filenames.
>
> In simple terms, File (Field) Paths allows you to automatically sort and rename your uploaded files using token based replacement patterns to maintain a nice clean filesystem.

If you only want to change the path alias you can use hook\_node\_insert() or hook\_insert()

```
/**
 * Implements hook_insert().
 */
function mymodule_node_insert($node) {
    // Set the URL alias
    if (empty($node->path['alias'])) {
        $node->path['alias'] = 'image/' . my_random_function();
    }
}

```
> 1 votes

# Answer
*My answer below assumes that you want to display the image itself and not an image as the main content on a Drupal page (for this you may use Views module).*

---

I am proposing using the File Entity Paths module. From the module:

> It does the same, as ***Filefield Paths***, but focus to the file entity, not to the parent entity...

So you create an alias (let's call it IMAGE\_ALIAS) to the file without needing the filename or extension (the MIME type is saved with the file upload) and then you can do these:

1. Create a *symlink* to `sites/default/files/YOUR_IMAGES_PATH` so you end `up with www.example.com/IMAGE_ALIAS` (more can be found at https://www.drupal.org/node/53705)
2. Do a *rewrite* on Drupal root's `.htaccess` (more can be found at https://www.drupal.org/node/53705)

```
 RewriteEngine On
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule ^(.*)$ /sites/%{HTTP_HOST}/files/$1 [L]

```
3. Use another folder instead of common `sites/default/files` eg `files` (on root).
4. Use File Aliases module that does all the above.
> 1 votes

# Answer
Have you tried File Aliases?

> The File Aliases module allows you to use token customizable aliases for your uploaded files, giving you the ability to keep your file system organized as per usual while providing clean looking paths (i.e., **no more '/sites/default/files/'**).

I've not tested it nor use it, but it seems to be the right module for your problem.
> 0 votes

# Answer
There's a hook for altering the file url when it's being created:

> hook\_file\_url\_alter

You should be able to call that hook and then use the path functions to create an alias for a style if it doesn't exist. https://api.drupal.org/api/drupal/includes%21path.inc/7
> 0 votes

---
Tags: 7, path-aliases, media
---


# Question
Title: How to prepend a Views query with another query?
Due to a configuration problem at my host, I'd like to execute the query "SET optimizer\_search\_depth=0;" in the same DB session as a specific Views query. I looked into hook\_views\_query\_alter() and hook\_views\_pre\_execute(), but in both cases the query is only available as a Query object.

I think I need some way to modify the raw query string before it's executed, but (presumably) after it's built. Is this possible?

# Answer
> 0 votes
Why do you think you need to alter the query itself? You literally said you needed to set a …`session` value.

You can issue any query prior to the views query on that page load to achieve the desired affect. Eg `db_query('set mysql_max_group_concat=5;');`

If you want to so it in the views lifecycle you could use any hook\_views\_\* api call which states it runs prior to query execution. Look at the views api docs.

Or you could likely use hook\_page\_build for all its worth. Or hook\_init ... whatever suits your needs.

---
Tags: views, database
---


title: user register from overflow

text:
# Question
Title: user register from overflow
In my register form email address description is overflow. I know that I have to change theme, but I would like to know where to theme it.

Thanks,

# Answer
You just need to simply edit the css in style.css of your activated theme. Go to `sites/all/themes/YOUR_THEME/style.css.`

Apply the css to the appropriate div of the field.

```
#user-register-form . description-field{
//css code here
}

```

Hope it will help you!
> 0 votes

# Answer
I don't know your themes output but maybe you could try to edit the style of

```
#user-register-form {

}

```

It would be helpful to see the website with the user-register-form.
> 1 votes

# Answer
You could fix it by css.

You need to write your css in the theme that are being used to display this page, it could be the admin theme.

```
e.g.
#user-register-form .description{
width:400px;

}

```

So you can use hook\_form\_alter() in your custom module to insert your css.

```
function customModuleName_form_alter(&$form, &$form_state, $form_id){
if($form_id=='user_register_form'){

drupal_add_css(/*css code */);
}
}

```
> 0 votes

---
Tags: theming, users
---


# Question
Title: How can I refresh a view block as soon as new content is added?
I want to refresh a views block whenever new content is added. I am using views auto refresh module

> Quick HOWTO: Using a ping script
>
> Using a ping script is essential for production environments, to avoid a full Drupal bootstrap at each refresh.
>
> Create a new page view Copy the file ping.php.example to your Drupal root folder and rename it as ping.php Edit ping.php such that DRUPAL\_ROOT points to your Drupal root, and adjust the query: $result = $db-\>query("SELECT count(nid) FROM node WHERE created \> $timestamp");
>
> to reflect your view's generated SQL query. Make sure to keep the created condition in the query. Add a new header of type Global: Autorefresh with: Set the interval time to 5000ms Check Use a ping url In Path to the ping script, enter ping.php Save the view and open its page In a second browser tab, add a new content that fits the view's criteria See the new content in the view!

Is there any other way we can refresh a views when content is created

# Answer
> 3 votes
You can achieve that using the Views node.js module

> This module implements dynamical update of views by nodejs after executing rules action. This module implements rules action which we can add to any rule for updating some views (views which need update, one can select in action).
>
> During updating of views all arguments that are already passed to view will be taken into account.
>
> It is also correctly working with views which use ajax. Introducing video.

---
Tags: 7, views, ajax
---


title: Latest Projects on front|home page

text:
# Question
Title: Latest Projects on front|home page
I created content type "Project". Added `node--projects.tpl.php`.

And now I need to display latest Projects on my front page WITHOUT Views module???

I need to get a piece of code and put it on my `page--front.tpl.php`. How can I get this code, this loop of my projects?

In WordPress it works very simple, but how does it work in Drupal 7?

# Answer
Check "Promoted to front page" option while creating every node of "Project" type.
> 2 votes

---
Tags: 7
---


# Question
Title: How to add large self hosted videos to Drual 7?
The Video module for Drupal 6 has an option to use videos uploaded through FTP. The Drupal 7 version does not have that option. How can I embed large self hosted Video files?

# Answer
> 4 votes
To answer your question: Use the contributed Drupal 7 Video module.

You will likely need to configure your server to allow for large file/video uploads.

I currently allowing video uploads that are up to 1GB using only the Video module, FFMPEG and a few helper modules to manage the 'video processing' workflow.

Most likely you will need to modify your PHP.INI file to allow large uploads. Specifically max post size and max upload size.

---

As for a widget that allows you to select a file uploaded via FTP, I see several issues in the Video modules issue queue that look relevant, but no solutions seem to be offered.

---

This question was also un-answered months ago. If FTP is a requirement you may need to write a custom module or contact the Video modules maintainers for a status update.

# Answer
> 0 votes
This is old question but nowadays there is solution for adding videos which are uploaded with FTP to server.

Solution is to use FileField Sources module. After this module is enabled then go to Manage fields in your Content type which has Video-field. Edit Video-field settings and you can find File Sources from there. Choose desired ways to add video for example File attach from server directory.

---
Tags: files
---


title: permission enable

text:
# Question
Title: permission enable
I have created new user/role for my user. What permission I need to enable for my user to let them access the Admin-\>Structure-\>Pages ?

I want this "Structure-\>Pages" enable in my user page

what permission I need to enable to let my user to access the "Structure-\>Pages"?

extra question, what permission I need to enable to let my user to access the "People-\>Newsletter subscription"?

Thank you.

# Answer
> 2 votes
You can assign its permission in admin(path-\>**`http://example.com/admin/people/permissions`**) e.g you have create a new role **testrole**

You just need to tick mark the checkbox under your newrole (**testrole**). Now it will be accessible to this role.

---
Tags: 7, users
---


# Question
Title: Non-directional/symmetric relation between nodes of the same content type
In a Drupal 7 website I would like to create an "is similar to" relation between nodes of the same content type. The nodes are vessels (ships) and a vessel can be similar to several others.

Think of the similarity as a *Volkswagen Golf I* is similar to the *VW Golf II*, *Golf III* and so on. The relation is symmatric, because the *VW Golf IV* is similar to the *Golf VII* and vice versa.

In the current custom made website, which will be migrated to Drupal 7, there are over 6500 relations between vessels.

I've tried several modules, but I can not create what I intend:

* the **Relation** module can not create relations between endpoints of the same entity type (e.g. nodes of the same content type);
* the module **Entity reference** only creates directional relations. This would mean creating two references per relation, ending up with over 13000 references;
* the **References** module also only creates directional relations, again ending up with over 13000 references.

So the question is: *how do I create non-directional/symmetric relations between nodes of the same content type?*

# Answer
Corresponding entity references fixes this for you:

> CER keeps reference fields in sync. If you have two entities that refer to each other using Entity Reference (or some other kind of reference field), it saves you the trouble of double-editing your entities in order to have them point at each other. If entity Alice references entity Bob, CER will make Bob reference Alice, and keep the references up-to-date when either entity is updated or deleted.
> 0 votes

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


# Question
Title: Why does aggregator report "There is new syndicated content" but still 0 items for this feed?
We've had a working feed aggregator running for quite some time now (over 12 months) from a YouTube feed link (`http://gdata.youtube.com/feeds/base/users/[username]/uploads`). We just recently noticed that there are no items displaying in this feed's block. Upon visiting the feed configuration page (`admin/config/services/aggregator/edit/feed/[feed-id]`), I can see that there are 0 items in the feed. Running the feed manually reports "*There is new syndicated content from YouTube.*", but there are no items created. The dblog shows an entry from the feed aggregator with the same message, but no error messages.

Has anyone experienced this or have any ideas on where to troubleshoot? Without any actual errors I'm unsure if this is a bug, works-as-designed, or potentially something wrong with YouTube's feed. I've validated the feed on a couple of websites and there are no (apparent) issues with it.

# Answer
I have just been experimenting with the aggregator and come across the same issue. The only workaround that I have been able to find in order to pull content from the RSS feed in issue has been to use the Feeds module. If you are still having this issue then this is a possible solution.

EDIT: Just found a far simpler solution for the problem. By default the aggregator deletes items older than 3 months and 3 weeks from the feed. If the youtube feed you are subscribing to has not had new content added in that time then you may get the situation you describe. If that is not the case then go with the first option I suggested. Otherwise you can change how long Drupal keeps the feed items in the Aggregator settings tab.
> 1 votes

---
Tags: 7, feeds
---


# Question
Title: How to display tags of content filtered by a different tag
I have a content type that has 3 taxonomy fields (Year, Project & Type, respectively).

On the top page of the view I want to display all terms of the Year-vocabulary, this is no problem. I rewrite the field so it links to

```
/work/Year

```

On the next page I want to show all the unique Project-terms for the selected year.

Example:

```
Project A: Year: 2014, Project: Scanning Paper, Type: Painting
Project B: Year: 2014, Project: Scanning Paper, Type: Drawing
Project C: Year: 2013, Project: Leaving , Type: Painting
Project D: Year: 2014, Project: Afterlife, Type: Painting

```

If the year 2014 is selected, I want the next view to display all unique projects:

```
Scanning Paper
Afterlife

```

I've been trying this to accomplish this using Views, and been working at a solution for a couple of days now, but I can't figure it out. I've tried a lot of things, searched here and elsewhere, but haven't find a solution. I'm beginning to think maybe the approach with taxonomy terms isn't right, but I need some guidance.

Thank you.

# Answer
> 1 votes
You will need to use three views.

The **first view** can be either a view of taxonomy terms (easy enough), or a view of your content type with a relationship, taxonomy terms on node. Use this path: work

If you select the second option you will get duplicate rows, and you will have to use aggregation. You will need three fields: tid (hidden), type (hidden and aggregation set to count), and term name (rewrite it to a link with this: work/\[tid\]).

The **second view** will have a path: work/% and will be a view of your content type. Add two relationships, one to taxonomy terms on node and select year, and another to taxonomy terms on node, and select project. Give them each a descriptive identifier. Now add a contextual filter: The tid of a taxonomy term, and select the relationship of the year taxonomy vocabulary. Now you will get a lot of duplicates. Again set aggregation on and this time you might have to add fields content type (hidden and aggregation count) as well as tid (hidden, relationship to year vocab, aggregation count). Add two hidden tid fields (for the link construction), one with year relationship, other with project. Add your link field and rewrite as link like this: work/\[tid\]/\[tid\_1\]

The **third view** is more of the same. It will have path of word/%/%. You will add one more relationship and contextual filter than you did for view 2.

In view 1 if you do it based on your content type then only years that are being used by your content will show. If you do it as a taxonomy view then all year terms will show, and depending on your content some of these term links will then navigate to empty views.

And when you build your views start off without any sorting on them as this will give initial issues with aggregation. You can add sorting back after you have a working solution.

# Answer
> 0 votes
I have a different scenario for you i accomplise this by having 2 views 1)list down year using views and using output this field as a link and provide "taxonomy/%" or whatever you like "anything/%". 2)make a view that list all the content now using relationship add taxonomy terms on node and choose you vocabulary. 3)Add a Contextual Filter with name Taxonomy Term, specify validation criteria check-\>Validator(Taxonomy Term)-\>Vocabularies(check year)-\>Filter value type(term name) apply . 4)path of this view would be anything/%.

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


# Question
Title: Drush won't clear uploaded temporary files
So, working on a unix system, it's common that /tmp has the sticky bit set (i.e. only the owner of the temporary file can write/delete it). This is an issue when running drush cron.

If I upload a file, and the file gets stored in /tmp, then the owner is \_www (I'm on a MacOS machine). When I run drush, I'm running it as my own user, so if I run drush cron then my user is attempting to delete the temporary file(s) that was uploaded, and I get a permission denied.

Can anyone think of a simple workaround for this problem?

# Answer
Simply make CRON run drush as \_www user. /etc/cron.d suppotys it, it's format is:

```
#<timing>   <user> <command>

```

Just make entry for your drush:

```
11 * * * *    _www   drush

```

Details, of course, may vary a little.

I used this answer.
> 1 votes

---
Tags: 7, drush, files
---


# Question
Title: How to apply css to the maintenance page?
I need to work on some serious update to my D7 website. So I put my site in maintenance mode. I'm able to personalize the maintenance page by creating *maintenance-page.tpl.php* in my theme's template directory and it works like charm, no issues. The problem is, none of my theme *css* files are loaded when I'm opening the site in maintenance mode.

I'd really like to prettify the maintenance page for any visitors who visits the site in the mean time (while I'm updating). How do I do that? BTW, I'm using omega theme stable release.

# Answer
> 5 votes
Override the maintainence stylesheet in the theme layers .info file...

```
  stylesheets[all][] = system.maintenance.css

```

To be honest if none of your theme stylesheets are loading then not sure it will work but ideally it should.

Heres some more info on theming the maintence page...

http://drupal.org/node/195435

---

**UPDATE**

Alternatively, try the following in your theme...

```
/**
 * Implements hook_preprocess_maintenance_page().
 */
function YOURTHEME_preprocess_maintenance_page(&$variables) {
  drupal_add_css(drupal_get_path('theme', 'YOUR_THEME') . '/css/maintenance-page.css');
}

```

# Answer
> 0 votes
You can even add direct css by following stylesheet link

```
<link rel="stylesheet" type="text/css" href="sites/all/themes/YOUR_THEME/css/maintaince.css">

```

Just remember to add full address to your theme i.e. `sites/all/themes/YOUR_THEME/YOUR_CSS`

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


# Question
Title: Only first step with multi step registration
I'm using the module Multi-step Registration for my user accounts. I have six steps in my registration proces.

But now I want to show only the **FIRST** step when a user registers. So the user can register with only username and email. And when they receive an email to set their password they can edit all their settings, all the steps with a wizard (this is also multi-step with the same module).

But I have no idea to make sure that when they register you can only see the first step...

How can I do this?

# Answer
> 1 votes
Make visible for specific fields in the Registration form for First Step, i.e., In Account Settings -\> Edit the field which you do not require in first step just Uncheck "Display on user registration form". After successfully created an Account then in Edit mode all the fields will appear. This is just my think not the exact answer.

---
Tags: 7, forms, users
---


# Question
Title: Migrating a field collection with a field that has multiple values
I have a field collection migration that is taking nodes of type Map List from a D6 site which have two fields, a title, and a node reference to entity of type Venue. There anywhere between 1-10 node reference fields on any given Map List.

The Map List nodes are to be migrated to a field collection on the D7 site called field\_city\_map\_list which lives on the D7 nodes of type City. On the D6 site the Map List nodes were referenced on the old City content type via entity reference fields.

With the query and sourceMigrations set I was able to get the field collections to be attached to the correct City node in the D7 site, however in the case where a Map List has multiple node reference fields, the migration creates a single field collection for each node reference.

So where field\_city\_map\_list should have several lists, with multiple node references like this:

```
CityNode->
  Title: Some Title
  City Map Lists:
    Some List Title 1:
      345
      677
      987
    Some List Title 2:
      876
      678
      908
    Some List Title 3:
      493

```

It actually gets imported like this:

```
CityNode->
  Title: Some Title
  City Map Lists:
    Some List Title 1:
      345
    Some List Title 1:
      677
    Some List Title 1:
      987
    Some List Title 2:
      876
    Some List Title 2:
      678
    Some List Title 2:
      908
    Some List Title 3:
      493

```

I thought ordering the query by the map list nid and then by the delta in the field venue nid list would solve the issue but it didn't change the migration results at all. There are no errors or migration messages that appear.

Here is my class:

```
class FCMapList extends myFieldCollectionMigration {
  public function __construct(array $arguments) {
    parent::__construct($arguments);

    $this->systemOfRecord = Migration::DESTINATION;

    $this->description = t('Field Collection: Map List Nodes');

    $dependencies = array(
      'VenueProfilePage',
      'City',
    );

    $this->dependencies = $dependencies;

    $query = Database::getConnection('default', 'legacy')
      ->select('content_type_map_list', 'ml')
      ->fields('ml', array('nid', 'field_link_title_value'));
    $query->join('content_field_venues', 'v', 'v.nid=ml.nid');
    $query->fields('v', array('nid', 'field_venues_nid'));
    $query->join('content_field_lists', 'l', 'l.field_lists_nid=ml.nid');
    $query->fields('l', array('nid'));
    $query->orderBy('ml.nid');
    $query->orderBy('v.delta', 'ASC');
    $query->isNotNull('v.field_venues_nid');

    $this->source = new MigrateSourceSQL($query);

    $this->destination = new MigrateDestinationFieldCollection('field_city_map_list', array('host_entity_type' => 'node'));

    $this->addFieldMapping('host_entity_id', 'l_nid')
         ->sourceMigration('City');
    $this->addFieldMapping('field_list_title', 'field_link_title_value');
    $this->addFieldMapping('field_venues', 'field_venues_nid')
         ->sourceMigration('VenueProfilePage');

    $source_key = array(
      'nid' => array(
        'type' => 'int',
        'description' => 'List content ID',
        'alias' => 'ml'
      )
    );

    $this->map = new MigrateSQLMap($this->machineName, $source_key, MigrateDestinationFieldCollection::getKeySchema());

     }
}

```

I had found a similar question that was self-answered however as I said above, ordering by source node nid and field delta did not solve the issue.

I'm on migrate version: 7.x-2.6-rc1+57-dev and field collection version: 7.x-1.0-beta7

# Answer
The only way around the issue I could find was to remove the map of D6 node reference field to the D7 entity reference field. Instead I set a default value to 1 so that it appears on the field collection in the prepare function, and I then repopulate it with a secondary query there. This solution was not ideal for me, but due to time constraints I was forced to go with this way. Hopefully someone can find a real solution to the issue.

One more issue I found while attempting to debug this behavior was that rolling back this field collection migration did not delete the field collections. It only reset the map messages and numbers of processed rows. To delete the field collections entirely I had to roll back the migration of the nodes they were on as well: `drush migrate-rollback City && drush migrate-rollback FCMapList`

```
class FCMapList extends myFieldCollectionMigration {
  public function __construct(array $arguments) {
    parent::__construct($arguments);

    $this->description = t('Field Collection: Map List Nodes');

    $dependencies = array(
      'VenueProfilePage',
      'City',
    );

    $this->dependencies = $dependencies;

    $query = Database::getConnection('mig_dest', 'legacy')
      ->select('content_type_map_list', 'ml')
      ->fields('ml', array('nid', 'field_link_title_value', 'field_link_subtitle_value'));
    $query->join('content_field_lists', 'l', 'l.field_lists_nid=ml.nid');
    $query->fields('l', array('nid'));
    $query->isNotNull('ml.nid');
    $query->isNotNull('l.field_lists_nid');

    $this->source = new MigrateSourceSQL($query);

    $this->destination = new MigrateDestinationFieldCollection('field_city_map_list', array('host_entity_type' => 'node'));

    $this->addFieldMapping('host_entity_id', 'l_nid')
         ->sourceMigration('City');
    $this->addFieldMapping('field_list_title', 'field_link_title_value');
    $this->addFieldMapping('field_venues')
     ->defaultValue(1);

    $source_key = array(
      'nid' => array(
        'type' => 'int',
        'description' => 'List content ID',
        'alias' => 'ml'
      )
    );

    $this->map = new MigrateSQLMap($this->machineName, $source_key, MigrateDestinationFieldCollection::getKeySchema());

     }

  public function prepare($field_collection, stdClass $row) {
    $legacy_list_nid = $row->nid;

    $venues_query = Database::getConnection('mig_dest', 'legacy')
      ->select('content_field_venues', 'v')
      ->fields('v', array('delta', 'field_venues_nid'))
      ->condition('v.nid', $legacy_list_nid, '=');
    $venues_query->orderBy('v.delta', 'ASC');
    $venues_query->orderBy('v.nid', 'ASC');
    $venues_query->isNotNull('v.field_venues_nid');
    $result = $venues_query->execute();

    while ($record = $result->fetchAssoc()) {
      $venue_delta = $record['delta'];
      $legacy_venue_nid = $record['field_venues_nid'];

      db_set_active();
      $venue_nid_query = Database::getConnection('mig_dest', 'default')
        ->select('migrate_map_venueprofilepage', 'mv')
        ->fields('mv', array('destid1'))
        ->condition('mv.sourceid1', $legacy_venue_nid, '=');
      $venue_result = $venue_nid_query->execute();
      $venue_nid = $venue_result->fetchField();

      if (is_array($venue_nid)) {
        $venue_nid = $venue_nid[0];
      }
      if (strlen($venue_nid) > 0) {
        $field_collection->field_venues['und'][$venue_delta]['target_id'] = (string)$venue_nid;
      }

    }

  }

}

```
> 0 votes

---
Tags: entities, migrations
---


# Question
Title: Listing all entity properties identifying unique entity instance?
Is there a generic way of knowing what collection of properties on an entity identify it as a unique instance?

For example, a node has a node id, and a revision id. Some entities do not have the revision id, other entities might require further keys.

Usecase example: Storing various entities in an external system, one wants to be sure to store enough data to be able to uniquely identify the resources in that system.

# Answer
> 1 votes
I have always assumed that when you do

```
$entity_info = entity_get_info('foo');
$table = $entity_info['base table'];
$schema = drupal_get_schema($table);

```

and then examine `$schema['primary key']` and `$schema['unique keys']` you get a tuple to represent uniqueness.

I would also assume that you can do

```
$entity_info = entity_get_info('foo');
$keys = $entity_info['entity keys'];

```

and this would represent a tuple to uniquely identify an entity. However, this gets a little confusing. For example, if you have UUID installed, then there is a uuid and revision uuid in the results. These are not needed within one system, but will guarantee uniqueness between systems.

# Answer
> 1 votes
The documentation for hook\_entity\_info() reports the following description for the properties the hook needs to return:

> * entity keys: An array describing how the Field API can extract the information it needs from the objects of the type. Elements:
>
> + id: The name of the property that contains the primary id of the entity. Every entity object passed to the Field API must have this property and its value must be numeric.
>     + revision: The name of the property that contains the revision id of the entity. The Field API assumes that all revision ids are unique across all entities of a type. This entry can be omitted if the entities of this type are not versionable.

The primary ID is what univocally identifies an instance of an entity. The revision ID identifies a revision, but it is not necessary for univocally identifying an entity instance. Clearly, the primary ID univocally identifies an instance for which you know the entity type.

Drupal 8 introduces another entity key (uuid), which is described as:

> uuid (optional): The name of the property that contains the universally unique identifier of the entity, which is used to distinctly identify an entity across different systems.

I guess it is unique among different entities.
Between the entities that Drupal 7, and Drupal 8 have in common, only the taxonomy vocabulary doesn't define a uuid field; node, user, and taxonomy term define it.

# Answer
> 0 votes
**Drupal 7**

If you have Entity module installed, then try:

```
entity_get_all_property_info('node');

```

Drush commands (one of these):

```
drush eval "var_dump(entity_get_all_property_info('node'));"
drush eval "print var_export(array_keys(entity_get_all_property_info('node')));"

```

Read more: Listing entity fields

---
Tags: entities
---


# Question
Title: How do I add view header content in code?
How do I add view header content in code?

I have seen questions related to this but only where the view is being embedded. I am not embedding any view, but would like to provide content for the view headers in code as I have quite a few views, and I do not want to add the content through the views UI as it is difficult to make changes quickly and as some views have many pages and share the same header.

Currently I have this code.

```
function MYMODULE_preprocess_views_view(&$vars){
  $function = __FUNCTION__ . '_' . $vars['name'];
  if (function_exists($function)) {
    $function($vars);
  }
}

function MYMODULE_preprocess_views_view_VIEW_NAME(&$vars){
  // do something here.
  $vars['attachment_before'] .= $SOME_CONTENT;
}

```

# Answer
> 6 votes
Use `hook_views_pre_render()`.

```
/**
 * Implements hook_views_pre_render().
 */
function cv_views_pre_render(&$view) {
  // dpm($view); // dpm view here to see its properties.
  // and replace $view->name and $view->current_display with actual values from your view.
  // Note that my example uses Global: Text area for header, that's why I use $view->header['area'].
  // Other options available for header have different names. Try to find one that you use.
  if ($view->name == 'homepage' && $view->current_display = 'homepage_page_display') {
    $view->header['area']->options['content'] = t('TEST message');
  }
}

```

---
Tags: 7, views
---


# Question
Title: Updating module using _update_n not appearing on update.php or in /modules/update
I had to change the schema of a module I created. I added a function like this:

```
function cloudinary_update_7200() {

  $spec = array(
    'keywords' => array('type' => 'longtext', 'not null' => FALSE),
    'primaryImage' => array('type' => 'tinyint', 'default' => 1, 'not null' => FALSE)
  );

  $cloudinary_field_table = 'field_data_field_cloudinary';
  $revision_table_name = 'field_revision_field_cloudinary';

  $keywords = 'field_cloudinary_keywords';
  db_add_field($cloudinary_field_table, $keywords, $spec);
  db_add_field($revision_table_name, $keywords, $spec);

  $primaryImage = 'field_cloudinary_primaryImage';
  db_add_field($cloudinary_field_table, $primaryImage, $spec);
  db_add_field($revision_table_name, $primaryImage, $spec);

  //UPDATE FIELDS
  $description_spec = array(
    'description' => array('type' => 'longtext', 'not null' => FALSE)
  );
  db_change_field($cloudinary_field_table, "field_cloudinary_alt", "field_cloudinary_description", $description_spec);

}

```

So how do I get it to run? I've gone to /update.php but nothing. I tried /admin/modules/update and the module is not listed.

Yes, I have cleared my cash many many times. And yes, I've cleared it again.

# Answer
> 1 votes
Rename cloudinary\_update\_7200 to cloudinary\_update\_7100 in case if you are using 7.1 version (refer to hook\_update\_N) and try once again.

If it doesn't work perform SQL query to figure out the number of the latest performed update of the module:

```
SELECT schema_version FROM system WHERE type = 'module' AND name = 'cloudinary';

```

If it is 0 - 7100 should work, if it is for instance 7101 - try cloudinary\_update\_7102.

---
Tags: 7, updating
---


# Question
Title: How to combine two contents of same type and display in views
How to combine two contents of same type and display in views?

the following picture will clear my question.

# Answer
There is a module for that, Views Merge Rows. From the project's description:

> Sometimes when you use relationships in views you get a number of rows with the same content in some of the fields. This results in a huge table (grid, list, etc.) that affects the usability of your view. The Views Merge Rows module provides a way to combine rows with the same content in the specified fields.

Keep in mind that there is a pretty straightforward guide to configure the module in the project's page that includes very descriptive screenshots.
> 2 votes

---
Tags: views
---


title: Views: Show current user-entered filter

text:
# Question
Title: Views: Show current user-entered filter
I have a view with an exposed form for searching titles/bodies of content. Is there a way I can display "Showing results for: $keywords" with the values that the user enters?

# Answer
> 1 votes
You can use the PHP text filter in core. It is quick and dirty.

Add a Header of global text area to the view. Then add this PHP code using the PHP code text format:

```
<?php
$query_params = drupal_get_query_parameters();
if (isset($query_params['title'])) {
  print t("Results for @query", array('@query' => $query_params['title']));
}
?>

```

Exposed filter and sort queries in views are passed as query parameters in the form of:

```
?title=test

```

In the above code I am just looking at the parameter 'title', but you can adapt that code snippet to suit your needs. Just look at your url to see what query parameters are passed along.

---
Tags: views
---