# Question
Title: How can I give option tags of a select tag ids or classes in Drupal 7?
I was able to add classes to option tags in a select statement in Drupal 6 using a very convoluted method. I was hoping that there would be a better way in Drupal 7. Does anyone know how to add classes to option tags in select tags?

# Answer
> 0 votes
You cannot give class or an id to options directly through form api. you can however, theme select element to add classes to select options.

```
   // theme_select
function THEME_select($variables) {
  $element = $variables['element'];
  element_set_attributes($element, array('id', 'name', 'size'));
  _form_set_class($element, array('form-select'));
  return '<select' . drupal_attributes($element['#attributes']) . '>' . THEME_form_select_options($element) . '</select>';
}

/**
 *
 * @param type $element
 * @param type $choices
 * @return string
 */
function THEME_form_select_options($element, $choices = NULL) {
  if (!isset($choices)) {
    $choices = $element['#options'];
  }
  // array_key_exists() accommodates the rare event where $element['#value'] is NULL.
  // isset() fails in this situation.
  $value_valid = isset($element['#value']) || array_key_exists('#value', $element);
  $value_is_array = $value_valid && is_array($element['#value']);
  $options = '';
  foreach ($choices as $key => $choice) {
    if (is_array($choice)) {
      $options .= '<optgroup label="' . $key . '">';
      $options .= THEME_form_select_options($element, $choice);
      $options .= '</optgroup>';
    }
    elseif (is_object($choice)) {
      $options .= THEME_form_select_options($element, $choice->option);
    }
    else {
      $key = (string) $key;
      if ($value_valid && (!$value_is_array && (string) $element['#value'] === $key || ($value_is_array && in_array($key, $element['#value'])))) {
        $selected = ' selected="selected"';
      }
      else {
        $selected = '';
      }
      $options .= '<option class="' . drupal_clean_css_identifier($key) . '"  value="' . check_plain($key) . '"' . $selected . '>' . check_plain($choice) . '</option>';
    }
  }
  return $options;
}

```

Similar question is answered here

---
Tags: 7, forms
---


# Question
Title: Easy way to copy drush vget variables from one site to another site?
I have a bunch of vget variables to copy over to another dev site. What is an easy way to do this? I'm able save it to a file via "drush vget | ack var\_name \> myfile", but how would i do a drush vset using those variables saved in the file?

# Answer
The problem here is that the output from a `drush variable-get` might be an array. Drush can easily render arrays on output, but `drush variable-set` does not provide a feature that allows you to provide arrays as input.

The best you can do with array data is to use php-eval:

`drush php-eval 'variable_set("var", array(...));'`

How do you get the `array` value to insert in here, though? Trying to do this directly from the `drush variable-get` output would be problematic; it would be very tedious to get all of the quoting and escaping right. I would not recommend this for your final solution.

Instead, you might consider using drush\_invoke\_process. Something similar to this might work:

`drush ev '$v = drush_invoke_process("@remote", "vget", array("var")); $data = $v["object"]; variable_set("var", $data);'`

That would probably do the trick for you. However, rather than building up a custom solution to moving configuration from one site to another with Drush, I might recommend that you instead examine the ctools export bonus Drush extension. It can export and import variables nicely, and might ultimately be better suited to your purpose.
> 4 votes

# Answer
You could set them in settings.php or you could write some sort bash script to loop through your export file and set each one.
> 1 votes

---
Tags: drush, configuration
---


# Question
Title: Programmatically develop search exposed filters
I developed a custom module to list contents of custom tables. Now I want to have search filters much like exposed filter. My code is below

```
$items['recording'] = array(
    'title' => 'Recordings',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('recordingcrud_sort_with_pager_content'),
    'access arguments' => array('access recordings'),
);

function recordingcrud_sort_with_pager_content($form, $form_state) {
global $user;
print_r($form_state);
if (!isset($form_state['storage']['recordingcrud']['search_criteria'])) {
  return render_table();
} else {
    print_r($_POST);
    $filters = $form_state['storage']['recordingcrud']['search_criteria'];
    return render_table($filters);
}

```

}

In render\_table function I am rendering the listing. and calling the fom

```
 $search_form = drupal_get_form('recordingcrud_search_form');
$output = drupal_render($search_form);

```

My search form and submit handler code is:

```
function recordingcrud_search_form($form, &$form_state) {
$form['search_term'] = array(
    '#type' => 'textfield',
    '#title' => t('Search'),
    '#size' => 40,
    '#maxlength' => 120,
);
$form['submit'] = array(
  '#type' => 'submit',
  '#value' => 'Apply',
  '#submit' => array('recordingcrud_search_form_submit'),
);

return $form;

    }

    function recordingcrud_search_form_submit($form, $form_state) {
        $form_state['storage']['recordingcrud']['search_criteria'] = $form_state['values'];
        $form_state['rebuild'] = TRUE;
    }

```

But this implementation I am getting the error

> PHP Fatal error: Unsupported operand types in /var/www/html/digitalFunctionalism/allprobail/includes/form.inc

What am I doing wrong?

# Answer
I finally managed to do this with the following changes.

I have changed the form method from post to get and then took the value of search term for url using `$_GET` Assigned action to the current page on which I am.

Changed the following code to

```
    'page callback' => 'drupal_get_form',
    'page arguments' => array('recordingcrud_sort_with_pager_content'),

```

to

```
'page callback' => 'recordingcrud_sort_with_pager_content',

```

and removed the second line.
> 0 votes

---
Tags: forms
---


# Question
Title: How to add a custom antispam questions in User registration Form
Recently I am receiving some user registration Spams...I use reCaptcha module but I want to add a anti-spam questions while User registers registration as you see in many forum sites.

Does anybody know how to do that ?...is there any module ..?

# Answer
> 2 votes
You can also customize captcha by the CAPTCHA Pack module. Here is a quote about it (from the module's project page):

> ... contains several CAPTCHA types for use with the CAPTCHA module. The CAPTCHA Pack module is meant to provide lightweight, yet effective alternatives for the traditional image CAPTCHA, which is undesirable in certain situation (e.g. bandwidth restrictions, cpu restrictions, accessibility constraints, etc).

# Answer
> 1 votes
You are probably looking for http://drupal.org/project/textcaptcha but if you have human spammers, they can answer any of these questions just as easily as completing a reCaptcha.

# Answer
> 0 votes
I have found the best way is to ask a question as part of your Captcha. Either of these should work:

https://www.drupal.org/project/captcha\_questions

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

The way you foil spambots is to ask a specific type of question that can't be solved by a Google search. If a Google search can solve your question, then a spambot will defeat it.

For example, I ask the user to select a word that doesn't fit in the pattern, such as "Which word doesn't belong? Washer, Dryer, Pony, Stove, Refrigerator."

I make it obvious for humans. I don't use any terms that could be a possible answer.

You can't stop human spammers, and that's not the intent, because you are then stopping humans. You are stopping spambots.

Human spammers reveal themselves, and you get rid of them and their content quickly.

I use this on a forum and a site, and so far zero spambots have been able to register or send me a spam e-mail. Zero. On my site, I have had 560 failed attempts and zero successful attempts to register. The first link has a tool that lets you see the failed attempts.

---
Tags: 7, advertising
---


title: Using comment view modes

text:
# Question
Title: Using comment view modes
I can use the UI to create a new view mode for a comment type in Drupal 8, without problems, but I don't see how to use that view mode.

For example, I just want to have a *teaser* that shows only the first few lines of each comment, and not the comments on this comment.

How do I specify a particular view mode should be used for the comments on a particular content type?

Does this require Display Suite?

# Answer
> 0 votes
There isn't a way to do this without writing your own formatters. However, could you open a feature request in the core issue queue as this is a worthy configuration option for the existing formatter.

---
Tags: 8, comments, entities
---


# Question
Title: Cannot install Drupal 8 on Windows 8 XAMPP PHP 5.6
Additional uncaught exception thrown while handling exception

Cannot install D8 in latest XAMPP workstation on Win8. Can install D7 though.

I did increase `max_allowed_packet = 64M`

# Answer
You have comments disabled in your opcache configuration. Add the following line

`opcache.save_comments=1` in php.ini or if `opcache` has its own config file

Please consult this for more details.
> 1 votes

---
Tags: 8, installation
---


# Question
Title: AJAX HTTP error on wsclient REST service
I'm trying out the wsclient in Drupal 7 and whenever I attempt to test the the transaction to another API using REST I get the following error:

```
An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /system/ajax
StatusText: OK
ResponseText:
Fatal error:  Call to undefined method HttpClient::__getLastRequestHeaders() in /home/dmwbm/www/sites/default/modules/wsclient/wsclient_tester/wsclient_tester.inc on line 143

```

Looking at the error it appears that this is an attribute required by the SOAP service. The SOAP examples are the only ones that work and the REST ones do not.

A friend suggested running this suite on simplytest.me so that I could isolate what is conflicting in my drupal install. Wouldn't you know, this message is output on this clean Drupal install.

Googling I see this error in a bug fix from two years ago. I must be doing something wrong in that this error should have been fixed by now and shouldn't show up in my install or simplytest.me. What obvious thing am I overlooking? thx, sam

# Answer
> 0 votes
It appears that both examples provided by the author no longer work, most likely because the API's changed. See link to author page above.

---
Tags: 8
---


# Question
Title: How can I use the MySQL FIELD() function within a SelectQuery object in Views?
I want to use the MySQL `FIELD()` function to alter a query so that it orders a particular field on a particular order of keys.

The keys for this 'select' field are: active, under\_contract, sold

I want to sort the View so that all of my results are sorted *first* by `node.created DESC` (this is simple, of course) and then push all `sold` nodes to the very bottom of the result.

I tried doing this first in hook\_views\_post\_execute():

```
function mymodule_views_post_execute(&$view) {
  if ($view->name == 'my_view') {
    usort($view->result, function($a, $b) {
      return ($a->field_field_status[0]['raw']['value'] == 'sold') ? 1 : -1;
    });
  }
}

```

but quickly discovered that, since my view only shows 25 results per page, this only pushes `sold` nodes to the bottom of each page.

Next, I tried to use `hook_views_query_alter()` to add the awesome MySQL `FIELD()` function that I just discovered – which works to achieve my goal perfectly in MySQL - but can't be added (at least as I'm discovering) to a SelectQuery object, which Views uses to run the query:

```
function mymodule_views_query_alter(&$view, &$query) {
  if ($view->name == 'my_view') {
    $query->orderby[0] = array(
      'field' => " FIELD(field_data_field_status.field_status_value, 'sold') ",
      'direction' => 'DESC',
  );
  }
}

```

