# Question
Title: Somehow forum's got associated to wrong taxonomy vocabulary. Need help
I am using Advanced Forum 2.6 and I noticed that some of the views were set to pull the wrong vocabulary instead of the forum vocabulary. I set them all to pull the correct vocabulary but when I go to **/forum** the page title is still for the incorrect vocabulary and any change I make at **admin/structure/forum** also affects the terms in the previously connected vocabulary. It seems that the database is confused and I'm not sure how to reset things.

I am also getting a pair of the following errors for every term:

> Notice: Undefined property: stdClass::$num\_topics in mothership\_preprocess\_forum\_list() (line 49 of /Users/seankennedy/Documents/\_IWS/drupal/sites/all/themes/mothership/mothership/functions/forum.php).
>
> Notice: Undefined property: stdClass::$num\_topics in mothership\_preprocess\_forum\_list() (line 60 of /Users/seankennedy/Documents/\_IWS/drupal/sites/all/themes/mothership/mothership/functions/forum.php).

I am mostly a front end guy so I have little experience with messing around in the database directly but not afraid to have a go if that's what it will take to fix it.

# Answer
### **Option 1**

Go to the Forum Topic manage fields and click edit in the forums field.

Check that the vocabulary is set to Forums

If it's not, delete the forum field and add the term reference field again.

### **Option 2**

Have u posted content already to the forum? or do you care about the forum content? if not, **disabling and uninstalling** both Forum and Advanced Forum would be an option you could try and then enable them again.
> 0 votes

---
Tags: nodes
---


# Question
Title: Commerce Feeds failing to import due to missing bundle property
I have a fresh install of Commerce Kickstart, and using the Commerce Feeds module to import my list of products from a CSV. I mapped my fields (sku, title\_field, commerce\_price:amount, field\_commerce\_saleprice:amount, and product\_id) to the fields in my csv. I am using a CSV parser, File upload, and attaching it to a standalone form. When I process the import of either 1 item, or my full list (474 items), none of them import due to the following error:

```
Missing bundle property on entity of type commerce_product

```

Here is the entity from the log:

```
Entity

(object) array(
  'type' => 'product',
  'product_id' => '588',
  'is_new' => FALSE,
  'sku' => '052-001-014588',
  'uid' => '1',
  'status' => 1,
  'created' => 1447383612,
  'changed' => 1447383612,
  'log' => 'Created by FeedsCommerceProductProcessor',
  'revision_timestamp' => 1447383612,
  'revision_uid' => '1',
  'original' => FALSE,
  'title_original' => '',
)

```

I can't seem to figure out why they won't process and import. Can anyone help? Let me know what information you'd like to see.

# Answer
So, apparently this may be an issue inside of the importer, but what is happening was I was trying to map `product_id` on to `product_id` when there was no such field within the product itself that was mappable.
> 0 votes

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


title: Static form to print on TPL

text:
# Question
Title: Static form to print on TPL
I have created a module i can use to create multiple blocks, now with one of those blocks, there is a requirement for a form (which the user needs to be able to see). However, this does not require any Drupal "Save" interactions.

Its a very simple static form that is manipulated with Ajax functionality. I have just coded this form simply within the TPL file.

```
<form name="formelement" method="post">
    <input name="data" type="hidden" value="" />
    <div class="something_here">something here</div>
    <div class="something_here">something there</div>
    <input required="" type="text" class="" name="blah1">
    <input required="" type="text" class="" name="blah">
    <div>
        <button type="submit" class="btn" href="">submit</button>
    </div>
</form>

```

**Question** \- I need to be able to get the $\_POST in a function - what would be the best method of creating this form with the .module file or the drupal 7 api and then print it within the tpl file

# Answer
> 0 votes
You can create form by develop custom module then you use developed form any where in node or block.

**Create a custom module**

* Create a file sites/all/modules/own/form\_test/f**orm\_test.info**
* Create a file sites/all/modules/own/form\_test/**form\_test.module**

(start it with `<?php` tag, but don't add ending `?>` tag)

```
function form_test_form($form,&$form_submit) {
  $form['firstname'] = array(
    '#title' => t('Firstname'),
    '#type' => 'textfield',
    '#required' => TRUE,
  );
  $form['lastname'] = array(
    '#title' => t('Lastname'),
    '#type' => 'textfield',
  );
  $form['submit'] = array(
    '#value' => 'Submit',
    '#type' => 'submit',
    );
  return $form;
}

```

More details

---
Tags: 7, forms, theming
---


# Question
Title: How can update.php be disabled from checking for Postgres databases?
Whenever I try to run the database update script `update.php` after upgrading modules a WSOD appears and the php error log shows this message:

> PHP Fatal error: Class 'DatabaseTasks\_postgresql' not found in `<site root>/includes/install.inc` on line 1338.

The only reason I can think of is that sometime ago I setup a Feed to import some records from a Postgres database into Drupal and it probably configured Drupal to check for Postgres. I am not sure if that is the real reason as it could be a different thing.

Is there some module I need to reinstall for the failure to go away?

These are the offending lines in `install.inc`.

```
**
 * Ensures the environment for a Drupal database on a predefined connection.
 *
 * This will run tasks that check that Drupal can perform all of the functions
 * on a database, that Drupal needs. Tasks include simple checks like CREATE
 * TABLE to database specific functions like stored procedures and client
 * encoding.
 */
function db_run_tasks($driver) {
  db_installer_object($driver)->runTasks();
  return TRUE;
}

/**
 * Returns a database installer object.
 *
 * @param $driver
 *   The name of the driver.
 */
function db_installer_object($driver) {
  Database::loadDriverFile($driver, array('install.inc'));
  $task_class = 'DatabaseTasks_' . $driver;
  return new $task_class();
}

```

`update.php` triggers a call to this piece of code and causes the error. Any ideas of the code may be bypassed or Drupal reconfigured to fix it?

# Answer
> 1 votes
It turns out there were two Postgres directories in `includes/database`.

`includes/database/pgsql/install.inc` and `includes/database/postgresql/install.inc`. The latter was out of date and redundant and may have been installed as part of the requirements for some Feeds SQL Importer. After deleting it the installation now works fine.

---
Tags: database
---


# Question
Title: The best way to list persons information
I am new to Drupal and have recently started using Drupal 8. I am creating a website to act as a business profile. One of the main content of this website is the profiles of the team members. I'd like one of the items of the main menu to be 'team members' and it should drop down into list of members. The link of the top menu item should show a page with a summary of all members and the sub-menu items each should show a full article about a single member.

What I've tried so far is:

1- Create a user for each member, and I've added some fields as full name, etc. I'v created a view to show all users. The problem I faced with this solution is: The view to list users cannot be seen by anonymous. The other issue is I couldn't filter this view to only show team members, for example it also shows 'admin'

2- The second approach was to create a content type called 'Team members' with fields like full name, image, etc. I am not sure if this is the correct approach. For instance the field 'Title' is an obligatory field that doesn't make sense for a team member.

What is the correct way to add such a feature to my website.

# Answer
> 0 votes
Stick with 1: In your view at the top where it says Access: Permissions. Click on permission and change that to Role; in FILTER, add a filter of Role.

---
Tags: views, 8
---


# Question
Title: How to customize drupal web services error messages
I am working in web services for ecommerce project, in that i want to customize or remove HTML Tags from drupal error messages., in user module.

See my code in below:

```
if ($errors = form_get_errors()) {
    $return = new stdClass();
    $return->body = 'null';
    $return->message = "Failed to register user.";
    $return->error = implode(" ", $errors);
    $return->status = 500;

    return $return;
}

```

My response error message is:

```
{
       "body":"null",
       "message":"Failed to register user.",
       "error":"Username field is required. The e-mail address <em class=\"placeholder\">user1@jc.com</em> is already registered. <a href=\"/zee/homechef2/user/password\">Have you forgotten your password?</a>",
       "status":500
    }

```

error contains some HTML tags, so i want to remove or customize that tags.

Anyone have any idea please share here.

# Answer
I used `strip_tags` function to remove HTML Tags,. partially fixed.
> 0 votes

---
Tags: services
---


# Question
Title: How to create a view that filters profiles based on current user's 'interested in' field value?
I am working on a small matrimonial application. I've installed the Profile 2 module and added a few fields like 'interested\_in', 'gender', 'partner preference', etc to the users of my site.

I need to create a view that will list all profiles with same gender as logged in user's 'interested in' field.

How can this be achieved?

# Answer
Solution that worked for me:

I used MyModule\_views\_query\_alter hook and added a join to the field table and the condition that matches the choice of logged in user and gender of users in db.

```
if ($view->name == 'profile_list') {
        $logged_in = $GLOBALS['user']->uid;
        $pr = profile2_load_by_user($logged_in,'main');

        $join = new views_join();
        $join->table = 'field_data_field_gender';
        $join->field = 'entity_id';
        $join->left_table = 'profile';
        $join->left_field = 'pid';
        $join->type = 'inner';

        $query->add_relationship('field_data_field_gender', $join, 'profile');

        $view->query->add_where(0, db_and()->condition('field_data_field_gender.field_gender_value', $pr->field_looking_for['und']['0']['value'], '='));
    }

```
> 1 votes

---
Tags: views, users
---


# Question
Title: View exposed filter with month and remove year
I have an issue that needs the help of everyone. I created the page in view to filter the node. I created a filter **Date created** in "view exposed filter" for filter by **Date created**.

I configured for the Filter granularity is check month, that filter will display 2 dropbox to me to choose, i.e. month and year dropbox. But I want to display only months option and defaults year is the current year. Do not know if anyone can help me handle the matter.

Thank you very much

# Answer
Using CSS and jQuery you can achieve your requirement.

**Step 1:** Using jQuery, on change() event of month select list assign current year to year select list.

```
$(".date-month").change(function(){
    //write code to set current year to year select list.
});

```

**Step 2:** Now using CSS, hide year select list.

```
.date-year {
    display: none;
}

```

> Note: You can also achieve the same functionality using Drupal custom hooks.
> 1 votes

---
Tags: 7, views
---


title: How to get live data from a service?

text:
# Question
Title: How to get live data from a service?
In the UK our weather office provides a live weather data feed. I would like my Drupal site to retrieve data from this service.

I've read up on the XML-RPC API that is in Drupal 7 core. I've successfully built a Hello World! module that acts as a client, makes a call to a service, and successfully gets a response.

However, Drupal 7 is old and I'm wondering if I should be looking into a more 'modern' approach. I've read up on the Services module.

Can anyone advise me on what are currently the recommended ways to get data from a service into a Drupal 7 site.

I'm not looking for a weather module. This is an API learning exercise.

Thanks.

# Answer
Thanks for the advice. The solution:

For example, to get a three-hourly five-day forecast for Dunkeswell Aerodrome:

```
  $base = 'http://datapoint.metoffice.gov.uk/public/data/';
  $resource = 'val/wxfcs/all/json/3840?res=3hourly';
  $api_key = '&key=abcde12345abcde12345';
  $url = $base . $resource . $api_key;
  $response = drupal_http_request($url);
  $data = json_decode($response->data, TRUE);

