# Question
Title: Multisite Drupal 7 sharing same code base
I have existing Drupal 7 site and I want to create a sub-domain using the multisite feature of drupal.

I followed all the steps required for drupal multisite as below.

Suppose my existing site url is www.abc.com and I want to make a sub-domain as www.jobs.abc.com

Steps I followed.

1. Under sites folder I created a new folder jobs.abc.com and copied the default.settings.php file renamed it as settings.php

sites/jobs.abc.com/settings.php

2.My existing domain settings.php file is under default folder sites/default/settings.php

3.I Renamed the example.sites.php to sites.php and added the following two lines.

$sites\['www.abc.com'\] = 'default'; $sites\['www.jobs.abc.com'\] = 'jobs.abc.com';

Finally I installed the Multisite wizard module http://ftp.drupal.org/files/projects/multisite\_wizard-7.x-1.3.tar.gz

I configured the module it is showing me the message

"Hint: the folders names should be the same as values of domain-folder array in the site.php file Folders to be created: default,job.abc.com" please find the screenshot.

I have already created these folders there. I am not sure why its showing this message again.

# Answer
> 1 votes
Having the folders that the message states in your sites/ directory involves two basic steps:

1. Creating the directories
2. Making the directories visible to the web server

In a typical Ubuntu installation with Apache as your server the first step is accomplished by executing the `mkdir` command in your sites directory:

Example

```
cd /var/www/my_drupal_site/sites
mkdir jobs.abc.com

```

and for the second step using the `chown` command.

```
chown -R www-data:www-data default
chown -R www-data:www-data jobs.abc.com

```

The chown command changes the ownership of the directory and with the -R flag it does the same thing recursively for every contained subdirectory and file. The www-data is the default user and group that Apache runs as (so if you have an nginx setup, you will probably have to change this).

---
Tags: subsites
---


# Question
Title: Fatal Error - Fatal error: Unsupported operand types in public_html/includes/common.inc on line 2999
The page of my work is not loading anymore! And Im not used to deal with drupal! What I have to do to the page load properly! I even cant login as user or see any page of the site! PLZ im really desesperated!

this error show when i try to enter in the page: Fatal error: Unsupported operand types in /home/storage/2/58/58/xxxxx/public\_html/includes/common.inc on line 2999 the page i wanna to work is that: www.meddco.com.br!

# Answer
You need to access the installation's database.

* Find the 'block\_custom' table. This contains all custom blocks.
* Browse the records and locate the one which creates the problem.
* Clear the field 'body' which should contain your custom PHP code.
> 0 votes

---
Tags: blocks
---


title: Grid View of images in a Content

text:
# Question
Title: Grid View of images in a Content
I want to display images in grid view. I have designed a view which can display each album in grid view. Here album is a content type. The problem is that inside album I can see list view of images. I have selected unlimited number of value in image filed under album content type. Below is the screenshot-

# Answer
You can do it with CSS.

You add CSS to your theme. If you're using a theme like Zen that has SASS, you can add the new rules to your SASS file(s) and compile them to CSS. There is documentation for adding CSS to pages on Drupal.org.
> 2 votes

---
Tags: nodes
---


# Question
Title: How to programatically add block to Drupal 7 page tpl AND respect visibility rules?
I want to add a block programatically to a page.tpl.php file in my Drupal 7 theme BUT I want it to respect the block's visibility rules.

I'm open to defining new visibility rules in PHP too but it seems whenever I manually invoke a module via code without assigning the block in a region it does not adhere to the block's visibility rules.

# Answer
> 0 votes
Turns out the solution was in how I was rendering the blocks.

Using this code to render my block added the block to Drupal's "knowledge" of the block being on the page.

```
$block = block_load($module, $bid);
$blockStuff = _block_get_renderable_array(_block_render_blocks(array($block)));
$output = drupal_render($blockStuff);
print $output;

```

---
Tags: blocks
---


# Question
Title: Automatic Nodetitles: How to hide "Pattern for the Title" when empty
I installed Automatic Nodetitles 7.x-1.0 on Drupal 7 for Staff Content Type. Everything seems perfect except the feature "**Pattern for the title**" for "**Automatically generate the title and hide the title field**".

The pattern I replaced with "**\[node:field-firstname\] \[node:field-middlename\] \[node:field-lastname\]**, but it displayed the ***ACTUAL TEXT*** "**\[node:field-middlename\]**" on title when middle name is empty. **Is there a setting or solution to hide pattern when empty?**

# Answer
Try the `-dev` version of the module. The release date for 1.0 of autmoatic nodetitles is `2011-Jun-07`. You really think something released in 2011 is bug-free in against Drupal 7.31 (current stable release) ...

If you really care you could request a new supported release of the module in the issue queue.
> 1 votes

---
Tags: 7, nodes
---


title: Keep showing log message

text:
# Question
Title: Keep showing log message
How can I disable this message?

# Answer
If you have the Click Heatmap module enabled, either disable the module or add clickheat to the libraries folder.

Though, looking at the path that is output in the error, it seems that clickheat is probably being included in a template file somewhere, find the code and remove it. Do a search through your files to try to find 'click.php'.

Just disabling database logging will remove it, but will also not log anything else, so this is probably not your best option. Better to fix the problem rather than just hide it.
> 3 votes

# Answer
It's possible to disable logging.

admin/config/development/logging

Disabling logging means you'll have no trace that your page is failing to load. Instead of pretending it's not happening, it would be better to find the underlying bug - why are users requesting a page that is failing to load?

If you need to disable the messages in the UI but would like to continue debugging, you can run this command from anywhere within your Drupal directory, assuming you have Drush installed:

```
drush watchdog-show --tail

```

This will give you all of the warnings / errors happening as you browse the site.

A truly robust Drupal installation will have an active log which is stored in a service like Splunk. Developers will intentionally add watchdog() functions in their code as a method of defense. Warnings and errors are critical for debugging problems with Drupal sites.
> 2 votes

---
Tags: 7
---


# Question
Title: Better way of adding Image as Block in home page
I am designing a personal website. I wanted to display my photo in the side bar in the home page. Below is screenshot-

To get the above display, I have created a basic page in which I have inserted the dummy image using IMCE in CKEditor. Then I have created a view, which is a block of basic page. In this view, the filter criteria is the content title, which should be equal to "my passport size image". Now I have added this block to sidebar.

I am looking for a better way to achieve the same.

# Answer
> 2 votes
This is sadly a reasonable solution - one of the easiest. However, as you can see, it's sad because your content - the image - isn't being managed by the entity which is displaying it. This is very confusing when you go back and edit your content. You'll have to wonder - "Where is this being displayed?"

A better solution is to use the BEAN module. This will allow you to build a block type - much like a content type - which has an image attachment. Then, you can manage the display of that image on the block itself. In fact, you can any fields you like to your block type!

https://www.drupal.org/project/bean

---
Tags: blocks
---


# Question
Title: node.tpl render field from referenced entity
I have a node.tpl.php file where I need to output a field from an entity referenced via the entity module (a reference field). I have tried using:

```
print render($content['field_parent']['#items'][0]['entity']->field_main_image);

```

but nothing appears! I also tried this way:

```
$parent = node_load($node->field_parent['und'][0]['target_id']);
print render($parent->field_main_image);

```

I just would like to render() a related field just as I do with $content fields.

Any hints ? Thank you

# Answer
> 1 votes
You can use https://www.drupal.org/project/inline\_entity\_display to do that with entity reference and field collection field.

# Answer
> 0 votes
You can't render the member variable of a node directly. In a frist step you have to bring it in a renderable from (array):

```
//returns the field in the correct language
$field_parent = field_get_items('node', $node, 'field_parent');

//retruns an array which you can render
$render_array = field_view_value('node', $node, 'field_parent', $field_parent [0]);

print render ($render_array);

```

Here's the differents between the two structures of these arrays. The array in the member variable of $node looks like:

```
array(1) {
  ["und"]=>
  array(1) {
    [0]=>
    array(3) {
      ["value"]=>
      string(15) "Your value"
      ["format"]=>
      NULL
      ["safe_value"]=>
      string(15) "Your value"
    }
  }
}

```

A renderable array (for a textfield) looks like that:

```
array(2) {
  ["#markup"]=>
  string(18) "Your value"
  ["#access"]=>
  bool(true)
}

```

# Answer
> 0 votes
```
$parent = node_load($node->field_parent['und'][0]['target_id']);
print render($parent->field_main_image);

```

should work as

```
$parent = node_load($node->field_parent['und'][0]['target_id']);
print drupal_render(field_view_field('node', $parent, 'field_main_image', 'displayname'));

```

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


# Question
Title: How to pass current loged in user id in Drupal view page settings
I am new to DRUPAL. Recently I have created a view with 3 pages. 1st page shows in the main menu . 2nd and 3rd page shows in main menu . Now I would like to display the list of the images uploaded by the user in one of that menu tab. So in order to accomplish this I have added a path like user/%/MY-images in page settings. Now if I click this menu-tab I am not getting the user id passed in the url.

My contextual filter is working fine. Only thing I need to pass the user id through the URL.

Can anybody help me out to figure the solution.

Thanks in advance

# Answer
> 0 votes
Once your contextual filter is set up correctly to use the UID, then you'll have to manually pass the UID as an argument in a query string parameter. Your menu tabs will not do this automatically.

Instead, you'll have to implement hook\_menu\_link\_atler() for each menu tab link.

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_menu\_link\_alter/7

You can use the global $user object to get the uid:

https://api.drupal.org/api/drupal/developer!globals.php/global/user/7

# Answer
> 0 votes
First you sure create contextual filter with default value "get default uid from url"(also if you want get logged in user you can get default value from logged in user) then test it in "preview" section. if everything work in your views correctly try clear the cache.
If not work update your question with snapshot if your contextual filter settings.

---
Tags: views
---


title: Region and language selection in URL

text:
# Question
Title: Region and language selection in URL
Is it possible in Drupal?

I'm developing a website in multilingual. It contains region (country name E.g USA, German, french....) and language (English, French, Japan....) selection.

When user select the region it brings in URL.

Eg: http://www.example.com/us\[region-name\]/en\[language-name\]

For single region, we can select many language

Eg: http://www.example.com/us\[region-name\]/jp\[language-name\] or http://www.example.com/us\[region-name\]/fr\[language-name\]

# Answer
> 1 votes
I achieve this by using Purl with help of mytheme\_url\_outbound\_alter()

---
Tags: views, 7
---


# Question
Title: Get all registered Users into a Field Type List
I would like to create a content/form where an authenticated user is able to choose another registered user from a list/dropdown. I've been searching for ways to get this done but am not able to find any working solution. Token can only display current-user, not all users. I can list all users using Views but not able to import them into the field of type list.