How can I add a `FIELD()` orderby function to this query? Is there another method to push a particular filter value to the bottom of the result queue?

# Answer
I got this working! I couldn't find any way to get the `orderBy` working in `hook_views_query_alter()`, so I tried to do this in the raw `hook_query_alter()`. In my particular situation, I couldn't get any result when I filtered against the table that Views had already joined with (I can't explain why) and so I added my own join. Voila, it works.

```
function mymodule_query_alter($query) {
  if ($query->hasTag('my_view_id')) {
    // Remove the current sort order.
    $order =& $query->getOrderBy();
    $order = array();

    // Join with the table that we need, giving it a custom alias.
    $query->join('field_data_field_listing_status', 'custom_status', 'custom_status.entity_id = node.nid');

    // Add our cool FIELD() function to push all 'sold' nodes to the very back of the list.
    $query->orderBy("FIELD(custom_status.field_listing_status_value, 'sold')", 'ASC');

    // Add any other ordering that we need...
    $query->orderBy('node_created', 'DESC');
  }
}

```
> 3 votes

# Answer
Building on the previous answer (thanks). I found a way to do it within the views API.

"5,2,1,4" is just a random order of ids, so you can replace this by whatever field and keys you wish.

```
function HOOK_views_post_build ($view) {
  if ($view->name == 'my_view' && $view->current_display == 'my_display') {
      $view->build_info['query']->orderBy("FIELD(id,5,2,1,4)", 'ASC');
    }
  }
}

```
> 0 votes

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


# Question
Title: Contextual Filter with Title and Language
I'm building an api that is going to change base on the title and the language that is been request. This request is base on the URL something like this www.example.com/abc/fr-fr

* **abc** = title of the content
* **fr-fr** = Language Code name

For some reason the context filter of the language is turning my search into empty. Here is what happen when I try to run **www.example.com/abc/fr-fr**

```
{
  "nodes" : []
}

```

And it should looks like this instead:

```
{
  "nodes" : [
    {
      "node" : {
        "Literal Api" : "{\n \"glossary\": {\n \"title\": \"example glossary\",\n\t\t\"GlossDiv\": {\n \"title\": \"S\",\n\t\t\t\"GlossList\": {\n \"GlossEntry\": {\n \"ID\": \"SGML\",\n\t\t\t\t\t\"SortAs\": \"SGML\",\n\t\t\t\t\t\"GlossTerm\": \"Standard Generalized Markup Language\",\n\t\t\t\t\t\"Acronym\": \"SGML\",\n\t\t\t\t\t\"Abbrev\": \"ISO 8879:1986\",\n\t\t\t\t\t\"GlossDef\": {\n \"para\": \"A meta-markup language, used to create markup languages such as DocBook.\",\n\t\t\t\t\t\t\"GlossSeeAlso\": [\"GML\", \"XML\"]\n },\n\t\t\t\t\t\"GlossSee\": \"markup\"\n }\n }\n }\n }\n}",
        "Title" : "abc",
        "Language" : "French"
      }
    }
  ]
}

```

Things that I have already try it out:

1. I thought that the problem was having multiple contextual filters but that did not fix the problem because I try using it only the language contextual filter and I still have the same problem.
2. Also, I try to use the word "**French**" instead of the language code, which is **"fr-fr"** and this did not fix the problem.

Here is my view configuration:

**Note** I'm using node translation in 7, not entity/field translation. Each language has its own copy of a node.

My question is why I'm getting an empty node instead of the entire node information?

# Answer
Multiple contextual filters are fine & dandy. The issue seems to be that the url prefix being used in a translated/localized content is a bit different from the actual machine code for the language. French is not 'fr-fr' but simply 'fr' in Drupal's views. French Canadian would be 'fr-ca'.

here is a list of defined languages I use on my site along with their codes. These should be what you're looking to filter on. No issues with multiple filters.
> 2 votes

---
Tags: 7, views, i18n-l10n
---


title: How to remove fee from order

text:
# Question
Title: How to remove fee from order
I have added a fee with rules using commerce\_fee module. I need to remove the fee but i can´t find a way. How can this be done?

# Answer
Commerce Fees creates a line item of a particular type. You can loop through each of the line items on an order and remove the line item that has a particular type by looking at it's type value. I believe you can remove it by setting the quantity of the line item to 0.
> 0 votes

---
Tags: commerce, rules
---


# Question
Title: How to hide "Delete Site" link for a user rather than Admin?
I have website created in Drupal LMS "Openscholar". Its a academy site and there are various,they have there on vsite where they can add content as per there role.When user logged in ,there is a link to "Delete Vsite" available on his/her profile,

Therefore,my issue is that he can delete his account without concerning Admin.I tried to hide it using `"Display:none"` in CSS but it will hide Delete link for admin too. Thus, i want to know how to resolve such issue ?

# Answer
You can solve it by using a condition in your code. If current user is **admin** then show that **Delete Link** else hide it.

```
global $user;
if(in_array('administrator', $user->roles){
  your code to show link
}

```
> 0 votes

# Answer
```
 $global $user
    //Get admin_id from database and add condition
    if ($admin_id == $user->uid){
         add your code here
         }

```

Hope this idea of code is helpful for you
> 0 votes

---
Tags: theming
---


# Question
Title: How to display all users except current user?
How to display all users in a view except the current login user?

I try to write some php code in contextual filter, but that not work. I think there is an easy way but I don't know it.

# Answer
> 3 votes
I was able to make a view that displayed all the users while excluding the current user. Here is a screenshot of the settings I used:

Note that the important filter here is the "User: Current (No)". That is the one you'll need to have.

---
Tags: 7, views
---


# Question
Title: How do I resolve missing content type references from uninstalled modules?
In my previous setup of my site, I installed a bunch of modules and had them uninstalled. But now I have many orphaned or missing **content types** that still resides in the database somewhere. Below is what is displayed on the Field list page where its trying to reference these non-existent content types. Is there a place where I can go to clean this up? Which tables would I be looking into? And if I were to delete these entries where else would I have to delete it?

# Answer
> 0 votes
this probably is happening because you've deleted the module from sites/all/modules before uninstalling it correctly via drupal / or the module you have installed did not provided the code to uninstall it from database. Based in this, you can try to install the module again and then, disable it first, then uninstall it, and then delete it from the sites/all/modules. And don't forget to clear the cache

If the problem persist, i think you can always delet the tables individually from phpmyadmin. Let me know if the problem persists. So, then i can analyze it with you

# Answer
> 0 votes
You can try to manually delete a content type by constructing the URL by hand. For example, to remove the "forum" type, visit `admin/structure/types/manage/forum/delete`. I have had success with this method in the past. As @hailton says elsewhere, take a backup first.

---
Tags: 7, nodes
---


title: How to display the username in view

text:
# Question
Title: How to display the username in view
I'm new to Drupal 7 and I have created a content revision view. For that I have added a column of author in which I have also specified the user author relationship in view.

Problem is i am creating the content type using mobile device using web services for this created content i have content revision view in D7 here for all the content created user name displaying as admin i,e if I check the user name column in content revision column, then it shows the same admin name for all content created through multiple users, as shown in this screen print:

# Answer
In advanced section add a relationship by author like this :

Then add a field, choose User:name (the user or the author name) :

make sure that you have the relationship "author" in the field setting :

Now you should see the correct author name.
> 4 votes

---
Tags: views, users
---


# Question
Title: What's the purpose of $item in taxonomy_field_is_empty($item, $field)?
Please explain:

```
taxonomy_field_is_empty($item, $field)

```

`$field` \- this is name of field

`$item` \- what is it ???

I want to use on my function for check if tags field empty in node we don't show other articles, show otherwise.

# Answer
> 2 votes
*With the help of @Clive*

I think that's not the way, `taxonomy_field_is_empty` is an implementation of `hook_field_is_empty()`, which is used to

> Define what constitutes an empty item for a field type.

`$item` is:

> An item that may or may not be empty.

An `item` is the data for a specific field entry, so what you'd find in, for example, `$node->field_tags['und'][0]` in your code example.

If you have access to the `$node` variable and your field is named `field_tags`you can do this:

```
//Recover all the items
$items = field_get_items('node', $node, 'field_tags');
//If there is not a tag, then do something
if (count($items) == 0) {
  echo "field empty";
}

```

Or

```
//If there is not a tag, then do something
if(count($node->field_tags[LANGUAGE_NONE]) == 0) {
  echo "field empty";
}

```

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


title: How to add Jquery plugin to Drupal?

text:
# Question
Title: How to add Jquery plugin to Drupal?
Should I just paste the code in the main template file, or is there any other recommended way of attaching new Jquery plugins in Drupal 7?

# Answer
The easiest way is just to add it on your theme's .info file:

```
scripts[] = js/my_jquery_plugin.js

```

The only exception is if you are adding an external resource (CDN/hosted script), in which case you should use drupal\_add\_js(), as explained by Jamie Hollern
> 15 votes

# Answer
Drupal has Jquery packaged with it.

To add a js file you can use drupal\_add\_js in the way descibed in other posts.

This will work in simple cases, but if you start to have plugins which depend on other plugins. you may want to look at the libraries api. I expect in time modules will be created to support popular libraries, there are some for JQuery ui built in see system\_library().

In this example to inclued the jQuery ui.accordion module you can use drupal\_add\_library()

```
drupal_add_library('system', 'ui.accordion');

```

This will make sure the js is included along with the CSS and any libraries which depend upon it. It will also make sure that the libraries are only included once.

*If you say which library you are using I can provide sample code for how to define it*

So first create a module to define the library (call it qtip) and upload the module to a js folder underneath the module folder

then implement hook\_library()

```
function qtip_library() (
 $libraries['qTip'] = array(
    'title' => 'qTip',
    'website' => 'http://craigsworks.com/projects/qtip/docs/',
    'version' => '1.0.0-rc3',
    'js' => array(
      drupal_get_path('module', 'qtip') . '/js/jquery.qtip-1.0.0.min.js' => array(),
    ),
    'dependencies' => array(
      array('system', 'jquery'),
    ),
  );
  return $libraries;
}

```

Then to add the file put in your code

```
drupal_add_library('qtip', 'qtip');

```

This may be overkill for a simple library but if you have to manage a large number of libraries over multiple sites and themes it does make life much easier.
> 12 votes

# Answer
If you want to load script only on some pages (not all) you can add it trough your template.php file. Just add code similar to this:

```
function YourTheme_preprocess_node(&$variables) {

 $node = $variables['node'];
if (!empty($node) && ($node->nid == 983)
 // here you can esily add more pages
) {

drupal_add_js('sites/all/libraries/jquery.ui/ui/ui.core.js');
drupal_add_js('sites/all/libraries/jquery.ui/ui/jquery-ui-1.7.3.custom.js');
drupal_add_js('sites/all/libraries/jquery.ui/ui/ui.progressbar.js');

drupal_add_css('sites/all/libraries/jquery.ui/themes/redmond/ui.progressbar.css');
drupal_add_css('sites/all/libraries/jquery.ui/themes/redmond/ui.core.css');
drupal_add_css('sites/all/libraries/jquery.ui/themes/redmond/ui.theme.css');
 }
}

```

I only tested this in Drupal 6.
> 5 votes

# Answer
You can add a JavaScript file to the theme you use in the Drupal site, by adding a `script[] =` line in the .info file of the theme you are using. I would consider this case only if you are using a customized theme, or a modified version of an existing theme that has been renamed; I would not suggest to do it if you are using, for example, Garland. Doing it in such cases would mean to lose all changes all times the theme is updated, or to copy the updated theme files, and then re-apply the same changes applied to the previous version of the files; if the change is only adding a `script[]` line, then the change is minimal, and it could be worth doing it, but it would also mean the JavaScript files are not added in the directory containing the theme files, or you should add the JavaScript files every time the theme is updated.

As alternative, you can create a custom module, or add code to an existing custom module you are already using for that site.
The pro is that the JavaScript files would be added to every theme is set as default, or administration theme, without the need to change all the themes that are enabled on the site, and that users can select for themselves.

As already reported in another answer, `hook_init()` is the hook you should implement. I will add that `hook_library()` is the new hook added in Drupal 7 for Javascript files like jQuery plug-ins.
> 3 votes

# Answer
You can use Js Injector module to add scripts directly in Drupal admin panel. Alternatively you can use drupal\_add\_js() function to add your js file to your page.
> 3 votes

# Answer
You could create a simple custom module and add it that way. The code would be similar to the following:

```
MYMODULE_init() {
  drupal_add_js(drupal_get_path('module', 'MYMODULE') . '/FILE.js');
}

```
> 1 votes

# Answer
You can simply use in `YOURTHEME_preprocess_theme()` if you want apply logical condition:

`drupal_add_js(drupal_get_path('theme','your_theme').'/js/yourplugin.js');`

and add also in yourtheme.info file:

`scripts[] = js/yourplugin.js`
> 1 votes

# Answer
If you're using the Context module, install Context Add Assets. Set up a global context, or a specific context, and add a new reaction to add the JS asset by path or by module.

No coding required.
> 1 votes

# Answer
There are many external libraries which need to be included nowadays.

Putting them all under the theme's js directory is not always desirable since sometimes those libraries are composed of multiple js files and multiple css files.

I ended up using the `libraries_get_path` function of the libraries module to take their paths from the sites/all/libraries dir:

Here is how I added selected files which relate to textext.js:

```
<?php
function MYMODULE_init() {

  // Add jQuery library to a specific page.
  if (arg(0) == 'messages' && arg(1) == 'new') {
    // Add the jQuery TextExt library ( http://textextjs.com/ )
    $libdir = libraries_get_path('jquery-textext');
    drupal_add_js("$libdir/src/js/textext.core.js");
    drupal_add_js("$libdir/src/js/textext.core.js");
    drupal_add_js("$libdir/src/js/textext.plugin.tags.js");
    drupal_add_js("$libdir/src/js/textext.plugin.autocomplete.js");
    drupal_add_js("$libdir/src/js/textext.plugin.suggestions.js");
    drupal_add_js("$libdir/src/js/textext.plugin.filter.js");
    drupal_add_js("$libdir/src/js/textext.plugin.focus.js");
    drupal_add_js("$libdir/src/js/textext.plugin.prompt.js");
    drupal_add_js("$libdir/src/js/textext.plugin.ajax.js");
    drupal_add_js("$libdir/src/js/textext.plugin.arrow.js");

    drupal_add_css("$libdir/src/css/textext.core.css");
    drupal_add_css("$libdir/src/css/textext.plugin.tags.css");
    drupal_add_css("$libdir/src/css/textext.plugin.autocomplete.css");
    drupal_add_css("$libdir/src/css/textext.plugin.focus.css");
    drupal_add_css("$libdir/src/css/textext.plugin.prompt.css");
    drupal_add_css("$libdir/src/css/textext.plugin.arrow.css");
  }

} ?>

```

I would love to hear if there is an external repository in which all of those libraries are predefined so I won't have to define them each manually.
> 1 votes

# Answer
I recomment you to load jQuery from the pupblic Google CDN. Check this link for more info: http://code.google.com/apis/libraries/devguide.html#jquery .Just make sure you don't load the same script multiple times in your site.
> 0 votes

# Answer
this is what worked for me, no need to create a module for a jQuery plugin or install one - in my template.php I added:

```
function YOURTHEME_js_alter(&$javascript){
    // overwriting for newer jQuery version
    $javascript['misc/jquery.js']['data'] = path_to_theme() . '/assets/js/jquery-1.9.0.js';
    // also the min...
    $javascript['misc/ui/jquery.ui.core.min.js']['data'] = path_to_theme() . '/assets/js/jquery-ui-1.10.0.custom.min.js';
    // here I add the library (jQuery plugin) to resolve an error -> $.browser.msie undefined
    $javascript[path_to_theme() . '/assets/js/jquery-migrate-1.1.0.min.js'] = array(
        "group" => -100,
        "weight" => -18.990,
        "version" => "1.1.0",
        "every_page" => true,
        "type" =>   "file",
        "scope" => "header",
        "cache" => true,
        "defer" => false,
        "preprocess" => true,
        "data" =>  path_to_theme() . '/assets/js/jquery-migrate-1.1.0.min.js',
    );

}

```
> 0 votes

# Answer
another way is to add the following code to the page.tpl.php file
drupal\_add\_js(drupal\_get\_path('theme', 'path/to/your/plugin') . '/plugin.js', 'file');
> -4 votes

---
Tags: javascript
---


title: Drupal Migrate - Assign Roles

text:
# Question
Title: Drupal Migrate - Assign Roles
I'm creating a Migration from our old website (non-Drupal) to our new Drupal website. On our old website, roles and role assignments were kept in 2 seperate tables. So far, I've written a simple UserMigration and a RoleMigration class. However, I'm in doubt how I should proceed for the RoleMembershipMigration.

In short: Should I manually load roles in a `prepare` function for the UserMigration, or should this be done in a seperate Migration class altogether? I'm inclined towards the first, since it is not actually a migration to a seperate entity.

# Answer
> 0 votes
I suggest to join roles and role assignements tables togother in your query of RoleMigration class, in that case you will have these fields as source fields : `role_id, user_id, role_name`

now in UserMigration you just need to apply the dependency of the role migration on "roles" field :

```
$this->addFieldMapping('roles', 'role_name')
            ->sourceMigration('Role')
            ->defaultValue(drupal_map_assoc(array(2))); // authenticated user default value

```

Don't forget also that the key field of migration mapping should be the user\_id field :

```
$this->map = new MigrateSQLMap($this->machineName,
        array('user_id' => array(
                'type' => 'int',
                'not null' => TRUE,
                'description' => 'User ID.'
                )
            ),
        MigrateDestinationUser::getKeySchema()
    );

```

Didn't test it but should work like that!

---
Tags: migrations, users
---


# Question
Title: Automatic copy node from Drupal A to Drupal B
Drupal A and B are different domain (example: drupal A: www.aaa.com and drupal B: www.bbb.com)but at the same server. At Drupal A, there are lot of fields, but I **only need to send date field value** to Drupal B (Everytime when it update or add new content). Drupal B will get date value and display at the content page. May I know how to do that?

I had tried Deploy (not working at all) How to add data from one Drupal site to other?

I had tried aggregate but I send everything to Drupal B.

I need help. Many thanks.

For far my current solution is: At Drupal B: php code connect drupal A database and get the date vaule. Echo to display at the content page.

# Answer
> 1 votes
I would solve the problem with either of the following

1) Write a 5 minute custom **php** script that would show the node ids and data value and then update the nodes with data value in the second database with a simple update query on `field_data_field_<your-field-name>` table based on entity id.

