# Question
Title: Tag every value of a single multi-value field
I have a photo contest website where every participant can upload up to 3 photos. I created a participant node type with a multiple file upload with max 3 entries.

How can I tag/edit/flag individual photos to filter/choose the best ones while they belong to a single node? How can I accomplish this? Is there any contributed module to help me, or do I need to change the logic?
I thought that a solution could be that every photo needs to be a separate node linked to participant's node through entity reference, but how do I create 3 separate photo nodes on a single form submit?

Thanx

# Answer
At first I thought to create a rule action too, but after some research I found the File entity module, that allows me to treat single uploaded photos like entities, where I added a Flag field, that integrates perfectly with the Views module. In this way, I solved my problem very quickly without changing the logic of my application.
> 0 votes

# Answer
* you could create a form with multiple file upload fields, and on submit have it create three nodes, adding the file information to a file field in the new node

Form API

> This module provides a new interface for creating nodes where the users are able to select the fields what they want to use for creating the nodes. It is designed to create multiple nodes in one round, it's possible to add more node input rows on-the-fly.

I have never used it, but it appears to do the first suggestion automatically for you. Even if it wasn't perfect, you could modify it into a custom module using it as a framework to build upon

* using a temp content type that is only used as a form (for simplicity), or creating a custom form via code or module, you could create a Rule acting upon submit to create three of the actual image nodes, using the field values from the temp content type. If Multi Node Add doesn't work, this has an advantage of the easiest (though probably least performance) way of accomplishing it of these options

> The Rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules). It's a replacement with more features for the trigger module in core and the successor of the Drupal 5 workflow-ng module.
> 0 votes

---
Tags: taxonomy-terms, entities, flags
---


# Question
Title: Multiple template pages when creating new pages
new to Drupal 7. I can kind of get the result I want through "hacky" methods but was wondering what best practice was.

I am creating a drupal 7 bootstrap subtheme.

The main content area of the site needs to come in two basic verities.

* A single column content area
* A two column content area

I want my end users to be able to select which of the two page layouts to use should they need to create a new page.

I can create the effect to some extent by having the two areas defined as regions in my theme and then having them populated - or not - with blocks. The issue with this solution is I don't want my end users to be able to add blocks to both layouts. I want them to be forced to select one or the other.

is there an accepted "drupal" way to do something like this?

# Answer
> 3 votes
**Option 1:**

The simplest "core" way to do this, is to create two separate content types. For this example, let's call one `One Column` and the other `Two Column`

You can now create two different node template files:

```
node--one-column.tpl.php
node--two-column.tpl.php

```

Now you can customize those two template files to display the content however you wish, and it would depend on what you want to accomplish with each of these.

**Option 1a:**

If you decide to go with option 1, using Paragraphs to allow your users to add multiple fields into the columns could be well suited to your needs.

**Option 2:**

Another option is to use Display Suite which has the similar idea of creating multiple template files, but here you can choose the display method on a per node basis (via Display Suite Extras) Also since you are using Bootstrap, there is a nice add-on called Display Suite Bootstrap Layouts that provides layouts for you to use.

**Option 3:**

Panalizer allows you to use "Panels" on a per node basis, which could help you solve this problem. There is also a Panels Bootstrap Layouts module as an add-on.

**Option 4:**

I believe Panopoly can do this as well.

**Summary:**

There are many different ways to do this, but you will have to try them out to see which works best for you. The options above are probably the most common so I'd start there. If you need anything more specific for your needs, there is always a way.

---
Tags: 7, theming
---


# Question
Title: How to do OR operation on one filter's options of Views 3
I have two content-types Courses and Groups. Courses is added as entity reference field in Group content-type. One category field is added in courses content-type.

View is created for list of all courses. Category is added as filter. This category has terms. AND operation is applied as default. Like if user has selected term1 and term2 as filters then courses who has both terms selected are only listed. But I want courses who has either term1 or term2 should be listed. I am using better exposed filter module and checkboxes for category filter options.

Group filter is created for category where I have added terms as :

```
term1, is equal to, term_id
term2, is equal to, term_Id

```

Other options are less than or equal to, greater or equal to, greater than, less than, in between, is empty etc. But no any setting using which I can apply OR operation on single field options.

How can I resolve this issue ? Any help would be appreciated.

Thanks in advance.

# Answer
You should be able to click the arrow next to the criteria and select "And/Or" to change this setting. Here I've added two criteria and set them to "or"
> 0 votes

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


title: Use Firebird Database to Lookup Data

text:
# Question
Title: Use Firebird Database to Lookup Data
I have installed my drupal in postgres. I've been using multiple databases in my customized module. Below is my settings.php:

```
$databases = array (
    'default' =>
        array (
            'default' =>
                array (
                    'database' => 'drupal-7.34',
                    'username' => 'drupal-7.34',
                    'password' => 'drupal-7.34',
                    'host' => 'localhost',
                    'port' => '',
                    'driver' => 'pgsql',
                    'prefix' => '',
                ),
            'import' =>
                array (
                    'database' => 'enrollment',
                    'username' => 'postgres',
                    'password' => '',
                    'host' => 'localhost',
                    'port' => '',
                    'driver' => 'pgsql',
                    'prefix' => '',
                ),
            'import_employee' =>
                array (
                    'database' => 'csudbnew',
                    'username' => 'sysdba',
                    'password' => 'masterkey',
                    'host' => 'localhost',
                    'port' => '',
                    'driver' => 'firebird',
                    'prefix' => '',
                ),
        ),
);

```

Below is my code in executing the query:

```
 $query = db_select('EMPLOYEES', 't1',array('target' => 'import_employee'));
 $result = $query
     ->fields('t1', array('LASTNAME'))
     ->condition('t1.EMPLOYEENUMBER','1016','=')
     ->execute();

```

This is where I get the error.

I aready `enabled extension=php_pdo_firebird.dll` in my `php.ini`file. What should I do next? I can query in my postgres databases except in firebird. Do I have to do more configuration?

Ive been following this tutorial. I downloaded the zip file in the site and unzip it in my `drupal\includes\database\firebird`.

# Answer
> 2 votes
The error is in the following line:

```
$query = db_select('EMPLOYEES', 't1',array('target' => 'import_employee'));

```

It is selecting *import\_employee* as target, and *default* as key, but in your settings.php file you have a *default* target with a *import\_employee* key. Failing to find the definition for the target you select, Drupal fallbacks to using *default* as target and (without being instructed differently), to use *default* also as key.

You can do one of the following:

* Edit your settings.php file so that it contains information about the *import\_employee* target and its *default* key. Keep in mind that the information about the database is given as `$database['<target>']['<key>']`, not `$database['<key>']['<target>']`.
* Change your code to always call `db_set_active()` before your query.

# Answer
> 0 votes
The query object doesn't know about the `EMPLOYEES` table because it's currently switched to the your default Drupal database until you specify otherwise. Use `db_set_active()` to change the active database:

```
db_set_active('import_employee');
//@TODO: Execute queries under the Firebird DB
db_set_active(); //Switch back to the default Drupal DB

```

---
Tags: database
---


title: Dynamic product catalogues

text:
# Question
Title: Dynamic product catalogues
So, I work at a web development agency and we recently decided to give our custom CMS up and start developing with Drupal. Currently, I am developing a wholesale product website. What I need to do is to create some product catalogs without using commerce since we do not need the purchase, checkout and payment features and I thought that using the built-in Content, Taxonomy and Views features we can get our job done.

I have created the product categories in Taxonomy. The main (root) categories are main Taxonomy objects and the subcategories are terms.

I created a custom Content type called: products. In this type I have the following form fields: Product Code, Name, Image, Description and a list field to choose the Terms I would like the product to be displayed in.

I would appreciate some help in order to set the whole structure up as I am still heavily influenced by the custom CMS we used to work on that had similar content management with Joomla!

In conclusion, I would like to:

* Set a sidebar menu up that contains the categories and the subcategories as a tree. I would also like the menu to be updated if any changes occur in the taxonomy (e.g I add a term in taxonomy and it shows up on the menu).
* Set the structure so that when someone clicks on a category that does NOT contain products but subcategories, gets the list of the categories bellow the active one.

I am really looking forward to your answers and I'd like to thank you in advance.

# Answer
Personally instead if all Vocabularies are part of same "Tree" they should be in one "vocabulary" and current items should be displayed as parent terms -\> children terms tree structure

**1. regarding first bullet point**

* https://www.drupal.org/project/taxonomy\_menu \<- allows adding taxonomy items to any menu of your choice
* https://www.drupal.org/project/taxonomy\_menu\_block \<- creates a block in sidebar with list of your terms of selected vocabulary with options such as "Count" that is updated on cron run
* taxonomy\_manager \<- I use to mess around with the order of things or importing lots of terms it really speeds up the process if you would need to move taxonomies from different vocabularies into one :) Google it as I cannot post more then 2 links :)

**2. regarding second bullet point**

For that you would need to create "Taxonomy view" instead of content view and set it up so that the categories would be displayed for example: (cant post example as not enough rep)
> 1 votes

# Answer
You're definitely going to want to leverage Views for this. You'll make a view to display all of your taxonomy terms in a block, and put it in the appropriate region in your theme. Views will keep that block updated automatically as any terms are changed.

You might find a module like Views Tree helpful for your display. And this question is pretty much a duplicate of the second part of your question: "Taxonomy with depth" view
> 0 votes

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


title: Form API - match field with error

text:
# Question
Title: Form API - match field with error
I have a weird question. Let's say we have this form:

```
$form['field1'] = array(
  '#type' => 'textfield',
  '#title'  => 'First field'
);
$form['container'] = array(
  '#type' => 'container'
);
$form['container']['field2'] = array(
  '#type' => 'textfield',
  '#title' => 'Second field'
);

```

Now if you set an error for field2, you do it like this:

```
form_set_error('field2', 'error message');

```

and not like

```
form_set_error('container][field2', 'error message');

```

I wonder how does drupal does recognize the right form element to add the error class. I wanna do something like that, to add a suffix for every field who did not passed validation.

