title: Tax rate on shipping price

text:
# Question
Title: Tax rate on shipping price
Drupal commerce shipping module. I want to set a tax rate on a shipping price so that the shipping price with its tax component is integrated in the subtotal of the line items. Guess it has to be done with rules but I don't know where to start. Any help is very welcome!

# Answer
> 2 votes
I guess that, as the creator and maintainer of the Drupal commerce shipping, I should bid in.

The short answer is that right now, this is actually possible without creating the functionality yourself from scratch. The issue was raised in the Drupal commerce shipping queue (by yourself?). Anyways as stated there, this is something that should be handled by commerce core, which right now is lacking a way to apply taxes to line items which aren't the product line items.

I have a chat with Ryan about the problem, where we agreed that the product line item is a special case, since a lot of price handling is tied to the product, where all other line items, shouldn't have a relationship like that. The issue has been raised on the Drupal commerce issue queue, which I believe you are aware of.

If you don't have the ability to create the code for this yourself, your best bet is to wait for some one to fix it, or buy it.

**Update:**
This is now built in the Commerce shipping module, by exposing an event in rules that can be used to add taxes on shipping line items.

# Answer
> 1 votes
I have really struggled to get this to work. And since it took me several days, I'm sharing!

I needed to apply NC Sales tax to a Flat Rate Shipping Cost. I did the following:

1) Create NC Sales Tax Rate Condition: Order address component comparison (Shipping state is NC) and Condition: Not line item contains specific product type: Giftcard (no tax on gift cards)

Actions: Apply a tax rate to a line item (commerce-line-item)

2) Create New Shipping Tax Type called "Shipping Tax". Event: Calculating the sell price of a product

Elements: NONE

3) Create NC Shipping Sales Tax Rate called "Shipping Sales Tax" Condition: Order address comparison (Shipping state is NC)

Actions: Apply a tax rate to a line item (commerce-line-item)

4) Create New Shipping Calculation Rule called "Calculate NC Sales Tax" Event: Calculating a shipping rate

Actions: rule: Calculate Shipping Sales Tax (commerce-line-item)

Subtotal $36.00 NC Sales Tax $1.71 Shipping Sales Tax $0.48 Flat Rate Shipping $10.00 Order total $48.19

Now to just get the Shipping Sales Tax to fall below the Flat Rate Shipping line. :-)

Thanks!

---
Tags: commerce
---


# Question
Title: Find how many times keyword is repeated in all nodes
I have nodes for business listings which have title , body and other contact fields of the business. I want to do a research on all my content "10000 nodes" and find the most repeated words in the title and body fields of each node, so I can tag the content using the keywords found.

Any ideas ?

# Answer
> 2 votes
You can do something like this.

I wrote this code from the top of my head and haven't tested it so I'm not sure if it works. There also might be some errors in it so you probably need to do some debugging.

```
// Get the body and title of all nodes.
$query = db_select('node', 'n');
$query->join('field_data_body', 'body', 'body.entity_type = "node" and body.entity_id = n.nid');
$query->fields('n', array('nid', 'title'));
$query->fields('body', array('body_value'));

$result = $query->execute();

$blacklist = array('the', 'a');

while ($record = $result->fetchAssoc()) {
  // Put the words in an array.
  $title_words = explode(' ', strtolower($record->title));
  // Count the same words.
  $title_word_count = array_count_values($title_words);
  // Sort the array.
  asort($title_word_count);

  /* Do the same for $record->body_values and merge this array with $title_word_count. */

  // Filter blacklist elements.
  foreach ($blacklist as $blacklist_word) {
    if (isset($word_count[$blacklist_word])) {
      unset($word_count[$blacklist_word]);
    }
  }

  if (!empty($word_count)) {
    // The last element of the array contains the most frequent word.
    $word = array_pop($title_word_count);

    /* Here you can insert this word as a taxonomy term and add it to the node. */
  }
}

```

Hope it helps. Good luck!

# Answer
> 0 votes
It sounds like you want Solr installed which provides such thing out of box.

1. Install and configure Search API Solr Search \+ Apache Solr.
2. Create Solr server and indexes, so all nodes are indexed.

Now Solr server can give you such information, as you can either log-in to your Solr web interface and execute specific query to fetch the statistics or use Luce (Lucene Index Browser) which allows to show you such statistics.

---

Alternatively you can use SQL or shell command.

For example:

```
drush sqlq "SELECT title, COALESCE(r.body_value, '') FROM node n LEFT JOIN field_data_body r ON n.nid = r.entity_id AND n.vid = r.revision_id" | sed -e 's/<[^>]*>//g' | grep -o "\w\+" | sort | uniq -c | sort -r | head -n20

```

will print top 20 most used words from all the nodes. For specific nodes or type, use `WHERE` to narrow down the results.

---
Tags: 7
---


# Question
Title: What is the difference between t() and l()?
If I understand correctly, `t()` is the Drupal translations function, is `l()` simply calling the localization settings for translation specifics, or is there something more to it then that?

# Answer
The l() function is primarily for links. It takes the parameters of `$text, $path, array $options = array()` to properly translate links. It also returns a HTML string containing a link to the given path.

It's use looks something like this:

```
<?php
  l(t('Link text'), 'about-us', array('attributes' => array('class' => array('about-link'))));
?>

```

Another note is it looks as though it's going away in D8, as it currently has no entry in the APIs for 8. Instead, Drupal 8 will use the class:link like so:

```
$link = Link::fromTextAndUrl($text, $url);

```

t() is much more general and is used to translate strings. It also takes a different set of arguments (`$string, array $args = array(), array $options = array()`).
> 2 votes

# Answer
function l correctly handles aliased paths and adds an 'active' class attribute to links that point to the current page (for theming), so all internal links output by modules should be generated by this function if possible.

However, for links enclosed in translatable text you should use t() and embed the HTML anchor tag directly in the translated string. For example:

```
t('Visit the <a href="@url">settings</a> page', array('@url' => url('admin')));

```

This keeps the context of the link title ('settings' in the example) for translators.

To make strings used in Drupal translatable. Every string in a t() function can be translated through the Drupal UI. That way people who use a Drupal site in a different language can adapt it to their needs.

2-why can't i use a variable in it ?

You can, but you have to do it through a placeholder like one of these:

```
<?php
$text = t("This is !name's website", array('!name' => $username));
$text = t("This is @name's website", array('@name' => $username));
$text = t("This is %name's website", array('%name' => $username));
?>

```
> 1 votes

---
Tags: i18n-l10n
---


# Question
Title: How to change the output field date in a view?
I want to alter a field 'Date' in the view to display only year using '`hook_views_query_alter`', so that I can display only Year in the date field.

I'm trying below code, which is not working. Can anybody help me?

I'm not sure about assigning new value to the field in the code.

```
function alb_jobs_views_query_alter(&$view, &$query) {

  if ($view->name == 'test-archive') {
  $query->where[0]['conditions'][0] == array('field'=>"field_data_field_issuu_date.field_issuu_date_value","value"=>'%YEAR(STR_TO_DATE(field_data_field_issuu_date.field_issuu_date_value,"%Y"))%',"operator"=>"LIKE");

  }
}

```

Here is my date field screenprint:

# Answer
If you are asking for the how to get year from date and use the year in view query alter then

You can use strtotime();

```
$year = date('Y', strtotime($field_data_field_issuu_date.field_issuu_date_value));

```

Another way in view you can use ***custom date format*** on display and show only year and use that value.(Depends on requirement)
> 2 votes

---
Tags: views
---


# Question
Title: Hook form alter not firing on a custom form that does exist
I have a hook form alter function that is not recognizing or firing on a form that clearly does exist on the page. And i’ve tested this function against the Drupal built in form with the id of ‘search\_block\_form’. In my template.php file i have this code.

```
function mytheme_form_alter(&$form, &$form_state, $form_id){
if($form_id == 'search_block_form'){

    echo '<script>alert("whatup?");</script>'; /* for testing purposes */
    drupal_add_library('system', 'ui.accordion');

    $form['search_block_form']['#attributes']['placeholder'] = t('enter burp search terms...');
    }

if($form_id == 'views-exposed-form-browse-albums-page') {
    echo '<script>alert("whatup beeatch?");</script>'; /* for testing purposes */
    drupal_add_library('system', 'ui.accordion');
}

```

}

As a test first IF statement alters the default Drupal search whose id is ‘search\_block\_form’. This part does run and is working.

The second IF statement tests for my custom views form but does not run at all. The form does clearly exist (see attached). I’m stumped at this point and don’t know what to do next. Why is the second IF statement not running?

# Answer
> 2 votes
Before Drupal 8, the form ID is also the name of the PHP function that builds the form itself (or an ID contained in the array Drupal gets from a `hook_forms()` implementation).
As such, it can only contains those characters a PHP function name can contain. Underscores are allowed, but not so dashes; dashes are used in HTML. The correct form ID is the one with underscores.

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


# Question
Title: How do I choose a default theme if the theme gives a white screen?
I tried to make a folder templates for all tpl files but after that now I can not load my theme anymore on Xamp? Now when I try to load theme in drupal there was only white screen.What can I do?

I am tired of that so if you just make one mistake in Drupal, you are need to install again and again.

I choose a different theme and I close the browser, but the theme is not working. How can I load a different theme if I don't have access anymore to Drupal?

# Answer
You can update in database.

Change the active theme in the database

The default theme setting is stored in Drupal's database, and thus can be changed by manipulating the database from the command line or an administration overlay or client like PHPMyAdmin or MySQL Workbench for MySQL.

Always make a backup of your database before changing values in it directly, as it is possible to destroy data and render your site unrecoverable at the database level. You have been warned.

In Drupal 6 and 7, the setting is stored in the system table:

# activate a trusted theme

```
UPDATE system SET status=1 WHERE name = 'garland';

```

# change the default setting

```
UPDATE variable SET value='s:7:"garland"' WHERE name = 'theme_default';

```

# clear the cache tables

```
TRUNCATE cache;
TRUNCATE cache_bootstrap;
TRUNCATE cache_block;

```

Another way

```
sites/default/settings.php:
$conf['theme_default'] = 'bartik';

```
> 1 votes

---
Tags: 7
---


# Question
Title: Why is my Views row template not loaded?
I am using Views 3.

I have created my view and get these theme suggestions:

As you can see I created a `--presse-page.tpl.php` file bold marked in the second block. It works fine, but I need to style only the rows. So I created a `views-view-fields--presse.tpl.php` file, but if I rescan the theme, it does not appear.

