# Question
Title: How to override node_search_execute() to implement partial matching search?
I would like to override node\_search\_execute, so the search query will find partial match of a word instead of full word match i.e *coffee*, I would like partial match *coff* should return *coffee* result.

How can I override `node_search_execute()` to implement partial matching search?

# Answer
> 0 votes
`hook_search_execute()` is a hook that modules integrating with the Search module implement to execute the search. As such, `hook_search_execute()` is invoked only for those modules that have a tab in the search page, not for every modules implementing it. Since the Search module doesn't use `hook_search_execute_alter()` there isn't a quick method to totally override `node_search_execute()`.

There are some way to make Drupal call another function instead of `node_search_execute()`, but those involve writing code. The quicker is probably altering the *search/node* menu to change the page callback, which normally is `search_view()`.

```
foreach (search_get_info() as $module => $search_info) {
  $path = 'search/' . $search_info['path'];
  $items[$path] = array(
    'title' => $search_info['title'],
    'page callback' => 'search_view',
    'page arguments' => array($module, ''),
    'access callback' => '_search_menu_access',
    'access arguments' => array($module),
    'type' => MENU_LOCAL_TASK,
    'file' => 'search.pages.inc',
    'weight' => $module == $default_info['module'] ? -10 : 0,
  );
  $items["$path/%menu_tail"] = array(
    'title' => $search_info['title'],
    'load arguments' => array('%map', '%index'),
    'page callback' => 'search_view',
    'page arguments' => array($module, 2),
    'access callback' => '_search_menu_access',
    'access arguments' => array($module),
    // The default local task points to its parent, but this item points to
    // where it should so it should not be changed.
    'type' => MENU_LOCAL_TASK,
    'file' => 'search.pages.inc',
    'weight' => 0,
    // These tabs are not subtabs.
    'tab_root' => 'search/' . $default_info['path'] . '/%',
    // These tabs need to display at the same level.
    'tab_parent' => 'search/' . $default_info['path'],
  );
}

```

Since the goal you are trying to achieve is allowing searching by partial matching, you just need to install one of the modules that allows this, such as:

The first module is the lighter one, since it doesn't depend from other modules, while the second one requires the *Search API* module, which in turn requires the *Entity API* module; the third one integrates with Apache Solr, and it is just a possibility for you if you have a server running Apache Solr. The Search API module also integrates with Apache Solr.

### Reference

---
Tags: nodes, search
---


# Question
Title: What is the syntax for the 'Query string value' in a view argument input?
down vote favorite share \[g+\] share \[fb\] share \[tw\]

In Views (3.3) you have the possibility to provide an argument input once you set up a relationship and a contextual filter. One option is to get this argument from the Query string value.

I tried it with visiting a link like this:

```
....url_to_view_page?argument=foo

```

and also

```
....url_to_view_page?foo

```

and even

```
....url_to_view_page?q=foo

```

But it doesn't seem to work. What is the correct syntax for this in the URL?

# Answer
Syntax depends on your view display path, e.g. for *page displays*.

For example, if your page display path is `url_to_view_page/%` then the syntax is:

`url_to_view_page/foo`.

If you do not have a path, then you'll always fall back on the *contextual filter not provided* behavior, this is always the case for blocks.
> 1 votes

# Answer
when `Clean Url` is enable all Urls converted to `foo/bar/...` structure,The views contextual filter address is `pageurl\arg1\arg2\....` So if you view page url is `url_to_view_page\%` then the Url can be like `url_to_view_page\foot`.

( also you can use `?q=url_to_view_page/foo`)
> 1 votes

---
Tags: views
---


# Question
Title: Drush 8.0-dev sql-sync does not report the path to the dump file produced
When syncing a remote db into my local db, drush 8 fails at `The Drush sql-dump command did not report the path to the dump file produced. Try upgrading the version of Drush you are using on the source machine.`

This is normally caused when the 2 servers are running different versions of Drush, however both are running 8.0-dev. The remote server does have an older version of Drush installed system wide, but I also have Drush 8.0-dev installed via composer for my specific user and I'm assuming drush uses the updated composer version since it logs in with my credentials. Could it be possible that the old system wide version of Drush is running on the remote server?

The remote server successfully dumps the database into `/drush-backups/` but it seems the dump location does not get passed on.

This is a postgres database using the `.pgpass` option for Drush.

Here's a --verbose --debug of the command starting after the alias checking:

```
You will destroy data in .... and replace with data from ......
Do you really want to continue? (y/n): y
Returned from hook drush_sqlsync_sql_sync_validate [10.62 sec, 6.8 MB]                                                                                [debug]
Calling hook drush_sqlsync_sql_sync [10.62 sec, 6.82 MB]                                                                                [debug]
preg_match() expects parameter 2 to be string, array given environment.inc:627 [10.62 sec, 6.82 MB]                                                                                [warning]
Starting to dump database on Source. [10.62 sec, 6.83 MB]                                                                                [ok]
Backend invoke: ssh -o PasswordAuthentication=no ...@.... 'env COLUMNS=231 drush  --backend=2 --verbose --debug --strict=0 --root=/.....com --uri=.....com  sql-dump   --gzip     [command]
--result-file 2>&1' 2>&1 [10.62 sec, 6.84 MB]
ssh -o PasswordAuthentication=no ...@.... 'env COLUMNS=231 drush  --backend=2 --verbose --debug --strict=0 --root=/.....com --uri=....com  sql-dump   --gzip --result-file        [notice]
2>&1' 2>&1 [10.62 sec, 6.84 MB]
Bootstrap to phase 0. [0.01 sec, 1.71 MB]                            [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drush() [0.01 sec, 1.82 MB] [bootstrap]
Cache HIT cid: 5.10.0-commandfiles-0-e83b78d19750fe135e1b944620e04d58 [0.02 sec, 1.84 MB]                                                                                [debug]
Bootstrap to phase 0. [-0.26 sec, 4.3 MB]                                                                                [bootstrap]
Bootstrap to phase 0. [-0.26 sec, 4.31 MB]                                                                                [bootstrap]
Found command: sql-dump (commandfile=sql) [-0.26 sec, 4.31 MB]                                                                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_root() [-0.25 sec, 4.36 MB]                                                                                [bootstrap]
Initialized Drupal 7.39 root directory at /.....com [-0.24 sec, 5.2 MB]                                                                                [notice]
Drush bootstrap phase : _drush_bootstrap_drupal_site() [-0.24 sec, 5.21 MB]                                                                                [bootstrap]
Initialized Drupal site .....com at sites/.....com [-0.24 sec, 5.21 MB]                                                                                [notice]
Cache HIT cid: 5.10.0-commandfiles-2-33c9dd42c31668865dc2b7d939fada15 [-0.23 sec, 5.21 MB]                                                                                [debug]
Drush bootstrap phase : _drush_bootstrap_drupal_configuration() [-0.23 sec, 5.21 MB]                                                                                [bootstrap]
Cache HIT cid: 5.10.0-commandfiles-3-d970728376beb137057865c63baa822f [-0.23 sec, 5.23 MB]                                                                                [debug]
Calling system(pg_dump  --file /....../drush-backups/....../20151013010137/......_20151013_010137.sql  ...... --host=localhost --port=5432 --username=www-data --clean  && gzip -f /....../drush-backups/....../20151013010137/......_20151013_010137.sql);
Database dump saved to /....../drush-backups/..../20151013010137/....._20151013_010137.sql.gz [0.59 sec, 6.42 MB]                                                                                [success]
Command dispatch complete [0.59 sec, 6.39 MB]                                                                                [notice]
 Timer  Cum (sec)  Count  Avg (msec)
 page   0.818      1      817.66

Peak memory usage was 6.68 MB [0.59 sec, 6.39 MB]                                                                                [memory]
The Drush sql-dump command did not report the path to the dump file produced.  Try upgrading the version of Drush you are using on the source machine. [13.11 sec, 6.87 MB]                                                 [error]
Returned from hook drush_sqlsync_sql_sync [13.11 sec, 6.84 MB]                                                                                [debug]

```

**Update**: I've tried downgrading both servers to Drush 7.\* and am receiving the same results.

# Answer
If Drush is not selecting the correct executable on the remote system, you can specify the full path to Drush via the `%drush-script` element in the site alias on your local machine.

```
$aliases['remote'] = array(
    'uri' => 'http://example.com',
    'root' => '/path/to/remote/drupal/root',
    'remote-host' => 'myisp.com',
    'remote-user' => 'www-admin',
    'path-aliases' => array(
      '%drush-script' => '/path/to/drush/drush',
    ),
);

```
> 4 votes

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


# Question
Title: Page title unable to overwrite default title
`admin/config/search/page-title` \- Global default title is *abc*

`admin/config/search/page-title` \- Content type *BOOK* -\> title is *def*

meta tag -\> Content -\> page title is *ghi*

meta tag -\> Content -\> BOOK -\> page title is *jkl*

content type *BOOK* -\> create new node -\> page title -\> *mno*

In the website(Content type Book), the title always shows *abc*.

I want to edit title, may I know how?

Many Thanks.

# Answer
> 1 votes
```
function mytheme_preprocess_page(&$variables) {

  if (!empty($variables['page']['content']['system_main']['#form_id']) && $variables['page']['content']['system_main']['#form_id'] == 'form_id') {
    if (arg(0) == 'node' && arg(2) == 'node-type') {
    drupal_set_title(t('Your title'));
    }
   }
 }

```

you can use dpm($variables) to find form id. This for changing page title.

For changing header title i.e the title displaying in tab, below code can be used

```
function mytheme_preprocess_html(&$vars) {
  if (!empty($vars['page']['content']['system_main']['#form_id']) && $vars['page']['content']['system_main']['#form_id'] == 'your_form_id') {
    $vars['head_title'] = t('title');
  }
}

```

# Answer
> 0 votes
Edit

Using this module you can edit your title field.

OR

you can do it by custom

```
*
 * @form
 * the node form at node/add/[node-type]
 */
function node_entry_form_after_build($form, &$form_state) {

  //set a drupal title here
  drupal_set_title('my title');

  return $form;
}

```

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


title: Drupal multilingual menu

text:
# Question
Title: Drupal multilingual menu
I have created one menu for all languages and set the items as neutral and added the language translations. But when I add translations, only the *title field* is working and it's not working with others field.

# Answer
Install Internationalization module and enable *Menu translation* sub module. Now it allows users to select a translation mode for each menu.
> 1 votes

---
Tags: i18n-l10n
---


# Question
Title: Change timezone display format in user edit page
In drupal 7 timezone field in user edit will be like `Asia/Kolkata: Friday, October 9, 2015 - 17:24 +0530`. I want to display it like `Asia/Kolkata`. I have tried the method specifed in https://drupal.stackexchange.com/a/177073/50991 but not working. How to change the display format

