# Question
Title: Deleting the "Page title" module in an existing site that needs some module-removal (Will damage SEO?)
A drupal 7 site owner asked me to clean all unnecessary modules in her site. After I've successfully updated all modules and DB, I went to start delete some modules.

I've deleted unused modules until I came across Page title, the well known module from the Drupal 6 era, which it's functionality now a part of the Metatag module. I wonder if deleting it will destroy the page titles that have already been added to the site's nodes... What is the technical truth?

# Answer
> 1 votes
Page Title stores its titles in a DB table, which will be deleted (along with all its data) if you uninstall the module. It uses an HTML preprocess hook to load that data from the DB on a page-by-page basis, and replaces whatever would normally be the title for that page right at the last minute.

So...

> I wonder if deleting it will destroy the page titles that have already been added to the site's nodes

Is entirely accurate. If you remove the module, you'll also remove the page titles that were added using it, and Drupal will use whatever default title was applicable for the entity before you installed it in the first place (e.g. for nodes that'll be whatever is in the `title` property).

---
Tags: 7
---


# Question
Title: How can I have the JS/CSS cache refresh on every page load?
How to clear cache on every page load?

I am doing CSS & JS theming and currently having to manually clear cache (using devel module) every time and then reload the page again to see my changes?

How do I do it so that in every page load cache is cleared?

# Answer
As long as you don't have *JS* or *CSS aggregation* turned on, you shouldn't have to clear cache to see your changes to existing files. You can see this settings by going to;

*Admin-\>Config-\>Development-\>Performance(`admin/config/development/performance`).*

If you are adding new *CSS* or *JS* files, you'll probably have to clear cache to register them with the theme system.

If you really want to clear cache on every page load, you should create a custom module that implements *hook\_init()* and runs *drupal\_clear\_css\_cache()* and *drupal\_clear\_js\_cache()* (or any other cache clearing functions you may want), but this should be unnecessary.
> 4 votes

# Answer
If you disabled caching in Drupal (Performance) and still files are not reloaded, it's probably cached by your web browser.

Some web browser can force the cache reload by holding `Shift`.

In Chrome internal caching can be disabled in DevTools settings (`F1` once you open *Developers Tools*), then: *Disable cache (while DevTools is open)*.
> 0 votes

# Answer
This is not a perfect solution. But you can use this in dev stages

Copy/Paste this code in your themes template.php

```
function YOURTHEME_preprocess_page(&$variables) {
  global $base_root
  include_once $base_root.'/includes/bootstrap.inc';
  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
  drupal_flush_all_caches();
}

```

Try and let me know the status.
> -2 votes

---
Tags: theming, performance, debugging
---


title: Add a discount to a product with Rules

text:
# Question
Title: Add a discount to a product with Rules
I want to add a new *price field* called *Discount* to a product. So now I have two price fields, *Price* and *Discount*.

Then with the help of the rule, I am interested in showing in the *node page* the price(with line-trough) and the discount.

Then when adding the product to the cart, the discount price will be added, instead of the normal price. How can I achieve this with rules?

PS: I don't want to use the Commerce Sale price module since it doesn't integrate with Search api.

I have found these instructions but I am not sure how to create the rule!

1. Add another price field to your product type.
2. Add a rule that applies the discount to the price on that product if the extra price field exists. Make sure you use the *Discount* price component when creating the rule.
3. Use Extra Price Formatters to display the difference.

# Answer
I finally found a solution:I cloned the rule of the Commerce Sale module: I created a Component: Conditions: -Entity has field:Parameter: Entity: \[line-item\], Field: commerce\_product -Entity has field:Parameter: Entity: \[line-item:commerce-product\], Field: field\_discount\_price -NOT Data value is empty:line-item:commerce-product:field-discount-price:amount