Why not?

# Answer
> 1 votes
Your file should be called **views-view-field--presse.tpl.php**. field without an 's' not views-view-fields--presse.tpl.php file

# Answer
> 1 votes
check which theme you selected and make sure that same theme is affecting the page.

And check filename present in the theme info and tempate filename are same also clear cache then rescan it. May be it helps.

# Answer
> 0 votes
You have to clear the cache when changing any template file

---
Tags: 7, views
---


# Question
Title: Hide "Your name" field in comment form from everyone except admin
What I want to achieve is to hide the "Your name" field in *comment form* from all anonymous and authenticated users but visible to users with the admin role.

I was able to use CSS to hide the field, but it also hides from admin.

Please is there a way to selectively hide the field to anonymous and authenticated users but not to administrators?

# Answer
> 6 votes
```
function YOURMODULE_form_comment_form_alter(&$form, &$form_state) {
  global $user;

  if ($user->uid != 1) {
    unset($form['author']['name']);
  }

}

```

Another way is, if your theme has a comment.tpl.php file, putting a condition to restrict authenticated and anonymous user.

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

```

To limit this to a particular content type, you can create a separate comment template file for that content type.

# Answer
> 4 votes
If you have more than one users having *administrator* role then you may use this snippet. Place this piece of code at the bottom of `template.php` of your current theme.

Note: Replace *YOUR\_THEMENAME* with the name of your current theme and *YOUR\_FORM\_ID\_HERE* with *id* of your form.

```
function YOUR_THEMENAME_form_alter(&$form, &$form_state, $form_id) {
    switch($form_id){
    case 'YOUR_FORM_ID_HERE':
      global $user;
      if (!in_array('administrator', $user->roles)) {
          unset($form['author']['name']);
      }

    break;
  }
}

```

---
Tags: comments
---


# Question
Title: How to programmatically add a link to an image field in a view
I have a view with an image field and other fields, and I need to link the rendered image, not the content which is one of the configuration choice, but on another computed filtered view. I think that I should use `my_theme_preprocess_views_view_field_myviewname` to catch this field, using it's name as selector then wrap it with the computed link, but didn't find how to do it.

To clarify my question, the image in this view is normally displayed, and I "dynamically" create a link to another view which is not related to the image. I wrote a function (in my template) to compute this link, and I need to know how to add this link to the image field within `my_theme_preprocess_views_view_field_myviewname(&vars)`. The preprocess function is executed several times to build the view, I tried to use var\_dump(vars) to see where is the image field, but it generates a too huge amount of data.

# Answer
> 0 votes
As per your question, I assume that you want the image link to open the image in existing/new tab. For this you can add a relationship of 'File Usage : File'.Post that you get the file path field in the fields section of the view. Add that file path field and in the rewrite result section or in template file you can create tag with the required image. PS: In field image setting select noting in link image to setting.

# Answer
> 0 votes
After some more search/tests and your help here is the solution I used to do it. In my theme template.php I added

```
function MyTHEME_preprocess_views_view_field__VIEWNAME__page(&$vars) {
  $view = $vars['view'];
  $field = $vars['field'];

  // field is an object of type views_handler_field_node

  if ((isset($field)) && ($field->field == 'my_image_field_name' )) {

     // create a string like <a href="" >
     $myLink = myFunctionToBuildLink($view);

     $vars['output'] = $myLink . $vars['output'] . '</a>';
  }
}

```

Now I have the right link to the specific view and page I wanted. The "\__page" at the end of the function name is because I use a view with display page.

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


# Question
Title: Share Unpublished nodes through a link that needs a user authentication
I am trying to share unpublished node through its URL to a specific role.

What I am trying is that when that user (with the specific role) opens that link, he'd have to login to open the URL.

Is it possible?

Thanks

# Answer
You could do something like:

http://example.com/user/login?destination=node/123

That would take them to the login screen and after logging in they would be taken to node 123
> 1 votes

# Answer
Access unpublished

> Easy to use module grants access to view unpublished content to anyone who has a unique URL and appropriate permissions. Visitor can be anonymous or authenticated user with the user role.
>
> When administrator or users with enabled privileges visit (or save) unpublished node, can see link for direct view that unpublished content. Unique URL link is displayed as Drupal message or in node content.
>
> Administrator can enable view an unpublished node for any roles with "View unpublished contents" permission. If it is set for anonymous users, anyone who know the link with hash key, can view the unpublished node. View only, not edit.
>
> Default URL parameter is "hash" and can be changed on configuration page for more security or customization.
>
> Module is useful for proofreaders, content checkers etc. Webmaster does not need to create user accounts and can keep the website safer. Each node has its own unique hash key (like Google Docs).
> 4 votes

# Answer
You may want to use the view\_unpublished module. Some more details about it, from its project page:

> This module allows you to grant access for **specific** user roles to view unpublished nodes of a **specific** type. Access control is quite granular in this regard.
> 3 votes

---
Tags: users
---


# Question
Title: list on node page where node selected on different content types
I have a content type 'projects' and a content type 'staff'. So on the projects node I have two fields that list the 'staff' nodes, 'project manager' (one staff node) and 'other people' (multiple staff nodes). So what I want to do is on the 'staff' node when this is viewed on it's own to list the projects they are involved in. Is there a way in the template to grab any project link that this person might be involved in, be it leading it or just listed?

# Answer
I assume you are lining the nodes via Entity Reference.

In that case use Views to grab the staff node nid and show the related projects via a relationship. Add it to your staff page via a block, EVA, Display Suite, Panels or some other contrib module (there are a quite a few that can embed a View).

The exact module you choose depends on your requirements, such as what modules you already have installed, and what other features you would like from the module.

You can do it yourself in the template if you wish, but you will have to create an SQL query for that or use views\_embed\_view to embed the same view referred to above directly into the template as a variable via template\_preprocess\_node. The problem is that the list of staff is available on the project node but not the other way round. You can solve that by having a two-way reference, by using a module such as Corresponding Entity References, but to me that sounds too convoluted.
> 1 votes

---
Tags: nodes, entities
---


title: Drush not working

text:
# Question
Title: Drush not working
I am using Drush 7 version on my MAC with MAMP PRO. When I am using any command of Drush it shows me an error message :

> PHP Fatal error: Allowed memory size of 262144 bytes exhausted (tried to allocate 12288 bytes) in /Users/pankajsachdeva/drush/includes/preflight.inc on line 49

Can anybody help me to get out of it?

# Answer
Drush uses the CLI version of PHP, which has its own `php.ini` file. You should locate this `php.ini` file on your installation and increase the memory limit. It can be on different places depending on how you installed the PHP.

It is generally around the same folder with the regular `php.ini` file but has something with `cli`.

For example on my Linux machine, the regular `php.ini` file is located under

> /etc/php5/**apache2**/php.ini

And the **CLI-Version** is located under:

> /etc/php5/**cli**/php.ini
> 1 votes

---
Tags: drush
---


# Question
Title: How does forum determine new replies for each user?
When I visit `drupal.org/forum/*`, in `Replies` column I can see how many new posts have been added. Drupal also marks them with a `New` tag.

I'm wondering how does drupal determine which replies are new for me? Are they new since my last visit to the page, or my last logout from drupal.org? In case the later is correct, how does drupal know when I loggeout out last time?

I'm very interested to know what algorithm is behind this nice feature?

# Answer
Drupal has a `history` table to record when any user viewed any node.

So it knows when you last viewed the node, and which comments have newer timestamps. So it marks those comments with newer timestamps as `new` or `updated`.

**UPDATE:** There is also a constant `NODE_NEW_LIMIT` set in the `node.module` file which defaults to 30 days ago. That means nodes changed before 30 days are always marked as read.
> 2 votes

---
Tags: 7, nodes
---


title: Insert query for PostgreSQL

text:
# Question
Title: Insert query for PostgreSQL
In Drupal 7 with a developed custom module that insert data into a postgreSQL db, I use the following query :

```
$query = Database::getConnection('default', 'move')
  ->query("INSERT INTO clients (client_ref,client_lastname,client_firstname) VALUES('E11366235','DUPOND') RETURNING client_id")
  ->execute();

```

But the returned client\_id is always 1.

If I set `INSERT INTO clients (client_ref,client_lastname,client_firstname) VALUES('E11366235','DUPOND') RETURNING client_id` in pgAdmin 3, the returning id is correct.

**In both case data are inserted into database** but Drupal doesn't return the good id.

Any explanation ?

# Answer
> 1 votes
According to all messages there are two ways to solve the problem :

**1) db\_insert**

Using `db_insert()` to insert data and create a specific query for postgreSQL database to get the last id after insert :

```
// Default insert
(...)->insert("...");

// Call this query to get last id only for pgSQL
(...)->query("SELECT currval('sequence')")->fetchAll();

```

You juste need to replace sequence by the key provided in your postgreSQL database.

You have to call currval right after insert to stay in the same context.

**2) db\_query**

Rewriting the entire query with specific synthax for postgreSQL database to get the last id :

```
(...)->query("INSERT INTO {$table} ($fields) VALUES($value) RETURNING $id")->fetchField();

```

**Conclusion**

The first solution seems to be the best to avoid rewriting all `db_insert()` functions.

# Answer
> 0 votes
I'm guessing that function you're using is returning the number of rows affected.

You should use -\>insert for insert queries, or better yet use drupal's db\_insert function: https://api.drupal.org/api/drupal/includes!database!database.inc/function/db\_insert/7

As you can see it uses -\>insert and that will hopefully return what you need

# Answer
> 0 votes
Looks like `DatabaseConnection_pgsql::query()` has an option for that. Try:

```
$sql = "INSERT INTO clients (client_ref,client_lastname,client_firstname) VALUES('E11366235','DUPOND') RETURNING client_id";
$new_id = Database::getConnection('default', 'move')
  ->query($sql, array(), ['return' => Database::RETURN_INSERT_ID]);

```

---
Tags: 7, database
---


# Question
Title: Invalid response object from API: (HTTP response code was 0)
I am using Ubercart and stripe and enabled this module its working great for my dev version which is `HTTP` but when I use similar at live site having `HTTPS` I get below error.

Please suggest what I am doing wrong or what i need to resolve it, I tried searching it tried support but not able to find any solution.

Please suggest!

> Payment failed for order 32: Stripe Customer Creation Failed for order 32: Invalid response object from API: (HTTP response code was 0)

Thanks!

# Answer
> 0 votes
I downloaded the stripe api and ran all it's unit tests. That way I could find that curl was disabled. By enabling following functions in php, all unit tests succeeded and it got working:

```
shell_exec
proc_open
curl_exec

```

---
Tags: ubercart
---


title: accessing fields in a view template

text:
# Question
Title: accessing fields in a view template
I have a view that I want to create a view template for in my theme.

So, I have created: `views-view--homepage-suppliers.tpl.php`

I have then several content items of content type: `Supplier` that the view uses.

The have various fileds, such as `title`, `field_supplier_image`

How do i then access these fields in this view template?

Is it something along the lines of:

`$rows['field_supplier_image']`?

thanks

# Answer
It would appear your using a 'Display output' template when you probably want a 'Row style' output so you can access fields. You will need to change your tempate by going to 'advanced \> theme information', it will probably be something similar to 'views-view-fields--homepage-suppliers.tpl.php'.

You can then get a nid from the field and access a whole host of information through the node object.

```
  $nid = $row->{$view->field['field_supplier_image']->field_alias};
  $node = node_load($nid);

```

If you var\_dump() the $node variable you can see what you have to play with.
> 3 votes

# Answer
I ended up using this in a field template:

```
$row->field_field_link_text[0]["rendered"]["#markup"]

```
> 0 votes

# Answer
You can access fields through the $view-\>result object.

Here's an example I use to create a ical calendar:

(views-view--ical.tpl.php)

```
BEGIN:VCALENDAR
VERSION:2.0
METHOD:PUBLISH
<?php
define('CRLF',"\r\n");
global $base_url;
$ical_time_format='Ymd\THis\Z';

function ical_extract_value($field,$key='value'){
    return $field['und'][0][$key];
}

function ical_shorten_line($line){
    $line=str_replace(array("\r\n","\n"),'\n',$line);
    return trim(chunk_split($line,76,"\r\n "));
}

print 'PRODID:'.$base_url.'/'.current_path().CRLF;

foreach ($view->result as $node){
        $data=$node->_field_data['nid']['entity'];
//      print_r($data); // uncomment to see available data
        print 'BEGIN:VEVENT'.CRLF;
        print 'UID:'.$data->nid.'@'.$base_url.CRLF;
        $description = ical_extract_value($data->body);
        print ical_shorten_line('DESCRIPTION:'.$description).CRLF;
        print 'DTSTART:'.date($ical_time_format,ical_extract_value($data->field_start)).CRLF;
        print 'DTEND:'.date($ical_time_format,ical_extract_value($data->field_start,'value2')).CRLF;
        /** other fields here **/
        $keywords = ical_extract_value($data->field_tag_list);
        $keywords = str_replace(' ', ',',$keywords);
        print ical_shorten_line('CATEGORIES:'.$keywords).CRLF;
        print 'END:VEVENT'.CRLF;
} ?>
END:VCALENDAR