ie: Nomination Form Favorite Sport : \[options\](list from taxonomy)\[/options\] Favorite Users : \[options\](list of all registered users)\[/options\] etc

Appreciate if someone can point out what I am missing. Thank you

# Answer
You can create form using Entity form. It provides interface you to fetch content from the drupal fields taxonomy and other fields. Term reference is inbuilt in drupal to add the Sports list.

For user reference list you can add the references module which will ask you to choose users from the registered users.

Hope it will help you
> 0 votes

---
Tags: entities, users, tokens
---


# Question
Title: Drush can't connect to local MySQL through socket on WAMP
Trying to set up Drush with in a local dev environment on Windows 7 and can't get MySQL properly configured. A test command I've been running via Cygwin, with the resulting error, is as follows:

```
$ drush sql-query "SELECT * FROM erg_node WHERE nid=3"
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

```

I can run the same SQL statement in phpmyadmin and it works fine. I can run the same drush command with a remote site and it also works, so it seems like it must be related to how MySQL is configured with WAMP and Cygwin. When I check `which mysql` via Cygwin, I get back `/usr/bin/mysql` instead of the path for WAMP's mysql. But the WAMP mysql path is set in my system environment PATH variable, so it should be accessible.

I've tried changing my.ini to include `host = 127.0.0.1`, copied the my.ini file to `/etc/my.cnf`, and run `chmod -R 755 /tmp/`. I'm not sure if there's something else I need to do to ensure drush uses the WAMP mysql command? Any help would be appreciated. Thank you!

# Answer
> 2 votes
For anyone else with this problem, it was an issue with the PATH variable. I had to add the path to the version of mysql that I wanted to use (the WAMP version) to the beginning of my PATH variable in my .bash\_profile. SO post regarding PATH variable in .bash\_profile.

# Answer
> 0 votes
Look at this post, they are talking about MAMP but I think that the problem is the same...

---
Tags: drush
---


title: Bulk of HTML files to node Migration

text:
# Question
Title: Bulk of HTML files to node Migration
I am developing a module for migrating data from html file to drupal node. Each Html file is having 500+ logs. I want to create node for each log record. I have started development of module as it is explained in DRPAL DOCUMENTATION i.e.: https://www.drupal.org/node/2029713/

But I am not getting exact solution for resolving it. Getting this error:

> An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows. Path: /batch?id=40&op=do StatusText: Service unavailable (with message) ResponseText: PDOException: SQLSTATE\[22007\]: Invalid datetime format: 1366 Incorrect integer value: '/Chat Log - 07:01:2014.html' for column 'sourceid1' at row 1: INSERT INTO {migrate\_map\_alertnodemigrate} (sourceid1, needs\_update, rollback\_action) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2); Array ( \[:db\_insert\_placeholder\_0\] =\> /Chat Log - 07:01:2014.html \[:db\_insert\_placeholder\_1\] =\> 3 \[:db\_insert\_placeholder\_2\] =\> 0 ) in MigrateSQLMap-\>saveIDMapping() (line 337 of /data/disk/o1/static/chartz\_2/sites/all/modules/contrib/migrate/plugins/sources/sqlmap.inc).

Here is my code for this:

```
class AlertNodeMigration extends Migration    {
  public function __construct($arguments)
  {
    parent::__construct();

// SOURCE OBJECT
$directories = array('/data/disk/o1/static/chat_log/html');
$base_dir = '/data/disk/o1/static/chat_log/html';
$regex = '/(.*\.htm$|.*\.html$)/i';
$list_files = new MigrateListFiles($directories, $base_dir, $regex);
$item_file = new MigrateItemFile($base_dir);
$fields = array(
'title' => t('Node: Title'),
'uid' => t('Node: User Id'),
'created' => t('Node: Created Timestamp'),
'changed' => t('Node: Modified timestamp'),
'status' => t('Node: Published'),
'promote' => t('Node: Promoted to front page'),
'sticky' => t('Node: Sticky at top of lists'),
'revision' => t('Node: Create new revision'),
'log' => t('Node: Revision Log message'),
'language' => t('Node: Language (fr, en, ...)'),
'tnid' => t('Node: The translation set id for this node'),
'translate' => t('Node: A boolean indicating whether this translation page needs to be updated'),
'revision_uid' => t('Node: Modified (uid)'),
'is_new' => t('Option: Indicates a new node with the specified nid should be created'),
'field_instrument' => t('Field: Instrument (entityreference)'),
'field_alert' => t('Field: Alert (text_long)'),
'field_alert:language' => t('Subfield: Language for the field'),
'field_sentiment_analysis' => t('Field: Sentiment Analysis (list_text)'),
'field_tags' => t('Field: Tags (taxonomy_term_reference)'),
'field_tags:source_type' => t('Option: Set to \'tid\' when the value is a source ID'),
'field_tags:create_term' => t('Option: Set to TRUE to create referenced terms when necessary'),
'field_tags:ignore_case' => t('Option: Set to TRUE to ignore case differences between source data and existing term names'),
'field_source' => t('Field: Source (list_text)'),
'path' => t('Node: Path alias'),
'comment' => t('Whether comments may be posted to the node')
);
$this->team = array(new MigrateTeamMember('alertnode', 'alertnode@drupal.org', t('Implementor')));
    $this->description = t('Alert Node Migration');

$this->source = new MigrateSourceList($list_files, $item_file, $fields);

// DESTINATION Object
$this->destination = new MigrateDestinationNode('alert');

// MAP OBJECT
    $this->map = new MigrateSQLMap($this->machineName,
    array(
      'sourceid' => array('type' => 'int',
                      'unsigned' => TRUE,
                      'not null' => TRUE,
         )
    ),
    MigrateDestinationNode::getKeySchema()
  );

// FIELD MAPPING OBJECT
$this->addFieldMapping('title', 'title');
$this->addFieldMapping('uid', 'uid');
$this->addFieldMapping('created', 'created');
$this->addFieldMapping('changed', 'changed');
$this->addFieldMapping('status', 'status');
$this->addFieldMapping('promote', 'promote');
$this->addFieldMapping('sticky', 'sticky');
$this->addFieldMapping('revision', 'revision');
$this->addFieldMapping('log', 'log');
$this->addFieldMapping('language', 'language');
$this->addFieldMapping('tnid', 'tnid');
$this->addFieldMapping('translate', 'translate');
$this->addFieldMapping('revision_uid', 'revision_uid');
$this->addFieldMapping('is_new', 'is_new');
$this->addFieldMapping('field_instrument', 'field_instrument');
$this->addFieldMapping('field_alert', 'field_alert');
$this->addFieldMapping('field_alert:language', 'field_alert:language');
$this->addFieldMapping('field_sentiment_analysis', 'field_sentiment_analysis');
$this->addFieldMapping('field_tags', 'field_tags');
$this->addFieldMapping('field_tags:source_type', 'field_tags:source_type');
$this->addFieldMapping('field_tags:create_term', 'field_tags:create_term');
$this->addFieldMapping('field_tags:ignore_case', 'field_tags:ignore_case');
$this->addFieldMapping('field_source', 'field_source');
$this->addFieldMapping('path', 'path');
$this->addFieldMapping('comment', 'comment');

}

public function prepareRow($row)
 {
     return true;
 }

 public function prepare($node, stdClass $row) {

// Set to admin for now.
$node->uid = 1;

// Create a new SourceParser to handle HTML content.
$source_parser = new SourceParser(substr($row->sourceid, 1), $row->filedata);
$alerthtml = $source_parser->parse_alert_html($row->html);

   $node->title = $alerthtml['title'];      // Node: Title
   $node->uid = '1';                //Node: User Id
   $node->created = $alerthtml['timestamp'];    //Node: Created Timestamp
   $node->changed = '0';            //Node: Modified timestamp
   $node->status = 'published';         //Node: Published
   $node->promote = '0';            //Node: Promoted to front page
   $node->sticky = '0';             //Node: Sticky at top of lists
   $node->revision = '0';           //Node: Create new revision
   $row->log = '0';             //Node: Revision Log message
   $node->language = 'en';          //Node: Language (fr, en, ...)
   $node->tnid = '0';               //Node: The translation set id for this node
   $node->translate = '0';          //Node: A boolean indicating whether this translation page
   $node->revision_uid = '1';           //Node: Modified (uid)
   $node->is_new = '1';             //Option: Indicates a new node with the specified nid
   $node->field_instrument = $alerthtml['inst'];//Field: Instrument (entityreference)
   $node->field_alert = $alerthtml['alert_text'];//Field: Alert (text_long)
   $node->field_alert['language'] = 'en';   //Subfield: Language for the field
   $node->field_sentiment_analysis = 'positive';//Field: Sentiment Analysis (list_text)
   $node->field_tags = '0';         //Field: Tags (taxonomy_term_reference)
   $node->field_tags['source_type'] = $alerthtml['src_typ'];//Option: Set to \'tid\' when the value is a source ID
   $node->field_tags['create_term'] = $alerthtml['term'];//Option: Set to TRUE to create referenced terms
   $node->field_tags['ignore_case'] = $alerthtml['ignr'];//Option: Set to TRUE to ignore case differences
   $node->field_source = $alerthtml['src']; //Field: Source (list_text)
   $node->path = $alerthtml['title'];       //Node: Path alias
   $node->comment = $alerthtml['comments']; //Whether comments may be posted to the node
}

}

```

Is anyone can help me ? Thanks in advance.

# Answer
The exception is telling you what the problem is:

```
Invalid datetime format: 1366 Incorrect integer value: '/Chat Log - 07:01:2014.html' for column 'sourceid1' at row 1

```

What this means is that the value that you're trying to assign to a datetime field is incorrect, and it gives you the illegal value that was encountered.

I suspect it's in this code:

```
<?php
  $node->created = $alerthtml['timestamp'];    //Node: Created Timestamp**strong text**
?>

```

The value of $alerthtml\['timestamp'\] appears to be "/Chat Log - 07:01:2014.html", not quite what you expected. You'll want to do some validation to make sure that when you parse out that date value, you get what you expect and clean up as necessary.
> 2 votes

---
Tags: migrations
---


# Question
Title: Using Profile 2 with Entity Reference--How to display the user name and not the "Profile Name"
I've reviewed the threads similar to this, and can't seem to find a definitive answer. I have a Content Type in Drupal 7 where I want to be able to associate multiple users to a content item. For example, I have a "Music Ensemble" content type, and I want the ensemble leader to be able to select all of their ensemble members from the list of user profiles.

I've been through all the steps to configure a view with the Entity Reference Widget, and add / configure the Entity Reference field on my content type. When I go to create a content item, the View loads, displays the correct profile fields and allows me to select users.