Actions:Set the unit price to a specific amount (Specify the numeric amount to set the price to:Price:Amount Value:Discount

Then I created a rule: Events:Calculating the sell price of a product Action:The previous component (Data selector:Commerce line items)

Then I used a price formatter and its done https://www.drupal.org/project/commerce\_extra\_price\_formatters Thanks!
> 1 votes

# Answer
I had a similar case and tried to build the rule as you described. At start I did not get it right but then I looked into the component setup here: Commerce Saleprice rules code

I used this module to manage the formatters: Drupal Commerce Extra Price Formatters

I added a Discount field to my product fields and a Rule to calculate price using the above component. I also went for a % instead of using a final price so I used the Multiply option.
> 0 votes

---
Tags: commerce
---


# Question
Title: Images show up once, then have to clear styles folder to see again?
So I'm trying to get a site setup with a template (global news), which requires Drupal 7.x, so I'm using 7.41. Anyway, I have all the modules set up and the general layout as it should be. However, I'm having a problem with getting the images to render.

It seems as though if I delete the /default/files/styles folder, the images will generate and show up on the website, however if I refresh the page the images fail to load until I delete the folder again. If I don't delete the folder I get a 403-forbidden for each image I'm trying to load.

It's weird, and I've almost driven myself crazy trying to get this figured out.

Any advice?

# Answer
The fact that derived images can be fetched when they are absent from the filesystem but not when they are present indicates this is a webserver configuration issue.

The webserver rules are normally be set up so that any non-existent paths are routed to Drupal. When image thumbnails are generated they get served by Drupal, but once on disk they should be served directly from the filesystem. Check your .htaccess files (if using Apache) and somewhere there is likely to be an rule denying access to that area of the filesystem.
> 0 votes

---
Tags: views, media
---


# Question
Title: Which .tpl file should I use to theme the quiz module's detail page?
I am using the Quiz module for a requirement.

I want to theme the quiz *detail page*, *multiple choice questions page* and the *Jquery timer* which I am using with that page.

Which `.tpl` files should I edit for this?

# Answer
> 0 votes
The answer surely will be here it describes how to create a .tpl files for ehat you want D7 theme suggestions

---
Tags: 7, theming, quiz
---


title: Import csv to cart

text:
# Question
Title: Import csv to cart
Is there a way to import from a cvs (or similar) to the cart? The csv could be very simple: sku and quantity. I'm using Drupal 7 with commerce.

Thanks!

# Answer
To my knowledge, there are no modules that implement this. You might be able to get feeds working if there were some tampers added that were able to create an order and associate it with the information that was coming in (e.g. you're creating line items). But that's just a guess. You'll need to implement something custom for this.
> 0 votes

---
Tags: commerce, importing-exporting
---


# Question
Title: How to filter groups of paired values in Views
I have a Field Collection field in a node. The field collection has two fields, so I can associate a group of paired values to a node. For example, {a,1}, {b,2},{c,3},{d,4}.

I have a View in which I want to filter by the values above. If I use a filter for the first type of values and put **a**, it will return the first 2-tuple. If I put **2** in the second filter (and nothing in first filter), it will return the second 2-tuple. But if I look for **c** in first filter and **4** in the second filter *simoultaneously*, it will return the 2 last values, because *c* matches the condition and *4* matches the condition, **separatedly**. How can I make the View filter so I get the desired result, which is empty result in this case?

# Answer
I am not able to reproduce the behavior you describe. In configuring a Field Collections and Views in the way you describe I do get the desired results.

Here is a screenshot of my configuration:

And here are the results:

And here is the filtering:

By letter:

By number:

Mismatched letter/number yields no results:

And here is the full View export:

```
$view = new view();
$view->name = 'stacktest_fieldcollection';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'stacktest_fieldcollection';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'stacktest_fieldcollection';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
/* Relationship: Content: FC (field_fc) */
$handler->display->display_options['relationships']['field_fc_value']['id'] = 'field_fc_value';
$handler->display->display_options['relationships']['field_fc_value']['table'] = 'field_data_field_fc';
$handler->display->display_options['relationships']['field_fc_value']['field'] = 'field_fc_value';
$handler->display->display_options['relationships']['field_fc_value']['required'] = TRUE;
$handler->display->display_options['relationships']['field_fc_value']['delta'] = '-1';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Field collection item: Letter */
$handler->display->display_options['fields']['field_letter']['id'] = 'field_letter';
$handler->display->display_options['fields']['field_letter']['table'] = 'field_data_field_letter';
$handler->display->display_options['fields']['field_letter']['field'] = 'field_letter';
$handler->display->display_options['fields']['field_letter']['relationship'] = 'field_fc_value';
/* Field: Field collection item: Number */
$handler->display->display_options['fields']['field_number']['id'] = 'field_number';
$handler->display->display_options['fields']['field_number']['table'] = 'field_data_field_number';
$handler->display->display_options['fields']['field_number']['field'] = 'field_number';
$handler->display->display_options['fields']['field_number']['relationship'] = 'field_fc_value';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
/* Contextual filter: Field collection item: Letter (field_letter) */
$handler->display->display_options['arguments']['field_letter_value']['id'] = 'field_letter_value';
$handler->display->display_options['arguments']['field_letter_value']['table'] = 'field_data_field_letter';
$handler->display->display_options['arguments']['field_letter_value']['field'] = 'field_letter_value';
$handler->display->display_options['arguments']['field_letter_value']['relationship'] = 'field_fc_value';
$handler->display->display_options['arguments']['field_letter_value']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['field_letter_value']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['field_letter_value']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['field_letter_value']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['field_letter_value']['limit'] = '0';
/* Contextual filter: Field collection item: Number (field_number) */
$handler->display->display_options['arguments']['field_number_value']['id'] = 'field_number_value';
$handler->display->display_options['arguments']['field_number_value']['table'] = 'field_data_field_number';
$handler->display->display_options['arguments']['field_number_value']['field'] = 'field_number_value';
$handler->display->display_options['arguments']['field_number_value']['relationship'] = 'field_fc_value';
$handler->display->display_options['arguments']['field_number_value']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['field_number_value']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['field_number_value']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['field_number_value']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['field_number_value']['limit'] = '0';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'stacktest-fieldcollection';

```
> 1 votes

---
Tags: 7, views, entities
---


# Question
Title: How to debug what module/process is requesting a file?
I moved my drupal 6 site to server with php 5.5 and the site started to throw not found error - sites/all/libraries/jquery.ui/themes/base/jquery-ui.css on every page. I have not installed any new module and the file was never on that location. How would be possible to debug this? Thank you.

# Answer
It is possible that the previous server was suppressing errors entirely and this error would have shown up had error reporting been turned on. In general, you can debug such errors by using the `dsm()` function from devel module. If you need to know where a functional call is coming from, you can use `debug_backtrace()`.
> 0 votes

---
Tags: 6, javascript
---


# Question
Title: How to filter for a Field Collection in a View
I have a View of Field Collection fields. The Field Collection is composed of `field 1`and `field 2`. The Field Collection is associated, as a single field, to a content type. If I filter the View by a combination of values for **field 1** and **field 2**, and I have established a relationship with the associated content type, I can filter **combinations** of values, which come as 2-tuples; for example: **Music** and **Great Britain**, **Sports** and **USA**, etc.

However, if the View is a view of the content type, of the nodes, I don't know how to group filters in such a way that I can look for the specific combinations above. If I put two filters, and search by **Music** and **USA**, I will retrieve results even if the correct value is the 2-tuple **Music** and **Great Britain**. The view filters in ALL the Field Collections instead of just looking in one each time.

How can achieve the result with a View of content (products)? Or the way is to do it with the Field Collections, as I have done?

# Answer
> 1 votes
I answered over in How to filter groups of paired values in Views which appears to be essentially the same question.

---
Tags: 7, views, entities, input-formats
---


# Question
Title: Main differences between registry and file_registry tables in Drupal SQL tables structure?
I already know that in computing in general, registry is the main data structure for paths (whether as a table in DB or a as a standalone DB).

In the case of Drupal, I saw two tables in the DB's. When is "registry" and the second is "file\_registry".

While I understand that file\_registry table holds paths for files, I wonder what are the main kinds of paths that the "general" registry table holds, and thus what are the main differences between them. I hope a Drupal developer who have dived into these SQL files could explain the main differences,

# Answer
The `file_registry` stores entries for all uploaded files as `attachments` or `file_entities` to Drupal. Files marked for deletetion are removed at Cron and cleared from the table.

The `registry` table stores Drupal system information on all available code files available to the system from `modules` and `themes`. And more importantly includes all php `classes` used in the system and where they may be found. When you install or remove modules or themes from your Drupal installation php files are added/removed from the `registry` table.
> 0 votes

---
Tags: database
---


# Question
Title: How to specify a Rules condition like 'Before creating new content'?
I need to show an "Add content" link to users but I need to consider user field values to give access to the node form. For example, is the boolean field "Subscription fee paid" is True.

I thought the **Rules** module could help me. But I can not find any event "*Before creating new content*", only "Before saving content". Indeed, I do not want users to fill the form before conditions are verified. Because after 5 or 10 minutes of completing a form, it would not be user-friendly to get a warning message like "\*you are not allowed to do that!" ...

So I tried **Rules link** to create a sort of button, with conditions and reactions. For example, in a block, I show the Rules link. When accessed, if conditions are true, I redirect the user to the form. Unfortunately, Drupal uses the Rules link path by default (for example, submit-the-form) and not the redirection page url included in my rule (for example: `node/add/article`) and finally the page is not found, since nothing is behind the default path.

Well, I guess I am close but still stuck. Any suggestions?

EDIT : I have tried to create a rule, as suggested by @Pierre.Vriens. Here is the short code.

```
{ "rules_subscription_check" : {
    "LABEL" : "Subscription check",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "path" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "path_has_alias" : { "source" : "[site:url]\/node\/add\/manuscript-submission" } },
      { "data_is" : { "data" : [ "site:current-user:field-subscribed" ], "value" : "0" } }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "Sorry, subscription is needed to add that type of content.",
          "type" : "warning",
          "repeat" : "0"
        }
      },
      { "redirect" : { "url" : "no_access" } }
    ]
  }
}

```

Unfortunately, an unsubscribed but authentified user can still add content when he clicks on the form link.

# Answer
> 1 votes
Try using Rules (System) event "Drupal is initializing" (= `init`), which is actually BEFORE your form is shown. If you still can't get it to work, you may have to add an extra condition (like the URL of such form?).

You may also want to look at my answer to the question "How to restrict access to a node via node/12 and allow access via a path like content/sometitle?". The sample there also includes such "Drupal is initializing".

However using a condition like `path_has_alias` will most likely NOT work either. Instead try replacing such condition with something similar to this Rules condition (in export format here):

```
{ "text_matches" : {
    "text" : [ "site:current-page:url" ],
    "match" : "node\/\\d+$",
    "operation" : "regex"
  }
}

```

In the above example, adapt the regular expression (= `node\/\\d+$`) to fit your URL naming for that form. In your case that regular expression should be something similar to `node\/add\/manuscript-submission` ...

To double check my own answer here (regex-stuff can be complicated ...), I created this prototype rule to get you going:

```
{ "rules_limit_access_url_node_add_something" : {
    "LABEL" : "Limit access URL node\/add\/*",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      },
      { "OR" : [
          { "text_matches" : { "text" : [ "site:current-page:url" ], "match" : "node\/add\/book" } },
          { "text_matches" : {
              "text" : [ "site:current-page:url" ],
              "match" : "node\/add\/article",
              "operation" : "regex"
            }
          }
        ]
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "Adding content for selected content types (such as for \u0022\u003Cstrong\u003E[site:current-page:path]\u003C\/strong\u003E\u0022) triggers some extra (Rules) logic, as you can see here.",
          "type" : "warning"
        }
      }
    ]
  }
}

```

Some more details to understand this proto-type (and make it work for your case also):

* my **1st condition** was just to have "some other condition" (in my case: applies for admins only), that's like the "data\_is"-condition in your question (ignore my condition here for the rest).
* my **rules action** in my prototype is **just for (easy) debugging**, and as a proof that my rule works as I expect it to work (use whatever action you see fit in your case).
* the `text_matches` Rules condition is the most important part for you to look at. Actually, you'll need 1 such condition for each of your content type you want your rule to apply to. In my prototype I decided to have it apply to these 2 content types (whereas I used 2 different techniques you can pick from):
    + **article** : just using an exact text match
    + **book**: using an (extremely basic) regular expression (which you may want to take advantage of if you have multiple content types that you can group together in a single regular expression.
* in case you didn't notice: be aware of the **or** part of the Rule condition also ...

I suggest you replace the `path_has_alias` condition with the applicable parts of my prototype rule above (i.e. the `text_matches` Rules conditions). Together with the "Drupal is initializing" (as in your edited version already), it should work.

# Answer
> 1 votes
Based on previous answer by Pierre.Vriens, using only the **Rules** module and **Drupal core modules**.

Here is the final code for an effective rule if you need to check users values before they can add content :

```
{ "rules_subscription_check" : {
    "LABEL" : "Subscription check",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "node\/add\/manuscript-submission",
          "operation" : "regex"
        }
      },
      { "AND" : [] },
      { "data_is" : { "data" : [ "site:current-user:field-subscribed" ], "value" : "0" } }
    ],
    "DO" : [
      { "redirect" : { "url" : "\u003Cfront\u003E" } },
      { "drupal_message" : {
          "message" : "Sorry, subscription is needed to add that type of content.",
          "type" : "warning",
          "repeat" : "0"
        }
      }
    ]
  }
}

```

So if someone needs to activate a rule before adding a new content, do not forget to use "Drupal is initializing" (=`init`) as an event, like @Pierre.Vriens suggested. Then a text comparison between the current page url (where an user goes by clicking on a button, in my case) and the form url (for example node/add/article) using regular expression without any escape characters (automatically added by Rules and Drupal, apparently).

---
Tags: rules
---


title: Extend a modules database table

text:
# Question
Title: Extend a modules database table
I would like to extend the schema of another module's ("Rooms") database table.

I have my own module for alterations of that module (specifically the Rooms-module)

Rooms has "Options" with Name, Value..etc...

I want to add "Description" to Options.

My question:

is it possible to alter the database-table of another module..??

How would I start to change this?

# Answer
> 1 votes
I'm a litle confused about your goal, but taking your question literally as *I would like to extend the schema of another module*, and assuming by extend you mean alter and not inherit from, then yes, it's pretty straightforward.

First of all, implement `hook_schema_alter()` so that Drupal knows about the change you're going to make to the table:

```
function MYMODULE_schema_alter(&$schema) {
  $schema['rooms']['foo_table']['new_column'] = array(
    // ...
  );
}

```

Then add an update hook to your module's install file to physically add the field to the table, e.g.

```
function MYMODULE_update_7100() {
  $schema = drupal_get_schema_unprocessed('rooms', 'foo_table');
  db_add_field('foo_table', 'new_column', $schema['new_column']);
}

```

It would also be advisable to implement `hook_uninstall()`/`hook_disable()` to remove that column from the table when your module is no longer active. Leaving it there probably won't hurt anything, but for the sake of cleanliness it's a good idea.

# Answer
> 0 votes
You could with `hook_schema_alter` for example. but I wouldn't recommend it.

Rather I would try to use something like your own database table and an entity reference or use the Relation module to store your own fields. Then use `field_extra_fields` to attach your custom fields onto the Room forms or display output.

---
Tags: database
---


# Question
Title: Trying to update node using node_save() produces integrity constraint exception
This is the first time I've tried to do this so I may be missing something really obvious. I'm developing a module which uses hook\_node\_insert() to catch the creation of a node, and puts the node into Drupal Queue for later treatment by a cron process.

At the end of the process, I want to update a field in the node and save it. I've tried using entity\_metadata\_wrapper as well as node\_save, but in both cases I get an error "PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry '3011' for key 'PRIMARY': INSERT INTO {node}....". Apparently, Drupal is unaware that the node exists already despite the fact that $node-\>nid is set (which is why we get a duplicate entry integrity constraint).

Looking at the node\_save() code, it certainly seems to be supposed to check and load the node first if the nid is set (which it is - I've followed this step by step in debug). I must be doing something wrong, but what?

Here is the code from hook\_node\_insert which queues the node for treatment:

```
if ($node->type == "sms_message") {
  $queue = DrupalQueue::get('sms_message');
  $node_wrapper = entity_metadata_wrapper('node', $node);
  $node_wrapper->field_queued->set(1);
  drupal_set_message($node_wrapper->label() . ' has been queued');
  $queue->createItem($node);
}

```

And here is the relevant code from the callback module for hook\_cron\_queue\_info

```
function sms_textlocal_outgoing($node) {
  global $user;
  $user = user_load(1);
  $node_wrapper = entity_metadata_wrapper('node', $node);
  $message = $node_wrapper->field_sms->value();
  $sms_sent = 0;
// Then we do some processing...
  $node_wrapper->field_sms_sent->set($sms_sent);
  node_save($node);

```

I've also tried:

```
$node_wrapper->save();

```

instead of node\_save, but with the same result.

# Answer
> 0 votes
In fact, the problem seems to be due to the fact that the node had not been loaded prior to node\_save(). It's a bit of a shame - I had despatched the entire node to the queue in the hopes that the Drupal Queue callback function would just be able to take the node off the queue and update it direct, but apparently not.

So, this worked:

```
function sms_textlocal_outgoing($node) {
  global $user;
  $user = user_load(1);
  $node_upd = node_load($node->nid);
  $node_wrapper = entity_metadata_wrapper('node', $node_upd);
  $message = $node_wrapper->field_sms->value();
  $sms_sent = 0;
// Then we do some processing...
  $node_wrapper->field_sms_sent->set($sms_sent);
  $node_wrapper->save();

```

# Answer
> 0 votes
please see the documentation of the hook https://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook\_node\_insert/7

Notice that it says that the hook is invoked (i.e. triggered) by node\_save and that means that the data is NOT yet written in the database! so you essentially create an infinite loop.

Try to do something like $node-\>yourfield\['und'\]\[0\]\['value'\]= 'yourvalue\_here' and DO NOT call node\_save again. Also do not use a wrapper because in this case only adds complexity. Notice that if you dont use the wrapper you must provide the langauage (\['und'\] in my example) the number of the item (\[0\] ie the first one in my example) and the key of the table that stores the value (\['value'\] in my example). This is done automatically when you re using an entity wrapper but since your node is not ready yet it is not the best option because you clone the object by value and not by reference and then even if you change it the changes are not reflected in the original one that will be fed into the database.

---
Tags: nodes, cron, queue
---


title: How to update a field value for a node?

text:
# Question
Title: How to update a field value for a node?
I want to change the value of a field for a node.I used the following code:

```

$node = node_load($nid); // $nid is the function's parameter
$node->field['field_myfield'][$node->language][0]['value'] = 1;
node_save($node);

```

The problem is `$node->language` returns `es` while in `print_r($node)` it's `und`. Why `$node->language` is different from what's in *$node* array and how can I get it?

# Answer
```
$node = node_load($nid);
$node_wrapper = entity_metadata_wrapper('node', $node);
$node_wrapper->field_myfield->set(1);
$node_wrapper->save();

```

Entity metadata wrapper is a great way for set or read values of fields in the node!
> 42 votes

# Answer
Try `field_attach_update()` function.

```
$node = node_load($nid); // $nid is the function's parameter
$node->field['field_myfield'][LANGUAGE_NONE][0]['value'] = 1;
field_attach_update('node', $node);

```

It will update the field's value and it performs better than `node_save`.
> 11 votes

# Answer
```
$node = node_load($nid);
$field_language = field_language('node', $node, 'field_myfield');
$node->field['field_myfield'][$field_language][0]['value'] = 1;
node_save($node);

```
> 6 votes

# Answer
If you want to update only field value (without updating node metadata about updated time, revisions) use function `field_attach_update()`.

Example:

```
$node = node_load($nid);
$field_language = field_language('node', $node, 'field_myfield');
$node->field_fieldname[$field_language][0]['value'] = 'some value';
field_attach_update('node', $node);

```

Sometimes additionally you might need to reset node static cache with `resetCache(array($nid))`:

```
entity_get_controller('node')->resetCache(array($node->nid));

```

Source: Saving node's fields without saving the node itself
> 5 votes

# Answer
I have just implemented this and found that this code worked for me.

```
$node = node_load($nid);
if (isset($node)) {
  $field_language = field_language('node', $node, 'field_myfield');
  $node->field_fieldname[$field_language][0]['value'] = 'some value';
  node_save($node);
}

```

Note that I when updating field\_fieldname I found that using this in line 4

```
$node->field['field_myfield'][0]['value'] = 'some value';

```

did not work.
> 2 votes

---
Tags: 7, entities
---


# Question
Title: How to remove span from rewrite result in a field view?
In a custom view I have several fields excluded from display.
I wanted to use their values within an `global:fieldset` with rewrite output option.
This works but the values are embedded in a `<span>` that I don't want, and I didn't find the way to remove it. i.e. if rewrite text use the replacement patterns \[field1\],\[field2\],\[field3\] I got as result

```
<span>field1 result, field2 result, field3 result</span>

```

instead of only: `field1 result, field2 result, field3 result`

# Answer
> 2 votes
You will need to click on the fields you excluded (one by one), click on **Style settings** and select **Customize field HTML**. Then select `-None-` under **HTML Element**. You may need to do this for Customize label and Customize wrapper. Click Apply. Don't forget to click Save.

**EDIT:** Since you have now clarified that you are using Views Fieldsets (and for next time, be sure to provide **ALL details** about your problem!), I believe you will need to override the default tpl.php file for the Views Fieldset fields.

Views Fieldset provides default tpl.php files inside the `template` folder inside the module folder (usually found in `/sites/all/modules/views_fieldset`. You need to copy the content of that file, save it in your theme's template folder and modify it. Follow the steps in this general tutorial (you will need to adapt it to your problem) to **override** the default template for Views Fieldset fields. Good luck.

---
Tags: 7, views, entities
---


# Question
Title: In a menus's render array, where are the render arrays for the second-level options?
I have a render array made by calling `menu_tree_output` on my main menu. The menu contains first-level options, naturally enough, and some of these have second-level children. I need to reformat my menu so that when output by `render` or `drupal_render`, each list of second-level options appears not just as `<ul>` and `<li>` elements, but as a more complicated chunk of HTML containing the links. (These chunks will implement dropdown menus with icons and subgroup headings inserted between and above links.) Reading http://themery.com/book/export/html/100 , "Using the Render API", I thought render arrays would be ideal. I could transform each list and shove the result back into the render array as raw markup. However, I'm having trouble finding the render arrays that represent the second-level menu options.

Putting my problem in more abstract terms, I've got a menu render array holding a list of lists *Li*. Each *Li* is a `<ul>` containing `<li>` and `<a>` elements. In the render array, I want to replace each *Li* by *f( Li )*, where *f* is a PHP function that I'll implement. It will insert HTML between *Li*'s elements and around them.

I started by doing

```
  $tree = menu_tree_all_data( 'main-menu' );
  $options = menu_tree_output( $tree );

```

The second line is because, as explained in https://groups.drupal.org/node/145064 , "Geek question - Why is there no render array for links in D7?", menus are not render arrays, and need to be converted to such.

So `$options` is a render array. I first tested that I understood its structure well enough to loop over it and print the first- and second-level options. Here's my code:

```
  foreach ( $options as $option ) {
    $title = $option[ '#title' ];
    if ( strlen( $title ) != 0 ) {
      print $title . '<BR>';
      $sub_options = $option[ '#below' ];
      if ( count( $sub_options ) > 0 ) {
        foreach ( $sub_options as $sub_option ) {
          $sub_title = $sub_option[ '#title' ];
          if ( strlen( $sub_title ) != 0 )
            print ' &nbsp' . $sub_title . '<BR>';
        }
      }
    }
  }

```

This seems to work, displaying the list:

```
  OPTION 1
  OPTION 2
    Sub-option 2.1
    Sub-option 2.2
  OPTION 3
    Sub-option 3.1

```

(The above are the names of my test options — not very interesting, I know.)

A problem I had when writing the code is that I couldn't find a spec of exactly what a menu's render array has in it. But from `dpm` and the source of `menu_tree_output`, I gathered that an option's name is in its `#title` element, and that its sub-options are in its `#below` element, which is an array.

Actually, that wasn't quite enough. Some options had empty titles which I had to skip: hence my tests on the length of `$title` and `$sub_title`. But I seemed to be going in the right direction, so I then tried another loop. This one was intended, just as a proof of concept, to add a prefix and a suffix to each list of options: both the first-level list and the second-level lists.

Here's that code:

```
  foreach ( $options as $option ) {
    $title = $option[ '#title' ];
    if ( strlen( $title ) != 0 ) {
      $sub_options = $option[ '#below' ];
      if ( count( $sub_options ) > 0 ) {
        $sub_options[ '#prefix' ] = 'Level 2 prefix';
        $sub_options[ '#suffix' ] = 'Level 2 suffix';
      }
    }
  }
  $options[ "#prefix" ] = "Level 1 prefix";
  $options[ "#suffix" ] = "Level 1 suffix";
  print( drupal_render( $options ) );

```

Apparently, it's a feature of all render arrays that if you set their `#prefix` and `#suffix` elements and then render and display them, you'll see the prefix appear before the output and the suffix after it. So I thought this would be a good test. The first-level prefix and suffix do indeed appear, enclosing the menu itself.

But the second-level ones don't. Why? The source of `menu_tree_output` contains the line

```
$element['#below'] = $data['below'] ? menu_tree_output($data['below']) : $data['below'];

```

which certainly looks as though the `#below` elements should become render arrays. So why aren't `#prefix` and `#suffix` working on them?

By the way, I clear my cache before each test with `drush cc all`. If it matters. And my code is running in a `page.tpl.php` which I've written from scratch as part of a new theme. So there shouldn't be any interference from an existing theme.

# Answer
> 1 votes
As Clive pointed out, I should have assigned my sub-arrays by reference. So my code should have been:

```
  foreach ( $options as &$option ) {
      $title = $option[ '#title' ];
      if ( strlen( $title ) != 0 ) {
        $sub_options = &$option[ '#below' ];
        if ( count( $sub_options ) > 0 ) {
          $sub_options[ '#prefix' ] = 'Level 2 prefix';
          $sub_options[ '#suffix' ] = 'Level 2 suffix';
        }
      }
    }
    $options[ "#prefix" ] = "Level 1 prefix";
    $options[ "#suffix" ] = "Level 1 suffix";
    print( drupal_render( $options ) );

```

That worked, printing the first- and the second-level prefix and suffix.

Armed with the knowledge that I was on the right track, I modified my code as below. Each loop cycle renders one list of sub-options and stores the resulting HTML. It then encloses it in a \
 tag, just as a demo. And it then puts the result back as raw markup. Rendering the entire menu will then display that markup, so that all my sub-options are enclosed in a table border and headed with a caption. In real life, they'd be a hidden div which reveals when you hover over it, displaying a fancy sub-menu.

One subtlety is that I had to call `show`, because the line `$rendered_sub_options = drupal_render( $sub_options );` flags those sub-options as already printed, so that the final call to `render` would ignore them unless I unset the flag.

```
  foreach ( $options as &$option ) {
    $title = $option[ '#title' ];
    if ( strlen( $title ) != 0 ) {
      $sub_options = &$option[ '#below' ];
      if ( count( $sub_options ) > 0 ) {
        $rendered_sub_options = drupal_render( $sub_options );
        $rendered_sub_options = entable( $rendered_sub_options );
        show( $sub_options );
        $sub_options[ '#markup' ] = $rendered_sub_options;
        $sub_options[ '#type' ] = 'markup';
      }
    }
  }

  function entable( $html )
  {
    return "<table border=1>" .
           "<tr><td>SUB-OPTIONS</td></tr>" .
           "<tr><td>$html</td></tr>" .
           "</table>" ;
  }

  print( drupal_render( $options ) );

```

---
Tags: 7
---


# Question
Title: What are the technical implications of choosing asynchronous or synchronous billing cycle?
When using the Commerce License Billing module the "`/admin/commerce/config/license/billing-cycle-types/manage/monthly`" page clearly states:

> Asynchronous
>
> Determines whether the billing cycle starts at the time of purchase, instead of starting at the beginning of the calendar period. For an order placed on Jan 5th, a monthly synchronous billing cycle would start on Jan 1st 00:00 and end on Jan 31st 23:59:59, while a monthly asynchronous billing cycle would start at the time of purchase (Jan 5th) and end a month later (Feb 5th).

I wonder what are the technical implications of choosing asynchronous or synchronous billing cycles. I mean if I go with synchronous billing period will all the recurring services be renewed on 1st of each month at the same time? Won't that make it difficult for cron?

Synchronous billing cycle seems very convenient and more appealing to the end-customers, however my main concern is that Drupal cron might stack in posterity with growing number of orders for the recurring services in the system.

Could anybody elaborate on this to confirm or mitigate my concern?

# Answer
The "implications" are that it mimics how you want to charge your customer for access. If you want to provide a revolving 30-day access to some content, an asynchronous billing cycle might make the most sense. Whereas if you're charging for a service and want everyone to have the same billing cycle, then you'd end up prorating the first month to get to the first point of your billing cycle.

At a technical level, cron should be running in daemon mode (or at least every 5-10 minutes) since your license provisioning requires it. You shouldn't have to do anything different.
> 1 votes

---
Tags: commerce
---


title: Drush get all non-required modules

text:
# Question
Title: Drush get all non-required modules
In Drupal, the Module Filter module adds four search filters to /admin/modules:

1. Enabled
2. Disabled
3. Required
4. Unavailable

If "Required" is unchecked, the admin page will only show modules that are not dependencies of any other module. I know that `drush pm-list --status=Enabled` will show only the enabled modules, but it doesn't filter out modules that are required by other modules.

Is there a way to do the same thing using drush?

# Answer
> 2 votes
Drush does not support such a feature, but it sounds like it would be an interesting enhancement.

---
Tags: 7, drush
---


# Question
Title: Services 3 Session authentication CSRF Validation with Persistent Log in
I am trying to use Services 7.x-3.11, the latest stable available to authenticate and access Drupal 7.34. Accessing from mobile devices with Native coding. I want to keep the user authenticated forever. Is it possible?

Here is the workflow i am following.

**First launch of app**

1. POST `/services/session/token` to retrieve CSRF Token
2. POST `myendpoint/system/connect` with *X-CSRF-Token* header
3. IF not Logged In Try Log in `/myendpoint/user/login`
4. Log in Success and keep `session_name=sessionid` in Cookie Varible

**Future Launches**

1. POST `/services/session/token` to retrieve CSRF Token
2. POST `myendpoint/system/connect` with *X-CSRF-Token* header along with previousely saved `session_name=sessionid` as *Cookie* Header

From this point I am getting **\["CSRF validation failed"\]** message. Am I missing something? Is the workflow correct?

# Answer
Evidently the workflow has been simplified. I make a single call to `/user/login`. Here is an example:

```
{
  "method": "POST",
  "url": "http://HOSTNAME/SERVICE_PATH/user/login",
  "headers": {
    "Content-Type": "application/json",
    "Accept": "application/json",
    "Connection": "keep-alive"
  },
  "json": {
    "username": "USERNAME",
    "password": "PASSWORD"
  }
}

```

which returns:

```
Response: {
  "sessid": "waroHcB4h8rbU0yhZjh-zGLAquZYlpayC_kB38gx--I",
  "session_name": "SESSb4d5ba755bb4eb727d982993490e6681",
  "token": "MHT4hmagxHgf0lOYlkENGlTZGk2AZ96G3p3ZCCc2kvo",
...
}

```

Now the cookie is created by concating the session\_name and sessid with the equal sign separating them. The `X-CSRF-Token` header is simply the `token` in the response. All future requests will reuse the `X-CSRF-Token:` and `Cookie: headers:`

Here is an example of a user profile request:

```
{
  "method": "POST",
  "url": "http://http://HOSTNAME/SERVICE_PATH/user/profile",
  "headers": {
    "Content-Type": "application/json",
    "Accept": "application/json",
    "Connection": "keep-alive",
    "X-CSRF-Token": "MHT4hmagxHgf0lOYlkENGlTZGk2AZ96G3p3ZCCc2kvo",
    "Cookie": "SESSb4d5ba755bb4eb727d982993490e6681=waroHcB4h8rbU0yhZjh-zGLAquZYlpayC_kB38gx--I"
  }
}

```

Short answer: call `/user/login` once, set and reuse the **X-CSRF-Token:** and **Cookie:** headers for all future REST calls.
> 2 votes

# Answer
Don't request for new CSRF token use the returned one for previous request.

You will find it in a key named `token` in the result returned.

Just request a new csrfCSRF token for the first time only.
> 1 votes

---
Tags: services, sessions, cookies, csrf
---


# Question
Title: How to speed up Reference module's Views plugin?
I have a 'Node reference' field via the References 7.x-2.1 module which is pointing at a View which returns up to ~5000 results. I'm also exposing this field as a filter in a separate View. The issue that I'm having is that these ~5k results are taking up to 20s to render, despite only 10 rows being shown to the browser.

Judging by XHProf's results, I thought the best way to do this was to cache the rendered results of the referenced View. That brought the time for `references_plugin_display::render` down from 20s down to 10s, but that still seems like a long time. The References module doesn't seem to have documentation.

Is there a way to skip rendering 'Node reference' options, or to generally speed this process up? If the solution is to change modules, is there a migration path from D6 References fields to the new module in D7?

# Answer
> 0 votes
I wound up replacing references\_plugin\_style with a custom, bare-bones plugin style in `my_references_plugin_style.inc`:

```
/**
 * @file
 * Handler for my_references_plugin_style.
 */
class my_references_plugin_style extends references_plugin_style {
  function render() {
    if (!empty($this->options['grouping'])) {
      throw new Exception(t('References list (fast) does not support grouping.'));
    }

    $options = $this->display->handler->get_option('references_options');

    // Play nice with View UI 'preview' : if the view is not executed through
    // _*_reference_potential_references_views(), just display the HTML.
    if (empty($options)) {
      // "Render" rows quickly
      foreach ($this->view->result as &$row) {
        $row = $row->node_title;
      }

      $function = new ReflectionMethod('views_plugin_style', 'render');
      return $function->invoke($this);
    }

    // Foreach supposedly has better performance than array_map
    // @see http://stackoverflow.com/questions/18144782/performance-of-foreach-array-map-with-lambda-and-array-map-with-static-function
    $results = array();
    foreach ($this->view->result as $input) {
      $results[$input->nid] = array(
        'rendered' => $input->node_title,
        'group' => '',
        'title' => $input->node_title,
      );
    }

    return $results;
  }
}

```

Then registering it with:

```
/**
 * Implements hook_views_plugins().
 *
 * references.module's references_style plugin was way too slow (110s to render ~5k rows),
 * so fork that style plugin and strip most of the functionality away.
 */
function my_views_plugins() {
  $plugins = array(
    'style' => array(
      'my_references_style' => array(
        'title' => t('References list (fast)'),
        'help' => 'Returns results as a PHP array of names + rendered rows. (Less bloat than "References list").',
        'handler' => 'my_references_plugin_style',
        'theme' => 'views_view_unformatted',
        'uses row plugin' => FALSE,
        'uses fields' => TRUE,
        'uses options' => FALSE,
        'uses grouping' => FALSE,
        'type' => 'references',
        'even empty' => TRUE,
      ),
    ),
  );
  return $plugins;
}

```

And including the .inc file in my module's .info file:

```
files[] = views/my_references_plugin_style.inc

```

Finally, I went to my Views' UI and updated the Formatter to the new "References list (fast)" format.

---
Tags: views, nodes, performance
---


# Question
Title: How can I rewrite the output of image field to become a div with this image as a background image?
I have a view to display a content that have an image field, and I need to display this image as a background image of a div so I can apply some CSS on it.

what I tried to do is to rewrite the output of this field using twig to be like this:

```
<div class="page-image" style="background-image: url({{ field_image }});">
</div>

```

the problem is that Drupal strips style attribute so the output will be like this:

```
<div class="page-image">
</div>

```

In D7 I used to fix this kind of issues by overriding the template for the specific field, but I couldn't figure out what is the name of the needed template in D8. when I enabled twig debug it turned out that the field is using the template file `views-view-field.html.twig` which is the default template for all fields in views, but I couldn't find the needed template name for this specific field in this view, I tried to rename it like in D7 to be `views-view-field--page-image--field-image.html.twig` (the view name is page\_image) but it didn't work out.

any suggestions?

# Answer
> 0 votes
Set all fields to "Exclude from display", add a "Global: Custom text" field and then build your html there using the "Replacement patterns" available.

I assume this still works in drupal 8.

# Answer
> 0 votes
While I haven't done that in Views just yet, I did have to put a image as background-image in the Page Title template. The same technique might work in this case as well.

In the preprocess, I did this :

```
$variables['header_attributes'] = new Attribute(array(
  'style' => "background-image: url('" . $headerImage->toString() . "');",
));

```

And then, in `page-title.html.twig`, I just did this ( headerClass is just another class I add in the Twig template itself :

```
<header {{ header_attributes.addClass(headerClass) }}>

```

And this works fine. My style attribute doesn't get stripped off.

Don't forget to add `use Drupal\Core\Template\Attribute;` at the top, if you want to give this a try.

---
Tags: views, 8, theming
---


# Question
Title: How to use data in fields from one node to create a new node of different content type?
I have a content type called "*Submit a photo*" where anonymous users can upload a photo alongside with their name, email and short description. And I have another content type where an admin uploads images and publishes them as "*Looks*", and Looks are more complicated content type, with image tags, categories ...

Than I have a view which lists all of the submitted images so that an editor can pick and create new node "Look" using existing fields. But I'm looking for a way to somehow pre populate fields in that new content type with fields of "Submit a photo".

So editors can review all the images that are submitted by anonymous users. If they like one, they click “Add new Look” or something like that, which opens a new “Add Look” form using that image.

Should I look at nodereference or something like that?

# Answer
> 2 votes
Have a look at the Node\_convert module. From it's project page:

> adds a menu tab "Convert" on the node view page, i.e. node/1/convert, which gives the ability to convert the node from its current node type to another node type. The module provides the means to transfer all the field values of the current node type into fields on the destination node type, or discard them.

I'm using Node\_convert already for long time, works great. It allows for implementing a lifecycle (or workflow?) to start from a node that is only just something like an idea (or suggestion, question, issue, abstract, etc). So that would be like your "Submit a photo" content type. When the node's content evolves (read: the more effort/details added to it), I convert its content type to finished products like (eg) a recipe, a redbook (already from my Drupal 6 days a few years ago). In your case it'd be the "Look" content type.

By combining it with an access module such as Content Access (my preference) or Taxonomy Access Control you can make it more restrictive to give access to it. E.g. public (anybody) to start from, then "authenticated", and in the end only for roles such as "subscribers", "students", etc.

# Answer
> 0 votes
Another way is using the Rules module like so:

* Event: after saving new node
* Conditions : content type
* Action : create new node of "look", fetch images from "sumbit a photo" , update the created node.

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


# Question
Title: How not show in a View certain taxonomy items if there are no associated nodes?
I'm using a View to display all the items from a taxonomy term list I've setup. The taxonomy term is used as a field in my nodes. That's all fine.

Now, I created another view called 'all categories' that displays all the taxonomy terms (each term is only displayed once). When a user clicks the term they automatically go to the term page and see the nodes that are using that term.

The problem is that some of the terms haven't yet been used by any nodes so when the user clicks the term name for those it just takes them to a page that says \[name\] at the top with no other information. I'd rather just hide any categories that have no associated nodes, but I don't know how to do it. I'd also be open to other suggestions for alleviating this issue.

*Note: if a term DOES have nodes associated with it and you click the term it takes you to a page with the term as the title and the associated nodes listed below the title.*

Here's the settings I have for the 'All categories' view:

```
Show: Fields
Fields: Taxonomy term: Name (link this field to its taxonomy term page)
Filter Criteria: Taxonomy vocabulary: Machine name (=Category)

```

# Answer
Easiest way is to add a relationship in the view to the node type that contains the taxonomy term reference field and make it mandatory. This will force Views to only return the taxonomy terms that are present on a node.

1. Edit your view
2. Expand "advanced" (if its not already expanded)
3. Click "Add" beside Relationships
4. Click "Taxonomy term: Representative node"
5. Click "Require this relationship"
6. Click "Apply"

Note: I used the representative node vs the content with term option for performance reasons, the former only retrieves a single node for each term vs matching every term to every node
> 4 votes

# Answer
Go to the **Advanced** Settings in the view and click in the **Theme: Information**

Search the **Field Taxonomy term: Name (ID: name)** section and select a name, in my case was **views-view-field--temp.tpl.php**

Go to the folder `YOUR_SITE/sites/all/modules/views/theme` and copy to your theme folder the file `views-view-field.tpl.php` and rename it to **views-view-field--temp.tpl.php**

Edit your new file `views-view-field--temp.tpl.php` and put inside only this code to eliminate the link:

The taxonomy\_select\_nodes() function will return an array of nids matching the query.

```
<?php

if(count(taxonomy_select_nodes($row->tid)) > 0) {
  print $output;
} else {
  print $row->taxonomy_term_data_name;
}

?>

```

In the View go to the bottom of the Information window and click **Rescan template files** and click **OK**, then save your View.

And go to see your result:

My example:

If you don't want to show the taxonomy items without associated nodes use this code:

```
<?php

if(count(taxonomy_select_nodes($row->tid)) > 0) {
  print $output;
}

?>

```

And your output will be this:

PS: You must copy your `.tpl` file to the folder of your active theme, then rename in this folder.
> 4 votes

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


title: Start next batch process automatically

text:
# Question
Title: Start next batch process automatically
Is it possible to start next batch\_set() after finishing first one? I've some import functionality which includes 4 steps. The next step takes data processed from first batch process so this is consecutive process which needs to be run one after one.

# Answer
> 1 votes
I have done this before using Core drupal tools. Although I suspect different than your current approach.

I use a drupal Queue. and I fill it with items:

```
                                                    Queue
          Task1Items              Task2Items          Task3Items              Task4Items
    [---item1---item2---item3|item4---item5---item6|item7---item8---item9|item10---item11---item12]

```

I put all the tasks, in the ordering for the various `steps` of your task into a Queue. Then be sure to use a Drupal Reliable Queue:

> There are two kinds of (default) queue backends available: reliable, which preserves the order of messages and guarantees that every item will be executed at least once. The non-reliable kind only does a best effort to preserve order in messages and to execute them at least once but there is a small chance that some items get lost. For example, some distributed back-ends like Amazon SQS will be managing jobs for a large set of producers and consumers where a strict FIFO ordering will likely not be preserved. Another example would be an in-memory queue backend which might lose items if it crashes.

After inserting all the items. Your batch call simply iterates over the queue you've populated. Use something like Ultimate Cron to setup a group of task workers, or Background Process, or Ultimate Cron Queue Scalar to speedup your workload if you want.

Another handy module to view your queue visually is the Queue UI module. As the core Queue API is a developer API and has no UI by itself. Don't want to write php code to create/manage a queue -- look at Rules Queue.

---
Tags: 7, batch-operations
---


# Question
Title: How to remove default divs on views result?
I'm trying to add use bootstrap modal and bootstrap slideshow to show a view but the slideshow doesn't work the way I want it because of the default generated divs by Views module. Here is the code:

```
    <div id="block-views-custom-package-form-venue-option" class="block block-views">
        <div class="content">
            <div class="item active">
                <div class="carousel-caption">
                    <h4>heading 1</h4>
                    <p>This is the description.</p>
                </div>
            </div>
            <div class="item">
                <div class="carousel-caption">
                    <h4>heading 2</h4>
                    <p>This is the description.</p>
                </div>
            </div>
        </div>
    </div>

```

I want the result of the view supposedly like this:

```
<div class="item active">
        <div class="carousel-caption">
        <h4>heading 1</h4>
        <p>This is the description.</p>
    </div>
</div>
<div class="item">
    <div class="carousel-caption">
        <h4>heading 2</h4>
        <p>This is the description.</p>
    </div>
</div>

```

Only the output of the view with no views default generated divs.

# Answer
Go to the **Settings** of your **Fields** and uncheck the Option: **Provide default field wrapper elements**
> 2 votes

# Answer
Use semantic views module to strip tags

> This Views plugin makes unformatted styles, field row styles and other output more readily configurable without needing to override template files. Instead of overriding row style templates for views where you want to specify different HTML elements (tags) and class attributes, you can specify these inside the Views UI and avoid overriding templates for each view.
> 1 votes

# Answer
You can markup anything you'd like in views theming information. See the attached picture below.

Create a .tpl file using the "Display output". The highlighted ones are being used or the default ones. See below on how to do it:-

* Create a .tpl file using the theme suggestions in the display output eg. "views-view--machinename--page.tpl.php".
* Click the "Rescan template files". (The views-view--machinename--page.tpl.php will be highlighted when you've created it properly).
* Click the "Display output" link.
* Copy the opening php tags until at the end of its php tags, then paste that in "views-view--machinename--page.tpl.php".
* Click the OK button, then Flush all caches.
> 1 votes

---
Tags: views, theming
---


title: Create file through services

text:
# Question
Title: Create file through services
I've been trying to create and update users and their pictures through REST calls using the services module. So far, I've got creating and updating users to work, but creating files to set their profile pictures still doesn't work.

I try to do a POST request to my API endpoint (http://www.domain.com/api/api\_name/file), with the following data:

```
    $data = array(
        'file' => base64_encode($file),
        'filename' => $filename,
        'filepath' => 'public://' . $filename
    );

```

I POST this using CURL, with the exact same settings (apart from the API endpoint) as I'm using to create a user, which is working. However, I'm getting a HTML 500 as a response, with no response contents otherwise. The following error is logged in the Drupal error log:

```
Notice: Undefined property: stdClass::$fid in file_entity_access() (regel 1661 van /home/enschede/domains/aegee-enschede.nl/public_html/sites/all/modules/file_entity/file_entity.module).

```

The function that it errors on, `file_entity_access`, says that its `$file` parameter will either be an object, or a string with the file type (e.g. `"image"`) if it is a create action. Apparently, it receives an object, so the create action is not executed properly on the server.

However, at this point I'm stuck. I can't find where these calls are coming from on the server, and I can't find anything I should change in the POST request. The fields I'm posting are the same as a tutorial I've followed. I'm posting the following fields to create a user, with the exact same CURL options otherwise:

```
    $initialData = array(
        'name' => 'test.user',
        'mail' => 'bogus_email@provider.com',
        'pass' => 'waytoolongboguspassword',
        'status' => 1
    );

```

# Answer
> 0 votes
If you need to create/update a file alongside the entity posted JSON you need to create the file in your code like:

```
//Implements of hook_services_request_preprocess_alter().
function my_module_services_request_preprocess_alter($controller, $args, $options) {

switch ($controller['callback']) {
case '_user_resource_create':
case '_user_resource_update':
  if (isset($args[1]['avatar'])) {
    $data = base64_decode(trim($args[1]['avatar']));
    $finfo = finfo_open();
    $mime_type = finfo_buffer($finfo, $data, FILEINFO_MIME_TYPE);
    finfo_close($finfo);
    // get file type png. jpg
    $ext = $mime_type ? str_replace('image/', '', $mime_type) : 'png';
    $file_name = str_replace(' ', '-', $args[1]['name']);

    $file = file_save_data($data, 'public://users/' . $file_name . '.' . $ext, FILE_EXISTS_REPLACE);
    $args[1]['field_field_user_picture'] = array(
      'fid' => $file->fid,
      'width' => 100,//set your own
      'height' => 100,//set your own
      'alt' => $args[1]['name'],//set your own
      'title' => $args[1]['name']//set your own
    );
  }
}

```

By that way you could create any image field with any entity easily.

From the best practice I advice you to use the module user picture field that let's you deal with the user picture as a field so you could have it in views with different formats instead of just have the file id.

Another tip is to send the image format as It won't be possible to get the mime type from the json decoded file source.

Sure you still be able to create a file through file services but I think you have to make the post request format **www/url-encoded** instead of json

---
Tags: services, 8
---


# Question
Title: Register nodes seen in a view as not "new"
I have a view of nodes, the only place those nodes will be seen is in the view - never as individual entities. These are short "updates". When someone has seen an update, I no longer want it marked as "new" (as in drupal's 'content: has new content' functionality).

Is it possible to trigger whatever it is that makes entities 'read', but when that node is loaded into to a view on a page the user is viewing?

# Answer
The `New` or `Updated` mark is generated by a simple theme function (`theme_mark`) which can be overriden. Normally you would do that in your `template.php` but since this theme function is used in the admin theme, that's not gonna work.

A workaround for this is to add your own theme function to a custom module, like this:

```
/**
 * Implements hook_mark().
 */
function yourmodule_mark($variables) {
  // Always return an empty string.
  return '';
}

```

Now, we need to add this function to the theme registry like this:

```
/**
 * Implements hook_theme_registry_alter().
 */
function yourmodule_theme_registry_alter(&$theme_registry) {
  // Check if the default theme function of mark exists
  // and override it with our own theme function.
  if (isset($theme_registry['mark']['function']) {
    $theme_registry['mark']['function'] = 'yourmodule_mark';
  }
}

```

**Clear your cache** and your done.

You'll find the original theme function here in the Drupal docs.

Note that this code will permanently override the output of this function where ever it is used.
> 0 votes

---
Tags: views
---


# Question
Title: Flag module integration with Message module
I am using Rules, Message, Message Notify and Flag modules. I added a message to the activity stream when user flags a node as "**Favorite**".

My problem is I am getting notification, but the node that was flagged seems to be missing from the message entity. Please guide for the steps, or where I may be wrong

**UPDATE:** Adding rules in export format for better understanding and reference. In mail being send through rule, every token is working perfectly, but not in message added to activity stream.

```
{ "rules_user_likes_a_node" : {
    "LABEL" : "User likes a node",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "flag" ],
    "ON" : { "flag_flagged_group_flag" : [] },
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "node", "value" : [ "flagged-node" ] },
          "PROVIDE" : { "variable_added" : { "node" : "Added variable" } }
        }
      },
      { "mail" : {
          "to" : [ "flagged-node:author:mail" ],
          "subject" : "[flagged-node:content-type] [flagged-node:title] est aim\u00e9",
          "message" : "Hello [flagged-node:author:name],\r\n\r\n\r\n[flagging-user:name] loved[flagged-node:content-type] [flagged-node:title]",
          "language" : [ "" ]
        }
      },
      { "entity_create" : {
          "USING" : {
            "type" : "message",
            "param_type" : "commons_activity_streams_user_likes_a_node",
            "param_user" : [ "site:current-user" ]
          },
          "PROVIDE" : { "entity_created" : { "message" : "Created entity" } }
        }
      },
      { "data_set" : { "data" : [ "flagged-node" ], "value" : [ "flagged-node" ] } }
    ]
  }
}

```

# Answer
> 3 votes
Actually, I tried "Set a data value" action, but was setting wrong variables in it. Using it right way and adding "Save entity" action (I think without this also it may work fine now) worked for me.

Following is the rules' export format in case someone need it in future:

```
{ "rules_user_likes_a_node" : {
    "LABEL" : "User likes a node",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "flag" ],
    "ON" : { "flag_flagged_group_flag" : [] },
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "node", "value" : [ "flagged-node" ] },
          "PROVIDE" : { "variable_added" : { "node" : "Added variable" } }
        }
      },
  { "mail" : {
      "to" : [ "flagged-node:author:mail" ],
      "subject" : "[flagged-node:content-type] [flagged-node:title] est aim\u00e9",
      "message" : "Hello [flagged-node:author:name],\r\n\r\n\r\n[flagging-user:name] loved[flagged-node:content-type] [flagged-node:title]",
      "language" : [ "" ]
    }
  },
      { "entity_create" : {
          "USING" : {
            "type" : "message",
            "param_type" : "commons_activity_streams_user_likes_a_node",
            "param_user" : [ "site:current-user" ]
          },
          "PROVIDE" : { "entity_created" : { "message" : "Created entity" } }
        }
      },
      { "data_set" : {
          "data" : [ "message:field-target-nodes:0" ],
          "value" : [ "flagged-node" ]
        }
      },
      { "entity_save" : { "data" : [ "message" ] } }
    ]
  }
}

```

---
Tags: 7, rules, flags, message-subscribe
---


# Question
Title: Getting the nodequeue id from the nodequeue name?
I want to get the nodequeue qid from the nodequeue name.

Suppose I have a node queue with the name of "Slider". I want a function so that I pass it the name of the nodequeue and It returns the qid or sqid of that nodequeue.

Is it possible?

# Answer
I don't think there's an API function for it but writing your own should be fairly straightforward:

```
function nodequeue_load_queue_by_name($name) {
  $query = db_select('nodequeue_queue', 'nq')
    ->fields('nq', array('qid'))
    ->fields('nsq', array('sqid'))
    ->condition('nq.name', $name);

  $query->join('nodequeue_subqueue', 'nsq', 'nsq.qid = nq.qid');

  $result = $query->execute()->fetchObject();

  // Decide whether you want to use $result->qid or $result->sqid based on your
  // business logic, then return it.
  $return_val = a_function($result);

  return $return_val;
}

```

That comes straight from memory so excuse any small mistakes, but I'm pretty sure it'll work.
> 1 votes

# Answer
There is a function of the same name as in the excepted answer included in current versions of the nodequeue module.

```
$queue = nodequeue_load_queue_by_name($name);

```

It returns the queue definition, or an empty array if no queue was found with the given machine name. So the id would be found at:

```
$queue->qid;

```
> 2 votes

# Answer
You can check the table existance.

```
$table = db_table_exists('nodequeue_queue');<br>
  $table1 = db_table_exists('nodequeue_subqueue');<br>

  if ($table1 && $table) {<br>
    $query = db_select('nodequeue_queue', 'nq')<br>
      ->fields('nq', array('qid'))<br>
      ->fields('nsq', array('sqid'))<br>
      ->condition('nq.name', $queue_name);<br>

    $query->join('nodequeue_subqueue', 'nsq', 'nsq.qid = nq.qid');

    $result = $query->execute()->fetchObject();
  }

```
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Limit Entity Reference to published nodes
Here is a content type structure called Bill :

> * Bill\_ID =\> Int
> * Bill\_Date =\> Date
> * Services =\> Entity Reference (Target Type : Node , Target Bundle : Service , Widget : Auto-complete)

The only problem is that the end user shouldn't be allowed to make a reference to an unpublished Service.

So how can we limit user to only make a reference to published contents ?

# Answer
Create a view with entity reference display. Click add and in the drop down you will see entity reference.

Now create a view and create a filters normally as you do. Now go to your content type services field settings and click views instead of simple selection

Select the views you created and your options will be limited to the result of the view.
> 5 votes

---
Tags: 7, entities
---


title: Custom CSS and JavaScript

text:
# Question
Title: Custom CSS and JavaScript
How to add custom css and javascript file in Drupal 8.

# Answer
> 1 votes
there are several ways to add js/css, one example:

**Attaching custom javascript or css in your theme**

Add a library to yourtheme.libraries.yml in your theme folder:

```
  yourlib:
  version: 2.6
  css:
    theme:
      css/your.css: {}
  js:
    js/your.js: {}
  dependencies:
    - core/jquery

```

The paths given are relative to your theme. Dependencies is optional, you can force loading of additional js like jquery.

Now to add this library to your theme go to yourtheme.info.yml and add it like this:

```
    libraries:
      - yourtheme/yourlib

```

---
Tags: javascript, theming
---


# Question
Title: Search api solr result reordering on field value
I'm using search\_api\_solr and search\_api\_location. I have a view with exposed filters to perform geolocation searches.

I'm trying to reorder search result from a solr query based a referenced node's field. My question is witch hook to use, **where i can access node fields and reorder the results.**

I already tried:

* hook\_views\_pre\_render()
* hook\_views\_post\_execute()
* hook\_views\_post\_render()
* hook\_views\_pre\_view()

but reordering is effectless or i don't have access to node fields. I'm doing something like this:

```
$results = &$view->result;
$to_search_top = array();
foreach ( $results as $i => $capacity){
  if ((int) $capacity->{_entity_properties}['field_free_capacity_company_ref:field_last_review'] > 1) {
    unset($results[$i]);
    $to_search_top[] = $capacity;
  }
}

foreach ($to_search_top as $capa) {
  array_unshift($results, $capa);
}

```

Thank

# Answer
Finaly i was only able to solve this with hook\_preprocess\_views\_view\_table().

```
$to_search_top = array();
foreach ($vars['rows'] as $index => $row) {
  if ((int) $row['field_company_review_number_1'] > 0) {
    $to_search_top[] = $row;
    unset($vars['rows'][$index]);
  }
}

// Sort reviewed by distance.
usort($to_search_top, function ($item1, $item2) {
    if ($item1['field_free_capacity_coordinates_latlon'] == $item2['field_free_capacity_coordinates_latlon']) {
            return 0;
    }
    return $item1['field_free_capacity_coordinates_latlon'] > $item2['field_free_capacity_coordinates_latlon'] ? -1 : 1;
 });

// Move to results top.
foreach ($to_search_top as $row) {
  array_unshift($vars['rows'], $row);
}

```
> 0 votes

---
Tags: 7, search, views
---


# Question
Title: How to redirect particular page after login via social networking site?
In my Drupal site I have placed a `link` in checkout page which takes to user/login. On successful login it redirects back to checkout page. For this I have used `?destination=checkout` in the url. I have achieved using form alter

```
function module_form_commerce_checkout_form_checkout_alter(&$form, &$form_state, $form_id) {
  $form['checkout_message']['#markup'] = t('<a href="/user/login?destination=/checkout">Click to login</a>');
}

```

This redirects to `login` page and then redirects back to `checkout` page, till now it works fine. I have social site login in my login page (for eg., facebook, twitter, google).

How can I redirect the user to checkout if he/she login via social sites? FYI: Above is not working for social network login.

These are the modules used for performing a social login:

# Answer
> 1 votes
You can use user\_login\_destination() for your requirement which third-party authentication modules may use to determine the proper destination after a user has been properly logged in.

```
function user_login_destination() {
  $destination = drupal_get_destination();
  if ($destination['destination'] == 'user/login') {
    $destination['destination'] = 'user';
  }
  return $destination;
}

```

You just need to change line 4 to:

```
$destination['destination'] = '<path you want to go to after login>';

```

# Answer
> 1 votes
I would use the Rules module to get this to work, using a variation of the sample rule included in my answer to "How to use the Rules module to implement a custom redirect for an outdated URL?". Here are some modifications you'd need to get it to work for your case also:

* Adapt the URLs to point to your checkout page.
* Add a Rules event specific to the social site they used to perform a login, i.e.:

By using Rules as detailed above, you probably won't need the custom code anymore that you already have (as mentioned in your question).

To make the value of the URL argument available as a new variable to Rules, you can use the Rules URL Argument module. Here is a quote about it (from its project page):

> ... provides two rules conditions based on URL arguments:
>
> * check if a URL argument is present.
> * compare the value of an URL argument.
>
> It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.

For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "*Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10*". Here is the relevant part of it:

> * add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
> * add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "`amount_from_url`".
>
> You will now be able to use the amount value as a variable "`amount-from-url`" for other actions in this rule.

**PS**: If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework, organized in 7 chapters.

---
Tags: users, redirection, authentication-authorization, social-network
---


# Question
Title: "Page not found" when accessing a custom module
I have created the custom registration module for drupal8. I define the path on routing.yml file but when access that module on browser side I got "Page not Found" message. Here the sample code.

### custom\_form.routing.yml

```
    custom_form.register:
path: '/custom_form/my_form'
defaults:
 _form: '\Drupal\custom_form\Form\Formsettings'
 _title: 'Registration page'
 requirements:
  _permission: 'view user registration form'

```

### custom\_form.module

```
error_reporting(E_ALL);
ini_set("display_errors", 1);
/**
*@file
*custom_form.module
*/
use Drupal\Core\Routing\RouteMatchInterface;
/**
* Implementation of hook_permission()
*/

function custom_form_permission() {
  return array(
    'submit custom_form' => array(
      'title' => t('Submit custom_form'),
      'description' => t('Submit the custom_form Form'),
    ),
  );
}

/**
* Implementation of hook_menu()
*/
function custom_form_menu() {
$items=array();
    $items['custom_form/my_form'] = array(
     'title'=> 'My Example Form',
     'route_name' => 'custom_form.register',
     );
    return $items;
  }

```

# Answer
As stated, YAML has very specific spacing rules.

```
custom_form.register:
  path: '/custom_form/my_form'
  defaults:
    _form: '\Drupal\custom_form\Form\Formsettings'
    _title: 'Registration page'
  requirements:
    _permission: 'view user registration form'

```

Try that spacing, and Formsettings will need to be a form controller in custom\_form/src/Form if it isn't already - you didn't link to it.

Both hook\_permission() and hook\_menu() are no longer used, so you'll want to remove them from the code base. (though I don't think they will stop it from loading properly.)
> 3 votes

---
Tags: forms, 8
---


# Question
Title: Ubercart shipping quotes are being based on total before discounts
I'm hoping someone can help with this. A site I built (www.bebeperla.com) is using Ubercart 7x-3.8 and Ubercart Discounts 7x-2.0 Alpha3.

The customer gets free shipping for orders over $80, but if they use a coupon to bring the total for the order below $80 they're still getting free shipping.

My shipping quotes are flat rate and the rules are based on a data comparison of the order:order-total. Unfortunately it's not working - it seems to be calculating the shipping from either the sub-total or the total before the coupon is applied. Any ideas? I've searched the web but I can't find an issue that matches.

# Answer
So apparently I needed a good nights sleep. For anyone else in my situation, advise your client that this is not a good idea. Why? Because you WANT the shipping module to calculate the amount of shipping on the final total WITHOUT coupons because you still need to incur the cost of shipping the items. (head smack)

For example - if I changed it to calculate shipping on the total AFTER the coupon is applied, for all the other shipping methods this might bump the customer down to a lower shipping rate - and the store owner would lose money on the shipping.

My solution - exclude free shipping from carts that contain a coupon and create a new free shipping for carts including coupons with a higher $ amount. For example instead of being $80 for free shipping it would be $100 for free shipping with carts including a coupon. It's not a perfect solution, but it's better then screwing up all the other shipping settings.
> 0 votes

---
Tags: ubercart
---


# Question
Title: How do I get the Google Analytics module settings to show up? I am unable to configure
I have installed the Google Analytics module and enabled it. But I am unable to configure the settings for it.

More specifically when I click on the configuration gear it just brings me to `Home/admin/config/system` and lists in this order: Site information - statistics - actions - backup and migrate - special menu items - cron.

In all the videos I have watched on installing this module. This page is where the Google Analytics settings tab should be.

I have also opened up the main configuration page and it brings this error message at the top. "One or more problems were detected with your Drupal installation. Check the status report for more information" It tells me Google analytics isn't configured yet. Then gives me a link to Google analytics settings. But when I click on it, it just brings me back to the page I mentioned above.

What do I do to get the Google Analytics settings tab showing up?

# Answer
> 0 votes
The path is admin/config/system/googleanalytics

There is post about this on https://www.drupal.org/node/1510436

Comment number 17 states a fix

> But after uninstalling--\> run cron--\> clear caches--\> reinstalling--\> run cron--\> clear caches the configuration page appeared, voilà!

Also don't forget to run update.php afte you install a module en clear your caches

---
Tags: google-analytics
---


# Question
Title: REST Web Services - Return all fields from Content entity association
I am currently using the latest release of Drupal 8.0 (downloaded and installed today).

I have two content types. I have a entity reference on one of the content types that references content from the other content type.

Using both the Views REST Export and the built in REST API I am unable to find a way to return the associated content entity fields. Currently what gets returned is the target\_id as well as a link to the entity. I am using the hal\_json content type.

I have scoured the Drupal docs and I am unable to figure this out. Any help would be greatly appreciated!

# Answer
> 1 votes
RESTws will retrieve your content using an Entity Metadata Wrapper. By default, this won't retrieve the referenced node. To get the nested content you'd need to write your own resource class in a custom module.

The new resource class is registered with hook\_restws\_resource\_info(). In your resource class, extend `RestWSEntityResourceController` or just implement `RestWSQueryResourceControllerInterface` (You can see the default implementation here.)

Your new resource class would look something like this:

```
class MyCustomResourceController extends RestWSEntityResourceController {

  /**
   * Override the wrapper method.
   */
  public function wrapper($id) {
    $wrapper = entity_metadata_wrapper($this->entityType, $id);
    /**Add something here to add the referenced node */
    return $wrapper;
  }

}

```

---
Tags: 8, services
---


title: Disable node summary using Page Manager

text:
# Question
Title: Disable node summary using Page Manager
There are a few modules and methods specifically for disabling / removing the node summary page (at `/node`), like Node Page Disable, but I'm wondering if there's a way to redirect or override the page using the Page Manager module.

There's a good summary of other methods on this stack exchange question and answer and this Drupal forum post. One problem I'm running into with Page Manager is that the `/node/%node` path is already in use, and I'm not sure how to set it up for just the `/node` page without any additional arguments.

# Answer
> -1 votes
Yes, you can do that with a variant. I've used that methodology on a personal project. Here are screenshots of the configuration.

The first variant (which returns a 404) checks, the node type (I have a content type called 'person'), the taxonomy terms applied to the node, and the role of the user.

---
Tags: 7, redirection, path-aliases
---


# Question
Title: How do I add the login form in page.html.twig?
I am using a subtheme from the Neato theme (in Drupal 8) and I am customizing page.html.twig.

Yesterday I performed a logout, and now I want to log in again, but the login form has disappeared.

How do I add the login form in page.html.twig? Do I need another html.twig file?

# Answer
I think your best bet is to go directly to the path '/user' where the login form will be the main contents of the page.
> 1 votes

---
Tags: theming, 8, users
---


# Question
Title: How do I place connect a template to a certain content type
As the questions says, how do I perform this and how do I render certain fields at certain spots placed in the template file?

I already got it so that everything is placed by using

> {{ page.content }}

But how do I do something like:

> {{ field\_textblock }}

In where the given input in that field would be display on the site.

# Answer
> 0 votes
I think you could use the "without" filter on the {{ page.content }} as below:

```
{{ page.content|without(field_textblock) }}

```

and then you should be able to output "field\_textblock" as you were before.

There is a good page about twig filters here https://www.drupal.org/node/2357633

# Answer
> 0 votes
You need to use the correct template for that.

The syntax changed from PHPTemplate to Twig but conceptually, everything is still pretty much the same as in Drupal 7.

Meaning, there are many, many nested templates and you need to find the right template to change what they display. The page template is just about displaying blocks/regions and the overall page wrappers.

If you want to change how a node with fields is displayed, you need to change the node template or even the field template for a given field.

To find out which template you need to overide, enable the twig debug mode. See `sites/example.settings.local.php` for instructions on how to enable "development mode" including twig debug, which will then display helpful markers around each template that tells you what template is used and what suggestions are available.

---
Tags: 8
---


# Question
Title: Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[HY000]: General error: 1 no such table:
I'm getting a strange error with my Drupal site. The error is as follows:

```
Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[HY000]: General error: 1 no such table: router: SELECT name, route, fit FROM {router} WHERE pattern_outline IN ( :patterns__0 ) AND number_parts >= :count_parts; Array ( [:count_parts] => 0 [:patterns__0] => / ) in Drupal\Core\Routing\RouteProvider->getRoutesByPath() (line 344 of core/lib/Drupal/Core/Routing/RouteProvider.php).

```

I don't know much about what's causing the error. I took a look at the file the error references, but I can't figure out what to change.

Here are the steps I took that led up to the error:

1. I started with a Drupal 7 website.
2. I deleted all of my files from the website directory. Note: The "sites" directory would not delete no matter how many times I tried.
3. I uploaded my Drupal 8 release candidate 1 hoping that that new "sites" directory would overwrite the old one.
4. I reloaded my website page and was presented with error above.

Any ideas?

# Answer
Unfortunately you've gone down the wrong path by deleting your existing site. Hopefully you have a backup you can restore from...

Drupal 8 isn't an update, it's a brand new system; you need to migrate your D7 site to it.

The docs are here, they should contain everything you need
> 0 votes

---
Tags: 8
---


# Question
Title: How to manage version control for patched contrib modules?
I got some great feedback regarding patching contrib modules.

Is there a good way to keep track of patches to contrib modules? For example, let's say I create a patch for a contrib module and submit the patch to the issue queue.

A month goes by, a new version of the module has been released (without my patch) and I get notified to update to the next version. If I keep my patch file in the module directory I think it will get wiped out when I do the automatic upgrade?

Should I move the module from sites/all/modules to sites/default/modules to prevent automatic updates?

Does anyone have a good system?

# Answer
> 6 votes
Use Drush Make. It's built into Drush 5. Your makefile will serve as not only documentation of what patches you're using, but documentation of what versions of *everything* you're using, where to download external libraries, it's practically guaranteed to be up to date, and it means you no longer have to store contrib and external code in your source code repository. Just your custom code.

Basically, you create a file that tells Drush Make what version of core to download, which contrib modules and themes to download, which external libraries to download, where to place them (you can separate contrib modules to a "contrib" subdirectory, for instance), which patches to apply (to all of those).

Drush Makefiles are used to build Drupal distributions.

Have a look at a pretty simple makefile from Discursive, and a more terse makefile from OpenOutreach.

**EDIT:** I really should include a link to at least one makefile that uses a bunch of patches and a much better example of using Drush Make on a client project: WiseDecider (check the makefiles in that install profile directory, then also go up a directory to find the rebuild.sh script that "builds" it -- downloads, patches, etc. the site and sets up symlinks and such to glue everything together. Also a disclosure: Wise Decider is a client of the Drupal shop I work for and Discursive is the open-source version of another client project of ours.

**EDIT 2:** Don't use any kind of "automatic updates" with this method. The process is:

1. Update your makefile locally
2. Rebuild the site by rerunning the build script
3. Test on your local instance of the site against a new dump of the production database (don't forget `drush updb`)
4. Deploy the updated codebase to your testing/staging server (don't forget `drush updb`) for internal QA / client QA (if applicable)
5. Redeploy the updated codebase to production (and again, don't forget to run the db update scripts).

Our deployment scripts (included in Wise Decider) use rsync and symlinks to pushing code to the remote LAMP server.

# Answer
> 0 votes
http://bitbucket.org/davereid/drush-patchfile is now a better answer to the original question. It requires an install profile, but once that's configured using drush up will attempt to reapply any patches. MUCH better than leaving copies of patches in the project directories and doesn't require running drush make to update a single project.

---
Tags: 7, updating, version-control
---


# Question
Title: How to write page.tpl.php file for bootstrap site
I have the below code in the page.tpl.php file.

```
<header id="navbar" role="banner" class="<?php print $navbar_classes; ?>">
  <div class="container">
    <div class="navbar-header col-xs-12">
      <?php if ($logo): ?>
      <a class="logo navbar-btn pull-left col-xs-12 col-sm-12 col-md-2 col-lg-2" href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>">
        <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />
      </a>
      <?php endif; ?>
............
  </div>
</header>

```

As you can see, I have written bootstrap class col-xs-12 inside a class:

```
<a class="logo navbar-btn pull-left col-xs-12 col-sm-12 col-md-2 col-lg-2" ....   </a>

```

Then I uploaded an image whose original size is 658 x 318 (Appearance \> bootstrap sub theme \> Logo image ).

When I visit my using in mobile phone, I still see the logo in original size. I thought me adding col-xs-12 will instruct bootstrap to fit the image in 12 column grid system of my mobile screen. Do you know why image is still in original size even though I added the bootstrap class col-xs-12?

---

**#Test1 - Passed**

In tpl file \> header region \> I have added img-responsive class:

"\>

```
  <div class="container">
    <div class="navbar-header col-xs-12">
      <?php if ($logo): ?>
      <a class="logo navbar-btn pull-left col-xs-12 col-sm-12 col-md-2 col-lg-2" href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>">
        <img src="<?php print $logo; ?>" class="img-responsive"  alt="<?php print t('Home'); ?>" />
      </a>
      <?php endif; ?>
.....

</div>
</header>

```

After that, I have uploaded the logo (appearance \> bootstrap \> Upload image...). When I view the page in mobile, I see that image was responsive. This is good.

**#Test2 - Failed**

In tpl file \> main container region \> I have added img-responsive class:

```
<div class = "main-container container">

/** I have added this for all the images to be responsive for main contents */
<div class="container">
  <img src="..." class="img-responsive" alt="Responsive image">
</div>

  <header role="banner" id="page-header">
    <?php if (!empty($site_slogan)): ?>
      <p class="lead"><?php print $site_slogan; ?></p>
    <?php endif; ?>

    <?php print render($page['header']); ?>
  </header> <!-- /#page-header -->

  <div class="row">

    <?php if (!empty($page['sidebar_first'])): ?>
      <aside class="col-sm-3" role="complementary">
        <?php print render($page['sidebar_first']); ?>
      </aside>  <!-- /#sidebar-first -->
    <?php endif; ?>

............

</div>

```

After that, I uploaded some images to content types. When I view the node in mobile, I still see those images in original sizes. How do I update the tpl file so all the images in main container class become responsive as well?

# Answer
> 3 votes
Use `.image-responsive` class in your tpl.php file on your image or link tag like that

```
<div class="container">
  <h2>Image</h2>
  <p>The .img-responsive class makes the image scale nicely to the parent element (resize the browser window to see the effect):</p>
  <img src="cinqueterre.jpg" class="img-responsive" alt="Cinque Terre" width="304" height="236">
</div>

```

image-responsive in bootstrap

# Answer
> 1 votes
The image itself needs an `.img-responsive` class on it to scale.

# Answer
> 1 votes
This helped me solving the problem:

For the bootstrap theme, under appearances \> visit the settings page for the theme. Under the default tab ("general") and open the "Images" fieldset and check "Responsive Images "

---
Tags: theming
---