I tried getting the error field with `form_get_errors()` but it returns `field2` as a field with an error. It's obvious that `$form['field2']` does not exists add I can't add a suffix to it.

Any help is greatly appreciated. Or at least a hint to the right direction. Thanks :)

# Answer
I ended up adapting the general solution to each individual form I needed to achieve this functionality by looking at the form structure and setting the suffix that way.
> 0 votes

# Answer
Drupal does it on elements theme level with `_form_set_class` function. This function gets `$element` array and checks if it has errors with function `form_get_error`. Because errors are set with indexes like `'foo][bar][value'` (parents) that can be not so easy to find them in the `$form` array. So I suggest to use the same check as in `_form_set_class` with your function at pre\_render, theme or validate level when you have `$element` array. `hook_element_info_alter` can be useful.

The super simple example:

```
function YOUR_MODULE_element_info_alter(&$elements) {
  foreach ($elements as $type => $value) {
    $elements[$type]['#pre_render'][] = 'YOUR_MODULE_element_error_check';
  }
}

function YOUR_MODULE_element_error_check($element) {
  if (isset($element['#parents']) && form_get_error($element)) {
    $element['#suffix'] = t('error!');
  }
  return $element;
}

```
> 0 votes

# Answer
I have no idea how Drupal knows how to fetch the correct form element just from the name without indicating the parents.

As for getting the form element from the name that `form_get_errors()` gives you, the following worked for me:

```
$name = 'container][field2';

// Split the elements/indexes apart.
$split_name = explode('][', $name);

// Check for integer indexes. (Not sure if this is entirely necessary.
foreach($split_name as &$arr_nest) {
  // Don't quote integer indexes.
  $arr_nest = !is_int($arr_nest) ? '"' . $arr_nest . '"' : $arr_nest;
}

// Put the name back together again. eg. "container"]["field2"
$split_name = implode('][', $split_name);

// Get the whole element from the form.
eval('$element = $form[' . $split_name . '];');

// Check the results
dsm($element, 'form element');

```
> 0 votes

# Answer
Maybe you could check the Inline Form Errors module. I think it will suit your needs.
> 0 votes

---
Tags: forms
---


# Question
Title: Getting Parse Error during installation of Drupal 8
I am getting the following error while Installing Drupal 8.

> Parse error: parse error, expecting `T_CONSTANT_ENCAPSED_STRING' or`'('' in var\www\html\core\includes\bootstrap.inc on line 3

When I checked the line number 3 in index.php I saw following two lines.

```
use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

```

I don't know what is the meaning of above two lines and why these are creating the above error.

# Answer
> 12 votes
Hopefully you're not installing Drupal 8 in the hope of using it as a stable website...it's nowhere near ready yet :)

That said, the reason you're getting the error is because the PHP `const` keyword has only been available for use in the global scope since PHP 5.3. Drupal 8 uses `const` in the global scope in a lot of places (correctly, as Drupal 8 will require at least PHP 5.3).

My guess is you have PHP 5.2 or lower installed on your server.

Some helpful links:

# Answer
> 0 votes
Maybe you are using an unsuported version of PHP for Drupal 8. I tried on PHP 5.3 and got a similar error message.

Althou Drupal 6 runs on PHP 5.x, and 7 runs on 5.2.5, **the minimun version of PHP supported for Drupal 8 is PHP 5.5**.

Check the requirements here, look specifically for Drupal 8: https://www.drupal.org/requirements

---
Tags: installation, 8
---


# Question
Title: Display comment box to the author of the node being referenced using panels
I am creating a project that needs ONLY the author of a node being referenced AND the author of the referencing node to participate on comments on the referencing node, a sort of customer support Question/Answer system where ONLY the node author of the referencing node and the node author of the referenced node can participate in the comments section. I am implementing this with panels.

So far i can show the comment block only to the referencing node author (Question author) using the following code which checks to see if node-author-id = logged-in-user id:

```
global $user;
if (arg(0) == 'node' && is_numeric(arg(1))) {
  // Get the nid
  $nid = arg(1);

  // Load the node if you need to
  $node = node_load($nid);
}

if($node->uid == $user->uid){
return TRUE;
} else {
return FALSE;
}

```

How do i also display this comment box to the author of the node being referenced?

**Please note:** The Question Content type and Answer Content type are two different content types

Thanks.

ps: I know about the Answers module as well as the Question/Answer modules. Somehow the best answer submodule included with the Answers7.x-4.0-rc2 module is able to let the author of the question flag an answer referencing his question as the best answer

# Answer
> 2 votes
Database query would help you.

```
function my_module_get_author_by_nid($node_nid) {
  $author = '';
  if (is_numeric($node_nid) && $node_nid != 0) {
    $uid = db_select('node', 'n')
        ->fields('n', array('uid'))
        ->condition('nid', $node_nid, '=')
        ->execute()
        ->fetchField();
    return $uid;
  }
}

```

// And then a slight change in your code

```
    global $user;
    if (arg(0) == 'node' && is_numeric(arg(1))) {
      // Get the nid
      $nid = arg(1);

      // Load the node if you need to
      $node = node_load($nid);
    }

     // Get Reference Node Nid
    $reference_nid = $node->your_reference_field_name[$node->language][0]['target_id'];
    // Get Author for reference Node
   $reference_author =  my_module_get_author_by_nid($reference_nid);
    if($node->uid == $user->uid || $user->uid == $reference_author){
      return TRUE;
    } else {
      return FALSE;
    }

```

---
Tags: 7, entities
---


# Question
Title: How to display the View according to the logged user?
I'm Creating a view of a specific content type called "requests (Demande)" , Each request is assigned to a specific user (I have two users : "Salaktarus" and "Zaferro") , what I want to know is how to configure the filter so each user ("Salaktarus" or "Zaferro") sees only the requests which he/she is assigned to.

# Answer
Add a relationships based on user who is assigned in the request (if he/she is assigned using a reference field , select that field) , then create a filter based on user (the user who is currently logged in and is viewing the table) , use relation to relate user to nodes which he/she is assigned to.
> 0 votes

---
Tags: users, entities, views
---


# Question
Title: Create a permanent list of a content type
I have a content type named "clients" which can be filtered within a view and all can be selected using bulk operations.

What I would like to do is take the filtered list in the view and copy it to a permanent list of content on my site. So that it is saved and can be accessed at a later date without having to go through the filter options again.

For example, to store a list of clients all from one country, say Germany, to a list of these clients named Germany.

Any ideas how I would do this?

# Answer
Views Save module can help you. The module page says

> This projects allows admins to add a "Save" button to their views (on a per-view basis). This button allows logged-in visitors to save their current exposed filter settings on the site, so they can later return to the same page. The saved views are stored per user, and can be listed with Views themselves, to provide users with an overview of all their saved views. Saved views can also be overwritten with new settings.
>
> Anonymous users are offered a way to log in or register when trying to save a view – if they do, the view is saved to their (possibly new) account, otherwise it is purged after a while.
> 3 votes

---
Tags: input-formats
---


# Question
Title: Automated database history save and recovery Drupal 7
I have a site implemented in Drupal 7. I want to make a history database recovery tool, which will recover previously recorded MySQL data. I have tested correctly on non-Drupal content which is used by the site. If I want to recover previous versions of Drupal content (just nodes and the info related), should I use a collaboration module? Which would be recommended? Should I restore the complete database or could I mysqldump and later mysql some selected tables (fields\*, node\*, etc.). Thanks!!!

# Answer
Take a look at Backup & Migrate Module:

> Back up and restore your Drupal MySQL database, code, and files or migrate a site between environments. Backup and Migrate supports gzip, bzip and zip compression as well as automatic scheduled backups.
>
> With Backup and Migrate you can dump some or all of your database tables to a file download or save to a file on the server or offsite, and to restore from an uploaded or previously saved database dump. You can choose which tables and what data to backup and cache data is excluded by default.
> 0 votes

---
Tags: 7, database
---


title: View cache clear on node create

text:
# Question
Title: View cache clear on node create
I've searched a lot of this but all kind of cache issues appear not related to this. If this has already been asked I apologize.

I just want to know if this is an embedded feature or a module is needed for this.

My homepage has 12 VIEW blocks with very complex queries so you could imagine that non caching them is not an option.

Some of the views retrieve the latest nodes so my question is: when a user creates a new node, is there a way to clear the block cache on new nodes? If I cache the block for an hour, the rest of the users won't see the new node until an hour passed.

Thanks

# Answer
> 3 votes
The combination of Rules module and Cache Actions module should solve your issue.

# Answer
> 0 votes
You could done this without contrib modules.

```
function hook_node_insert($node) {
  if ($node->type == 'something') {
    //clear particular views cache here
    cache_clear_all('MY_VIEW_NAME', 'cache_views_data', TRUE);
   }
}

```

---
Tags: views, blocks, caching
---


# Question
Title: Is it possible to enable the title field for the module views slideshow?
I'm working with the module views slideshow and was just curious if anyone knew how to enable to title field for the images you upload for it. The alt text field is enabled but not the title field.

And no you don't just go to edit the field.

# Answer
> 0 votes
I figured it out. The options to add alt and title fields are in the field collections module and not in the field that the field module creates. So look in the field collections module if you have this problem.

# Answer
> 1 votes
Consider looking at Views Slide show Content title and description modification, which details the steps to do this, such as:

* Set the title field to "exclude from display".
* Check the option "Rewrite the output of this field".
* Put the token in a DIV, and style with CSS as needed.

---
Tags: views, 7, media
---


# Question
Title: Why can't I see the settings for the customfilter module in the Drupal admin?
I'm following this tutorial to add a custom filter using the Custom Filter module. I've installed and enabled the module.

However, when I try to navigate to `/admin/settings/filters` like it suggests, there is nothing there nor can I see any settings for the Custom Filter module anywhere in the admin interface.

What do I need to do to get this module working?

# Answer
> 0 votes
> when I try to navigate to /admin/settings/filters like it suggests

I'm not sure where you've seen that, but looking at the code, it's wrong. Maybe you're following a tutorial for a previous version of Drupal.