# Answer
> 0 votes
I think `$form['#after_build']` should work for you

```
function module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id ==  'user_profile_form') {
    $form['#after_build'][] = 'module_user_profile_form_after_build';
  }
}

function module_user_profile_form_after_build($element, &$form_state) {
  $options = array();
  foreach(timezone_identifiers_list() as $timezone => $value) {
    //$options[$timezone] sets the value for date_default_timezone select
    //$timezone set the display for select
    $options[$timezone] = $value;
   }
   $element['account']['timezone']['timezone']['#options'] = $options;
   return $element;
 }

```

# Answer
> 0 votes
You can do it with below code

```
    function yourcustomodulename_form_alter(&$form, &$form_state, $form_id) {
    if($form_id=='user_profile_form'){
 $form['#after_build'][] = 'yourmodulename_after_build';

    }
    }
function yourmodulename_after_build($form, &$form_state) {
      $options = array();
      foreach(timezone_identifiers_list() as $timezone) {
        //$options[$timezone] sets the value for date_default_timezone select
        //$timezone set the display for select
        $options[$timezone] = $timezone;
      }
      $form['account']['timezone']['timezone']['#options'] = $options;
return $form;
}

```

---
Tags: 7, forms, datetime
---


# Question
Title: Replacing the updated module in drupal 7 without effecting the database from previous module?
I have seen that whenever we apply patch to a module, without reinstalling the module, new updates of the module won't be reflected. The problem is reinstalling the module will truncate the module related tables in the database. Is there any other way, so that we can replace the updated module without effecting the data from previous module?

Thank you in advance.

# Answer
> 2 votes
That's what `hook_update_N` is used for:

> For each change that requires one or more actions to be performed when updating a site, add a new hook\_update\_N(), which will be called by update.php. The documentation block preceding this function is stripped of newlines and used as the description for the update on the pending updates task list. Schema updates should adhere to the Schema API.

e.g. Adding a new column to a table:

```
function MYMODULE_update_7100() {
    db_add_field('foo_table', 'bar_col', array(
      'type' => 'varchar',
      'length' => 255,
      'not null' => TRUE,
      'description' => 'My new integer column.'
    ));
}

```

---
Tags: version-control, installation
---


# Question
Title: Sensible way to rewrite a field for all views in Drupal 8?
In Drupal 8 seems one has to create 2 or 3 files plus folder structures to do even the simplest of tasks. So I am trying to figure out how to do a simple hack without all the overhead.

I have a node type for which I attached images. There is a parent node for which I want to display one of the images from the children. I created an Image field for the parent.

So literally, all I need to do is query the database, grab a child's image at random (in every view, each time the parent is viewed, I want the image re-assigned randomly), and rewrite the parent's image field accordingly. This was so easy in Drupal 7...

Does anyone have an idea of how to do this in Drupal 8 in the simplest possible manner, ideally editing just one file?

Thanks!

# Answer
You can use hooks the same way as in Drupal 7, if you want to change the content of the node before rendering, you can put a hook in your module or theme:

```
module/theme_preprocess(&$variables, $hook) {
   if ($hook == 'node') {
      ...

```

check if you are in the right node and change it.

The simplest solution for your problem would be to put all children images in the node display and then hide the images you don't want:

```
hide($variables['content']['field_image_?']);

```

So you don't need to lookup the children image yourself.
> 2 votes

---
Tags: entities, 8
---


# Question
Title: How to update table taxonomy_index when adding a node referencing a term?
I have two node types: `Lesson` and `Exercise`. A lesson contains several exercises, which are children. Lessons have a category field which is a reference field of type taxonomy term. Exercises point to lessons through a Lesson reference field, which I suppose indirectly maps exercises to terms.

When I create a lesson, I use the following code:

```
    $node = Node::create([
      // The node entity bundle.
      'type' => 'lesson',
      'langcode' => 'en',
      'created' => $lesson->created,
      'changed' => $lesson->changed,
      'uid' => $lesson->uid,
      'title' => $lesson->title,
      'field_category' => $tid,
      'body' => [
        'summary' => $lesson->summary,
        'value' => $lesson->body,
        'format' => 'full_html',
      ],
    ]);
    $node->save();

```

Note the `field_category` field.

The above does not result in the `taxonomy_index` table being updated. I could update it with an sql query, but I would like to know how to do it via the above core approach.

And for the `Exercise` node type, I suppose I need to do likewise, unless my linking of an `Exercise` to a Lesson already accomplishes the hierarchy.

How do I alter the above to result in the `taxonomy_index` table being updated?

# Answer
I ended up figuring this out. here is what I did:

```
$result=db_query("SELECT nid FROM node WHERE type = 'lesson'");
foreach($result as $row){
    $node=entity_load('node', $row->nid);
    $result =  taxonomy_build_node_index($node);
}

```

This ensures that my lesson node is tracked in the taxonomy\_index table. I should probably start learning the class-based approach, but for now this works.
> 1 votes

---
Tags: nodes, entities, taxonomy-terms, 8
---


title: multifield and reference to other nodes

text:
# Question
Title: multifield and reference to other nodes
I would like to ask about my logic problem with site. I want to make a searchlist of distributors. Client selects manufacturer, and all distributors who are providing goods from certain manufacturer will be displayed. I have two content types: 1. Distributor, 2. Manufacturer. Im assigning x manufacturers to one distributor (multiple entity references). And the problem is here. I want to have for every distributor link to their shop where they offer the goods from selected manufacturer. How it can be done if one distributor can have x manufacters? I tried to search some module which dynamically adds text field for every nodereference which is set to multiple values, but didnt find anything. If I use multifield I cannot acces is aterwards with entity reference filter.

Just to be clear this is how it should look like.

* Distributor1
    + Manufacturer-1
    + Manufacturer-x
    + Manufacturer-y
* Distributor2
    + Manufacturer-1
    + Manufacturer-x
    + Manufacturer-y
* Distributor3
    + Manufacturer-x
    + Manufacturer-y
    + Manufacturer-z
* Distributor4
    + Manufacturer-1
    + Manufacturer-x
    + Manufacturer-y
* Distributor5
    + Manufacturer-x
    + Manufacturer-y
    + Manufacturer-z
* Distributor6
    + Manufacturer-1
    + Manufacturer-x
    + Manufacturer-y

# Answer
If I understand you corretly, you need to store other field(s) together with the reference of Manufacturers, right? I think the best way is to add the (a single-value) reference field to Distributor in the Manufacturer content type along with other necessary fields. After that you can create your list with a View.
> 0 votes

---
Tags: views, entities
---


title: Filtered HTML does not work in field

text:
# Question
Title: Filtered HTML does not work in field
I have a field and set its input format to *Filtered HTML*. Its content some text within the `<strong>` and `</strong>`, which are allowed by the input format I chose.

However, when displaying the a node of that content type, the text is still displayed as plain text and the `<strong>` tag seems to be ignored.

What can be the reason for that?

# Answer
> 0 votes
Go to **config \>\> content \>\> formats \>\> filtered\_html**

In bottom have **Filter setting** choose **Limit allowed HTML tags** add in it allowed HTML tags

# Answer
> 0 votes
I tried adding a field as you did, and it worked perfectly, for me.

>

The only way I could make the field not displayed with the allowed tags I used for its content was to set the format of that field to *Plain text* (on admin/structure/types/manage/page/display, where page is the content type to which I added the field).

>

Drupal should use the default format, as it happened with me. I cannot tell you why it used the *Plain text* format in your case, since I cannot reproduce this for a field I create ex-novo.

---
Tags: entities
---


# Question
Title: How to get the drupal version using phpMyAdmin query?
How to get the drupal version using query ? Or how do we detect using query the drupal version is 7,6,5 or 4?

# Answer
This will work with Drupal 7 - I don't have other version to test it on but think it should work...

Because the version is stored in the text file CHANGELOG.txt we can write that to a table in the DB, read from the table, and then delete it again afterwards:

First run this: (make sure to change the path to your changelog file)

```
CREATE TABLE `drupal_version` (`data`  varchar(255) NULL);
LOAD DATA INFILE '/var/www/your_site/htdocs/CHANGELOG.txt' INTO TABLE drupal_version;
SELECT * FROM drupal_version WHERE data LIKE "%Drupal%" LIMIT 1;

```

This will return something like:

```
Drupal 7.26, 2014-01-15

```

And run this to delete the table we just made:

```
DROP TABLE drupal_version;

```

Whilst this is a long winded way of reading text from a text file it is strictly speaking getting the version using MySQL...

## Second Option

As Topsitemakers suggested looking in the system table I had a look and found the version was hidden in there, but only against specific modules. I figured the field module would be in all version of drupal, however I very highly doubt that this query will actually work on any version other that 7 as it's so specific and a bit of a beast:

```
SELECT MID(info, LOCATE(':"', info, LOCATE('"version";', info)) + 2, MID(info, LOCATE('"version";', info) + 12, LOCATE(':"', info, LOCATE('"version";', info)) - LOCATE('"version";', info) - 12))
FROM system WHERE filename LIKE "%/field.module"

```

For me this query returns:

```
7.26

```
> 3 votes

# Answer
Open `modules/system/system.info` file and check out the value of `core` item.
The value will tell you the version, e.g. 6.x/7.x/8.x.
> 2 votes

# Answer
This should work for D7 and D6, i don't have other versions to test but if system table is similar, it should work as well.

```
SELECT MAX(schema_version) FROM system;

```

This will get something like "7002" or some number starting with a 7 for Drupal 7 and "6005" or something starting with 6 for Drupal 6. It's not the exact running version but if you just have a database dump you can figure out from where it comes from.
> 1 votes

---
Tags: 7, database
---


title: Custom migration from external DB

text:
# Question
Title: Custom migration from external DB
I'm trying to migrate content from an Expression Engine database to Drupal 8.

I set up a `$databases['migrate']['default']` in settings.php and copied and modified *BeerNode.php* from *migrate\_plus migrate\_example* module in a custom module. This is my query code in BlogNode.php.

```
  public function query() {
    // $this->configuration['ignore_map'] = true;
    $query = $this->select('exp_weblog_titles', 'tab1');
    $query->addField('tab1', 'entry_id', 'bid');
    $query->addField('tab1', 'title', 'name');
    $query->addField('tab2', 'field_id_10', 'body');
    $query->innerJoin('exp_weblog_data', 'tab2', 'tab1.entry_id = tab2.entry_id');
    $query->condition('tab1.weblog_id', 10, '=');
    return $query;
  }

```

Now Drush complains about a missing column:

> Migration failed with source plugin exception: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'b.bid' in 'on clause':
>
> ```
> SELECT tab1.entry_id AS bid, tab1.title AS name, tab2.field_id_196 AS body, map.sourceid1 AS migrate_map_sourceid1, map.source_row_status AS
> migrate_map_source_row_status
> FROM
> {exp_weblog_titles} tab1
> INNER JOIN {exp_weblog_data} tab2 ON tab1.entry_id = tab2.entry_id
> LEFT OUTER JOIN destinationdatabase.migrate_map_blog_node map ON b.bid = map.sourceid1
> WHERE  (tab1.weblog_id = :db_condition_placeholder_0) AND( (map.sourceid1 IS NULL ) OR (map.source_row_status = :db_condition_placeholder_1) );
>
> ```

This is the implementation of getIds():

```
  public function getIds() {
    return array(
      'bid' => array(
        'type' => 'integer',
        'alias' => 'b',
      ),
    );
  }

```

I assume that the second part of the query should be `ON tab1.entry_id = map.sourceid1` but I can't set anything other than `bid`.

I kind of resolved by temporarily setting `$this->configuration['ignore_map'] = true;` before the query losing some traking functionality though.

# Answer
Remove 'alias' =\> 'b', from your getIds() call, that parameter is only needed if you need to remove any ambiguity from the source query.
> 0 votes

---
Tags: drush, 8, migrations
---


# Question
Title: Taxonomy Term Reference Tree Widget with Other field
I am using Drupal 7 Taxonomy Term Reference Tree Widget my requirement is, user should be able to create new term while adding the content. Is it possible in this module? Any patch available?

Please help me.

Thanks,

# Answer
> 1 votes
You might do this with the alternative module Hierarchical select.

**Hierarchical select:**

> Hierarchical Select has the ability to save the entire lineage of a selection or only the "deepest" selection. You can configure it to force the user to make a selection as deep as possible in the tree, or allow the user to select an item anywhere in the tree. Levels can be labeled, you can configure limit the number of items that can be selected, configure a title for the dropbox, choose a site-wide animation delay, and so on. You can even create new items and levels through Hierarchical Select!

---
Tags: taxonomy-terms
---


# Question
Title: Update webform without losing existing webforms
I'm using webform 7.x-3.20 version and I want to to upgrade it to 7.x-4.x, but I've 7 to 8 existing webforms whenever I update this I'm losing my previous webforms cause of changed table structure. If is there any easiest way to update then please let me know. It'll be appreciated.

# Answer
> 0 votes
In the comment section of the documentation there is written: `Note that you must be running the latest 3.x version of Webform (for either Drupal 6 or Drupal 7) before upgrading to Webform 4.x.`

---
Tags: views, webforms, updating, chaos-tool-suite
---


# Question
Title: how to use panel to display content types but using condition?
I have two content types.

Liquor product which have fields \[Title, origin, effects, side effects, price, how to drink, etc.. \] Liquor store fields are \[store name, address, contact no.\] I am used panel to display Liquor content.I want to display all content of liqour if they have in store. For e.g If I am click on absolute vodka then panel display absolute vodka info comes(i.e Title, origin, effects, side effects...) but now i want add condition show all stores which have absolute vodka

How to do this?

# Answer
> 1 votes
Create two blocks in Views, one that shows the Liquor info with a contextual filter of the nid, then a second block that lists stores again with contextual filter and a relationship to the nid of the liquor (with whatever field you are using to relate the store to the liquor).

Once your Views blocks are in place, you can then add them into your panel using the Content tab, then selecting the Content cogwheel on left top corner, then select Add Content, then in the dialog box look under Miscellaneous, you will see your Views blocks listed, add them and you're done!

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


# Question
Title: Can the Autocomplete delay be lowered in forms?
I have seen that the autocomplete widget in Forms API is started when I finish typing, or when there is a delay between one key hitting and the next one. Could it be configured so it is launched as soon as I press a key, like in Google Autosuggest or other search boxes?

# Answer
As Clive suggested in a comment major part of the delay is because of the time taken by your server to populate the dropdown list. This generally happens because Drupal has to load all the enabled modules and do a complete Drupal bootstrapping.

In special cases like Autocomplete responses that may not be necessary. Hence you can load only what is required and do a minimal Bootstrapping.

You can check out the details of how this is done on this page.

`Note :` This involves custom coding and will not to perform any access checks unless you manually do it.
> 3 votes

# Answer
As others have suggested, there is a delay with AJAX autocomplete due to the server round trip. However, there is a delay baked into Drupal itself.

In misc/autocomplete.js, there is this section of code

```
Drupal.ACDB = function (uri) {
  this.uri = uri;
  this.delay = 300;
  this.cache = {};
};

```

The delay property is used in `Drupal.ACDB.prototype.search` to debounce the search requests when a user is typing, so that the input has to be stable for 300ms before triggering the autocomplete callback.

You can get around this by monkey patching, and providing your own version of `Drupal.ACDB` that uses a different delay.
> 2 votes

# Answer
Try with Autocomplete Deluxe Module.

Refer How to use autocomplete deluxe programatically

May be this will help you.
> 1 votes

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


# Question
Title: How to translate variable containing html with the i18n_variable module?
I am trying to translate a variable with i18n\_variable module. I am using the following code:

```
/**
 * Implements hook_variable_info().
 */
function MY_MODULE_variable_info($options) {
  $variables['pm_email_notify_subject'] = array(
    'title' => t('My variable title'),
    'description' => t('The description', array(), $options),
    'default' => t('A good default value', array(), $options),
    'type' => 'string',
    'localize' => TRUE,
    'access' => 'administer checkout',
    'group' => 'my_variable_group',
  );
  return $variables;
}

```

This works as expected: I can choose the variable to be translated at `/admin/config/regional/i18n/variable` and when I do so, I can find its value via `/admin/config/regional/translate`.

But the problem is, that the variable contains HTML markup and although this works with the original content, the markup in the translated string gets converted to HTML entities. what am I missing?

# Answer
> 0 votes
The simple answer is, not to use the interface for string translation of the i18n module under `admin/config/regional/translate/translate`, but instead go to the admin path, where the original (not translated) variable is set. In my use case this was `/admin/config/messaging/privatemsg`. As I patched the privatemsg module, to make it's variables translatable, on the module's admin form appeared a language selection option:

If you put in the translation there, all HTML is preserved. I guess this would be the general approach to translate variables, which are set via the admin interface. If you have to translate a variable, which is not set via the admin interface, I guess you have to provide the translation in code.

# Answer
> 0 votes
A solution I used when I faced a similar problem in a different context is to preventively replace tag-markers by the corresponding entity in the content before it is processed.

Adapated to your case, it might look like this:

```
/**
 * Implements hook_variable_info().
 */
function MY_MODULE_variable_info($options) {
  $my_variable_content = preg_replace_all(
    '/<([^>]*)>/', '<$1>',
    'A good default value with some <tags> inside'
  );
  $variables['pm_email_notify_subject'] = array(
    'title' => t('My variable title'),
    'description' => t('The description', array(), $options),
    'default' => t($my_variable_content, array(), $options),
    'type' => 'string',
    'localize' => TRUE,
    'access' => 'administer checkout',
    'group' => 'my_variable_group',
  );
  return $variables;
}

```

This way, the finally rendered text keeps its "\<" and "\>" intacts.

But caution: it might be not appropriate to your case, so try it carefully.

---
Tags: i18n-l10n
---


# Question
Title: Taxonomy widget - select maximum level depth
I want to make a taxonomy field widget that allows me to select the maximum level depth of the taxonomy vocabulary. This widget should be used in node forms and the value (selected term) should be saved in the node object.

What is the best (Drupal) way to approach this?

I don't want to use hierarchal select.

# Answer
> 1 votes
Content Taxonomy is what you're looking for. It extends the default select list widget and adds a maximum level depth.

# Answer
> 1 votes
For me not works any module to remove unnecesary taxonomy depths, but I can fix it with my own code like this:

function \_remove\_sub\_services(&$form, &$form\_state) {

```
foreach ($form['profile_fields']['field_select_the_service'][LANGUAGE_NONE]['#options'] as $index => $value){

    if(strstr($value, '--')){
        unset($form['profile_fields']['field_select_the_services'][LANGUAGE_NONE]['#options'][$index]);
    }
}

return $form;

```

}

// I call this code inside a hook\_form\_alter