2) Use services 3 module to expose your data and then import that field with put method with only the field you want.

# Answer
> 0 votes
You have several options:

* Use Migrate: This is like what you have but more Drupal way. The migration code should be the iterator that queries your Drupal A and returns the list of nodes and the code that takes each node and updates or creates nodes on Drupal B. I recommend you to put it in a Drush command and call it from system cron (not Drupal cron but system cron).
* Using some kind of services: When Drupal A detects a change that should be sent to Drupal B make a service petition to a service on Drupal B. You have to set up the service on Drupal B and the code that consumes the service in Drupal A.
* Exposing info from Drupal A: A simpler option is to export the data in Drupal A as a View and Drupal B access the URL to check new data and import it, using Drupal cron. You can protect the URL with Basic Auth allowing only local connections.

You can even combine (for example, use Migrate but instead of connect directly to the other database consume data from a View form Drupal A).

Disclaimer: I've not tested other modules to copy content, may be there's a module that suits your needs, I'm extending your current solution.

# Answer
> 0 votes
I would suggest that you use drupal\_sync module. it allow sync content between multiple websites. Its built on top of API so you can create your own custom module on top of it.

---
Tags: 7
---


# Question
Title: How to alter commerce cart view to show custom line item data - either through UI or custom module
In a custom module I am adding data to a line item added to the cart like this:

```
$user_to_add =_get_user_by_ain($ain);
$product = commerce_product_load($product_id);
$line_item = commerce_product_line_item_new($product, 1, 0, array('apply_to_user' => $user_to_add));
commerce_cart_product_add($user->uid, $line_item);

```

This data is used in Rules after checkout is completed. What I'm struggling with now is being able to show that data in the cart view (default, Commerce provided, commerce\_cart\_form). For example, if the $user\_to\_add contains the users first name, I'd like to be able to show that in the cart view next to the product label.