However, when I submit the view form and return to the content UI, I get the following:

The "Main profile" text is displayed for every member I select. What I really want to display on the content item is the user's name from their profile.

I can't seem to find a way to configure around this. Is this simply a limitation of the Entity Reference / Profile 2 relationship, or is there something I'm missing that could solve this? I can figure things out on the front-end display with Views, but this is rather challenging for someone unfamiliar with content authoring (which most of my authors are).

Thanks in advance for any help.

# Answer
> 0 votes
You can use Entity View Modes to create a User view mode, and then set the fields for display on that view mode. Then select the view mode in the field formatter for the Entity Reference field.

---
Tags: users
---


title: Import fields and field types

text:
# Question
Title: Import fields and field types
I am developing a Management Information System in Drupal, holding thousands of suppliers in different certification schemes. Due to the nature of these certification schemes, and because of working with third parties, I need to import comprehensive surveys in CSV from other systems. I normally do that via feeds which works fine.

The issue now is how to deal with the big variety of D7 fields. In the present situation I need to key in all these fields, and map them to the import fields in the feeds. Lots of work with about 10 surveys carrying approx. 100 questions each.

Survey questions (= fields) and related Field types are however available in CSV. Would there be a way of importing Fields and Fields types from such CSV into new or existing content types, similar to https://www.drupal.org/project/webform\_auto\_field ?

Posted this question before under Entityform, only realizing later that the question would be more relevant under core.

# Answer
I would use the Migrate module with the CSV as a data source.
> 0 votes

---
Tags: entities
---


# Question
Title: How to build a slider or JCarousel 100% width and previous and next Image with 25% width?
I need to build a Carousel with the following specs:

* width 100%, height 600px
* show 3 items, (previous only 25% screenwidth, current and centered 50% screenwidth and Next also 25% screenwidth). so previous and next item are shown only half.
* layout is responsive (tablet and desktop 3 items, mobile 1 item)

I tried JCarousel, OWl Carousel. But JCarousel shows always full items and not centered. OWL Carousel 2 did work correctly with views (Views 3.8, Jquery Update 2.4, OWL Carousel 2 Dev Version). That is unfortunate because the specs here http://www.owlcarousel.owlgraphic.com/demos/center.html showing exactly what i need (only with 5 images). Did anyone built something similar? Maybe is it possible with adjusting the JCarousel CSS or is there also Javascript needed.

# Answer
I managed to get it to work somehow with css, but had some bugs when trying to skip to the next item infinitly.

Now it works better with Flexslider and i applied this css http://jsfiddle.net/Y3kx5/2/.
> 0 votes

---
Tags: theming, javascript
---


title: Simple twitter module recommendation

text:
# Question
Title: Simple twitter module recommendation
Can anyone recommend me a simple twitter module which will enable me to include twitter feeds on my site? I am using a corporate clean theme and would like to display it in the middle column of the footer section.

# Answer
You should use the Twitter module.

> This module provides API integration with the Twitter microblogging service. Out of the box, it allows users to:
>
> * Associate one or more Twitter accounts with their Drupal user account
> * List tweets in different ways thanks to Views
> * Post to their own Twitter account or a site-wide Twitter account whenever they create new content or based on Drupal Actions or Rules
> * Log in to your Drupal site via Twitter
> * Format twitter @usernames and #hashtags as links to Twitter.com
> 6 votes

# Answer
If your needs are simple I would choose a Twitter widget. If you need more advanced integration then I would suggest the Twitter module, perhaps along with Twitter Pull (7.x-2.x-dev), as that is basically the only option with OAuth authentication which will be required when Twitter shuts down API v.1, if they haven't already done so. Most other Twitter modules will no longer work when that happens, and right now the Twitter module is the best option.
> 2 votes

# Answer
The Twitter Block module provides configurable blocks for a Twitter feed.

Other Tweet modules which might be useful are:

* Tweet button adds the Twitter buttons to your nodes.
* Twitter provides API integration with the Twitter microblogging service. Out of the box, it allows users to:

+ Associate one or more Twitter accounts with their Drupal user
    account
    + List tweets in different ways thanks to Views
    + Post to their own Twitter account or a site-wide Twitter account whenever they create new content or based on Drupal Actions or Rules
    + Log in to your Drupal site via Twitter
    + Format twitter @usernames and #hashtags as links to Twitter.com
> 0 votes

# Answer
The Twitter module is your best bet. I know it can be intimidating at first but just follow the directions and you should be fine. Here's a step by step.

1. download and install the module.
2. go to https://apps.twitter.com/app/new and register your application
3. then go to admin/config/services/twitter/settings and enter your OAuth Consumer key and OAuth Consumer secret and save
4. Then go to admin/config/services/twitter and add an authenticated account. You can also add other users accounts.

Once you've done all that, you can use views to pull in tweets and display them in pages and blocks.

Hope this helps you out.
> 0 votes

---
Tags: 7, social-network
---


# Question
Title: Hiding a filter in a view with same filter in contextual filters
I've a simple problem. In Views I've city filter(exposed) set that'll show jobs in a city. Now I've set the same City in contextual filters as well with the condition to show all values when no argument is supplied. So this view is "General Advanced Job Search"

Now I want to offer "Jobs in Citi1", "Jobs in Citi2". But I want to reuse the same View without duplicating it. I'd call it "Advanced Job Search given a city".

So I can pass the arguments as Citi1 etc and it'd show Jobs in Citi1 at the same time it'll show City filter as drop down in Filter Criteria. I want to hide this City in Filter criteria as it is of no use as cities are already being limited by the argument passed(Citi1).

I've tried searching here and there but nothing found.

**In short if argument is passed to a view I want to hide an exposed field show in filter criteria.**

# Answer
The following code will help you to solve your issue.

```
/**
 * Implement hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {

  if($form_id == 'views_exposed_form') {
    if($form['#id'] == 'views-exposed-form-myview-page') {
       // argument 1 represent city1
      if(arg(1)) {
        // hide city field
        unset($form['#info']['filter-jobs_in_city']);
        hide($form['jobs_in_city']);
      }
    }
  }
}

```

**Notes:**

* Replace form id `views-exposed-form-myview-page` with your own form id
* Replace argument 1 with the right City1 argument index
* Replace `jobs_in_city` field name with your own city field
> 2 votes

# Answer
You can use this module

https://www.drupal.org/project/filter\_harmonizer

It fixed that problem for me. if you have the same exposed filter as a contextual filter this module helps you to avoid this problem. Read the instrucions in the module's page
> 0 votes

---
Tags: 7, views
---


# Question
Title: Can't get module configuration form into modal
I'm writing my first Drupal 7 module. I've successfully created the block's html and integrated that with the home page. I've also succeeded in creating a configuration form fo the block.

However, you can only access the configuration form by going to mysite.com/admin/config/content/mymodule and I would much rather have the user be able to access it in the modal that appears when they click the upper-right gear and click "Configure block."

Is there a good way to add my module configuration form to the block configuration?

# Answer
> 1 votes
You need to add your configuration form using the hook\_block\_configure instead of making it a page. Add your information to the form as you would any normal drupal form api along with your validate and submit functions. You will also need to hook into hook\_block\_save for save functionality.

---
Tags: forms, javascript
---


# Question
Title: Why does a try block affect drupal_set_message?
I have a try block set up:

```
try {
//some code
throw new Exception ( 'My exception message' );
}
catch ( Exception $e )
drupal_set_message('Caught exception: '. $e->getMessage(),1);}

```

But instead of using 'status', 'warning' or 'error' I used an integer and get a greyish looking message box. Are there any other "hidden" drupal\_set\_message options? Thx

# Answer
> 1 votes
The second argument of drupal\_set\_message() should be a string. This string is just added as a class around the message. It an be anything you want.

---
Tags: users, database, forms
---


# Question
Title: Content type or web form(creating own form using hooks) Which one is best way of collecting input from user?
I am new to Drupal and learning is in progress. I know about content types and creating webforms using hooks. Now I want to collect data from user and store it to db and view it later (easily I can do with a content type) but I need to apply some jQuery events. i.e. if user choose a country then in another drop down I want to show the states of that particular country and I want to change input style.

Which suits best for above problem and why not another one more suitable?

# Answer
> 1 votes
If you dont want to make your hands dirty playing with code then better use webform module as per your drupal version. Webform module in drupal gives you everything, you dont need to make further queries to manage the input data, its just a use of normal CMS. Better try with that, an in addition you can export data as well. I hope this helps you. Thanks

# Answer
> 0 votes
yeah you can do that, the way it is done in normal form. You can use all the normal hook that are used in form. Thanks

---
Tags: javascript, theming, forms
---


title: node access by related fields

text:
# Question
Title: node access by related fields
I have created the following List field type of checkboxes to allow users to select their own content's privacy settings when creating a node called RideShares:

```
1|me only
2|any registered site member
3|users on the same flights as me
4|users arriving at the same airport during the same week as me.
5|public

```

I can use the exposed filter to manually select any matching nodes, but do not know how to automatically filter the queried RideShares to the current user's data in other bundle/content types. For example, whether the current user has entered a Flight into where the destination airpor catches one of the existing RideShares.

It seems this cannot be done with context filters in Views.

# Answer
> 0 votes
> I can use the exposed filter to manually select any matching nodes, but do not know how to automatically filter the queried RideShares to the current user's data in other bundle/content types. For example, whether the current user has entered a Flight into where the destination airpor catches one of the existing RideShares.

Views is a simple query builder. Typically this would be SQL like `Select * From RideShares Where city = 'denver'`. Your question cannot be expressed in single SQL expression you would need `JOINs` in SQL of PHP and multiple queries to arrive at an answer.

Your talking about *relating* a set of results with additional logic or data-sources.

This can be done in Drupal using a combination of Views Relationships perhaps Attachment Views to build results you want.

For example I might create a Nodequeue of `uids` that are `users on the same flights as me` and examine a View result that uses the Nodequeue as a `Filter` against the current user to see if that logic produces any results.

You could then place many view `blocks` on a single page that acts as a search results page. Each block can be a View with many view-attachments, etc.

---
Tags: 7, views
---


# Question
Title: How do I add different URL to the HOME link in the breadcrumb for the authenticated user
I'm using breadcrumbs in my drupal 7 website.

How and where do I change the URL for the \[home\] breadcrumb, based on role/authentication of the user - when the authenticated user signs in, they are taken to role based page, when they hit the home breadcrumb, I want them taken back to their role-based home page/url, not the main/anonymous user home page.

I think I want to add a preprocessor function to the template.php that will say--\> function themename\_breadcrumb() {if auth\_user home url is $this else $homeURL is $this}. How would I write this?