# Answer
> 0 votes
There is a new module called Client-side hierarchical (https://www.drupal.org/project/cshs) that does a good UI and solves it.

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


# Question
Title: How to use form API to edit sub form that is added to user_register_form
I need to alter a Redhen Contact form when it is attached to the user registration form. More generically, I need to alter a sub form. The form is added to `user_register_form()` via `hook_form_FORM_ID_alter()` in rendhen\_contact.module:1029. (I don't think this is specific to Redhen's implementation; I'm just providing this as a reference point.)

The first issue I encountered was that the hook implementation in redhen\_contact.module hadn't occurred when my hook was called. In a custom module, I used `hook_module_implements_alter()` to resolve that (see screenshot at bottom for `kpr()`). With that I'm still unable to alter, for example, the `#title` attribute of `field_agency_interest`. Even if I do `$form['redhen_contact]['form']['field_agency_interest']['und']['#title']` or `...['und'][0]['title']` it doesn't change.

I tried using `$form['#after_build'][] = 'module_callback_name'` but I can't edit the sub form elements.

How can I alter a sub form added to a form?

# Answer
I came across this: https://drupal.stackexchange.com/a/129617/7595, which identifies that you have to dig a bit deeper into the element; specifically the `['value']` element.

So, for editing a subform this will work:

```
function hook_form_alter(&$form, &$form_state, $form_id) {
  $form['redhen_contact']['form']['field_agency_interest']['#pre_render'][] = '_field_agency_interest_pre_render';
}
function _field_agency_interest_pre_render($element) {
  $element[$element['#language']][0]['value']['#description'] = '<a href="test">Test</a>';

  return $element;
}

```

I'll note again that I'm using `#pre_render` because the RedHen module hook was being called after this one and this ensures everything has been added to the form prior to making changes.
> 0 votes

# Answer
You probably forgot to reference the `$form` variable ("`&$form`").
The alternative to `#after_build` would be `#pre_render`, which misses `$form_state` but should generally be preferred for changes that only affect the rendering of a form.
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Drupal Search API Placeholder && Front Page?
I'm trying to get some placeholder text working for the Search API form, but have a different placeholder on the front page. Here's what I have so far which does work everywhere...

```
function THEME_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form['search_api_views_fulltext'])) {
    $form['search_api_views_fulltext']['#attributes']['placeholder'] = t('Search Text here...');
  }
}

```

How can I get this working on only the front page, with a different placeholder text on all other pages? I've tried many things and totally stumped at the moment. Any help would be appreciated.

# Answer
> 0 votes
Check for `drupal_is_front_page()`

> **Return value**
>
> Boolean value: TRUE if the current page is the front page; FALSE if otherwise.

```
function THEME_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form['search_api_views_fulltext']) && drupal_is_front_page()) {
    $form['search_api_views_fulltext']['#attributes']['placeholder'] = t('Search Text here...');
  }
}

```

---
Tags: theming, search
---


# Question
Title: How can I pass more resource IDs with a single request?
I've been using the Services module with the REST module from quite some time now.

I want to make a single *PUT application/json* request with an appropriate JSON raw body for it, passing more than a resource ID, instead of making different requests. So far as I read, I found I can use `PUT request: http://.../resource_endpoint/resouce_name/resource_id`.

# Answer
> 0 votes
Implement `hook_services_resources()`.

```
function example_services_resources() {
  $resources = array();
  $resources['einvoice'] = array(
    'actions' => array(
      'search' => array(
        'access callback' => '_example_resource_access',
        'callback'        => '_example_resource_search',
        'help'            => 'E-invoice online checker.',
        'file'            => array(
          'type'   => 'inc',
          'module' => 'exmaple',
          'name'   => 'resources/exmaple.resource',
        ),
        'args'            => array(
          array(
            'name'        => 'input',
            'optional'    => FALSE,
            'source'      => array('data' => 'input'),
            'type'        => 'string',
            'description' => 'Put the query string to get some data.',
          ),
        ),
      ),
    ),
  );
  return $resources;
}

```

In the *example.resource.inc* file, you put the functions declared in that hook.

```
function _example_resource_access() {
  return TRUE;
}

function _example_resource_search($input) {
  // To do something you want.
}

```

---
Tags: services, 8
---


title: How to display field revisions?

text:
# Question
Title: How to display field revisions?
I want to keep field revisions: I want to see who changed a field to which value and when. Currently I can keep node revisions, but in the revisions tab, it only shows title and body changes.

1. How can I also keep field revisions?
2. How can I display revisions preferably like this:

* User 1 changed Color: red to Color: green
    * User 2 changed Color: green to Color: white

Is the second one achievable by Views?

# Answer
I came across a similar issue and found your post last week. After a bit of searching around I found this module:

https://drupal.org/project/track\_field\_changes

It appears to cover what you were looking for in terms of functionality as well as what I was trying to cover. I've since installed the module and set it up, but unfortunately whilst some of it is working for me I can't get a view to display the 'value after' or 'value before' fields (See https://drupal.stackexchange.com/questions/81507/how-to-display-values-in-the-value-after-value-before-fields-track-field).

If you still need this functionality perhaps try out the module - if you have success with it let me know as it's still not quite working fully for me, but that could be down to user-errors perhaps.

All the best

Tom
> 3 votes

# Answer
1. Field revisions, at least in Drupal 6, exist alongside node revisions.
2. At least some of that functionality exists in the Diff module.
> 2 votes

# Answer
Using the track\_field\_changes module, I was able to get the side by side values in a view. Note , I also have revisions turned on for this node type.
> 1 votes

---
Tags: entities, nodes
---


# Question
Title: How to close (ctools) modal node/add form after submit?
I wrote this module that print the node/add form for a content type (article) in a ctools modal window. It works and the new node is saved, but the modal window remains opened after submitting the form.

I would like to automatically close the modal window after saving the node, end and optionally redirect drupal to the new node. Any hint?

```
      <?php

    function modaltest_menu()
    {
    $items['modaltest']            = array(
        'title' => 'Modaltest Page',
        'page callback' => 'modaltest_page',
        'access arguments' => TRUE
    );
    $items['modaltest/%ctools_js'] = array(
        'title' => 'Modaltest page 2',
        'page callback' => 'modaltest_page_modal',
        'page arguments' => array(
            1
        ),
        'access arguments' => TRUE
    );
    return $items;
}

      function modaltest_page_modal($js = NULL)
    {
      $nojs_message = t('Hello World');
    if (!$js) {
        return $nojs_message;
    }
    module_load_include('inc', 'node', 'node.pages');
    $form = node_add('article');
    ctools_include('modal');
    ctools_include('ajax');
    $output   = array();
    $output[] = ctools_modal_command_display(t('My modal test'), $form);
    print ajax_render($output);
    exit();
}

    function modaltest_page()
    {
    ctools_include('modal');
    ctools_include('ajax');
    ctools_modal_add_js();
    return ctools_modal_text_button(t('Popup link'), 'modaltest/nojs',      t('test popup'), 'ctools-modal-test-style');
    }

```

# Answer
ctools\_modal\_command\_dismiss() will close the modal.

You can find more information on that command and ctools modals in general by installing the Advanced Help module and visiting `/help/ctools/modal`.
> 1 votes

---
Tags: ajax, chaos-tool-suite, javascript
---


title: Programmatically add node translation

text:
# Question
Title: Programmatically add node translation
I am using i18n module. How can I programmatically create node translation?

# Answer
> 9 votes
```
// Define which node is the source, this node has his own id as translation nid (tnid)
$source_node = node_load($source_nid);
$source_node->tnid = $source_nid;
node_save($source_node);

$new_node_in_a_other_language = new stdClass();
$new_node_in_a_other_language->type = 'your_type';
node_object_prepare($new_node_in_a_other_language);
$new_node_in_a_other_language->title    = 'title fr';
$new_node_in_a_other_language->language = 'fr';
// define source tnid
$new_node_in_a_other_language->tnid = $source_nid;
node_save($new_node_in_a_other_language);

```

# Answer
> 0 votes
here is a code that will work a bit better in terms of cloning such features like panelizer and node configurations.

```
$node_id = 42611;
$source_node = node_load($node_id );
$es_node_404 = clone $source_node;
$source_node->tnid = $node_id ;
node_save($source_node);

// Making cloned node unique.
unset($es_node_404->nid);
unset($es_node_404->vid);

node_object_prepare($es_node_404);
$es_node_404->title = '[ES] ' . $source_node->title;
$es_node_404->language = 'es';
$es_node_404->status = 1;
// Define source tnid.
$es_node_404->tnid = $node_id;
node_save($es_node_404);

```

---
Tags: 6, i18n-l10n
---


# Question
Title: Attach the module "Insert" to ALL "Body" fields?
I've just installed the Insert module. I have many many content types in my site and all of them contains the same "Body" field. It would take me much time to attach an Insert image-field to each one of them manually and I need a way to do that *at once*.

How will you achieve this goal? If you drop a module's name please also detail in steps where and what will you do to achieve it.

# Answer
> 4 votes
You may add this code snippet in the `install` file in your custom module and run `update.php`. It works fine, I've tested this code on my local site

```
<?php
/**
 * Add an image field to a node.
 */
function my_module_update_7001() {
  $field_name = 'field_insert_image';

  // Make sure the field doesn't already exist.
  if (!field_info_field($field_name)) {
    // Create the field.
    $field = array(
      'field_name' => $field_name,
      'type' => 'image',
    );
    field_create_field($field);
  }

  $content_types = node_type_get_types();
  $exclude = array('example');
  foreach ($content_types as $content_type) {
  if (!in_array($content_type->type, $exclude)) {
    $instance = field_info_instance('node', $field_name, $content_type->type);
    if (!$instance) {
      // Create the instance.
      $instance = array(
        'field_name' => $field_name,
        'entity_type' => 'node',
        'bundle' => $content_type->type,
        'label' => 'Image Insert',
        'description' => 'An image for the article.',
        'required' => TRUE,
        'settings' => array(
          'file_extensions' => 'png jpg jpeg',
          'file_directory' => '',
          'max_filesize' => '20 MB',
          'alt_field' => 1,
          'title_field' => 1,
          'max_resolution' => '300x200',
          'min_resolution' => '200x125',
          'default_image' => 0,
         ),
         'widget' => array(
          'type' => 'image_image',
          'module' => 'image',
          'active' => 1,
          'settings' => array(
            'insert' => 1,
            'insert_absolute' => 1,
            'insert_styles' => array_keys(insert_styles_list()),
          ),
         ),
         'display' => array(
          'default' => array(
           'label' => 'hidden',
           'type' => 'image',
           'weight' => 0,
           'settings' => array(),
           'module' => 'image',
         ),
         'full' => array(
           'label' => 'hidden',
           'type' => 'image',
           'weight' => 0,
           'settings' => array(),
           'module' => 'image',
         ),
         'teaser' => array(
           'label' => 'hidden',
           'type' => 'image',
           'weight' => 0,
           'settings' => array(),
           'module' => 'image',
         ),
       )
      );

      field_create_instance($instance);
    }
  }
 }
}

```

# Answer
> 0 votes
Your requirements is not very clear. Insert module allows user to insert the image in the body field in a single click using the insert button.

The short answer to your question is `NO` short method. Even if you're using a shared field and the original field has been configured to use Insert button you still have to configure each field to enable the `Insert` button. It is possible to do this via Drupal API but you have to be familiar on `field apis` at least or via `hook_update_N`. As of my understanding of your requirements is you are looking for a fastest method to enable Insert for each content type. So yeah your only option is to enable it manually.

# Answer
> 0 votes
My suggestion for you is to get all content type (also you can exclude some of them that you don't want to add) then in one `foreach` with field\_create\_instance add your desire field to content type.

I provide some help code (I don't test it right now and just typing them) you can achieve what you with some think like below code.
(you can also get your field info with field\_info\_instances)
First register a menu, in callback of menu call a function, in function in `foreach` of your content types you want add field with `field_create_instance`.

```
  <?php

  function  autoaddinsert_menu(){
    $items =array();

    $items['admin/addautoinsert'] =array(
      'title' => 'Add isert field',
      'description' => 'add insert  field automatically to all content type',
      'page callback' => 'autoinsert_addfield',
      'access callback' > true,
    );
    return $items;
  }

  function autoinsert_addfield(){

    $ctypes=node_type_get_types(); //
    foreach($ctypes as $content_type){

    // Check if our field is not already created.
      $yourfieldname='field_yourinsert';// @todo put your  machine name of insert field here
      if (!field_info_field($yourfieldname)) {

      // Create the field base.
        $field = array(
          'field_name' => $yourfieldname,
          'type' => 'image',  //@todo put your field type here
        );
        field_create_field($field);

        // Create the field instance on the bundle.
        $instance = array(
          'field_name' => $yourfieldname,
          'entity_type' => $content_type->type,
          'label' => 'My Field Name', //@todo put your label here
          'bundle' => $content_type->type,
          // If you don't set the "required" property then the field wont be required by default.
          'required' => TRUE,

          'widget' => array(
            'type' => 'textfield',
          ),
        );
        field_create_instance($instance);
      }
    }
  }

```

---
Tags: entities
---


# Question
Title: How can I programatically log another user out in D7?
On our site we have client accounts, each with a super administrator and sub users belonging to that account.

We want the super admin to be able to force sub users to log out. What's the best way to destroy a user's session in Drupal that works regardless of whether the session information is stored in Redis, Memcache or the database?

Before someone feels tempted to suggest user\_logout(), that destroys the *current* user's session. I want the current user to be able to destroy a *different* user's session!

# Answer
> 6 votes
`drupal_session_destroy_uid()` sounds like a safe bet:

> Ends a specific user's session(s).

The core implementation clears the database, as you'd expect, but any module that overrides session.inc, and doesn't provide a working implementation of that function, would surely be considered broken (as `user_delete_multiple()` and other functions need it).

So in theory you should be able to use that function regardless of the storage.

# Answer
> 1 votes
Session Proxy provides a generic replacement for Drupal's session handling that is supposed to work with various backends.
As such it also implements `drupal_session_destroy_uid()`.

Note that the session implementation of Memcache API and Integration is considered unstable, and that the maintainer of Redis recommends the use of *Session Proxy*.

The problems of handling sessions consistently across various backends are outlined in issue 1260634.

# Answer
> 0 votes
In Drupal 7, We can log out a user if we have his User\_ID using db\_delete():

```
db_delete('sessions')->condition('uid', $User_ID)->execute();

```

---
Tags: sessions, users
---


# Question
Title: How to validate node title field Drupal 7
I want to add validation to the node title field. When the user enters the character X and submits the form they should get a message saying "you are not allowed to enter special character X".

# Answer
> 1 votes
You can setup field/property validations with the module Field validation.

Here's the documentation on how to add validation to properties (with the Field validation module), as the title isn't a field in Drupal 7.

# Answer
> 1 votes
Check these module Node Title Validation

> These is very light weight module, and helps to validate node titles with min/max characters, Blacklist characters/words and unique node titles.

# Answer
> 0 votes
You can implement hook\_node\_validate() and check the special character in node title.

```
function MYMODULE_node_validate($node, $form, $form_state){
 // special character list, Add more special character if you want.
 $special_character_list = '[\'^£$%&*()}{@#~?><>,|=_+¬-]';
 if(preg_match('/' . $special_character_list . '/', $node->title) !== 0){
   form_set_error('title', 'Special character are not allowed in form title.')
 }
}

```

**UPDATE :**

```
function MYMODULE_node_validate($node, $form, $form_state){
  // special character list, Add more special character if you want, escape the character if required.
  $special_character_list = '\'^£$%&*()}{@#~?><>,|=_+¬\-\[\]';
  if(preg_match('/[' . $special_character_list . ']/', $node->title) !== 0){
    form_set_error('title', t("Special characters !special_character_list are not allowed in title.", array('!special_character_list' => $special_character_list)));
  }
 }

```

# Answer
> 0 votes
I had the same problem, field validation module work correctly for another field but when I want to validate title I can't validate it and finally find the Title module ,
**Usage**

> After enabling the module as usual, visit the Manage fields page of the content type, taxonomy vocabulary or "comment type" which you wish to replace fields of and click the replace link. That's all.

after installing this module go to your field management and see "Replace" beside title , with this feature, it convert drupal default title and after converting you can work with field title like another fields. I hope this help you and future guys that have the same problem.

---
Tags: forms, nodes
---


# Question
Title: Searching on Taxonomy terms with the Search API module?
I've been playing around with the Search API module for a little bit now, and it seems to be working fairly well, but I can't figure out how or why I am not able to search on terms even though they are selected among the search fields.

Does anyone have any hints or pointers on what I could be doing wrong?

# Answer
You can only search on full text fields, so you need to not only add the term but also fx make the term name searchable, another option is to use terms as facets, but then you can't search on them using full text.
> 1 votes

# Answer
On the field index page, at the bottom see **Add related fields** select the term field you want to search. When you save, this adds a number of items associated with the term fields. Then select **Taxonomy \>\> Name** to index as Fulltext. Now it is searchable.
> 5 votes

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


# Question
Title: Title encoding to display correctly foreign characters
In my `html.tpl.php` file in the `<head>` tag I display the page title as follows:

`<title><?php print $head_title; ?></title>`

This displays the foreign characters not correctly when watching the pages in the browser.

I tried to add the `<meta charset="utf-8" />` but it didn't help.

Caches were cleared.

What else could you change so that the foreign characters are encoded correctly?

# Answer
> 0 votes
Instead of trying this.

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

```

try this and check.

```
<?php print html_entity_decode($head_title); ?>

```

# Answer
> 0 votes
The form of the meta tag should be, `<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />`

But if what the HTTP-response header says contradicts (check as @bgm suggested), then what is displayed is up to your browser (and sometimes it may depend on the language environment of your OS, for the TITLE tag, though modern OSs are generally good at it). Trying with different browsers may help in some cases.

If you display the same string in a normal content, that may help to confirm it can be displayed correctly in those cases. If not, chances are the chracter-code of the string may be different from what you intended (UTF-8?).

# Answer
> 0 votes
I found the only way was to change the codepage to western Europe

```
<meta http-equiv="Content-Type" content="text/html; charset="ISO-5591-1" />

```

this worked for me

---
Tags: 7
---


title: Parameters in the HTTP request

text:
# Question
Title: Parameters in the HTTP request
I am trying to render a block depending on the parameter(entity) present in the requested page. Suppose if I am on a url like this: `http://localhost/drupal8/user/1` then a block with label user is created. Same thing I am trying to achieve for other urls like `http://localhost/drupal8/node/1`, `http://localhost/drupal8/comment/1`. I am using this piece of code:

`if ($this->request->attributes->has($entity_type)) {
 return code for rendering block
 }`

(here $entity\_type will be replaced by user,comment,node) to check whether requested page has a particular key. This piece of code works for checking keys like node and user when I am on page `http://localhost/drupal8/node/1` and `http://localhost/drupal8/user/1` respectively but when I am on page like `http://localhost/drupal8/comment/1` and check for key: 'comment' then it returns `FALSE` because it is not defined. Is this an expected behaviour, if yes then what should I do to solve my problem. Thanks.

# Answer
> 1 votes
Instead of inspecting the request object directly, the `current_route_match` service is the preferred object to consult for request parameters. It provides both the raw and upcast values of parameters. Additionally, using `\Drupal\Core\Routing\StackedRouteMatchInterface` you can retrieve values from the master request.

The reason you are having trouble with `/comment/{comment}` is because that route is special: it performs a subrequest to view the entity the comment belongs to. This explains why you only have the node entity available when viewing a comment on a node.

To work around this, consult the master request:

```
$comment = \Drupal::routeMatch()->getMasterRouteMatch()->getParameter('comment');

```

---
Tags: 8, entities
---


# Question
Title: A deleted image filename is printed to the top of SOME of my nodes
## Background:

I once had an image file in the site (I think the image was added via an image-field I already deleted).

## The problem:

This image filename I described is printed to the top of **SOME** of my nodes (I should note that these are nodes from different content-types). In some nodes it doesn't appear but in some others it does... Any idea why would this strange beahvior happen?

* I already tried to flush all caches - didn't help.

## Live examples (Images):

---

---

---

# Answer
While I don't know the mechanism of the behavior, deleting the SQL file-data from the relevant SQL tables via PHPmyAdmin **and then** flushing all caches, solved the problem.

Note: There where references to the file in 2 tables (One table deals with files and one deals with the Watchdog).
> 0 votes

---
Tags: files
---


title: Date display field drupal

text:
# Question
Title: Date display field drupal
I have created two content types **A and B**. I have a **Date** field in A which is referred in B. But in B I want to display the **Date** field separately i.e 3 different select list for month, year and day.

# Answer
Using the Date API module (part of the Date module), you can do something like this...

```
<?php
$form['payment_expirationDate'] = array(
    '#type' => 'date_select',
    '#title' => t('Expiration Date:'),
    '#date_format' => 'm', OR  '#date_format' => 'y',
    '#default_value' => $expirationDate,
    '#date_year_range' => '-1:+10',
    '#required' => TRUE,
    '#date_label_position' => 'within'
 );
?>

```

The date\_select type will give you select box form elements for your field. And the #date\_format array key allows you to use a PHP date format string to control what select boxes appear and what goes inside them.

Reference
> 0 votes

---
Tags: datetime
---


# Question
Title: Should I use underscore or hyphenated tokens?
When displaying tokens that can be used I often see this type of thing:

I have seen that there are a number of d.o issues on this; one in particular is extensive and detailed. But is there a reason to use the dashed one or the hyphened one? There may be a D8 migration reason for all I know?

# Answer
> 3 votes
Tokens are just arbitrary strings, Drupal doesn't mind which characters are used to indicate separation of words (some characters are blacklisted, like `]`, but for the most part that's true). All that matters is the module that provides them, e.g. Entity in this case, knows how to interpret them when it needs to.

The issue you referenced has two key core contributors debating it, without a resolution, so there simply isn't a standard to apply to this.

Both sets of token provide the same data, so it's a matter of personal preference which one you use.

Since the Entity module provides more field tokens than core modules do, you might end up standardising your site better over time if you choose the ones provided by Entity. But YMMV, in real terms it doesn't matter.

---
Tags: 7, tokens
---


# Question
Title: Views: upcoming events list with first upcoming event at the top
I have content type which have date field(multiple). It also collect the end date.

Now I am creating a view which will list the nodes of that content type.

It will sort the nodes with the start date in ascending order. And only those nodes will display whose start date is greater than the current date.

I have added the filter of start date. If start date is greater than the current date. The option `Add multiple value identifier` is set to `Yes` in the filter settings.

In the query settings I Distinct and pure distinct is checked. I have also tried the aggregation but still the view returns duplicate results.

Any Idea how will remove the dupliation?

**EDIT**

This is the sql query that view generates

```
SELECT DISTINCT node.title AS node_title, node.nid AS nid, field_data_field_event_date_time.field_event_date_time_value AS field_data_field_event_date_time_field_event_date_time_value, node.created AS node_created, 'node' AS field_data_field_event_date_time_node_entity_type
FROM
{node} node
LEFT JOIN {field_data_field_event_date_time} field_data_field_event_date_time ON node.nid = field_data_field_event_date_time.entity_id AND (field_data_field_event_date_time.entity_type = 'node' AND field_data_field_event_date_time.deleted = '0')
WHERE (( (node.status = '1') AND (node.type IN  ('event')) AND (DATE_FORMAT(ADDTIME(field_data_field_event_date_time.field_event_date_time_value, SEC_TO_TIME(-25200)), '%Y-%m-%d\T%H:%i') >= '2014-05-15T22:19') ))
ORDER BY field_data_field_event_date_time_field_event_date_time_value ASC, node_created DESC
LIMIT 10 OFFSET 0

```

The problem is if an event has 2 dates then it is displaying two times and if it has 3 dates then it is displaying 3 times in the results.

# Answer
> 0 votes
I have managed to do this by creating a module (easier than you might think) and adding a post execute function like this (text in caps has to be replaced by your module and view names):

```
function MODULENAME_views_post_execute(&$view) {
  if($view->name == "MYVIEWNAME") {
    $view->result = array_reverse($view->result);
  }
}

```

---
Tags: 7, views, datetime
---


# Question
Title: Image field: Force at least/exactly two images per field
I can easily set the maximum number of elements per field, but is there an easy way to specify the *minimum* value?
For now, I have an Image field, and I want at least two images.

# Answer
> 1 votes
This question has already answer here

You can do it by using **Field validation** Module.

The following validators are listed:

> * Regular expression
> * Numeric values (optionally specify min and / or max value)
> * length (optionally specify min and / or max length)
> * number of words (optionally specify min and / or max words )
> * Plain text (disallow tags)
> * Must be empty (Anti-Spam: Hide with CSS)
> * Words blacklist
> * number of selections (optionally specify min and / or max selections )
> * Unique
> * Match against a field
> * Match against a property
> * Specific value(s)
> * Require at least one of several fields
> * Equal values on multiple fields
> * Unique values on multiple fields
> * PHP Code (powerfull but dangerous)
> * URL (support internal path and external url validation)
> * Email
> * Pattern (Regular expression lite)
> * Date range2

Hope this will help you

---
Tags: entities, media
---


# Question
Title: How to display a date without hour, minutes, and seconds?
I have created content type and installed Automatic Entity Label and generated the auto label using field tokens of:

1. field\_id
2. field\_DOB
3. field\_Gender

After saving the content *DOB format* is displaying with time stamp *56u **2015-10-13 00:00:00** Male* but here I want to show only something like this *56u **2015-10-13** Male*.

I want to remove this `00:00:00`.

While creating the field DOB I have chosen the following settings but still getting the hour, minutes, and seconds. How to remove this? Any suggestion?

# Answer
> 6 votes
Steps to achieve your requirement:

1. Goto **/admin/config/regional/date-time/formats/add** link, and add Format string as explained in the PHP manual.
2. Now add **Date type** and select the format you created.
3. Finally, go to content type **Manage Display** settings and add your newly created date format.
4. At URL **/admin/structure/types/manage/page/auto\_label**, add token of the DOB field with the format you created by **Browsing Available Tokens**.

---
Tags: datetime
---


# Question
Title: Views with contextual filter ignores sort order and number of nodes per page
On my site I want to define tutorials. One tutorial consists of several nodes of the same **Tutorial content type**. The content type has a field **taxonomy term reference** and a weight, to determine the sort order.

My idea was to have a single view, selecting on **Tutorial content type**, ordering by weight, one node per page. So far this works. But to only show nodes for one specific **tutorial** I defined a contextual filter, on the tutorial field. Now only nodes for that specific tutorial are shown, as expected, but this also has the effect that:

* The nodes are no longer sorted by weight.
* I no longer have one node per page

I've been looking for workarounds, different settings, etc., so far to no available , so help would be greatly appreciated.

If this is a behavior of views that can't be helped, any other approaches to my use case would also be met with immediate gratitude.

Using: Drupal 7.39, Views 7.x-3.11

# Answer
I tried your example (with Drupal 7.39 and Views 7.x.3.11) and was not able to reproduce the issue. In short, I followed the following steps:

* Created a taxonomy vocabulary, called "**Tutorial Vocabulary**"
* Created a content type, called "**Tutorial Type**" containing two additional fields:

1. "**Tutorial term**" (Entity Reference to Taxonomy Terms of type "Tutorial Vocabulary") and
    2. "**Weight**" (Integer).
* Created some content.
* Created a **View** for "Content" type "**Tutorial type**", added the "sorted by Weight" criterium, removed the default "**sorted by creation date**" criterium, and configured the default pager to display only "1 item"
* Created a **contextual filter** for the "**Tutorial term**" field, specifying "Show page not found" when the filter value is not in the URL, and leaving everything by default.

The **contextual filter** seems to work as expected when I pass the **tid** of the taxonomy terms: Only the nodes associated to a term are displayed, they are sorted by weight, and only one node per page.

Maybe you are following different steps from the ones I am listing above. If so, please edit your post to specify them, it might be useful in order to find a solution to your question.
> 1 votes

---
Tags: views
---


# Question
Title: What could be causing drupal to want to reinstall itself after I clear cache?
I am trying to update Drupal from 7.17 to 7.18. I uploaded a copy of my site from a test server to my production server. Everything installs fine, I actually see the site working, and I can navigate it. Then, as soon as I perform updates on modules and core, I run database updates, and then the site automatically navigates me back to install.php to reinstall the site from scratch. I have tried to reinstall the site several times from scratch, manually and using Drush.

What is the mechanism that determines to redirect to install.php? How can I determine how and why this is happening?

Even though the install.php page is showing up in the browser, `drush status` shows that the site is up, running, successfully connected to the database with correct theme. According to Drush, everything is working properly.

# Answer
That occurs because Drupal can't connect to its database. Ensure you have the *settings.php* file in the *sites/default* folder. The *settings.php* file must be readable by the account used to run the web server; it must contain valid database connection string credentials for that server. Make sure that `$base_url` in that file is either commented out (as it is by default), or it's a valid URL for that domain.

See `_drupal_bootstrap_database()` for the place where the install.php redirect occurs.

Also, make sure you run update.php and clear all the caches, whenever possible.
> 7 votes

# Answer
Just to add, after my site (D7.23 on Ubuntu 12.04.3) randomly decided it needed to be installed again, I found out that an archive process had changed the permissions on the `sites/default` directory to `755`.

At first I didn't think it was this because the change in permissions was less restrictive i.e. giving user and group more permissions; but I guess there is a security check somewhere in Drupal that will only accept the `sites/default` if it has the permissions `555` — the thinking being that the folder may have been tampered with. The same also seems to be true for `settings.php` in that my install requires it to be `444`, if not, I get the install UI.
> 2 votes

# Answer
I found the solution to this issue. See the solution given by bryancasler on the page https://www.drupal.org/node/984112

How to fix this problem

* Go to **xampp\mysql\bin**
* Open **my.ini**
* Change "`max_allowed_packet` from `1m` to `16m`
* Save **my.ini**

Now restart MySql through the XAMPP control panel.

Thanks.
> 1 votes

---
Tags: 7, installation
---


# Question
Title: Saving custom fields for nodes and users
I'm trying add a new user to drupal 7, here is my code:

```
$values = array('name' => $name, 'pass' => $password,  'mail' => $email, 'status'=>1);
$newUser = user_save('', $values);

```

But i also have the new field field\_foobar, if i add it to the values array drupal does nothing with it. What is the correct drupal way of adding these values to my user object so that drupal saves them when i call the user\_save function?

I also saw that the fields are stored in the same type of table that stores custom fields of nodes. Also can't get this done, but i guess these 2 problems can have the same solution.

Thanks!

# Answer
> 8 votes
I haven't done this with `user_save()` before but if it follows convention from the rest of the system (which is likely) it'll be like this:

```
$values = array(
  'name' => $name,
  'pass' => $password,
  'mail' => $email,
  'status'=>1,
  'field_foobar' => array(
    LANGUAGE_NONE => array(
      0 => array(
        'value' => $field_value
      )
    )
  )
);

$newUser = user_save('', $values);

```

In fact there are a few examples further down the page in the `user_save()` docs confirming this method is the right one.

# Answer
> 0 votes
Take a look at an existing user that has all the fields filled in.

For example. Add the following to your code somewhere:

```
global $user;
dpm($user);

```

When you know what the user object looks like, it's easy to duplicate the fields in it.

Also take a look at this page, describing how to add users programatically.

# Answer
> 0 votes
In my case, I had to UPDATE the user account. So, I read Clive's answer which is specifically for ADDing a user account. Later, I started to review the user\_save function sourcecode, and an online discussion on this topic, and found the following lines of code working:

```
$loaded_user = user_load($uid); //$uid is a variable with the user id numeric value
$updated_values = array(
  'field_first_name' => array(
    LANGUAGE_NONE => array(
      0 => array(
        'value' => "ehsan"
      )
    )
  )
);
$loaded_user->is_new = 0;
$loaded_user->original = entity_load_unchanged('user', $uid);
$newUser = user_save($loaded_user, $updated_values);

```

So the $updated\_values are the updated fields which if your are really like to address them with the correct structure, use the following lines before writing the above lines of code:

```
$test_user = user_load($uid);
dpm($test_user);

```

---
Tags: entities, users
---


# Question
Title: Allow file access to specific users in Drupal (not roles)
I have historical data recorded in pdf files for our clients. Now I am developing a website (in Drupal) from where clients should be able to access this data. The problem is that i don't want this files to be available to anyone else than the user to whom the information belongs.

Since this data is periodically recorded I could store it in a specific folder for each user. My question is that if it's possible to give access to this folders or its content to specific users in Drupal. Because the alternative would be to create a Role for every user which is not good.

# Answer
At the end I found a solution that covers all my needs. I created a custom page template for the page from where i want to access the files (ex. node--4.tpl.php) that catches the username and generates a cookie with it:

```
global $user;
$username = $user->name;
$cookie_name = 'cookie_name';//
$cookie_value = $username;//
setcookie($cookie_name, $cookie_value, time() + (3600), "/");

```

Then I create a .htaccess file in each user's folder that contains this code:

```
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_COOKIE} !cookiename=username [NC]
RewriteRule .* http://alternativepath/ [L]

```

So only the user who's username is like the username i ask for in the htaccess can access the folder. In my case I ask for another field, not the username, but this should be enough as a simple example.
> 0 votes

# Answer
1. Create a new **content type** and add fields according to your requirement or user reference field
2. Disable its Front page publish option.
3. Create new user **Role** like "client".
4. Create view of files and add **relationship or contentuxal filter** against user loggin id.
5. Create **block view** assign this block into specific region.
> 0 votes

---
Tags: users, files
---


# Question
Title: Will I loose this content or the content will be saved?
I'm new in drupal. I have one site that is running on drupal version 7 and now needs to be upgraded. My question is: I have big content in this site, after the upgrade will I loose this content or the content will be saved?

# Answer
No, you will not loose any content after upgrading the site. But before upgrading the site please take care of the following things.

1. **Back up your database.**
2. **Back up your code.**
> 1 votes

# Answer
Your content will be saved, but you should back up your database and all the code inside of your `sites` folder.

I used to do manual upgrades, but I found that upgrading via Drush is much easier.

`drush up` updates Drupal core and contrib projects and apply any pending database updates. `drush up --security-only` will only install security updates, which I find most useful when maintaining older sites.
> 0 votes

---
Tags: 7, upgrading
---


# Question
Title: Why does updating newly added field collection on hook_field_collection_item_insert fail?
The main goal is to create product & product display using drupal 7 & drupal commerce when a user with a certain role add a new field collection.

What I'm trying to do is when a new field collection is added :

* access host entity fields and retrieve some datas
* do some custom stuff
* update 1 value of a field collection which is a field reference to product

Steps followed :

* I'm using **hook\_field\_collection\_item\_insert** to access newly created field collection.
* I call a function which create a product (using commerce modules suites). Above steps works just fine.
* Then I call a function that update the current field collection field by adding a value which is a reference of product created in **function my-module-create\_product().**

`$fc_wrapper->save(TRUE);` is failling to save with the following error :

`Exception: Unable to save a field collection item without a valid reference to a host entity in FieldCollectionItemEntity->save() (line 520 of ../mysite.local/docroot/sites/all/modules/contrib/field_collection/field_collection.module)`

I've done some search so far without any success.

I can't figure out the fix for this, some direction or any information that will help to solve this issue will be much appreciated.

Below a simplified code that I'm using :

```
function my_module_field_collection_item_insert($field_collection_item) {

    $item_id = $field_collection_item->item_id;
    //dpm($item_id);

    //Check the field collection bundle & if it's just have been created
    if ($field_collection_item->field_name == 'field_my_field_collection' && $field_collection_item->is_new == TRUE) {

        //Access host entity
        $node_wrapper = field_collection_item_get_host_entity($field_collection_item);

        //Do custom stuff with host entity fields
        //...
        //set $product_type, $price, $extras values

        //Call a function that create product
        $product = my_module_create_product($product_type, $price, $extras);

        //Product creadted
        if ($product) {

            $product_display = my_module_create_product_display($product, $item_id);

        } else {
            throw new Exception('Product creation as failed...');
        }
    }
}

```

---

```
//Function that create product
function my_module_create_product($product_type, $price, $extras) {
    //create product
    return $created_product;
}

```

---

```
//Function that create product display
function my_module_create_product_display($product, $item_id) {

    //Note that loading existing field collection here works but it not what I need
    //Loading created field collection
    $fc_wrapper = entity_metadata_wrapper('field_collection_item', $item_id);

    if ($fc_wrapper) {

        if ($fc_wrapper->field_product_ref->value() == NULL) {

            //Setting product reference
            $fc_wrapper->field_coaching_product_ref->set($product->product_id);

            //Only need to save the current field collection
            $fc_wrapper->save(TRUE);

            //I've tried bellow still don't work either
            //$fc_wrapper->save();
            return $fc_wrapper->getIdentifier();

        } else {
            //Product display already exist
            return FALSE;
        }
    } else {
        throw new Exception('Exception... ');
    }
}

```

# Answer
> 4 votes
You can only set the host entity while creating the field collection item (as your exception also states).

What you can do however is use `$fc_wrapper->value()->updateHostEntity('node', $node);` before you save the $fc\_wrapper. For that to work you will first have to load your host entity node of course (`node_load()` will suffice).

Hopefully this gets you on your way.

---
Tags: 7, commerce, entities
---


# Question
Title: How to add extra classes in body tag so that i will come only for the anonymous user?
I want to add a extra unique class in body tag so that it will come only for the anonymous user.

How to add it?

# Answer
> 3 votes
The proper way to do this is in a preprocess hook:

```
function MYTHEME_preprocess_html(&$vars) {
  if (user_is_anonymous()) {
    $vars['classes_array'][] = 'foo-class';
  }
}

```

Don't try to make this decision in a template file, you'll find it doesn't work properly when you have caching enabled. Or it'll break your caching entirely for the page.

# Answer
> 2 votes
Core already does this for you. If you examine includes/theme.inc, you will find the implementation for `template_preprocess_html()` which is run by default before module and theme specific versions. In it is this code blip

```
function template_preprocess_html(&$variables) {
  // ...
  $variables['classes_array'][] = $variables['logged_in'] ? 'logged-in' : 'not-logged-in';
  // ...
}

```

So, there are already body classes, `logged-in` and `not-logged-in`, added for you. If those classes is not there, something is altering the `$variables['classes_array']` in a naughty way.

---
Tags: theming
---


# Question
Title: Search engine for Drupal site, Apache Solr or ElasticSearch?
Hello Drupal community,

I'm facing a issue for a new site that i'm developping. I need to implement a search engine and don't know which search engine to use between Apache Solr and ElasticSearch. It's the first time I do such work and I am desperatly in need of feedbacks from people who used it in there website and who can tell me the difference it makes in a Drupal site.

Edit : I want a new one to display a search bar in the front office to index all the content of the site in a special way. I also want the results to be displayed right away.

Thanks in advance.

# Answer
> 1 votes
Use Apache Solr.It has every feature you dream and the searching is super fast.It can search through pdf as well. As per your requirements I suggest to use Apache Solr. It can be easily done with it.

---
Tags: 7
---


# Question
Title: How to render a view as a entity field on form edit?
I'm looking for a module (or alternative solution) to render view in the field.

Similar to Viewfield, but it should be rendered when filling the form (Entityform or node edit).

The purpose for that is to include Commerce views in the entity form (such as commerce\_cart\_form, commerce\_cart\_summary, commerce\_payment\_order) which are actually views.

# Answer
> 2 votes
Use EVA module. It will provide the view as field. So in display settings you can assign views the region you would like. Quite simple and useful module

---
Tags: views, entities, commerce
---


# Question
Title: Unlimited value field in custom form, with remove button
I'm working on creating an unlimited value field in a custom form, and getting hung up on the remove button. I've been able to create a form that will pull the saved values for the fieldset, then allow the user to click an "Add" button to get more date field values in the fieldset. The problem is the individual remove button paired with each date. BTW, the context for the form is that a user needs to be able to add an indeterminate number of dates, then remove or update dates as needed.

I've tried adding the remove buttons with name values that correspond to the date's index in the `$form` and `$form_state` array values, then accessing that value through `$form_state['clicked_button']`, removing the date, then re-rendering the fieldset. I've also tried simply returning nothing from the ajax call in order to just remove that date from the form. I run into different issues with each approach.

If I try to re-render the entire fieldset in the callback, the remove button only removes the last date in the fieldset. I've `dpm`-ed all the values that I'm looking at, and I can't figure out where that data is being rendered from.

If I try to return an empty string from the callback and only update the single removed date field, it seems to work initially. After I hit save and the page refreshes though, I'm left with what seems to be a weird re-indexing of my values. For example, if I have consecutive days 1-4 in October and try to remove the 1st, after hitting save, I'm left with 2, 2, 3.

The code I'm working with (including some comments and troubleshooting) is below:

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

  // Fieldset container where we can add unlimited values
  $form['closed_mon_exceptions'] = array(
    '#type' => 'fieldset',
    '#tree' => TRUE,
    '#prefix' => '<div id="closed_mon">',
    '#suffix' => '</div>',
    '#description' => t('Exceptions to our typical closed Mondays.'),
  );
  // Add a flag to add on additional Mondays if the user clicks "Add Open Monday"
  $form_state['storage']['add_monday'] = isset($form_state['storage']['add_monday']) ? $form_state['storage']['add_monday'] : 0;
  if (isset($form_state['clicked_button']) && $form_state['clicked_button']['#value'] == 'Add Open Monday') {
    $form_state['storage']['add_monday']++;
  }

  // If the user clicked to remove a day, need to regenerate the dates with that value removed
  if (isset($form_state['clicked_button']) && $form_state['clicked_button']['#value'] == 'Remove Monday') {
    // get current values from form_state
    $closed_mon_dates_array = $form_state['values']['closed_mon_exceptions'];
    // remove the Add Open Monday button from this array
    array_pop($closed_mon_dates_array);
    // retrieve the index of the one we need to remove
    $remove_mon = $form_state['clicked_button']['#name'];
    // Try to remove that value from any array it's being used in
    //unset($form['closed_mon_exceptions'][$remove_mon]);
    unset($form_state['values']['closed_mon_exceptions'][$remove_mon]);
    unset($form_state['complete form']['closed_mon_exceptions'][$remove_mon]);
    unset($closed_mon_dates_array[$remove_mon]);
    // reorder the array, so we have expected 0 through (count-1) indices
    $closed_mon_dates_array = array_values($closed_mon_dates_array);
  } else {
    // if we're not trying to remove a monday, just get the saved values
    $closed_mon_dates_array = variable_get('closed_mon_exceptions');
  }
  dpm($closed_mon_dates_array);
  dpm($form_state);
  $num_closed_mondays = count($closed_mon_dates_array);

  // Add all the current closed Monday exceptions
  for ($i = 0; $i < $num_closed_mondays; $i++) {
    if (isset($closed_mon_dates_array[$i])) {
      $current_date_val = $closed_mon_dates_array[$i];
      // Remove the value for the button, if this data was pulled from
      // $form_state above
      if (count($current_date_val) == 4) {
        array_pop($current_date_val);
      }
    }
    dpm($current_date_val); // Just making sure it's formatted as expected...
    $form['closed_mon_exceptions'][$i] = array(
      '#type' => 'date',
      '#default_value' => $current_date_val,
      '#title' => t('Closed Monday Exception'),
      '#prefix' => '<div id="monday-' . $i . '">',
      '#suffix' => '</div>',
    );
    // Add a remove button for each one
    $form['closed_mon_exceptions'][$i]['remove_day'] = array(
      '#type' => 'button',
      '#value' => t('Remove Monday'),
      '#name' => "$i",
      '#ajax' => array(
        'callback' => 'monday_remove',
        'wrapper' => 'closed_mon' // Update the whole fieldset
        //'wrapper' => 'monday-' . $i, // Alternately, try to update just this value
      ),
    );
  }

  // Check if user clicked "Add Open Monday"
  if ($form_state['storage']['add_monday'] > 0) {
    // Starting index for adding open Mondays
    $i = count($closed_mon_dates_array);
    $number_to_add = $form_state['storage']['add_monday'];
    $end_index = $i + $number_to_add;
    for ($index = $i; $index < $end_index; $index++) {
      $form['closed_mon_exceptions'][$index] = array(
        '#type' => 'date',
        '#default_value' => array(),
        '#title' => t('Closed Monday Exception'),
        '#tree' => TRUE,
        '#prefix' => '<div id="monday-' . $index . '">',
        '#suffix' => '</div>',
      );
      $form['closed_mon_exceptions'][$index]['remove_day'] = array(
        '#type' => 'button',
        '#value' => t('Remove Monday'),
        '#name' => "$index",
        '#ajax' => array(
          'callback' => 'monday_remove',
          'wrapper' => 'closed_mon',
          //'wrapper' => 'monday-' . $index,
        ),
      );
    }
  }
  $form['closed_mon_exceptions']['add_open_monday'] = array(
    '#type' => 'button',
    '#value' => t('Add Open Monday'),
    '#ajax' => array(
      'callback' => 'multi_date_ajax_callback',
      'wrapper' => 'closed_mon'
    ),
  );

  return system_settings_form($form);
}

function monday_remove($form, &$form_state) {
  //return ''; // Trying to update just the date + remove button field
  $form_state['rebuild'] = TRUE; // Tried adding this for troubleshooting; not seeing any difference
  return $form['closed_mon_exceptions'];
}

function multi_date_ajax_callback($form, &$form_state) {
  return $form['closed_mon_exceptions'];
}

```

# Answer
I believe I've got this figured out, and the code for two separate unlimited value fieldsets is included below.

The basic idea is on the initial form rendering, pull the stored values from the database. On subsequent renderings, pull the values from the `$form_state['values']` array. If the user has clicked the 'Add item' button, one additional item is added to the fieldset. If the user clicks the 'Remove item' button, the index is pulled from the button name and the item is removed from anywhere it's set in `$form_state`. I had to remove it from multiple arrays in `$form_state` because there are different arrays used for the saving the data and rendering the form.

I also had to add some unique button names and `preg_match` to pull the index of the removed item properly. (There are some bugs that I believe may be related to an issue I was seeing: FAPI identifies wrong button and Wrong detection of triggering element)

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

  // CLOSED MONDAY EXCEPTIONS
  // Fieldset container where we can add unlimited values
  $form['closed_mon_exceptions'] = array(
    '#type' => 'fieldset',
    '#tree' => TRUE,
    '#prefix' => '<div id="closed_mon">',
    '#suffix' => '</div>',
    '#description' => t('Exceptions to our typical closed Mondays.'),
  );

  // Add a flag to add on additional Mondays if the user clicks "Add Open Monday"
  $form_state['storage']['add_monday'] = FALSE;
  if (isset($form_state['triggering_element']) && $form_state['triggering_element']['#value'] == 'Add Open Monday') {
    $form_state['storage']['add_monday'] = TRUE;
  }

  $form_state['storage']['monday_init'] = isset($form_state['storage']['monday_init']) ? $form_state['storage']['monday_init'] : TRUE;

  // First time through, grab the values from the DB
  if ($form_state['storage']['monday_init']) {
    $closed_mon_dates_array = variable_get('closed_mon_exceptions');
    $form_state['storage']['monday_init'] = FALSE;
  // On subsequent renderings, grab the values from the values array
  } else {
    // get current values from form_state
    $closed_mon_dates_array = $form_state['values']['closed_mon_exceptions'];
    // remove the Add Open Monday button from this array
    array_pop($closed_mon_dates_array);
    $num_closed_mondays = count($closed_mon_dates_array);
  }

  // Get all the stored closed Mondays exceptions and remove the user-selected index
  if (isset($form_state['triggering_element']) && $form_state['triggering_element']['#value'] == 'Remove Monday') {
    // retrieve the index of the one we need to remove
    // preg_match required to get around Drupal bug related to multiple
    // submit buttons with the same name
    preg_match('/\d+/', $form_state['triggering_element']['#name'], $remove_mon);
    $remove_mon = $remove_mon[0];
    unset($closed_mon_dates_array[$remove_mon]);
    // reorder the array, so we have expected 0 through (count-1) indices
    $closed_mon_dates_array = array_values($closed_mon_dates_array);

    // Update the form values that will be submitted
    unset($form_state['input']['closed_mon_exceptions'][$remove_mon]);
    $form_state['input']['closed_mon_exceptions'] = array_values($form_state['input']['closed_mon_exceptions']);
    // or re-rendered to the form
    unset($form_state['complete form']['closed_mon_exceptions'][$remove_mon]);
    unset($form_state['values']['closed_mon_exceptions'][$remove_mon]);
  }

  $num_closed_mondays = count($closed_mon_dates_array);

  // Add all the current closed Monday exceptions
  for ($i = 0; $i < $num_closed_mondays; $i++) {
    if (isset($closed_mon_dates_array[$i])) {
      $current_date_val = $closed_mon_dates_array[$i];
      if (count($current_date_val) == 4) {
        array_pop($current_date_val);
      }
    }
    $form['closed_mon_exceptions'][$i] = array(
      '#type' => 'date',
      '#default_value' => $current_date_val,
      '#title' => t('Closed Monday Exception'),
      '#prefix' => '<div id="monday-' . $i . '">',
      '#suffix' => '</div>',
    );
    // Add a remove button for each one
    $form['closed_mon_exceptions'][$i]['remove_day'] = array(
      '#type' => 'button',
      '#value' => t('Remove Monday'),
      '#name' => "removemon-$i", // need to create unique names, regardless of tree structure
      '#ajax' => array(
        'callback' => 'monday_ajax_callback',
        'wrapper' => 'closed_mon'
      ),
    );
  }

  // Check if user clicked "Add Open Monday"
  if ($form_state['storage']['add_monday']) {
    // index for this one is at the end of the stored values
    $index = count($closed_mon_dates_array);
    $form['closed_mon_exceptions'][$index] = array(
      '#type' => 'date',
      '#default_value' => array(),
      '#title' => t('Closed Monday Exception'),
      '#prefix' => '<div id="monday-' . $index . '">',
      '#suffix' => '</div>',
    );
    $form['closed_mon_exceptions'][$index]['remove_day'] = array(
      '#type' => 'button',
      '#value' => t('Remove Monday'),
      '#name' => "removemon-$index", // need to create unique names, regardless of tree structure
      '#ajax' => array(
        'callback' => 'monday_ajax_callback',
        'wrapper' => 'closed_mon',
      ),
    );
  }

  $form['closed_mon_exceptions']['add_open_monday'] = array(
    '#type' => 'button',
    '#value' => t('Add Open Monday'),
    '#name' => t('add-monday'),
    '#ajax' => array(
      'callback' => 'monday_ajax_callback',
      'wrapper' => 'closed_mon'
    ),
  );

  // HOLIDAYS
  // Fieldset container where we can add unlimited values
  $form['holidays'] = array(
    '#type' => 'fieldset',
    '#tree' => TRUE,
    '#prefix' => '<div id="holidays">',
    '#suffix' => '</div>',
    '#description' => t('Additional closed days.'),
  );

  // Add a flag to add on additional Holidays if the user clicks "Add Holiday"
  $form_state['storage']['add_holiday'] = FALSE;
  if (isset($form_state['triggering_element']) && $form_state['triggering_element']['#value'] == 'Add Holiday') {
    $form_state['storage']['add_holiday'] = TRUE;
  }

  $form_state['storage']['holiday_init'] = isset($form_state['storage']['holiday_init']) ? $form_state['storage']['holiday_init'] : TRUE;

  // First time through, grab the values from the DB
  if ($form_state['storage']['holiday_init']) {
    $holidays_array = variable_get('holidays');
    $form_state['storage']['holiday_init'] = FALSE;
  // On subsequent renderings, grab the values from the values array
  } else {
    // get current values from form_state
    $holidays_array = $form_state['values']['holidays'];
    // remove the Add Holiday button from this array
    array_pop($holidays_array);
    $num_holidays = count($holidays_array);
  }

  // Get all the stored closed Holidays and remove the user-selected index
  if (isset($form_state['triggering_element']) && $form_state['triggering_element']['#value'] == 'Remove Holiday') {
    // retrieve the index of the one we need to remove
    // preg_match required to get around Drupal bug related to multiple
    // submit buttons with the same name
    preg_match('/\d+/', $form_state['triggering_element']['#name'], $remove_holiday);
    $remove_holiday = $remove_holiday[0];
    unset($holidays_array[$remove_holiday]);
    // reorder the array, so we have expected 0 through (count-1) indices
    $holidays_array = array_values($holidays_array);

    // Update the form values that will be submitted
    unset($form_state['input']['holidays'][$remove_holiday]);
    $form_state['input']['holidays'] = array_values($form_state['input']['holidays']);
    // or re-rendered to the form
    unset($form_state['complete form']['holidays'][$remove_holiday]);
    unset($form_state['values']['holidays'][$remove_holiday]);
  }

  $num_holidays = count($holidays_array);

  // Add all the current Holidays
  for ($i = 0; $i < $num_holidays; $i++) {
    if (isset($holidays_array[$i])) {
      $current_date_val = $holidays_array[$i];
      if (count($current_date_val) == 4) {
        array_pop($current_date_val);
      }
    }
    $form['holidays'][$i] = array(
      '#type' => 'date',
      '#default_value' => $current_date_val,
      '#title' => t('Closed Holiday'),
      '#prefix' => '<div id="holiday-' . $i . '">',
      '#suffix' => '</div>',
    );
    // Add a remove button for each one
    $form['holidays'][$i]['remove_day'] = array(
      '#type' => 'button',
      '#value' => t('Remove Holiday'),
      '#name' => "removehol-$i", // need to create unique names, regardless of tree structure
      '#ajax' => array(
        'callback' => 'holiday_ajax_callback',
        'wrapper' => 'holidays'
      ),
    );
  }

  // Check if user clicked "Add Holiday"
  if ($form_state['storage']['add_holiday']) {
    // index for this one is at the end of the stored values
    $index = count($holidays_array);
    $form['holidays'][$index] = array(
      '#type' => 'date',
      '#default_value' => array(),
      '#title' => t('Closed Holiday'),
      '#prefix' => '<div id="holiday-' . $index . '">',
      '#suffix' => '</div>',
    );
    $form['holidays'][$index]['remove_day'] = array(
      '#type' => 'button',
      '#value' => t('Remove Holiday'),
      '#name' => "removehol-$index", // need to create unique names, regardless of tree structure
      '#ajax' => array(
        'callback' => 'holiday_ajax_callback',
        'wrapper' => 'holidays',
      ),
    );
  }

  $form['holidays']['add_holiday'] = array(
    '#type' => 'button',
    '#value' => t('Add Holiday'),
    '#name' => t('add-holiday'),
    '#ajax' => array(
      'callback' => 'holiday_ajax_callback',
      'wrapper' => 'holidays'
    ),
  );

  return system_settings_form($form);
}

function monday_ajax_callback($form, &$form_state) {
  return $form['closed_mon_exceptions'];
}

function holiday_ajax_callback($form, &$form_state) {
  return $form['holidays'];
}

```
> 3 votes

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


# Question
Title: How can I restrict a Flat Rate to a single product SKU?
Shipping 2.0. Flat Rate is $4.95. I only want to offer this one Flat Rate I created to product SKU= 146

The place I am confused is in editing Conditions. What do I set the "Data Selector" to? Everything else makes sense to me but the Data Selector.

# Answer
> 0 votes
It really depends on the context of the event. If that event is receiving an order by default, then your conditions either need to be based on the order (such as "Order contains a particular product") or you'd need to loop over commerce-order:commerce-line-items and evaluate line item based conditions via custom Rules components.

I'd give that condition I mention above a shot before trying anything more complicated, though.

---
Tags: commerce
---