Either way, the config path for the D7 version is **admin/settings/customfilter**.

---
Tags: 7, input-formats
---


# Question
Title: Multisite cannot find module in sites/default
I haven recently set up a multisite setup with Live, staging and tag as the domina/subdomains used by the code

in the sites directory I have the modules set up like so:

```
sites/all/modules/<modules shared by ALL sites>
sites/default/modules/<modules ONLY used by default>
sites/tag.example.com/modules/<modules ONLY used by tag>
sites/staging.example.com/modules/<modules ONLY used by staging>

```

in the default, staging and tag modules directory are independent copies of modules that I am developing.

However when I add new urls to hook\_menu() in any module in staging it is not picked up at all, only when the function is populated to sites/all

further to this, the modules disappear from the admin/modules page

on top of this there is this next issue.

If I place My\_Module into the default and staging folder there are times that it either says that a function name cannot be found (when it is blatantly using the module) OR even worse is when it says I cannot re-declare a given function name

So can anyone point out if I am doing something wrong?

Am I putting the modules in the correct places because when I have EXACT duplicates of a module in separate site folders (staging and default but not all) I am able to edit the content and see that the content has been edited but not add new urls/functions that get picked up.

And YES I am flushing all caches when uploading new hook\_menu() items and function changes etc

Any Help is appreciated.

Thanks, Jim.

# Answer
So this was the issue,

When I created the sub-domain i used cpanel, even though I specified

/home/\<username\>/\<subdomain-name\>

as the home directory path,

it would override it in the vhost entry to:

/home/\<username\>/public\_html/\<subdomain-name\>

so, even though I created the symlink at the right place, it never hit it, so when I went to the subdomain url is was picked up by the drupal htaccess as a url to the live site

lots of confusion and lots of annoying behaviours

As soon as I edited the vhost entry to the corect path, everything worked correctly

thanks for all the reads though

Jim
> 0 votes

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


title: Form does not save value to variable

text:
# Question
Title: Form does not save value to variable
I'm loosing my head. This is the function for generating my admin form:

```
function section_description_and_images_settings() {
  $form = array();

  $form['images_style'] = array(
    '#type' => 'radios',
    '#title' => t('Set default images style'),
    '#options' => array(
      0 => t('Bootstrap columns'),
      1 => t('Slideshow'),
    ),
  '#default_value' => variable_get('section_description_and_images_images_style', 0),
);

  dsm(variable_get('section_description_and_images_images_style', 0));
  return system_settings_form($form);
}

```

And variable section\_description\_and\_images\_images\_style does not store the desirable value. It's always 0, whether I set 0 or 1.

Any ideas what might be wrong?

# Answer
Variable name is "images\_style" in your case
> 1 votes

---
Tags: forms, configuration
---


# Question
Title: How can I view & access all available variables for a Drupal Commerce cart?
For theming purposes I'm trying to access any and all available Drupal commerce cart variables. For starters, I want to give the user feedback regarding the cart in the global nav.

I thought these vars would be available within the $\_SESSION var but not so(?).

an example of what i’m trying to do is as follows, via some pseudo code to be put into the global nav…

```
<!—- Global nav—->
<li>Cart
    <?php  if($items_in_cart == true) {
        echo ‘*’;
     } ?></li>

```

or,....

```
<?php
if($items_in_cart) {
print $total_items_in_cart;
}?>

```

# Answer
You can use the function `commerce_cart_order_load` & `commerce_line_item_load()` to load the current order(cart) object & order product objects respectively:

```
  global $user;
  $order = commerce_cart_order_load($user->uid);
  $cart_items = array();
  foreach ($order->commerce_line_items[LANGUAGE_NONE] as $line_item) {
    $cart_items[] = commerce_line_item_load($line_item['line_item_id']);
  }

```

In this example, `$order` contains the Commerce order(cart) object for the current user & `$cart_items` contain an array of line item (order products) objects.
> 2 votes

---
Tags: commerce
---


# Question
Title: Boost won't work after configuration of .HTaccess
## Preliminary data

It seems I've configured .HTaccess right, as required by the following guide to installing Boost, But it also seems the module doesn't work.

What I did was to copy my .HTaccess **auto generated rules** from `admin/config/system/boost/htaccess/generator` and paste it exactly instead of the sentence "-------paste the rules right here--------" mentioned above, but I don't know if that was the true intention of the author...

Anyway, the final outcome is this:

```
# RewriteBase /

### BOOST START ###

# Allow for alt paths to be set via htaccess rules; allows for cached variants (future mobile support)
RewriteRule .* - [E=boostpath:normal]

# Caching for anonymous users   # Skip boost IF not get request OR uri has wrong dir OR cookie is set OR request came from this server OR https request
RewriteCond %{REQUEST_METHOD} !^(GET|HEAD)$ [OR]
RewriteCond %{REQUEST_URI} (^/(admin|cache|misc|modules|sites|system|openid|themes|node/add|comment/reply))|(/(edit|user|user/(login|password|register))$) [OR]
RewriteCond %{HTTPS} on [OR]
RewriteCond %{HTTP_COOKIE} DRUPAL_UID [OR]
RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule .* - [S=3]

# GZIP
RewriteCond %{HTTP:Accept-encoding} !gzip
RewriteRule .* - [S=1]
RewriteCond %{DOCUMENT_ROOT}/cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html\.gz -s
RewriteRule .* cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html\.gz [L,T=text/html,E=no-gzip:1]

# NORMAL
RewriteCond %{DOCUMENT_ROOT}/cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html -s
RewriteRule .* cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html [L,T=text/html]

### BOOST END ###

# Rewrite URLs of the form 'x' to the form 'index.php?q=x'.
# Pass all requests not referring directly to files in the filesystem to
# index.php. Clean URLs are handled in drupal_environment_initialize().
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]

```

## Why I'm assuming a problem?

On one hand, Drupal's CRON tells me *Boost installed correctly, should be working if properly configured.* On second hand, while surfing from another browser anonymously, I checked page source (CTRL+U), But didn't the famous message (as HTML note):

> Page cached by Boost @ YYYY-MM-DD HH:MM:SS, expires @ YYYY-MM-DD HH:MM:SS, lifetime X hours

Therefore, I assume a problem. Now, as Shawn instructed in the comments below, I turned on the Boost debugger, went to Reports \> Recent log messages, and then saw two interesting errors:

**First error:**

```
Array
(
    [cache_this] =>
)

```

**Second error:**

This error is to long to be pasted here, but it seems to do something with Drupal's Autocomplete mechanism.