# Answer
You could use the theme\_breadcrumb hook and change the link for the home breadcrumb by checking the role of the currently logged in user.

I've put some sample code in below, but I am assuming that your breadcrumbs array will always have the 'Home' breadcrumb as the first element.

This code should go in template.php

```
function yourtheme_breadcrumb($variables) {
  global $user;
  $breadcrumb = $variables['breadcrumb'];

  if (!empty($breadcrumb)) {

    // Check if the user has the right role.
    if(in_array('your_role', $user->roles)) {
      $breadcrumb[0] = l('Home', 'path-to-role-homepage');
    }

    $output = '<h2 class="element-invisible">' . t('You are here') . '</h2>';
    $output .= '<div class="breadcrumb">' . implode(' » ', $breadcrumb) .'</div>';
    return $output;
  }
}

```

Hope that helps out.
> 1 votes

# Answer
I think you could use the Rules module to redirect from the root page to the desired page if the user has the selected role.
> 0 votes

---
Tags: theming, breadcrumbs
---


title: Database query with WHERE and ORDER BY

text:
# Question
Title: Database query with WHERE and ORDER BY
Can't figure out why the following query executes directly through phpMyAdmin perfectly well:

```
SELECT id FROM `stats` WHERE type="load" ORDER BY id DESC LIMIT 1

```

but firing this:

```
db_query('SELECT id FROM {stats} WHERE type = '.$param.' ORDER BY id DESC LIMIT 1')->fetchField();

```

from a module outputs:

```
PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'load' in 'where clause': SELECT id FROM {server_stats} WHERE type = load5 ORDER BY id DESC LIMIT 1; Array ( ) in server_tab_stats_submit() (line 750 of /home/dev/public_html/sites/all/modules/custom/server/server.inc).

```

Column's name there is "type", I don't know why Drupal query thinks "load" is a column, it is just a value derived from $param variable.

# Answer
> 0 votes
Try This

```
$nid = db_query('SELECT id FROM {stats} WHERE type = :type ORDER BY id DESC LIMIT 1', array(':type' => $param))->fetchField();

```

Refer db\_query for more information...

---
Tags: database
---


# Question
Title: Customize login block's position in page.tpl
I'm trying to position my login block in my page.tpl file. Everytime I insert the code

`<?php print drupal_render(drupal_get_form('user_login')); ?>`

in my page.tpl file. It throws an error. The error it throws is

> Strict warning: Only variables should be passed by reference in include() (line 79 of C:..\sites\all\themes\neptune\templates\page.tpl.php).

How can I fix this issue?

# Answer
You can do it like this:

```
if(!user_is_logged_in() ){
    $userLoginForm = drupal_get_form('user_login');
    print drupal_render($userLoginForm);
}

```

because drupal\_render receives argument as reference..
> 0 votes

---
Tags: forms, users
---


# Question
Title: create double view with same url alias for different theme
In my drupal. I created a two theme one for desktop and another for mobile using Mobile switch I change the theme. Now I Created a View as a page for desktop with alias "xxx/yyy" and for mobile also I created a view as a page with same alias "xxx/yyy"(some modification Done). While switching the theme from desktop to mobile, the desktop view is appear. How to differentiate?

# Answer
ok

create a menu with hook\_menu then with checking condition you want load your views in callback of your menu

Something like below

```
/**
 * Implements hook_menu().
 */
function mymodule_menu() {
  $items['myurl'] = array(
    'title' => 'title',
    'page callback' => 'myfunction_callbackfuction',
    'access callback' => TRUE,
  );

  return $items;
}

function myfunction_callbackfuction() {
  $view = views_get_view('view_name');
if($mycondtion)
  $view->set_display('page1');
else
  $view->set_display('page2');

  $view->pre_execute();
  $view->execute();
  print $view->render();
}

```
> 3 votes

# Answer
I achieve this by using

```
$view_name = 'my_views_name';
$display_id = 'my_views_display_id';
print views_embed_view($view_name , $display_id);

```
> 0 votes

---
Tags: views
---


title: No suggestions in Data Selector (Rules)

text:
# Question
Title: No suggestions in Data Selector (Rules)
following this guide to display alternative prices for certain roles: http://jamestombs.co.uk/2012-09-14/drupal-commerce-different-prices-different-customer-groups

But for some reason I don't get any suggestions or dropdown in the Data Selector field.

I've tried changing jquery versions which doesn't correct the error.

Any other ideas? I've added a detailed description of my approach below the screenshot.

It's a d7 commerce site, all modules is the latest versions

Step by step approach to making the pricing rule

1. created 'retailer' role
2. added a new field of the type 'price' called field\_ppd (ppd = price per dealer)
3. created a 'retail price' rule at admin/commerce/config/product-pricing/rules/add
4. added a 'Entity has field' condition
5. And it's in the condition config I'm stuck since the Data Selector field doesn't auto-suggest when I start typing

# Answer
It is a bug in the rules module. The issue is discussed HERE.
You can either apply the patch in the issue or use the latest dev version of the jquery update module which allows you to select the drupal default version of jquery for the backend.
> 1 votes

# Answer
Thanks @2pha. To elaborate:

* I disabled jQuery Update, cleared the cache, checked that Rules were working (they were), reenabled jQuery Update. At this step Rules was out of order again, with 1-5 as admin and 1.8 as default. I tried changing to 1.7 as admin version, still no result. I then tried new settings in the CDN field. Having 1.7 as admin with jQuery as CDN works:)
> 0 votes

---
Tags: commerce, rules
---


# Question
Title: The requested page could not be found error appear in page but page is render correctly-drupal 7
i had create one block in my custom module, which display in "CONTENT" region, only on "currant-trustees" page.

when i access url "localhost/drupal/currant-trustees" page is render correctly, but with error "The requested page "/drupal/currant-trustees" could not be found." and also page title is page not found.

# Answer
It sounds to me like you only want to show said block on that page and nothing else. You might be better off implementing hook\_menu() to register a callback (a page) which displays custom content, instead of creating an empty page and showing a block on that.

It might look something like this:

```
/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {
  $items['currant-trustees'] = array(
    'page callback' => 'MYMODULE_currant_trustees',
    'title' => 'Currant trustees',
    'type' => MENU_CALLBACK,
  );
  return $items;
}
function MYMODULE_currant_trustees() {
  $content = 'This is where your content should go, just copy the code from the block content';

  return $content;
}

```
> 1 votes

# Answer
The problem is i just registered block with specific page/url, but there is no any page/url on which drupal going to display block, so first i need to register page/url in drupal so create one page and than display block on that page.
> 0 votes

---
Tags: 7
---


# Question
Title: How to force Local Task Menu to display on specific pages
I’ve made a tabbed display out of my Local Task Menu as imaged.

Some of the extra buttons are ‘pages’ as made with ‘pages manager’ . Here you can assign the page to the Local Menu; when doing so by this method the created page also shows with these user tabs.

However a couple of pages ( one created by the Nodequeue and the other a Custom Module made by myself ) ; with these I’ve assigned to MENU\_LOCAL\_TASK in hook\_menu\_alter . And although they show up in the menu when clicked on they no longer have the Local Task Menu. Does anyone know a way I can force these pages to show it ?

Many thanks

# Answer
> 0 votes
I managed to solve this be engineering a fix with ( https://www.drupal.org/project/local\_tasks\_blocks )

There is a patch here at https://www.drupal.org/node/2141653 for 'Fixed path for displaying tabs' which sounds like the same issue I had . However the patch didn't work for me.

Checking the value of $tasks\['#primary'\] ; I concluded that if I could keep this array for a session then I could use the Local Tasks Menu on all the pages I wished while the User is logged in. Ie something like

```
if (empty($tasks['#primary'])) {

// 1.  Check the cookies if we have one then use that
if (isset($_SESSION['usertasks']['primary'])) {

$tasks_primary = $_SESSION['usertasks']['primary'];
$tasks['#primary'] = $tasks_primary;
}
else {
$usertasks = &$_SESSION['usertasks'];
// well need to create a new instance of this array so we don't    effect it for the page we're on
$tasks_primary = $tasks['#primary'];
$usertasks['primary'] = $tasks_primary;
  }
}

```

My next step is to make a patch for this if anyone else may find it of use.

---
Tags: routes
---


# Question
Title: Add and customize login block on page.tpl
I'm trying to add the user login block in my page.tpl file. I've tried inserting the following code but the only thing I see is the username, password and submit fields. The "Register" and "Forgot your Password" fields are not there. And I would like to do this in code form. Cause I wanna put the user login block in a specific place.

```
if(!user_is_logged_in() ){
    $userLoginForm = drupal_get_form('user_login');
    print drupal_render($userLoginForm);
}

```

Thanks :)

# Answer
> -1 votes
you can do it like this:

```
$block = block_load('user', 'login');
$block = _block_render_blocks(array($block));
$block_build = _block_get_renderable_array($block);

print drupal_render($block_build);

```

this will generate a block with title and contexual links also..

---
Tags: forms, users
---


title: File upload empty in custom form

text:
# Question
Title: File upload empty in custom form
I have a really simple form with a file upload. It actually used to work until I recently noticed it's not saving the file. When I check for the submitted values, the file field is empty, but the file is in $\_FILES.

Here is how I build the form:

```
function tag_graphics_form($form_state) {
    $form = array();
    $form['tag'] = array(
        '#required' => TRUE,
        '#type' => 'textfield',
        '#title' => t('Tag'),
        '#size' => 30,
      );
    $form['image'] = array(
        '#type' => 'file',
        '#title' => t('Image for tag page'),
        '#description' => 'Recommended width for image: 605px'
    );
    $form['description'] = array(
        '#type' => 'textarea',
        '#title' => t('Page Description for SEO')
    );
    $form['#attributes'] = array('enctype' => "multipart/form-data");
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Save'
    );
    return $form;
}

```

And this is how I process things in the submit:

```
function tag_graphics_form_submit( $form, &$form_state ) {
    // save the image and put to the database
    print_r($form_state['values']);  // the image field is completely empty here. other fields are ok
    print_r($_FILES); // the uploaded file is here just fine
    if ($form_state['values']['image']) { // all of this used to work...
        $validators = array();
        $file = file_save_upload('image', $validators, file_directory_path());
        file_set_status($file, FILE_STATUS_PERMANENT);
        $filepath = $file->filepath;
    }
    // more code...
}

```