I've been going through the views api, testing the hooks available, and I can't figure out where to do this. In the hooks that I've tried, the data is is available in `$view->result[0]->_field_data['commerce_line_item_field_data_commerce_line_items_line_item_]['entity']->data['apply_to_user']`

# Answer
If you're wanting to display information from inside the `$order->data` array, then you'll need to create a Views handler for each value and write some code to load the object, access the data, and then display it. An example of how to do this can be found in the GetID3 views integration. It loads file metadata and exposes it to views, but the idea is the same.
> 1 votes

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


# Question
Title: How to add custom "pay now" button and after submit, redirect to the checkout/orderId page
In the *Deal details page* I want to add a new button *Pay Now* and then user clicks it, then redirects to the *checkout/orderId* page. How is it possible ? Please help.

# Answer
Use a rule. Example:

```
{ "rules_forward_user_directly_to_checkout" : {
    "LABEL" : "Forward user directly to checkout",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [],
    "REQUIRES" : [ "commerce_order", "rules", "commerce_cart" ],
    "ON" : { "commerce_cart_product_add" : [] },
    "IF" : [],
    "DO" : [ { "redirect" : { "url" : "checkout" } } ]
  }
}

```

Note that you don't need to redirect to `checkout/%order_id`, you just need to redirect to `checkout` and Commerce will take care of the rest.
> 0 votes

---
Tags: commerce
---


# Question
Title: Top article image not showing when I share content with Facebook or Google Plus
So I inspected the image element and everything looks fine compared to other sites code. But when I share an article from my blog nothing shows in the image section. Interesting enough if I share the same article on Linkedin the top article image appears like it should. Body images always show if any are present. it's just the top article image with the issue.

Here's an example: http://thepoliticus.com/content/how-well-do-you-know-state-union

Element:

# Answer
That page doesn't have the proper OG tags in the head of the HTML. Facebook uses these to process the things about the page that you want them to know or they scrape the page to get them. They normally take something like the first image if the og:image tag isn't there. You can see what exactly they are taking by running a URL through their debugger. The page ran through the debugger. If you scroll down you will see what they are using for the OG tags.

To handle this in Drupal you will need to use a combination of the Metatag module and Drupal Tokens in order to get the dynamic properties. After configuration and the proper token setup you should see your sharing work correctly (I have seen the FB servers cache pages that are shared so it may take some time to eventually get the results) provided you have the proper OG tags in the HTML Head. You can always run the pages through the FB debugger to scrape the page and see the actual results that should be shown.

Note: There may be other ways to accomplish this but this is the top way that I accomplish this task.
> 0 votes

# Answer
We need to pass the url for the image derivative based on the style we're using.

So - not this:

```
[my_site]/sites/default/files/my_image.jpg

```

Rather, this:

```
[my_site]/sites/default/files/styles/large/public/field/image/my_image.jpg?itok=kB4r6YaD

```

This image derivative url is not part of the $node object, so we have a bit of wrangling to do. One way is to enable the php filter and use this as the value for facebookpost:field-facebook-picture:

```
<?php
  if($node->field_image) {
    if(array_key_exists(0, $node->field_image['und'])) {
      $fid = $node->field_image['und'][0]['fid'];
      $result = db_select('file_managed', 'fm')
        ->fields('fm', array('uri'))
        ->condition('fm.fid', $fid,'=')
        ->execute()
        ->fetchAssoc();
      $path = $result['uri'];
      $style_name = 'your_style_name';
      print (image_style_url($style_name, $path));
    }
  }
?>

```

I used similar logic in a custom token instead of using php evaluation for the value of facebookpost:field-facebook-picture.
> 1 votes

---
Tags: media, social-network
---


# Question
Title: User Login with Email Address - Services
Drupal login form allows users to enter their *username* or *email* to login into the site.

I need to achieve the same thing with services. But services allows users to login with username (not working with email).

JSON format for User Login (works).

```
{"username":'myusername', "password":"mypassword"}

```

But how can we do login using "email" as username? I've tried the following JSON formats

**Input:**

```
{"username":'myusername@gmail.com', "password":"mypassword"}

```

**Response:**

`["Wrong username or password."]`

**Input:**

```
{"mail":'myusername@gmail.com', "password":"mypassword"}

```

**Response:**

```
["Missing required argument username"]

```

According to this link, I need to tweak the services modules to achieve this requirement.

Is there any way to achieve this?

# Answer
> 4 votes
You can do this in a *custom module*:

```
/**
 * Implements hook_services_resources_alter().
 */
function my_module_services_resources_alter(&$resources, &$endpoint) {
  // Override the normal user login callback.
  if (isset($resources['user']['actions']['login']['callback'])) {
    $resources['user']['actions']['login']['callback'] = 'my_module_services_login';
  }
}

/**
 * Replacement callback for the Services user login resource. Optionally use the email address to login.
 *
 * @see _user_resource_login().
 * @see https://drupal.org/node/1431724
 */
function my_module_services_login($username, $password) {
  $result = db_query(
    "SELECT name FROM {users} WHERE LOWER(mail) = LOWER(:username)",
    array(':username' => $username)
  )->fetch();
  if (!empty($result->name)) { $username = $result->name; }
  return _user_resource_login($username, $password);
}

```

Using this technique, you don't need to patch the Services module.

This solution is borrowed from DrupalGap:

http://cgit.drupalcode.org/drupalgap/tree/modules/drupalgap\_logintoboggan/drupalgap\_logintoboggan.module

# Answer
> 0 votes
For time-being I've added my own patch in my services module.

In the user\_resource.inc file, added the following line of code in the `_user_resource_login` function, just before the call to `user_authenticate`

```
if (valid_email_address($username)) {
$username = db_query("SELECT name FROM {users} WHERE mail = :mail",array(':mail' => $username))->fetchField();
}

```

I've tested both following formats to login the user, working great.

```
{"username":"myusername","password":"mypassword"}

{"username":"mymail@gmail.com","password":"mypassword"}

```

I'll try to post @Clives suggestion (from comments) as my answer once I get some time :)

I hope this helps for someone who looks to add their own patch to their services module

---
Tags: 7, services
---


# Question
Title: How to restrict access to blocks depending on the roles?
How can I restrict the Access to the blocks in my website depending on the roles? I.e only a particular role can see (edit view delete configure) a particular block and nobody else can do so.

I tried the Block Access module but to no avail.

Is there any other module that can help?

# Answer
This patch could help you in controlling access to blocks.

Patch is here https://drupal.org/node/1916028#comment-7302100.

Need to apply this patch on dev version of this module **7.x-1.x-dev** of **Block Access**
> 1 votes

# Answer
Using the Bean module you can perfectly implement what you're asking for. Here is a quote about its project page:

> Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require. The bean content can then be placed around the site just like any other block.

Combined with the options available for granting the appropriate **Bean permissions**, it should give you a lot of flexibility about how exactly you want to use this (great) module in your specific case: for each ***Block type*** created with the BEAN module, you can use the typical *Permissions* page (at `admin/people/permissions`) to grant **Add/Edit/View/Delete** access to selected roles. So if you'd create one such "block type" for each of the roles you have, then all users with that role (and only those) could then edit view delete configure such blocks (which may be either just 1 block or multiple blocks).

Some more background info about BEANs:

* To define a *Block type* you use the admin UI (via `admin/structure/block-types`), which is similar to defining content types (via `admin/structure/types`).
* The difference is that you don't create *nodes* (of a selected "content type", and by using `node/add`), but *blocks* instead (of a selected "block type", and by using `block/add`).

This module also works great in combination with the UUID and UUID Features Integration modules. And after you become familiar with the Bean module, you might find other cases in your site where you also want to use this module (which somehow compensates the fact that you need to add another module).

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.

PS: this is a D7 module, integrated in core in D8 ...
> 1 votes

---
Tags: blocks, users
---


title: direct acces image url

text:
# Question
Title: direct acces image url
I searched but cannot find an answer to my question.

I'm using Drupal 7 and created content with image. The path of the content is `http://example.com/page/content`

My problem: I want to share the URL of the image to facebook.

`http://example.com/sites/default/files/image01.jpg`

But the request URL shows "404 not found".

I have set the media to show in public.

Did I miss something?

# Answer
If that file does actually exist within /sites/default/files/ then your link should work.

Have you messed around with the .htaccess file in the root of your site? Or it could be the hosting package your on as there's a rule in that htaccess to not go into drupal if the file exists in that directory
> 0 votes

---
Tags: 7, media, uri
---


# Question
Title: How to convert taxonomy term name to term id at time of importing and create custom node from csv in drupal?
I am creating content type programmatically. I am importing content from csv file.. Everything working fine. But I am not able to select category at the time of import like other fields.. and how to convert term name to term id ,because csv giving me term name.

# Answer
This function will return the term object if you pass it the term name: https://api.drupal.org/api/drupal/modules%21taxonomy%21taxonomy.module/function/taxonomy\_get\_term\_by\_name/7

There is an example at the bottom of that link
> 0 votes

---
Tags: taxonomy-terms, importing-exporting
---


title: View / Edit tabs no longer functional

text:
# Question
Title: View / Edit tabs no longer functional
I seem to have done something to mess up the View / Edit tabs which appear above page content when you are logged in with appropriate rights. The tabs appear but they are no longer clickable. If I access the "edit" link via the dashboard, I can edit the page contents no problems - it's just the handy short-cut that has stopped working.

Anybody know how to fix this?

# Answer
Use chrome/firefox's inspector and click on the edit link that will highlight the element that's sitting over the top of it and you can sort your CSS out for that element
> 0 votes

---
Tags: 7
---


title: How to limit block management by role?

text:
# Question
Title: How to limit block management by role?
In a Drupal 7 site, I want to give users with a certain role the permission to manage some (but not all) blocks. More specifically, only want to allow editing the blocks provided by the Nodeblock module.

I can probably do a lot with hook\_form\_alter, but maybe there is a cleaner way (or even a module) to specify edit permissions on the block level.

# Answer
Take a look at Block Access.

From the project page:

> This module adds a set of global permissions for creating, viewing, moving, enabling, disabling and configuring blocks as well as permissions at the individual block level.
> 1 votes

# Answer
Part of your question is *"... only want to allow editing the blocks provided by the Nodeblock module"*. Whereas the purpose of that module is like so (from its project page):

> This module allows you to specify content type(s) as being a block. This allows the content managers of the site to edit the block text and title without having to access the block administration page. Users only need edit access to that node in order to edit it.

Together with *"... I want to give users with a certain role the permission to manage some (but not all) blocks ..."* (as in your question), it seems that a translation (summary) of your question is something like "**How can I allow the content managers of my site to manage some (but not all) blocks (eg: edit the block text and title) without having to access the block administration page**".

Using the Bean module you can perfectly allow your content managers to ""***manage some (but not all) blocks (eg: edit the block text and title) without having to access the block administration page***"". Here is a quote about the Bean module (from its project page):

> Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require. The bean content can then be placed around the site just like any other block.

