# Question
Title: How get commerce order total(excl vat, exlusive dicount), vat price, discount price, order total(incl vat and discount) in rules?
I am creating a rule on event "When checkout process is completed". I want to send an email to the user when order completes. In the email I want to send the following information

```
Order total price Exclusive discount and VAT
VAT price
Discount price
Order total Inclusive discount and VAT

```

But I don't see any token for these values. Only for the order total inclusive vat is available.

How will I display these values?

# Answer
> 0 votes
There appears to be a feature request for this in the Commerce issue queue.

This post here describes what you'd need to do to add this to your site.

---
Tags: 7, commerce, rules
---


# Question
Title: Is it a problem when entity field storage info is not registered in the key_value table?
This is a Drupal 8 (beta 15) site, basic, few content types. On the status report page it says:

```
Entity/field definitions
    Mismatch detected
    Mismatched entity and/or field definitions.

```

After investigation it turned out, this is caused by a few fields. The `Drupal\Core\Entity\EntityDefinitionUpdateManager::getChangeList()` is reporting them, because their original storage definition is missing from the `key_value` table for the column-collection: `entity.storage_schema.sql`

(The column-collection = `config.entity.key_store.field_config` entry is there for all fields.)

My question is - how can we fix this? All configuration is stored in configuration files (staging directory) - including all fields yml files. The configuration manager reports no difference, export will keep the files the same, and import will not change anything. drush updb will report no updates as well.

Is there a command we should call in an update hook to sync/register this storage info? Any idea?

# Answer
It will depend on what exactly is reported from getChangedList() but what is happening is that a module needs to update the entity schema with something like:

```
\Drupal::entityDefinitionUpdateManager()
->installFieldStorageDefinition('the_field_name', 'node', 'node', $field_storage_definition);

```

Everything you need to know is in the change record: https://www.drupal.org/node/2554097

There is also an effort underway to provide additional information on the status page: https://www.drupal.org/node/2554911
> 3 votes

---
Tags: entities, 8, files
---


# Question
Title: How to get comment depth in a view template?
How can I get the depth of a comment in a view template? I can see the depth when I load the comment in the comment template, but it doesn't seem to be available elsewhere. Any ideas?

# Answer
There is special field in views to get depth of comment. It's "Comment: Depth". Just add it in your view and use in your template.
> 1 votes

---
Tags: theming, comments
---


# Question
Title: How to set newest first in the view of content created
How to set **newest first** in view of content created. So far I have created a view for **content type** and now it's displaying created new content on last page but I want to set in first page. Can anyone help?

# Answer
> 1 votes
Under *Sort Criteria* section, add field *Content: post date* and set it's configuration as *descending* as shown in image below.

---
Tags: views
---


title: How to override $page_top variable?

text:
# Question
Title: How to override $page_top variable?
I am new to drupal 7 theming. I see that there is a variable called `$page_top` in `html.tpl.php` file, which contains HTML markup for the header section of the body. I want to override this and print my markup. How can I do that in `template.php` file, or is there any other way?

# Answer
> 1 votes
you can use hook\_preprocess\_html() like this :

`function hook_preprocess_html(&$vars) {
 $vars['page']['page_top'][] = array('foo' => array('#markup' => 'foo'));
 // Or other render array stuff
}`

# Answer
> 1 votes
You override markup by using :

```
  function template_preprocess_field(&$vars){
    if($vars['element']['#field_name'] == 'field_event_geofield')
     {
          //kpr($vars); //Uncomment to output the $vars array.

           if(isset($vars['element']['#items']['0']['lat']) && isset($vars['element']['#items']['0']['lon'])) { $vars['items']['0']['#markup'] = 'View Map'; } return; }
           }

```

---
Tags: theming
---


# Question
Title: How to Create a single page within a module and set page variables?
I create a page within my custom module with the following code:

```
function mymodule_menu(){
    $items['product-detail'] = array(
        'title' => t('Product detail'),
        'page callback' => '_mymodule_product_detail',
        'variables' => array('var1' => "Hello World Attempt #1"),
        'type' => MENU_CALLBACK,
        'access callback' => TRUE,
     );

 function _mymodule_product_detail(){
      // global $var1 = "Hello Workd Attempt #3";

     return array('variables' => array("var1" => "Hello World Attempt #2") , '#markup' => '<p>This is some markup content displayed correctly in the page</p>');
 } // function

```

It renders the template, sets the title and display the markup (content of the page). However, I would like to fill some variables defined in the `page.tpl.php` and I don't know how to send these parameters, I tried with the *variables* key in the code but nothing is written. I want to display the message `"Hello World Attempt #?"` in the place in page.tpl.php where I have the code `<?php if(isset($var1)) print $var1; ?>`

I have been able to reach my goal with the following code, but using GLOBAL, which is not adequate:

```
function mymodule_preprocess_page(&$variables) {
   global $var1;
if(isset($var1) && $var1 != "") $variables["var1"] = $var1;

}

```

The global `$var1` is set to `$var1 = "HELLO WORLD Attempt #3"` in the `_mymodule_product_detail()` function above (lines commented).

# Answer
The link in my comment may not get you all the way there so I am adding a working example. Assuming everything else in your code is working changing this line

```
 return array('variables' => array("var1" => "Hello World Attempt #2") , '#markup' => '<p>This is some markup content displayed correctly in the page</p>');

```

to

```
$output = array("var1" => "Hello World Attempt #2" , '#markup' => '<p>This is some markup content displayed correctly in the page</p>');
return theme('page', $output);

```

Added the entire `$output` array to the hook\_preprocess\_page\`.

NOTE: You may have to add a theme callback to your menu item. Example here.
> 0 votes

# Answer
most probably you should define your own hook\_theme implementation. I will give you an example.

```
/**
 * Implements hook_theme().
 */
function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'mymodule_theme_name' => array(
      'variables' => array(),
      // Use next line only if you need template.
      // Add templates directory inside your module.
      // And add mymodule-theme-name.tpl.php file.
      'template' => 'templates/mymodule-theme-name'
    ),
  );
}

/**
 * Custom menu callback.
 *
 * @see mymodule_menu()
 */
function _mymodule_product_detail() {
  return theme('mymodule_theme_name', array(
      "var1" => "Hello World Attempt #2" ,
      'markup' => '<p>This is some markup content displayed correctly in the page</p>')
  );
}

```

If you will use your own template you can access var1 as $var1 and markup as $markup.

To clean theme registry clear cache.

I hope it will help you.
> 0 votes

---
Tags: 7
---


title: How to add basic page content

text:
# Question
Title: How to add basic page content
I wanted to add basic page content but I cant see in add content why it is? can anyone tell me how to create it now please?

# Answer
> 0 votes
You need enable the basic page link in `admin/structure/menu/manage/navigation`. I think this might be the problem

# Answer
> 0 votes
Maybe you have deleted Basic page content type , easiest solution could be creating the same type using Content type UI , it is easy this type has only a title and body and comments are off. PHP codes as body or text area , is not suggested in drupal but if you want to insert it in your body then Code Filter Module will allow you to insert PHP.

---
Tags: nodes
---


# Question
Title: Commerce: how can I execute javascript after a product has been added to the cart?
I want to run Javscript once a product has been added to cart (with the script including product info).

The only thing I have tried is `hook_commerce_cart_product_add()` with `drupal_add_js()` but this doesn't seem to work. Ideally I would like it work like `drupal_set_message()`, so the script displays on the next page view.

I also need to get this working with removing products from the cart.

EDIT: Well I've discovered that doing the following actually works, but seems dodgy as hell, and would like to find a better way:

```
drupal_set_message("<script>alert('TEST');</script>");

```

Any ideas would be welcomed!

# Answer
You should better use **Rules** here and the related events. The hook you mention (hook\_commerce\_cart\_product\_add) is a rules event hook.

```
Commerce Cart: After adding/removing a product to the cart

```

Then on the action add with php the js (`drupal_add_js()`) but if you simply want to **show a message** there is an action to do this easily.

```
System: Show a message on the site

```
> 0 votes

---
Tags: commerce, hooks
---


title: How to shorten file urls

text:
# Question
Title: How to shorten file urls
So for a file the standard url is `example.com/sites/default/files/the_file.pdf` how can I get rid of the leading `/sites/default` ?

# Answer
If you want to get rid of the **/sites/default/files/** part and change it to something shorter then just go to the **admin menu** and follow **Configuration \> Media \> File System**

( Or just follow the url : **/admin/config/media/file-system** )

There set your **Public file system path** and **Private file system path** to what ever you want.

**---- EDIT ----**
Actually the above is valid for **Drupal 7**.
For **Drupal 8** you will have to change the value of ***$settings\['file\_public\_path'\]*** in the settings.php file, as mentioned by 4k4.
In D8 the Configuration \> Media \> File System page displays these two parameters but no longer allows editing them.
**----END EDIT----**

So you could change your **sites/default/files** to something like **resources** for example.

And then your files will have urls like this : **example.com/resources/the\_file.pdf**
instead of what you had : **example.com/sites/default/files/the\_file.pdf**

Also **make sure that** :
\- your resources directory exists, and
\- is located at your web document root directory, and
\- is writable by your apache user (or whatever webserver you use).

Of course, this will be fine for a fresh setup, but if you already have a lot of contributed stuff then changing these settings may impact on your existing node contents.
> 2 votes

# Answer
ShURLy is no option, it is not avaiblable for drupal 8.

To change the location of the file, use settings.php:

```
$settings['file_public_path']  = 'path/to/the/files/directory';

```

If you want to keep the file in the same location and only change the url of the file you can put a rewrite into .htaccess.
> 1 votes

---
Tags: 8, uri
---


# Question
Title: Using groupby in hook_views_query_alter()
I have a view that is using a format that doesn't include group by fields in its settings. I'm trying to mimic that by using the `hook_views_query_alter()` function in a module.

I know the code is running, because I see the DPM value and the error log string, but the group by doesn't seem to be working. I know that group by in views is a different thing than mySQL's group\_concat (which you can use via aggregation, but that doesn't work in this case because we need one field to not be aggregated.) So I'm not expecting to see a group\_concat in the printed-out query. But I would have expected it to produce the same results as if I had set up Group By in unformatted list settings for the same four fields (which does work as expected.)

Here is what my view looks like without any group-by (either in the settings or the module):

You can see that there are two complete chunks of information for April Carlisle, because she is speaking at two sessions.

If I turn on Group By for speaker name (content: title), job title, and company in unformatted list settings, this is what I get (and what I want):

So I had thought that my module code would reproduce that result, but it's not. Can anyone tell me why?

Here's the main function:

```
function group_speaker_carousel_views_query_alter(&$view, &$query) {
  switch($view->name) {
    case 'speakers_carousel':
      error_log("view name now: ".$view->name);
      $query->groupby[0]['field'] = "title";
      $query->groupby[1]['field'] = "field_job_title";
      $query->groupby[2]['field'] = "field_company";

      $select_query = $query->query();
      $query_string = (string)$select_query;
      dpm($query_string);
      break;
  }
}