```

As you can see, a certain field value can be accessed by $view-\>result\[n\]-\>filed\_xxx\['und'\]\[0\]\['value'\].
> 0 votes

---
Tags: views
---


title: How to warm-up Twig?

text:
# Question
Title: How to warm-up Twig?
I would like to warm-up Twig templates after cache rebuild or when needed. By warming-up I mean to process each twig template into php file.

Is this possible without rendering the content first?

# Answer
You can warm up the twig cache with drush:

```
twig-compile (twigc)  Compile all Twig template(s).

```

The twig cache is located in

```
/sites/default/files/php/twig

```

Here you can check the compiled php files.
> 3 votes

# Answer
The question sounds like coming from a Drupal 7 background :)

If I understand it correctly, you are looking for a way to execute some PHP logic before rendering the content. Just like what we were used to do in the `*.tpl.php` files.

However, PHPTemplate was removed and replaced by Twig for a reason. **For truly separating business and presentation layers** \- on of the major reason.

This does not mean that you loose on to the control which you had with PHPTemplate files. This only means that you are now forced to follow the best standard practices ;-)

Ideally, in both Drupal 7 and 8 the template functions the rendering should be broken in two steps:

1. Business logic - The function which is responsible for initializing the data (to be returned to page). This could be a function which calls the `theme()` function, like the `page callback` of your `hook_menu` implementation where you pass the variables into it. These could also be the `preprocess` functions which could be used to add new and or change existing `$variables` to the theme element being called.
2. Presentation logic - These are nothing but the functions or template file responsible for printing the values that it gets from the Business layer into appropriate markup. In D7 we used `*.tpl.php`, whereas in D8 we use `*.twig`.

To deal with the issue at hand, you will need to the template\_preprocess() function. The `*.twig` file is responsible to **only print the variables**, with minimum logical checks.
> 2 votes

---
Tags: 8, caching, theming
---


# Question
Title: How to get url of Product image field of Entity Reference field
Trying to create a view (a block) with associated products on product pages. Products have a field "Related products" (Entity Reference) and in my view (show products' fields) I can get images and titles of them using contextual filter (Content: Nid) and relationship (Entity Reference: Related products). But there's a problem with the url of titles and images, they're leading to editing pages (like admin/commerce/products/1), but not to content. I tried to add a field Content:Path, but I get a link to a product itself, not to related with it products.

# Answer
As you're creating your view, you need one more relationship. Look for this relationship:

> Commerce Product: Referencing Node
>
> (Relate a product to the Node referencing it through field\_product.)

This will allow you to harness the "reverse-relationship" going from the product to the reverse-node. Add this relationship, require it, and then use this to generate your links.
> 0 votes

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


# Question
Title: Create database fields to an existing table when installing a module
I'm new to drupal and I need some help.

I created a new module with name `user_extra`. Which create necessery table when Installing the module.

But I also need to insert some database field in `'users_field_data'` table (`'user_extra_id'` and `'user_office'`)

In `baseFieldDefinitions` I wrote all necessery database table fields for `user_extra` table.

```
 public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    // Standard field, used as a unique if primary index.
    $fields['id'] = BaseFieldDefinition::create('integer')
        ->setLabel(t('Unit ID'))
        ->setDescription(t('The unit ID.'))
        ->setReadOnly(TRUE)
        ->setSetting('unsigned', TRUE);

    $fields['uuid'] = BaseFieldDefinition::create('uuid')
        ->setLabel(t('UUID'))
        ->setDescription(t('The unit UUID.'))
        ->setReadOnly(TRUE);
        .
        .
        .
    $fields['user_info'] = BaseFieldDefinition::create('string')
        ->setLabel(t('User Info'))
        ->setDescription(t("The User Info"))
        ->setSetting('max_length', 255)
        ->setDisplayOptions('form', array(
          'type' => 'string_textfield',
          'weight' => 10,
        ))
        ->setDisplayConfigurable('form', TRUE);
     return $fields;
     }

```

When I install the module it inserts all values that I define in `baseFieldDefinitions`.

**But I also need to create `'user_extra_id'` and `'user_office'` in `'users_field_data'` table with `setDisplayOptions` and `setDisplayConfigurable` options.**

This is the commenting that I made in entity file

```
/**
 * @ContentEntityType(
 *   id = "user_extra",
 *   label = @Translation("user extra"),
 *   handlers = {
 *     "storage" = "Drupal\user_extra\UserextraStorage",
 *     "storage_schema" = "Drupal\user_extra\UserextraStorageSchema",
 *     "access" = "Drupal\user_extra\UserextraAccessControlHandler",
 *     "list_builder" = "Drupal\user_extra\UserextraListBuilder",
 *     "view_builder" = "Drupal\user_extra\UserextraViewBuilder",
 *     "views_data" = "Drupal\user_extra\UserextraViewsData",
 *     "form" = {
 *       "default" = "Drupal\user_extra\Form\UserextraForm",
 *       "add" = "Drupal\user_extra\Form\UserextraAddForm",
 *       "edit" = "Drupal\user_extra\Form\UserextraEditForm",
 *       "delete" = "Drupal\user_extra\Form\UserextraDeleteForm",
 *     }
 *   },
 *   admin_permission = "administer user_extra",
 *   base_table = "user_extra",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "name",
 *     "uuid" = "uuid",
 *   },
 *   links = {
 *     "canonical" = "/admin/user_extra/{user_extra}",
 *     "add-form" = "/admin/user_extra/add",
 *     "delete-form" = "/admin/user_extra/{user_extra}/delete",
 *     "overview-form" = "/admin/user_extra/${user_extra}/overview",
 *     "edit-form" = "/admin/user_extra/{user_extra}",
 *     "collection" = "/admin/user_extra",
 *     "children" = "/admin/user_extra/{user_extra}/children",
 *   },
 * )
 */