Combined with the options available for granting the appropriate **Bean permissions**, it should give you a lot of flexibility about how exactly you want to use this (great) module in your specific case: for each ***Block type*** created with the BEAN module, you can use the typical *Permissions* page (at `admin/people/permissions`) to grant **Add/Edit/View/Delete** access to selected roles (Note: these are 4 separated permissions also). So if you'd create one such "block type" for the role "content managers", then all users with that role (and only those) could then Add/Edit/View/Delete such blocks.

Possible bonus: would you still need the Nodeblock module?

Some more background info about BEANs:

* To define a *Block type* you use the admin UI (via `admin/structure/block-types`), which is similar to defining content types (via `admin/structure/types`).
* The difference is that you don't create *nodes* (of a selected "content type", and by using `node/add`), but *blocks* instead (of a selected "block type", and by using `block/add`).

This module also works great in combination with the UUID and UUID Features Integration modules. And after you become familiar with the Bean module, you might find other cases in your site where you also want to use this module (which somehow compensates the fact that you need to add another module).

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.

**Remark**: interesting detail on the Nodeblock project page:

> ... There are several other modules and approaches that allow nodes to be presented as a block. See a comparison at http://groups.drupal.org/node/93499 ...

And this last link states the following:

> The Bean module does not allow nodes to be presented as blocks, per se, but creates block entities instead. Since entities are the fundamental unit of Drupal 7 content, this is analogous and can accomplish many of the same ends.

This sounds like "Now that the BEAN module is available (it wasn't at the time this question was asked), you don't need blocks to be presented as nodes anymore to do more advanced things with blocks" ... no?

PS: The Bean module only started as of D7 (because of the "entities" of course that were only introduced in D7), and already has over 22K reported installs. AND it has been integrated (already) in core in D8. Those who don't use it yet should definitely start looking at it in preparation of some day upgrading to D8.
> 2 votes

---
Tags: 7, blocks, users
---


# Question
Title: drupal 7 xml sitemap showing nodes that are unpublished
we have xml\_sitemap 7.x-2.0-rc1 and drupal 7.23 core and it is putting unpublished nodes in the xml site map. What can we do?

# Answer
solution - turn off the individual node. with the xmlsitemap node module enabled. at the bottom of the content page when you are editing you can choose Inclusion: Excluded.
> 1 votes

# Answer
Excluding the node manually, isn't really the long term solution. The actual problem resides with the module. There is currently a patch that claims to handle this issue and that's the best place to start.

See this: https://www.drupal.org/node/2266933
> 1 votes

---
Tags: xml-sitemap
---


title: Twig theme variables

text:
# Question
Title: Twig theme variables
I am working on creating a theme from scratch for Drupal 8 and I am 90% of the way there. I do have a question on how to access variables in the

```
{{ dump() | raw }}

```

I have created a page.html.twig and the {{ page.BLOCKNAME }} is working great. But when I try to place {{ title }}, or any variations, I get NULL or nothing at all.

I can see the title in the dump(), but it has \["string":protected\]=\> so I am not able to access. I was able to create a new block region and move the title there, but the title will not be in the same place from page to page. I would also like to access the content type, node ID, and node url, with some other custom fields I created, but I can't seem to get to those either.

In summary, how do I use the dump() and actually get to the variables that are presented?

# Answer
If you wanna see all variables available in your twig template file in Drupal 8 use `{{ kint(_context) }}`. Don't forget, you must enable kint in devel module settings.
> 2 votes

# Answer
In the page template you shouldn't be printing blocks directly. Blocks should be always printed inside a regions. More information about how to add your custom region can be found here.

If you are printing an already existing region the syntax for that is:

```
{{ page.region_name }}

```
> 1 votes

---
Tags: 8, theming
---


# Question
Title: How to set Drupal Commerce shipping rules by the longest of the shortest dimensions of a product?
How can I create shipping rules which will base the shipping charge on the length of the package? Specifically, I need two rules for shipping: 1) if the length is less than X, then charge Y; 2) else/if the length is greater than X charge Z. Finally, I only need longest of the shortest dimensions for the shipping price.

I have a use case where the shipping charge is determined by the length of the packaging, not weight, or number of units. The products are posters, which will be rolled along the shortest side, such that I cannot simply base the shipping on a specific physical dimension (e.g. the length) as the posters are sometimes horizontally oriented and for this reason the dimension which needs to be used for the shipping calculation should be the shortest, but shipping must be calculated on the longest of the short dimensions. I'm only just now diving into the shipping rules and I've looked at Commerce Physical and Physical Fields, but I'm not sure how to take the shortest of two dimensions of the products, and then base the shipping on the longest of these.

As always, any advice would be greatly appreciated.

# Answer
> 0 votes
The best way to do this will be to create a custom rules action that sets this the way you want it. Writing rules actions isn't very scary. It's mostly a wrapper around a PHP function. Then you can get the logic just right. You could:

1. Write an action that takes the order as a parameter, returns the dimension you want, and then calculate the shipping in Rules, or
2. write a function that applies a shipping line item directly to the order.

Option 1 is easier to write and would be my initial tack on the problem. Option 2 is a bit more holistic but requires that you look at the shipping modules to see how they properly add a shipping line item to the order.

---
Tags: commerce
---


# Question
Title: What is placeholder_token in html.html.twig for?
Started to dive into Drupal 8 twig, and what better place to start than from the top: html.html.twig

But found this:

```
<head-placeholder token="{{ placeholder_token|raw }}">

```

Here is the change record:

And some related issues:

And the documentation:

But nothing really clarifies why this was done.

Is this a Drupalism? A Twigism? What are these tokens for?

The only other time I've seen a placeholder token system like this was with CTools where they create a placeholder in the generated HTML output and then go back later and replace the token with the actual value. If this is the same concept, why does Drupal core need to do this? (The CTools system was ostensibly to get around some core limitations).

# Answer
The reason why placeholder\_token is used in html.html.twig instead of using just a normal variable is that in Drupal 8 we have different render strategies than just the simple rendering where everything gets rendered in the template and we are able to collect the assets.

In the Drupal cores default Renderer we have placeholders (placeholders might attach some additional assets). If we would print the assets in a normal variable it would happen before all the assets have been collected. So what Drupal 8 does is it first renders everything with the normal rendering in the template, then it replaces the placeholders and collects assets from then, and after all that has been done we finally replace the asset placeholders to add the assets to the page.
> 9 votes

# Answer
**TL;DR:** In a practical scenario `<head-placeholder token="{{ placeholder_token|raw }}">` == `{{ head }}`

The issue where this change was introduced is: Move attachment processing to services and per-type response subclasses

And like this change record says this:

```
 <head-placeholder token="{{ placeholder_token|raw }}">

```

Just replace this:

```
{{ head }}

```

The token attribute is just for avoid collisions it doesn't have any other special purpose.

You can see at Theme.inc at the function `template_preprocess_html` the following code:

```
$types = [
  'styles' => 'css',
  'scripts' => 'js',
  'scripts_bottom' => 'js-bottom',
  'head' => 'head',
];
$variables['placeholder_token'] = Crypt::randomBytesBase64(55);
foreach ($types as $type => $placeholder_name) {
  $placeholder = '<' . $placeholder_name . '-placeholder token="' .
  $variables['placeholder_token'] . '">';
  $variables['#attached']['html_response_attachment_placeholders'][$type] = $placeholder;
}

```

Which basically builds all the tokens and put them in the `html_response_attachment_placeholders` array.

Later when the page is being rendered the tokens are replaced by the data (scripts,styles etc) see `HtmlResponseAttachmentsProcessor::processAttachments`
> 6 votes

---
Tags: 8, theming
---


# Question
Title: Change the disabled status of a form element via Ajax
I have a form built with the Form API. I have a field which is, at first, disabled. I want to change the status of that field to enabled when the user selects another contiguous field.

I have a working example of changing the callback URL of Ajax complete of that field, so the form is making a kind of OnChange and working well, but for some reason I am not able to change the disabled status.

Code. Here the 2 elements, first brand and next the model, which is disabled at the beginning.

```
 $form['brand'] = array(
'#type' => 'select',
'#title' => t('Brand'),
'#options' => $brands,
'#default_value' => $brand,
'#ajax' => array(
    'callback' => 'hook_models_update',
    'wrapper' => 'models_wrapper',
    'progress' => array(
        'message' => '',
        'type' => 'throbber',
    ),
),
);

 $form['model'] = array(
    '#type' => 'textfield',
    '#title' => t('Model'),
  //    '#description' => 'Please note available models change based on the brand selected.',
'#required' => FALSE,
'#autocomplete_path' => 'providers/autocomplete/' . $brand,
'#attributes' => array("placeholder" => t('Model')),
'#prefix' => '<div id="models_wrapper">',
'#suffix' => '</div>',
'#disabled' => TRUE,
);

```

Now the code for the "onChange" behaviour, which is a "throbber" called hook\_models\_update:

```
function hook_models_update($form, &$form_state) {
    unset($form_state['input']['model'], $form_state['values']['model']);
    $brand = $form_state['values']['brand'];
    $form['model']['#autocomplete_path'] = 'providers/autocomplete/' . $brand;
     $form['model']['#enabled'] = TRUE;
    // $form['model']["#disabled'] = FALSE
    return form_builder($form['#id'], $form['model'], $form_state);
} // function

```

I have tried with **#enabled** = TRUE and with **#disabled** = FALSE, with no successs.

# Answer
I found the solution here:

Enable DropDown using Ajax Call

The code finally gets this:

```
     function hook_models_update($form, &$form_state) {
         unset($form_state['input']['model'], $form_state['values']['model']);
         $brand = $form_state['values']['brand'];
         $form['model']['#autocomplete_path'] = 'providers/autocomplete/' . $brand;
         unset($form['model']["#attributes"]['disabled']);
         $form['model']['#disabled'] = FALSE;
         return form_builder($form['#id'], $form['model'], $form_state);
} // function

```

The trick lies in these two lines:

```
     unset($form['model']["#attributes"]['disabled']);
     $form['model']['#disabled'] = FALSE;

```

Apparently, there has to be an unset and not of #disabled, but #attributes - disabled. Why this is so convoluted is beyong my comprehension.
> 2 votes

---
Tags: 7, forms
---


# Question
Title: Creating Private file directories inside public files directory
I am developing a custom entity, which has a file field, which accepts .zip files. After the entity save, the contents of the zip file are decompressed into a folder specific to the .zip file, in the public files directory.