# Answer
```
function tag_graphics_form($form_state) {
    $form = array();
    $form['#attributes'] = array('enctype' => "multipart/form-data");
    $form['tag'] = array(
        '#required' => TRUE,
        '#type' => 'textfield',
        '#title' => t('Tag'),
        '#size' => 30,
      );
    $form['image'] = array(
        '#type' => 'file',
        '#title' => t('Image for tag page'),
        '#description' => 'Recommended width for image: 605px'
    );
    $form['description'] = array(
        '#type' => 'textarea',
        '#title' => t('Page Description for SEO')
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Save'
    );
    return $form;
}

function tag_graphics_form_validate($form, &$form_state){
  $field = 'image';

  $directory = file_directory_path();
  if (file_check_directory($directory, FILE_CREATE_DIRECTORY, $field)) {
    $validators = array();
    if ($file = file_save_upload($field, $validators, $directory)) {
      file_set_status($file, FILE_STATUS_PERMANENT);
      $form_state['storage']['file'] = $file;

    }
  }
}
function tag_graphics_form_submit(&$form, &$form_state){
  print_r($form_state['storage']['file']);
}

```
> 1 votes

---
Tags: 6, forms
---


# Question
Title: How to automatically create subitems based on node entries?
I have a content type called "brand", and about 30 brands. I want them to automatically appear as a list of items below a main parent menu item. Is there something that does this already?

# Answer
Try the Content Menu module.

This module provides an easy way to add existing nodes (content) as a sub item to menu.

> Content menu module improves Drupal's default menu management interface for tighter integration of content authoring and menu management, so content can be created and edit right from the menu interface (e.g. creating content for a menu item that has been just created. See the screenshot
> 1 votes

---
Tags: routes
---


# Question
Title: Show datetime value in views with entity api
I made a custom entity with a date field stored as datetime in mysql.

I see the proper output in my content, and all other field values in my views except the datetme value. Only the label is shown. So I believed that I have to write a getter callback because of this:

> getter callback: (optional) A callback used to retrieve the value of the property. Defaults to entity\_property\_verbatim\_get(). It is important that your data is represented, as documented for your data type, e.g. a date has to be a timestamp. Thus if necessary, the getter callback has to do the necessary conversion. In case of an empty or not set value, the callback has to return NULL.

Question is how to use it? Apparantly I have to get a timestamp from a datetime field!???

Another one mentioned that views doesn't relate to property\_info():

> Getter and Setter callbacks are used only by entity metadata wrappers, not Views.

So my code looks like this atm:

```
$info['pricedefault']['properties']['preis_zeitraum_von'] = array(
'label' => t('Start period'),
'description' => t('Preis Zeitraum von'),
'type' => 'date',
'schema field' => 'preis_zeitraum_von',
);

```

So it makes no sense to add a getter callback??? Or do I have to make my own views entity controller class?

ATM I'm very confused. Can anybody explain how to proceed?

THX in advance

maen

# Answer
You won't need to define a custom getter callback for known data types with a schema field since it can use entity\_property\_verbatim\_get as it's getter callback, which is used by default if no 'getter callback' property is set.

```
$properties = &$info['foo']['properties'];
$properties['created'] = array(
  'label' => t('Date created'),
  'description' => t('The date the foo entity was created.'),
  'type' => 'date',
  'schema field' => 'created',
);

```

For maximum control, I would suggest you try describing your entity to views. Assuming you have an entity type called **foo**, stored in the table **foo** with a **created** field, you can:

```
/**
 * Implements hook_views_data()
 */
function foo_views_data() {
  $data = array();

  $data['foo']['table']['group']  = t('Foo entity');

  $data['foo']['table']['base'] = array(
    'field' => 'foo_id',
    'title' => t('Foo entity'),
    'help' => t('The foo entity.'),
  );
  $data['foo']['table']['entity type'] = 'foo';

  // Expose a timestamp (e.g. created date).
  $data['foo']['created'] = array(
    'title' => t('Created'),
    'help' => t('The date the foo was created.'),
    'field' => array(
      'handler' => 'views_handler_field_date',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort_date',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_date',
    ),
  );
}

```

Then, you can also do things like:

```
// An argument handler accepting year and month
$data['created']['created_year_month'] = array(
  'title' => t('Created year + month'),
  'help' => t('In the form of YYYYMM.'),
  'argument' => array(
    'field' => 'created',
    'handler' => 'views_handler_argument_node_created_year_month',
  ),
);

```

For more info on integrating with views, you can install Advanced help module, and check out the included Views documentation.
> 1 votes

---
Tags: views, datetime, entities
---


# Question
Title: Add a youtube video in the template file using url
I've tried using this code `<?php print theme('video_embed_field_embed_code', array('url' => $video['http://www.youtube.com/embed/Zz1HPLtecOg'])); ?>` but it only displays the url and doesnt show the video. How can I fix this?

# Answer
> 0 votes
```
<?php print render($content['field_video_url]']);?>

```

try this

---
Tags: 7, files
---


# Question
Title: How to pass custom variables into drush site-install?
I'm installing drush profile via:

```
drush site-install my_profile --db-url=db.url --account-name=admin --account-mail="admin@example.com" --site-mail="admin@example.com" --site-name="My Site"

```

**But how I can pass some variables into my\_profile to initialize them with default values?**

In example I'd like to set specific file\_public\_path and file\_private\_path as some module fails to install because of the folder misconfiguration.

# Answer
You can add any additional settings you wish to pass to the profile in the following format (the key is in the form `[form name].[parameter name]`):

```
drush site-install my_profile install_configure_form.site_default_country=FR my_profile_form.my_settings.key=value
drush site-install my_profile install_configure_form.date_default_timezone="Europe/London" update_notifications.update_status_module=1
drush site-install my_profile variables.file_public_path="sites/default/files" variables.file_private_path="sites/default/private/files"

```

Then you can handle the variables in your profile code by either implementing `hook_install_tasks` or `hook_install_tasks_alter` where you can access `$install_state` array which have information about the current installation state of your profile and your variables which can be accessed in `$install_state['forms']`.

In example (when set from drush via `variables.X="Y"`):

```
foreach ($install_state['forms']['variables'] as $name => $value) {
  variable_set($name, $value);
}

```

For `file_public_path` and `file_private_path`, it's not enough only to pass the variables, but you should prepare the directories as part of the installation script, e.g.:

```
file_prepare_directory($install_state['forms']['variables']['file_public_path'], FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
file_prepare_directory($install_state['forms']['variables']['file_private_path'], FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
file_prepare_directory($install_state['forms']['variables']['file_temporary_path'], FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
drupal_static_reset('file_get_stream_wrappers'); // clear static cache for stream wrappers

```

This was implemented in drush as part of Site Install: allow passing additional form parameters feature request.

Please note that above feature it's only supported on Drupal 7 and above.
> 5 votes

---
Tags: drush
---


# Question
Title: CKEditor 4 library is not detected by Wysiwyg module
The Wysiwyg installation instructions tell me to

> Extract the archive and copy its contents into a new folder in the following location: sites/all/libraries/ckeditor
>
> So the actual library can be found at: sites/all/libraries/ckeditor/ckeditor.js

These 2 conditions are met, however in the overview of editors, the CKEditor is now red. So it sees something is there, it's just not right. What can be wrong? where should i be looking to troubleshoot?