```

# Answer
> 1 votes
There are a couple of inconsistencies with the question and code so I am not sure whether or not this can be accepted as an answer to the strict question "How do I create database fields to an existing table when installing a module".

1. "user\_extra" is defined as a new content entity. What this means is that it is a fundamental new thing that is not related to a Drupal User entity nor the User entity's storage. This might be a similar use case to Profile2.
2. Modifying base field definition is probably a bit too heavy/complex for adding in the "user\_office" and "user\_extra\_id" data that your site needs. The "Drupal Way" would be to add a "Bundle Field" to the entity.
    * This could be done as a site builder in the user interface (See Configuration \> People), programmatically or providing YAML in `config/install` (Berdir). See field.storage.user.user\_picture.yml.
    * Adding many fields to the User entity may have a performance impact, which could be solved by using a module such as Profile2 to only load that information on certain pages.

---
Tags: hooks, entities, 8
---


# Question
Title: An AJAX HTTP request abnormally terminated in autocomplete textbox
I have autocomplete textbox which populate the suggestion based on search text.

### Steps

1. User type in search text box
2. User press enter instead of waiting for AJAX autocomplete to respond

It comes up with the following error.

> An AJAX HTTP request terminated abnormally.
> Debugging information follows.
> Path: path/allcontent/autocomplete
> StatusText: error
> ResponseText: ReadyState: 4

I read Drupal alerts "An AJAX HTTP request terminated abnormally" during normal site operation, confusing site visitors/editors, but it didn't help.

This is the callback code.

### Autocomplete Textbox

```
function search_user($form) {
        $form['text_usersearch'] = array(
            '#type' => 'textfield',
            '#title' => t(''),
            '#autocomplete_path' => 'searchuser/autocomplete',
            '#size' => 30,
            '#attributes' => array('class'=> array('auto_submit'),'style'=> array('float:left')),
        );

$form['submit_user'] = array(
            '#type' => 'submit',
            '#value' => t('Find'),
            '#attributes' => array('class'=> array('submit_user linkbuttonAction'),'style'=> array('float:left;margin-left:10px')),

        );

```

### Autocomplete menu register

```
$items['searchuser/autocomplete'] = array(
     'title' => 'Autocomplete for User',
     'page callback' => 'user_autocomplete_search',
     'access arguments' => array('access content'),  //or whatever permission makes sense
     'type' => MENU_CALLBACK
      );

```

### Menu callback

```
function user_autocomplete_search($string) {
        global $user;
        $arrUserMatch = array();

        $matchCode = '%'.db_like($string).'%';
        $arrUserTitle = SelectMatchingUserTitle($matchCode,10);

        foreach ($arrUserTitle as $userId=>$userName)
        {
            $autotext .= check_plain($userName);
            $arrUserMatch[$userName] = $autotext;
        }

        drupal_json_output($arrUserMatch);
    }

```

### Form submission handler

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

        $searchval= $form['text_usersearch']['#value'];

        if($searchval=='')
            return;
        else
           drupal_goto('user/'.$searchval);
}

```

### JavaScript autocomplete

```
$(window).load(function(){
                Drupal.jsAC.prototype.select = function (node) {
                        this.input.value = $(node).data('autocompleteValue');

                        if(jQuery(this.input).hasClass('auto_submit')){
                              this.input.form.submit();
                        }};

        });

```

# Answer
i am using the following code to auto complete the name of the partners (store owners) in a search box in a form to edit a store's detail (not all form elements used are shown here): the auto\_complete call back returns the list of all the partners in the database. (here one partner owns one store)
you could try and workout something similar:

the submit button links to a submit handler that updates the database.

```
function partner_store_form($form, &$form_state, $sid = 0) {
      $edit = NULL;
      if ($sid != 0) {
      $query = db_select('store', 's')
        ->fields('s', array('partner_pid'));
      $query->leftJoin('partner', 'p', 's.partner_pid = p.pid');
      $query->condition('s.sid', $sid);
      $query->addField('p', 'name', 'p_name');
      $edit = $query->execute()->fetchObject();
      }
      $form['pid'] = array(
        '#type' => 'textfield',
        '#title' => t('Partner Name'),
        '#size' => 30,
        '#required' => TRUE,
        '#default_value' => isset($edit) ? $edit->p_name . "  [Id:" . $edit->partner_pid . "]" : '',
        '#maxlength' => 96,
        '#autocomplete_path' => 'partner/autocomplete'
      );

      $form['submit'] = array(
        '#type' => 'submit',
        '#value' => isset($edit) ? t('Edit') : t('Save'),
        '#submit' => array('partner_store_form_submit')
      );
    }

    ----------

    $items['partner/autocomplete'] = array(
        'title' => 'store autocomplete',
        'page callback' => 'partner_store_autocomplete',
        'access arguments' => array(CONST_PERM_LIST_PARTNER),
        'type' => MENU_CALLBACK,
      );

    -----------------

    function partner_store_autocomplete($string) {
      $store = array();
      $query = db_select('partner', 'p');
      $return = $query->fields('p', array('pid', 'name'))
        ->condition('p.name', '%' . db_like($string) . '%', 'LIKE')
        ->condition('p.remove', 0)
        ->execute();
      foreach ($return as $field) {
        $store[$field->name . "  [Id:" . $field->pid . "]"] = check_plain($field->name);
      }
      if (empty($store)) {
        $store[''] = t('No Such User');
      }
      drupal_json_output($store);
    }

```
> 0 votes

# Answer
This could be caused by an open problem to correct in Drupal core (Drupal alerts "An AJAX HTTP request terminated abnormally" during normal site operation, confusing site visitors/editors). Certain developers claim that it is not a bug but a UX problem. Either way, you can apply the recommended patch until the core team backport a fix when ready for Drupal 8 (autocomplete-1232416-218-7.37.patch):

```
diff --git a/misc/ajax.js b/misc/ajax.js
index 01b894d..34831e8 100644
--- a/misc/ajax.js
+++ b/misc/ajax.js
@@ -448,7 +448,10 @@
  * Handler for the form redirection error.
  */
 Drupal.ajax.prototype.error = function (response, uri) {
-  alert(Drupal.ajaxError(response, uri));
+  if(response.status != 0) {
+    alert(Drupal.ajaxError(response, uri));
+  }
+
   // Remove the progress element.
   if (this.progress.element) {
     $(this.progress.element).remove();
diff --git a/misc/autocomplete.js b/misc/autocomplete.js
index 5679081..ee4e336 100644
--- a/misc/autocomplete.js
+++ b/misc/autocomplete.js
@@ -307,7 +307,9 @@
         }
       },
       error: function (xmlhttp) {
-        alert(Drupal.ajaxError(xmlhttp, db.uri));
+        if (xmlhttp.status != 0) {
+          alert(Drupal.ajaxError(xmlhttp, db.uri));
+        }
       }
     });
   }, this.delay);

```

However, to avoid patching core each time Drupal needs updating, another solution, depending on how important keeping abnormal AJAX request termination error reporting alerts is for you, could be what I and a few others did by injecting a redefined Drupal behavio(u)rs AJAX error handling function as so(ish) in forms, etc. that suffer from unnecessary AJAX termination alerts:

```
(function($){
  Drupal.behaviors.YourThemeNameOrWhatever = (function(){
    return {
      attach:function(context, settings){
        $.ajaxSetup({
          beforeSend: function(jqXHR, settings) {
            settings.error = function(jqXHR, textStatus, errorThrown) {
                if (window.console && console.log)
                {
                  console.log(textStatus);
                }
            };
          }
        });
      }
    }
  })();
})(jQuery);

```
> 0 votes

---
Tags: 7, ajax
---


title: CSS and JS are not showing

text:
# Question
Title: CSS and JS are not showing
I just started using Drupal 8 and i am already experiencing problems. In my info.yml file I've added library/ies and in my libraries.yml are those files included. And when I clear cache in Admin, the css is not showing in source code. I've even clear cache in Drush, if that would be the problem but it's not.

Here is my libraries.yml file

```
global-styling:
version: 1.x
 css:
  theme:
   css/style.min.css: {}

global-js:
 js:
  js/app.min.js: {}
 dependencies:
  - core/jquery

```

And here is my info.yml file:

```
name: MyTheme
description: MyTheme template for Drupal 8
type: theme
package: Custom
core: 8.x
screenshot: mytheme.jpg
libraries:
 -mytheme/global-styling

regions:
 header: Header
 content: Content
 footer: Footer
 sidebar: 'Footer2'

```

What am I doing wrong?

# Answer
> 3 votes
There is a space missing between the dash and the item:

```
libraries:
  - mytheme/global-styling

```

And be careful with the indendation. Better use 2 spaces for each level. One space is difficult to see and if you miss one, the whole yaml-file will be invalid.

---
Tags: theming, .info, 8
---


# Question
Title: How to expose the quantity of list items to an action?
Put another way.

Using a **loop**, how do I pass the number of items in a list to an **action** outside the **loop**?

I have created a loop and within the loop I have added an action to calculate a data value as follows

```
Data selector: 'loop_name:quantity'

Calculation: *1 = calculation_result

```

From within the loop I can access the new variable '`calculation_result`' however I can not figure out how to expose the calculation result to other data selectors.

What steps am I missing?

# Answer
You have to create a new variable BEFORE your loop.

And then select the type of variables in that list. For your example, perhaps a list of decimals?

Be sure to give it a good custom name for your loop:

Then, in your loop, you can add a new variable to an existing list:

Then, after your loop, you can access calculation results:

Note, that if you don't know explicitly which in your loop you want, then you will have to loop through your new calculation results and use a condition rule to return the one you need as (yet another) variable.
> 2 votes

---
Tags: rules
---


# Question
Title: How to create report to list users who change only specific field?
I have a content type with several fields which are updated manually over time by different users.

Let's say, for example, the content type name is ***Ticket*** and the fields in this content type are:

* Ticket Status
* Ticket Resolved Date
* Ticket Escalation Date (default empty)

Every time a user changes a field, a revision is created automatically.

How can I create a report (using the Views module) to list the users who only change the field "Ticket Escalation Date" from empty to some value?

**Note**: The site exists for quite some time already and contains data. So a report about these cases that were created in the past is needed also, based on the current design and existing data.

# Answer
# Part 1 - Intercept these cases from now on

If you're willing to also consider using the Rules and Flag module, then it'll be a peace of cake to use Views for creating the view you're looking for. Below are the main steps to do so ...

### Step 1: Create a flag to prepare for reporting such users

Using the Flag, create a non-global flag that will be used to get the users flagged that fit your specs (= users who only change the field "Ticket Escalation Date" from empty to some value).

### Step 2: Use Rules to flag such users

Using the Rules module, create a rule to "automatically flag users" that fit your specs (= users who only change the field "Ticket Escalation Date" from empty to some value). Here are the specs of such rule:

* Rules **Event**: after updating content (of type = ticket)
* Rules **Condition**: only the field "Ticket Escalation Date" was changed from empty to some value (this will need some refinements from your part to actually specify such condition, refer to **(\*)** for some guidance on this).
* Rules **Action**: flag such user (with the flag from step 1). But make sure to use the userid of the updater, which may be different from the node author ... Probably you want to use "current user".

**(\*)**: Some more details on those Rules Conditions (ALL conditions must apply):

* Add an "entity has field" (with field = Ticket Escalation Date), to make that field available in your rule. If such field (machine name) is only used for "tickets", then there is no need in the Rules event to refine with the "(of type = ticket)".
* BEFORE saving the content (= value before the edit started) "Ticket Escalation Date" is blank.
* AFTER saving the content (= value after the edits will have been saved) "Ticket Escalation Date" is NOT blank.
* "Ticket Status" is unchanged (value BEFORE saving is equal to value AFTER saving).
* "Ticket Resolved Date" is unchanged (value BEFORE saving is equal to value AFTER saving).

### Step 3: Create your view

Using the Views module, create a view of "users", which were "flagged" with the flag from Step 1.

# Part 2 - Report about similar cases in the past

What is explained in Part 1 can be used as a solution if it was put in place from the beginning (when the site was launched), or to intercept these cases from now on. For existing sites, you could "report" about similar cases using a custom SQL query (based on the current design and content of your Drupal tables), combined with using the Forena module (disclosure: I'm a co-maintainer of it). This module comes with quite some Community documentation. Here is a summary of this module:

> Forena is built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.
>
> Various DBMSs are supported, such as Oracle, MS Sql, Postgress, SQLite, MySQL, any PDO compliant DBMS ... And there are quite some reasons for considering Forena.
>
> Visit the Forena HowTos page for some links (near the bottom) to some , and there is a live demo site of it.

Assume you have a query which looks like so (as in your comment to this answer):

```
SELECT r.title, u.name
FROM field_revision_field_expedite_date re, node_revision r, users u
WHERE r.nid=re.entity_id and r.vid=re.revision_id and u.uid=r.uid
GROUP BY re.entity_id
HAVING min(revision_id)

```

It'd be straight forward to transform the query results of this SQL in a report (and/or even chart if you'd want ...). Refer to the example in my answer to "How to retrieve data directly from a Drupal database" to get an idea of what it is like to use Forena, such as the SQL query and the source of the "custom report" there.

PS: not sure what you'd want to "do" with such list (created as explained in "Part 1"), but if at some point you want to reset/re-init such list, you could do so easily using the VBO module also (= unset the flag for all users in my View).
> 3 votes

---
Tags: 7, views, users, entities, log-messages
---


# Question
Title: Special non-utf-8 characters appearing in feed imported from a windows based system?
I have a custom feed importer that import content from an external feed. The import happens on cron and everything is working fine except that the content comes with special non-utf-8 characters. I looked on stackoverflow and there are a few suggestions about how to do this in code, I tried couple and it has not worked for me yet. I am hoping to see if there is a drupal way of handling it.
The character that I am having problem with is `Â`. It represent a space I believe and it only appear at end/and beginning of sentences.

# Answer
You can use the Feeds Tamper module to do this with a custom plugin.

In your module:

```
/**
 * Implements hook_ctools_plugin_directory().
 */
function MYMODULE_ctools_plugin_directory($owner, $plugin_type){
  if ($owner == 'feeds_tamper' && $plugin_type == 'plugins') {
    return 'plugins';
  }
}

```

and in your module/plugins/utf8\_encode.inc

```
$plugin = array(
  'form' => 'MYMODULE_utf8_encode_form',
  'callback' => 'MYMODULE_utf8_encode_callback',
  'name' => 'Convert ISO-8859-1 to UTF-8',
  'multi' => 'loop',
  'category' => 'Text',
);

function MYMODULE_utf8_encode_form($importer, $element_key, $settings) {
  $form = array();
  $form['html'] = array(
    '#markup' => t('This will convert all ISO-8859-1 characters to their UTF-8 equivalents.'
),
  );
  return $form;
}

function MYMODULE_utf8_encode_callback($result, $item_key, $element_key, &$field, $settings, $source) {
  $field = utf8_encode($field);
}

```

If that doesn't work, then you can use one of the strip-non-UTF8 regex functions to do it in the callback instead. I use

```
$regex = '/((?:[\x00-\x7F]|[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}[\xF0-\xF7][\x80-\xBF]{3}){1,100})|./x';

preg_replace($regex, '$1', $field);

```
> 3 votes

# Answer
You can replace the special characters with empty string in **hook\_feeds\_after\_parse** like so:

```
/**
 * Implements hook_feeds_after_parse().
 */
function mymodule_feeds_after_parse(FeedsSource $source, FeedsParserResult $result) {
  //Replace special characters with '' to prevent PDO exception
  foreach($result->items as $item_key => &$item) {
    foreach ($item as $sub_item_key => $sub_item) {
      $item[$sub_item_key] = preg_replace('/[\x00-\x08\x10\x0B\x0C\x0E-\x19\x7F]'
      . '|[\x00-\x7F][\x80-\xBF]+'
      . '|([\xC0\xC1]|[\xF0-\xFF])[\x80-\xBF]*'
      . '|[\xC2-\xDF]((?![\x80-\xBF])|[\x80-\xBF]{2,})'
      . '|[\xE0-\xEF](([\x80-\xBF](?![\x80-\xBF]))'
      . '|(?![\x80-\xBF]{2})|[\x80-\xBF]{3,})/S',
      '', $item[$sub_item_key]);
    }
  }

```
> 0 votes

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


# Question
Title: Is using Drupal for a frontend and a non-Drupal API for a backend possible?
For my design, I want to have Drupal handle all security and presentation. My backend is an api that returns JSON. All I could find showed Drupal as "headless," where Drupal was the back end.

I am trying to avoid building too much into Drupal and being dependent on it.

Is using Drupal for the frontend and having separate API for the back end possible? It sounds like I have it backwards, but I do not to build everything in Drupal. I want to do all the Database and Business logic outside of Drupal.

Edit: This is for an Intranet where I hit many databases.

# Answer
Drupal 7/8 can make use of Remote Entities which could be provided in a JSON format. But, what your describing seems needlessly complex. If you have a JSON based backend I would do something more simple like create the frontend using Javascript to talk to your backend, or maybe using a more generic php framework.

Attempting to use Drupal as a frontend and ignoring its data creation CRUD, Content Types and storage mechanisms -- sounds like big headache.
> 4 votes

# Answer
It is technically possible. You could model the external data as "remote entities:" https://www.drupal.org/project/remote\_entity

However I would not recommend pursuing that strategy. The reason there are more "headless" examples that show drupal as the backend is because Drupal's data modeling is much better than its theming system.
> 3 votes

---
Tags: nodes
---


title: Output views_embed_view to Ajax content

text:
# Question
Title: Output views_embed_view to Ajax content
I have a View block. I can print the content with `views_embed_view` function, passing **$display\_id**, *contextual filter*, etc.

Now I want the user to click on a point in an image, and with Javascript, show the block in a div. So when the user click on different coordinates of the image, I show different product details in that div.

This should be possible to accomplish using Ajax ( `$(#div-id).html()` or `div_id.innerHTML` ), but my limited experience with Ajax is to retrieve a JSON formated data, not a full HTML block of a View.

How could I get it working? Is it possible at all?

# Answer
> 0 votes
I have finally solved it, by using the following code which goes in a custom module. The problem I had was that it was not rendering anything as there were nested divs. If you play with styles or add some HTML between divs, it will show the data.

The code is available at http://www.seanbuscay.com/ajax-reader-demo/

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


# Question
Title: Is it possible to control a User's Role based on their Email Address?
Currently I am emailed everytime time an employee at my company needs their account role upgraded to 'Authenticated' to 'Employee', any suggestions on a way to automate that process?

Thanks!

# Answer
> 1 votes
"Auto Assign Role" and "Apply for role" modules seem to be close to what you are asking for.

https://www.drupal.org/project/autoassignrole https://www.drupal.org/project/apply\_for\_role

If they don't fit your exact use case then I suggest looking at the way `autoassignrole_user_presave()` works as a starting point for custom coding. http://cgit.drupalcode.org/autoassignrole/tree/autoassignrole.module#n183

---
Tags: emails, users
---


# Question
Title: Alter Block render array and add another block's content
I am attempting to attach a block to another block via hook\_block\_view\_alter. The source block is a menu\_block and the block to be attached is a view block, but the type of block shouldn't matter to the solution.

Here is the code used to attach the block. Assume that `block_attached_block` is populated with the bid of the block and at the point where I am altering the render array I have a fully rendered block.

```
function MODULE_block_view_alter(&$data, $block) {
  if (!empty($block->block_attached_block)) {

    // load the attached block from the database
    $attached_block = db_select('block', 'b')
      ->fields('b')
      ->condition('b.bid', $block->block_attached_block)
      ->execute()
      ->fetchObject();

    // render the block
    $block_content  = _block_render_blocks(array($attached_block));
    $build          = _block_get_renderable_array($block_content);
    $block_rendered = drupal_render($build);

    // attach the block
    $data['block_attached_block'] = array(
      '#type' => 'container',
      '#attributes' => array(
        'class' => array('block_attached_block'),
      ),
      'block' => array(
        '#markup' => $block_rendered,
      ),
    );
  }
}

```

If I render `$data` at this point I see the attached block rendered perfectly.

```
drupal_render($data);

```

However, when I load the page the attached block is missing. The documentation is pretty light.

My question is how do I get the rendered block to output on the page.

# Answer
> 0 votes
Here is an updated function taking into account some of the various types of blocks that we can attach blocks to.

```
function MODULE_block_view_alter(&$data, $block) {
  if (!empty($block->block_attached_block)) {

    // load the attached block from the database
    $attached_block = db_select('block', 'b')
      ->fields('b')
      ->condition('b.bid', $block->block_attached_block)
      ->execute()
      ->fetchObject();

    // render the block
    $block_content = _block_render_blocks(array($attached_block));
    $build         = _block_get_renderable_array($block_content);

    // create attached block render array
    $block_attached_block = array(
      '#type' => 'container',
      '#attributes' => array(
        'class' => array('block_attached_block'),
      ),
      'block' => $build,
    );

    // attach the block
    switch ($block->module) {

      // menu block module blocks
      case 'menu_block':
        $data['content']['#content']['block_attached_block'] = $block_attached_block;
        break;

      // views module blocks
      case 'views':
        $data['content']['#markup'] .= drupal_render($block_attached_block);
        break;

      // block module blocks
      // webform module blocks
      case 'block':
      case 'webform':
        $data['content'] .= drupal_render($block_attached_block);
        break;

      // all other module blocks
      default:
        $data['content']['block_attached_block'] = $block_attached_block;
        break;
    }
  }
}

```

Thanks Clive for getting me started on the right path.

---
Tags: 7, blocks
---


# Question
Title: What causes menu to stop querying for children half way through menu
I have a 'primary menu', rendered in one case using the 'bartik' theme (site preview) and rendered in the other using the 'Bootstrap' theme. (site preview)

With the bootstrap theme, working from left to right the children are presented until 'Publications'. Then there are no children. The same menu presents all the children in Bartik all the way across. Looking through it, the children are not in the php data ($element\[#below\]) and are not printed out to the HTML.

What is causing this?

# Answer
> 2 votes
this is what i see. There are no children missing. Have you cleared your Browser cache?

Some themes need the parent item set to "expanded". The setting is available (e.g. http://example.com/admin/structure/menu/manage/main-menu)for every menu item but only parents need it.

> Show as expanded. If selected and this menu link has children, the menu will always appear expanded.

This is the only wild guess i can take from your informations.

---
Tags: theming
---


title: How to get page statistics with views?

text:
# Question
Title: How to get page statistics with views?
I need to do a lot of sort criteria based on the number of profile pages viewed in Views , but I do not have any fields related to statistics and I cannot find any module which would help me to add fields to Views displays. Is there any module that would do the job or what do I have to do to get statistics about certain pages?

Someone said to alter the view query but how do I know in which table and what reference is between that table and the page that I want the statistics for?

# Answer
> 2 votes
For this you have to enable the **Statistics module** which is provided by `Drupal Core`. Follow these steps : 1. First enable Statistics Module 2. Then make a view and add a field provided by Statistics module. It basically provides three options:

```
Most recent view
Total Views
Views today

```

and then use `Total Views` as mentioned in your requirement.

# Answer
> 1 votes
## 1. Module Visitors

Have a look at the Visitors module. It comes with a set of **Visitors Reports**, such as:

* User activity report (hits, nodes, comments).
* A *Visitor* tab that is added to each node, with details about Referrer, Date, User, IP address, User agent.

This module comes with its own set of (fixed) reports, whereas these reports are about data stored in the tables this module maintains.

If the reports they come with don't meet all your reporting requirements, you could use something like the Forena module to create custom reports (and charts) about the data stored in any of these tables. Another option is to create a custom module (with custom queries) for this kind of reporting.

## 2. Module Forena

If you'd want to "roll your own cookies" (i.e. some report that perfectly fits your custom requirements), then you might want to consider the Views integration of the Forena module. Here is a relevant excerpt about that from its project page:

> Use Views with Forena to create additional more complicated layouts than can typically be created using views. Forena provides a views rowstyle plugin that lets you use a Forena report to format the output of a view.

For an example of such custom report, created with Forena, start from the statistics (summary info) of the Watchdog Statistics, as in this Watchdog Statistics sample. Note the red numbers to the right of the table, which are actually hyperlinks that can be used as drill-down reports. I.e. if you click on any of them (like the "2" for "Page not found"), you get a details report about (in this case) the 2 specific records related to the "Page not found"). More details about this specific case can be found in comment #2 of issue 2337327.

Disclosure: I'm maintainer of the Visitors module, and co-maintainer of Forena,
I hope this does not violate the site's policy on self-promotion.

# Answer
> 0 votes
There is also the Better Statistics Module that will further expand the core Statistics module by letting you omit paths/roles/lots of other customizations. Then all of this info is available on the node level in views.

---
Tags: 7, views, nodes
---


# Question
Title: Cant login to my sites on AWS but I CAN login with the same database on my local machine
I've loaded two different Drupal 7 sites on Amazon Web Services (AWS) Ubuntu instances. They both work fine and are configured mostly correctly.

**The only problem i**s, I can't login to either site using my Drupal username/password combinations! (either site). I've double and triple checked my passwords/making sure CAPS LOCK isn't on, etc. I cleared cookies and even tried the permissions suggestion given in this article.

No matter what I do when I try to login to either site on AWS I get a silent login fail. No errors, the browser just reloads and prompts me to login again. I know the username/password work because on my local machine for both sites I can login easily using the same database.

*Note: I, of course, imported the databases for both projects so they SHOULD have the same user data.*

Anyone know what else I can try?

# Answer
Well, I fixed it. I had to run the following command:

```
sudo a2enmod rewrite

```
> 1 votes

# Answer
So the real problem was, when you said:

> I've loaded two different Drupal 7 sites on Amazon Web Services (AWS) Ubuntu instances. They both work fine and are configured mostly correctly.

You neglected to prepare your site for migration by putting it into a state which is ready to be deployed elsewhere, even a newly spawned, and default configured OS (with no prior websites running). Even if you use a tool like Drush and `archive-backup` command it's recommended when moving a Drupal site to clear-cache, and to disable clean-urls for example as webserver configurations may be different between hosts.

When moving a site you want it configured minimally so that it is simple to restore, and test, on the destination server and so whatever custom tweaks need to occur on the new host can be performed after deployment.

Other modules that can help with this for example is Pathologic:

> Pathologic is an input filter which can correct paths in links and images in your Drupal content in situations which would otherwise cause them to “break;” for example, if the URL of the site changes, or the content was moved to a different server. Pathologic can also solve the problem of missing images and broken links in your site’s RSS feeds.
> 1 votes

---
Tags: 7
---


# Question
Title: Do any comment modules play well with revisioning?
I'm faced with a situation where we need to keep track of which node revision a comment was made for, so that we can display whether the comment was made for a newer/older revision, or for the one currently being looked at. Do any comment modules allow this in D7?

---

**Use cases**

1. Not the actual use case, but a decent, easy-to-follow approximation of the idea: imagine a bookstore, where users can post comments about books. Typically, when a user asks to see a book's page, he sees the page about the book's newest edition, but in some cases a page for an older edition of the book is presented. In the list of comments for the book, comments are annotated with whether they were made about a different edition than the one being currently looked at, since the comment might not be applicable for other editions.
2. The actual use case is: teacher A creates learning material LM.v1 and then revises it to LM.v2; teacher B starts using LM.v2 with her class; when A revises LM.v2 to LM.v3, we still need to allow B and her class to use LM.v2, because LM.v3 might not work for B's needs at all (and changing a learning material mid-project is a big no-no); so, when looking at LM.v2, we want to be able to see all comments made about it, but with an annotation if the comment was about LM.v1 or LM.v3, since these may or may not be applicable in the LM.v2 case.

# Answer
I'm thinking out loud here... to simplify some aspects, I would probably try something like this first:

* set up each 'revision' as it's own content
* add a field that will follow each revision (ie. an internal product code that doesn't change even with revisions)
* add a Views block to the bottom of the content page for that content type which includes a filter of ALL comments where those comments share the same internal product code but not from the current content - that way direct comments show normally, and then there's a view showing comments from the other revisions
> 0 votes

# Answer
Surprising that this isn't addressed anywhere. I have a similar requirement and can't find any modules in this space. There is a Drupal core issue about this but it hasn't received any love.

Somehow, comments (comment.cid) need to be mapped to node versions (node\_revision.vid). This could be done with a custom table, or simply use a field on the comment to track vid. Pros and cons either way. Either way, expose to Views as needed, and implement hook\_comment\_insert() to add an entry to the table/set the field (and similarly hook\_comment\_delete()).

Since they are all attached to the node though, I think comments would have to be filtered on node view (see related question), which is far from ideal.

I hope to get something working and update this post with more detail.

---

**UPDATE WITH MORE DETAIL**

I ended up going for the field strategy. I added an integer field to the comment fields on my content type (machine name `field_comment_node_version`), and then added a piece of code to populate it:

```
/*
* Implements hook_comment_insert().
*/
function MYMODULE_comment_insert($comment) {
  // Populate the comment field for node version
  $node = node_load($comment->nid);
  $wrapper = entity_metadata_wrapper('comment', $comment);
  $wrapper->field_comment_node_version->set($node->vid);
  $wrapper->save();
}

```

And that's really all there is to it. Now you can use views to get the vid the comment was submitted against.
> 0 votes

---
Tags: 7, comments, nodes
---


title: Custom TWiG template for SELECT element

text:
# Question
Title: Custom TWiG template for SELECT element
I have created twig template to override SELECT element for SELECT-element in user exposed filters.

However I can't figure out how to make it only work within a specific view "testing" ?

# Answer
> 1 votes
You should implements hook\_theme\_suggestions\_HOOK\_alter() to add a suggestion for 'select' element. Then create a new twig template in THEME/templates folder with the name 'select--$view\_id.html.twig'.

Example code:

```
function HOOK_theme_suggestions_select_alter(array &$suggestions, array $variables) {
  $routeObject = \Drupal::routeMatch()->getRouteObject();
  $view_id = $routeObject->getDefault('view_id');
  $display_id = $routeObject->getDefault('display_id');

  if (!empty($view_id)) {
    $suggestions[] = 'select__' . $view_id;

    if (!empty($display_id)) {
      $suggestions[] = 'select__' . $view_id . '_' . $display_id;
    }
  }
}

```

---
Tags: 8, theming
---


# Question
Title: How to open Bootstrap Photo Gallery on page load?
I am using Bootstrap Photo Gallery, and would like to open the slideshow when the page loads.

# Answer
Add your gallery into model window then used #modelid in then then gallery is automatically load when your page is loaded.

```
<script type="text/javascript">
    $(window).load(function(){
        $('#myModal').modal('show');
    });
</script>

```
> 1 votes

---
Tags: media, theming
---


title: Form API Field Permission

text:
# Question
Title: Form API Field Permission
I am creating a *custom form* and storing data in *custom table*. I was wondering if there is any method to apply *field level permission* like

```
$form['value']['#permission'] = array('access this field');

```

I know I am having field permission module to apply permission on core fields but how I can achieve this?

# Answer
> 0 votes
I am already not try this but i think it will work

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {

  global $user;
  if ($form_id == 'FORM_ID') {
  if (in_array('yourrole', $user->roles)) {
  $form['your_field']['#access'] = FALSE;
    }
  }
}

```

# Answer
> 0 votes
As said by Adi, '#access' in your form will give access to a form field based on a user role.

Check this link

---
Tags: forms, users
---


# Question
Title: Is it possible to make a second "edit account" page that only allows users to edit some profile fields?
So here is my situation: users on my site have to fill out a rather large number of fields upon registration. However, after they register, only four (out of about twenty) of these fields need to be changed regularly. I would like to create a separate "edit" page to allow users to modify just these four fields to keep things simple.

* field\_checkbox\_a
* field\_checkbox\_b
* field\_checkbox\_c
* field\_checkbox\_d

These fields are all contained in a field group, **so ideally the page would show this field group, the four checkboxes inside it, and then have a submit and cancel button, that's it.**

I want to do this as a separate page, not in-place editing like the Quick Edit module.

Users still need to be able to access the original edit account page to change their timezone, e-mail address, etc. but I could really use a separate screen to allow them to edit the most common account options.

# Answer
I had the same situation before and handle it with power full druapl feature hook\_form\_alter, we have 2 forms for user, registration and user edit

* user\_profile\_form ( in editing)
* user\_register\_form (in registration)

We just need hide your specified fields in edit manner So in your custom module

```
function yourmodule_form_alter(&$form, &$form_state, $form_id)
{
    global $user;

    if ($form_id == "user_profile_form") {
       // ym($form);
       // you also can perform this action for specified roles
        //if (!(in_array('blogger', $user->roles) || in_array('administrator', $user->roles))) {
            hide($form['field_mytest']);
            // hide other field with this method
        //}
    }

}

```

After that field exists in registration as you can see below

and not exist (hide) in edit manner

**Also you can** set them read only instead hiding them with `$form['field']['#access'] = FALSE;`

And another solution is using field permission module

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity. Features:
>
> * Enable field permissions on any entity, not just nodes.
> * Role-based field permissions allowing different viewing patterned based on what access the user has.
> * Author-level permissions allow viewing and editing of fields based on who the entity owner is.
> * Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields where this feature is needed.

As features that this module provides for us anonymous user( un-register user can edit those field and register user only see(readonly manner).
> 8 votes

# Answer
Instead of having two forms, you could use the default one, and add a "Show all the settings" checkbox, such as the following one.

```
$form['show_all_settings'] = array(
  '#type' => 'checkbox',
  '#title' => t('Show all settings'),
);

```

Then, you can alter the form fields you want to show when the checkbox is selected, and include the following property for those form fields.

```
'#states' => array(
  'invisible' => array(
   ':input[name="show_all_settings"]' => array('checked' => FALSE),
  ),
),

```

In this way, the users would be able to toggle between a form showing all the setting, and a form showing a minimal set of settings, without to pass from a page to another one.

### References
> 6 votes

# Answer
You can use Profile2 module for that.

* Create a profile type or use the default main profile.
* Add those fields to that profile type and set them to be shown on registration form.

So that those fields will be available on the *registration form* among the other fields from *user account*. But to edit those fields, the user should go to the *profile edit* page instead of *user edit* page.
> 5 votes

# Answer
Try VBO module, you can create a VBO page, add USER relationship in view, add those fields that available for user to mod, set the Permission. Make sure you select content "belongs" to CURRENT user only (via Contextual Filter)
> 1 votes

# Answer
Based on zhilevan's answer to this question and this question and this discussion on drupal.org, here is the actual code that works for me:

```
function MYMODULE_menu() {
  $items = array();
  $items['user/editpurposes'] = array(
    'title' => t('Change your purposes'),
    'page callback' => 'MYMODULE_purpose_edit_form',
    'access callback' => TRUE,
    'access arguments' => array('access content'),
    'description' => t('Purpose Edit Form'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function MYMODULE_purpose_edit_form() {
  // Needed to load AJAX.
  module_load_include('inc', 'user', 'user.pages');
  global $user;
  $account = user_load($user->uid); // Load a user object
  $form = drupal_get_form('user_profile_form', $account, 'account', 'purposes');
  return $form;
}

function MYMODULE_form_user_profile_form_alter(&$form, &$form_state) {
  if(isset($form_state['build_info']['args'][2]) && $form_state['build_info']['args'][2] == 'purposes') {

    // Remove name, email, password, etc.
    $form['account']['#access'] = FALSE;
    // Remove language.
    $form['locale']['#access'] = FALSE;
    $form['timezone']['#access'] = FALSE;
    // Remove various custom fields.
    $form['field_acc_displayname']['#access'] = FALSE;
    $form['field_acc_code_agree']['#access'] = FALSE;

    // Needed to load AJAX.
    form_load_include($form_state, 'inc', 'user', 'user.pages');
  }
}

```
> 1 votes

# Answer
I think you should be able to tidy things up a bit with the Field group module, e.g. put fields under different tabs. Common ones under one tab and the rest under another tab.
> 0 votes

# Answer
try this code. and hide other fields u don't want to show.

```
<?php
global $user;
$user=user_load($user->uid);
module_load_include('inc', 'user', 'user.pages');
$user_form = drupal_get_form('user_profile_form', $user);
print(drupal_render($user_form));
?>

```
> 0 votes

---
Tags: 7, nodes, users
---


# Question
Title: What does 'Rebuild Permissions' actually do?
I've been working with a lot of custom content types lately, and I keep getting a message to rebuild my permissions.

It seems like it happens everytime I create a new content type. Is this normal behavior? And what exactly is happening when I do this?

# Answer
> 4 votes
Drupal core uses database tables to control some aspects of content viewing/editing permissions. These tables are used by contrib modules like Domain Access or Taxonomy Access Control to store information about which roles/users can see which nodes. Because it is not easily determinable which configuration changes will result in actual permission changes Drupal marks these tables as needing updating for a broad set of configuration changes.

# Answer
> 0 votes
In drupal, permissions are saved in node\_access table. Based on key/value pair in node access table, permissions are restricted to users.

When you use any content access modules like (Organic groups, Access by Term), permissions for each node will be rebuilt on node access table based on configuration.

So when a new content type is created, it is needed for those modules to rebuilt new permissions for the newly created content type

In general, rebuild permission will call node\_access\_rebuild function. Check that function for more info.

---
Tags: nodes, users
---


title: Overriding Field Collection output

text:
# Question
Title: Overriding Field Collection output
I have a content type named: `lectures`

In this content type I have a field collection field named: `field_course_video_slide_sync`

This field collection consists of 3 fields: `field_start_slide_sec`, `field_slide_title` and `field_slide_number`

What I'm trying to achieve is to rewrite them into this:

```
<ul>
 <li begin="field_start_slide_sec"><a href="#field_slide_number">field_slide_title</a></li>
</ul>

```

I've tried `tpl.php`, `preprocess_node`, `field_get_items` and views but nothing seems to work. I can't figure out what I'm missing.

# Answer
Please override **field-collection-item.tpl.php** file present in the Field Collection module directory. You can put your code in that. Just simply copy it to your theme folder, and place the code inside it.
> 1 votes

---
Tags: theming, entities
---


# Question
Title: Add configuration options for Views block under Structure > Blocks > configure
I'm building a module that defines several blocks and provides custom options for those blocks via `hook_block_configure()`. Two of these blocks were built from scratch using `hook_block_info()` and their configuration options defined in `hook_block_configure()` display as intended. In other words, if you navigate to Structure \> Blocks and click configure for either of these two blocks, the custom configuration options are displayed as intended.

The third block is a **Views** block, defined by `hook_views_api()` and `hook_views_default_views()`, and the `hook_block_configure()` hook doesn't trigger at all for this block. Navigating to Structure \> Blocks and clicking on configure for this block just shows the default block configuration options.

What I would like to know is how to add custom configuration options for this **Views** block or a similar solution. Is there any way to register this block so that it will also listen in on the `hook_block_configure()` hook? Or is there maybe a different hook that would allow me to accomplish my goal? My Google-fu has yielded nothing.

# Answer
> 1 votes
To "***add fields to the block configure pages for these two blocks***" (as in your question), you should look at the Bean module as a possible alternative to answer this question. 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 (see screenshot below). The bean content can then be placed around the site just like any other block.

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 ...

---
Tags: views, blocks
---


title: Custom login -> admin

text:
# Question
Title: Custom login -> admin
I know it is *possible*, but is it *advisable* or even *in common sense* to try to implement second (own) login i.e. `mysite.com/login2` and access that way to custom layout (admin page), where is some custom data to manage our own hidden things, nothing related to drupal tho.

The reason for this, I love drupal, and I would use it for frontend publishing and managing site easy. But thing is I need some sort of portal (module for drupal) to handle data from my other sources where this own login and admin comes handy.

This is currently done with custom coding, but is it possible to integrate this "custom code" to drupal with modules and use durpals see, friendly urls, database handling etc advantages?

I don't expect this to happen in no time, need to learn a lot deeper but if there is a change to do this in reasonable time and without breaking drupal itself, I would love to start developing this :)

# Answer
> 1 votes
It seems like you would like for one login to give access to Drupal site administrative functionality, and also give access to specialist non-Drupal functionality.

The easiest and most flexible way to achieve this is might be to add an extra link to the Drupal administrative menu. When someone logs in, that new link would be there prominently along side the other Drupal administrative links.

The link could point to another website, to non-Drupal pages and scripts on the same server, or to Drupal pages generated by a custom Drupal module you created.

Perhaps the biggest advantage of putting your custom code inside a custom Drupal module would be that you could use Drupal's access control system: logging into Drupal with the right role would automatically grant users (and only these users) access to your custom functionality.

Generally speaking, taking existing code and turning it into a Drupal module so that it outputs it results "through" Drupal in a minimal but viable way should be easy.

Fully converting your code to take advantages of all Drupal's API features (theming, UI widgets, etc., etc.) would be a much bigger task. It's not necessary for your stated goal, it's more something you might consider for the sake of improving the robustness of your code by leveraging the quality of Drupal's APIs.

---
Tags: 8
---


# Question
Title: Using images in custom module (not through css)
I am making a flex slider module, and it needs to just load some images statically, the only way I was able to get hold of any of the images was when I used a relative path in a background-image: url(relative-path-to-image) in a css file, but I am not interested in loading it through css.

If I try to access it relative from the template, using `<img src="relative-path-to-image">` it won't work of course, because the `src` tag are being loaded on the client. I have looked a bit at the templating system and I can use a {{ directory }} variable inside of twig, to maybe get the absolute path to the images right. But I just feel like even if I made that work it would still be a disaster implementation.

So my question is, if you need to add a tag and give it a src path-to-image, what is your go-to solution to get that image accessible?

# Answer
> 4 votes
If you want to access images in the module folder:

preprocess function (assuming page, but can be any other template):

```
mymodule.module:
function mymodule_preprocess_page(&$variables) {
  global $base_root, $base_path;
  $variables['image1'] = $base_root . $base_path . drupal_get_path('module', 'mymodule') . '/images/' . $image1;
}

```

twig:

```
<img src="{{ image1 }}" />

```

I don't know your logic for multiple images, I guess you have to code a loop for this.

But accessing static images in a module folder is not a cms way to do this, I would put the images into a node. You can make a content type "slider" for this and then access the absolute path of the image field:

twig:

```
<img src="{{ file_url(slider_node.field_slider_image.0.entity.uri.value) }}" />

```

Here you can code a twig loop to access multiple images in the field.

---
Tags: 8, media
---


# Question
Title: Extract PDF front page and store it as an image field in node
I'm using Document Library module to manage my files and create listings for them.

I've also noticed the existence of PDFPreview module and I'd like to ask if the following is possible:

I'd like to upload a pdf file in a Document Library Document item and with this file to generate an preview image, **stored as a new independent field (lets say the Thumbnail image field) in this content type**. As things are now the preview replaces the file field which is something that I need to avoid.

# Answer
Oh I just realized that another module, the PDF to Image Field module does exactly what I need! Some more details about thsi module (from its project page):

> The PDF To ImageField module provides automatic conversion of uploaded PDF files to images. It can be used either to create a snapshot of the front page to use as a preview thumbnail, or to generate a gallery of images from each page in the document.
>
> The module is implemented as an additional widget for File Field where PDFs are uploaded to. It places generated images into a Image Field on the same content type.

At least, I hope this helps other people too.
> 2 votes

---
Tags: media, files, entities
---


# Question
Title: Deciding which field should be on Product node and which on product variations
I'm wondering if I'm implementing my products the right way.

As I understand it should be the following.

I have different product variations with each their specific fields and SKU. For example storage = 8 GB or 16GB

Then I have the main product to which these variations belong with main attributes such as the product name or compatibility. These are shared over the different variations.

So I consider I have my product nodes (or product displays?) with al my product information that is the same over the variations. And I have my product variations with the SKU's and fields that are specific to each variation of the main product.

For me personally I think this is the correct way because you don't have duplicate data in your database. And if some field data needs to change, if it's a product specific field and not variation specific, you don't need to edit it over all the variation entities.

But I'm not sure that this is the correct way to do this according to standards, advise, other things I'm missing, ... . Because I'm very new to drupal commerce.

# Answer
In the end we decided to put all the fields on product variation level.

In this sense it also gives more flexibility to the product managers in which attributes define the variation instead of a hard coded limit on which attribute.
> 0 votes

# Answer
I think you're on the right track. If I'm not mistaken, a product display could be something like "Tee Shirt". The product variants would then be something like color or size. It's the same product with the core information, but the variants would be what ever is different, be it storage size or any other kind of variation from the original.

Edit: The product display can display any products. The variants are dependent on the actual product but the display can show anything.
> 0 votes

---
Tags: commerce
---


# Question
Title: Drupal Commerce Mirgrate product displays
I'm trying to create a migration class for my product displays. I already have one for the product variations which is seperate because it has a different CSV source.

So I'm just trying to create the drupal nodes of the product displays. When I check the database in the node table, the nodes are there with the correct type. However when I go to the product page, I don't see the new items there.

I think it has something to do with this line:

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

```

or

```
$this->map = new MigrateSQLMap($this->machineName,
      array(
        'Name' => array(
          'type' => 'varchar',
          'length' => 255,
          'not null' => TRUE,
          'description' => 'Recorder',
        ),
      ),
      //MigrateDestinationCommerceProduct::getKeySchema('commerce_product')
      //MigrateDestinationEntityAPI::getKeySchema('video_storage_recorder')
      MigrateDestinationNode::getKeySchema('video_storage_recorder')
    );

```

where video\_storage\_recorder is my content type.

Also I tried

```
$this->destination = new MigrateDestinationEntityAPI('video_storage_recorder');

```

But no different behaviour.

I think the nodes are created but not considered products for Drupal Commerce. But I don't know why. Also Migrate does not give any (error) messages and just says 9 items were created.

# Answer
When I added a product variation in code the product appeared in the list. It's required to have at least one variation to be linked for the product display to be considerd a product display.
> 0 votes

---
Tags: commerce, migrations
---


# Question
Title: Form hook not found through module_hook_info in module subdirectory
**Context:** In my Drupal 7 project, I have a module with several submodules. Because the module's root directory got crowded, I moved the submodule files to their own directories within the root.

My module's structure is like this:

```
mymodule
├── mymodule.info
├── mymodule.module
├── mymodule1
│   ├── mymodule1.block.inc
│   ├── mymodule1.form.inc
│   ├── mymodule1.info
│   ├── mymodule1.module
│   ├── mymodule1.page.inc
│   └── pages
│       └── foo.tpl.php
└── mymodule2
    ├── classes
    │   └── foo
    │       └── Bar.php
    ├── mymodule2.form.inc
    ├── mymodule2.info
    ├── mymodule2.install
    ├── mymodule2.module
    ├── mymodule2.page.inc
    └── pages
        ├── foo.tpl.php
        └── bar.tpl.php

```

Before "the big move", files that are now in the subdirectories `mymodule1` and `mymodule2`, were located in their parent directory (the module's root directory).

---

**The problem:** Ever since moving the files, my custom forms are not loading anymore. I have a form in `mymodule1.form.inc`, which used to load and render perfectly before. Now, when I use `drupal_get_form()` to load the form, I only get an empty form with a hidden build ID input.

Keep in the mind that the only thing that has changed here, is that the .inc files have been moved to the subdirectory, along with the module file. Also, `drupal_get_path('module', 'mymodule1')` returns the correct path to the module in the subdirectory.

Strangely, there are also block hooks, located in `mymodule1.block.inc`, which work perfectly fine, even after clearing all caches.

This is the first time I'm working with separate directories per submodule within a module. I got the inspiration from the module `i18n`, which uses the same construction. I searched in the Drupal documentation and the code of `i18n`, but could not find where I'm going wrong.

Does anyone know where I could possibly have gone wrong, or if I need to add data to `mymodule1.module` or `mymodule1.info` to make this work? Thank you.

---

**Some details:** Caches were cleared through `<path to project>/admin_menu/flush-cache` multiple times.

I use `module1_hook_info()` to direct the hooks for blocks and forms to separate files. This is the return value:

```
array (size=9)
  'block_info' =>
    array (size=1)
      'group' => string 'block' (length=5)
  'block_configure' =>
    array (size=1)
      'group' => string 'block' (length=5)
  'block_save' =>
    array (size=1)
      'group' => string 'block' (length=5)
  'block_view' =>
    array (size=1)
      'group' => string 'block' (length=5)
  'forms' =>
    array (size=1)
      'group' => string 'form' (length=4)
  'form' =>
    array (size=1)
      'group' => string 'form' (length=4)
  'form_validate' =>
    array (size=1)
      'group' => string 'form' (length=4)
  'form_submit' =>
    array (size=1)
      'group' => string 'form' (length=4)
  'form_alter' =>
    array (size=1)
      'group' => string 'form' (length=4)

```

My form functions are called:

* `mymodule1_foobar_form`
* `mymodule1_foobar_form_validate`
* `mymodule1_foobar_form_submit`

# Answer
> 1 votes
Thanks to Clive I found module\_load\_include(), which is used to load files when working with a form. I moved `hook_forms()` back to my main module's file and now load the mymodule1.form.inc through there, like so:

```
/**
 * Implements hook_forms().
 */
function mymodule1_forms($form_id, $args)
{
    module_load_include('inc', 'mymodule1', 'mymodule1.form');
    $forms = array();

    $forms['mymodule1_foo_form'] = array(
        'callback' => 'mymodule1_foo_form',
    );

    return $forms;
}

```

Now all my forms are loading correctly (again), over both `mymodule1` and `mymodule2`.

The one thing I'm not sure about, that whether this could have been achieved without redundantly declaring the form callbacks to their same-named form IDs.

# Answer
> 0 votes
I'm going to take a stab at what happened here, I might be wrong.

`hook_form()` isn't a normal hook, it's only invoked for modules that define node types (you haven't indicated any of yours do). It isn't invoked when you arbitrarily invoke `drupal_get_form()`. Same goes for `hook_form_validate()` and `hook_form_submit()`.

Some of the hooks in your `hook_hook_info()` implementation *are* called for all modules, though. e.g. `hook_forms()` and `hook_form_alter()`.

I would surmise that `mymodule` contained an implementation of `hook_form_alter()` or `hook_forms()`, which was coincidentally invoked on the same page(s) as the forms that you've now moved to `mymodule1` were displayed. Those hooks being invoked implicitly result in `mymodule.form.inc` being included, and the functions were available.

Now that you've moved the code into `mymodule1`, I'm guessing you haven't implemented either of the hooks that would have resulted in that coincidental behaviour. So Drupal now can't find your form function, and fails silently.

To fix, include the file manually:

```
module_include('inc', 'mymodule1', 'mymodule1.form');

```

---
Tags: 7
---


# Question
Title: Unique Fields with the ability to be a reference to multiple records
I wonder to know is it possible to have an unique field (let consider a text filed), when we input a data into it firstly it check the table if it doesn't exist add a record, if it find a record refer to it?

i.e.: I have a field in my content type to store telephone number whenever I want to add a new node, after entering the data into the telephone field if the number was stored in my database instead of creating a new record in the table I just reference to the number

My aim is to have a contact list of some users that submit a form but I don't want duplication (just unique phone number and name)

# Answer
> 3 votes
I would envision this as

* Create a rule that post a node each time the form from anonymous user is submitted.
* Create a condition before creating a node - the condition will loop through all entered node telephone numbers if they found that the user has already entered the data don't do anything other wise post the node with phone, name and email information.

---
Tags: 7, entities
---


# Question
Title: Drupal Commerce add multiple products to cart at once with different attribute values
I'm developing a shop based on Drupal Commerce which sells customizable objects. I'd like to be able to order t-shirts of a certain type in different colors an sizes (like 5 orange ones size XS, 10 blue ones size L...).

This would normally be done by going to the product page, selecting "orange" as the color, "XS" as the size, adding it to the cart, then going back to the product page...but this is too complicated.

So I'm wondering what is the cleanest approach to achieve this.

Here is an example of the result I would like to obtain (choose a color, then a size, then a quantity, do it as many times as you need, then only click add to cart) : http://www.objetrama.fr/tee-shirt-personnalise-femme-melrose-150-gr-m.html

I think this could be done by finding a way to send multiple add to cart requests from the same page using ajax (tried this approach with not much success). Another solution would be to create a custom add to cart function which accepts multiple products with different attribute values.

# Answer
Since your not sending a single SKU, you could just overwrite the validate and submit handler for the add to cart form and then, using the existing validate and submit handlers as a blueprint, write your own logic to add multiple products. You'll want to make sure you create line-items for each of the variants your adding to the cart so that pricing is calculated properly, but it should be a fairly straightforward process.
> 0 votes

---
Tags: commerce
---


# Question
Title: Admin approval notification based on role choose by user on registration form?
I need to set admin approval for a particular role. I am using auto assign module to provide user to choose role on registration form.

authenticated users: Do not need admin approval

```
$form_state['values']['status'] = 1;

$form["account"]["status"]["#default_value"] = FALSE;

```

Try to use above line on validate function but not getting any success.

# Answer
I have created a module for this, which addresses my question. It can be found at Select registration roles. Some more details about it (from its project page):

> The Select Registration Roles module adds a role field on the user registration form. Admin can configure roles to be displayed on the registration form as, and can set roles which require admin approval.

Here is a screenprint of it also:
> 1 votes

---
Tags: users
---