I'm am wondering if it is possible to create "private directories", which would act similar to standard Drupal private files...basically I want to restrict access to any file in the directory, but Drupal not knowing what files may be in the directory.

Basically the zip file will contain several .html files, javascript, and css files, which will be launched on the entity view page in an iframe.

Is this even possible?

Would anyone have some possible strategies to accomplish this goal?

I'm not asking how to setup a private file directory for storing and controlling access to single files, as is standard Drupal, I'm asking if it is possible to control access to any random file in a certain directory....inside the public files area.

I'm wanting to manage unmanaged files, by managing the parent directory, not the individual files

I'm open to using the Drupal core private file system, as long as Drupal doesn't have to manage the individual files specifically

# Answer
> 0 votes
Using just Drupal, it's not possible.

It's important to consider what setting store files as public means for Drupal. Essentially, it means Drupal relies on the web server for output of files URLs (vs. it being the gatekeeper to a directory non-accessible from the web server).

As such, to do what you want would require your zip processing code to do extra work of configuring your web server to restrict access (e.g. creating .htaccess files). You would also need some custom code to create proxy URLs paths to any file inside the unpacked zip directory. Lastly, you'd want to take a hard look at possible security vulnerabilities you're opening up by giving users unfettered access to run/view any arbitrary JS/HTML/CSS on your domain.

---
Tags: files
---


title: Token replacement for list keys

text:
# Question
Title: Token replacement for list keys
I'm trying to define a Display Suite Code Field which would be responsible for converting a list item key (selected in a dropdown on admin side) into an image on the output side. The field simply assumes the list keys:

```
series1|Series 1 Name
series2|Series 2 Name

```

correspond to the images names and the tokenized field definition is as in:

```
<img class="product-series" src="/path/to/image/[node:field-product:field-series].png"/>

```

However what I got after replacement is the label ("Series 1 Name"), instead of the key. Is there a way to force the key replacement? (Yes I know I could drop the Label part, but this would not be admin friendly)

# Answer
Enable the "Token" view mode and select "Key" as field formatter for the "Series" field.
> 0 votes

# Answer
Way old, I know but I was fighting with a similar issue (though I wanted keys and was getting labels) and after much fighting got it to work so I figured I would share. I went to "Manage Display Settings" for the content type and enabled "Tokens" under "Custom Display Settings." Then selected "Tokens" under the "Manage Displays" heading and changed my select list's format from "Default" to "Key". Using the Devel module I could see then that I had 2 available Tokens one was in the format \[node:field-example-field-one\] and the other in the format \[node:field\_example\_field\_one\]. The one with dashes contained my Label and the one with underscore contained my Key.
> 0 votes

---
Tags: tokens, display-suite
---


# Question
Title: How can I overidde html.html.twig in a module?
I have an application that is two parts: a website front-end and a restful back-end I can do with AngularJS.
The restful part is done by a module and I need to override html.html.twig.

How do I achieve this?

# Answer
Overriding templates in the modules is not suggested because Drupals architecture doesn't really support multiple modules overriding same template.

However if you are still willing to do this, you have to simply add hook\_theme() like this in your module file:

```
/**
 * Implements hook_theme().
 */
function modulename_theme() {
  return [
    // Normally theme suggestion templates are only picked up when they are in
    // themes. We explicitly define theme suggestions here so that these
    // templates in this module are picked.
    'html' => array(
    'render element' => 'elements',
    'base hook' => 'html',
  ];
}

```

Note: This will cause error messages in case you don't have the html.html.twig template available in the templates folder.
> 1 votes

---
Tags: theming, 8
---


# Question
Title: Display definition of the term searched for - above search results
Beginning a search on google with 'what is psych'... triggers auto completion with 4 suggested phrases - arrow down through each and you will see its definition appear above its pertaining results:

How can I add a definition of the terms (if available) above the results? Ideally would like to use auto complete. I've attempted to achieve this with the Google custom search engine and Google site search modules. Unfortunately, the Google Dictionary service appears to no longer be supported by Google.

I explored another option such as using Solr search api and coding a second custom call from a definition source such as Wordnik and then combining that result with the Solr results. I think this may be feasible but not sure yet how will combine the results.

How could I combine search results to include a definition and/or is there a better way to include a definition of what the user may be searching for, above the actual results?

# Answer
> 0 votes
It turned out it was necessary to use Wordnik api (or similar) to get the definition service that I required. So I've written a module to handle the api and show definition/image for the searched terms if available.

After talking to Google support and verifying my research that google no longer provides a definition service (they did back in 2011) to private websites, I realized it best to abandon the idea of using the google custom search engine. Instead I've setup Solr which is a bit more work but much more custom.

---
Tags: search
---


# Question
Title: Can`t access config panel after the installation of Ubercart and e-commerce modules
Fatal error: Call to undefined function dpm() in /home/u275855040/public\_html/sites/all/modules/ecommerce/ec\_store/ec\_store.tokens.inc on line 10 How to fix that?

# Answer
You are using dpm function to print variable. To fix this issue you just need to enable the devel module or comment the dpm function.
> 1 votes

---
Tags: ubercart
---


# Question
Title: Theme settings to include different PHP files into template
I'm trying to include a template section into another template under conditions based on the themes settings.

**page.tpl.php**

```
<header>
    <?php
    $theme_header_style = theme_get_setting('header_style');//the value is 1
    $header_path = "header_tpl_".$theme_header_style.".php";
    include_once $header_path;//includes header_tpl_1.php
    ?>
    <h1><?php print $site_name; ?></h1><!--this works-->
</header>

```

**header\_tpl\_1.php**

```
<h1>this will show up</h1>
<h1><?php print $site_name; ?></h1><!--this will not work just an empty h1-->
<p>this will show up on page.tpl.php as well</p>

```

I'm pulling in `header_style` from my themes settings and for this example the value is 1. The file it will include is being added, as the html from the file is displaying but any php in the file is being ignored. anything on page.tpl.php is working as expected its only the php content on included files like `header_tpl_1.php` that is not working.

**Update**

Now that I know using a PHP include doesn't work I would like to know how I could include the contents of the `header_tpl_1.php` into the template prior to Drupal rendering the page, as this clearly would be the solution. The end objective is being able to load different PHP files into `page.tpl.php` based on a value set in the themes settings. The code in my `header_tmp_1.php` was removed from `page.tpl.php` as working code and put into `header_tpl_1.php` so I know there are no errors in it, as it works if it's added directly into `page.tpl.php`. The problem is including content into a template. I need the content to be included prior to Drupal rendering the variables.

# Answer
> 0 votes
Did you cleared cache ? I usually include header.inc, but I try your code and it worked on my site.

---
Tags: 7, theming
---


# Question
Title: How do I access variables displayed in devel?
Using devel I'm able to retrieve the names of certain variables and how to access them.

For example I might want to use the book menu name. Devel has it listed as so

```
$...->book['menu_name']

```

But I'm not sure how to print that info in page.tpl.php or access it in general. I'm also not sure what to replace the $... with.

I've tried the following with no luck.

```
print $page->book['menu_name'];
print $node->book['menu_name'];
print render($page->book['menu_name']);
print render($node->book['menu_name']);

```

# Answer
If you want to do any theming to node use node.tpl.php instead of page.tpl.php

in page it is not suggested. If you want to render a field in node.tpl just write the following

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

```

or simply

```
<?php print $node->book['menu_name']; ?>

```
> 1 votes

# Answer
I think $content\['body'\]\['#object'\]-\>book\['menu\_name'\]; is what you're looking for. Here is an example using it to render the parent book menu.

```
<?php
$menuName = $content['body']['#object']->book['menu_name'];
print drupal_render(menu_tree($menuName));
?>

```
> 0 votes

---
Tags: 7, theming, debugging
---


# Question
Title: Create a custom filter in Views related to a custom table
I have a table where I keep some logs, for example, when a user visits a node, I record of the form:

```
The user 34 visited node 235.

```

Then I have a Views what show me the following fields:

* NID
* Title
* Body

How to display only the nodes that the current user has visited or not?

EDIT:

Example of my custom table:

```
------------------------------------------------------
| UID | action                        | IP           |
------------------------------------------------------
| 34  | The user 34 visited node 235. | 200.54.21.24 |
------------------------------------------------------

```

UID = User ID

# Answer
> 1 votes
I would do the following to achieve this. In the custom table where you maintain log create a view handler using hook\_views\_data. Add the following code in your .module file

```
     function MODULENAME_views_api() {
       return array(
           'api' => '3.0-alpha1',
           'path' => drupal_get_path('module','MODULENAME'). '/views',
       );
    }

Then add a file with the name MODULENAME.views.inc in your module views folder and the following code.

    /**
 * Implements hook_views_data()
 *
 */
function MODULENAME_views_data() {

 $table = array(
    'custom-table-name' => array(  //  Custom table
       'table' => array(
          'group' => 'Custom Tables',      // Groupname
             'base' => array(
               'field' => 'id',  //Primary key
               'title' => '<your table name>',
            )
        ),
     //Description of id
        'id' => array(
           'title' => t(' Id'),
           'help' => t(' Id field'),
           // is mydons_custom_id field sortable TRUE
           'field' => array(
              'click sortable' => TRUE,
            ),
      //Filter handler for filtering records by mydons_custom_id
           'filter' => array(
               'handler' => 'views_handler_filter_numeric'
            ),

           'sort' => array(
              'handler' => 'views_handler_sort'
           )
         ),

         'user_id' => array(
           'title' => t('User ID'),
           'help' => t('User ID referring to User for users table'),
           'field' => array(
              'click sortable' => TRUE,
           ),
           'filter' => array(
              'handler' => 'views_handler_filter_string'
           ),

           'sort' => array(
              'handler' => 'views_handler_sort'
           ),
           'relationship' => array(
            'base' => 'users', // The name of the table to join with.
            'base field' => 'uid', // The name of the field on the joined table.
            'relationship field' => 'user_id',
            // 'field' => 'nid' -- see hook_views_data_alter(); not needed here.
            'handler' => 'views_handler_relationship',
            'label' => t('User'),
            'title' => t('Referenced USER entity'),
            'help' => t('Add USER Fields'),
          ),

        ),

         'node_id' => array(
           'title' => t('Node ID'),
           'help' => t('Node ID referring to Node'),
           'field' => array(
              'click sortable' => TRUE,
           ),
           'filter' => array(
              'handler' => 'views_handler_filter_string'
           ),

           'sort' => array(
              'handler' => 'views_handler_sort'
           ),
           'relationship' => array(
            'base' => 'node', // The name of the table to join with.
            'base field' => 'nid', // The name of the field on the joined table.
            'relationship field' => 'node_id',
            // 'field' => 'nid' -- see hook_views_data_alter(); not needed here.
            'handler' => 'views_handler_relationship',
            'label' => t('User'),
            'title' => t('Referenced USER entity'),
            'help' => t('Add USER Fields'),
          ),

        ),

      )
    );
    return $table;
}

```