# Answer
The WYSIWYG module is not compatible with CKEditor 4, because CKEditor 4 uses double quotes `"` around it's version string, where CKEditor 3 used single quotes `'`. This breaks the version detection regex in the WYSIWYG module.

You could use CKEditor 3, like Bruno suggests, or you could patch the WYSIWYG module like described here https://drupal.org/comment/6790812#comment-6790812.

In `editors/ckeditor.inc`, replace line `81`:

```
if (preg_match('@version:\'(?:CKEditor )?([\d\.]+)(?:.+revision:\'([\d]+))?@', $line, $version)) {

```

with:

```
if (preg_match('@version:[\"|\'](?:CKEditor )?([\d\.]+)(?:.+revision:[\"|\']([\d]+))?@', $line, $version)) {

```

If you're not bound to using the WYSIWYG module, you could also use the CKEditor module.
> 13 votes

# Answer
Try an older version of the editor, some newer doesn\`t support by the wysiwyg module. Look at the name of the .js data file.
> 1 votes

# Answer
You can too use the "dev" branch of the "wysiwyg" module.
> 1 votes

# Answer
wyguf seak is correct the older version WILL work. go to http://ckeditor.com/download/releases and 3.6.1 and that will work for you.

The latest version did not work for me, so I went for older versions
> 0 votes

---
Tags: 7, wysiwyg, installation
---


title: Nesting Navigation Tabs

text:
# Question
Title: Nesting Navigation Tabs
In my custom module, I'm defining a menu\_item with the type *MENU\_NORMAL\_ITEM*. In the default bartik theme, this adds a new navigation tab (next to the *Home* tab). This is great; however, I need nested tabs as well! Something like the following:

```
<li>Home (default tab on Bartik)</li>
<li>Menu Navigation Item added via custom module</li>
    <ol>
        <li>Nested Friend</li>
    </ol>
</li>

```

With a structure similar to this, my frontend guys can theme around this and make a dropdown out of it. I've tried this:

```
$items['custom tab'] = array...
$items['custom tab/sub-item'] = array...

```

But there's no luck, and it's not even rendered when I clear my caches and do na inspect element, so I know it's not hidden or anything. I think I'm attempting to define a parent/child relationship purely through PHP. Any tips?

# Answer
You need to change the type for submenu.

```
 $items['custom tab'] = array(
    'type' => MENU_NORMAL_ITEM,,
);
 $items['custom tab/sub-item'] = array(
    'type' => MENU_DEFAULT_LOCAL_TASK,
);

```
> 1 votes

---
Tags: routes
---


# Question
Title: Apply different css files according to user selection
Use case: content managers would have permissions to change the color scheme of the site.

Solution: I would make a page from hook\_menu and give option to select from different pre defined css files.

Is there a hook/function I can use to render css files accordingly as per selected by user.

like: user selects red option the red named css file should render on site and previous, default css should be overridden.

Thanks

# Answer
> 0 votes
I found the link bit helpful... It might help you too. http://wearepropeople.com/blog/7-ways-to-add-custom-js-and-css-to-a-page-in-drupal

# Answer
> 0 votes
at the time of using hook\_menu 'page callback' =\> 'your\_php\_function',

then later in function

function your\_php\_function(){

drupal\_add\_js() // check for this function in google and add your js file here

drupal\_add\_css() // check for this function in google and add your css file here

/\* * your code goes on \*/

# Answer
> 0 votes
Create a specific module "custom\_css" for exemple.

Use a single function custom\_css\_preprocess\_page() https://api.drupal.org/api/drupal/includes%21theme.inc/function/template\_preprocess\_page/7

inside call the Global $user; get the css value form $user node and use like shrindar say, the drupal\_add\_css() function.

And it should work. If the red is selected, you'll charge the red CSS. Be care, you'll maybe need to flush your cache if you activated them.

Why do you want to create a custom page from hook\_menu? You can in Drupal 7 add fields to the profile, each user can choose his own theme from the edit profile page.

---
Tags: theming
---


# Question
Title: How can you load redirects for a node to delete them? (redirect api)
I'm trying to create a module which creates a redirect when a node is unpublished and removes it if the node is published again.

The redirect module API, has functions for doing both `redirect_save` and `redirect_delete`.

However I can't work out how to load all the redirects for a specific node in order to delete them, I think you might be able to use `redirect_load_by_source` but I can't work out how to get it to function correctly.

Has anyone tackled this sort of problem before?

# Answer
Asked a question to soon. Solved it by digging around in the redirect module tables. Here's an example of what a couple rows look like.

```
+-----+---------------------------------------------+----------+-----+---------------------------------------------------------------+----------------+-----------+------------------+----------+-------------+-------+------------+
| rid | hash                                        | type     | uid | source                                                        | source_options | redirect  | redirect_options | language | status_code | count | access     |
+-----+---------------------------------------------+----------+-----+---------------------------------------------------------------+----------------+-----------+------------------+----------+-------------+-------+------------+
|   2 | FLzM1K67ig-cItlqDDOPhWjLytEuRwdnvXW9e7Nk7TA | redirect |   0 | mypath/nodetype/node-title                                    | a:0:{}         | node/1275 | a:0:{}           | und      |           0 |   108 | 1410048251 |
|   3 | WUltm2RBISR13aRoShkSvOIvZSAgoA8Wn5miIvUIS9w | redirect |   0 | mypath/nodetype/node-title2                                   | a:0:{}         | node/1276 | a:0:{}           | und      |           0 |     5 | 1409544283 |

```

As you can probably now see it's fairly obvious that `$source` is referring to the redirect that was created. This does appear to mean it's not possible to look up all the redirects related to one node, not a problem in my case but perhaps a problem for someone else in the future.
> 0 votes

---
Tags: 7, redirection
---


title: Re-use a form array multiple times

text:
# Question
Title: Re-use a form array multiple times
I'm a little stuck here. I want to make a block with 4 upload fields. So i'm trying to set the keys in 1 form array with the name file\_link.

When editing the block, I can see the 4 upload fields. But when i'm trying to save the block Drupal gives me an error: (*Notice: Undefined index: file\_link in block\_with\_fields\_block\_save()*).

It seems something goes wrong in the block\_save() function. Any idea how I can solve this? Here's my code:

```
function block_with_fields_block_configure($delta) {

$form = array();

switch($delta) {
    case 'test':
    $description = variable_get('description', array('value' => '', 'format' => NULL));
    $file_link = variable_get('file_link', array());

        $form['description'] = array(
            '#type' => 'text_format',
            '#title' => t('Text'),
            '#cols' => 60,
            '#rows' => 10,
            '#description' => t('WYSIWYG text block'),
            '#required' => TRUE,
            '#format' => isset($description['format']) ? $description['format'] : NULL,
            '#default_value' => $description['value'],
        );
        $form['file_link'] ['first_field'] = array(
            '#tree' => TRUE,
            '#type'         => 'managed_file',
            '#title'        => t('1st file'),
            '#size'         => 60,
            '#description'  => t('Select your file'),
            '#upload_location' => 'public://',
            '#default_value' => variable_get('file_link'),
            '#upload_validators' => array(
                                    'file_validate_extensions' => array(),
                                    'file_validate_size' => array(26214400)
                                    ),
        );
        $form['file_link'] ['second_field'] = array(
            '#type'         => 'managed_file',
            '#title'        => t('File 2'),
            '#size'         => 60,
            '#description'  => t('Select another file'),
            '#upload_location' => 'public://',
            '#default_value' => variable_get('file_link'),
            '#upload_validators' => array(
                                    'file_validate_extensions' => array(),
                                    'file_validate_size' => array(26214400)
                                    ),
        );
        $form['file_link'] ['third_field'] = array(
            '#type'         => 'managed_file',
            '#title'        => t('File 3'),
            '#size'         => 60,
            '#description'  => t('Another one...'),
            '#upload_location' => 'public://',
            '#default_value' => variable_get('file_link'),
            '#upload_validators' => array(
                                    'file_validate_extensions' => array(),
                                    'file_validate_size' => array(26214400)
                                    ),
        );
        $form['file_link'] ['fourth_field'] = array(
            '#type'         => 'managed_file',
            '#title'        => t('File 4'),
            '#size'         => 60,
            '#description'  => t('Misc'),
            '#upload_location' => 'public://',
            '#default_value' => variable_get('file_link'),
            '#upload_validators' => array(
                                    'file_validate_extensions' => array(),
                                    'file_validate_size' => array(26214400)
                                    ),
        );
    break;

}
return $form;
}

function block_with_fields_block_save($delta = '', $edit = array()) {
switch($delta) {
    case 'test':
        variable_set('description', $edit['description']);
/** Line below caused notice */
        variable_set('file_link', $edit['file_link']);

$current = variable_get('file_link', NULL);
$current_fid = isset($current['report']['fid']) ? $current['report']['fid'] : NULL;

if ($current_fid) {
    if ($data['report']['fid'] != $current_fid) {

    $file = file_load($current_fid);
        if (is_object($file)) {
            file_usage_delete($file, 'block_with_fields', 'report');
            file_delete($file);
        }
    }
}

break;
}
return;
}

```

# Answer
The problem seems to be of the 'file\_link' element missing from the edit() array. The line where you have commented that the below line is causing issue, there you need to debug the edit array and make sure you are having the '**file\_link**' element in that array, few things that can be done are:

* Debug the value of `$edit['file_link']);` using `dpm()` provided by the devel module, or just use the `print_r()` or so and make sure that you are getting the required value otherwise may the element you are trying to access is having different key and you can just check the complete edit() array.
* The variable 'file\_link' whose value you are trying to set is the correct and the required variable, cross check the name of the variable.
* Create a check for the value before assigning or adding it to the variable to make sure that the values is available and to avoid this kind of errors.
> 1 votes

# Answer
The problem is that I placed the #tree property wrong. As what Ayesh explained on the Drupal Forums:

Use of '#tree' property will make Drupal to put submitted values of child form elements into an array (instead of a flat single-level array). However, this '#tree' must go to the parent.

Add this right before any line that adds child elements to the $form\['file\_link'\] array.

```
<?php
$form['file_link']  = array(
        '#tree' => TRUE,
    );
?>

```

After this, Drupal knows children of $form\['file\_link'\] should have 'file\_link' as its parent.

More information here: http://ayesh.me/drupal-bad-practices#tree
> 1 votes

---
Tags: forms
---


# Question
Title: Have an exposed filter on a view be a list of US states
I would think this would be a pretty common thing, but I have a job board that I am exposing for users to search on. They can search by city and/or state so I exposed some filters on my view for city and state. Now, of course, plain text boxes work fine out of the box if I want the user to freely type in a state, but I really want it to be a dropdown of states. I see that I can do a "Grouped Filter" which allows me to specify some key|value pairs, but do I REALLY need to enter in all 50 states manually? Is there a way programatically to have the dropdown be a list of states? I also noticed that even if I DO specify a few values to test with like AZ|AZ, CA|CA, NV|NV, when I go to use the exposed filters instead of the URL being something like this:

```
http://sandbox/job-board?city=&state=AZ

```

it actually uses:

```
http://sandbox/job-board?city=&state=1

```

where there is a "1" instead of "AZ". I would really like to be able to pass "AZ" not a 1 in the URL because if I have other apps posting to the job search page, I don't want to have to map ID's to actual state values, I just want to pass in the state code. What's the best way to go about this?

THANKS

# Answer
Thanks guys. I don't think the Address Field module will work for me because the field I am exposing is not an address field. It is a field from a custom table, so I don't think the Address field module would pick that up. Anyway, I ended up just doing a form alter on the exposed filter form swapping out the text box with a drop down of states and it works great:

```
/*
*    hook_form_alter()
*/
function bullhorn_form_alter(&$form, $form_state, $form_id) {

  // Check form is exposed filter, object is a view and view name
  if ($form_id == 'views_exposed_form' && is_object($form_state['view']) && $form_state['view']->name=='job_board' ) {

    $states = array(
      ''=>'-ALL-',
      'AL'=>'Alabama',
      'AK'=>'Alaska',
      'AZ'=>'Arizona',
      'AR'=>'Arkansas',
      'CA'=>'California',
      'CO'=>'Colorado',
      'CT'=>'Connecticut',
      'DE'=>'Delaware',
      'DC'=>'District of Columbia',
      'FL'=>'Florida',
      'GA'=>'Georgia',
      'HI'=>'Hawaii',
      'ID'=>'Idaho',
      'IL'=>'Illinois',
      'IN'=>'Indiana',
      'IA'=>'Iowa',
      'KS'=>'Kansas',
      'KY'=>'Kentucky',
      'LA'=>'Louisiana',
      'ME'=>'Maine',
      'MD'=>'Maryland',
      'MA'=>'Massachusetts',
      'MI'=>'Michigan',
      'MN'=>'Minnesota',
      'MS'=>'Mississippi',
      'MO'=>'Missouri',
      'MT'=>'Montana',
      'NE'=>'Nebraska',
      'NV'=>'Nevada',
      'NH'=>'New Hampshire',
      'NJ'=>'New Jersey',
      'NM'=>'New Mexico',
      'NY'=>'New York',
      'NC'=>'North Carolina',
      'ND'=>'North Dakota',
      'OH'=>'Ohio',
      'OK'=>'Oklahoma',
      'OR'=>'Oregon',
      'PA'=>'Pennsylvania',
      'RI'=>'Rhode Island',
      'SC'=>'South Carolina',
      'SD'=>'South Dakota',
      'TN'=>'Tennessee',
      'TX'=>'Texas',
      'UT'=>'Utah',
      'VT'=>'Vermont',
      'VA'=>'Virginia',
      'WA'=>'Washington',
      'WV'=>'West Virginia',
      'WI'=>'Wisconsin',
      'WY'=>'Wyoming',
    );

    $form['state'] = array(
      '#type' => 'select',
      '#options' => $states,
    );

  }
}

```
> 1 votes

# Answer
```
AL|AL
AK|AK
AS|AS
AZ|AZ
AR|AR
CA|CA
CO|CO
CT|CT
DE|DE
DC|DC
FM|FM
FL|FL
GA|GA
GU|GU
HI|HI
ID|ID
IL|IL
IN|IN
IA|IA
KS|KS
KY|KY
LA|LA
ME|ME
MH|MH
MD|MD
MA|MA
MI|MI
MN|MN
MS|MS
MO|MO
MT|MT
NE|NE
NV|NV
NH|NH
NJ|NJ
NM|NM
NY|NY
NC|NC
ND|ND
MP|MP
OH|OH
OK|OK
OR|OR
PW|PW
PA|PA
PR|PR
RI|RI
SC|SC
SD|SD
TN|TN
TX|TX
UT|UT
VT|VT
VI|VI
VA|VA
WA|WA
WV|WV
WI|WI
WY|WY
AE|AE
AA|AA
AP|AP

```
> 0 votes

---
Tags: views
---


title: How to load a large amount of users

text:
# Question
Title: How to load a large amount of users
I have to perform actions on about 15000 users. I'm using a query to retrieve all uids, but the script crashes when using the user\_load\_multiple

```
$uids = db_select('users', 'u')
          ->fields('u', array('uid'))
          ->condition('u.status', '1', '=')
          ->execute()
          ->fetchCol();

$users = user_load_multiple($uids);

```

The script is executed every night, in order to find all users for which the field "Contact again on" (field\_contact\_on) is empty. If it is empty, we put todays date + 1 year.

Does anyone has a suggestion on how to make this more efficient.

Thanks !

# Answer
> 0 votes
I was running into this issue as well. I ended up using EntityFieldQuery to pull my nodes. Then also went into my php.ini file and set my resource limit params to what I have pasted below.

```
max_execution_time = 1024     ; Maximum execution time of each script, in seconds
max_input_time = 2048   ; Maximum amount of time each script may spend parsing request data
memory_limit = 5048M      ; Maximum amount of memory a script may consume (8MB)

```

I've included my php module code below for your reference as well.

```
// go through player names and search
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'content_type_name_to_pull')
  ->propertyOrderBy('title', 'ASC')
  ->propertyCondition('status', 1);