```

# Answer
"Group By" is not working on hook\_views\_query\_alter and it is views module issue. that is reported at https://drupal.org/node/590534, http://drupal.org/node/1608742, http://drupal.org/node/389230#comment-2637200

So, You should use other hooks such as general **hook\_query\_alter**.

```
function hook_query_alter( &$query) {

  if($query->alterMetaData['view']->name == "your_views_name"){
     $query->groupBy("domain_source.domain_id");
     //also you can unset other group by critera by using, unset($query->getGroupBy());
  }
}

```
> 2 votes

# Answer
You may use **groupby** function in `hook_views_query_alter()` function like:

```
//$query->add_field('table_alias', 'field_name', 'field_alias', array('function' => 'groupby'));
$query->add_field('node', 'nid', 'node_nid', array('function' => 'groupby'));
//Distinct = TRUE -used to avoid unnecessary groupby conditions
$query->distinct=TRUE;

```
> 1 votes

# Answer
The views distinct module will be the best solution to remove duplicates from the view.

**INTRODUCTION:**

> Relationships or other joins in Views often create "duplicate" results. For example, a node with a field that has multiple values may show up in the View once per value in the multi-value field. It's frustrating, and the "DISTINCT" SQL query option in the Views UI does not actually solve the problem because the result row is technically distinct. This module aims to give a simple GUI method to remove or aggregate these "duplicate" rows.
>
> For any given field, including "Global: Text" fields, you can optionally mark the field as filtered ("Filter Repeats") or aggregated ("Aggregate Repeats"). All rows with the same value in that field will either be removed as duplicates (filtered), or aggregated in-line.
>
> The "value" of the field as used for filtering or aggregation can be taken pre-render (fastest and totally cacheable), or post-render (after any rewrite rules or other transformations have occurred). Post-render actions are a bit slower (the View must be re-rendered, though the query is not re-run), but also work with Global fields, like Global: Text w/rewrite rules.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Create two nodes with url aliases on one submission
I have a content type **"News"**. With URL aliases pattern and token the URL is like this: `news/[node:title]`.

Is it possible to create two nodes on one submission with different URL aliases? Let's say on submitting on the news node, it will create two nodes with **two URLs** like this: The first one is `news/[node:title]` and the second will be `news2/[node:title]`.

The whole point is not to create a two different content types, but one and the clone node will have a **different URL aliases**, so I can filter a new menu block with visible path `news2/*` and make other logic too.

# Answer
Use hook\_node\_insert() where you can additionally create another node. I am not sure that the url alias will already be available. If not use the following code, found at Programmatically create alias using pathauto for node, to get the original URL alias and then edit it to match your criteria: module\_load\_include('inc', 'pathauto'); // include the inc file for Pathauto module

```
/*
pathauto_create_alias($module, $op, $source, $data, $type, $language)
@param $module: Your module name
@param $op: The operation (insert, update, return, bulkupdate)
@param $source: Internal Drupal path (i.e.: node/1)
@param $data: Addition data used to generate a pathalias, in this case the node object
@param $type: Type of content that will be used to match a pattern, defined in the backend url alias patterns
@param $language: If you have a multlingual website, you need to pass the language for which you want to generate the url alias
*/

pathauto_create_alias('your_module_name', 'insert', 'node/1', array('node' => $node), $node->type, $language->language); // Language is optional

```

Set the node alias and create a node with node\_save().
> 0 votes

# Answer
You can use hook\_node\_presave copy the $node entity, change its URL and then save it with node\_save or even better use entity\_metadata\_wrapper. I do not know if its recommended but i think it is a solution.

You can check if the node is new or not with $node-\>is\_new i think
> 0 votes

# Answer
**Multiple aliases in Drupal**

\[To put this in something more resembling English, we're talking about creating multiple URLs, more than one web address, to one page or piece of content on a Drupal site.\]

It's actually very easy. Go to admin/path/add and add another alias for the node which you want multiply aliased.

(Look up the node/## first by going to the node, and checking the node/##/edit path– you'll have to be logged in to see the edit link.)

So if it's that simple, why would this need an explanatory page on Agaric Design?

Well, if you try to add your alias by editing an existing path, it doesn't work. (For instance if you first tried to redirect from a new path alias to an existing alias, which really doesn't work, and then edited it to point to a system path, any existing alias to that system path gets replaced.)

And seeing the fact that changing foo/bar to foo path alias to foo/bar to node/7 made foo to node/7 disappear-- well, you might logically assume that Drupal isn't letting you have multiple aliases to node 7.

Not true. Adding an alias, instead of editing an existing one to point to the system path, will give you multiple path aliases to the same system path
> 0 votes

# Answer
When you need to create a duplicate node on submission of one node. That means new node needs to be created after creation of first node. Drupal by default do not provide any hook which works for post node action. Even if you do something with `node_presave()` or `node_insert()` or `node_update()` that would always be buggy because all are working before db transaction ends. I have figured out a quick trick for you to overcome issues. And solving this question was also interesting. Thank you for such a question.

1. Download a contrib module hook\_post\_action
2. Install it and create a new custom module with following code, don't forget to add dependency of hook\_post\_action in .info file.

I have checked below code with both conditions when pathauto module is enabled and disabled. Any suggestions are welcome.

```
    /**
     * Implements hook_node_postinsert().
     */
    function MYMODULE_node_postinsert($node) {
      // We need to keep in mind that newly created duplicate node will also invoke this hook so use $_SESSION to avoid infinite looping.
      if (isset($_SESSION['nid_to_duplicate'])) {
        $path = path_load(array(
          'source' => 'node/' . $node->nid,
        ));
        if (!$path) {
          $path = array(
            'source' => 'node/' . $node->nid,
            'language' => $node->language,
          );
        }
        $previous_node_path = path_load(array(
          'source' => 'node/' . $_SESSION['nid_to_duplicate'],
        ));
        if (!$previous_node_path) {
          $alias_prefix = 'node/' . $_SESSION['nid_to_duplicate'];
        } else {
          $alias_prefix = $previous_node_path['alias'];
        }
        $alias_suffix = '-duplicate'; // IN YOUR CASE change it to '2' or whatever you want.
        $path['alias'] = $alias_prefix . $alias_suffix;
        path_save($path);
        unset($_SESSION['nid_to_duplicate']);
      }
      else {
        $_SESSION['nid_to_duplicate'] = $node->nid;
        $new_node = clone $node;
        $new_node->nid = NULL;
        $new_node->vid = NULL;
        if (isset($new_node->path)) {
          unset($new_node->path);
        }
        node_save($new_node);
      }
    }

```

And when you have pathauto module enabled, to match your scenario here is another set of code:

```
/**
 * Implements hook_node_postinsert().
 */
function MYMODULE_node_postinsert($node) {
  if (isset($_SESSION['nid_to_duplicate'])) {
    $path = path_load(array(
      'source' => 'node/' . $node->nid,
    ));
    // We are assuming that auto alias would be [node:content-type]/[node:title] and that is automatically created for the new node as well. Now change it.
    $alias_array = explode('/', $path['alias']);
    $path_suffix = '2'; // You can of course change it according to your need.
    // Change news to news2
    $alias_array[0] .= 2;
    // [node:title] token will be changed by pathauto, recreate it.
    $data = array(
      'node' => $node,
    );
    module_load_include('inc', 'pathauto');
    $alias_array[1] = token_replace('[node:title]', $data, array(
      'sanitize' => FALSE,
      'clear' => TRUE,
      'callback' => 'pathauto_clean_token_values',
      'language' => (object) array('language' => $node->language),
      'pathauto' => TRUE,
    ));
    $path['alias'] = implode('/', $alias_array);
    path_save($path);
    unset($_SESSION['nid_to_duplicate']);

  }
  else {
    $_SESSION['nid_to_duplicate'] = $node->nid;
    $new_node = clone $node;
    $new_node->nid = NULL;
    $new_node->vid = NULL;
    if (isset($new_node->path)) {
      unset($new_node->path);
    }
    node_save($new_node);
  }
}

```
> 0 votes

---
Tags: nodes, path-aliases
---


# Question
Title: Clear Example for drush rsync exclude paths
I've seen many exclude path examples here on stack exchange. But I can't figure out the way to make it work.

To keep it simple :

We have two aliases @self and @live

we have a theme called themename in /sites/all/themes/themename

in the theme folder we have a subdirectory called node\_modules because of the use of gulp in our development workflow.

***How can we make sure to exclude /sites/all/thems/themename/node\_modules/ when syncing with drush rsync @self @live ?***

# Answer
> 2 votes
**drush rsync** has an **--exclude-paths** parameter that will allow you to exclude your node\_modules directory.

Have a look at the parameters for rsync.

You should be able to do something like :

```
drush --exclude-paths=sites/all/themes/themename/node_modules rsync @self @live