Clear the cache and go to views page and create another view of your custom table. Add relationship to your node and users and contextual filters to show logged in users node.

---
Tags: 7, views
---


title: Form Loading Itself

text:
# Question
Title: Form Loading Itself
I want to load a form with values from a DB using a date so that the user can edit the data later - however, it doesn't input the data into the fields beyond the initial load. I've created a very basic code to demonstrate my problem: I just think I'm not understanding the appropriate solution to this issue.

```
  public function buildForm(array $form, FormStateInterface $form_state) {
    if ($form_state->hasValue('date')) {
      $date = $form_state->get('date');
      $result = 'Date Set';
    } else {
      $form_state->setValue('date', REQUEST_TIME);
      $result = 'Date Not Set';
    }

    $form['ajax_wrapper'] = [
      '#type' => 'container',
      '#attributes' => [
        'id' => 'ajax_wrapper',
      ],
    ];

    $form['ajax_wrapper']['date'] = [
      '#type' => 'date',
      '#title' => $this->t('Date'),
    ];

    $form['ajax_wrapper']['submit_button'] = [
      '#type' => 'submit',
      '#value' => 'Load',
      '#ajax' => [
        'callback' => [$this, 'ajaxFormCallback'],
      ],
    ];

    $form['ajax_wrapper']['result'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Result'),
      '#default_value' => $result,
    ];

    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    dd('submit');
    $form_state->setRebuild();
  }

  public function ajaxFormCallback(array &$form, FormStateInterface $form_state) {
    dd('callback');
    $response = new AjaxResponse();
    $response->addCommand(new HtmlCommand('#ajax_wrapper', $form));
    return $response;
  }

```

# Answer
> 0 votes
I'm pretty sure this is the wrong way to go about it, but I managed to get what I wanted to happen to happen. It turns out the values being displayed on the form aren't what is in $form\_state-\>getValue, but $form\_state-\>getUserInput. This will successfully load the value 'Date Set' into the result box when it is submitted.

```
if ($form_state->hasValue('date')) {
  $user_input = $form_state->getUserInput();
  $userInput['result'] = 'Date Set';
  $form_state->setUserInput();
} else {
  $form_state->setValue('date', REQUEST_TIME);
  $result = 'Date Not Set';
}

```

# Answer
> 1 votes
When you are working with ajax you have to store everything that has to be preserved in the $form\_state's storage.

So in your example it would be:

```
  public function buildForm(array $form, FormStateInterface $form_state) {
    $date = REQUEST_TIME;
    if ($form_state->has('date')) {
      $date = $form_state->get('date');
    } else {
      $form_state->set('date', $date);
    }

    // ...

    $form['ajax_wrapper']['date'] = [
      '#type' => 'date',
      '#title' => $this->t('Date'),
      '#default_value' => $date
    ];

    // ...

    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $date = $form_state->getValue('date');
    $form_state->set('date', $date);
    $form_state->setRebuild();
  }

```

---
Tags: forms, 8
---


# Question
Title: Creating a view of child groups in Organic Groups
How do you create a View showing all the child groups of a group in Organic Groups?

I've started off with the 'OG Extras Groups' view, which shows all groups. I thought it'd be simple to then just add a filter for 'Content: Parent group', and that would show the children of a selected group. It returns no results, though.

I've tried all sorts of relationships but can't get the child groups to show. This thread is the only information I've found: https://www.drupal.org/node/159988. The explanation is for D6, though, and I can't see an easy translation to D7.

I've only got five groups so I don't need to set a contextual filter - I can hard code the parent group value (either name or ID).

# Answer
Answering my own question: it *was* as simple as adding the 'Content: Parent group' filter. For some reason I'd added a relationship I didn't need, which I was using on the filter. In fact you don't need any relationships at all. You can delete the 'OG membership: OG membership from Node' relationship from the default 'OG Extras Groups' view.
> 1 votes

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


# Question
Title: How to force a specific user in the Author textfield in Rules Create Entity
I created a rule which creates an entity. I would like that every created entity has a specific author.

for the moment, it's look like I can only put the currently logged-in user in that textfield.

# Answer
> 1 votes
You will have to fetch a user entity first. There's an action called fetch entity by id, which will allow you to select user as type and specify the user id.

At the bottom you can assign label and machine name for the variable that will be made available.

make sure to do the fetching before creating the new entity, else this variable won't be available.

---
Tags: 7, rules
---


# Question
Title: How to delete Ghost Menu Link in Main Menu?
I added a menu link in main menu: `user/%/notifications/subscription`. The menu is never visible except that when a user goes to his subscription page via 'My Account'. The menu link is not available when I try to edit the main menu links. It is not there. This problem surfaced up after I installed Menu Token module. However, I committed the sin before installing the Menu Token\] module. I have uninstalled this module.

Additionally, user gets the following error when visiting `user/%/notifications/subscription`.

> "Notice: Undefined index: localized\_options in menu\_navigation\_links() (line 1858 of /home/carrotjo/public\_html/includes/menu.inc)."

After some search on the Internet, I commented out `$l = $item['link']['localized_options'];` (line 1857 in menu.inc). The error is gone. But the ghost appears in the main menu link.

# Answer
> 1 votes
I think the easiest way is to manually delete this item from the table `menu_links` search for value `user/%/notifications/subscription` in `link_path` column. Delete that row and clear your cache.

---
Tags: routes
---


title: How to prevent caching of a page?

text:
# Question
Title: How to prevent caching of a page?
I've set a custom homepage url at example.com/welcome. The user comes to the example.com/ and logs in on that page. Drupal redirects to example.com/welcome

Now the user clicks on the home page which loads example.com/ from browser cache (which has the login form on it).

I guess if Drupal would reload the homepage at example.com/ instead of example.com/welcome I wouldn't have that problem. How would I do that?

What else could I be doing?

Btw, anonymous pages are getting cached by varnish.

# Answer
First step is to see if http://drupal.org/project/cacheexclude does it for you. If your on Drupal 6 check out this issue: http://drupal.org/node/197786#comment-1817644. If your on Drupal 7 see this one: http://groups.drupal.org/node/212103

If none of the above do it for you, you might want to look at modifying your VCL and add in more logic to make it work with your site.

Also take a look at something like http://drupal.org/project/globalredirect in order to make sure you have one URL for a resource (like the front page).
> 10 votes

# Answer
`drupal_page_is_cacheable` can also be used.

Calling:

```
drupal_page_is_cacheable(FALSE);

```

Should do the trick.

And for Drupal 8:

```
Drupal::service('page_cache_kill_switch')->trigger();

```
> 12 votes

---
Tags: 7, caching
---


# Question
Title: how to set Default time zone and date format
I have user registration page in that I could see Time Zone as in screen shot attached now problem is I want to make it as default time zone for all users as well Need to use same date format throughout drupal7 i,e in content type **views** also, can anyone tell me how to achieve this?

# Answer
> 3 votes
You can set default timezone and whether user should be able to edit default timezone settings or not.

Go to **Regional and language settings**:

http://yousite.com/admin/config/regional/settings

And ***uncheck* : *Users may set their own time zone.***

On same page other settings also available. See :

To add any new format you can add from here :

http://yousite.com/admin/config/regional/date-time

---
Tags: users
---


# Question
Title: How Specify the class name of our columns in Responsive Grid View?
I'm trying to build a responsive Views grid using views responsive grid module. But added fields in the view is not visible.

I'm confused in adding grid class.Please anybody guide me to set class name, so that fields can be seen in the grid?I have attached screenshot of my settings below.

# Answer
> 0 votes
For Wrapper do not use `<div>` you need to use a name. Ex: magazine\_grid\_wrapper

---
Tags: 7, views, theming
---


title: How to hide roles in user edit page?

text:
# Question
Title: How to hide roles in user edit page?
I have a user registration page where in being a admin i have assigned particular to user.

But now when a users edits his/her own profile, all the available roles are showing up and in fact users can assign roles by themselves and save that. Such users can even edit as admin.

This is obviously not correct, so what should I do to correct that?

# Answer
In `/admin/people/permissions/roles` Add a new role, Ex call it Admin2

Then assing that user the Admin2 role

In `/admin/people/permissions` for the Admin2 Column.

Under User:

* Administer permissions
* Administer users

Make sure both of these are unchecked.

For all the other permissions, basically you check mark all the stuff you would like to allow Admin2 to do and leave uncheck all permissions you don't want him to have.
> 0 votes

---
Tags: users
---


# Question
Title: How to avoid CKeditor to change the HTML code?
I want to add code like `<a><div></div></a>` to make the whole block as a link, but after saving it getting changed to `<div><a></a></div>`. I am using CKeditor module, have done changes in config/text-format/filter HTML to disable the Limit allowed HTML tag. In short I want that editor do not do anything with HTML code.

# Answer
I know that this is not the answer to your problem (which is annoying) but personally I would **avoid putting a `<div>` inside a `<a>` tag**. It is normally not allowed to put a "block" type of tag inside an "inline" type of tag.

So you could do the following:

```
<a class="block"><span>Your stuff</span></a>

```

and then add a CSS rule:

```
a.block,
a.block > span {
  display: block;
}

```

This way you are HTML valid and CKEditor should not try to correct it.
> 2 votes

# Answer
go to:

/admin/config/content/ckeditor/edit/Advanced (for Filter HTML)

/admin/config/content/ckeditor/edit/Full (for Full HTML)

Then under Advanced Content Filter, select disabled.

**If the above does not do it**, depending on which one you are using (filter or full html) You need to go to

/admin/config/content/formats/filtered\_html

OR

/admin/config/content/formats/full\_html

### **Uncheck the correct faulty and chopped off html box.**
> 1 votes

---
Tags: wysiwyg
---


title: colorbox on a external link

text:
# Question
Title: colorbox on a external link
I have create a little fotogallery where I display only the first 3 images, the first "big" on the left side and the other two (small, width / 2 of the big one) on the right side. All images are "linked" to colorbox. If I click on one of these 3 images colorbox "run" (ok, perfect).

Via a div in a absolute position style I have added this phrase "See all NUMBER images". Now I need to link this "phrase" to the event that run colorbox from the first image (the big).

How can i do this ?

# Answer
This can be achieved with jQuery `.trigger()` event.