$result = $query->execute();

if (!empty($result['node'])) {
  $nids = array_keys($result['node']);
  $nodes = node_load_multiple($nids);

  foreach ($nodes as $node) {
    // do what you want with the node
  }
}

```

---
Tags: users, database
---


# Question
Title: Drupal automagically changing password hash
This issue happened on my localhost machine while in development but I thought nothing of it since I had multiple drupal projects and was jumping to one another constantly - I figure it was cookies or what not and was constantly resetting my passwords. However I recently went into production and this issue is still occuring.

I have a new drupal site for which I created 2 new users for testing purposes. I realized that after 24 hours or so, the login credentials for these users would not work and I would get :

> Sorry, unrecognized username or password. Have you forgotten your password?

I use these accounts to log in via browsers other than my main one and test the user interface of my production site. After each use I make sure I logout.

I made sure to configure the $cookie\_domain in my settings.php and chmod the file properly but the issue still occurs.

Recently I started tracking the hashes in the user table and low and behold they are magically changing without any human intervention ! What can be causing that ?

Oddly enough, this issue does not happen with the admin account (#1) for which I have yet to logout, and another account which was created but never used. In both cases user\_check\_password() returns true.

Clearing cache does nothing.

I am running the latest core with latest version of all contrib. modules. I use SSL everywhere I have APC and memcache running. I use a mix of MongoDB and MySQL

# Answer
> 0 votes
The issue was with my own code.

I would load the user object every day to perform operations and change some fields value.

Instead of just passing the new fields as the second argument of user\_save(), I would pass the newly changed user object cast as an array, which was causing my password hash to be re-hashed on every call of this function.

---
Tags: 7, users
---


# Question
Title: How Do I change existing theme to a new one without losing content?
Can someone lead me to documentation that explains how I can change an existing Drupal theme to a new one without losing all of my existing content?

The blog I manage is currently set up on the Omega 7.x 3.1 framework, with a semi-custom subtheme. We would like to install a new theme with more out of the box capabilities and a better design but it is important that the two years of published articles are maintained in the current chronological order and with their image content, etc.

Any help finding the instructions on how to accomplish this will be a great help.

Best wishes from Spain!

# Answer
Technically you won't loose any of your content since Drupal's *theme layer* is seperate from the content. Depending on how your previous theme is set up (templates, theme functions, etc) it can however happen, that the **display** of some of your content might not work / work differently in another theme.

A good starting point for learning more about Drupal's *theme layer* is the ***Theming Guide*** which is part of the Community Documentation at drupal.org. A more advanced view on theming can be found in the chapter **'Themes'** of the book *Drupal 7 – the Essentials* which you can actually read online at drupal.org.
> 2 votes

# Answer
However.... If any one involved in building that site cut any corners and placed content directly INTO the theme files, then you might lose content when switching themes.

The more common example of this is having TPL files where the developer hand coded content in there instead of creating nodes or other entities.

If your site was built with Best Practices in mind, then you can switch themes as much as you like and never lose any content.

Curious... What theme are you thinking of going to?
> 0 votes

---
Tags: theming
---


title: View Contextual Filter format for Block

text:
# Question
Title: View Contextual Filter format for Block
I have created a View on my /blog/ page for displaying blog articles. For layout reasons this view is in a block.

This view has a contextual filter for Taxonomy tid on node and, since it is a block, it has a default value of Taxonomy Term ID from URL. When I enter tids in the preview box it works.

However, how do I format this in the url? /blog/1 /blog/term/1 and /blog?tid=1 all return 404 pages. How do I put the tid in the url?

# Answer
Mainly contextual filter works with **/blog/page/\[contextual filter id\]** e.g. **/blog/page/2**

By default its hard to pass the contextual filter id to a block, but you can do it this way

If you have url **blog/page/2** then you can set this as shown in the image(3rd argument is 2 that will be passed to view block ), also add necessary relations accordingly.

Hope it will help you.
> 0 votes

---
Tags: views
---


title: How to export drupal commerce products?

text:
# Question
Title: How to export drupal commerce products?
I need to export products generated by Commerce module. What can I do to accomplish this?

# Answer
> 3 votes
I would use views module with a plugin that fits your export format expectations such as views datasource or views\_data\_export for CSV, XML, etc

# Answer
> 0 votes
I've used the solution suggested by pcambra.

I used the views\_data\_export module and it worked perfectly.

I read the documentation to find out how to use it.

1. Create a new view page and change the selection in the "Show" select box from "Content" to "Commerce Product". A whole set of different options become available.
2. Click "Continue & Edit".
3. Add the fields you want to have exported and a path (since it is a page view after all).
4. Add a display to your view and select "Data Export".
5. Give it a path and attach it to your first page view.

Then go to your page view url and you should see a CSV logo at the bottom of the screen that allows you to download a csv of what is displayed in the view.

---
Tags: 7, commerce
---


# Question
Title: Drush hangs when trying to bootstrap Drupal
Running Ubuntu 12.04 with the 14.04 backports for Drush (meaning we are running Drush 5.10.0)

After importing the database (with drush sqlc \< dump.sql), Drupal is no longer able to be bootstrapped by Drush.

```
drupal-site@uat-previewweb1:/var/www/drupal/uat-preview/current$ drush st -v -d
Bootstrap to phase 0. [0.01 sec, 3.81 MB]                            [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drush() [0.01 sec, 4.04 MB] [bootstrap]
Loading drushrc "/etc/drush/drushrc.php" into "system" scope. [0.01 sec, 4.04 MB]                                                                            [bootstrap]
Cache HIT cid: 5.10.0-commandfiles-0-42f7d1cb79623ad6de6c23932c9a4e2b [0.02 sec, 4.07 MB]                                                                        [debug]
Bootstrap to phase 0. [0.06 sec, 9.04 MB]                                                                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_root() [0.08 sec, 9.04 MB]                                                                                [bootstrap]
Initialized Drupal 7.31 root directory at /var/www/drupal/uat-preview/releases/20140911-4 [0.09 sec, 10.69 MB]                                          [notice]
Drush bootstrap phase : _drush_bootstrap_drupal_site() [0.09 sec, 10.7 MB]                                                                                [bootstrap]
Initialized Drupal site uat-preview at sites/default [0.09 sec, 10.7 MB]                                                                                [notice]
Cache HIT cid: 5.10.0-commandfiles-2-c32acd775c18a90c5b41d0fc9accf5ab [0.09 sec, 10.71 MB]                                                                       [debug]
Drush bootstrap phase : _drush_bootstrap_drupal_configuration() [0.1 sec, 10.75 MB]                                                                          [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_database() [0.1 sec, 10.81 MB]                                                                               [bootstrap]
Successfully connected to the Drupal database. [0.1 sec, 10.81 MB]                                                                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_full() [0.12 sec, 11.92 MB]                                                                                [bootstrap]

```

The command hangs here and does not return.

Does anyone have any ideas on what could be causing this? Is it worth it to stray from debian packages and run Drush 6.4.0 here?

# Answer
> 3 votes
In this particular case, the issue was with an incorrectly configured memcache server settings, the Drupal environment in question was attempting to communicate with a memcache instance that had a firewall dropping all connections.

The fix was to configure memcache servers in the Drupal settings file. Hope this helps someone else.

# Answer
> 2 votes
Drush 5 is no longer supported, so I would recommend installing Drush 6 per the instructions in the README on the project page. My guess is that Drush 6 will behave the same for you here, but it might be worth a try. (If you are running Drupal 8, you **must** run the master branch of Drush, though.)

Regarding your specific problem above, a lot can go wrong if the versions of your modules is no longer in sync with the versions of the table schemas in your database. If the database is OLDER than the code, you could try running `drush updatedb` immediately after you import the database.

If that does not help, it's hard to tell from the information available what could be causing the hang-up. You'll have to dive in deeper and find out where in the code the bootstrap is having trouble, and isolate from there.

---
Tags: 7, drush
---


# Question
Title: Contextual Links add destination=node to URL - can i restrict that from happening? - stopping delete functionality
I have a contextual link on a block that will take the user to an admin screen with a delete button on the admin screen. The delete button works fine when not coming from the contextual link. I noticed the contextual link adds "destination=node" to the end of the URL. The fact that the contextual link adds that to the URL does not allow for my admin screen to redirect to the delete confirm admin screen. If i remove the "destination=node" from the admin screen URL, it goes to the delete confirm admin screen with no issues. Has anyone else had this issue? I noticed this is for absolutely any module or block in drupal. If going to the admin screen from a contextual link and it has a delete button on the admin screen, the delete functionality will not work! Any suggestions?

# Answer
> 2 votes
`hook_menu_contextual_links_alter()` allows you to go in and change anything your heart desires. :)

# Answer
> 4 votes
The accepted answer is not entirely correct. When hook\_menu\_contextual\_links\_alter() gets to act on the array of contextual links, no destinations have been set yet.

Instead, just a few lines after menu\_contextual\_links() (and so its alter hook) is called in contextual\_pre\_render\_links(), there is this line adding the destination to the contextual link:

```
$item['localized_options']['query'] += drupal_get_destination();

```

If you set a query destination in hook\_menu\_contextual\_links\_alter(), the one you set will win. But if you just want to get rid of the destination so for instance a redirect set in the form can do its thing (including, say, adding a fragment)... removing the destination before it is added here doesn't work.

This being Drupal, however, two lines later another alter hook is called:

```
drupal_alter('contextual_links_view', $element, $items);

```

(This is all in contextual module.)

So implement that hook instead. For a module named example removing the destination from all node edit alter hooks on a given array of content type machine names available with the function *example\_selected\_node\_types()*, the implementation would look like this:

```
/**
 * Implements hook_contextual_links_view_alter().
 */
function example_contextual_links_view_alter(&$element, $items) {
  if (isset($element['#element']['#entity_type']) &&
      $element['#element']['#entity_type'] == 'node' &&
      in_array($element['#element']['#bundle'],
               example_selected_node_types()))
  {
    $element['#links']['node-edit']['query'] = array();
  }
}

```

---
Tags: nodes, navigation, views
---


title: About the "read more" link

text:
# Question
Title: About the "read more" link
There are some related questions but they are not very new, and I'm not sure if I get it right. My question seems quite elementary.

Am I wrong in assuming the following basic fact? *In the standard default installation of Drupal 7, all articles show a "read more" link, even if there is actually no more text to show. And there is no simple way of changing that stupid behaviour.*

Please, tell me that I'm wrong.

# Answer
> 2 votes
No, and yes - sort of, in order.

The teaser system assumes that there will always be more to read so if you choose to show the teaser, by default it will always have a 'read more' link.

You can, however turn off the link entirely quite easily. Copy node.tpl.php from your main theme into your custom theme directory and comment out this part:

```
<?php print render($content['links']); ?>

```

If you only want to show a read-more link when there is more to read, you almost certainly need to build a custom module for that. There's lots of good documentation on how to do that, but we can probably help with the specifics here once you have a framework going if that's what you decide to do.

Note that if you only want to change the behaviour for a particular content type, put some logic around the line instead of commenting it out, like this:

```
<?php if ($node->type != 'article'): ?>
  <?php print render($content['links']); ?>
<?php endif; ?>

```

# Answer
> 2 votes
depending on the level of control you need, you could try the Read More Control module:

> A module to control when the teaser Read More link appears in Drupal 7.
>
> There is no mechanism in core to decide if the read more link should appear. This means that this link will always show no matter if there is additional content to display. This module tries to overcome this issue by allowing administrators to determine how to handle this link in relation to both the content type and individual fields.
>
> The module allows you to add Read more links to other supported view modes (RSS feed, Search results, etc) or even other supported entity types. Particularly useful if you use panels or views and either programmatically add additional view modes or use other contrib modules to provide these.

---
Tags: 7, nodes
---


# Question
Title: Which hook is invoked when an order is updated?
Which hook is invoked when an order is updated?

I created a module that must perform some operations when an order is modified, for example when its status is changed or when an item is changed.

# Answer
Commerce doesn't provide an explicit hook for that (these are the hooks it does define for orders).

Since a commerce order is an entity, you're looking for `hook_entity_update()`, which is used to

> Act on entities when inserted.
> 4 votes

# Answer
The documentation for commerce\_order\_status\_update() says:

> While there is no explicit Rules event or hook devoted to an order status being updated...

It is possible to use hook\_commerce\_order\_presave():

```
/**
 * Implements hook_commerce_order_presave().
 */
function my_module_commerce_order_presave($order) {
  if ($order->status != $order->original->status) {
    drupal_set_message("The order status changed from {$order->original->status} to {$order->status}");
  }
}

```

Here's an optional helper function for use elsewhere if you have an `$order` object, and are curious if its status has changed from what is stored in the database:

```
/**
 * Given an order object, this returns FALSE if the order status has not
 * changed. If it has changed, it returns an associative array with the
 * following keys: new_order_status, old_order_status
 */
function my_module_order_status_changed($order) {
  $result['new_order_status'] = $order->status;
  $result['old_order_status'] = db_select('commerce_order', 'co')
    ->fields('co', array('status'))
    ->condition('co.order_id', $order->order_id)
    ->execute()
    ->fetchField();
  if ($result['new_order_status'] == $result['old_order_status']) {
    return FALSE;
  }
  return $result;
}

```
> 7 votes

# Answer
Try: hook\_commerce\_order\_presave($order);

It allows you to prepare order data before it is saved.
> 1 votes

---
Tags: hooks, commerce
---


# Question
Title: How to let a role be able to administer part of permissions?
For example, uid 1 grants role A some permissions as *Article: Create new content, Basic page: Create new content*, then users with role A can grant these 2 permissions to other roles in the same interface as /admin/people/permissions.

# Answer
> 1 votes
I use Permissions Lock to achieve this. You can give your role A the 'administer permissions' ability and then lock off all of the ones that you do not wish them to have access to. It's a bit backwards in that you have to go through and tick *all* of the checkboxes except the ones you want to provide, but it works.

Also you need to check it each time you install new modules or go through an update that provides new permissions as the new permissions default to 'available'.

# Answer
> 0 votes
You know well about the permissions.

1) One step is to give the administrator role, if you have no problem with this.

2) Second option is that you can admin/people/permissions tab and search for "**User**" heading and tick under that **Role** and against the **Administer permissions** and **Administer users** accordingly.

Hope it will help.

# Answer
> 0 votes
take a look at RoleAssign module:

> RoleAssign specifically allows site administrators to further delegate the task of managing user's roles while withholding the Administer permissions permission.
>
> RoleAssign introduces a new permission called Assign roles. Users with this permission are able to assign selected roles to still other users. Only users with the Administer permissions permission may select which roles are available for assignment through this module.

---
Tags: users
---


# Question
Title: How to handle if Drupal site goes down, show a static fallback page instead?
One of my sites went down with the following mysql server down message:

How can I show a basic static page when something fatal like this happens? Are there any modules that do this already? What are some other solutions if a site goes out. I tried cloudflare, but they don't already detect the site going down and still show a fatal message. It would be good if users were shown a static page instead.

# Answer
Because Drupal is completely unresponsive when this happens, it's not something you can fix within Drupal.

Setting a static fail page is possible within your web server - most likely Nginx or Apache. If you are using a CDN, you can also configure it to display only cached versions of your pages if your server is unresponsive.

You'll have to consult your server documentation to get your answer.
> 1 votes

# Answer
In errors.inc line 245 there is this line:

```
print theme('maintenance_page', array('content' => t('The website encountered an unexpected error. Please try again later.')));

```

And in theme.inc I see this:

```
/**
 * Process variables for maintenance-page.tpl.php.
 *
 * The variables array generated here is a mirror of
 * template_preprocess_page(). This preprocessor will run its course when
 * theme_maintenance_page() is invoked. An alternate template file of
 * maintenance-page--offline.tpl.php can be used when the database is offline to
 * hide errors and completely replace the content.
 *
 * The $variables array contains the following arguments:
 * - $content
 *
 * @see maintenance-page.tpl.php
 */

```

So it seems you can use a template file to customize the error.
> 1 votes

# Answer
Drupal's default .htaccess has a section, something like:

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

```

> The DirectoryIndex directive sets the list of resources to look for, when the client requests an index of the directory by specifying a / at the end of the directory name. Local-url is the (%-encoded) URL of a document on the server relative to the requested directory; it is usually the name of a file in the directory. Several URLs may be given, in which case the server will return the first one that it finds. If none of the resources exist and the Indexes option is set, the server will generate its own listing of the directory.

so, by default it looks first for index.php - which it finds, but Drupal has errors and gives you that screen. One option is to change this behaviour like this:

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

```

By switching the first two entries around, you can accomplish a manual override by including an index.html file in the root directory. When the site is up and running, simply remove the index.html (or rename it) and it will move on to index.php (drupal). If there's an error and the entire site is down, add your index.html and it will bypass Drupal entirely. Of course, you will have to actually write an index.html and store it somewhere.
> 0 votes

---
Tags: 7
---


# Question
Title: Is it possible to implement date field as one select list?
Currently when we use default date field with widget select list, it shows like 3 drop-downs with Year, month and date. Is there any way to make it as one drop down. I need to display few dates from today's date( may be 5 or 10 dates).

My date field should look like below section. Format can be different but will display whole date in one select list.

```
September 19 2014
September 20 2014
September 21 2014

```

# Answer
I would recommend replacing the date field with text box and add a date pop to allow certain dates. This could be easily done by `hook_form_alter` in your custom module. See below:

```
    /**
     * Implements hook_form_alter().
     */
    function yourmodule_form_alter(&$form, $form_state, $form_id) {
      switch($form_id) {
        case 'your_form_id':
          $form['yourfield']['#type'] = 'date_popup';
          $form['yourfield']['#date_format'] = 'd/m/Y';
          $form['yourfield']['#datepicker_options'] = array('minDate' => '-15D', 'maxDate' => '-1D');
          $form['yourfield']['#readonly'] = TRUE;
          break;
      }
    }

```

You will need the Date module enabled before you can use this. Let me know how you go..
> 1 votes

---
Tags: datetime
---


# Question
Title: Add placeholder in registration form and removing labels
I wanna customize my registration form on drupal 7. I wanna add placeholders and remove the labels. How can I do that? Thank you

# Answer
This could be easily done my hook\_form\_alter in your custom module. See example below:

Suppose you have a form with id as 'your\_form\_id' and are looking at overwriting title and placeholder text for a field named 'yourfield', you can create a custom module and add this code to your custom module. You will need to replace 'yourmodule' with the name of your module. Same with 'your\_form\_id' and 'yourfield'.

```
     /**
     * Implements hook_form_alter().
     */
     function yourmodule_form_alter(&$form, $form_state, $form_id) {
       switch($form_id) {
         case 'your_form_id':
           $form['yourfield']['#title'] = t(''); // Remove title from yourfield.
           $form['yourfield']['#attributes']['placeholder']= t('Your placeholder text'); // Set placeholder text for yourfield.
           break;
       }
     }

```

The t() method is used for internationalisation.

Let me know how you go...
> 3 votes

# Answer
You can use Form Place Holder module... I have used it earlier and works like a charm..

> Module creates possibility to quickly add (by UI) placeholders to all textfields in any form on site.
> 1 votes

---
Tags: forms, users
---