```

Because the Drush rsync command uses strict option handling, the --exclude-paths option must appear before the `rsync` command name.

---
Tags: 7, drush
---


# Question
Title: Changing decimal field scale and precision using database
I'm using a custom decimal field in a custom product type in Drupal commerce. It has a precision of 10 and a scale of 2 (2 digits to the right of the decimal place).

I have a client with a large number of products that use this field, but their specification has now changed to require a decimal to 3dp.

By default Drupal "locks" the field to avoid data loss:

> Because the field already has data, some settings can no longer be changed.

I took to editing the database, and it seems to have worked fine. I did three things:

1. Changed the structure type of `field_THIS_FIELD_value` field in the `drupal_field_data_THIS_FIELD` table from `decimal(10,2)` to `decimal(11,3)`
2. Repeated the same for the field revision table
3. I downloaded the BLOB from table 'drupal\_field\_config' for `field_THIS_FIELD` and altered `{s:9:"precision";s:2:"10";s:5:"scale";s:1:"2"` to `{s:9:"precision";s:2:"11";s:5:"scale";s:1:"3"`

I cleared cache and existing data now has an extra 0 after the decimal place, and when I alter the data it stores it to 3 decimal places.

So it seems to work fine. But am I missing anything? Is there anywhere else where field data is changed that I might need to change?

Does the system integrity remain intact? I think I've done what's necessary but don't want to inadvertently break something else or cause any weakness in the system.

# Answer
> 0 votes
you could create a new field with the settings you need and import the data from the old field. see: https://www.drupal.org/node/1491590#comment-9682599

---
Tags: 7, entities, database
---


# Question
Title: How to allow users unsubscribe without logging in by changing the value of a custom field?
I have a Drupal 7 site with a checkbox (Boolean field) that users check on registration to receive promotional emails.

However, Gmail started blocking some of my emails because they want every email to have a link that users can click to unsubscribe without logging in.

The first idea that came to mind is to link to a webform and then process the unsubscriptions manually, which doesn't sound like any fun.

# Answer
> 0 votes
This can be solved using the form API.

1. Define a path using `hook_menu()`.
2. Define an unsubscribe form for the menu path.
3. Write a validation handler to check the email address.
4. Write a submit handler for the form.

---
Tags: emails
---


# Question
Title: How to get webform field value in hook_webform_results_access
In webform 7.x-4.11 I use this :

```
if (webform_results_access($node)) {
    $actions['resend_app'] = array(
      'title' => t('Resend Appointment'),
      'href' => 'ical/' ,
    );
  }

```

I use it to add a "Resend Appointment" option (just as "resend email") when editing a webform.

I would like to add in the "href" some field value of this webform. How can I do that?

# Answer
$submission-\>data\[$sid\]\[0\]

for exemple:

```
if (webform_results_access($node) && ($node->nid == '23')) {
      $actions['resend_ical'] = array(
      'title' => t('Resend ical'),
      'href' => 'ical?' . $submission->data[5][0] . '&' . $submission->data[6][0] . '&' . $submission->data[35][0] . '&' . $submission->data[36][0] . '&' . $submission->data[24][0] . '&' . $submission->data[34][0] . '&' . 'node/' . $node->nid . '/submission/' . $submission->sid ,
      'query' => drupal_get_destination(),
    );
  }

```

this is that simple!
> 0 votes

---
Tags: hooks, webforms
---


# Question
Title: In simple words please, what is the "Rendered file" image-format?
I've tried to Google the term `"Rendered file" "Drupal"` to have some clear data about this image-format and what makes it even possible for choosing (I guess, a module I installed for another purpose that does it), but that data I found wasn't clear and didactic enough for me.

My only aim is to use Drupals image API with the monumental module Insert. The display should be "Hidden" for the field (so it would not be duplicated when the image is inserted to the CKeditor). But I ask to know anyway, and that people to come will have a better clearer answer for what is the "Rendered file" format.

Please give the shortest, clearest definition you can, for this term, and in the end, some words about it's connection to the Views module. Thx,

# Answer
> 0 votes
Since Drupal 7 Images can be rendered the same way as any other entity. Images are a special case of a file and file is a fieldable entity.

Fields can be added to the entity and how the fields are displayed can be configured here:

admin/structure/file-types/manage/image/display

But most times you don't want a rendered file, but a resized image. That is provided by the module "image" in core and if enabled you can configure image styles and use this in node displays and views.

---
Tags: media
---


title: path from theme css

text:
# Question
Title: path from theme css
I'm trying to include my own font to my drupal website. I've got a custom.css file in my theme inside 'sites/all/themes/mytheme/css' folder. My fonts are in my 'sites/all/themes/mytheme/fonts' folder. The css is called from the template.php in my theme folder. This is my css code right now:

```
@font-face {
    font-family: 'slashbadass_black';
    src: url('../fonts/Myfont.eot');
    src: url('../fonts/Myfont.eot?#iefix') format('embedded-opentype'),
         url('../fonts/Myfont.woff2') format('woff2'),
         url('../fonts/Myfont.woff') format('woff'),
         url('../fonts/Myfont.ttf') format('truetype'),
         url('../fonts/Myfont.svg#slashbadass_black') format('svg');
    font-weight: normal;
    font-style: normal;
}

```

So is this path OK? For what I've seen the font-family is not available right now.

# Answer
> 0 votes
Define your css in `mytheme.info`:

`stylesheets[all][] = css/style.css`

```
@font-face {
  font-family: "Oswald";
  src: url(../fonts/oswald.eot?#iefix) format("embedded-opentype"),
     url(../fonts/oswald.woff) format("woff"),
     url(../fonts/oswald.ttf) format("truetype"),
     url(../fonts/oswald.svg) format("svg")
}

```

instead of `template.php`

---
Tags: theming, uri
---


# Question
Title: After wrong submit redirects to wrong url
I have my form on page at url alias http://mypage.com/services. After wrong submission, form redirects me to http://mypage.com/services/formname \- and every field is unordered, because Drupal doesn't read there template for this page. I want to after wrong submit drupal redirect me to same page, and list fields names that are required (and aren't filled).

Changing form options (eg. custom url) doesn't work too. It concerns only the case when all required fields are submitted.

# Answer
You can do this by using below ways :

1. Using Rules module.

> The Rules module allows site administrators to define conditionally executed actions based on occurring events.

2. Using Webform Rules module.

> This module adds rules integration on webforms.
> 0 votes

---
Tags: webforms
---


# Question
Title: Views to show all child terms without showing parent
Vocabulary has 5 parents, each containing 10 child.

Through views I want to display all child terms in a block, but to hide/skip showing parent terms in result.

Creating view that displays both parents and child was easy, but this I cant figure out.

# Answer
> 1 votes
You can add a relationship with your parent term. After that you can set a filter with your parent term and filter all terms, which have a parent term id (parent taxonomy term: term id(not null)).

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


title: Max length of text field

text:
# Question
Title: Max length of text field
How can I increase the max lenght of Tab-Title ?

# Answer
With module: Title you can convert title to field and then you can change the field length

For title-tab goto: `admin/structure/types/manage` choose your content type and then `manage fields` `edit` your field
> 0 votes

# Answer
Maxlength

> Maxlength allows you to set maximum length of any field on any form making use of the form API. This includes fields created using the UI. (Example: any text field on a node) In D6 Maxlength allows you to set maximum lengths to the body, title and CCK textfields of any content type (node).

**By custom**

explain by tostinni
> 0 votes

# Answer
I got the solution for my question. I have create a custom\_field\_length.module. In custom\_field\_length module I have add this code.

```
function custom_field_length_change_text_field_max_length($field_name, $new_length) {
 $field_table = 'field_data_' . $field_name;
 $field_revision_table = 'field_revision_' . $field_name;
 $field_column = $field_name . '_value';

 // Alter value field length in fields table
db_query("ALTER TABLE `{$field_table}` CHANGE `{$field_column}` `{$field_column}` VARCHAR( {$new_length} )");

// Alter value field length in fields revision table
db_query("ALTER TABLE `{$field_revision_table}` CHANGE `{$field_column}` `{$field_column}` VARCHAR( {$new_length} )");

// Update field config with new max length
$result = db_query("SELECT CAST(`data` AS CHAR(10000) CHARACTER SET utf8) FROM `field_config` WHERE field_name = '{$field_name}'");
$config = $result->fetchField();
$config_array = unserialize($config);
$config_array['settings']['max_length'] = $new_length;
$config = serialize($config_array);
db_update('field_config')
    ->fields(array('data' => $config))
    ->condition('field_name', $field_name)
    ->execute();
}

function custom_field_length_update_8002() {
  custom_field_length_change_text_field_max_length('field_tab_title', 255);
}

```

After enable module I will run update.php after that my field size is increase to 255.
> 0 votes

---
Tags: nodes, 7
---


title: None of the forms are submitting

text:
# Question
Title: None of the forms are submitting
I have a strange problem - on my local installation none of the forms are getting submitted.

I can access forms and when I click submit, page just reloads and nothing happens. That applies for all configuration forms, as well as node save/edit forms. Strangely, I can log in.

I don't really know where to look. Any suggestions?

# Answer
> 0 votes
This can happen when there are problems with your local .htaccess file -- it might be that Apache locally is not set up to read .htaccess files, or there may be an error in the file, or it may be missing altogether.

If the issue is specifically with the login form, you might be having issues with HTTP/HTTPS switching if your site is configured to attempt to negotiate the scheme, but your local server is not configured to serve HTTPS.

---
Tags: forms
---


# Question
Title: Is it possible to add css class to the page's body tag with rules when certain conditions are met?
I seem to have read that there is a way of making Rules add a css class to the body tag, but I can't find out how to do it. Any ideas?

# Answer
> 3 votes
Yes - the Context module allows you to add CSS classes to the body (Theme HTML condition) based on whatever events you specify. You would then combine this with the Context Rules module which extends Context to allow for context events from Rules.

# Answer
> 1 votes
Assuming you are using the Pathauto module to automatically create semantic paths your content pages based on the menu path you can use the page's path to create the classes you are looking for:

```
function THEMENAME_preprocess_html(&$vars) {
  $path = drupal_get_path_alias();
  $aliases = explode('/', $path);

  foreach($aliases as $alias) {
    $vars['classes_array'][] = drupal_clean_css_identifier($alias);
  }
}

```

---
Tags: rules
---


# Question
Title: How do I add a class to the HTML "body" tag programmatically?
I would like to add a custom CSS class to the `<body>` tag. I am using Drupal 7/Corolla.

How can I do it programmatically from my custom module?

# Answer
> 13 votes
The preprocess functions can be implemented from modules, and themes.

The preprocess function that you need is `hook_preprocess_html()` and the variable to set is `$variables['classes_array']`, which is an array containing all the classes set for the `<body>` element. The content of the html.tpl.php file that is used by default by Drupal (if the theme doesn't use a different template file) is the following one:

```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN"
  "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language; ?>" version="XHTML+RDFa 1.0" dir="<?php print $language->dir; ?>"<?php print $rdf_namespaces; ?>>

<head profile="<?php print $grddl_profile; ?>">
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
  <?php print $styles; ?>
  <?php print $scripts; ?>
</head>
<body class="<?php print $classes; ?>" <?php print $attributes;?>>
  <div id="skip-link">
    <a href="#main-content" class="element-invisible element-focusable"><?php print t('Skip to main content'); ?></a>
  </div>
  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>
</body>
</html>

```

In your module you just implement the preprocess function as follows:

```
function mymodule_preprocess_html(&$variables) {
  $variables['classes_array'][] = "new-class";
}

```

template\_process() then uses `$variables['classes_array']` to populate `$variables['classes']` with the following code:

```
$variables['classes'] = implode(' ', $variables['classes_array']);

```

Using a preprocess function in a module is preferable if your site uses more than one theme, or if the theme set for your site is not the one you created. In this case, you are able to set your custom CSS classes, and not lose them when updating the theme, or simply changing the default theme used by your site. If your site uses just a theme, and that theme is a custom theme you created, then you can implement the preprocess function in your custom theme. As you maintain the theme, the CSS classes are not lost when updating your theme.

# Answer
> 9 votes
add to MODULENAME.module and clear cache

```
function MODULENAME_preprocess_html(&$vars) {
  $vars['classes_array'][] = 'custom-class';
}

```

# Answer
> 4 votes
Whilst you can do this through hook\_preprocess\_html, quite often you'll be in a completely different part of your codebase when you come to need this. If that's the case then I'd suggest that you use `ctools_class_add` instead:

```
ctools_class_add(array('class1', 'class2', 'class3'));

```

You can call that from anywhere as long as hook\_preprocess\_html hasn't yet run and the classes will be added.

# Answer
> 1 votes
You can do this via `template_preprocess_html()`. You can put this in your `template.php`, wherever your theme / base theme deems most appropriate (eg, Omega preprocess folder), or in a custom module, depending on what is most appropriate.

```
function mytheme_preprocess_html(&$variables) {
  $variables['classes_array'][] = "class1";
  $variables['classes_array'][] = "class2";
  $variables['classes_array'][] = "class3";
}

```

Despite the names in the API reference, the `theme_preprocess` and `theme_process` functions can be called from modules, and not just themes. All you need to do is name the hook to match your module, eg `mymodule_preprocess_html()`.

# Answer
> 1 votes
Assuming you are using the pathauto module to automatically create semantic paths for your content pages based on the menu path you can use the page's path to create the classes you are looking for:

```
function THEMENAME_preprocess_html(&$vars) {
  $path = drupal_get_path_alias();
  $aliases = explode('/', $path);

  foreach($aliases as $alias) {
    $vars['classes_array'][] = drupal_clean_css_identifier($alias);
  }
}

```

---
Tags: 7, theming
---


# Question
Title: Simplest way of creating a themed page from a module
Unifying the questions below, I want to check if the problem and solution is correct:

Problem: I want to create a page with hook\_menu from my custom module. This page will have a different template to the other pages. Some of the dynamic content of the page will be retrieved by my custom module.

Solution: the code below, with these convoluted steps:

1. hook\_menu with callback function
2. callback function returns empty array.
3. Based on path, hook\_preprocess\_page retrieves data and send to page.
4. theme suggestion is set, based on path.

**What I don't understand is why 3. and 4. cannot be accessed directly from callback function, avoiding to guess what page we are accesing via path.**

Code:

```
function hook_menu(){
    $items['product-detail'] = array(
       'page callback' => '_hook_product_detail',
       'type' => MENU_CALLBACK,
       'access callback' => TRUE,
);

function _hook_product_detail(){
   return array("#markup" => "");
} // function

function hook_preprocess_page(&$variables) {
   $cp = current_path();
   $cp_arr = explode("/", $cp);
   if($cp_arr[0] == "product-detail"){
       $variables['theme_hook_suggestion'] = 'page__product_detail';
       // ... get data to populate var1, used in page--product_detail.tpl.php
       $variables["var1"] = $var1;
   } // if

 }

```

Questions unified: How to Create a single page within a module and set page variables? and https://drupal.stackexchange.com/questions/177604/how-can-i-put-the-results-from-my-module-into-a-page-tpl-php

# Answer
You can add variables from the page callback. I imagine the placement of the variable in your `$vars` will depend on your theme.

This works for me using a responsive\_bartik sub theme and panels. The `my_var` exists in `$vars['page']['content']['system_main']['my_var']`.

```
my_module_menu() {
  $items['test-empty'] = array(
    'page callback' => 'my_module_page_view',
    'page arguments' => array('This is my var'),
    'theme callback' => 'my_module_theme',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
}

my_module_page_view($var) {
  $output['#markup'] = 'Your markup or just an $output render array';
  $output['my_var'] = $var;
  return $output;
}

my_module_theme() {
  return your_theme
}

my_module_page_preprocess($vars) {
  dpm($vars);
  // Path to my_var may differ from theme to theme and by set up.
  $vars['page_level_var'] = $vars['page']['content']['system_main']['my_var'];
}

```

Now your $page\_level\_var should be available in your tpl.

You shouldn't need the theme callback but I could be wrong. (It would have been a pain not to use it with my current set up.)
> 1 votes

---
Tags: 7, theming
---


# Question
Title: Authenticated users can't edit their own content even with permissions set accordingly
As an authenticated user, I've created a node. The Tasks menu is completely absent. If I try to access it via node/476/edit, I see "Access Denied".

The Task menu (edit, view, revisions) is seen by the Administrator but Authenticated users. How can I bedug this further?

However, I have permission set for this Content Type as follows below. I've included another Node TYpe called Event as well.

I even tried looking into the table node\_type to see if anything was off

```
       type: user_posted_content
       name: User Posted Content
       base: node_content
     module: node
description: Postings by users
       help:
  has_title: 1
title_label: Title
     custom: 1
   modified: 1
     locked: 0
   disabled: 0
  orig_type: user_posted_content

```

**Other Modules** I previously had tried both Content Access (content\_access) and Node view permissions (node\_view\_permissions) but ended up deactivating both.

**Digging deeper** It appears I may have some residual from one of those modules.

```
MariaDB [s7data]> select * from node_access where nid = 476;
+-----+-----+-------+------------+--------------+--------------+
| nid | gid | realm | grant_view | grant_update | grant_delete |
+-----+-----+-------+------------+--------------+--------------+
| 476 |   0 | all   |          1 |            0 |            0 |
+-----+-----+-------+------------+--------------+--------------+

```

# Answer
You don't need to restore your database, you only need to enable your nodeaccess module in your modules page and it should restore on its own and you will have access to all stored data. Then go to nodeaccess config, undo all the restrictions, save, then go back to modules page and uninstall nodeaccess. And rebuild permissions. Hopefully that'd do the trick!
> 0 votes

---
Tags: users
---


# Question
Title: Dynamically linking from author name(s) in a View to a nodes by author View
I need to have a View that includes an author name with each node that also links to another View showing all the nodes by that author.

Currently I've got a home page View that always shows the most recent node for a particular content type. I added the field 'display name' (a custom field I created for users) to the View so it shows 'First Name' 'Last Name', and that works well.

I also see I can make it a link in 'rewrite rules' but that would be a hard-coded link to a particular author's page. It needs to be dynamic and link to whichever author's page belongs to the author writing the particular article that will be displayed in the View block.

Anyone know how to do this?

# Answer
> 2 votes
Assuming that authors are the user that created the piece of content and not an entity reference field, and that you're using D7:

1. Create a clone of the current view that you're using, assuming that you want the author's list of nodes to have the same layout/fields/what have you that the current view you're working with does, and create a new page for it.
2. For the path of the new view, create a path that includes a wildcard (%) such as /posts-by-author/%
3. Under Advanced, add a Contextual Filter for Content: Author uid. When you put in a user's UID in the "Preview with contextual filters" box above the preview and hit Update preview, it should show you that user's posts.
4. Now, back to your original view. Assuming that you're using a display format that requires fields, add the Content: Author uid field to your display and set it to "Exclude from display".
5. Under "Add" there's a "Rearrange" option when you click the arrow next to the Add option. Rearrange the fields so that the UID field is above the name field. This will allow you to use it in the name field when you create a link.
6. Under "Rewrite results" select "Output this field as a link" and enter the link path with \[uid\] replacing the wildcard symbol.

Now, when you click on an author's name, it should take you to a page that displays all the nodes created by that author.

---
Tags: views
---


title: WordPress Migrate 502 Bad Gateway nginx

text:
# Question
Title: WordPress Migrate 502 Bad Gateway nginx
I did a fresh Drupal(v7.39) installation on Nginx server. Everything seem fine until the WordPress Migration process with "Migrate", "WordPress Migrate", and "Migrate Extras" modules. The error message I got is
`An AJAX HTTP error occurred. HTTP Result Code: 502 Debugging information follows. Path: /batch?id=83&op=do StatusText: Bad Gateway ResponseText: 502 Bad Gateway 502 Bad Gateway nginx`.

Even I got an error, all the content did migrate correctly except the url alias. The URL was set for "***Set path aliases to their original WordPress values***" during the process, but they came out like node/101, node/103....

What may causing the error and how can I fix this?

# Answer
A 502 Bad Gateway error can mean a lot of things, however, if you had the site working OK and then it stopped after changing things in the database, then it basically points to a problem with the way PHP is interpreting things in the database.

* You'll need to look at your PHP configuration to find where the PHP error log is on the server and then look into that error log to understand what the problem is.
* There is a chance that the error is being recorded into Drupal's watchdog, usually available at admin/reports/dblog - if you can't view that inside the website you could use drush with the `drush ws` command to see items in watchdog, or just use `SELECT * FROM watchdog ORDER BY wid DESC LIMIT 20;` at a sql client to see the contents of the watchdog table.

The 502 error indicates there is a problem, but doesn't indicate the specific problem. If you post more details from your PHP error log it will be easier to help you fix it.
> 3 votes

---
Tags: 7, uri, migrations
---


# Question
Title: Views' taxonomy term page by content type
I have two regular content type **Article** & **Blog**, both share a term reference field **field\_tags**. When I use **Taxonomy term** view that come with Views module, it display tags term in both content type.

For example, there are two Article nodes tag as **health** and three Blog nodes tag as **health**. Then if I use **Taxonomy term** view to display **health** term, it will display five nodes: two Article nodes and three Blog nodes.

Is there a way to separate the display result by content type? For example, if user click on health term on an Article node, Taxonomy term view will only display two Article nodes and if user click on health term on a Blog node, Taxonomy term view will show three Blog nodes.

Prefer not to use an extra module or adding different tag field for Blogs content type. Thank you for helping!

# Answer
> 0 votes
in the view you can filter by your desired content type.

just add the filter criteria named *Content: type*

# Answer
> 0 votes
You can achieve that by using Contextual filters in your view. Filter by Content:type and then provide the value in the URL.

---
Tags: views
---


# Question
Title: including javascript via theme.info doesn't work.
I'm trying to include a simple javascript into my theme using the theme.info

It works like a charm on my home-setup but when I try to load in on a real page it doesn't include the .js-files (not even an empty `<script>`-Tag is displayed in the source).

The Code:

```
...
engine = phptemplate
stylesheets[all][] = css/bjqs.css
stylesheets[all][] = css/style.css
scripts[] = js/bjqs-1.3.js
scripts[] = 'js/jquery-latest.min.js'
features[] = main_menu
regions[slider] = Slider
...

```

The CSS-Files get included on both projects without any problem.

# Answer
> 0 votes
Do you have aggregation on in configuration \> development \> performance?

If so, this causes the problem. Clear all caches, and the problem should be solved.

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


# Question
Title: How to change stylesheet ordering of base and child theme?
I have downloaded Drupal Commerce and started playing around with it. I have a new theme created using Commerce Kickstart as base. My theme is in `sites/all/themes`. Any styles that I put in the stylesheets of my new theme are being overridden by the base drupal commerce stylesheet.

How can I make sure my styles get applied on top of the default?

# Answer
> 1 votes
First of all, if you look into the section of your code, can you find the css file? If not, it can be that the css is aggregated (in this case you'll find a random alphabetic css file), then clear your cache. If there is no aggregation, and you can't find your file, it is most probably set wrong in your theme.info file.

If the file is there, but not working, check in your browser (via fe element inspect) if and why the selectors are overridden...

---
Tags: 7, commerce, theming
---


# Question
Title: How to embed a view (with contextual filters) into a node or another view?
I'm using the modules below with the Views module to create a views block of all **referenced nodes** in the entity reference fields.

There is no problem to create a views that lists all the referenced nodes based on this tutorial.

## What I want to do is to **embed** this views into nodes.

I tried both the EVA and Views Field View modules but couldn't be success (no result). The view I want to embed into nodes uses **contextual filters** and **relationships** and I think while using this view into a node or another view, the contextual filter doesn't work.

## So, how I can embed this view (with contextual filter) into a node or another view?

# Answer
Using panels module you can create a "pane view" for your view and easily pass any argument as view contextual filter .

here is a tutorial about views content panes
> 1 votes

# Answer
You can embed a view into a node using Insert View.
You can have your contextual filters setup as arguments in the format below,

```
[view:<view_name>=<display_name>=<argument>]

```

You can embed a view into a view as a field using Views Field View.
You will have to place your contextual filters from the replacement patterns as shown in the below picture.
> 1 votes

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


title: breadcrumb not working with taxonomy

text:
# Question
Title: breadcrumb not working with taxonomy
Im using the zen theme to create a subtheme. I cannot display the breadcrumb properly. My url is using taxonomy as its parents so something along the lines of http://example.com/link1/title-article. I want the breadcrumb to be `"Home > Link1 > title article`.

Unfortunately I only have `Home / title-article` as the breadcrumb. How can I resolve this? I havent changed the `zen_breadcrumb` function in the zen template..

# Answer
> 0 votes
The Crumbs module will do what you are looking for. It allows you to set the pattern for crumb generation. In your case the pattern for an article would be something along the lines of

`[node:field_tags]`

Home is automatically generated so this will give you a crumb path of: `Home >> Taxonomy Term`

If you want to include the article title, then you would just add \[node:title\] to the crumb pattern.

`[node:field_tags]/[node:title]`

Which would produce: `Home >> Taxonomy Term >> Title`

---
Tags: breadcrumbs, theming
---


title: Webform redirect to login before submit

text:
# Question
Title: Webform redirect to login before submit
I am creating a webform for my users to submit it but i have one question. How to redirect users to login before they submit a webform?

# Answer
Take a look at the Login Redirect module. It should do what you are describing.
> 0 votes

# Answer
You need to use a custom implementation of hook\_node\_access so your users can see the node and then probably hook\_form\_alter to hide the form if not user\_is\_logged\_in()
> 0 votes

---
Tags: webforms
---


# Question
Title: How to rename uploaded file using form API and Drupal managed_file field
I make a Drupal Form using FAPI (Drupal 7) in this form I used managed\_file field

```
$form['image_fid'] = array(
  '#title' => t('Image'),
  '#type' => 'managed_file',
  '#upload_location' => 'public://',
);

```

I want to rename the uploaded file (make the filename = filename+date)

How can I make something like that

# Answer
> 3 votes
Assuming you know about file status, file\_save & file\_usage\_add.

In your submit callback:

```
$file = file_load($form_state['values']['image_fid']);
$file->filename = 'somefilename';
$file->status = FILE_STATUS_PERMANENT;
file_save($file);
file_usage_add($file, 'yourmodule', 'foo', 1);

```

More info at the Form API Reference.

# Answer
> 3 votes
The best way to rename file is using https://www.drupal.org/project/filefield\_paths module .

> The File (Field) Paths module extends the default functionality of Drupal's core File module, Image module and many other File upload modules, by adding the ability to use entity based tokens in destination paths and file names.
>
> In simple terms, File (Field) Paths allows you to automatically sort and rename your uploaded files using token based replacement patterns to maintain a nice clean filesystem.

also you can rename it programmatically with hook\_file\_insert

something like

```
function hook_file_insert($file)
{
    $parts = pathinfo($file->filename);
    if (in_array(mb_strtolower($parts['extension']), array('jpg', 'jpeg', 'gif', 'png', 'tif', 'flv', 'pdf'))) {
        $uri = 'public://' . 'dsfr_' . $file->uid . '_' . $file->timestamp . '.' . $parts['extension'];
        $file = file_move($file, $uri);
    }
}

```

# Answer
> 2 votes
You can rename file on upload context through validator functions

here is the edited code

```
$form['image_fid'] = array(
  '#title' => t('Image'),
  '#type' => 'managed_file',
  '#upload_location' => 'public://',
  '#upload_validators'=>  array('file_validate_name' => array()),
);

function file_validate_name(stdClass $file) {
  $errors = array();

  //generate file name
  $new_filename = convert_filename_to_filename_date($file->filename);

  $file->filename = $new_filename;

  //changing file location
  $destination_dir = "public://file_location/";

  //check if file exists. if exists rename it append incremental number  until the filename is unique

  $file->destination = file_destination($destination_dir.$file->filename, FILE_EXISTS_RENAME);

  // If file_destination() returns FALSE then $replace == FILE_EXISTS_ERROR and
  // there's an existing file so we need to bail.
  if ($file->destination === FALSE) {
    $errors[] = t('The file %source could not be uploaded because a file by that name already exists in the destination %directory.',
    array('%source' => $file->source, '%directory' => $destination_dir));
  }

  return $errors;
}

```

# Answer
> 0 votes
I have been struggling with this for a couple of days but this seems to be working for what I wanted to do:

https://api.drupal.org/api/drupal/includes!file.inc/function/file\_move/7

---
Tags: 7, forms
---


# Question
Title: How variable_get and variable_set works in drupal
How do variables work? Is it as simple as using

```
variable_set('myvar', 'my_value');

```

to set, and

```
variable_get('myvar');

```

to retrieve?

Additionally, where are these variables stored, and do they have any sort of categorisation/access control (i.e. can any module get the variables set by any other module)?

**Update from comment**

I can see a line like `$custom_theme = variable_get('admin_theme', '0');` But i cant see any `variable_set('admin_theme')` in anywhere in the module though .

# Answer
Variables created through `variable_set()` and `variable_get()` are stored in the variables table in the database.

`variable_set('myvar', 'my_value')` is used to change the value of an existing variable to the provided value, or to create a new variable with the provided value if none exists.

`variable_get('myvar', 'optional_default')` is used to retrieve the value of `myvar`. If `myvar` does not exist, then it is created using the value from `optional_default`. If `optional_default` is not specified, then `myvar` defaults to `Null`.
> 1 votes

---
Tags: 6, configuration
---


# Question
Title: drush cron fails: Drush command terminated abnormally due to an unrecoverable error
```
$ drush -v -d cron
Bootstrap to phase 0. [0 sec, 1.65 MB]                               [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drush() [0 sec, 1.77 MB]    [bootstrap]
Cache HIT cid: 5.4-commandfiles-0-33f01882e55343a61f1cb10880b0da0f [0.01 sec, 1.78 MB]                                          [debug]
Bootstrap to phase 0. [0.02 sec, 4.16 MB]                                                                                [bootstrap]
Bootstrap to phase 6. [0.02 sec, 4.16 MB]                                                                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_root() [0.02 sec, 4.17 MB]                                                  [bootstrap]
Initialized Drupal 7.28 root directory at ...htdocs [0.03 sec, 5.78 MB]                                [notice]
Drush bootstrap phase : _drush_bootstrap_drupal_site() [0.03 sec, 5.78 MB]                                                  [bootstrap]
Initialized Drupal site default at sites/default [0.03 sec, 5.79 MB]                                                           [notice]
Cache HIT cid: 5.4-commandfiles-2-c32acd775c18a90c5b41d0fc9accf5ab [0.03 sec, 5.79 MB]                                          [debug]
Drush bootstrap phase : _drush_bootstrap_drupal_configuration() [0.03 sec, 5.79 MB]                                         [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_database() [0.03 sec, 5.8 MB]                                               [bootstrap]
Successfully connected to the Drupal database. [0.03 sec, 5.8 MB]                                                           [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_full() [0.04 sec, 6.3 MB]                                                   [bootstrap]
Cache HIT cid: 5.4-commandfiles-5-21916586faf556c236c401ff89ea50f6 [0.18 sec, 33.52 MB]                                         [debug]
Drush bootstrap phase : _drush_bootstrap_drupal_login() [0.18 sec, 34.19 MB]                                                [bootstrap]
Successfully logged into Drupal as Anonymous (uid=0) [0.18 sec, 34.2 MB]                                                    [bootstrap]
Found command: core-cron (commandfile=core) [0.18 sec, 34.2 MB]                                                             [bootstrap]
Drush command terminated abnormally due to an unrecoverable error. [0.2 sec, 34.87 MB]                                      [error]

```

There's nothing showing up in `admin/reports/dblog`.

Note that heading to `/cron.php?cron_key=...` works fine from the web interface. But it fails when curling it from console. (I also reported an issue at https://github.com/drush-ops/drush/issues/664 but was directed here.)

How can I find out what's wrong?

P.S. related: https://stackoverflow.com/questions/10014142/cron-fails-when-running-through-drush-and-calling-node-load

# Answer
> 1 votes
Apparently Elysia Cron was installed and in that case you have to

```
drush elysia-cron

```

And `drush cron` is an alias of `drush core-cron`.

---
Tags: drush, cron
---


# Question
Title: How to create Omega 4 subtheme with new "default" libSass based starterkit?
I am trying to install omega 4, now at 4.4, which uses liBsass for the default starterkit. How do I proceed about this - I understand I need now npm and gulp instead of the previous Ruby stuff required for Omega 4.3?
Everything installs fine, but `drush omega-guard` complains about gemfile (which it should not use, as I understand).

# Answer
> 1 votes
I've had a lot of problems getting started with the new starterkit. It seems to me as if omega-guard does not yet support the new kit. You can still accomplish the same by running `gulp` in the subthemes directory. This will start the gulp watching process in foreground.

For more information about gulp and the libSass starter kit, I can recommend this post: https://www.drupal.org/node/2537364#comment-10287771

---
Tags: theming
---


title: Licence billing

text:
# Question
Title: Licence billing
My question is regarding the recurring payment for drupal commerce.

I use Commerce Licence with 'Licence role' and Commerce Licence Billing to make my users pay for a monthly subscription.

The question I have is, how does the recurring system work?

* Does the licence Role expire after given time, but gets re-acitvated if a payment is made?
* Does the recurring payment happen automatically, or does my user have to buy a licence every month?
* Does the previous question depend on my "Payment Gateway"?

What I want to do is make my users buy a licence(Role) once, and then never have to buy a licence again. But they have to pay a monthly fee otherwise the licence will expire. So in other words the site much purchase a licence for the user in the background when the previous one expires, but charge them the monthly fee.

It's a tedious process to go and buy a licence(role) every month to keep using the site.

Thanks

# Answer
I discovered this module today and i am having same questions :) I have understand quite things.

A partof the answer in the documentation of the module :

After a license is renewed, the queue "commerce\_license\_billing\_cycle\_close" will set the "Recurring: Payment pending" status to the order.

```
$order->status = 'recurring_payment_pending';
commerce_order_save($order);

```

If you use commerce card on file module, a default rules will try to charge the user credit card and then the Order will have a "Completed" status.

Otherwise, user will have to pay line items through the site to have the order completed.

To answer your first question, if i understand, the module will renew license without manage the payment but will create corresponding orders with a specific status. Either you charge your client with a specific rule or tell your client to pay different orders.

For the second question, your customer will get the license every months automatically and will have to pay (if you don't do it via a rule) after.
> 0 votes

---
Tags: commerce
---


# Question
Title: Granting per-node-type permissions in hook_node_type_insert()
I use the Override Node Options module to specify granular permissions for publishing, leaving Revision log entries, etc. for each node type.

I almost always grant the same set of permissions to a certain role for every node type, so I thought I'd have Drupal automatically assign them on node type creation:

```
function MYMODULE_node_type_insert($info) {
    if(module_exists('override_node_options')) {
        user_role_grant_permissions(4, array(
            'override ' . $info->type . ' published option',
            'enter ' . $info->type . ' revision log entry'
        ));
        $role = user_role_load(4);
        drupal_set_message(t('The @role role has been given permission to publish, unpublish, and enter revision logs on @nodetype nodes.', array('@role' => $role->name, '@nodetype' => $info->type)));
    }
}

```

But when I do so, I get errors:

> *Notice: Undefined index: override NODETYPE published option in user\_role\_grant\_permissions() (line 3152 of /htdocs/modules/user/user.module).*
>
> *PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1048 Column 'module' cannot be null: UPDATE {role\_permission} SET module=:db\_update\_placeholder\_0 WHERE ( (rid = :db\_condition\_placeholder\_0) AND (permission = :db\_condition\_placeholder\_1) ); Array ( \[:db\_update\_placeholder\_0\] =\> \[:db\_condition\_placeholder\_0\] =\> 4 \[:db\_condition\_placeholder\_1\] =\> override NODETYPE published option ) in user\_role\_grant\_permissions() (line 3154 of /htdocs/modules/user/user.module).*

As it happens, `node_type_get_types()` ( which is called by `node_permissions_get_configured_types()`) does not return the node type I'm in the middle of creating, even though the documentation says "This list can include types that are queued for addition or deletion."

So now I'm flummoxed. How can I set a per-node-type permission automatically when that node type is created?

# Answer
So, my bet is that the new node type isn't getting added to the cached list of types that `node_type_get_types()` returns. At the very end of `node_type_save()`, it calls `node_type_cache_reset()`, but that's probably running too late for your code.

So try putting a call to `node_type_cache_reset()` at the top of your function, and hopefully that will do the trick.
> 2 votes

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


# Question
Title: How to make a link between Drupal and my ownCloud server?
I want my documents uploaded from Drupal to be **directly** stored on my ownCloud server. Drupal server and ownCloud are both installed in the **same** machine.

**Do you know how to do this type of action?**

# Answer
> 2 votes
As a first step you would need to share users between owncloud and drupal.

I found this github project that appears to allow your owncloud installation to use the users from the drupal database.

Anything beyond this point requires some coding.

Assuming that the above worked and you have the user shared between the two platforms, then I expect you would need to write a drupal module with that used the owncloud API to submit a file from a drupal form. You would also need to use the owncloud api to return a list of files associated with a user.

This would be a very crude implementation, which bypassed all of drupal's file handling functionality, and relied on your own code for every interaction with owncloud (I can't find an existing module). A more advanced module would aim to use owncloud as a backend for the file system, in which case you might want to look at the patterns used in the Droogle or dropbox modules and adapt them to the owncloud api.

Whilst writing this answer I found what looks to be an interesting discussion from drupalcon Austin entitled Collaborative Spaces: Integrating Drupal with Google Drive, Dropbox, and more. Maybe that would be of help.

# Answer
> 1 votes
You can get your uploaded files directory in the ownCloud via the ownCloudApp External storage support, following these steps:

1. Enable the *External storage support* App
2. Add a mount of type "Local" to the filesystem directory Drupal is uploading to.

You should, however, take care of giving access only to trustworthy users as they will be able to access/change/delete all files in that directory. A subdirectory for a certain upload case (e.g. by node type) could be sufficient. Be aware that Drupal will typically not be notified of file changes!

This solution only works if the ownCloud server is running as a user with (file system) read permissions to that directory. This should be the case if Drupal and ownCloud are running as the same user.

To prevent users from changing files, you could set suitable filesystem rights (read and not write) for the user ownCloud is running as. If that's not possible (e.g. because Drupal and ownCloud are running as the same user) you could still play with different mount types which allow setting read/write permissions.

---
Tags: 7
---


# Question
Title: Make page.tpl.php and page--front.tpl.php share same html
Is there a way to make `page.tpl.php` and `page--front.tpl.php` share the same template base?

If any of you are familiar with the Twig templating engine, You can define blocks with `{% block content %}Node Content{% endblock %}` and then do something like:

```
{% extends 'page.html.twig' %}
{% block content %}Home Page Stuff{% endblock %}

```

Does PHPTemplate have anything equivalent? I tried using PHP's `include()` but it doesn't work.

# Answer
> 2 votes
The theme system works by looking for templates that are a precise matches for the current path and then falling back to looking for less and less precise pages.

If you

1. delete your `page--front.tpl.php`
2. clear the cache

Then phptemplate should use `page.tpl.php` for your front page.

# Answer
> 0 votes
Make a file, fe called page.shared.inc.php enter your shared code (html/php).

Then add the following to the page.tpl.php and page--front.tpl.php

This should work.

# Answer
> 0 votes
PHP `include()` does work, and I bet I know why you're having trouble. Relative paths in `include()` are relative to the original script, not the file being included. So if you put `include('thingy.php')`, it's probably looking for it in the Drupal root directory next to `index.php`, not in your theme.

PHP's `__DIR__` constant returns the path to the current PHP file's directory, so if you do something like

```
<?php include(__DIR__ . '/thingy.php');

```

it ought to work. (Do remember to lead your path with a slash, as `__DIR__` does not end with one.

---
Tags: 7, theming
---


title: Migrate failure: on clause is ambiguous

text:
# Question
Title: Migrate failure: on clause is ambiguous
I'm working with the `migrate` module for the first time and I've worked with the `db_select` api a little bit, but I'm running into an error.

I'm trying to convert some old labels into a drupal taxonomy. When I browse to the `/admin/content/migrate` page, it does my query correctly and shows the right number of rows that should be migrated. However, when I actually try to run the import, I get this error:

> Migration failed with source plugin exception: SQLSTATE\[23000\]: Integrity constraint violation: 1052 Column 'labelId' in on clause is ambiguous

Here is the code I have in my LabelMigration class:

```
$this->map = new MigrateSQLMap($this->machineName,

    array(
        'labelId' => array('type' => 'int', 'not null' => TRUE)
    ),
    MigrateDestinationTerm::getKeySchema()
);
$query = db_select('migrate_account_label', 'l')
         ->fields('l', array('labelId', 'label'))
;

$query->leftJoin('migrate_asset_labels_membership', 'lm', 'l.labelId = lm.labelId');
$query->leftJoin('migrate_asset', 'a', 'lm.assetId = a.assetId');
$query->addExpression('count(*)', 'num');
$query->condition('a.type', 'B');
$query->groupBy('l.labelId');
$query->groupBy('l.label');

$this->source = new MigrateSourceSQL($query);

// Set up our destination - terms in the vocabulary
$this->destination = new MigrateDestinationTerm('article_labels');

$this->addFieldMapping('name', 'label');
$this->addFieldMapping('description')
    ->defaultValue('');

```

If I remove the `leftJoin()` calls then obviously the error about the `on` statement goes away, but I don't understand how `labelId` is ambiguous because I'm always referencing it with a table alias.

Any ideas where this error is coming from? Is it coming from the MigrateSQLMap at the top? If so, how can I reference that `labelId` with an alias to make it non-ambiguous? I tried making it `l.labelId`, but that didn't work.

# Answer
> 30 votes
Figured it out!

When defining the field in the MigrateSQLMap I can set a table alias for the field:

```
$this->map = new MigrateSQLMap($this->machineName,
    array(
        'labelId' => array(
            'type' => 'int',
            'not null' => TRUE,
            'alias' => 'l', // it's the letter small case "L", not the digit 1
        )
    ),
    MigrateDestinationTerm::getKeySchema()
);

```

The `'alias' => 'l'` makes the `labelId` become `l.labelId` in the queries.

# Answer
> 1 votes
I thought that he was setting `alias` to `1` (ie, boolean true), but there's a reason it's a string - that is the actual alias, so if you're alias is `n`, `'alias' => 'n'`. That actually cost me about 1/2 hr.

---
Tags: 7, database, migrations
---


title: Practical staging of config

text:
# Question
Title: Practical staging of config
I am successfully migrating at least the bulk of my config from `dev` thru `stage` to `prod`. But the process could obviously be more robust.

Current procedure:

* create central (bare) repository
* create `dev`
    + clone to `dev` machine
    + perform set-up (usually `standard` template) using separate `sites/dev.mysite.com` settings. No content. No real settings beyond the defaults imported from the template and the `install.php` process.
    + export config to `from_dev` config dir
    + push all to central repository.
* create `stage`
    + clone to `stage`
    + perform identical setup but using `sites/stage.mysite.com` instead.
    + import config from the `from_dev` config dir
        - use `drush config-edit` to change the freshly created UUID's for `system.site` and `shortcut.set.default` so they match the UUID's from the `dev` site.
        - use `drush config-import` to duplicate the config from `dev`.

Basically repeat this process for any other sites in the staging tree.

Problems:

* All the sites now have identical UUID.

I'm not clear on the value/purpose of UUID but as long as they are all unique within a site; I'm not sure that's a problem?
* The import process does not have the ability to modify existing config objects when the change is limited to UUID. If the UUID's differ, the old object is deleted and the new (otherwise identical object) is created from scratch. This has the side effect of also deleting any content associated with the old object.

In theory, this sort of delete/replace only happens during initial setup before the sites have any data; so there's no harm. However, great care is obviously required to guarantee that no "important" object will be deleted thru the entire life of the project.

Is this an intended D8 workflow?

Should the UUID (either in the live target `stage` site or in the configs from `dev` to be imported) be edited to match before the import?

Is there anyway to instantiate a D8 `stage` (`prod`) site that is genuinely "blank" (i.e.: an initial config import would require no editing of UUID and/or deletion/recreation of config objects)?

I've been using the `standard` template because it includes things like `Configuration Manager` which facilitate the config sharing process. Note that if `stage` is not built with the same template as `dev` than the import will fail with something like (paraphrase from memory): `Unable to uninstall module 'minimal' because it does not exist; Unable to install module 'standard' because it does not exist.` Is there a better template for this process?

# Answer
> 1 votes
I would approach it this way:

Have a branch master:

Create 2 separate branches fed from the master (master being prod): \- stage \- test

Create a new branch abcfeature based from master, after complete, merge to stage/test.

Use domain alias's to setup different URLS in your test environment.

---
Tags: drush, 8, configuration
---


title: How do I find the source of an error?

text:
# Question
Title: How do I find the source of an error?
I'm seeing the following error when running cron (in terminal via drush and on screen via the status report page.

> Error: Call to a member function getScriptTag() on a non-object in /home/loktah/public\_html/includes/common.inc(1762) : eval()'d code, line 2

I'm not sure where to even start looking for the source. Any direction would be appreciated.

# Answer
The line 1762 is inside `drupal_eval()`, in Drupal 6. You need to check those nodes that use the PHP filter and call `getScriptTag()` on a variable that doesn't contain a PHP object.

It happens during cron tasks because one of the implementations of `hook_cron()` indirectly calls `node_view()` on some nodes.
> 1 votes

---
Tags: cron, log-messages
---


# Question
Title: add users to og group via vbo doesn't work: record is deleted immediately
I like to add users to an OG group using vbo, a custom action and og\_group().

I build up a page with a view of users to add (/node/%nid/add\_user).

On this view I added a views bulk operations field with the "skip batch" option. (I skipped the batch to get the current %nid from the url).

In the custom code I like to add the selected user to the page shown. I know I can do this also with the standard group forms, but I want to do it this way :-)

So here is my code to subscribe the user to the group:

```
function mymodule_vbo_actions_users_woform(&$user_node, $context) {
  global $user;
  //dpm($node); dpm($context);return;
  switch ($context['settings']['action_type']) {
    case 'add_user_to_group':
      $nid_page = menu_get_object();
      if (!isset($nid_page)) $nid_page = arg(1);
      $nid_page = $context['page_nid'];
      $account = user_load($user_node->uid);
      //dpm($nid_page);
      $node_page = node_load($nid_page);
      dpm($user_node);
      dpm($account);
      dpm($node_page);

      $aValues = array('entity_type'=>'user','entity'=>$account,'membership type' => 'OG_MEMBERSHIP_TYPE_DEFAULT',);
      $og_membership = og_group('node',$node_page->nid,$aValues,FALSE);
      $og_membership->save();
      dpm($og_membership);

      // get member roles id for selected group bundle
      $result_roles = db_query("SELECT rid FROM og_role o where group_bundle = :bundle and name=:name and gid=:gid;",array(':bundle'=>$node_page->type,':name'=>'bidder', ':gid'=>$node_page->nid));
      $role_id = NULL;
      foreach ($result_roles as $key_roles => $value_roles) {
        $role_id = $value_roles->rid;
        break;
      }
      dpm($role_id);
      og_role_grant('node',$node_page->nid,$account->uid,$role_id);
      break;
  }
}

```

This code seems to be correct. I watched the `og_membership` table and the record for the selected user is inserted, but then DELETED immediately!?

So the question is of course: Why is the record deleted?

# Answer
> 0 votes
You might need to grant a OG role to the new member after adding them.

e.g. `og_role_grant('node', $node_page->nid, $account->uid, 2);`

The magic number on the end determines the type of role granted. 1 = non-member, 2 = member, 3 = administrator member

# Answer
> 0 votes
I had the same issue today.

VBO is reverting the action if you don't have the proper og\_permission. So check if you have assigned the proper permissions.

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


# Question
Title: adding block region inside of menu section
I have a menu section in my theme where i display the `main-menu` menu. This works as expected. with the following code.

```
<?php print theme('links', array(
                    'links'         => menu_navigation_links('main-menu'),
                    'attributes'    => array('class'=> array('navbar', 'navbar-collapse', 'collapse'))
));?>

```

I would like to make a block region inside of this rendered menu section for the search box. The end results will be block region at the end of the menu that i can style to be to the right of the menu. I could do this in css but was hoping to make the rendered html a little cleaner. This is what I have tried.

```
<?php print theme('links', array(
                'links'         => menu_navigation_links('main-menu'),
                'attributes'    => array('class'=> array('navbar', 'navbar-collapse', 'collapse')) ,
                'region'        => render($page['search']);
));?>

```

There looks to be no tutorials on adding a block region to the menu array. Is is possible to inject a block region into the menu render array?

# Answer
Part of the problem is that regions aren't really what you're looking for here. Drupal regions are just areas of the page, and you set content to appear in a given region. One way of utilizing regions for this would be to have a menu region defined in your theme's .info file, and then putting the menu and the search block in that region. I'm betting that's not really what you're after, though, because it doesn't result in very clean code.

There are two other options that I can see. One is to create your own theme callback for menus so that instead of calling `theme('links', array(...))`, you're calling `theme('your_new_theme_callback', array(...))`. You can define different variables for this theme, and one of them could be for the search block.

Of course, because this is Drupal, there's already someone who's gone "Man, I really want blocks in my menu and there's no nice way to do that in Drupal" and created a module. The Menu Attach Block module lets you attach a block to your menu. I've not used it before so I'm not 100% sure how to implement it in the way you're looking for. It doesn't look like you'd have to change your code at all, I don't think, because it looks like the module overrides `theme_link()` for you.

Does that make sense? If you want more details, let me know!
> 1 votes

---
Tags: routes, theming, blocks
---


# Question
Title: name of last person who modified node - Display suite
with Display suite in Drupal 7 I can get the last modified date , but how can I display which user did the last modificatioin?

# Answer
The easiest way to see who did the last revision is to, well, enable revisions for that content type and require them. This won't help you with past edits, but going forward, every edit will create a new revision, which will have a user associated with it, so you can see who made the last edits.
> 1 votes

---
Tags: display-suite
---


# Question
Title: Previewing a view does not show a phone number but when I look at the view by visiting the URL of the page it does?
I have taken over a Drupal website and I am completely new to Drupal. One of the features of the website is to list out all the employees of a company (a Directory).

The directory is displayed with a tabled view, and is pretty easy to understand.

When I look at the view while editing it in the preview view I don't see the each employees' list of phone numbers, I dont see a field for those numbers (i.e. Content:Phone\_Number) either, but when I actually look at the view, from visiting the URL of the page I see the phone numbers.

Additionally, when I visit the URL that is hosting the View and use Firebug (DOM Explorer) I can see that there is a td tag that is holding the phone numbers. But, when I visit the View from a editor standpoint and check the preview view with FireBug (DOM Explorer) I see that exact td tag, but it's holding the user's NID number, not the phone numbers!

How is this possible?

Please and THANK YOU.

# Answer
> 1 votes
They most likely modified a tpl.php file. In the Views module when you are viewing to edit it, look for Theme: information and click information.

You will then see a list of possible tpl.php files. If you see one that is not in the first position and bold, then you know they did some type of override on the tpl.php. Look in the theme folder for that file name.

If its not in there, then you will want to look at your themes template.php for some type of override. Finally, some people will put these overrides in a utility module.

---
Tags: views
---


# Question
Title: How to get URL parameters values inside access callback
I have a link looking like this:

```
members/get-certificate/<user_id>/<group_id>/<pass date>

```

The access callback should work like this:

```
if($user->uid == <user_id>)
{
    //any user can get his own certificate
    <generate certificate>
}
else
{
    //user with low admin priviledges can generate a certificate for any user
    if (user_access('low admin task'))
    {
        <generate certificate>
    }
    else
    {
        print "Access denied";
    }
}

```

In `hook_menu` I wrote this:

```
$items['members/get-certificate'] = array(
    'page callback'    => 'members_get_certificate',
    'access callback' => 'members_access_get_certificate',
    'access arguments' => array('access content', $user_id),
    'type' => MENU_CALLBACK,
    );

```

### Access callback

```
function members_access_get_certificate($permission, $user_id)
{
    global $user;

    if ($user_id != $user->uid)
    {
        if (!user_access('low admin task'))
        {
            return false;
        }
    }

    return true;
}

```

### Page callback

```
function members_get_certificate($user_id, $group_id, $pass_date)
{
    //generate certificate
}

```

### Problem

Unfortunately, $user\_id is undefined in `members_access_get_certificate` and I am unable to do the validation. How can I pass the parameter from URL into the callback?

# Answer
> 1 votes
You can specify arguments in the URL path you are registering by using the "%" character:

```
$items['members/get-certificate/%'] = array( ... );

```

You can then pass the argument value to your page callback and/or your access callback by specifying which segment of the URL path to pass. The segments are the parts of the path separated by "/" characters, and you start counting them from 0. So to pass the value of '%' from the above example, you will specify the integer value **2** in your 'access arguments' value:

```
  'access arguments' => array('access content', 2),

```

So when a user attempts to access the path 'members/get-certificate/30', the access callback will be passed the argument values **'access content'** and **'30'**. The callback you provided would then have the correct intended values.

Here then is your hook\_menu item definition, corrected as outlined above:

```
$items['members/get-certificate/%'] = array(
    'page callback'    => 'members_get_certificate',
    'access callback' => 'members_access_get_certificate',
    'access arguments' => array('access content', 2),
    'type' => MENU_CALLBACK,
    );

```

---
Tags: routes
---


title: Allow SQL injection

text:
# Question
Title: Allow SQL injection
I'm trying to use Drupal for a specific research purpose and it would be helpful if I could intentionally make a text box **vulnerable** to **SQL injection**. Specifically, it would be convenient if I can make the search box **vulnerable** but anything is better than nothing. How can I do this? As a point of clarification, I'm trying to do this from a browser, not the `api` or terminal. Thanks!

# Answer
> 1 votes
So the only way to to do this would be to write a custom module and explicitly write bad code that would normally not pass community inspection.

I'll leave that as an exercise to the asker. ;)

Hint: Your module should also have a dependency on this module.

---
Tags: database
---


# Question
Title: How to get Views caching working with contextual filters?
Using Drupal 7.19 and Views 3.5 cache is not respecting contextual filter argument- it is displaying the same cache result no matter what argument given. How to get this working properly?

# Answer
> 2 votes
This is a Views bug actually and it is not solved yet, but you can work around it by using this patch if you are using contextual filter Taxonomy with depth as I guess, and if it didn't work you can turn off the "Field Language" for the view if you have neutral language content, but this patch is not complete as there is some issues not solve, you can see the full discussion of this issue here issue here

# Answer
> 2 votes
Fixed since 7.x-3.8

Resolution comment: https://www.drupal.org/node/1055616#comment-8611373

# Answer
> 1 votes
This article talks about this problem and has a patch to solve

# Answer
> 1 votes
Just try this module: Views argument cache

EDIT: You also have this module available Views custom cache

---
Tags: views, caching, performance
---


title: Drupal 7 Views: Align text with image

text:
# Question
Title: Drupal 7 Views: Align text with image
Hello Drupal Stack Exchange crowd. I am working on building a *view* for a content type that has several fields and an image. I am using an **"Unformulated list"**

Using Drupal 7 core and the most recent update of views.

**My goal is to align the field image to the right so the text is right next to it.**

I have put the text field and image "Inline" in field settings and "**remove HTML**" formatting and changed the text to "**Plain Text**". This places the text starting at the bottom right corner of the image but I'm wanting the text to align starting at the top right. I have tried rewriting the field to do this but have had no luck.

It seems like something like this would be very simple without `.css` (since I'm not the best at it).

**My Questions are:**

1. If I use `.css`, what style sheet should I insert the code into (Views, Theme, ??)?
2. Is there a way to get around using a `.css` to accomplish what I want to do?

Thank you in advance for your time. WO

Addition info 10/22/15 - **in response to argiepiano**: I already use and love display suite and have never noticed the "Display Suite" option in Views. THANK YOU. I have gone through the first 5 videos but: **I still have trouble getting text/images to align correctly in Display Suite (css), do you mayhap know of any good videos or articles on that?**

Thanks Again, WO

# Answer
> 0 votes
I would suggest you use Display Suite. This module allows you to define a layout for the entry form and/or the display of any content type. If you want to use Views to create a list of nodes, you can use the layout you created to display each of the nodes in the View by selecting `Unformatted list of Full posts` in the Display format dropdown lists in the Views wizard.

There are several excellent video tutorials for Display Suite, but I'd recommend the ones its author created.

---
Tags: views, display-suite
---


# Question
Title: Create a Login Role in order to view unpublished content
I need to create a **role** where an authenticated user can log in and see pages that were unpublished to the outside world. Is there **documentation** that explains the best way to set this up?

Any assistance would be appreciated

# Answer
There's the administer content permission you can set for a role, but that is a pretty broad permission. It sounds like you're looking for View Unpublished module. It even has such a use case on the project page:

> Used in concert with the Override node options module, you can give specific roles the ability to publish/unpublish certain node types without giving those roles administrative access to all nodes. A tutorial for this use case exists here: http://brightbacon.com/blog/drupal/allowing-node-publishingunpublishing-...
> 2 votes

---
Tags: users
---


title: Views Block origin link in breadcrumb

text:
# Question
Title: Views Block origin link in breadcrumb
I've created a **views block**, which contains a list of same **node types**. The block is placed within another node on my page "**home \>\> blockpage**". When you now follow some link in the block view you will get a breadcrumb like "**home \>\> pageFromBlock**". How to achieve a breadcrumb like "**home \>\> blockpage \>\> pageFromBlock**".

I am using drupal 7 with breadcrumb module and views.

# Answer
> 1 votes
You can do by using these modules:

Custom Breadcrumbs

> Many new features have been added including support for Views, Panels, Taxonomy vocabularies and terms, paths, and a simple API that allows contributed modules to enable custom breadcrumbs for module pages and theme templates. These are implemented using optional, independent submodules that depend on the main Custom Breadcrumbs module.

Path Breadcrumbs

> This module is a solution for all problems with the breadcrumbs on your site!
>
> Path Breadcrumbs module helps you to create breadcrumbs for **any page** with **any selection rules** and load **any entity** from the URL!

---
Tags: views, breadcrumbs
---


# Question
Title: When creating a view based on order products in ubercart, only people with access to all orders can see it
I've created a view based on **order products** in ubercart, but only those with admin role, who have permissions to see all orders can see the view.

Now this is problematic, as the view is a most popular products grid, which is meant for anonymous users who visit the webshop.

My question is: can I somehow restrict access to *anonymous* and *authenticated* users to see all the orders but at the same time allow them to see that one view, based on order products?

Hope my question was clear, and thanks in advance,

Huba

# Answer
> 0 votes
In the view's advanced settings, go to 'SQL Settings', and check 'Disable SQL rewriting'.

Drupal modules can hook in to SQL queries and alter them before they are executed. The Ubercart module automatically adds a permission check to queries that touch the Order table, to implement the 'view own orders' permission. Individual views can opt out of this rewriting mechanism, but that will prevent any module from altering the query. Be sure to thoroughly test that the view does not leak any sensitive information.

---
Tags: views, ubercart, users
---


# Question
Title: Multi-site - can I route second site to different urls?
I've got a multi-site Drupal installation with 2 **sub-domains** pointing to the same Drupal site. Eg: **subdomain1.mysite.com** and **subdomain2.mysite.com**

I have a page set up using `hook_menu` with the path `'site/%`'. Eg: ***subdomain1.mysite.com/site/test***

I want all requests to subdomain2.mysite.com/% to point to this page. Eg: subdomain2.mysite.com/test should point to the same page as subdomain1.mysite.com/site/test

How can I do this?

# Answer
> 0 votes
**Redirecting to a different domain**

Redirect URLs From Old To New Domain Using 301 Redirects In **.htaccess**

When you need to switch a website from an old domain to a new domain, you need to redirect all your page URLs, this is when **htaccess** is your friend.

The code below will create 301 url redirects for both the **www** and **non-www** version of ‘**olddomain.com**‘ to the new domain ‘**newdomain.com**‘.

Add this **.htaccess** file to the OLD site **webroot** and upload the files from the old site to the new to see a seamless switch from an old domain to a new one.

So the example below is redirecting all URLs from **olddomain.com** to **newdomain.com**

```
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.olddomain\.com$
RewriteRule (.*) http://www.newdomain.com/$1 [R=301,L]
RewriteCond %{HTTP_HOST} !^olddomain\.com$
RewriteRule (.*) http://www.newdomain.com/$1 [R=301,L]

```

You can also apply this to a subdomain – so the example below is redirecting all URLs from **subdomain.olddomain.com** to **subdomain.newdomain.com**

```
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^subdomain.olddomain.com$
RewriteRule ^(.*)$ http://subdomain.newdomain.com/$1 [R=301,L]
RewriteCond %{HTTP_HOST} ^www.subdomain.olddomain.com$
RewriteRule ^(.*)$ http://subdomain.newdomain.com/$1 [R=301,L]

```

For more details

---
Tags: multi-sites, routes
---


title: Search across multiple views

text:
# Question
Title: Search across multiple views
I have a page with two view blocks in it, each pulling from different content types. Is there a way to allow the user to *search both views at the same time*? I want to be able to enter a search term and have both views be filtered by this term.

---

**Edit**: Going off of johnbburg's answer, I found a solution using Panels, but would really like to avoid adding Panels to the site. Perhaps I could use javascript to insert the search term into the other field?

# Answer
What I ended up doing is implementing some custom code that adds an input field to the page, and takes that input and feeds in into the multiple block filters on the page, just using javascript.
> 0 votes

# Answer
You can set the "Filter identifier" for each exposed filter to use the same name. This is available under the "MORE" options in the filter's settings.

These will be used as GET parameters in the request and picked up by both views. This however also means that you can't use ajax with either views as they need to detect the parameter during a page request.
> 0 votes

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


# Question
Title: How to bypass required fields in form validation function of a module?
I have a form with two radios and two forms related to each of them. These forms have some required fields. user can just check one radio and then fill in one form. but then clicks on submit button drupal gives error for those unselected and empty field ( which are required but now they are not required because their radio isn't selected) .

How can I bypass those required inputs in my module ? I am developing my module's form with Form API.

# Answer
If you are building your own form, you need to remove `'#required' => TRUE,` from field to bypass validation or assign `FALSE` value.

Example with required field:

```
$form['title'] = array(
  '#type' => 'textfield',
  '#title' => t('Subject'),
  '#default_value' => 'whatever',
  '#size' => 60,
  '#required' => TRUE, // remove this if you want to bypass or give it FALSE value
);

```

Check Form API Reference for more details

Now you can do the same for existing form by alter the form using `hook_alter_form` and unset required attribute or assign `FALSE` value.

Example:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'FORM_ID') {
    $form['FIELD_NAME']['#required'] = FALSE;
    // or
    unset($form['FIELD_NAME']['#required']);
  }
}

```
> 1 votes

# Answer
You can use #limit\_validation\_errors in Drupal 7. See https://api.drupal.org/api/drupal/developer%21topics%21forms\_api\_reference.html/7#limit\_validation\_errors
> 0 votes

---
Tags: 6, forms
---


title: Features Revert or Update

text:
# Question
Title: Features Revert or Update
Just to clarify some attributes about features.

Revert will take what is in my code and add it to the database?

Update will take what is in my database and change the code?

What happens if I have overridden fields and want to omit them when copying the feature over to another site? Which one of the two from above will I use?

# Answer
When your feature is in overridden state and you want to omit the changes that you have done recently, you have to revert the feature.

You can use the user interface to revert the feature, or you can use `drush fr feature_machine_name`.
> -2 votes

---
Tags: features
---