```
> 1 votes

# Answer
For the most part I think it's something you'll have to build yourself. You can create a module with a "service" and "controller" inside it to get that data. You'll have to use an HTTP request and hit their endpoint for the data you want to retrieve in your controller. Then pass that response to the service in your module and perform whatever actions you need before returning it to the controller. From there your controller can do whatever it needs to with the data. Can send it over to the Javascript side or to another module/controller/service/etc.

I have not seen an easy way to do this with drupal as everything is VERY specific to the API you want to interact with. drupal\_http\_request() may be of some use for you if you don't know how to make requests.
> 0 votes

---
Tags: 7, services
---


# Question
Title: Best way to get current user purchased products
I need to get purchased products by the current user (Drupal Commerce).

I use this function to reach there :

```
function mymodule_user_purchased_products() {
    global $user;
    $query = db_select('commerce_order', 'corder');
    $query->join('commerce_line_item', 'li', 'corder.order_id = li.order_id');
    $query->join('field_data_commerce_product', 'prod', 'li.line_item_id = prod.entity_id');
    $query->condition('corder.uid', $user->uid, '=')
          ->condition('corder.status', 'completed', '=')
          ->fields('prod', array('commerce_product_product_id'));
    $result = $query->execute();
}

```

But I think I forget certain things, and this solution isn't optimal.

Is it the recommended way?

# Answer
> 0 votes
One one thing that I can think of to change. Make sure you only get a single result.

```
$query = db_select('commerce_order', 'corder');
$query->join('commerce_line_item', 'li', 'corder.order_id = li.order_id');
$query->join('field_data_commerce_product', 'prod', 'li.line_item_id = prod.entity_id');
$query->condition('corder.uid', $user->uid, '=')
      ->condition('corder.status', 'completed', '=')
      ->addExpression('DISTINCT prod.commerce_product_product_id', 'product_id');

```

Using this line:

```
->addExpression('DISTINCT prod.commerce_product_product_id', 'product_id');

```

instead of:

```
->fields('prod', array('commerce_product_product_id'));

```

will insure that you only get one product\_id per row in your result. By using the `DISTINCT` SQL Keyword, it will only allow distinct values to be returned.

---
Tags: 7, commerce, database
---


# Question
Title: Update the price of a line item after shipping method is selected
I looked everywhere and couldn't find the appropriate and clear explanation of how to change the price of a line item. I have a line item called "fee", the fee changes based on the date and zipcode. I have a function that returns the correct fee based on the parameters. Now what hook do I call to update the "fee" line item? This is what I found

```
function ck_custom_commerce_cart_order_refresh($order_wrapper)
{
$fee = _ck_custom_delivery_fee($order);//this function returns an integer

foreach ($order_wrapper->commerce_line_items as $line_item_wrapper)
{
    if($line_item_wrapper->type->value()=="fee")
    {
        //I would like to update the fee
    }
}
}

```

Please what is the right of way of accomplishing this? FYI: I'm using the commerce fees module if that helps.

# Answer
> 0 votes
You want to change the price components of the line item you're wanting to update. You can use rules for this, but since you're writing a hook, you can just call the function that Rules would use:

```
commerce_line_item_unit_price_amount($line_item, $amount, $component_name, $round_mode);

```

For example, if you want to change it to $5.00:

```
commerce_line_item_unit_price_amount($line_item, 500, 'base', COMMERCE_ROUND_HALF_DOWN);

```

---
Tags: commerce
---


# Question
Title: Custom template for displaying inner blog contents
I am trying to create a custom layout for my blog listing and blog content display pages.

The following url will display all the latest blogs based on the conditions that I have set.

http:///general-blog

When I click on the 'Read more' button corresponding to a button, it will display the full blog contents in another page.

Sample format : http:///general-blog/tourist-details

I am able to modify the layout of the page corresponding to blog listing. For this, I have created a custom tpl file : page--general-blog.tpl.php.

What I want is to create a new template file for displaying the contents of individual blogs.

The individual blog content display page is not entering - page--general-blog.tpl.php file. It's always using the template - page.tpl.php.

I tried creating separate tpl files like :

page--general-blog--%.tpl.php

But, the changes in this template is not getting effect in the individual blog content display page.

How should I move forward. Has someone had any similar situations?

# Answer
> 0 votes
Declare your template using 'theme\_suggestion\` in your page preprocess function. like the following:

```
function THEMENAME_preprocess_page(&$vars){
  // Page template suggestion based on node type
  if (!empty($vars['node'])) {
    $node_type = $vars['node']->type;
    $vars['theme_hook_suggestions'][] = 'page__node__' . $node_type;
  }
}

```

if your node type is blog then your template will `page--node--blog.tpl.php` Don't forget to ***clear cache*** after adding this code and your `tpl` file

---
Tags: views, nodes
---


# Question
Title: How to prevent access to a page but allow query
I have a page defined by Views module.
(for example: http://namedomainnn.com/cvstaff)

However, I want user only allow to access using query command)
(for example: http://namedomainnn.com/cvstaff?name=user1)

How can I prevent any users to access without query.

# Answer
Simply check that your **URL parameter exists and it's not empty** before loading your view:

```
/**
 * Implements hook_views_pre_view().
 */
function MY_MODULE_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'MY_VIEW_NAME') {
    // If your URL parameter doesn't exist or it's empty, deny access.
    if (!isset($_GET['name']) || empty($_GET['name'])) {
      drupal_access_denied();
      exit();
    }
  }
}

```

So, accessing:

http://example.com/cvstaff?name=user will work.

http://example.com/cvstaff will show an *Access Denied* page.
> 2 votes

---
Tags: views, redirection
---


title: Drupal .dev database problem

text:
# Question
Title: Drupal .dev database problem
Drupal website unexpectingly takes all data from .dev db, thow settings point the main db.

Is there any way to fix that?

# Answer
Your settings are messed up somehow. I'd suggest looking into the multi-site capability to keep things straight.

You would create directories for live and test under `/sites`. Assuming `example.com` and `test.example.com` are your site:

```
/sites
    /example.com
        settings.php    # connection details for your live database

    /test.example.com
        settings.php    # connection details for your test database

    /example.local
        settings.php    # (optional) details for local development environment

```

Under this scheme, when you browse http://example.com, Drupal will look for the database settings in `/sites/example.com/settings.php`. When you browse http://test.example.com, Drupal will look in `/sites/test.example.com/settings.php` and so on.

An alternative would be to use environment variables set in you Apache or Nginx configuration. You would then use the PHP getenv() function to access the values. This approach would be a little bit harder to set up and troubleshoot.
> 0 votes

---
Tags: database
---


# Question
Title: How to implement date filters with operators like <= or >= in a JSON query string?
We use Drupal 7 and the Service (Version 3) module. First we created a view using a date with a "between operator" as a filter, which works fine. Then we added a service view as .json format inn which we try to pass that date operator in the query string of it, but we cannot get that to work.

The query string we are using looks similar to this example:

`http://example.com/drupal/api(endpoint)/sampleview.json?field_invoice_date_value<='2013-12-31'&field_invoice_date_value>='2013-11-31'`

To produce the output of the view in format, we used the (amazing!) Services Views module. We added the service view path to the services resource. As mentioned above, the date filtering is working fine in the view (as confirmed by our testing of the view, without using JSON). But if we try using JSON then the between operator for the date is for unknown reasons not (yet) working.

Below are 5 screenshots to further explain what we're trying to implement (and what we got to work so far).

# 1. Service View

# 2. Date filter

# 3. View output

# 4. Adding service view as service resource

# 5. JSON query string variations

> http://web.com/drupal/api\[endpoint name\]/chart(view service pathname).json?field\_invoice\_date\_value\>=2013-11-01&field\_invoice\_date\_value\_1\<=2013-12-31

The above string is NOT working, note the filter in it like so:

> "field\_invoice\_date\_value\>=2013-11-01&field\_invoice\_date\_value\_1\<=2013-12-31"

Other filters are working correctly, like this one:

> http://web.com/drupal/api\[endpoint name\]/chart(view service pathname).json?facility\_name\_value='test'

Since we need the JSON output using that 'between date', we also tried this variation, which is NOT working either:

> http://web.com/drupal/api\[endpoint name\]/chart(view service pathname).json?field\_invoice\_date\_value='20131210--20131213'

When testing with the string above, we received the following error message too:

***"Cannot create references to/from string offsets nor overloaded objects in common.inc on line 6579"***

**My question:** Please let me know how to implement the ***date between operator*** in a JSON query string, or any other ideas you have to further debug this issue.

# Answer
OK, below is what appears to be the solution for it ... We need to pass the query string as follows (all string, sorry for the formatting ...):

> http://web.com/drupal/api\[endpoint name\]/chart(view service pathname).json?field\_invoice\_date\_value\[min\]\[year\]=2013&field\_invoice\_date\_value\[min\]\[month\]=12&field\_invoice\_date\_value\[min\]\[day\]=1&field\_invoice\_date\_value\[max\]\[year\]=2014&field\_invoice\_date\_value\[max\]\[month\]=1&field\_invoice\_date\_value\[max\]\[day\]=1

Things to notice in what is shown above:

1. No (more) `<=` or `>=` (can't use that in such JSON string).
2. Use notations like `[min][month]`, `[max][day]`, etc. instead (rather self explaining ... if you know about this syntax of course).

Done, works as designed ...
> 0 votes

# Answer
I was having the same exact problem, I solved it by creating a views using views datasource module. I created json display for my view and used post date in contextual filters. I also enabled Views Contextual Range Filter module.
> 0 votes

---
Tags: views, uri, services, 8
---


title: Unable to add content?

text:
# Question
Title: Unable to add content?
I am working on a project with a fresh install of Drupal 7.41 and the customer wanted to use a Themeforest layout.

Installation of core, theme and modules went without a problem, however, when I try to create content via 'article or basic page' nothing happens except a page refresh. No content shows in the content list and no content is created.

Yet, I am able to create a webform with the webform module.

### Notes

* I have checked my logs and there are no errors. None!
* I cleared my cache several times
* I am running as Admin and the proper permissions have been checked.
* My roles are in the proper order. (Admin being at the bottom)
* I created a new custom content type and that does not work either. Even after enabling permissions.

Any insight would be greatly appreciated as I have never encountered this issue before.

# Answer
> 0 votes
Apparently there is an issue with the CKEditor module. Once I disabled it I am now able to post content as normal. I will have to find another WYSIWYG to replace it.

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


# Question
Title: Is it possible to do calculations like percentage in Views
I am using Views module. The view has three columns.

In the third column, I want a calculated percentage using the first two columns of the view.

# Answer
You can use global php to acheive this **(not recommended)**

The best way to do it is by using this hook\_views\_pre\_render(&$view) in your theme template file or in your custom module.
> 1 votes

# Answer
If it's based on some rules, try using Computed Field and you can define the values via PHP code. Alternatively use Views PHP which allows you to directly use PHP inside views which may be useful for calculating percentage using the first two columns of your view.
> 1 votes

# Answer
You can use **Global:Math Expression** in views to perform mathematical operations.

You would need tokens if you want to use your fields to perform calculations.
It is pretty simple to calculate percentage using this.

For example, to calculate percentage using two fields \[field1\] and \[field2\],
you can do it like

`[field1]*100/[field2]`

I hope its clear.
> 1 votes

---
Tags: views
---


# Question
Title: How to redirect all URLs of all terms in a specific vocabulary to custom URLs
I am a newbie to Drupal and having hard time to understand how to redirect all URLs for all terms in a specific vocabulary to custom URLs.

I have tried to use Entity Path, but it did not work for me. By some reasons this module sets automatic alias field empty in a term edit form. This breaks Pretty Path module that I am also using.

I have also tried to implement custom hook as described here, but cannot understand how to make it work only for a specific vocabulary, the hook applies to all vocabularies on my site.

I would be greatly appreciate if someone can provide a step-by-step instruction to solve this issue.

**edit after I tried to get it to work via Rues**

Here is exported Rules

```
{ "rules_redirect_an_old_path_to_a_new_path" : {
    "LABEL" : "Redirect Categories Terms to Custom Path",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : { "text" : [ "site:current-page:url" ], "match" : "existing_vocabulary_alias/[term:name]" } }
    ],
    "DO" : [ { "redirect" : { "url" : "custom_text\/custom_text\/[term:name]" } } ]
  }
}

```

# Answer
The Rules module is your friend to implement such redirects ...

Here is the rule you'd need for it (in Rules export format, just use copy/paste it to import it in your own setup via the Rules UI):

```
{ "rules_redirect_an_old_path_to_a_new_path" : {
    "LABEL" : "Redirect an old path to a new path",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "the_old_path",
          "operation" : "starts"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Sorry, the old path (= /the_old_path) is no longer in use, you will be redirected automatically to its corresponding path (= /the_new_path)" } },
      { "redirect" : { "url" : "the_new_path" } }
    ]
  }
}

```

A few more tweaks to make it fit your exact scenario:

* change all occurences of `the_old_path` to your old path corresponding to `[term:vocabulary]/[term:name]`.
* change all occurences of `the_new_path` to your new path corresponding to `CUSTOM_WORDS/CUSTOM_WORDS/[term:name]`.

Attention (1): when applying those 2 changes above, you want to do so using the Views UI. So that you are sure that you'll use the exact Rules syntax, e.g. using "tokens" that the Rules module makes available. But also know that sometimes it's a bit tough and/or tricky to get that right.

Attention (2): it could well be that the Rules condition (with that `text_matches`) has to be replaced by something using a "regular expression" (instead of that `starts` in my sample).

Whenever such redirect actually happens, the user will also receive an informational message like so:

> *Sorry, the old path (= `/the_old_path`) is no longer in use, you will be redirected automatically to its corresponding path (= `/the_new_path`)*

If you don't want such message to appear, then just delete the line containing `drupal_message` in the exported rule above.
> 1 votes

---
Tags: 7, taxonomy-terms, uri, redirection
---


# Question
Title: How do I properly add css to my feature?
I have a feature that just contains a few views. How do I properly add a stylesheet to it?

# Answer
1. You add the css file to the module.
2. Use `drupal_add_css` to include the css file in the `.module`, this could be done in `hook_init` and would look something like this:

```
module_name_init() {
  if (arg(0) == 'views_path') {
    drupal_add_css(drupal_get_path('module', 'module_name') . '/path_to.css');
  }
}

```
> 13 votes

# Answer
If you just want to add some CSS style information, add it to your theme. Create a new CSS file, store it in the theme folder and add it to the .info file of the theme.

If you need to tweak the generated HTML as well, install the theme developer module. When activated, you can point to any part of the Drupal site and it tells you which functions are doing the theming and how to name your own ones if you want to override them.

Don't forget to refresh your cashes to make your changes visible.
> 3 votes

# Answer
I used `hook_views_pre_render()` in my recent project. A sample code snippet is here https://gist.github.com/1675931

```
/**
 * Implements hook_views_pre_render().
 */
function example_views_pre_render(&$view) {
  $deals_view = array('deals', 'previous_deals');
  if (in_array($view->name, $deals_view)) {
    drupal_add_js(drupal_get_path('module', 'td_deals') . '/td_deals.js');
    $contextual_module_path = drupal_get_path('module', 'contextual');
    drupal_add_js($contextual_module_path . '/contextual.js');
    drupal_add_css($contextual_module_path . '/contextual.css');
  }
}

```
> 2 votes

# Answer
As mentioned, portability is an issue when adding it to your theme's css folder. I would suggest placing the .css file inside a newly created folder (css) at the root of your exported feature, then reference it inside your feature's .info file like so:

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

Your stylesheet will now be included when the module is enabled. What's nice is when regenerating your feature, this addition will be preserved.
> 1 votes

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


title: Language missing from node field arrays

text:
# Question
Title: Language missing from node field arrays
For some fields, not all, the language index is missing from the field array. For example, here is the `body` field of the packaged `blog` content type (using `print_r`):

```
[body] => Array
    (
        [0] => Array
            (
                [value] => <p>Shirley Temple[...]
                [summary] => <p>Shirley Temple[...]
                [format] => html_raw
                [safe_value] => <p>Shirley Temple[...]
                [safe_summary] => <p>Shirley Temple[...]
            )
    )

```

Expected structure:

```
[body] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [value] => <p>Shirley Temple[...]
                            [summary] => <p>Shirley Temple[...]
                            [format] => html_raw
                            [safe_value] => <p>Shirley Temple[...]
                            [safe_summary] => <p>Shirley Temple[...]
                        )
                )
        )

```

I have only ever seen this happen on two fields (the one above and another field from a different content type). Other fields on the `blog` content type are fine. It looks like it is only happening on my development environment, production seems to be fine. If I set `$reset` to `true` when calling `node_load()` then the structure is fine.

`field_get_items()` returns `false` and wrapping the node using the Entity API's `entity_metadata_wrapper()` and calling `$wrapped_node->body->value()` I gives the following PHP error:

> EntityMetadataWrapperException: Missing data values. in EntityMetadataWrapper-\>value() (line 83 of /vagrant/web/sites/all/modules/entity/includes/entity.wrapper.inc).

Setup:

> Drupal 7.28
> PHP 5.3.10
> MySQL 5.5.34
> Apache 2.2.22
> memcached 1.4.13

# Answer
I haven't run into this issue again. I think a Drupal update resolved the problem.
> 0 votes

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


# Question
Title: Persistent variable (`variable_set()`) name restrictions
Are there any restrictions, conventions, etc. for the names of persistent variables created with `variable_set()`?

Aside from project name prefix, I haven't found anything in the documentation. However, I notice that most modules restrict themselves to the same rules that apply to PHP variables.

# Answer
> 1 votes
Until Drupal 7, the main storage for the variables is the `variable` table in the same database Drupal uses.

The `name` column is a `varchar(128)` so that requires the variable names to have equal or fewer characters than 128.

Prefixing the variable names is purely by convention. Drupal Form API can handle spaces in machine names too, but you will almost never see a form array item key with spaces in it.

There are workarounds, but it's easier if there are no spaces, for example when you use `drush`, export settings, etc.

---
Tags: 7, configuration
---


title: Feeds Node processor mapping

text:
# Question
Title: Feeds Node processor mapping
I want to import XML data from a remote server. The Feeds module has to interact with an API that outputs the data in a XML format where the actual content is in JSON format. Here's an example of the XML file:

```
<serverResponse>
  <status statusCode="0">OK</status>
    <messages>
      <user/>
      <tech/>
      <alert header="_*Alert*_"/>
    </messages>
  <content>
    {"appointmentSet":[{"appts":[]}],"bookingAllowed":false,"maxBookAheadPeriod":25}
  </content>
</serverResponse>

```

What I try to achieve is to let the Feeds module grab the `<content>` data and put it in a node text field. Then I want to use the *drupal\_json\_decode* function to decode the JSON data in readable text.

In my XML Xpath parser settings I've used **//content** for the Context value. But I've no idea what to do with the processor mapping. Can someone please help me? Does the Node processor mapping require a unique identifier for the GUID or is this not mandatory?

# Answer
## Does the Node processor mapping require a unique identifier for the GUID or is this not mandatory?

You do not need to have a unique identifier to import data, but you might get duplicate data if you do not use a unique identifier. From your question I assume you are interacting with the API in the feeds fetcher. Can you get "duplicate" results when using the API? Or, is each import ALWAYS creating new nodes?

## Xpath

Use **//content/text()** to return the json *text* `{"appointmentSet":[{"appts":[]}],"bookingAllowed":false,"maxBookAheadPeriod":25}`
> 0 votes

---
Tags: feeds
---


# Question
Title: Problem in drush configuration with wamp server 64 bit
I am trying to enable drush for wamp server 64 bit.

I have configured all things with youtube videos and it seems it must be ok but when I run drush via cmd console, I see this error message :

**PHP Warning: PHP Startup: Unable to load dynamic library './php\_gd2.dll' - The specified module could not be found.**

My operating system is windows 7 64 bit. so I have installed Wamp server 64 bit version. PHP version is 5.5.12 and apache version is 2.4.9

I don't know what is the reason of this problem. I checked my php.ini extension path is ok. also I can see "php\_gd2.dll" file inside extension folder.

so why I see this error that says specified module could not be found?

# Answer
PHP for Apache and CLI have different configuration files, so check if you're using the right one.

To identify which php.ini is used by drush, run `drush status`:

```
$ drush status
PHP executable         :  /path/to/bin/php
PHP configuration      :  /path/to/php.ini

```

then edit that file and check if you've the right extensions specified.

Alternatively check using `php` command, for example:

```
$ php -i | grep php.ini

```

Note: In case `grep` command is not found, replace with the with `find`.

If you still have a problem, possibly that your DLL library was compiled for the wrong version of PHP. So either use the one included with WAMP, or download the right one specifically for that version of PHP.

Also double check that your command-line `php` points to the right place (WAMP folder):

```
$ where php
$ which php

```

which should give you `C:\WAMP\PHP\bin`-like path, if it's not, update your system `PATH` variable in advaned system settings.

Finally to check if your GD2 library is loaded, check by:

```
php -r "phpinfo();" | grep gd2

```

Note: The `grep` can be replaced with `find` on Windows if you don't have Linux command utilities installed.
> 2 votes

---
Tags: drush
---


# Question
Title: Escape forward slashes in hook_update_n() descriptions for display on update.php
I've created a module update function:

```
/**
 * Create alias for node/add/video-submission.
 */
function my_module_update_7103()
{
  // magic
}

```

But on update.php the message shows up without the forward slashes:

> 7103 - Create alias for nodeaddvideo-submission.

What can I do to force the forward slashes to display?

# Answer
Given that line 1161 of includes/update.inc is this:

```
$description = str_replace(array("\n", '*', '/'), '', $func->getDocComment());

```

(replaces new lines, asterisks and forward slashes in the doxygen comment with blank strings, everything else is considered to be the update description)

I'd say you have two options:

1. Use an HTML entity:

```
/**
 * Create alias for node/add/video-submission.
 */

```
2. Patch the offending line with something like:

```
$description = str_replace(array("\n", '/*', '*/', '*'), '', $func->getDocComment());

```
> 4 votes

---
Tags: 7, updating
---


# Question
Title: What is it called when a Drupal Module installs with several modules?
I looked up submodule, but that seems to be a Git thing. So, when a Drupal module installs with a whole group of things that show up in the dashboard, what is each piece called? For example, there are about 8 items that show up in Modules -\> Chaos Tool Suite. If they show up in one group, does that mean they are all written by the same entity?

# Answer
> 2 votes
> what is each piece called?

I don't have an official reference, but "submodules" or "sub-modules" is by far the most common phrase I've seen used for modules included in a main module to complement/extend its functionality. Prominent members of the Drupal community seem comfortable with referring to them as such.

> If they show up in one group, does that mean they are all written by the same entity?

It can in some cases, but there's nothing to guarantee it. Any module can list itself under any of those groups by setting the `package` key in its .info file. A lot of modules that provide field types list themselves under the generic "Fields" group, for example.

---
Tags: 7
---


# Question
Title: What field is Views using to determine the pager 'offset'?
When I use Views \> pager \> 'items to display' and set the **offset** value ... what field is Views using to determine the pager 'offset'? Is it 'post date'?

How can I change the offset to use a different date field that I've created?

# Answer
It offsets by row.

If offset = 5, it will skip the first 5 rows of your view result.

By default, the View SORT is using Post Date.

Remove Post Date and add the desired field to the SORT area. (when adding, look for your custom date field that you created.)
> 1 votes

---
Tags: views
---


# Question
Title: How to reduce BARCODE FONT in barcode module?
I am using Barcode module to generate barcode i have downloaded that module from drupal.org modules,i am able to reduce the rectangle lines of barcode but under the rectangles lines i have serial number like "**123456**" i cant able to reduce the size of it,I need to reduce the size of serial number.any suggestions.Thanks in advance

# Answer
Add this to your theme css file, in `/sites/all/themes/yourtheme/css`

```
.barcode { font-size: 10px; }

```
> 0 votes

---
Tags: theming
---


# Question
Title: How to fix broken file.module function 'file_ajax_progress' without hacking the core and patching after every update?
When site has enabled page cache and anonymous user tries to upload a file, he cannot see upload status progress. He see only message "*Starting upload...*". Bug was reported in June 2012, has a working patch and I have a question:

How to fix broken **file.module** function **`file_ajax_progress`** without hacking the core and patching after every update? Should I do some function override by custom module?

This is all working code together:

```
/**
 * Menu callback for upload progress.
 *
 * @param $key
 *   The unique key for this upload process.
 */
function file_ajax_progress($key) {
  $progress = array(
    'message' => t('Starting upload...'),
    'percentage' => -1,
  );

  $implementation = file_progress_implementation();
  if ($implementation == 'uploadprogress') {
    $status = uploadprogress_get_info($key);
    if (isset($status['bytes_uploaded']) && !empty($status['bytes_total'])) {
      $progress['message'] = t('Uploading... (@current of @total)', array('@current' => format_size($status['bytes_uploaded']), '@total' => format_size($status['bytes_total'])));
      $progress['percentage'] = round(100 * $status['bytes_uploaded'] / $status['bytes_total']);
    }
  }
  elseif ($implementation == 'apc') {
    $status = apc_fetch('upload_' . $key);
    if (isset($status['current']) && !empty($status['total'])) {
      $progress['message'] = t('Uploading... (@current of @total)', array('@current' => format_size($status['current']), '@total' => format_size($status['total'])));
      $progress['percentage'] = round(100 * $status['current'] / $status['total']);
    }
  }
  // Mark this page as being uncacheable.
  drupal_page_is_cacheable(FALSE);
  drupal_json_output($progress);
}

```

# Answer
The answer is simple: make a module. So I created one. Module has name Upload progress fix.
> 0 votes

# Answer
Patching core is not the same as hacking core. Many of us have patched versions of Drupal in the wild (eg, using Secure Pages).

You need to work out how you want to manage this between upgrades.

On sites where I don't track Drupal's repo, I keep a directory of patches next to the DOCROOT. Before I upgrade, I check on whether the patch is needed or not. I then `drush pm-update drupal` and apply patches.

On sites that I have built with git, I can typically build the site in its own branch, apply patches, and then upgrade core versions by merging the latest tag and doing the database updates.
> 1 votes

---
Tags: 7, ajax, caching, files
---


# Question
Title: How to show/hide fields based on visitor's country?
I have two fields (consider field\_A, field\_B). Anyone should see only one of these 2 fields based on their IP address:

* If users from US access the page, only field\_A should be visible.
* For other countries, field\_B should be visible.

How can I achieve this?

# Answer
You can make use of **Geo Ip** to do this. Install **Geo Ip** by following the instruction mentioned in the link http://www.beginninglinux.com/home/php/ubuntu-php-5-geo-ip

Make use drupal ip\_address() function to get user ip address.

```
function test() {
  $code = geoip_country_code_by_name($ip);
  if ($code == 'US') {
    //hide  field B
  }
  else {
    //hide field A
  }

}

```

**geoip\_country\_code\_by\_name** returns country code. I think this approach gives you solution.
> 1 votes

# Answer
If you want show and hide your field according to country that detected by user IP first you should use a module that detect user country (like ip2country module) and if it have javascript API to detect IP use it else where in `hook_form_alter` detect country and hide field something like

```
function yourmoudle_form_alter(&$form,$form_state,$form_id){
 if($form_id=='your_form_id'){
     $ip = $_SERVER['REMOTE_ADDR'];
      $country_code = ip2country_get_country($ip);
    if($country=='US'){
     hide($form['field_b']);
   }
  }
}

```

**Alternative Solution**
Also you can handle it without module and use Geo IP and as @Vamsi suggest you can

> Install **Geo Ip** by following the instruction mentioned in the link http://www.beginninglinux.com/home/php/ubuntu-php-5-geo-ip Make use drupal ip\_address() function to get user ip address.

geoip\_country\_code\_by\_name **return** Returns the two letter ISO country code on success, or FALSE if the address cannot be found in the database.

```
function yourmoudle_form_alter(&$form,$form_state,$form_id){
 if($form_id=='your_form_id'){
     $ip = $_SERVER['REMOTE_ADDR'];
      $country_code = geoip_country_code_by_name($ip);
    if($country=='US'){
     hide($form['field_b']);
   }
  }
}

```
> 1 votes

---
Tags: 7, entities, location
---


# Question
Title: Get nodes of specified content type with REST
I want to retrieve all nodes of specified content type (as example'news') with `GET` method with REST, How can I achieve it? (first I want try it with firefox RESTClient and if it work implement it in my application)

# Answer
> 3 votes
The only way that core offers is building a view with a REST display. That is, in fact, the only way in core to have collections (a list of resources) for rest.

See https://www.drupal.org/project/graphql for another approach, that allows to execute a sort of query through services.

---
Tags: 8
---


# Question
Title: How do I change taxonomy page callback for a specific vocabulary only?
Following Clive's answer to this question, I would like to change taxonomy page callback and redirect users to another page just for a specific vocabulary.

```
function MYMODULE_taxonomy_page_callback($term) {
  if (/* Check if the vocabulary is the one we need to implement hook to */) {
    drupal_goto('somewhere');
  }
}

```

How can I achieve this?

# Answer
Since the callback is getting the taxonomy term object as argument, you can check the value in `$term->vocabulary_machine_name` to get the machine name of the vocabulary, and see if it is the one you are interested in.

```
function MYMODULE_taxonomy_page_callback($term) {
  if ($term->vocabulary_machine_name == 'MYVOCABULARY') {
     drupal_goto('somewhere');
  }
  else {
    return taxonomy_term_page($term);
  }
}

```
> 1 votes

---
Tags: taxonomy-terms, redirection
---


# Question
Title: How to perform entity validation on code level?
I have an entity that has a field attached to it and the values that user types into the field has to be globally(website) unique(compared to other entities).

I have added validation to the entity form but what if I create this entity programmatically? How can I prevent the entity to be saved into the storage?

I've noticed there is a validate method in ContentEntityBase, though not in ConfigEntityBase. Is this the place for it? If so, I could use some examples.

# Answer
Fields have constraints defined on them and as everything is a field on an entity, that's that. See `Comment::baseFieldDefinitions` does `->setConstraints(array('CommentName' => array()));`. Then there's appropriate plugin in the `Drupal\comment\Plugin\Validation\Constraint` namespace in a class called `CommentNameConstraint`. The logic is in `CommentNameConstraintValidator`.

So the chain is

1. `setConstraints` in `basedFieldDefinitions` setting a list of plugin ids (`CommentName`) and their arguments (empty array in the example
2. A plugin in the `Drupal\modulename\Plugin\Validation\Constraint` namespace with the appropriate plugin id. The classname is not magic, the plugin id is what's important. Using the plugin id plus `Constraint` as classname seems to be best practice.
3. Whatever classname you picked in the previous step, append `Validator` to it, make it extend `Symfony\Component\Validator\ConstraintValidator` and put your validation logic in `validate`.
> 5 votes

# Answer
Constraints for fields can be provided at two places: \- on a per field-type level, i.e. in its annotation or getConstraints() method \- on a per field basis by adding it to the field definitions. Right now, this is only possible for non-configurable fields - e.g. by implementing https://api.drupal.org/api/drupal/core!modules!system!entity.api.php/function/hook\_entity\_base\_field\_info\_alter/8. It's not possible to add custom constraints to configurable fields right now (sounds like this could need improvement).
> 0 votes

# Answer
I think this has come in more recently change record.

I found this article that really helped when I was writing validation contraints: Introducing Drupal 8's Entity Validation API.
> 0 votes

---
Tags: entities, 8
---


title: Custom url theme for drupal

text:
# Question
Title: Custom url theme for drupal
We got site written on Drupal.

We want to make Nginx caching but there is one problem we met.

Nginx caching works perfect, but if user A will go to page `http://domain.com` and nginx cache it. User B use mobile theme `http://domain.com/?theme=mobile` and went to `http://domain.com/` , he will see desktop version instead of mobile version.

I want to make something like `http://domain.com/any/url/path` for desktop version and `http://domain.com/mobile/any/url/path`

Is it possible? Where can I found information about how to do it?

# Answer
> 1 votes
If you are using Drupal6 Have a look at Mobile Tools module.

> The Mobile Tools module provides Drupal developers with some tools to assist in making adjustments to your site based on the visitor's device.

Once you install the module you can define different paths for desktop and mobile, then browser will detect the device and redirect to corresponding path. For Drupal 7 Mobile Switch module is the alternative

# Answer
> 1 votes
It was easily than I expect.

We use ThemeKey module so I added some rules depends on url like "`drupal:path visuallimpaired/%`" and just make my own plugin that use `hook_url_inbound_alter` and `hook_url_outbound_alter` to add and remove prefixes, and it works.

---
Tags: theming
---


# Question
Title: Auto fill billing information in cc avenue payment
I am using Commerce Cc Avenue as a payment gateway for my eCommerce site. During checkout step user enter his billing information. In the next step it verifies his/her order and redirects to Cc avenue payment gateway, there it asks user billing address again. I want to auto fill the user billing address which he/she enters in previous step. Is that possible to do?

# Answer
Finally found the answer with help of this issue queue https://www.drupal.org/node/2310505

In commerce\_ccavenue.module added few lines inside **commerce\_ccavenue\_redirect\_form($form, &$form\_state, $order, $payment\_method)**

```
$billing_address = $wrapper->commerce_customer_billing->commerce_customer_address->value();
  $order_data = array(
    'merchant_id' => $payment_method['settings']['merchant_id'],
    'amount' => $wrapper->commerce_order_total->amount->value() / 100,
    'order_id' => $order->order_id,
    'cancel_url' => url('checkout/' . $order->order_id . '/payment/back/' . $order->data['payment_redirect_key'], array('absolute' => TRUE)),
    'redirect_url' => url('checkout/' . $order->order_id . '/payment/return/' . $order->data['payment_redirect_key'], array('absolute' => TRUE)),
    'working_key' => $payment_method['settings']['working_key'],
    'access_code' => $payment_method['settings']['access_code'],
    'language' => 'EN',
    'currency' => $currency_code,
    'billing_name' => $billing_address['name_line'],
    'billing_address' => $billing_address['thoroughfare']. ' ' . $billing_address['premise'] . ' ' . $billing_address['sub_premise'],
    'billing_zip' => $billing_address['postal_code'],
    'billing_city' => $billing_address['locality'],
    'billing_state' => $billing_address['administrative_area'],
    'billing_country' => 'India',
  );

```

These lines are missing inside **commerce\_ccavenue\_redirect\_form($form, &$form\_state, $order, $payment\_method)**. Works fine after adding those lines.
> 1 votes

---
Tags: commerce
---


title: Loading of assets via Libraries API

text:
# Question
Title: Loading of assets via Libraries API
I'm writing a new module which has a dependency on an external library. In Drupal 7 I would use hook\_libraries\_info giving the name of the library the required assets and Drupal would search the valid locations, libraries directories, to load these assets when required. Drupal 8 introduces \*.libraries.yml and after reading https://www.drupal.org/node/1996238 it seems that module developers must now provide a path, relative or absolute, to the required assets.

In my case I will be expecting site builders to download the external library - where should libraries be located in Drupal 8?

# Answer
> 2 votes
hook\_libraries\_info is not in core, it is from a contrib module:

Libraries API

This module provides the external libraries. It will be ported to drupal 8 and can be used the same way as in drupal 7.

In drupal 8 the libraries, that are defined in \*.libraries.yml are seperate and should not be confused with the external libraries, despite their identical name. They are mainly for js and css packages, that are specific to one module, but can also be used by other modules. They can be a replacement for the external libraries, but do not provide the full functionality.

In the long run composer will probably be the way module developers will go for downloading external libraries. But for now this is an ongoing discussion how this can be implemented.

Your reference to https://www.drupal.org/node/1996238 is a seperate issue about the replacement of `hook_library_info()` in drupal 8 core. This must not be confused with the external libraries defined in `hook_libraries_info()`.

---
Tags: 8, theming
---


title: How to add custom fields to a page

text:
# Question
Title: How to add custom fields to a page
Am newbie here. I just have a problem with fields adding them to a page. I want fields specificly textboxes and a button to be in a page. This page will be used by my authenticated users. These textboxes will be filled in by the said users then have the system save the info to the DB after click of the button.

How do I do this? I created a content type of this but i can't seem to add them in the page. No article i can find here either that answers my problem. Please help. Am new here and am not a coder. Thanks y'all.

# Answer
Drupal allows content to go onto your site, such as a Page or Book through a `content type`. If you want to show a Page or Book and embed a field or form on that page that is backed by a database -- typically you have to use another module for that which allows you to embed Forms onto existing Page (Node) content.

To do this usually you can use 1 of the following modules:

Webform

> Webform is the module for making forms and surveys in Drupal. After a submission, users may be sent an e-mail "receipt" as well as sending a notification to administrators. Results can be exported into Excel or other spreadsheet applications. Webform also provides some basic statistical review and has an extensive API for expanding its features.
>
> Some good examples could be contests, personalized contact forms, or petitions. Each of these could have a customized form for end-users to fill out. If you need to build a lot of customized, one-off forms, Webform is a more suitable solution than creating content types and using CCK or Field module.

or

EntityForms

> The Entityform module enables you to create front-end forms (fieldable entities), which contain fields that you define! These forms use the standard Drupal fields. This means that out of the box, you can use any standard Drupal node field!

These modules allow you to embed any form you define through their admin interface into existing page content.

A key difference is in these forms is that Webforms stores its own data in a custom backend difficult to make into drupal (page) content on your website. While EntityForm since it uses Drupal Fields -- it's submitted content may easily be turned into Drupal site content (but need not be).
> 0 votes

---
Tags: nodes, entities
---


# Question
Title: Conf_path is deprecated but what is its replacement?
Im upgrading a D7 module to D8 and it turns out conf\_path() is deprecated but I cant find the replacement.

I found a github page that said use this

```
 DrupalKernel::findSitePath(Request::createFromGlobals())

```

but I still WSOD when that is called.

# Answer
One of two change records for conf\_path() is Bootstrap refactored to use the kernel. This states that

> Note: In D8, instead of using conf\_path(), \Drupal\Core\DrupalKernel::getSitePath() instead. If the kernel is unavailable (such as above, where the code shows the booting of the D8 kernel) or the site path needs to be recalculated then Drupal\Core\DrupalKernel::findSitePath() can be used

So if you have access to the DrupalKernel object, then calling getSitePath() on that object will work. This is probably not the case.

However, there is a service for this called site.path that can be injected into a class that you need it. I think the change record could be updated to reference this factory class.

Using the global Drupal object:

```
$conf_path = \Drupal::service('site.path');

```
> 2 votes

---
Tags: configuration, 8
---


# Question
Title: How to interruput ajax request but keep for next possible uses?
I want to add simple confirmation box for ajax delete action created via: ctools\_ajax\_text\_button

JS:

```
(function ($) {

    Drupal.behaviors.mymod = {
        attach: function (context, settings) {

            Drupal.ajax.prototype.beforeSend = function (xmlhttprequest, options) {

                if ($(this.element).hasClass(Drupal.settings.mymod.confirm_element_class)) {
                    return confirm(Drupal.t('Please confirm your action'));
                }

                return true;
            }
        }
    };

})(jQuery);

```

It works, but only first time. When I click delete link and choose Cancel option in modal dialog, next clicking doesn't trigger AJAX action at all on this link, so basically makes ajax action inactive.

# Answer
> 0 votes
I've solved it by:

```
        Drupal.ajax.prototype.beforeSend = function (xmlhttprequest, options) {

            if ($(this.element).hasClass(Drupal.settings.mymod.confirm_element_class)) {
                if (!confirm(Drupal.t('Please confirm your action'))) {
                    this.ajaxing = false;
                    return false;
                }
            }

            return true;
        }

```

---
Tags: 7, javascript, ajax, chaos-tool-suite
---


# Question
Title: Change module's weight - by module or manualy
I am looking for solution how to change particular module's weight in D7. I know that it is possible to do in config tables in database, but I don't know how. Another solution that I found in Drupal.org is to use hooks - but I need more detail explanation or some guidance where I could get some tutorials about that.

The thing that I need to do is to make some priorities of some particular modules higher for it to load faster than other modules as otherwise they will not work. One of the examples is video streaming using Lightbox2 popup watching that on Safari browser on OS X - it's not loading until you change the priority of Lightbox module.

# Answer
If you have access to phpmyadmin, you can look through the system table and when you find your module, you can click the little pencil icon to edit the row in the table. You would edit the weight column.
> 1 votes

# Answer
Since it was explicitly asked, there is also a module, Modules weight, that performs this task as well.

> We always need to modify modules execution order, and some could write a code that execute a query to modify the weight of a module in system table, some might go straight to his favorite SQL client and modfiy the record directly, This module provide admin interface for users/people has the access to modules page to reorder the module weights as they want
> 3 votes

# Answer
What I have seen in different modules is that they do it directly in the database with a db\_query call. Something like:

```
db_query("UPDATE {system} SET weight = 12 WHERE name = 'admin_views'");

```
> 1 votes

# Answer
You can use `drush` for this job as well. Use the commands below, and adapt the values of `modulename` and `moduleweight` to your liking:

1. Look up the current weight of your module:

```
modulename="rdf"
drush php-eval "drush_print_r(db_select('system', 's')
  ->fields('s', array('weight'))
  ->condition('name', '$modulename', '=')
  ->execute()
  ->fetchField()
);"

```
2. Set the new weight of your module:

```
modulename="rdf"
moduleweight="1"
drush php-eval "db_update('system')
  ->fields(array('weight' => $moduleweight))
  ->condition('name', '$modulename', '=')
  ->execute();"

```
> 1 votes

---
Tags: database, caching, javascript
---


# Question
Title: Remove one item in cart removes all - Ubercart/Webform
I'm using:

* Drupal: 7-4.1
* Webform: 7.x-4.12
* Ubercart/webform intg: 7.x-3.0
* Ubercart: 7.x-3.8

I am using this wonderful Webform module to add products to cart, all works ok, however, when added more that one item to the cart using multiple webform submissions then When I try to remove one item from the cart it says:

> If you remove this product from your cart, all products associated with your form submission will also be removed. Are you sure you want to delete this product?

So my question is; is there a way to remove one single item from the cart without removing all?

# Answer
> 0 votes
Yes, but not with the module itself. You can build a custom module to modify UC Webform Integration to suit your needs. This would involve 3 parts:

1. Implement a `HOOK_form_uc_cart_view_form_alter()` function such that cart **Delete** link for each submission and they have 2 arguments: **cart/delete-form/$NID/$SID**. You may need to adjust your custom module weight so that it executes after, `uc_webform_form_uc_cart_view_form_alter()`.
2. Implement a `HOOK_menu()` function that defines the new `cart/delete-form/%/%` path. `uc_webform_menu()` should give you an idea how it's done.
3. Implement your own form/submission handler for the `cart/delete-form/%/%`. The function `uc_webform_submission_delete_products_form()` & `uc_webform_submission_delete_products_form_submit()` should give you an idea how it's done. The key thing here is you'll be adding something like `$wf_sid = arg(3);` and replacing `isset($cart_item->data['webform_sid'])` with `$cart_item->data['webform_sid'] == $wf_sid` so that only the selected submission is deleted instead of all submissions on that form.

---
Tags: webforms, ubercart
---


# Question
Title: How to disable a feature whose checkbox is grayed out?
I would like to disable some features, but they are grayed out. What does that mean? I assume some kind of dependency? (I am using Drupal Commons and would like to disable groups.)

# Answer
This is true for Module page and Features page:

The page should list out the dependencies and modules/features that are dependent on that module/feature so you would have to turn off those modules/features before you can turn off the one that is disabled, if you use drush it will tell you that you are turning off all dependent modules when you perform `drush dis modulename`

One thing to note: on some setups that dependency list may be collapsed. Certain developer/helper modules will collapse those options on the modules page so you may have to click to expand but the reason why a module could not be disabled is b/c it is a dependency for another module so unless you are using drush like mentioned above you will need to turn off all the modules listed as needing that module to operate first.
> 1 votes

---
Tags: features, 7
---


# Question
Title: EVA field: file entities filtered by taxonomy term of attaching node
I have a node type 'XY' with a reference to a taxonomy vocabular 'country'. Also I have a reference to this vocabular in file entities.

I have a view with an EVA display. This EVA field is attached to the node type 'XY'. This view displays file entities. These entities should be filtered by the taxonomy term of the attaching node.

When a node has the taxonomy term 'America', all file entities with taxonomy term 'America' as well should be displayed in the view (and in the node via the EVA field).

Without any filter it works with displaying all file entities.

I set a contextual filter File:

Country (field\_file\_image\_country), Provide default value-\>Field value from current node/term-\>field\_gallery\_country (the taxonomy reference in node type)-\>TID

Specify validation criteria-\>Taxonomy Term-\>Vocabular 'Country'-\>Filter value type 'Term ID'

But it doesn't work. Nothing's displaying.

# Answer
I have a similar case of two Content types that share the same Taxonomy vocabulary referenced, and the need to show all nodes of Content type B that are tagged with a certain term to show on the node type A that is also tagged with the same term.

I created EVA views display that lists nodes of type B, under Bundles chose Content type A, **under Arguments chose token** (Use tokens from the entity the view is attached to) and chose

```
[node:field-myvocabulary:tid]

```

for token replacement (I selected it from the list below the textfield).

Then under Contextual filters I added

```
Content: Has taxonomy term ID

```

and set it up like this:

**When the filter value is NOT available**

* Provide default value Taxonomy term ID from URL
* Load default filter from term page
* Load default filter from node page, that's good for related taxonomy blocks
* Limit terms by vocabulary (myvocabulary)
* Filter to items that share any term

**When the filter value IS available or a default is provided**

* Specify validation criteria
* Taxonomy term:
(myvocabulary)
* Filter value type: Term ID
* Transform dashes in URL to spaces in term name filter values
* Action to take if filter value does not validate: Display "Access denied" (this hasn't been triggered for me)
> 1 votes

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


title: Check activity of authors during period

text:
# Question
Title: Check activity of authors during period
I would like to have some sort of management system in the control panel where the management people can view the activity of the authors during a certain period.

So: A person with a certain role (management) must have a management tab in his administration menu where he can see the names of all authors + their amount of articles they have created during a certain period, where the manager can choose the start and enddate of this period.

Example:

Manager chooses:

1 september 2015 - 30 september 2015

and then he gets an overview of all authors and their amount of articles made that month.

Is there a module by any chance that already has this?

# Answer
> 0 votes
Well, to those who might wonder the same as me: apparently there is no module yet that does this, which surprises me, as it seemed such a basic request to me.

So you have to do it yourself.

For those who need it, I hereby give you my own solution, but ofcourse other possibilities are available.

I made this with a combination of views & total control module.

Total Control gives you a nice dashboard which you can fill with views. For the view itself, you just have to use the aggregate function and a relationship.

1. Relationship: 'Content: Author'
2. Use AJAX: Yes (this is to make sure filters can be exposed in blocks)
3. Use Aggregation: Yes
4. Make a table with following fields and filters:
    * Field: '(author) User: Name'
    * Field: 'Content: Nid' (Aggregation: Count (Distinct))
    * Filter: 'Content: Post date' =\> Exposed

extra fields are possible, like I have also added the date of the last article that person made in this specific period, which could also be handy for activity monitoring. To do this, use the field 'Content: Post date' and add the aggregation setting MAX to it.

Hope this helps others in case they are looking for something similar that is easy to maintain, without having to invent things that already exist.

---
Tags: views
---


# Question
Title: Which tables should I exclude from a backup?
As a fan of svelte sql backups I've successfully used, for several years this bash script for backing up my Drupal site's databases. By excluding "noisy" tables, I've seen remarkable reduction in the size of the resulting sql file. I am so confident of it, I nearly used it for my Drupal 8 project. However, I presume the schema has undergone some rather significant changes.

Here are the following tables my current script excludes, expressed as a grep pattern:

```
echo "Starting to dump the table data."
TABLES2=`echo "$TABLES" | grep -Ev "^(accesslog|cache.*|flood|search_.*|semaphore|sessions|feeds_log|watchdog)$"`
mysqldump --complete-insert --disable-keys --single-transaction --no-create-info -u ${USER} --password=${PASS} -h ${HOST} ${DB} ${TABLES2} >> ${DB}.${DATE}.sql

```

I'm curious how Drupal 8 changes which tables are safe for exclusion. Note that I'd rather err on the "safe" side. So, for example, sessions (as I understand them in D7) have limited value for backup, but that's for my general application. Your mileage may vary. Also, sorry for the unresponsive table, but there is apparently a row length limit on code posts.

```
| table name:                  | backup? | | table name:                  | backup? |
| batch                        | Yes     | | node__comment                | Yes     |
| block_content                | Yes     | | node__field_image            | Yes     |
| block_content__body          | Yes     | | node__field_tags             | Yes     |
| block_content_field_data     | Yes     | | node_access                  | Yes     |
| block_content_field_revision | Yes     | | node_field_data              | Yes     |
| block_content_revision       | Yes     | | node_field_revision          | Yes     |
| block_content_revision__body | Yes     | | node_revision                | Yes     |
| cache_bootstrap              | No      | | node_revision__body          | Yes     |
| cache_config                 | No      | | node_revision__comment       | Yes     |
| cache_container              | No      | | node_revision__field_image   | Yes     |
| cache_data                   | No      | | node_revision__field_tags    | Yes     |
| cache_default                | No      | | queue                        | Yes     |
| cache_discovery              | No      | | router                       | Yes     |
| cache_dynamic_page_cache     | No      | | search_dataset               | Yes     |
| cache_entity                 | No      | | search_index                 | Yes     |
| cache_menu                   | No      | | search_total                 | Yes     |
| cache_render                 | No      | | semaphore                    | Yes     |
| cache_toolbar                | No      | | sequences                    | Yes     |
| cachetags                    | No      | | sessions                     | Yes     |
| comment                      | Yes     | | shortcut                     | Yes     |
| comment__comment_body        | Yes     | | shortcut_field_data          | Yes     |
| comment_entity_statistics    | Yes     | | shortcut_set_users           | Yes     |
| comment_field_data           | Yes     | | taxonomy_index               | Yes     |
| config                       | Yes     | | taxonomy_term_data           | Yes     |
| file_managed                 | Yes     | | taxonomy_term_field_data     | Yes     |
| file_usage                   | Yes     | | taxonomy_term_hierarchy      | Yes     |
| flood                        | Yes     | | url_alias                    | Yes     |
| history                      | Yes     | | user__roles                  | Yes     |
| key_value                    | Yes     | | user__user_picture           | Yes     |
| key_value_expire             | Yes     | | users                        | Yes     |
| menu_link_content            | Yes     | | users_data                   | Yes     |
| menu_link_content_data       | Yes     | | users_field_data             | Yes     |
| menu_tree                    | Yes     | | watchdog                     | No      |
| node                         | Yes     |
| node__body                   | Yes     |

```

# Answer
I would exclude batch, anything starting with cache\_, flood, queue, sessions, sequences, semaphore, watchdog, although one may argue about the batch, flood, queue, sequences and semaphore tables.

Also don't forget to export their schema.
> 3 votes

---
Tags: 8, backups
---


# Question
Title: How to keep/access copy of original Feed file when using HTTP Fetcher?
I've created Feeds importer to parse remote XML feed using HTTP Fetcher fetcher and I've created content type for that importer and *Attached* to it in *Settings*.

So my feed and import works fine after I've created importer node based on remote Feed URL.

However I would like to keep original remote XML feed file (fetched from the provided URL) similar as this happens for *File upload fetcher* to have a record/copy of it.

Is it possible? How?

# Answer
I have a simple solution for you but in this time I have not enough time to test it by myself.

First find your importer `form_id`, then in your custom module add custom submit handler then get URL of uploaded file then save it in where you want with `system_retrieve_file()`, e.g.:

```
function yourmodule_form_alter(&form, &$form_state, $form_id){
  if ($form_id == "importer_form_id") {
    $form['actions']['submit']['#submit'][] = 'yourcustom_form_submit_handler';
  }
}

function yourcustom_form_submit_handler($form, $form_state){
  // dpm($form_state['values']);
  // find file url and put it in $url
  // then try to fetch it with system_retrieve_file
  system_retrieve_file($url);
}

```
> 2 votes

---
Tags: 7, feeds
---


# Question
Title: Select users that do have certain roles and do not have others
I need some help with my SQL in that I want to get all users with a certain role that do have another role.

```
SELECT distinct users.uid, users.name, users.mail
FROM users AS users, users_roles AS ur
WHERE ur.uid = users.uid
AND ur.rid <> 4
AND ur.rid = 13

```

My SQL is really bad so any help would be appreciated.

# Answer
> 1 votes
According to Drupal db\_select API Use this to fetch user id and names that user have `roleId` 13 and not have `roleId` 14

```
$query = db_select('user', 'u');
$query->join('role', 'ur', 'u.uid = ur.uid');
$query->fields('u',array('uid','name'))
 ->condition('ur.rid', 13)
 ->condition('ur.rid', 14,'<>');
 $result = $query->execute()->fetchAll();
dpm($result);

```

# Answer
> 0 votes
I actually found out how to do the SQL. I used an 'anti-join'!! (a new one on me)

eg.

```
SELECT users.name, users.mail from
users, users_roles as ur1
where
ur1.uid = users.uid
AND
ur1.rid =  13
AND
NOT EXISTS (SELECT 1
FROM users_roles ur2
WHERE ur1.uid = ur2.uid
AND sur2.rid = 4)

```

Same result as using the api just using SQL.

---
Tags: 7, users
---


title: Use of pattern in hook_theme()

text:
# Question
Title: Use of pattern in hook_theme()
I'm trying to implement pattern but It doesn't work. Here is the implementation of hook\_theme() with my pattern:

Call `theme('publication__' . 'news', array('bean' => $bean));`

in file atom\_publications.module

```
function atom_publications_theme() {
  return array(
    'publication' => array(
      'variables' => array('bean' => NULL),
      'pattern' => 'publication__',
      'file' => 'atom_publications.theme.inc',
      'preprocess functions' => array('atom_publication_custom_preprocess'),
      'template' => 'publication',
    ),
  );
}

```

In file atom\_publications.theme.inc write this code:

```
function atom_publication_custom_preprocess(&$variables) {
}

```

Files in module dir:

* publication.tpl.php
* publication--news.tpl.php

But render only publication.tpl.php template. Why?

# Answer
Looking at theme(), I notice that the "pattern" property is never used. What the function does is using the following code.

```
  // If there's no implementation, check for more generic fallbacks. If there's
  // still no implementation, log an error and return an empty string.
  if (!isset($hooks[$hook])) {
    // Iteratively strip everything after the last '__' delimiter, until an
    // implementation is found.
    while ($pos = strrpos($hook, '__')) {
      $hook = substr($hook, 0, $pos);
      if (isset($hooks[$hook])) {
        break;
      }
    }

```

In your case, `theme()` first looks for `publication__news` key in theme functions array, and then it looks for the `publication` key. As in your case there isn't any match for `publication__news`, it uses `publication`, and the template file associated with that theme function.

This is documented in theme().

> If the name contains a double-underscore (`__`) and there isn't an implementation for the full name, the part before the `__` is checked. This allows a fallback to a more generic implementation. For example, if `theme('links__node', ...)` is called, but there is no implementation of that theme hook, then the 'links' implementation is used. This process is iterative, so if `theme('links__contextual__node', ...)` is called, `theme()` checks for the following implementations, and uses the first one that exists:
>
> * `links__contextual__node`
> * `links__contextual`
> * `links`
>
> This allows themes to create specific theme implementations for named objects and contexts of otherwise generic theme hooks.
> 1 votes

# Answer
I've ran into the same situation and couldn't figure what went wrong. If I look at the Views module, there are patterns defined, and when I place a file called `views_view_field__<fieldname>.tpl.php` in my theme folder it works.

So I tried to move the theme override file from the module folder to the theme folder. It worked there.

The problem is that the \*.tpl.php files should not be in the module folder. Only the theme folder is scanned for the pattern. (Making it impossible to define several sub-templates in a module).

Also the pattern should contain underscores, where the template uses dashes:

```
function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'entity_name' => array(
      'render element' => 'elements',
      'path' => $path . '/theme',
      'file' => 'mymodule.theme.inc',
      'template' => 'entity-name',
      'pattern' => 'entity_name__',
    ),
  ),
}

```

In order to define other options at module level, you should include all of them in hook theme:

```
function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'entity_name' => array(
      'render element' => 'elements',
      'path' => $path . '/theme',
      'file' => 'mymodule.theme.inc',
      'template' => 'entity-name',
      'pattern' => 'entity_name__',
    ),
    'entity_name__variation' => array(
      'render element' => 'elements',
      'path' => $path . '/theme',
      'file' => 'mymodule.theme.inc',
      'template' => 'entity-name--variation',
    ),
  ),
}

```

Defining the pattern again is not be necessary, and now it works from both the module folder (for your own alterations) and the theme folder (for the end-user's alterations).
> 0 votes

# Answer
You have to place your templalte file (publication--news.tpl.php) in your theme directory.

Best,
> 0 votes

---
Tags: theming
---


# Question
Title: Rotate Specified # of Views Results on a Time Based Schedule
I have 1000 results in a View Block. It contains a title and a teaser body. I want to be able to show 10 different results every week. How can this be done using Views? Or is there additional modules I would need?

# Answer
> 1 votes
Not many answers so I'll add my two cents.. A week long cache for the view sounds like it could do the trick.

---
Tags: 7, views, datetime
---


# Question
Title: How do I print breadcrumbs on page.html.twig?
How do I print breadcrumbs on page.html.twig?

I tried `{{ breadcrumb }}` but it's not working.

# Answer
> 8 votes
The breadcrumbs are now a block. You have to go to the block layout and put them into a region. If you want `{{ page.breadcrumb }}` to work, you have to put them into the region breadcrumb.

This is the same for site branding and title, they all have moved into blocks.

# Answer
> 1 votes
As it is done in the page.html.twig template used by Drupal 8, you simply use `{{ page.breadcrumb }}`.

In Drupal 8, the breadcrumb is now a region of the page, together the following ones.

* page.header: Items for the header region
* page.primary\_menu: Items for the primary menu region
* page.secondary\_menu: Items for the secondary menu region
* page.highlighted: Items for the highlighted content region
* page.help: Dynamic help text, mostly for admin pages
* page.content: The main content of the current page
* page.sidebar\_first: Items for the first sidebar
* page.sidebar\_second: Items for the second sidebar
* page.footer: Items for the footer region

---
Tags: 8, theming
---


# Question
Title: How do you add type-property schemas from Schema.org into 8 sites?
Some SEOers have reported good experience with enriching their websites with the formal schema vocabulary Schema.org.

Is there any way to implement such schemas on Drupal 8 webpages?

## Update - July 9 2016:

Is it true to say to most of the functionality of this module got into the Drupal 8 core via the module Aggregator 8.x.x ? I read now in the modules' page (for Drupal 7 as linked in the answer) and that's what I understood; But if it did, then when why creating a new module is on the quine? It is written there the module has not yet been ported and that's why I'm confused.

# Answer
Yes, there's a Drupal 7 module of the same name, schema.org.

> This project is a drop-in solution to enable the collections of schemas available at schema.org on your Drupal 7 site. The major search engines including Bing, Google and Yahoo! have agreed to recognized these in order to improve the display of search results.

Along with the core module, there's a UI that makes it pretty easy to setup; you specify the schema.org type on the content type settings page & then you specify the schema.org property names on the field settings page. It also has support for address field & fivestar fields.

In Drupal 8, the project has deferred to the RDFUI project, to provide the UI component, now that other parts of the module have been ported to core.

> The default RDF mappings of Drupal core have been updated to include schema.org in Drupal 8. Also, a lot of the backend code of this module was ported into Drupal 8 core. The User Interface allowing to set the mappings lives in the RDF UI, which is based on Sachini's Google Summer of Code project.
> 4 votes

---
Tags: 8
---


# Question
Title: Is it possible to use a list of values from a views display as exposed filter of another view?
I have a view with a page display where I have some fields showing. One of the fields is field `foo`. I want the user to be able to filter the view by the `foo` value, choosing one or multiple values. I want the items of `foo` to be available in a list. Can I accomplish this using the data of another display where I have all the unique values of `foo`?

Thanks!

# Answer
To do this,

Install the entity reference module. Create an entity reference view (like creating a block or content pane). The results in this view will be your exposed filter. Create an entity reference field in your content type. In that field's settings, select the above view. Use this field as an exposed filter.

Without more detail, I can't really describe how to set it up accurately but this is generally the accepted method.
> 0 votes

---
Tags: views
---


# Question
Title: Drush status runs the correct PHP version, drush sql-dump don't
I set the drush alias in my .bash\_profile as stated in the doc:

```
alias drush='DRUSH_PHP=/usr/local/php54/bin/php /home/dx_/drush/drush'

```

when I run the "drush status" the correct php version shows up

```
PHP configuration     :  /usr/lib/php5.5/php.ini

```

But when I want to run a drush sql-dump

```
The external command could not be executed due to an application error.                                                [error]
                                 [error]ly (returned: X-Powered-By: PHP/4.4.9

```

I tried to add an alias in aliases.drushrc.php but with no success.

Anyone sees what could be the problem?

# Answer
> 0 votes
Thanks greg for taking time to answer me.

Sorry I was just stupidly running my drush command at the root of my server and not in my website directory and the error message was stated "X-Powered-By: PHP/4.4.9" which made me confuse

```
(uiserver):uxxxxxxx:~ > drush sql-dump
The external command could not be executed due to an application     [error]
error.
The command could not be executed successfully (returned:            [error]
X-Powered-By: PHP/4.4.9
Content-type: text/html

<br />
<b>Parse error</b>:  syntax error, unexpected '{' in
<b>/homepages/xx/dxxxxxxxxxxx/htdocs/.composer/vendor/drush/drush/includes/environment.inc</b>
on line <b>545</b><br />
, code: 255)

```

How ever the only .bash\_profile setting that works for me is as follow:

```
alias drush='/usr/bin/php5.5-cli ~/.composer/vendor/drush/drush/drush.php'
export COLUMNS

```

As you said yourself in one of your post aliasing drush to call php directly is **outdated**. But I couldn't successffully set the DRUSH\_PHP variable.

this

```
alias drush="~/.composer/vendor/drush/drush/drush.php"
export DRUSH_PHP='/usr/bin/php5.5-cli'
export PATH="$DRUSH_PHP:$PATH"
export COLUMNS

```

or this

```
alias drush='DRUSH_PHP=/usr/local/php54/bin/php ~/.composer/vendor/drush/drush/drush.php'
export COLUMNS

```

both give me:

```
(uiserver):uxxxxxxxx:~ > drush status
X-Powered-By: PHP/4.4.9
Content-type: text/html

<br />
<b>Parse error</b>:  syntax error, unexpected '{' in <b>/homepages/xx/dxxxxxxxxx/htdocs/.composer/vendor/drush/drush/includes/environment.inc</b> on line <b>545</b><br />

```

Am I doing something wrong?

---
Tags: drush
---


# Question
Title: automatically fill the field info based on user selected
I have content type "A" and I have field\_users, and field\_mail, where in the fields\_users is entity reference field referring node of users, now when we select the user from the select list automatically the field\_email should update based on the user selected since the user already created in D7.Is there any way to achieve this?

# Answer
> 1 votes
Please make a try by using Entity reference autofill and Entityreference prepopulate Modules.

1. Add an entity reference field.
2. The entity reference autofill will automatically fill reference value into field.
3. Entityreference prepopulate will prepopulate the values. (you have to add existing fields for that.)

For more details please refer project page.

Another approach using ajax. Try the following code in a custom module.

```
function your_module_form_alter(&$form, &$form_state, $form_id){
  if($form_id =='your_node_form_id') {
     $form['your-email-field']['#prefix'] = '<div id="field-email-replace">';
     $form['your-email-field']['#suffix'] = '</div>';
}
$form['your-user-field']['und'][0]['#ajax'] = array('callback' => 'your_module_callback', 'wrapper' => 'field-email-replace','method' => 'replace',);
}

function your_module_callback($form, $form_state){
  $uid = $form_state['values']['your-user-field']['und'][0]['value'];
  $user = user_load($uid);
  $form['your-email-field']['und'][0]['value'] = $user->email;

  $commands = array();
  $commands[] = ajax_command_replace("#field-email-replace",  render($form['your-email-field'])); // use render if you want to render field.

 return array('#type' => 'ajax', '#commands' => $commands);
}

```

Hope this will help you.

# Answer
> 0 votes
If you want it to happen live, and all fields are on the form already, safest way would be to use `hook_form_FORM_ID_alter()` to add following to a form:

```
$form['#attached']['js'] = array(
    drupal_get_path('module', 'module_name') . '/js/copy_field_value.js',

```

Then in copy\_field\_value.js create behavior:

```
(function($) {
  Drupal.behaviors.moduleNameCopyFieldValue = {
    attach: function (context, settings) {

      // Repeat this for all fields as needed
      $('#source', context).on('blur', function(){
        // above you can use change instead of blur if element is not changed by another js
        if(!$('#destination').val() || 0 === $('#destination').val().length) {
          $('#destination').val($(this).val());
          // wrap line above in "if no value" like I did, or other condition you like
        }
      });
      // end of "repeat this"

    }
  };
})(jQuery);

```

Reference click here

If you are not good in programming

Use one of these modules:

Computed Field

> Computed Field is a very powerful field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views. (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of fields. So start cooking up your PHP based values!

Entity reference autofill

> The Entity reference autofill module gives Entity reference fields an option to populate other form fields with data from selected referenced entities.

---
Tags: users
---


# Question
Title: Twig_Sandbox_SecurityError: Calling "setOption" method on RC4
I'm porting light\_skeleton to Drupal 8, and it was working fine on RC2 but I ran into this issue after updating to Drupal 8 RC4.

```
Twig_Sandbox_SecurityError: Calling "setOption" method on a "Drupal\Core\Url" object is not allowed in "themes/light_skeleton/template/html.html.twig" at line 55. in Drupal\Core\Template\TwigSandboxPolicy->checkMethodAllowed() (line 101 of core/lib/Drupal/Core/Template/TwigSandboxPolicy.php).

```

After debugging I find out that it was due to this line:

```
{{ link(item.title, item.url.setOptions({'set_active_class' : TRUE, 'attributes' : {'class' : 'navbar-link'}})) }}

```

Which I stole from - Custom classes for menu links and it was working until RC4.

My question is what I'm doing wrong in here ? All I'm doing in there is setting up a variable into the links and in addition setting up the links if the link is active.

There seem to be a similar issue with the bear skin theme. You can look at this issue Twig\_Sandbox\_SecurityError

**Update**

Here is the results after debuggin on item.url `{{ kint(item.url) }}` RC4 (this is the one that does not work)

RC2 - this how it use to be and it was working.

# Answer
Core recently added a default sandbox so that it's not possible to e.g. call the delete method on node objects.

See https://www.drupal.org/node/2513266, you can bring it up there and try to allow it, try to extend it yourself or call that option in preprocess. Not sure what the best option is.
> 2 votes

# Answer
I ran into the same problem today. for me i had the same use of setOptions to add class to the menu link. I manage to solve it after reading Functions - In Twig Templates

So instead of using setOptions() with attributes i could just use `{{ link(item.title, item.url, { 'class':['nav__link']}) }}` to solve it.
> 1 votes

---
Tags: 8, theming
---


# Question
Title: How to get Signatures for Forums using SQL query?
In a D7 site, I'd like to get all of the user signatures using raw mysql query . I've found a `signature_forum_post` table but could not figure out how to make a query that returns both user.id and signature text, so appreciate your help.

# Answer
Please try the following.

`if ($account->id() && isset($form_state['values']['user_signature'])) {
 if (!$account->get('user_signature')->isEmpty()) {
 db_merge('user_signature')
 ->key(array('uid' => $account->id()))
 ->fields(array(
 'signature__value' => $account->get('user_signature')->value,
 'signature__format' => $account->get('user_signature')->format,
 ))
 ->execute();
 }
 else {
 db_delete('user_signature')
 ->condition('uid', $account->id())
 ->execute();
 }
 }`
> 0 votes

---
Tags: 7, database
---


title: Views - context filter by nid

text:
# Question
Title: Views - context filter by nid
I have created a view, which basically queries files of type image. That view creates a block, which associated with a certain content type. So the block is displayed whenever one of the nodes of that type is displayed, exactly what I would like to have.

Each of the files displayed has an entity reference field, which contains multiple references to that content type. So that is a one to many relationship, where one image can have multiple nodes of that type associated.

Is it possible within the views ui, to set a contextual filter that it sorts out each file, whose entity reference field (to that content type) contains the current node id?

In pseudo SQL the statement should look like:

`SELECT filename, path, node_refs FROM files WHERE node_refs contains <current node id>;`

Thanks in Ahead!

# Answer
1. Add a relationship as `Entity Reference: Referencing entity`
2. Name it with the name of your content type for instance (easier to read in the view settings)
3. Check the `Require this relationship` option
4. Add a contextual filter with `Content: Nid`

*Here comes the trick!*

5. Choose `Provide default value` in the *WHEN THE FILTER VALUE IS NOT IN THE URL* fieldset
6. Type should be `Content ID from URL`

This will make Drupal fetch the context from the current URL where your block is displayed and loop through the files referenced by the current node.

TA-DAAA :-)
> 1 votes

---
Tags: views
---


# Question
Title: Is it correct to use unset($form['#token']);
In my Drupal 7 site, form submit throws the following error:

> The form has become outdated. Copy any unsaved work in the form below and then reload this page.

Is it correct to use `unset($form['#token'])` to resolve that error?

# Answer
> 2 votes
A big **NO** would be the answer but I think you guessed that already.

Form tokens are an important piece of security, insuring your form has not been forged by some script/bot and helps preventing malicious attacks. You can find some more information on drupal.org about it but consider it as a *must-have* or *should-not-remove* feature of you prefer.

If you have an issue with a form submit, you have probably hacked the form too much and should identify which part of your code has generated this error (some module might be in fault as well). Post an issue about this specific part but unsetting `$form['#token']` is not a viable solution.

---
Tags: forms
---


# Question
Title: How can I programmatically create products via REST?
I have a module of rest service api, that is used to receive users upload products. Here is my code...

```
function commerce_services_product_create($data, $flatten_fields) {
    $status =1;
    $commerce_price = array();

    $sku = $data['sku'];
    $title = $data['title'];
    $type = $data['type'];
    $commerce_price = $data['commerce_price'];
    $price = $commerce_price['amount'];

    $cp = commerce_product_new('product');
    $cp->uid = 1;
    $cp->sku = $sku;
    $cp->title = $title;
    $cp->language = LANGUAGE_NONE;

    $cp->commerce_price = array(
        LANGUAGE_NONE => array(
            0 => array(
                'amount' => $price ,
                'currency_code' => 'MMK',
     )));

    // for store
    $cp -> cmp_store = array(LANGUAGE_NONE => $data["cmp_store"]);
    // for category
    $cp->field_category[LANGUAGE_NONE][0]['value'] = 137;

    try{
        commerce_product_save($cp);
        $result = "success!";
    }catch(Exception $ex){
        $result = "not success!, error -> ". $ex;
    }
}

```

When I pass the following json string to the function, this function create a product but not include cmp\_store, mean cmp\_store is null.

```
{
  "sku": "saa_prduct120",
  "title": "saa_prduct",
  "type": "product",
  "commerce_price": {
    "amount": "150000",
    "currency_code": "USD"
  },
 "cmp_store": 2
}

```

And when I check store drop down button with themer info module, it shows #name as like this, "field\_product\[und\]\[form\]\[cmp\_store\]\[und\]".

Above my code I use this code for adding store, mean when users upload their product, they have to choose store. User choose store is passed by json.

```
 // for adding store
 $cp -> cmp_store = array(LANGUAGE_NONE => $data["cmp_store"]);

```

And I also try like this,

```
$new_product ->field_data_cmp_store[LANGUAGE_NONE]['cmp_store']['und'] = $data["cmp_store"];
$new_product -> field_product[cmp_store][und] = $data["cmp_store"];
$new_product -> cmp_store = $data["cmp_store"];
$form_state['values']['cmp_store']['und'] =   $data["cmp_store"];

```

not ok yet!

# Answer
> -1 votes
This might need to work around as below

\['field\_store'\]\['und'\]\['#options'\] = Store\_array

---
Tags: commerce, 8, services
---


title: How to replace nodes in quicktab?

text:
# Question
Title: How to replace nodes in quicktab?
How can I replace nodes in quicktabs on click of a link?

# Answer
i guess your using the quicktabs block. if so you can configure here **admin/structure/blocks**
> 0 votes

---
Tags: hooks, blocks
---