```
jQuery('#id-of-your-phrase').click(function (e) {
 e.preventDefault();
 jQuery('#id-or-class-of-first-image-YouCanAlsoUse-first-child').trigger('click');
});

```

This code will open the colorbox from First Image (the Big).
> 2 votes

---
Tags: entities, media, javascript
---


# Question
Title: Putting additional functionality for Commerce Files/License
I am making a files selling website with Drupal 7.41. Using the **Commerce Files / Commerce License Modules**, I have been able to setup the after payment completes, allow file download functionality.

However the files that becomes available to download is just the raw file. I want the file, which becomes available for download to be a zip/tar file which consists the

1. File sold
2. A simple readme.txt
3. A pdf file consisting license information, made for that particular user transaction. Like Envato!

Is this automation possible? Can anybody please guide me on how I may be able to achieve this? Even pointing out the path would be helpful!

# Answer
Here's what you need to get started.

You'll need to create a new license type and extend the `CommerceLicenseBase` class (or the file class). When your license class (whose parent class is `CommerceLicenseBase`) gets activated, the `->activate()` method ends up calling `->save()`. Your new class will implement `->save()` and within that function you can:

1. Generate a PDF.
2. Generate or load a README.txt.
3. Create a Zip file.
4. Store that file and attach it to some entity, email it, etc.
> 1 votes

---
Tags: commerce
---


title: Language selector Drupal 8

text:
# Question
Title: Language selector Drupal 8
I can't seem to get a Language Selector to appear on my page.html.twig (or in a block). I must be doing something wrong, I can perfectly translate my content by I can't switch language (unless I change the URL myself).

# Answer
This guide shows how to create a multi-lingual content.

https://www.ostraining.com/blog/drupal/d8-multi-lingual/

If not success please post some code you're trying to do. Remember to clear the cache.
> 2 votes

---
Tags: 8, i18n-l10n
---


title: How to import massively taxonomy terms?

text:
# Question
Title: How to import massively taxonomy terms?
I have taxonomy terms installed and there I have article categories listed.

I have a lot of categories and articles. Now I need to import more categories from .txt file.

What is the best way to do this? I don't want to create these categories one by one.

# Answer
> 2 votes
I use in every of my projects the Taxonomy Manager module, among its features you can find:

* mass adding of new terms
* dynamic treeview
* mass deleting
* moving of terms in hierarchies

---
Tags: taxonomy-terms, importing-exporting
---


title: Your current logout threshold text box

text:
# Question
Title: Your current logout threshold text box
I have added the Automated Logout module, now its working fine but in user edit page "Your current logout threshold text box" is showing up what is it. How to remove this please help me?

# Answer
> 2 votes
Go to `YOUR_SITE/admin/people/permissions`and under the ***Automated Logout*** section uncheck the ***Change own logout threshold*** option for ***authenticated user***.

---
Tags: users
---


# Question
Title: How to create a user with field collections programmatically?
This is what I use to create the user:

```
    $new_user = array(
        'name' => $form_state['values']['email'],
        'status' => 1,
        'access' => REQUEST_TIME,
        'roles' => array(),
    );

   user_save('', $new_user);

```

Now I want to add values to the field collection items. I have a field collection called `field_personal_details` and a field collection item called `field_firstname`, but I have no idea how to access it. Can someone help me get started?

# Answer
> 2 votes
I think following code should give you an idea.

```
    //Create a field collection entity
    $field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_personal_details'));
    $field_collection_item->field_firstname[LANGUAGE_NONE][0]['value'] = "Yassin Tahtah";
    //$field_collection_item->field_firstname['und'][0]['value'] = "Yassin Tahtah";
    $field_collection_item->setHostEntity('user', $user);
    // Save the entity.
    $field_collection_item->save(TRUE);

```

# Answer
> 2 votes
You can see this example:

```
$new_user = array(
    'name' => $form_state['values']['email'],
    'status' => 1,
    'access' => REQUEST_TIME,
    'roles' => array(),
);

 //making the field collection
 $values = array();
 $values['field_name'] = 'field_personal_details';
 $values['field_firstname'][LANGUAGE_NONE][0]['value'] = 'Yassin';

 //saving the collection
 $entity = entity_create('field_collection_item', $values);
 $entity->setHostEntity('user', $user);
 $entity->save();

 //saving the user
 user_save('', $new_user);

```

---
Tags: 7, users, entities
---


# Question
Title: theme_hook_suggestions for string wildcard
I need to create a copy of page.tpl.php using page--fixed\_arg\_0\__variable\_string\_arg\_1\__fixed\_arg\_2.tpl.php as pattern. For example, if the URL is http://example.com/models/model-title/special-offers, *model-title* is the variable. I only want one template file instead of 10 or more.

Any suggestions?

# Answer
> 1 votes
What you'd need to do use the theme suggestions. So you'd have 1 template file e.g. page--fixed.tpl.php

Then in template.php you could have an if statement e.g.:

```
function THEME_preprocess_page(&$variables) {
 $arg1 = arg(1);
 $arg0 = arg(0);
 if($arg0 == 'models' && ($arg1 = 'model-names' || $arg1 = 'anothermodel')){
  $variables['theme_hook_suggestions'][] = 'page__fixed';
 }
}

```

---
Tags: theming
---


# Question
Title: Drupal-to-Drupal data migration Taxonomy issues
I'm wondering if there is something special I need to do within the UI when using Drupal-to-Drupal data migration to actually get taxonomy terms to port over with all my nodes. I get an error that reads

> No matching taxonomy term found for source value '144' in vocabulary Topics.

I've created first level terms and ported over each term correctly, but what is the special thing I need to do to actually map the terms with the nodes? I've mapped the TID and yet it still doesn't work. Is there something special Im missing?

# Answer
> 1 votes
Well, this is a couple years' old now, but thank you doodirock for tickling my memory on this. You need to configure that field's source\_type value to 'tid'. I'm doing so in code, but I believe that you can set this in the UI. The code you need is this:

```
$this->addFieldMapping('field_news_categories:source_type')
  ->defaultValue('tid');

```

In my UI view, this row appears like this:

Where 'tid' is the value input.

As the documentation points out:

> **source\_type:** If the option value is 'tid', then the incoming value is assumed to be a valid term ID in the destination Drupal instance. Otherwise, it is assumed to be a term name (the default behavior). Note that you'll want to set this to 'tid' if the mapping has a source migration (the sourceMigration() method is used on the mapping).

---
Tags: taxonomy-terms, migrations
---


title: Trying to print a form with a shortcode

text:
# Question
Title: Trying to print a form with a shortcode
I'm currently working on a drupal module and I want to print a specific form called by a shortcode. So I've use this tuto and here is my code :

Info :

```
    function custom_shortcodes_shortcode_info() {
      $shortcodes['form'] = array(
        'title' => t('Link form'),
        'description' => t('A simple form.'),
        'process callback' => 'custom_shortcodes_shortcode_form',
      );
      return $shortcodes;
    }

```

Callback:

```
    function custom_shortcodes_shortcode_form($attrs, $text) {
      $attrs = drupal_get_form('custom_shortcodes_shortcode_form_attributes');
      return $attrs;
    }

```

Form :

```
    function custom_shortcodes_shortcode_form_attributes() {
      $form = array();
      $form['PrjLogement'] = array(
        '#type' => 'textfield',
        '#title' => t('Field1'),
        '#required' => TRUE
      );

      $form['MenageRevenuM'] = array(
        '#type' => 'textfield',
        '#title' => t('Field2'),
        '#required' => TRUE
      );

      $form['MenageApport'] = array(
        '#type' => 'textfield',
        '#title' => t('Field3'),
        '#required' => TRUE
      );

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

      return $form;
    }

```

Now the thing is that every time I'm calling the form with the specific shortcode the output is just "Array". Is there any way to print this form ? Thanks in advance for your help.

# Answer
Basically, drupal\_get\_form doesn't render the array - it just returns the renderable array from the form function. You need to render it yourself.

Try this:

```
function custom_shortcodes_shortcode_form($attrs, $text) {
  $form = drupal_get_form('custom_shortcodes_shortcode_form_attributes');
  $attrs = drupal_render($form);
  return $attrs;
}

```
> 0 votes

---
Tags: 7, forms
---


title: How to add tab page in views?

text:
# Question
Title: How to add tab page in views?
I am using Drupal 8.0.0. I try to add a custom tab page (view page, using views) to my custom content type.

I searched a lot, most sources related to D7 and their instructions not work in D8. It took me a few hours to test tab but tabs not appear in D8.

I also followed the instructions at How to create views tabs in D8? but that didn't work.

By the way, I can get tab by following instruction of https://www.drupal.org/node/2116767, but my question is:how to add tag page (or tab menu) in D8 Views (core version 8.0.0 and above), not by custom module.

Any suggestions?

# Answer
Ahmad's answer to my question that you reference, works just fine for me in a simplytest sandbox with D8.0.1.

You now have to give titles to the tabs, but they can be anything you like.

I suggest you check again in a clean simplytest sandbox. And remember to save the view - that's the easiest part to overlook.
> 0 votes

---
Tags: views, 8
---


title: Webform submit button does not work

text:
# Question
Title: Webform submit button does not work
I have created a webform block. After I enter all the info in the webform, I clicked the Submit button. Nothing happens. Do you know why the Submmit button is not working?

This webform block's submit button works: http://godrupal.info/?q=contact-us

Actual webform node's submit button works : http://godrupal.info/?q=node/16. Then I created block of the node/16 but then this webform blocks's submit button does not work: http://godrupal.info/?q=plan-an-event

# Answer
> 1 votes
if you look into your console log you will see the following errors

this happens when you hide a required field.

I had a look at your markup and found that you have the above 4 fields display set as none; and at the same time also has attribute required.

So remove the required attribute or apply novalidate on submitting form.

---
Tags: webforms
---


# Question
Title: "$.fieldValue is not a function" alert on login form submit
In Drupal 7, with Devel, CTools and Ajax Login/Register plugins, I get an alert on submitting the login form on http://p262957.mittwaldserver.info/drupal/user/login.

I am using a custom child theme based on bootstrap project. I already tried the instructions on https://www.drupal.org/node/1008664 that says I should be sure to load jquery.form.js before ajax.js.

Does anybody have an idea?

# Answer
In the parent theme was a ajax.js override function that caused the error. It can be found in theme\_root\_dir/js/misc/. You just have to empty it. Don't forget to empty your cache afterwards. Now it should work.
> 1 votes

---
Tags: 7, javascript, users
---