# Answer
You can verify Boost is working by browsing a page as an anonymous user (e.g. using your browser's Incognito/Private Browsing mode) and looking at the source code of the page. If Boost is working you should see a HTML comment at the bottom of the document that looks like this:

```
<!-- Page cached by Boost @ YYYY-MM-DD HH:MM:SS, expires @ YYYY-MM-DD HH:MM:SS, lifetime X hours -->

```
> 0 votes

---
Tags: caching
---


# Question
Title: How to link to a page view from a template file?
If I were linking to a node via a template file I would write something like this...

```
<a href="<?php echo url('node/22'); ?>">Back to blog</a>

```

I get that node ID by hovering over the node under 'Admin \> Content' and looking at the node number that pops up when I hover over the 'edit' link in the bottom left (in Chrome). In the screenshot attached I've hovered over the 'edit' link alongside the node 'Head of Development' which shows node/5 in the bottom left.

The issue I've got is that I want to link back to a page view which doesn't show alongside all the other content. Thanks in advance.

# Answer
> 0 votes
Assuming the View is set up as a page, you are required to define the path under Page Settings:

So, given this example you would create a link with:

```
<?php print l(t('Link to Monkey!'), 'monkey'); ?>

```

You can find more information on the l() function here

# Answer
> 0 votes
I would recommend you to use  function to build links in Drupal.

```
  <?php print l(t('Back to blog'), 'node/22'); ?>

```

I see Content administration page on you screenshot. If you want to build link to this page you may use next piece of code

```
  <?php print l(t('Content'), 'admin/content'); ?>

```

---
Tags: views
---


# Question
Title: why is admin not bypassing restrictions at views?
I have a problem of admin not having full access to content nodes. I wanted to create a view so that a user can see nodes he created and cannot see other users' nodes. However, 'admin' should be able to see all available nodes without any restricts, even if made.

My problem is that, when it comes to restricting the users to see only their nodes posted. Strangely the admin was included to see only his own posts as well! (even though the settings where telling me that whatever setting I make, the admins will not be affected) but that doesn't seem to be the case.

Does any one have any idea or suggestion?

I have gone to permissions, and checked ALL values to be selected. I rebuild the permission. Yet, this is happening.

Just in case I thought some module might be interfering, I had NodeAccessdisabled and some other modules, but the result is the same! The admin is not getting a full view as supposed to when restricting!

Here's a screen shot of a user view and admin, currently as an admin (aziz here), this is what I see (3 nodes created by admin):

and those are the setting:

While on the other hand, when I created another view WITHOUT restrictions, it shows all nodes:

and here are the settings for it:

Anyone has any idea why the admin is included in restriction?

Let me know if you think there's anything wrong here. Because based on my other question is the post " how to view data row table related to user only?" I was advised to follow these setting (as in image, and the user who advised is working very well with him). But I think that there's something interfering with my admin role for not letting it bypass restrictions made (at least, even when I do restrict the view for users, admin shouldn't have been included).

My last hope in the admin restriction is creating 2 views for every content type, which is quite troublesome.

I hope I gave clear picture.

# Answer
> 1 votes
In your 2nd screenprint, within "filter criteria", the last line of it is says "Content: Author uid (=aziz)". That doesn't seem to be correct ...

Make sure the filter criteria only has "Content: Author uid" without "Author user: current". And keep the ID blank for the author uid, because specifying the user will only refer to the nodes published by THAT user only.

---
Tags: 7, users, views
---


# Question
Title: How to show a view page but hide all the content in the view for certain roles?
Working on a membership site built on Drupal and am aiming to hide the **content** of certain views pages on the site unless the user has a specific (membership) role.

However, setting view page access control hides the entire page — including title and its very existence (page disappears out of nav menus, etc.). My goal is to show the page is still there (almost as a teaser), allow anonymous users to click on it, but hide all of the body content (fields, etc.) if the user does not have the correct role. That body content should then be replaced by a message to subscribe to the membership.

Is that doable with views or another module ? If so, how? Any suggestions?

Note: I'm already using the Field Permissions module to hide some of the same fields on other pages using roles. As such, I can't apply that module for this use.

Edit: We're using views to generate 800+ pages automatically (tokenized paths, etc.). That adds a layer of complexity — any solution has to be able to scale easily.

# Answer
> 1 votes
For a quick and easy solution use panels.

1. Use panels to display your view on the page for that specific user role.
2. Inside the variant portion, swap the panels to a *general text area* for anonymous users.

very useful links:

Creating Different Versions of Same Page Variants (watch all the free videos)

Can one apply a panels layout to a view page?

# Answer
> 1 votes
Thanks to those who replied! I've found a solution using only the Views module that so far appears to do the trick in a light way. This combines elements of Geoff's response with some Views module trickery.

Views allows multiple views to have the same path, simply showing them according to display order (in the generic view admin, this would be horizontally left to right). Knowing that, the basic steps are:

1. **Clone the page display and rename it.** I cloned the page display that already has the fields and page info in place, leaving url (and title settings) the same. Renamed the admin name to reflect that it is for "Non-Subscribers", or similar. All publicly visible information remains the same.
2. **Change the filters to ensure no content is displayed.** There are a variety of options when doing this. I changed the filters on the new page to select "Content Type: Is not one of:" and selected all of the existing content types. Note that this particular selection will not add newly-created content types to the exclusion list automatically, so may not be ideal for all sites. Taxonomy might be another way to address this — whatever will ensure no content shows for your site at all times.
3. **Set "No Results" message.** Under Advanced, I set up a No Results unfiltered text message that tells people that they have to subscribe to see this content, what they are missing, and how to subscribe. (I use unfiltered to put custom HTML in there, but unfiltered isn't required.)
4. **Set access permissions on both pages.** I set my "full content" view page to only show for the subscriber role, as well as any other internal "admin" type roles that should see full content. I also set my new "non-subscribers" page to only show for roles that will never see full content by themselves (anonymous, authenticated, etc.). However, setting "non-subscribers" page to specific roles may be unnecessary, because of the display order. See below.
5. **Make sure display order is set correctly.** The "full content" view page should be higher (i.e. farther left) in the display order than the "non-subscribers" view page.

Because views prioritizes based on display, it will show the "full content" view whenever it can (for views with the same url). Thus, in my scenario an admin role user (who is also ultimately an authenticated user) will see the full content view page because it is the higher priority. The lower priority page (with promo text) will not appear for that user at all. However, for users who don't have the role to access the "full content" view page, they will see the next display (at that url) they have access to: the "non-subscribers" view page.

Note: I haven't fully tested this long-term, yet. If anyone has comments on this approach (like where it might not work so well), feel free to add!

# Answer
> 0 votes
it can be done without large modules such as Panels, in fact depending on how you do it, it can easily be done without any extra modules:

* create a content type, 'Dummy Page' for our example - remove the body if you want (or use it to create a page header) and set everything else you want as you want the View Page to encompass
* limit permission to only Admin for creating this content
* create a node for the View, using the Title you would want the View to use

or

* use a module such as Empty Page to create an empty page

> The Empty Page module is a simple empty page solution. It provides an interface that assists in managing "empty" menu callbacks, mostly used for pages that only consist of blocks.

* either case, set a path alias ('ViewPage' for this example)
* build your View as a block - in the block UI limit it the roles you want, and limit it to the ViewPage page
* if you go the Empty Page way, you can also create a block limited to that page with the title or header information.
* you can also create a block on the same page (with either approach) set to only show for Anonymous that shows information about what the page is and that it is limited to authenticated users, maybe with a link to login (or a login block)

**EDIT**

If you want to restrict users from accessing the content universally (not being able to manually input the url), then it's even simpler:

* use Node Access to restrict access of the content types to the preferred roles

> Nodeaccess is a Drupal access control module which provides view, edit and delete access to nodes. Users with the 'grant node permissions' permission will have a grant tab on node pages which allows them to grant access to that node by user or role. Administrators can set default access controls per content type, and also define which roles are available to grant permissions to on the node grants tab.

* set up the View as normal, under Advanced, add a NO RESULTS BEHAVIOUR

Because Views honours the access control, all of the content will be hidden from an anonymous user, so the No Results Behaviour will be shown. However, if there is no content to show to an authenticated user, it will also be show. Therefore, you may want to include a block for the group of content that only shows for anonymous users instead, but the access control would remain the same. Because this acts on the nodes, they can be created however you want and it will still maintain functionality, whether there's 1 node or 10000

**EDIT #2**

Based on the comments, you would need to override the display hook for the View.

```
function THEME(OR MODULE)_views_pre_render(&$view)
{
    global $user;
    if($view->name == 'VIEWS_MACHINE_NAME' && $user->uid == 0)
    {
        unset($view->result);
        $view->empty['area']->options['content'] = 'ENTER NO RESULTS HEADER TEXT HERE!';
    }
}

```

This function runs after the view is ready to go, but before it is displayed. It checks if the current user is anonymous, and then removes all the results, and sets a NO RESULT BEHAVIOUR which displays as a header. You can also create the NO RESULTS BEHAVIOUR in the Views UI, but it would show for authenticated users if no results were found as well - this provides an anonymous only header.

Because you will have many Views and this hook runs on all Views, you need to adapt the IF statement depending on the naming convention you are using for the Views, for example:

```
if($user == 0)
{
  for($i = 0; $i < NUM_VIEWS; $i++)
  {
    if($view->name == ('VIEWS_BASE_NAME' . $i))
    {
      ...
    }
  }
}

```

This could similarly be done at the Field level using hook\_views\_field\_data\_alter, but you would still want the above to set the anonymous header information

---
Tags: views
---


# Question
Title: Cannot run drush rsync - PHP Fatal error in sitealias.inc
drush rsync @ dev @stage

> PHP Fatal error: Unsupported operand types in /usr/local/share/drush/includes/sitealias.inc on line 1468

Drush command terminated abnormally due to an unrecoverable Error:

> Unsupported operand types in /usr/local/share/drush/includes/sitealias.inc, line 1468

# Answer
Found an error in my alias files. I had a space between SQL username and password.

```
$aliases['devyau'] = array(
  'uri'=> 'dev.[sitename]',
  'root'=> '/var/www/vhosts/dev.[sitename]/',
  'db-url' => 'mysql://[username]: [password]/devDBname',
);

```
> 0 votes

---
Tags: drush
---


# Question
Title: Get the current range values from a QueryAlterableInterface
As far as I can see this isn't possible outside of `QueryAlterableInterface`, because the `$this->$range` variable is protected, and the `range()` method can only be used as a setter.

I suppose I could implement my own class that extends `QueryAlterableInterface` and adds in a method to expose the protected field... but I would have no idea how to get Drupal 7 to use the new class instead of its core one. Not to mention this would be quite over-kill.

Any better ideas?

## Context

I am attempting an external (i.e. outside of hacking the Reference module) general code fix for something similar to the following issue:

References module doesn't specify/read a pager limit when field is using a view to generate potential references

I have come across another instance where this is causing my site a problem, but I can't apply the specific fix found in the Q/A above. Mainly because the code takes a different route through the References module. Rather than my field using a view to generate its "potential" reference values — as in the previous Q/A, which makes it quite identifiable — it is instead just a field that relies on a direct query to source its values. This direct query still has the same problem of attempting to list far too many values, to the point of timing out.

My plan is to detect the particular query involved, and see if it has no limit applied, and then set a safe limit — so that the views UI doesn't attempt (and fail) to generate thousands and thousands of checkboxes. I can probably find a way to detect the specific query, but I don't think I can tell if a limit is set or not.

```
function hook_query_alter(QueryAlterableInterface $query) {
  if ( $query->getMetaData(...) == ...) {
    $query->limit(); /// this does not return the limit value.
    $query->limit; /// triggers an protected access error.
  }
}

```

## A different way to find this question

I realised that with the way I've posed this question, only those who know the underlying cause will be able to find a possible solution. So just as an aid to those who might searching for this specific problem — as it is easy to reproduce if you have a good sized database — here are some key search terms.

### Unable to add a filter to a View for a Reference field

When attempting to add a Reference field as a filter for a View, using the Views UI, the Ajax request seems to hang. After max execution time triggers the following error:

```
An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /admin/structure/views/ajax/config-item/related_nodes/default/filter/field_node_related_nid
StatusText: parsererror
ResponseText: Fatal error: Maximum execution time of 60 seconds exceeded in /var/www/drupal/includes/common.inc on line 6642

```

# Answer
Luckily (or thankfully) the Reference module adds some rather useful information as meta data to the query in question. Making it easy to spot in terms of its id *(although you have to watch out that the id is prefixed with a whitespace character)*. This is the same id for all similarly made queries. It also records the `$options` array, which means we have a reference to the `['limit']` value without going through the `$query` object.

I've set the following to work for any field, but have left reference to the `$field` in use just in case it is useful for others. For my purposes 300 rows is a suitable default to have, rather than just accepting an infinite number or records.

Whilst this doesn't access the limit/range value from the query itself, it does solve the problem in quite a general way.

```
/**
 * Implements hook_query_alter().
 */
function HOOK_query_alter(QueryAlterableInterface $query) {
  /// trim due to typo in references module (took me a while to spot this)
  $id = trim((string) $query->getMetaData('id'));
  if ( $id === '_node_reference_potential_references_standard' ) {
    $field = $query->getMetaData('field');
    $options = $query->getMetaData('options');
    if ( !empty($options) && (empty($options['limit']) || !$options['limit']) ) {
      drupal_set_message('Modifying Node References query to ' .
        'protect against too many values (limited to 300 values)');
      $query->range(0, 300);
    }
  }
}

```
> 1 votes

---
Tags: views, nodes, database
---


title: Creating a (candidate) template file

text:
# Question
Title: Creating a (candidate) template file
Drupal: 7.x Theme: Bartik

I am using the newly created Commune module to display wall posts on a user's profile page (panels.) Each post has a form below it for comments. The comment form is created by the commune module.

I am trying to theme that comment form but I can't find a candidate template file using Themer Devel. The closest template file is commune.tpl.php (in the core module/commune directory) but this includes a bunch of stuff I don't want to include in the theming.

How do I go about finding a candidate template file or creating one I can use to theme the comment form?

Thanks. :)

# Answer
> 1 votes
The default way to find theme template names as of Drupal 7.33 is to enable theme\_debug in your settings.php file. If the template name is available then you should see it in the rendered markup of the page by using your browsers inspect element feature. You can read more about how to find template names here: https://www.drupal.org/node/1089656

As for the certain template name you are looking for, there may or may not be one depending on what the developer used to create the markup. Sometimes the markup is made in a different way for performance reasons. You will probably have to inspect the module code to get the answer there. If I have time over the weekend I may dive into that but hopefully you can find it with the theme\_debug feature.

---
Tags: theming
---


title: drush sql-sync fails

text:
# Question
Title: drush sql-sync fails
drush sql-sync @devyau @stageyau returns:

```
Call to a member function dump() on a non-object in
/root/.composer/vendor/drush/drush/commands/sql/sql.drush.inc, line
275

```

echo $PATH returns:

```
/root/.composer/vendor/bin:/usr/lib64/qt-3.3
/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:
/root/bin

```

drush @devyau uli returns:

```
Call to undefined function drush_sql_get_class()
in /root/.composer/vendor/drush/drush/includes
/environment.inc on line 366

```

drush @stage uli returns:

```
call to a member function db_spec() on a non-object in
/root/.composer/vendor/drush/drush/includes/environment.inc, line 370

```

Here's environment.inc lines 361 to 378:

```
/**
* Tests the currently loaded database credentials to ensure a
database connection can be made.
     */
function drush_valid_db_credentials() {
try {
    $sql = drush_sql_get_class();
    if (!$sqlVersion = drush_sql_get_version()) {
      return FALSE;
    }
    if (!$sqlVersion->valid_credentials($sql->db_spec())) {
      return FALSE;
    }
    return $sql->query('SELECT 1;');
  }
  catch (Exception $e) {
    return FALSE;
  }
}

```

drush ard returns:

```
The external command could not be executed due to
an application error. Unable to determine sites directory for
devyau. Archive saved to /root/drush-backups/archive-dump/20150703220104
/none.20150703_220105.tar.gz

```

drush status returns:

```
 PHP executable         :  /usr/bin/php
 PHP configuration      :  /etc/php.ini
 PHP OS                 :  Linux
 Drush script           :  /root/.composer/vendor/drush/drush/drush.php
 Drush version          :  7.0.0
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :  /etc/drush/prodyau.alias.drushrc.php
                           /etc/drush/devyau.alias.drushrc.php
                           /etc/drush/stageyau.alias.drushrc.php

```

devyau.alias.drush.php:

```
 <?php
 $aliases['devyau'] = array(
 'uri'=> 'dev.[sitename]',
 'root'=> '/var/www/vhosts/dev.[sitename]/',
 'db-url' => 'mysql://[username]:[password]/devDBname',
  );
?>

```

stageyau.alias.drush.php:

```
?php
$aliases['stageyau'] = array(
'uri'=> 'stage.[sitename]',
'root'=> '/var/www/vhosts/stage.[sitename]',
'db-url' => 'mysql://[username]:[password]/[stageDBname]',
  );
 ?>

```

Been working on this one for a week. Stumped. Any ideas?

# Answer
> 1 votes
Your site doesn't look like it is bootstrapping completely. So I would suggest that you see if `drush status` will complete in the `sites/default` or `sites/sitename` folder. It should look something like the full output below.

**A full `drush status` output**

```
Drupal version                  :  7.38
Site URI                        :  sitename.com // could be http://default if you have not set your site url
Database driver                 :  mysql
Database username               :  db_user
Database name                   :  db_name
Drupal bootstrap                :  Successful
Drupal user                     :
Default theme                   :  default_theme
Administration theme            :  admin_theme
PHP executable                  :  /usr/bin/php
PHP configuration               :  /etc/php5/cli/php.ini
PHP OS                          :  Linux
Drush script                    :  /usr/local/bin/drush-master/drush.php
Drush version                   :  8.0-dev
Drush temp directory            :  /tmp
Drush configuration             :  /usr/local/bin/drush-master/drushrc.php
Drush alias files               :  /usr/local/bin/drush-master/includes/../aliases.drushrc.php
Install profile                 :  install_profile
Drupal root                     :  /var/www/html/docroot
Site path                       :  sites/default // Could be sites/sitename.com
File directory path             :  sites/default/files // Same thing here could be sites/sitename.com/files
Private file directory path     :  /vagrant/private
Temporary file directory path   :  /tmp

```

**To help this is my alias setup I usually use**

This is what I usually use to setup my complete drush alias, it has options that most do not need but it may help someone in the future setup their drush alias that they may have not known existed. If you don't use the "path-aliases" below then you need to use "default" or whatever the "sites/sitename" folder name is named. You can see this in the example alias file from drush.

```
$remote_sites = '/path/to/site'; // usually /var/www/drupal-root-name
$aliases['site.dev'] = array(
  'uri' => 'sitename.com',
  'remote-host' => '{ip to remote}',
  'remote-user' => '{remote ssh user}',
  'root' => $remote_sites,
  'ssh-options' => '-p {if you ssh in on another port like 2222}',
  'path-aliases' => array(
    '%drush-script' => '/root/.composer/vendor/bin/drush', // This is so you can have multiple drush installs and use different ones on different sites.
    'php'=> '/usr/local/bin/php', // Again if you have different php's for different sites.
    '%site' => 'sites/default/', // This is the important part here, it will ensure the proper bootstrap
    '%dump-dir' => '/path/to/drush.dbdumps', // This is where you want to dump your databases, normally /tmp folder I think.
    '%files' => $remote_sites . '/files' // Your sites file folder, incase it is somewhere else.
  ),
  // You may actually need this, especially if you are running D7 since I haven't ever tested the db-url thing on D7 or above.
  'databases' => array (
    'default' => array (
      'default' => array (
        'driver' => 'mysql',
        'database' => '{db_name}',
        'username' => '{db_user}',
        'password' => '{db_pass}',
      ),
    ),
  ),
);

```

After writing the answer I was thinking that this may be a D6 question but I answered assuming the opposite. If that is the case please let me know and I will try to answer for D6 also if there are in fact any differences. Hope this helps, thanks!

---
Tags: drush
---


# Question
Title: Bootstrap CDN still being referenced in subtheme, turned off
These are the setting in my .info for my subtheme:

```
;;;;;;;;;;;;;;;;;;;;;
;; Stylesheets
;;;;;;;;;;;;;;;;;;;;;

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

; For information on choosing the desired method, please read the Drupal
; Bootstrap sub-theme "how-to" documentation:
; https://drupal.org/node/1978010

;----------------------------------
; METHOD 1: Bootstrap Source Files
;----------------------------------

;;;;;;;;;;;;;;;;;;;;;
;; Scripts
;;;;;;;;;;;;;;;;;;;;;

; scripts[] = 'bootstrap/dist/js/bootstrap.min.js'
scripts[] = 'bootstrap/js/affix.js'
scripts[] = 'bootstrap/js/alert.js'
scripts[] = 'bootstrap/js/button.js'
scripts[] = 'bootstrap/js/carousel.js'
scripts[] = 'bootstrap/js/collapse.js'
scripts[] = 'bootstrap/js/dropdown.js'
scripts[] = 'bootstrap/js/modal.js'
scripts[] = 'bootstrap/js/tooltip.js'
scripts[] = 'bootstrap/js/popover.js'
scripts[] = 'bootstrap/js/scrollspy.js'
scripts[] = 'bootstrap/js/tab.js'
scripts[] = 'bootstrap/js/transition.js'

; Disable BootstrapCDN if using Bootstrap source files in your sub-theme.
settings[bootstrap_cdn] = ''

```

When I view source I'm seeing this:

```
<link type="text/css" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css" media="all" />

```

Where is that coming from? Unless I've misread the settings above should have removed that. Several cache clears and it's still there.

# Answer
If you haven't downloaded the bootstrap source files then the CDN will still load I believe. Once you download and place bootstrap inside of your subtheme then the bootstrap source files should load then. The docs mention this but I don't think it's very obvious but you have to download bootstrap and compile the styles.css file from styles.less and that should include your bootstrap styles. So if that file doesn't exist that may be the issue. Or bootstrap just not being there all together. It's been a while since I setup from scratch, I use the dev version and have drush setup everything now.
> 0 votes

---
Tags: theming
---


title: Compute 3 New Date Fields

text:
# Question
Title: Compute 3 New Date Fields
What is the best way to output 3 new dates relative to the first date? For instance, I have a date field called "medication\_start" = 1/1/2010. I would like three new dates generated in 3 new fields in 6, 12, and 18 months from the start date.

Period 1 (6 months): 6/1/2010 Period 2 (12 months): 12/1/2010 Period 3 (18 months): 6/1/2011

# Answer
> 0 votes
You can use views\_php module. This module adds a field to the view and it also provides a few tokens. You can use the current row values. Note that you have to insert the main fields before the *PHP* field and exclude the *Price* field from display, Then the `$results,$data,$row` objects will give you the value of the row, Do the mathematical calculations and output the result.

# Answer
> 0 votes
You could use something like Computed Field for this or you can write your own custom module. You could hook into node save using hook\_node\_presave (since it acts on save and presave) and calculate the other 3 fields that you need to save. Either way should work pretty well. You would just use php date functions to calculate the new dates either way. There are a bunch of examples for computed field online and in their documentation you could use to draw inspiration from.

# Answer
> 0 votes
you can use math field too:

> The Math Field module defines a new field type to dynamically calculate values on entity forms. This is an alternative to Computed Field that does not require the use of PHP Filter.

this works much simpler than Computed field. enjoy

---
Tags: datetime
---


# Question
Title: What is the order of execution and redering of hooks and page components?
In order to have a better understanding of what Drupal does, I need to find out what the order of execution of hooks and page components is.

A page layout in Drupal consists of HTML, regions, nodes, blocks, Views and ... . Every one of these components have lots of preprocess or process functions, like `hook_preprocess_node`. There are also template functions, theme functions and ... that are run to build the page array.

To avoid my question to be too broad, let's only talk about the hook and preprocess functions not the core functions.

Thanks.

# Answer
> 2 votes
Consider looking at the X-ray module also. From its project page:

> X-ray module gives a look at the skeletal structure of a site to help developers and site builders see how things work.
>
> **Features**:
>
> * A technical summary is added to the help above the main administrative sections. For example, blocks, content types, and menus are summarized on Structure; themes on Appearance; etc.
> * A table of permission titles matched to their permission machine names.
> * A table of most\* hooks which Drupal invokes (and when they are invoked) and that are available to be implemented.
> * The function and arguments producing each page you visit, displayed on that page.
> * The form ID of every form you see, displayed on the form.

# Answer
> 0 votes
Information about modules is stored in the 'system' table. You can find there 'weight' column, order of execution of all hooks and preprocess functions depends from the module weight. But it can be changed using hook\_module\_implements\_alter function.

---
Tags: 7, theming, hooks
---


# Question
Title: hook_form_alter function does not call the validate function?
i'm creating a unique field module which restrict a user with specific role to create one node per year. it works first but after installing some modules Automatic Nodetitles, Cancel Button, Field Permissions, View profiles permissions, More Buttons Content my custom module does not work. its hook\_form\_alter function works but hook\_form\_validate function does not work.

```
function uniquefield_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'target_achieved_node_form' || $form_id ==  'target_node_form') {
    $form['#validate'][]  = 'uniquefield_form_validate';
  }
}
function uniquefield_form_validate($form, &$form_state) {
  $user = user_load_by_name($form_state['values']['name']);
  if ($user) {
    if($form_state['values']['type'] == 'target_achieved' &&  in_array('vidyakjatha', $user->roles)) {
      $query = new EntityFieldQuery();
      $query->entityCondition('entity_type', 'node')
     ->entityCondition('bundle', 'target_achieved')
     ->propertyCondition('status', 1)
     ->propertyCondition('uid', $user->uid , '=');
     if ($form_state['values']['nid'] != '')
       $query->propertyCondition('nid', $form_state['values']['nid'] , '<>');
       $query->fieldCondition('field_achieved_year', 'value', $form_state['values']['field_achieved_year'][LANGUAGE_NONE][0]['value'], '=');
       $result = $query->execute();
     if (isset($result['node'])) {
       form_set_error('field_achieved_year', t('You have already added target achived status for year !year.', array('!year' => date('Y', strtotime($form_state['values']['field_achieved_year'][LANGUAGE_NONE][0]['value'])))));
     }
   }
  }
}

```

# Answer
as your validating just one field - at least, it seems like it; consider using:

```
function uniquefield_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'target_achieved_node_form' || $form_id ==  'target_node_form') {
    $form['your_desired_field']['#element_validate']  = array('uniquefield_validate');
  }
}

```

on the fileds in your alter hook
> 0 votes

---
Tags: forms
---


# Question
Title: How can I rearrange taxonomy weights for terms with two-deep hierarchies?
I have a taxonomy vocabulary on my site of user ages.

It looks like this:

However, I want to change the weight so that 20s is -19, Late Teens is -18, Early 20s is -17, etc. In other words, I want to change the weight so that when I sort by weight in Views, the terms appear in exactly the same order as shown on the screen above.

However, when I manually adjust the weights to -19, -18, -17, etc., upon saving the list of terms the weights are reverted to those listed above.

I tried individually dragging and dropping each term to change the order, but again when I saved the list, the weights had returned to this pattern:

* Parent A 0
* A Child A 0
* A Child B 1
* A Child C 2
* A Child D 3
* Parent B 1
* B Child A 0
* B Child B 1
* B Child C 2
* Parent C 2
* Parent D 3

etc.

However, when sorting by weight in Views, this then gives a list like:

* Parent A
* A Child A
* B Child A
* C Child A
* A Child B
* Parent B
* B Child B
* C Child B
* A Child C
* B Child C
* Parent C
* C Child C

which looks terrible and makes no sense.

How can I manually control the weights and override whatever processing Drupal is applying to them?

# Answer
> 4 votes
For such small taxonomies (large and frequently changing ones will be a pain) you may create special custom field for flat sorting order, since weights are meant to be used on a certain hierarchy level:

Then you just add some sort criteria to your views:

Considering this terms structure:

you will get this output:

**Good thing:** this requires no code hacking at all, yet supports all Views features like caching.

**Bad thing:** you will go mad with setting this field values for large vocabularies.

# Answer
> 2 votes
This should work to get the desired output in views and enable you to rearrange your terms at will:

1. Configure Relationship: Taxonomy term: Parent term, make this relationship required.
2. Add another (second) field: Taxonomy term: Name, set the relationship to the parent and exclude this from display.
3. Configure sort criterion: Taxonomy term: Weight (asc) and set the relationship to parent
4. Page: Style options, set Grouping field nr.1 to (Parent) Taxonomy term: Name

# Answer
> 1 votes
Try this module: https://www.drupal.org/project/views\_term\_hierarchy\_weight\_field

It will add a normalized weight on every taxonomy term.

Volker solution will exclude parent's terms requiring parent term relation.

# Answer
> 0 votes
You can try Taxonomy Manger module, I think I face an issue in the past similar to your and I sort it with the Taxonomy manger. Give it a shot. http://drupal.org/project/taxonomy\_manager

# Answer
> 0 votes
I suggest you to re-order the view's result, by using a hook\_views\_pre\_render, according to your taxonomy\_tree

```
function custommodule_views_pre_render( &$view ){
  switch ( $view->name ){
    case "myviewname":

      $vid = 1;
      $tree =  taxonomy_get_tree( $vid );

      $result_to_reorder = array();
      //original result
      foreach( $view->result as $result ){
        $tid = $result->_field_data['nid']['entity']->field_term['und'][0]['tid'];
        $result_to_reorder[ $tid ][] = $result;
      }

      $result_reordered = array();
      foreach( $tree as $term ){
        $result_for_tid = isset( $result_to_reorder[ $term->tid ] ) ? $result_to_reorder[ $term->tid ] : NULL;

        if( !$result_for_tid ) continue;

        if( count( $result_for_tid ) >= 0 ){
          foreach( $result_for_tid as $value ){
            $result_reordered[] = $value;
          }
        }
      }
      //set the new result order to the view result
      $view->result = $result_reordered;

      break;
  }
}

```

i hope this could help you

# Answer
> 0 votes
Simply for sorting the taxonomy according to their weights can be done with the help of view .. In the view we can add **sort Criteria** according to the taxonomy terms either in ascending or in descending order....

Cheers...

---
Tags: taxonomy-terms
---


# Question
Title: What is the best way to add user points to existing users
I have a dev and prod versions of my D7 site. On dev I developed some functionality based on `User Points` module and plan to roll out it on prod. But it requires some initial number of user points for every user.

What is the best way to add user points to existing users: SQL query, Rules etc?

# Answer
One method here is to use the Userpoints API and execute a code snippet that will add the points for you. You can reference the userpoints API here. You can do something like this...

```
$initial_value = 10;
//@TODO: Build a list of all $uids in an array
foreach($uids as $uid) { =
  userpoints_userpointsapi(array(
    'uid' => $uid,
    'points' => $initial_value,
    'operation' => "Add Initial User Point Value",
  ));
}

```
> 1 votes

# Answer
I think User Points Contributed modules is a possible alternative to consider. I. e. submodule **userpoints\_retroactive**. Excerpt from that project page:

> Award users points for their nodes, comments and votes that they have created so far, before userpoints was enabled on the site.

However, the port of this module to D7 still **needs work**. Maybe you can/want to somehow contriute to the finishing touch of that issue?

Another approach to consider: create a rule with specs like so:

* **Event** = a user logging in
* **Condition** like "if user points is 0"
* **Action** to set the initial number of user points.

Haven't actually created such rule (yet), but pretty sure that's fairly easy to do.

PS: there is also Berdir's Api documentation about this submodule ... (maybe that helps somehow).
> 1 votes

---
Tags: 7, rules, userpoints
---


title: Contact form is not being translated

text:
# Question
Title: Contact form is not being translated
I have a multilingual Drupal 7 site with following languages enabled:

* Dutch (default)
* French

Now when I enable my sitewide contact form, and navigate to it using Dutch (http://www.mywebsite.com/nl/contact) it is in Dutch (as it should be).

However, when I navigate to what is supposed to be the French version (using http://www.mywebsite.com/fr/contact), it shows me the English contact form ...

I have downloaded & imported the French `.po` file for the contact form to no avail , the contact form stays in English.

Does anyone know a solution to this problem?

# Answer
> 4 votes
Instead of using `.po`-files, install the Localization Update module. It provides a much better interface for downloading, updating and managing translations.

# Answer
> 0 votes
I would suggest you install the Localization Client module as this will help in other translations also.

After installing, when you go to the French contact form (or any other French page), you will see the in-page translation interface at the bottom of the page. Just search for the terms like "Your name", put the French translations and save. Reload the page and you should see the translations.

# Answer
> 0 votes
Make sure the 'Contact Translation' (i18n\_contact) sub-module of i18n is enabled.

If you then navigate to admin/structure/contact and use the "edit" link for any of the available categories, you'll also have a "Translate" tab.

This tab can be used for translating the "*Category*" in the selected langusage, and to translate the "*Auto-reply*" for that language.

Refer to https://www.drupal.org/node/1396984 for more detailed (Community) documentation.

**Note**: the Localization Client and Localization Update modules (suggested in the other answers) are great modules, but they serve a different purpose. They won't help to make the French version of the form show up (instead of the English version of it).

---
Tags: 7, i18n-l10n, emails
---


# Question
Title: How to put conditional multiple recipients in drupal 7 default contact us form
I am working on a multilingual Drupal 7 site using a single contact us form. It has 4 languages. The contact us form is multilingual i.e labels of form fields changes, depending on the language you have selected. But it has a single recipient now.

Now I want it to have conditional recipients i.e if English is selected the contact us form should be emailed to a@gmail.com and if Danish is selected then to b@gmail.com and so on.

Any suggestions how to do it ?

website form : http://dev-salman.com/venuepoint/contact

# Answer
> 0 votes
Refer to my answer to the question "Contact form is not being translated" related to the usage of the i18n\_contact module. That's a prerequisite for the contact form to be available in multiple languages. However it will not allow you to specify an eMail ID for each language.

I'm not familiar (yet) with the tContact module, but it might help to implement what you're trying to setup. Here's an excerpt about it (from its project page):

> ... allows you to make the site-wide contact form fully translated on multilingual sites. Categories can be set to display only in a specific language, or they can be language neutral. Depends on the core "contact" module for the site wide contact form.

If with the tContact module you still can't get it to work, then I'd investigate if sending eMails by using the Rules module you can get it to work. E.g. by using the patch in comment #3 of issue # 1472316. For more details about this issue, visit the question about "Rule condition to check which language is used by the visitor?".

# Answer
> 0 votes
With this module https://www.drupal.org/project/tcontact you can create different contact categories for each language so you can specific different recipients.

---
Tags: i18n-l10n, emails
---


# Question
Title: Rules - Set language of message notification
We need to set up a rule that will send an email in the language of the Customer of an order LANGUAGE.

But the Message notify action in rules takes the CURRENT user **interface** language... so that might be fr or en, depending on the path in fact. The recipient language might be different.

1-Can you tell me what selectors I should use to set the mail language to the customer language? I guess I need to change some kine of data-value?

2-And maybe you can point how I can easily find this in the future. Would DEVEL help? Something else?

thanks!

# Answer
Consider investigating if the patch in comment #3 of issue # 1472316 might be of any help. Even though it is not the exact same question here, it may help to find inspiration about how to answer your question.

For more details about this issue, visit the question about "Rule condition to check which language is used by the visitor?".
> 0 votes

---
Tags: rules, emails, i18n-l10n, notifications
---


# Question
Title: How to display a percentage for a pie chart label using the Charts module?
I'm using the Views integration of the Charts module, with HighCharts as the charting engine.

I want to create pie chart, in which I want to also get the percentage displayed when I hoover over any of the pie slices. I cannot find any specific option to do so.

Anybody any suggestions to get this to working?

# Answer
> 2 votes
This is a typical request for the Charts module ... There is currently no out-of-the-box solution available in the Charts module. But since you're using Highcharts, there is a patch available that may help somehow. The patch is attached to Comment nr 4 of issue #2209467. Be aware of the current status of this issue, i.e.:

* the patch only works for Highcharts (as charting engine), the Google Charts counterpart of it is still missing (and prereq for adding this feature to the Charts module).
* it is related to the Charts API (which is different from the Views integration). So after the Charts API feature gets delivered, some more (minor?) work is needed to also make it available within the Views integration of the Charts module.

The child issues of this issue contain some more variations, which may also help.

So only considering the Charts module as an alternative, and applying the suggested patch is not sufficient. But at least it should help somehow to understand what the missing pieces are. And maybe inspire somebody to submit 1 (or more) additional patch(es) to make it complete?

**Note**: The issue about "Views field as data label for better tooltips" is somehow related to this issue, and specific to the views integration. Comment # 6 in it contains an interesting patch for it also.

**Disclosure**: I'm a maintainer of the Charts module, I hope this does not violate the site's policy on self-promotion.

---
Tags: 7, views, charts
---


# Question
Title: How to conditionally load - and allow a user to populate - a taxonomy image field in node create/edit form?
pardon the bad headline. I have a node with a autocomplete taxonomy field "categories". When a user creates a node, he can add a single term/category to that node.

How would you make it possible to also attach an image to that taxonomy in the same "create" or with ajax?

# Answer
> 2 votes
Might I suggest that you avoid taxonomy all together?

I am not a fan of taxonomy namely because it isn't a reliable way to tag your content. The most obvious is that any variation in the tags creates a whole new tag. For example, if you are doing a web site and you want to use the taxonomy of the different fruit:

```
apple != Apple

```

If you now go and create view to show all related content for "Apple", you won't get anything related to "apple." Technically speaking, you can have 256 (2^8 = 256) permutations of your taxonomy term; not very useful, if you ask me.

***So, the question is, what to use then?***

Use your own Content Types.

For example, I created a content type called "Section" and the only field I have in the content type is "Title" which I renamed to "Section Name". (You can ignore the "URL path settings field." This is because I had *pathauto* installed.)

Next...create some Section Names by adding content. Here I have added two content types: Big and Little.

And if you "Edit" or "View" that piece of content you will see that there is nothing but the one field that you created earlier.

***Next, is to create an entity reference to that content field*** This is where the magic happens. In another content type like "Article" (or whatever you like), create an entity reference field that links back to the "Section" content type.

Here, I have a content type called "Static Content" with just "Title" and "Body". I added an entity reference field called "Section", gave it machine name of "field\_er\_section" for readability, and made it a checkbox/options type of selector.

When you create/edit the field, you must make sure you reference back the content type you first created, in this case "Section".

***How does this all come together? Let's take a look at a new piece of content that we create....***

As you can see, we now have "terms" that the user can select rather than type out.

Where does this come in handy? *How about Views*? You can now add some filters based on your new "Section"

Execute your view and you have all content related to your new term.

Now, if we were to do this with "contextual filters" (found under Advanced in the Views page) you could base your view on the values in the URI. For example, using the section names in my pics above:

```
www.example.com/little/

```

That would display all content related to "Little." You could also create a block view that would display all the titles of related content based on the term in the URI.

***Now, as for your specific question, how do you add an image to your taxonomy term?***

This is a content type, after all. Just add an image field and that image will follow throughout your site.

I hope that gives you a direction to go in and a nice alternative to taxonomy.

# Answer
> 0 votes
You can use References dialog module with this patch

> This module extends reference fields like the user and node reference fields by adding links to add, edit and search for references through a dialog. This allows for a workflow where the user can create all the references to a node at the same time as she is creating it, a process which sometimes get's a bit backwards, when a user for instance needs to create all the facts for an article.

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


# Question
Title: How to adapt the date format in the admin/content page?
Each Article shows "Authored on YYYY-MM-DD" date per configured regional date format. e.g. 2015-05-14 00:00:00 +0100

However, the content listing at `admin/content` shows the `UPDATED` date as MM-DD-YYYY unlike anything else and is confusing to admins.

Users have no choice of Default Time / Region on the Drupal 7.37 site. Date and Time Long, Medium, Short formats are all `... YYYY-MM-DD`

# Answer
> 1 votes
Date (and time) formats can be configured via `admin/config/regional/date-time`. It can be used to specify the format for data types Long, Medium and Short.

Other tabs that are available on that same page:

* Formats (to define your own custom formats).
* Localize (for language specific tuning).
* Date Views (for date views specific to "day", "week" or "month").

# Answer
> 1 votes
The content listing at `admin/content` shows the updated date as **Short** format.

You can change the SHORT format at `admin/config/regional/date-time` from MM-DD-YYYY to YYYY-MM-DD or anything else you want and then the format of updated date at the `admin/content` will change.

---
Tags: 7, nodes
---


# Question
Title: "add content" suddenly not showing on navigation block anymore
Good day, I'm having a problem of a block not showing its content! the block is stock and called navigation, which has "add content" in its links.

but just recently, it has not been working on other users except admin. i checked it setting, and the access control says: "authenticated users" which is good. but the moment i check it at other users (the non admin), i can only see the navigation block with "chaos Ajax demo" ONLY..

i checked around possible permissions, link settings, but with no luck..nothing seemed strange to me..

here's a screen shot of the navigation block at admin: and here's 2nd shot at non admin (was working and showing few days back, but then suddenly became like this):

logically speaking, since the navigation block is existing at other users only means that its permissions is allowed for users to see the block.

but why suddenly it stopped showing the links?? im very much concerned about "add content" link, because i need it to add contents (otherwise, i'll have to go through a headache of creating 10s of manual links for each content to add).

let me note that I'm quit new to drupal, that's why I'm not pretty sure what did i mess with here.

any help is very appreciated, Thanks

# Answer
First a clarification about terminology: make sure to correctly separate access to "blocks" from "navigation links": your non admin users seem to have access to that "block" also (that Ajax link in it proofs that to me). Your real issue/question should be something like "why are some of the menu links missing in that block?".

Seems like you need to resolve that "Access Denied" message first. Even though it's hard to tell (from the screenshots provided), My best guess would be that you need to review/tune some of the settings related to "node" within `admin/people/permissions`.

So check/confirm that for the users who receive this "Access Denied", they are granted the permission like "View Published Content". If that permission was not granted yet, then do so now and try again to see what happens.

A few more "comments" (moved from the comments below to around here):

* The "menu items" that are shown in that block, will be shown (only) to the users who have access to the actual content (node) that the menu items are related to. And apart from that there is the "block visibility", which is typically something you "can" set so that it is only shown (or hidden) on specific pages, or so that it is only shown to users with specific roles.
* About "I didn't want every user to other users' published content": looks like there is something you mis-interprete about the "View published content": that permission is ONLY a way to tell Drupal "which roles are allowed to see anything (nodes) that have the "published" checkbox turned on. It seems to me that you MIGHT need to add something like the (great!) "Content\_Access" module to implement something similar to what you wrote in one of your last comments.
* If it makes sense, you should set the "default" content access for each content type first, so that you only have to change it for those nodes where you want content access to be different from that default. So no need to "go through every content to manage their content access".
> 1 votes

---
Tags: 7, routes, nodes, users, navigation
---


# Question
Title: Move “Submitted By” from node.tpl to page.tpl
I'm looking to move "Submitted By" info from node.tpl to page.tpl however when I add the following from node.tpl into page.tpl I get errors. Im assuming I dont have access to those variables, but would like to know how I can set up a pre-proccess to get it to display as it does in the node.tpl

```
  <?php if ($display_submitted): ?>
    <div class="submitted">
      <?php print $submitted; ?>
    </div>
  <?php endif; ?>

```

# Answer
you can construct your own with something like this, adjust as desired:

```
if(isset($node))
{
    $nodeUser = user_load($node->uid);
    print 'Submitted By ' . l(t($nodeUser->name), 'user/' . $node->uid) . ' on ' . format_date($node->created);
}

```
> 2 votes

# Answer
You can see herci's comment. It's settings to show or hidden submitted. Or you can see code here line below to preprocess variable $submitted

```
// Display post information only on certain node types.
  if (variable_get('node_submitted_' . $node->type, TRUE)) {
    $variables ['display_submitted'] = TRUE;
    $variables ['submitted'] = t('Submitted by !username on !datetime', array('!username' => $variables ['name'], '!datetime' => $variables ['date']));
    $variables ['user_picture'] = theme_get_setting('toggle_node_user_picture') ? theme('user_picture', array('account' => $node)) : '';
  }
  else {
    $variables ['display_submitted'] = FALSE;
    $variables ['submitted'] = '';
    $variables ['user_picture'] = '';
  }

```

You can write some line code in file template.php to set up show or hidden summitted.

```
function YourTheme_preprocess_node($vars){
  $node = $vars ['node'];
  if ($node->type == 'YOUR_TYPE') {
    $vars ['display_submitted'] = FALSE; //hide submitted
  }
}

```
> 0 votes

---
Tags: hooks, theming
---


# Question
Title: Move content from field to field collection
I'm working on a site where a current content type has six image fields, six title fields & six content fields. One field from each (one image, one title & one content) all make up one group, so in total there are six groups of these.

Is it possible to move these into a field collection? I just think it'd be tidier, make more sense & make it easier to maintain.

Also if this is possible, not only how do I do it but is it even wise to move content from a 'normal' field to a field collection like this?

# Answer
You can do it with 3 step

1. In your content type, creat new field collection
2. Write one module, use function hook\_node\_presave(). In this function, you can copy data from old fields to new field collections.
3. Go to page admin/content. Select your content type. Select all node. In tab **UPDATE OPTIONS** chose **Publish selected content** and submit. This action to do run code your module write in step 2.
> 1 votes

---
Tags: 7, entities
---


# Question
Title: Bypass comment validation for SOME anonymous users, based on the provided email address?
In the case of a low traffic blog (for instance), that only accepts anonymous comments (no user registration) and manually validates them before publishing them, would it be possible to have a sort of internal white list for trusted email addresses (in the comment "email" field)?

The idea would be that comments using one of those addresses would be published immediately, without requiring validation.

(Obviously the email addresses of the commenters are not visible to the visitors.)

Is there a module for that?

# Answer
> 2 votes
You can use the Comment Trust module in order to **auto-approve** comments from **trusted** visitors.

> Comment Trust auto-approves comments by users with previously-approved comments. It rewards trusted commenters with immediate approvals, while requiring you to approve the comments by new visitors. Works for both anonymous and authenticated users.

# Answer
> 3 votes
Make a rule with event after saving a new comment. Then make a view with the list of emails which should be bypassed. Compare this with the current email of the user, if there is a match publish the comment on the node. The comparing can be done with views + vbo and the rules action: Load a list of entity objects from a VBO View.combined with a loop statement.

---
Tags: 7, comments, users
---


# Question
Title: No orders in user profile with custom state of order-status
Drupal 6 + Ubercart. I had created some new order statuses with own state. But when order gets this status, order dissapears from user "Ordered products" (in user's profile)

How to fix this?

# Answer
The Order History page (user/%user/orders) retrieves orders that are `general` in scope.

If you created a custom Status through **/admin/store/settings/orders/edit/workflow/create**, this scope excludes *Canceled* & *In Checkout* statuses. If you've created a custom state through `hook_uc_order_state()`, you need to the `scope` to `general` for it show up.
> 0 votes

---
Tags: 6, ubercart
---


# Question
Title: WSOD on deploy: failed to open stream: No such file or directory
I am trying to deploy a site to a live server, but running into a "white screen of death". Enabling logs revealed that the zurb foundation starter theme was the source of my issues, so I disabled that and was able to use the site. I then switched it back on and went straight into white screen of death again.

Then I used drush to get a login url and accesed /admin where I could so the following list of errors:

https://gist.github.com/webconsult/a82eebc3d25480f674ed

I checked, and it seems these files and functions are all present. I'm not sure if the ownership settings are correct, though, but I am assuming the apache user is able to read and execute the fieles correctly since everything works if I switch away from the Zurb Foundation theme (i.e. Garland theme). Here is a sample of ownership and permission of the files in /includes:

```
-rw-r--r-- 1 admin admin  13816 Mar 19 18:30 actions.inc
-rw-r--r-- 1 admin admin  48742 Mar 19 18:30 ajax.inc
-rw-r--r-- 1 admin admin   1701 Mar 19 18:30 archiver.inc
-rw-r--r-- 1 admin admin  13664 Mar 19 18:30 authorize.inc
-rw-r--r-- 1 admin admin  17497 Mar 19 18:30 batch.inc
-rw-r--r-- 1 admin admin   2310 Mar 19 18:30 batch.queue.inc
-rw-r--r-- 1 admin admin 119919 Mar 19 18:30 bootstrap.inc

```

How can I fix this issue?

# Answer
> 0 votes
There is a file permissions overview on this page of how all file permissions should be setup. If you will scroll down to the bottom of the documentation page there is a shell script that you can install and run on an entire Drupal installation that will fix all file permission issues. That should fix any problems that OP was having.

---
Tags: files, wsod
---


# Question
Title: fields with Image styles only showing placeholder
I've got some images that's set to be shown in specific image styles. They appear fine on each node but in teasers and views I only get a placeholder.

The console in Chrome's inspector says:

> Failed to load resource: the server responded with a status of 500 (Internal Server Error)

The Files folder has permissions set to 775. Should be good, right?

Any ideas?

# Answer
> 1 votes
Here is an overview of how file permissions should be set on a Drupal installation: https://www.drupal.org/node/244924

If you scroll down there is a shell script that you can install on your server and it will fix all file/folder permission errors.

Your issue is definitely a folder permission error, Drupal has to be able to write to the /files folder. It makes new directories for each style, each image, each size so one folder may exist but the others may not be able to be made.

---
Tags: views, media, files
---


# Question
Title: How do I initially show 3 blank fields on a form when cardinality is unlimited?
I have created a field programmatically that has `'cardinality' => FIELD_CARDINALITY_UNLIMITED`. This is the functionality that I want. I want users to be able to add as many items as they need to. However, when the form first shows, I'd like to have 3 blank fields ready to be filled out before having to click the "Add another item" button. Is this possible?

Lots of answers on the web about how to set the cardinality, but that's not what I'm looking to do. I just want to show 3 blank ones to get started while still keeping my cardinality as unlimited. I hope this question makes sense.

# Answer
> 1 votes
You can alter your form to add your proposed blank fields , to do that you need to implement hook\_form\_alter in your module and inside you would have :

```
if (empty($form_state['field_counter'])) {
  $form_state['field_counter'] = 3;
}
else if($form_state['field_counter'] < 3)
{
  $form_state['field_counter'] = 3;
}
for ($i = 0; $i < $form_state['field_counter']; $i++) {
  $form['YOUR FIELD NAME'][$i] = array(
    '#type' => 'textfield',
    '#title' => t('Your Lable'),
  );
}

```

---
Tags: entities
---


# Question
Title: How to postpone access check to theme hooks?
I am trying to hide only a few fields for non-authenticated users, so I would like to bypass access check and check the permission in theme's template files and hide these fields accordingly. I am using Nodeaccess to control each node's permissions.

How could I bypass the permission check before `theme_preprocess_node` is called? I think after that I could use `nodeaccess_node_access` to check the permission manually.

# update

I found it easy to bypass the permission check by implement the hook\_node\_access and return `NODE_ACCESS_ALLOW` for all, but I cannot use Nodeaccess to check permission later, `module_invoke('nodeaccess', 'node_access', $node, $op, $account)` returned nothing (NODE\_ACCESS\_IGNORE).

# Answer
Take a look at the Field Permissions Module:

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

**EDIT**

Based on comments, either create a module using this or add this to a template.php file and adjust as necessary:

```
function THEME_OR_MODULE_NAME_node_view_alter(&$build)
{
    global $user;
    if($user->uid == 0)
    {
        if($build['#node']->nid == 1) // add node id's you want hidden here
        {
            if(isset($build['field_image']))
            {
                unset($build['field_image']);
            }
        }
    }
}

```

This example will hide the field\_image field on the node id = 1 only for anonymous users. Use the machine names for the fields found on the manage fields tab of the content type.

If you prefer a UI ready option, you can look at the Content Access Module

> This module allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.
> 1 votes

# Answer
Here is what I am doing now:

use `_nodeaccess_get_grants($node);` to get the grants array, then compare this with user's roles. If there is grant, then label the node by adding a new attribute. Then return NODE\_ACCESS\_ALLOW and check the new attribute in theme files.

This solved my question, although not so graceful.

```
function userview_node_access($node, $op, $account){
    if($op == 'view'){
         $node_grants = _nodeaccess_get_grants($node);

        $have = _check_access($node_grants['rid'], $account->roles); // check if any role have access.

        $node->haveAccess = $have;
        return NODE_ACCESS_ALLOW;
    }

}

```
> 0 votes

---
Tags: users
---