# Question
Title: how to upload an image of product in drupal commerce
I would like to upload an image of product in drupal commerce programmatically while creating a product, Here is my code for create product, but drupal return error said

```
Call to a member function set() on a non-object in <b>C:\xampp\htdocs\mySite\sites\all\modules\api\mymodule.inc

```

any suggestion is greatly appreciated.

Thanks

mymodule.inc

```
$wrapper = entity_metadata_wrapper('commerce_product', commerce_product_new('product'));
$properties = entity_get_property_info('commerce_product');

$wrapper->title = $title;
$wrapper->sku = $sku;
$wrapper->commerce_price->amount = $price;    // Price in minors units 500 = 5$
$wrapper->commerce_price->currency_code = 'MMK';
$wrapper->cmp_store = 2;
//$wrapper->field_category = 137;
$wrapper->field_product_color = 106;

$file_path = file_save_data(file_get_contents('C:\\Users\\ASUSS\\Desktop\\Nexus_5_(1).jpg'), 'public://products/Nexus_5_(2).jpg');
$wrapper->field_product_image->file->set($file_path);

try{
    $wrapper->save();
    $result = "success!" ;
}catch(Exception $ex){
    $result = "not success! -> ". $ex;
}

```

# Answer
Finally, I found the way, field\_product\_image can only accept array value. 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'];

    $wrapper = entity_metadata_wrapper('commerce_product',  commerce_product_new('product'));
    $properties = entity_get_property_info('commerce_product');

    $wrapper->title = $title;
    $wrapper->sku = $sku;
    $wrapper->commerce_price->amount = $price;    // Price in minors units 500 = 5$
    $wrapper->commerce_price->currency_code = 'MMK';
    $wrapper->cmp_store = 2;
    $wrapper->field_product_color = 106;

    $file = file_save_data(file_get_contents('C:\\Users\\ASUSS\\Desktop\\Nexus_5_(1).jpg'), 'public://products/Nexus_5_(2).jpg');
    $image_val = array(
        array(
            'fid' => $file->fid,
            'title' => $file->filename,
            'filename' => $file->filename,
            'filepath' => $file->filepath,
            'filesize' => $file->filesize
        ),
    );

    $wrapper->field_product_image = $image_val;

    try{
        $wrapper->save();
        $result = "success!" ;
    }catch(Exception $ex){
        $result = "not success! -> ". $ex;
    }

    $reply= (array('status' => $status,'result' => $result) );
    return $reply;
}

```

Thanks,
> 0 votes

---
Tags: commerce, media
---


# Question
Title: Autofill billing information on checkout page
I have placed billing information in the checkout pane. I want to autofill the billing information. There is a similar question in stackexchange Autofill billing Information on checkout page in Drupal Commerce. But this is not working for me. This is the code they mentioned

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

  if( $form_id == 'commerce_checkout_form_checkout' && $user->uid ){
    $user = user_load( $user->uid );
    $loaded_billing = commerce_customer_profile_load($user->field_commerce['und'][0]['profile_id']);

    // For each field in customer profile I fill the form field with the $user value
    $form['customer_profile_billing']['commerce_customer_address']['und'][0]['#address']  = $loaded_billing->commerce_customer_address['und'][0];
    $form['customer_profile_billing']['field_telephone_number']['und'][0]['value']['#default_value']  = $loaded_billing->field_telephone_number['und'][0]['value'];
  }
}

```

But I don't have `commerce_customer_profile_load($user->field_commerce['und'][0]['profile_id']);` . Is there any other solution.

# Answer
Use **Commerce Addressbook** module which provides solution for your problem. It is already mentioned in the same question as a comment.

More details about this module (from its project page):

> Commerce Addressbook is a module that allows authenticated customers to reuse previously entered addresses during checkout. They can manage all entered addresses in their user panel (user/%user/addressbook).
>
> Note that for data consistency reasons editing a previously entered address won't change it on previously made orders.
> 1 votes

---
Tags: ajax, commerce
---


# Question
Title: How to convert string count into number?
How to convert string count into number? I have string count column in views i.e. by using the view aggregating I am counting the nodes of content, along with this I have **field\_number** column i.e. from content type.

Now I want to subtracts these two column, while using math-expression its taking the string count column as string its not considering the count number.

Is there any solution to subtract these two fields?

# Answer
Drupal doesn't provide any conversion of value in "Math Expression" field. So we need to fix it in another way, for example following these steps:

* Add two new columns "string count" and "field\_number" same as previously added, excluding
    + When add fields tick "Exclude from display" checkbox
    + Select "Plain Text" to "Formatter" dropdown
* After it, edit "Math-Expression" field, in "Expression" textarea write your mathematical expression with that newly added fields, e.g. `[string_count_1] - [field_number_1]`
> 1 votes

# Answer
Use Views PHP

> This module allows the admin account (user 1) to add fields, filters and sorts to views which use PHP code. It also supports additional accounts when the core PHP Filter module is enabled

Then add PHP field in `Global category` and do that with php

in `OUTPUT` of field write something like(it is example and you should write it according your field)

```
//first dpm($data) and dpm($row) to see what data exists there then
echo intval($data->field_a['raw'][0]['value']) + $data->field_b['raw'][0]['value'];

```
> 0 votes

---
Tags: views
---


title: Default login page little change

text:
# Question
Title: Default login page little change
I want the following; In the default login page, I want to delete this line: Nieuw wachtwoord aanvragen (Also DELETE "request new passord) on this site: http://www.deklotvaarders.nl/user

Also I don't want that users can request new password. Where to do that?? Which file?

Thanks so much, Greetz, Pieter-Jan

# Answer
> 1 votes
The best way to accomplish this is using hook\_form\_alter() with custom module. For example,

```
function your_module_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_register') {
    drupal_set_title(t('Create new account'));
  }
  elseif ($form_id == 'user_pass') {
    drupal_set_title(t('Request new password'));
  }
  elseif ($form_id == 'user_login') {
  drupal_set_title(t('Log in'));
  }
}

```

# Answer
> 0 votes
I found THE clue: There is a module: noreqnewpass-7.x-1.2. Works fine!!

---
Tags: users
---


title: Display message to authenticated users

text:
# Question
Title: Display message to authenticated users
I have a Drupal site and my problem is that it doesn't display error messages when authenticated users are filling in, but they display with the administrator users.

An example of the messages I am referring to is "image size too exceed \[…\]."

How can I make the error messages appear for every users?

# Answer
> 0 votes
Use Disable Message Module. and set permission for user roles you want.

> Gives a site owner options to disable specific messages shown to end users. The core drupal message system as offered by drupal\_set\_message is an excellent way for modules to send out messages to the end users. However not all drupal site owners are keen to show all the messages sent out by drupal core and all modules to their users. This module gives site administrators a reasonably powerful way to filter out messages shown to the end users.

---
Tags: forms
---


# Question
Title: How to theme "group by" header in a view
I'm using views to create a list of nodes grouped by a field. The problem is that, in the html output, I've something like this:

```
<h3>Group title</h3>
<div class="view-row">content..</div>
<div class="view-row">content..</div>

<h3>Group title</h3>
<div class="view-row">content..</div>
<div class="view-row">content..</div>

```

I've put the group title and its contents in a common div, but which template do I have to work on?

# Answer
> 1 votes
Theming views can be done in a number of files. For best assistance I suggest in views you look at the "Theme Information" option. It can be found at {drupal site}/admin/structure/views/nojs/display/{view name}/page/analyze-theme (It's under the right hand side "Advanced" column).

On that screen you will find a list of all the files that you Drupal will look for to theme for the view concerned, ranging from the very specific (views-view-fields--{view-name}--{display-name}.tpl.php for row styling) to a slightly more generic views-view.tpl.php (Covers every view) You can drill further down depending on what your view selects (Fields, Rendered Entity, Display Suite content etc) but the Theme information link shown above should provide you with a list of every file that you can provide to Drupal for theming.

Remember to flush your cache when you add a new theming file so Drupal knows about it.

# Answer
> 0 votes
On the Theme Information views page you can find the views-view-unformatted--{view-name}.tpl theme sugestion that handles that specific code. It is just a matter of coping the file from the views module folder to the templates folder of your theme and override it.

```
<?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($title)): ?>
  <h3><?php print $title; ?></h3>
<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>
  </div>
<?php endforeach; ?>

```

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


title: SQL Subqueries in Views

text:
# Question
Title: SQL Subqueries in Views
I have a View, with its corresponding SQL query. I want a field to be a subquery ( `SELECT * FROM TABLE table WHERE ...` ) with its corresponding result fields. I don't know if this is allowed, it seems more like a field which is another View in itself, to be called from my View. Is that possible at all?

# Answer
You requirement can fulfill Views Field View module

> This module allows you to embed a view as a field in a view. A new field handler is made available, so this can also be used in area (header/footer/empty) handlers as well as rows.
>
> This view handler can accept arguments from fields of the parent view using tokens and pass them into the child view for each row. Raw or rendered token values can be used, as well as static values.
> 1 votes

---
Tags: 7, views
---


title: html formatted email using form api

text:
# Question
Title: html formatted email using form api
I have created my contact us module using form api, email is successfully generated and send to my specified email address, but I need body of the email to b html formatted, for this I have created another file `mymodule.install` in my module folder and add the below code:

```
function mymoduleenable() {
 $current = variable_get('mail_system', array('default-system' =>    'DefaultMailSystem'));
 $addition = array('mymodule' => 'mymoduleMailSystem');
 variable_set('mail_system', array_merge($current, $addition));
}

function mymoduledisable() {
 $mail_system = variable_get('mail_system', array('default-system' => 'DefaultMailSystem'));
 unset($mail_system['mymodule']);
 variable_set('mail_system', $mail_system);
}

```

and in my `mymodule.module`

```
 class mymoduleMailSystem extends DefaultMailSystem {
 public function format(array $message) {
 $message['body'] = implode("\n\n", $message['body']);
 $message['body'] = drupal_wrap_mail($message['body']);
 return $message;
 }
}

```

but due to above all piece of code I am unable to receive email, kindly suggest any solution.

# Answer
> 0 votes
Same thing i do in my module may be it is set to you requirement

```
    global $content;
    $content .= '<button class="btn btn-primary" data-toggle="modal" data-target=".bd-example-modal-lg">Apply</button>';
    $content .= '<div class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">';
    $content .= '<div class="modal-dialog modal-lg">';
    $content .= '<div class="modal-content">';
    $content .= drupal_render($form);
    $content .= '</div>';
    $content .= '</div>';
    $content .= '</div>';
    return $content;

```

---
Tags: forms
---


# Question
Title: Recommended approach for setting up contact management?
I need to develop a contact form that the administrator can reply to and categorize each message (Responded, Transferred, Archived, etc.) received from users.

Which would be the best approach for this?

# Answer
> 2 votes
Here are multiple options for implementing such contact form, as further details below.

# Default contact form (D6 or D7)

This is the `contact` module that comes with Drupal 7 core (though disabled by default). Typically used by Drupal newbies, and commonly known to have quite a few limitations / issues that can be resolved using some of the contributed modules (mentioned below).

# Webform (D6 or D7)

The Webform module is the traditional (and mature) solution used in quite a few (close to 500K) sites. Some details from its project page:

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

**Note**: It also has 2 related charting modules, i.e. Webform Chart and Webform Charts, both integrate very well with the Webform module to provide charts about data created via the Webform module.

# Entityform (D7 or D8)

The Entityform module is a fairly new solution used in "only" about 18K sites, and only has an RC1 release so far. Some details from its project page:

> ... 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! As of the time this article was written, there were over three hundred "field" modules. And since Entityforms are "Drupal entities", you will automatically be able to use future "field" modules!
>
> The forms can be used to create custom surveys, petition, and personalized contact forms, and other customized form. (For those of you who have used Webforms, this module brings Webform's functionality into the "standard" Drupal field / entity world.)

**Note**: in D8 renamed to eForm (to avoid name confusion).

# Contact forms in D8 core with the Contact Storage module (D8)

This is the `contact` module that comes with Drupal 8 core (enabled by default now).

Many more details about this can be found in the article about "Goodbye Webform? Contact Forms Are In the Drupal 8 Core", which explains why you will also need the Contact Storage module:

> The one key feature that's missing with the Contact module is the ability to store messages sent through the forms. This is odd, because Drupal 8 deals with contact messages as entities. You can add comments to them, for example. You just can't see them!
>
> To solve this problem, you'll need a contributed module called Contact Storage. The author says they hope to have this in core for Drupal 8.1 and that would make a lot of sense, filling this functionality gap.

Some details from the Contact Storage project page:

> ... will provide storage for Contact messages which are fully-fledged entities in Drupal 8.
>
> This plus core contact module aim to provide functionality equivalent to the base-features of Webform or Entity Form.
>
> The goal is to firm up this functionality in contrib with view to move into core in 8.1.x or later.

# Answer
> 1 votes
The default contact form module has some limitations interms of flexibility. You can use webform or entityform (in case you are using Drupal 7) which has so many features.

---
Tags: forms, emails
---


# Question
Title: Adding a css in preprocess view not woking
I'm trying to add a css to a view, through the preprocess view as below

```
function mytheme_preprocess_views_view(&$vars) {
 $view = &$vars['view'];
if ($view->name == 'gallery_view') {
drupal_add_js(drupal_get_path('theme', 'mytheme') . '/assets/js/responsive-image-gallery/gallery.js');
drupal_add_css(drupal_get_path('theme', 'mytheme') .'/assets/css/responsive-image-gallery/style.css');
 }
}

```

The Following code above is inserting the js file but not the css. Is there a reason why? Or other way to insert css file in certain view?

I have tried the following and its being inserted:

```
drupal_add_js(drupal_get_path('theme', 'zenon') .'/assets/css/responsive-image-gallery/style.css');

```

So is there something missing in the drupal\_add\_css function or it doesnt have read access on the server, is that possible?

# Answer
> 0 votes
Trudog way below is a workaround for the css file to be inserted, and it works.

But after further debugging my case, I found the main cause of the problem was in the file permission. Apache did not have read access to the responsive-image-gallery folder. Resolved it with the following command on the server:

```
chown -R apache:apache /var/www/Demo/sites/all/themes/mytheme/assets/css/responsive-image-gallerry

```

Then restarted apache just incase it did not take affect, and it worked like a charm

# Answer
> 1 votes
the path is wrong!

drupal\_get\_path('theme', 'mytheme') already provides the path to your theme folder. no need for '../../../...'

you should probably use

drupal\_get\_path('theme', 'zenon') . '/css/image-gallery/css/style.css'.

# Answer
> 1 votes
I agree with Trudog, you should not use a relative path when using drupal\_get\_path.

Also, I'm surprised the javascript gets inserted because both paths are incorrect. The function drupal\_get\_path does not contain a trailing slash so what you get now is something like this (assuming your themes folder is in sites/all):

```
drupal_add_css('sites/all/themes/mytheme../../../themes/mytheme/assets/css/image-gallery/css/style.css');

```

The folder **mytheme..** probably does not exist. Adding a trailing slash would result in:

```
sites/all/themes/mytheme/../../../themes/mytheme/assets/css/image-gallery/css/style.css

```

Which is the same as:

```
sites/themes/mytheme/assets/css/image-gallery/css/style.css

```

That location probably does not exist either.

I think the correct call would be:

```
drupal_add_css(drupal_get_path('theme', 'mytheme') .'/assets/css/image-gallery/css/style.css');

```

The same goes for your javascript call.

# Answer
> 1 votes
then try this:

```
function mytheme_preprocess_views_view(&$vars) {
 ... everything you already have there +
 $css_path = drupal_get_path('theme', 'mytheme') .'/assets/css/responsive-image-gallery/style.css';
 var_dump($css_path);
 }
}

```

make sure that the string printed on the screen is a valid path to your css file by copying the printed string and putting it in browser's address bar + enter. is should display the css content. if 404, something's wrong with the path... maybe spelling or something.

---
Tags: views, theming, javascript
---


title: Exclude domain in robots.txt

text:
# Question
Title: Exclude domain in robots.txt
Is it possible to exclude a domain name in robots.txt?

I have a single Drupal site with multiple domains pointing on it. For example our dev and staging server are being crawled by Google when our .htaccess password protection is disabled.

I don't intent to block any access in our development server but to tell search engine bots to stop indexing all the contents when the domain is/are dev or staging.

Basically I am seeing some of the links pointing in dev servers when I search some of my content in Google.

Is there any way or any module that could handle this?

EDIT:

Here's how I ended. Inside `theme_preprocess_html()`.

```
// Avoid search engines to index dev and stage domains.
  $restricted_domains = array('dev.mydomain.com', 'stage.mydomain.com', 'editorial.mydomain.com');
  if (in_array($_SERVER['HTTP_HOST'], $restricted_domains)) {
    $meta_robot = array(
      '#tag' => 'meta',
      '#attributes' => array(
        'name' => 'robots',
        'content' => 'noindex, nofollow'
      ),
    );
    drupal_add_html_head($meta_robot);
  }

```

# Answer
Robots.txt will not help your site being crawled (technically) by anything. They're just guidelines which Bots *should* follow. You should limit dev and test server access by Firewall rules, or as you've mentioned by httpauth.
> 9 votes

# Answer
Add these lines to your .htaccess:

```
# Dev environments other robots.txt to prevent indexing.
RewriteCond %{HTTP_HOST} (.*)mystagingurl\.com
RewriteCond %{REQUEST_URI} (robots\.txt)
RewriteRule .* robots-dev.txt [L]

```

Create an extra file in your root, named robots-dev.txt, and add following code

```
User-agent: *
Disallow: /

```

This will serve another robots.txt on the matching domains, excluding them from all search engines which follow the robots.txt-guidelines.

Some examples of matching urls for the given example are:

* mystagingurl.com
* www.mystagingurl.com
* abc.mystagingurl.com
* abc.def.mystagingurl.com
> 2 votes

# Answer
As stated by tenken, `robots.txt` or robots metatags does not block robots. They are just guidelines. However, all *well-behaved* robots (and *googlebot* falls in this category) will obey these guidelines.

Assuming (based on what you say in your question) that you have a production domain named `mydomain.com`, and three subdomains you do not want appearing in Google's SERP named `dev.mydomain.com`, `stage.mydomain.com` and `editorial.mydomain.com`, having the followming `robots.txt` in the *root directory* (`DocumentRoot`) of the three subdomains you want to exclude will work:

```
User-agent: *
Disallow: /

```

This is assuming that the production domain (`mydomain.com`) do *not* have the same `DocumentRoot` as the development sub-domains (`dev.mydomain.com`, `stage.mydomain.com` and `editorial.mydomain.com`). If your web-sever is configured so that all four domains are just aliases and point to the *same* root directory, then the `roobots.txt` file will be shared among all four, and will of course also prevent the main site from being crawled. In that case, you cannot use `robots.txt`, but must resort to adding metatags to the header depending upon domain, as you describe in the most recent version of your question.

Comment: It is correct, as staten by tenken, that using `robots.txt` or metatags is not the *best* way to protect development and staging servers from public access - but using this should *work* as a quick fix until you've put up a proper firewall.
> 1 votes

# Answer
I solved it with the metatags module (https://www.drupal.org/project/metatag). In dev.mydomain.com I configured the global settings of the metatags module (/admin/config/search/metatags/config/global) accordingly.

In the global settings click on "Advanced" and check "Prevent search engines from indexing this page." under "Robots".

This will add

```
<meta content="noindex" name="robots">

```

to the section of your development site.
> 0 votes

---
Tags: domain-access, 7, subsites
---


title: How to do core update with drush

text:
# Question
Title: How to do core update with drush
With which drush command can I update my Drupal 7.36 to 7.41?

I have tried so far the followings:

* drush up drupal
* drush pm-updatecode

But nothings has changed in either the code nor when I look at the currently pending updates.

# Answer
> 0 votes
Adi provided a good answer. So update the code with:

```
drush up drupal

```

But after that always preform database updates (if required):

```
drush updb

```

# Answer
> 0 votes
`drush upc` should update all modules and core

---
Tags: drush, updating
---


# Question
Title: How feasible is a Drupal 8 with a different language depending on its subdomain
So, let's say I have this massive content-heavy site with all sorts of paths like mysite.org/category/date/slug or mysite.org/someterm/subterm/date/slug. Let's say all this content is in English, and now I've gotten my hands on a Spanish version of all of my content. How feasible is it to integrate the Spanish content into the site, using the same installation, but only having the site show up in Spanish when people go to es.mysite.org, es.mysite.org/category, or es.mysite.org/someterm/subterm/date/slug.

How scalable is Drupal 8 in this regard? If we want to have several different language sites, potentially with different templates, would it be best to use different installations of Drupal 8 or does it facilitate this kind of set up I explained above so that one installation is perfectly logical?

# Answer
Multilingual has seen a big improvement for Drupal 8. All you need can be done with Drupal 7, so it it's possible with Drupal 8 too.

You have to set Language Negotiation to subdomain. This way Drupal sets the content language depending on the domain accessed. For example, `example.com/en/node/1` is English content and `example.com/es/node/1` is Spanish content (you can also configure so no subdomains maps to a certain language).

Regarding performance Drupal 8 has a very good caching system that is much better than Drupal 7 (specially when we talk about cache invalidation).

What I don't recommend in any case is to have two separate Drupal installations one for each language. No benefits from this approach and lot of issues instead. Just think on content sync, user sync, config sync, etc. Drupal can manage two and much more languages without having performance issues.
> 1 votes

---
Tags: i18n-l10n, path-aliases, multi-sites
---


title: How do I add a 'Title' and 'Label

text:
# Question
Title: How do I add a 'Title' and 'Label
How do I add 'Title' to a search Engine? For Section 508 compliance i need to add 'label or 'title' to the following section :

```
<input placeholder="Search" type="text" id="edit-search-api-views-fulltext" name="search_api_views_fulltext" value="" size="26" maxlength="128" class="form-text" />

```

I have created funtion.js with the following query:

$(document).ready(function(){

```
            $('#edit-search-api-views-fulltext').attr('title', 'Search');}

```

This doesn't seem to be working. View source says:

```
<div id="edit-search-api-views-fulltext-wrapper" class="views-exposed-widget views-widget-filter-search_api_views_fulltext">
                        <div class="views-widget">
          <div class="form-item form-type-textfield form-item-search-api-views-fulltext">
 <input placeholder="Search" type="text" id="edit-search-api-views-fulltext" name="search_api_views_fulltext" value="" size="26" maxlength="128" class="form-text" />
</div>

```

How do I add a Title?

# Answer
> 0 votes
I think you can better do this with hook\_form\_alter. Like this:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    $view = $form_state['view'];
    if ($view->name == 'my_view_machine_name' && $view->current_display == 'display_name') {
      // alter your exposed form here
    }
  }
}

```

If you do a var\_dump (or dpm if you use devel) on $form, you can easily find out which values to alter.

---
Tags: views, search
---


# Question
Title: Structuring a user rating/rebuttal system
I am looking to create a really basic rating system (user reference and fivestar content type). But I would like to be able to have users rebut ratings if need be. I am just trying to figure out, structurally, how to do it. Would I have to create another content type called rebuttal and reference the rating? What about adding a field to the rating content type with the ability for the referenced user to fill in a text field? Limit comment access to just the rating author and the referenced user?

This may be the wrong forum to ask this, since its an open ended and subjective question. But I guess my question would be "How would you allow users to make selective edits to a node or limit comments to only the node author or referenced user?"

# Answer
> 0 votes
Use the Flag module to create a **Rebut** flag, but do NOT make it a 'global' flag though. The flag is to be created (configured) by an admin, but each user (authorized to use the flag) will then be able to "rebut rating" using such flag. If it would make sense, you may want to have multiple flags configured for this (eg: Rebut-low , Rebut-medium, Rebut-high, whatever that would "mean" in your case).

Then create a view (with the views module) for each flag, whereas you create a "views relationship" with such flag(s).

If you're not familiar with the Flag module, checkout the set of 8 video tutorials about the flag module.

You might also want to look at some of the Flag related modules, such as (partial list):

Refer to Flag's Community documentation for (way) more details.

**Note**: Via Rules it should be possibly to add logic to verify the "usage" of such flag.

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


title: Print Parent Menu Items of Current Page

text:
# Question
Title: Print Parent Menu Items of Current Page
I would like to create a sidebar in `node.tpl.php` that prints the parent menu items of the current page with a depth that follows the current page's depth by one level.

So if I have a menu structure like:

```
A
B
C
--C1
--C2
--C3
D

```

... and I am on page `B`, I would see in the sidebar:

```
A
B
C
D

```

... or if I am on page `C2` I would see in the sidebar:

```
C1
C2
C3

```

# Answer
> 0 votes
Answering my own question:

In a custom module (or in your `template.php`):

**1) Create a helper function:**

```
// Helper function used to return the children of a specific menu item
function MODULENAME_menu_subtree_data($item, $tree) {
    foreach ($tree as $cid => $data) {
        if ($item['mlid'] == $data['link']['mlid']) {
            return array($cid => $data);
        }
        if ($data['below']) {
            $return = MODULENAME_menu_subtree_data($item, $data['below']);
            if ($return) {
                return $return;
            }
        }
    }
    return FALSE;
}

```

**2) Create a reusable output function:**

```
// Return all the menu items for the parent of the given page.
// $menuParent = menu_get_active_trail(); Needs to be called on the requesting page
function MODULENAME_parent_menu($menuParent) {
    // Get active trail to current page
    $menuParent = menu_get_active_trail();
    // Pop off last item of trail as that is the current page
    $menuParentPop = array_pop($menuParent);
    // Store the new last item in the trail as this is the parent menu item
    $menuParent = end($menuParent);
    // Set the depth to which we want to return the parent menu tree
    $max_depth = $menuParent['depth'] +1;
    $mlid = $menuParent['mlid'];
    $menu_item = menu_link_load($mlid);
    $tree = MODULENAME_menu_subtree_data($menu_item, menu_tree_all_data($menu_item['menu_name'], $link = NULL, $max_depth));
    $tree = array_shift($tree);
    $tree_array = menu_tree_output($tree['below']);
    return drupal_render($tree_array);
}

```

**3) Place this code in your `node.tpl.php` file wherever you want the menu to be rendered:**

```
<?php
// Print all the menu items for the parent of the current page.
print MODULENAME_parent_menu($menuParent = menu_get_active_trail());
?>

```

**Notes**: \- Replace `MODULENAME` with your custom module name or theme name if in `template.php` \- You can adjust the "depth" of what's returned by adjusting the `$max_depth` variable to suite your needs. 0 = show everything.

Totally welcome any way to improve this!

---
Tags: routes
---


# Question
Title: How to trigger email, account/user and order creation actions when payment is made in paypal, not when user is redirected back
I have read many discussions of this sort, but just couldn’t get my head around this issue.

I am testing my site locally and using paypal WPS as my module to process payments. As default, when my users are directed to paypal and makes the payment, they are not re-directed back to my site unless they click one of the paypal links to be redirected back and as a result no user account is created, no order is recorded and no order/welcome emails are fired, unless the user goes back to my site, which I do not want.

So I went to rules and replaced all the ‘Completing the checkout process’ events with ‘When an order is first paid in full’ events, so that I can have all the above actions triggered as soon as the payment is first made on paypal, but unluckily none of these rules are now working and I assume it’s because I am not receiving IPNs on localhost. I did look into the logs.

Here’s a quick list of questions I would need your advice on.

Q1. Am I really having these issues because of not receiving the IPNs in localhost. The way I looked for IPN was by looking into the admin\>reports\>Recent log messages. Please let me know if it’s the correct way?

Q2. If that is the reason, do I have to put my site live to test the IPNs. It might be a silly question but what if my users attempt to make payments while I my site is live and still in a test phase. Is there a way I can test this all locally first.

I hope it has nothing to do with rules and replacing all the ‘Completing the checkout process’ events with ‘When an order is first paid in full’ events is the right move to create accounts, orders and send emails when the payment is made, rather than when the user comes back to the site.

I am using xampp stack and paypal sandbox account to test my site.

# Answer
> 1 votes
**Q1**

To test Paypal unfortunattely you need to test on a website which Paypal also can connect to. This is not necessaraly your live site. Maybe you should setup a test/demo environment somewhere else. If you don't want people to access that site you can setup an extra login with htpasswd, but it needs to be disabled during testing of the IPN. An easy way to do this is using the shield module.

**Q2**

You can always test using another payment method. For other tests I always use the Payment Example module which is provided with the Payment module in Drupal Commerce. This way you can test payments without having to deal with receiving IPNs.

---
Tags: commerce, rules
---


# Question
Title: Allow multiple instances of reCAPTCHA on the same page
There are several forms in a page and I use recaptcha module for all of them. The problem is, the recaptcha is generated for one of them not all of them.

In Allow multiple instances of reCAPTCHA on the same page the recaptcha-mutltiple\_instances-1833822-31.patch patch is offered, and sounds it is working (I am not sure). But the problem is the `recaptcha.js` file doesn't exist in the recaptha module folder while it asks to update that file as well.

This is the module folder:

# Answer
> 1 votes
The issue was first open for the developer version 7.x-1.x-dev, which contains that file; then it was updated for 8.x-2.x-dev, and then 7.x-2.x-dev. You need to install the developer version, and apply the patch for that developer version.

---
Tags: 7, captcha
---


# Question
Title: array_shift() expects parameter 1 to be array, boolean given in include()
I'm using the following to get the raw value of a field Drupal:

```
$foo = field_get_items('node', $node, 'field_foo');
$foo_shift = array_shift($foo);
$foo_value = $foo_shift['value'];

```

Which works a treat but every so often I get the following error:

Warning: array\_shift() expects parameter 1 to be array, boolean given in include() (line 106 of ).

I think it might have somehting to do with checking the value is set as I only get it after going to a page where the value isn't set. But if I try to check 'field\_get\_items('node', $node, 'field\_foo')' is set that doesn't work.

# Answer
> 1 votes
How do you mean by "that doesn't work"? The problem is likely because `field_get_items` returns FALSE if the field doesn't exist on that node. Checking if `$foo` is empty (using `empty`) should work. So something like:

```
$foo = field_get_items('node', $node, 'field_foo');
if (!empty($foo)) {
  $foo_shift = array_shift($foo);
  $foo_value = $foo_shift['value'];
}

```

Alternately, because `field_get_items` returns false when it doesn't have a value to return, you could just put the `$foo = ...` line in the if statement itself:

```
if ($foo = field_get_items('node', $node, 'field_foo')) {
  $foo_shift = array_shift($foo);
  $foo_value = $foo_shift['value'];
}

```

The problem with `isset` is that it's just checking if the variable has a value attached to it. FALSE doesn't ping it as not being set, whereas FALSE is included in the list of values that are considered empty for `empty`.

The "Just to Remind" section of this posts: http://alexchernomaz.com/2014/10/14/php-empty-isset-is\_null/ provides an excellent table of what values are considered empty/null/set for each function (`empty`, `is_null`, and `isset`), if you're interested in learning more.

# Answer
> 0 votes
Never assume an array (or object) is filled. So after you retrieve an array or object (e.g. field\_get\_items) you always need to check if it has data before doing anything with that data.

In your case, your code would look something like this:

```
$foo = field_get_items('node', $node, 'field_foo');
if (!empty($foo)) {
  $foo_shift = array_shift($foo);
  $foo_value = $foo_shift['value'];
}

```

I mostly use the magical empty function which checks if the variable exists, is not empty, is not NULL and is not 0.

Edit: Erin was a sec faster posting the answer, at least we're on the same page. ;)

---
Tags: entities
---


# Question
Title: Filter entities in a view by referenced entity
I am creating a website in Drupal 8 that shows info about team members of a business.

I've created two new content types: \- Department \- Team Member

I've created an entity reference field in team member that refers to the department he/she works for. The relation is many to many so I allowed multiple values.

Now I want to create a menu item for each department and when clicked a page shows with the team members working for that department.

I am totally new to Drupal so please explain steps in details :)

I've tried creating a view and add "Entity Reference" but I don't know how to proceed after that. I also tried to add a filter criteria but didn't work as well.

# Answer
> 0 votes
**Phase1:**
You would need to construct a view using contextual filters, relationships and dynamic path (url) to display team members for a department.

* First create a view with **Content** type of **Department**. Also enable **Create a page** and add path like for example, ***/department/%***. Here % is used to make your path dynamic (to pass arguments such as nid using contextual filters). Then click **continue & edit**.
* Now in your view under the advanced section, add a reverse relationship to your team member content type. You should select something like **A bridge to the content entity that is referencing content via field\_teammember**. The field\_teammember is an entity reference field from team member content type.
* Next under fields, add all the required fields you need. If you add any of your team member content type fields, do not forget to add relationship in those fields settings.
* Again under the advanced section, add contextual filters. Select **Content:Nid** and in the settings *do not add relationship* because this Nid will be of the department content type (base table of your view).
* In the same contextual filter configuration, under **When the filter value is NOT available** section, select **provide default value** and then select type as **Raw value from URL**. The path component value will be the position of **%** in your url. In the path you specified **/department/%**, its in the second position. Select **2** for your path component value and click **apply**.

This should have already generated a view as you required.
Now to preview your view, find an Nid of any department node and paste it in the **Preview with contextual filters** and click **update preview**. This will display the team members of that department.

**Phase2:**
Now create a view of departments list for menu items.

* Create a view and select **Content** type of **Department**. You do not require a page for this view. Click **Continue & edit**.
* Under fields, if you already have a **Title** field as your department name then add only an **Nid** field. And in the Nid field settings enable **Exclude from display**.
**Note:** If you don't have title field as your department name, then remove the title field and add a department name field.
* Now if you are using title field, disable **Link this field to the original piece of content** option. Then expand **Rewrite results** section and enable **Output this field as a link**. In the link path, add your dynamic url created for previous view like ***www.xyz.com/department/\[nid\]***.
**Note:** In the link, Nid is replaced with %. This could be some other value in your view, so you need to get this from **Replacement Patterns** in the field settings.

This will create another view for your departments list. Now install and enable Menu views module if you don't have it. Next in the *Administrator/Structure/Menus*, create a menu and in the settings select departments list view to display the list as menu items.
Hope this helps.

---
Tags: views, entities
---


# Question
Title: How to debug rules that are not being run?
I have few rules bound to the **Event**: **Completing the checkout process**

After completing the checkout process these rules should run - but they do not work...

I am using Devel module to debug the Rules and in the dblog there is nothing about these rules - There are only rules that are actually being run upon other events.

How can I debug this ?

# Answer
/config/workflow/rules/settings

Enable all debugging and it should show in the log if the event is correct. It will go through each condition and say which passed and which failed.
> 0 votes

---
Tags: 7, rules, debugging
---


title: Help creating action

text:
# Question
Title: Help creating action
Here is the code I currently have:

```
function mymodule_action_info() {
  return array(
  'mymodule_send_mail_admin_action' => array(
  'type' => 'node',
  'label' => t('Send a mail to administration warning insertion and deletion of nodes.'),
  'configurable' => FALSE,
  'triggers' => array('node_insert', 'node_delete'),
  ),
);
}

function mymodule_send_mail_admin_action($object, $context) {

```

if ($context\['hook'\] == 'node\_insert') {}

//if ($context\['hook'\] == 'node\_delete') {} }

What should I put inside the `mymodule_send_mail_admin_action` function? How should I complete it?

**Note**: I need to write a function for this (not use rules).

# Answer
You don't need to create this action programmatically. You can simply use the Rules UI. I'm pasting an export of a sample Rule that does this. You can import it using the Rules UI import link.

```
{ "rules_email_administrators_when_new_node" : {
    "LABEL" : "Email administrators when new node",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [], "node_delete" : [] },
    "DO" : [
      { "mail_to_users_of_role" : {
          "roles" : { "value" : { "3" : "3" } },
          "subject" : "Node added or modified.",
          "message" : "Hi, administrator(s),\r\n\r\nA node has been added or deleted.\r\n\r\nNode ID: [node:nid]\r\nNode title: [node:title]\r\n\r\n"
        }
      }
    ]
  }
}

```

EDIT: Now, if you MUST do this programmatically, I would first look at the Examples for Developers project (it contains an action example). In a nutshell:

* First, I would use `dpm($context);` and '`dpm($object);` to see what parameters are being passed to the function. You can probably use some of the information there to include in the email, like the node ID and the author ID.
* Then I would load an array of administrator users, maybe using EntityFieldQuery or a db\_query.
* Then I would use `drupal_mail()` to send the email. It shouldn't be hard to do.
> 1 votes

---
Tags: nodes
---


# Question
Title: Retrieve taxonomy terms with EntityFieldQuery for a given parent term
I am retrieving a tid of a taxonomy term by using `EntityFieldQuery`. However, I need to cross-link the taxonomy\_term\_hierarchy table to list those terms which have a particular parent, but I am not able to get it. In the code below

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'taxonomy_term')
      ->propertyCondition('vid', $vocabulary)
      ->propertyCondition('name', $termino)
      ->propertyCondition('parent', $parent_id)

```

the last line is throwing the following (expected) error. The same code, without the last property condition, works correctly. How can I achieve the result?

The returned error is:

> PDOException: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'taxonomy\_term\_data.parent' in 'where clause'

# Answer
Using only the `EntityFieldQuery` class, you cannot because the information about the taxonomy hierarchy is not contained in the database table used for the entity data, but in the taxonomy\_term\_hierarchy table.

You would need to first get all the taxonomy term IDs having `$parent_id` as parent, from that table, and then use the `EntityFieldQuery` class for the other part of the query. Truly, the `EntityFieldQuery` class is excessive, in this case, since its purpose is to make a query involving the values of field attached to an entity. It also slower than a normal query done with `db_select()`, and you would not get any benefit, in this case.
> 4 votes

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


# Question
Title: What does Drupal do when registering a user?
I'm relatively new to Drupal. I like to understand what Drupal does programatically when a user is being created?

More specific I like to know if any file is being created? Or is it just a database transaction? Where is the database changed? Which tables?

Because I would like to build a 3rd internal party to create acct from 'behind' so I need to understand what it does so my 3rd party app can mimic the same and at the end the new user login seamless.

# Answer
No file is being created (unless you count the user avatar), only a database row in the *users* table.

You should check out the user\_save function in the Drupal docs.
> 2 votes

# Answer
It's in the database under "users"..

> ```
>    name   varchar(60)
>
>
>
>    pass   varchar(128)
>
>
>
>    mail   varchar(254)
>
>
>
>    theme  varchar(255)
>
>
>
>    signature  varchar(255)
>
>
>
>    signature_format   varchar(255)
>
>
>
>    created    int(11)
>
>
>
>    access int(11)
>
>
>
>    login  int(11)
>
>
>
>    status tinyint(4)
>
>
>
>    timezone   varchar(32)
>
>
>
>    language   varchar(12)
>
>
>
>    picture    int(11)
>
>
>
>    init   varchar(254)
>
>
>
>    data   longblob
>
>
>
>    uuid char(36)
>
> ```

And if you have the devel module, you can see a few other things that other modules implement by going to /user/1/devel

The password is hashed but I saw code somewhere before where that is explained.
> 0 votes

# Answer
If I were you I'd create a callback within drupal that programatically creates users with the user\_save() function. This way they are created correctly and you don't have to worry about what tables to write and stuff. Drupal uses hooks to trigger functionality when a user saves so if you write directly to the database you'll bypass all of that and potentially cause all sorts of problem

So from your third party system you can post some data to that callback (e.g. username, email address) to create these users.

There's lots of examples on creating users programtically e.g.: http://www.paulbooker.co.uk/drupal-developer/code-snippet/create-user-account-drupal-7-programmatically
> 0 votes

---
Tags: users
---


# Question
Title: Commerce form refresh: 500 error on /en/system/ajax
Where can I find more information about this error? Nothing is appearing in logs, the error message itself has no useful data.

```
An AJAX HTTP error occurred.
HTTP Result Code: 500 Debugging information follows.
Path: /en/system/ajax
StatusText: Service unavailable (with message)

```

Some background info:

Just grasping at straws this point, and may actually completely rework how this feature will work, but just in case anyone has any bright ideas:

Product variations exist in Commerce, certain options refresh the form via Ajax (this is a built-in commerce function), and on refresh any attribute/field that is no longer available is not included with the refreshed form. Again, total standard Commerce function.

I have used a few modules to help me create variations, such as Bulk Product Creation, and as recently has 1 month ago used the exact same process to do this successfully. That product is still working.

When I inspect the ajax call itself there's nothing really unique to this vs. the other working product(s).

I have tried eliminating variations, increasing PHP memory/POST stuff, etc., and have also turned on full error reporting.

# Answer
> 1 votes
Answering my own question so my stupidity is saved for all to learn from.

More details can be found in the "Reports" section of the site.

I have now resolved my issue, and it was a line of code in a custom module we made.

---
Tags: 7, commerce
---


title: Custom date formats in webform emails

text:
# Question
Title: Custom date formats in webform emails
I have a webform that sends an email. The webform has a date field and I need to format that date field.

I have tried:

```
[submission:values:date_field:CUSTOM_FORMAT]
[submission:values:date_field:long]
[submission:values:date_field:value:custom:d-M-y]

```

Both result in a blank date.

How can I format the date in a webform email using a non-default (which appears to be `short`) date format?

# Answer
I had to create a custom hook\_tokens function:

```
/**
 * Implementation of hook_tokens().
 */
function MODULE_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  if ($type == 'submission' && !empty($data['webform-submission'])) {
    $node = isset($data['node']) ? $data['node'] : node_load($submission->nid);

    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'values:date_field:custom_format':
          foreach ($node->webform['components'] as $cid => $component) {
            if ($component['form_key'] == 'date_field') {
              $replacements[$original] = format_date(strtotime($data['webform-submission']->data[$cid][0]), 'custom_format');
            }
          }
          break;
      }
    }
  }

  return $replacements;
}

```
> 1 votes

---
Tags: 7, webforms, tokens
---


# Question
Title: Different behaviour saving programatically vs UI
I am having a problem saving nodes programatically. I am attempting to save nodes that use the following pathauto pattern for an alias:

\[node:og-group-ref:0:url:relative\]/\[node:menu-link:parents:join-path\]/\[node:title\]

Both the first and last token work fine both ways. However, the middle token - \[node:menu-link:parents:join-path\] - returns empty when saving through a script and populates fine when saving through the UI.

I've inspected $node object that is being passed through in each case and they are identical, except for $node-\>path. When saving through the UI the $node-\>path value looks something like this (copied from devel dsm message):

```
[path] => Array
    (
      [alias] => communications/some-person
      [pid] => 153
      [source] => node/100
      [language] => und
      [pathauto] => 1
    )

```

However, when saving programatically $node-\>path looks like this:

```
[path] => Array
          (
            [pathauto] => 1
            [alias] =>
          )

```

As you can see, its missing data that is present when saving through the UI, and I suspect that data is needed to correctly parse the token.

Anyone have any idea why these two would be different or why the \[node:menu-link:parents:join-path\] token doesn't work when saving through the script?

If it matters, script is pretty straight-forward:

```
<?php
$nids = db_query('SELECT nid FROM {node} where nid = 100')->fetchCol();
foreach (node_load_multiple($nids) as $node) {
  echo "Saving node " . $node->nid . "\r\n";
  print_r($node);
  node_save($node);
}

```

Thanks in advance.

# Answer
> 1 votes
For anyone that might find this in the future, this is related to this issue:

http://drupal.org/node/1534356

Still trying to figure out a workaround for my scenario, but this is the cause.

---
Tags: tokens, path-aliases
---


# Question
Title: Page rendered correctly but display errors
Page was rendered correctly but it display the following error message:

```
Strict warning: Only variables should be passed by reference in include() (line 31 of C:\xampp\htdocs\mysite\sites\all\themes\mytheme\templates\page.tpl.php).

```

I have a image field name field\_header\_image and I want to used the image as the header background image in my page.tpl.php. here is my code

```
<div id="hero-container" class="hero-container" style="background:linear-gradient(rgba(0, 0, 0, 0.35), rgba(0, 0, 0, 0.35)), url('<?php echo render(file_create_url($node->field_header_image['und'][0]['uri'])); ?>');">

```

It display correctly and I can use the field image as my header background but it display the above error. Is there a better way to get rid of this error without using a module.

# Answer
First of all, the 'und' is not prefered, you should use LANGUAGE\_NONE constant instead. This is not part of the sollution, but part of the Drupal coding standards.

This is a tricky one. The function render() expects a string, but you give a part of an object with some deeper array keys. The simplest way to get around the strict warning is to use the following code:

```
<?php $uri = file_create_url($node->field_header_image[LANGUAGE_NONE][0]['uri']); ?>
<div id="hero-container" class="hero-container" style="background:linear-gradient(rgba(0, 0, 0, 0.35), rgba(0, 0, 0, 0.35)), url('<?php print render($uri); ?>');">

```
> 0 votes

---
Tags: theming, entities, media
---


# Question
Title: How do I integrate queries to legacy databases?
I'd like to totally move to Drupal and was hoping for information. I have an old classic asp site with webpages everywhere, not in a framework or cms or anything like that. They're just set up like the "old way" of doing things. Mixed code and presentation and so on.

I wanted to move to Drupal, but I need to know how to handle the legacy or new non-Mysql datasources.

For example, I have an asp page that hits a sql server database. If I rewrite that in PHP, how do I get it into Drupal? Do I create a module for each page I want to port over? What do I do? Should I not use Drupal if this is my need?

# Answer
> 2 votes
Welcome to Drupal (and also Drupal answers) :) Glad to hear that you've chosen Drupal.

Although the scope of this question is pretty big, I'll try my best to answer. Feel free to ask more questions.

You might want to first check out whether Drupal fits in your requirements. You can check Case Studies of different sites which were built (from scratch or migrated) on Drupal. See if it gives you any idea.

If Drupal does fit into your requirement (mostly it does), you can check if there is any Drupal distribution present which is closer to your requirement (e.g. Commerce Kickstart distribution is a customized Drupal installation which is modified to provide features for a typical e-commerce site; while OpenPublish distribution is for news/articles publishing).

You don't need to develop a module per page. If you come across any requirement, there is a popular saying which goes "There's a module for that", which just means that there is a possibility that someone else who faced the same problem came up with the solution in the form of a module. You can search the list of modules on the official Drupal.org site, or drupalmodules.com, or just google it ;-)

You might also check for the Migrate module, which provides out of the box support to migrate sites powered by other technologies to Drupal (with some customization).

If you get any queries in your *Journey to Drupal Land*, you're always welcomed here on StackExchange's Drupal site :)

# Answer
> 1 votes
Have a look at the Forena module which can be used to query (not update) any MS SQL database. It comes with a full suite of Supported database connections ... such as MySQL, MS SQL, Oracle, Postgress or any PDO compliant variation.

For more details about Forena, 2 types of documentation are available:

The Sample reports and graphs are fully functional, such as the drill downs available on the Master Summary with drill down.

The newest 7.x-4.x version also includes a UI for either creating your reports (the **WYSIWYG report editor**) and/or for creating your SQL queries (the **WYSIWYG Query Builder**).

Disclosure: I'm a co-maintainer of Forena.

**Note**: a D8 branch has been started, though no (beta) release for D8 is available yet.

---
Tags: migrations
---


# Question
Title: Lots of permissions errors, should the entire site be set to www-data?
This is my first time configuring a lamp stack and I'm running into lots of problems with permissions. Here's an example of one of the errors

`The specified file temporary://fileChLMzd could not be copied, because the destination directory is not properly configured. This may be caused by a problem with file or directory permissions. More information is available in the system log.`

When I go to reports / recent log messages, this is all I can find:

`REFERRER http://localhost/boilerplate/public/admin/reports/dblog
MESSAGE File temporary://fileChLMzd could not be copied, because the destination directory public://js is not configured correctly.`

I use to get a lot more of these errors when I had my temp directory inside of the apache installation, but I've since moved it to /tmp, which got rid of a lot of errors.

I've currently got my entire sites/default/files folder set to 777 with www-data access, which doesn't feel safe.. is this right?

Should everything else be set to have root access, like it currently is, instead www-data?

## Stuff that I'm using:

Ubuntu 14.04
Apache2
MySQL
PHP 5.5
**Drush status:**
Drupal version : 7.41
Site URI : http://default
Database driver : mysql
Database hostname : localhost
Database username : admin
Database name : boilerplate
Database : Connected
Drupal bootstrap : Successful
Drupal user : Anonymous
Default theme : boilerplate
Administration theme : seven
PHP configuration : /etc/php5/cli/php.ini
Drush version : 5.10.0
Drush configuration :
Drupal root : /var/www/html/boilerplate/public
Site path : sites/default
File directory path : sites/default/files
Private file directory path : /var/www/html/boilerplate/private Temporary file directory path : /tmp

# Answer
You should **never** give the files directory 777 permissions unless your workin on a local machine. Still then it is bad practice.

Every file in the system needs to be readable by the system user your webserver is using. Every directory should be readable, writable and executable by the same user. The same could be said for the webserver group.

I always set the user to my local user and the group to a group that is readable by my user account & the webserver account. The files directory (and his subdirectories) could be set to a simple 775 so the user and the group have permissions to it. All other users should only be able to read & execute the directory. As for the files inside the files directory, they should be readable and writable to the local user and the webserver group & only readable for all other users. They should be set to 664.

The same could be said about your private directory, which I just noticed in your error post.
> 1 votes

---
Tags: files
---


# Question
Title: Drupal cannot create sites/default/files even though permissions seemed to be set to standard
I continue to get an error message regarding file permissions on a sandbox server running RHEL 7

```
$ drush wd-show
 ID   Date          Type      Severity  Message
 398  15/Jun 20:15  file      error     The directory sites/default/files exists but is not writable and could not
                    system              be made writable.
 397  15/Jun 20:15  file      error     The file permissions could not be set on sites/default/files.
 396  15/Jun 20:14  file      error     The directory sites/default/files exists but is not writable and could not
                    system              be made writable.
 395  15/Jun 20:14  file      error     The file permissions could not be set on sites/default/files.
 394  15/Jun 20:12  file      error     The directory sites/default/files exists but is not writable and could not
                    system              be made writable.
 393  15/Jun 20:12  file      error     The file permissions could not be set on sites/default/files.
 392  15/Jun 20:12  file      error     The directory sites/default/files exists but is not writable and could not
                    system              be made writable.
 391  15/Jun 20:12  file      error     The file permissions could not be set on sites/default/files.
 390  15/Jun 20:11  file      error     The directory /var/www/drupal-private-file-system/tmp exists but is not
                    system              writable and could not be made writable.
 389  15/Jun 20:11  file      error     The file permissions could not be set on
                                        /var/www/drupal-private-file-system/tmp.

```

I have followed the model from Securing file permissions and ownership. Even though my file permissions are as such:

```
[dev@sandbox sites]$ ll
total 8
drwxr-x---. 6 dev apache   61 Jun  8 14:38 all
drwxr-x---. 4 dev apache   55 Jun 15 15:08 default
-rw-r-----. 1 dev apache 2365 May  6 23:13 example.sites.php
-rw-r-----. 1 dev apache  904 May  6 23:13 README.txt

```

and

```
[dev@sandbox default]$ ll
total 24
drwxr-x---. 3 dev apache    37 Jun 10 13:35 behat-tests
drwxrwx---. 3 dev apache    35 Jun  5 15:21 files
-rw-r-----. 1 dev apache 24103 Jun  8 10:30 settings.php

```

The folder structure looks like the following...

```
[dev@sandbox sites]$ tree -d -L 2
.
├── all
│   ├── libraries
│   ├── modules
│   ├── tests
│   └── themes
└── default
    ├── behat-tests
    └── files

```

**My question:** Where did I go wrong? Is there something you see here that I don't?

# Answer
> 0 votes
I disabled SELINUX by changing to disabled.

```
$ cat /etc/sysconfig/selinux

# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#     enforcing - SELinux security policy is enforced.
#     permissive - SELinux prints warnings instead of enforcing.
#     disabled - No SELinux policy is loaded.
SELINUX=disabled
# SELINUXTYPE= can take one of these two values:
#     targeted - Targeted processes are protected,
#     minimum - Modification of targeted policy. Only selected processes are protected.
#     mls - Multi Level Security protection.
SELINUXTYPE=targeted

```

I would love to understand SELinux better or how to tune it in regards to Drupal.

# Answer
> 0 votes
Disabling SElinux mean that you lose a lot of security features.

```
chcon -R -t httpd_sys_content_rw_t yoursite/sites/default/files/

```

The command

```
setsebool -P httpd_can_sendmail on

```

May also be helpful to enable sending e-mails.

You can learn more about SElinux here: https://drupalwatchdog.com/volume-2/issue-2/using-apache-and-selinux-together.

---
Tags: files
---


# Question
Title: How to use Subtitles/Captions with MediaElement.js module
Would anyone have some direction to upload subtitles/captions using the MediaElement.JS module?

# Answer
> 2 votes
The MediaElement module doesn't support it. In order for ME.js to display subtitles, you need to add a `<track>` element (e.g. `<track kind="subtitles" src="subtitles.srt" srclang="en" />`). The module's theme function, `theme_mediaelement_video()`, doesn't render that element.

In lieu of this, you can override the theme function to add the required `<track>` element. For example placing this in your theme's **template.php**:

```
//Here we're assuming an .srt with the same name of the video exists alongside
//(e.g. "sites/default/files/video.mp4 & sites/default/files/video.mp4.srt)
//Given you might want to upload srt files along with content
// you'll want a better solution

function MYTHEME_mediaelement_video($variables) {
  $output = '<div class="mediaelement-video">';
  $output .= '<video ' . drupal_attributes($variables['attributes']) . ' >';
  $output .= '<track kind="subtitles" src="' . $variables['attributes']['src'] . '.srt" />';
  $output .= '</video>';
  if ($variables['settings']['download_link']) {
    $output .= '<div class="mediaelement-download-link"><a href="' . $variables['attributes']['src'] . '">' . filter_xss_admin($variables['settings']['download_text']) . '</a></div>';
  }
  $output .= '</div>';
  return $output;
}

```

---
Tags: media, files
---


# Question
Title: How to add html head link tag when a specific block is loaded
I have a custom block with its own twig template file.

I want to add an html head link tag when this block is loaded. ex: `<link rel="import" href="test.html">`

In the twig template I can use `attach_library` to add css/js to , but I don't know how to add html imports in twig.

Is it possible to achieve this using `mytheme_preprocess_block` function, or any other hook?

I can add the html head link tag in `mytheme_page_attachments_alter` but I don't know how to limit this to only when my custom block is loaded.

Thank you.

# Answer
> 5 votes
See `NodeViewController::view()`:

```
  $build['#attached']['html_head_link'][] = array(
    array(
      'rel' => $rel,
      'href' => $node->url($rel),
    ),
    TRUE,
  );

```

You can add html\_head\_link #attached elements anywhere, including in your block, and it will bubble up and be added to any page that shows your block.

# Answer
> 0 votes
Thanks Berdir,

What I was missing is using `\Drupal::service('renderer')->render()`

I created an array with #attached key, then rendered it using the above method.

```
// Attach html head link.
function mytheme_attach_html_head_link($href) {
  // Prepare html head link tag.
  $link = array( array(
    'rel' => 'import',
    'href' => $href,
  ));
  // Attach link tag.
  $element = array();
  $element['#attached']['html_head_link'][] = $link;
  \Drupal::service('renderer')->render($element);
}

```

Then I was calling the above function conditionally in `mytheme_preprocess_block(&variables)` by checking `$variables['attributes']['id']`

---
Tags: 8
---


# Question
Title: how to set up checkbox value while creating a node
Here is my code. I have a problem with while creating node. There are three checkboxes which user have to select; only the last checkbox of data (black color) is saved for node.

What is wrong with my code?

```
$node = new stdClass();
$node->type = 'product';
node_object_prepare($node);

$node->title    = $title;
$node->language = LANGUAGE_NONE;

$node->field_operator['und']['0']['tid'] = 135;// white color
$node->field_operator['und']['0']['tid'] = 136;// blue color
$node->field_operator['und']['0']['tid'] = 162;// black color

node_save($node);

```

# Answer
> 1 votes
Supposing the field can accept multiple values, the code should be similar to the following one.

```
    $node->field_operator['und'][0]['tid'] = 135;
    $node->field_operator['und'][1]['tid'] = 136;
    $node->field_operator['und'][2]['tid'] = 162;

```

---
Tags: nodes
---


title: Custom block template

text:
# Question
Title: Custom block template
All the examples for creating custom block online return #markup from build(), but I'd like to return a render array and have it use a template that's part of the module.

Would love an example of how to do this.

# Answer
An array with #markup *is* a render array, just the most basic version of it. If you want to use a theme or template, then just do so. Using and defining templates hasn't changed that much compared to D7, the biggest difference is that they're now html.twig files and not .tpl.php.
> 2 votes

---
Tags: blocks, 8
---


# Question
Title: Hiding a Tab when the View from Field View is Empty
I'm using Views Field to show a view in a Horizontal Tab in a content type. My trouble is that when the view returns empty based on filter criteria, the tab is not hidden.

The view itself has 4 fields from the content plus some custom text.

I tried going through some of the "Not Empty" tips for hding blocks when views are empty, but It didn't work and it was all a shot in the dark anyway.

# Answer
Try with this

```
$node = node_load($argument);
if ((isset($node->field_fotos) ||
     isset($node->field_summary)) &&
     (is_array($node->field_fotos) &&
     count($node->field_fotos) > 0) ||
     (is_array($node->field_summary) &&
     count($node->field_summary) > 0)) {
  return TRUE;
}
else {
  return FALSE;
}

```
> 0 votes

---
Tags: views, entities
---


# Question
Title: An error occured while attempting to process /ajax/ajax_facets/refresh:$.blockUI is not a function
Ajax facets work but I get an error "**An error occured while attempting to process /ajax/ajax\_facets/refresh:$.blockUI is not a function**" when I click on ajax links with checkboxes for the facets for the first time.

I am using search api views as per mentioned in the project description You can check the error in the screenshot attached

# Answer
> 0 votes
The above issue was occuring due to conflict with other module Ajax Screen Lock

Disabling it solves the problem.

---
Tags: views, ajax, search
---


# Question
Title: How can I featurise / store changes to a view provided by a module?
In my case, Workbench and Workbench Moderation. Workbench Moderation gives me a "My Drafts" and "Needs review" view which I can edit to my taste, but I can't see a way of featurising the view or preserving my modifications in some way.

Is there an approach for this?

# Answer
You can programmaticaly alter the view with the following steps:

1. Make changes to the view lik you would do to any view.
2. Export the view and save the code returned.
3. Create a module and add the hook\_views\_default\_views\_alter() function (together with the hook\_views\_api() function.
4. Check the $views array for your view machine name and set `$views['your_view'] = PASTED VIEWS EXPORT`.

Now you may revert your view and the changes you made will be kept as the default settings.
> 1 votes

# Answer
As far as I know, you cannot featurize a view that is provided by a module. What you can do is clone the view and featurize that.

I don't know about the Workbench modules specifically, but some modules allow you to choose which view is displayed via the UI. If they don't allow that, you will likely need to go in and modify the view call manually in a custom module.
> 2 votes

# Answer
I have found a guide here which supplements lukedekker's answer with regard to overriding default views:

https://www.drupal.org/node/1014774
> 1 votes

---
Tags: 7, features
---


title: User profile page title is mistake

text:
# Question
Title: User profile page title is mistake
I use login toboggan and profile2. Now I'm logged in as "user1". The I logout and login with "user2". When I then go to the user profile page of user2 I see "user1" in page title.

Clearing the browser cache isn't a solution.

Clearing DRUPAL cache works (but at the moment DRUPAL cache is disabled). Then I see the right username in page title. Is it possible to exclude the user profile page data from DRUPAL cache?

# Answer
> 0 votes
Caching in metatag coused the problem. Disabling the metatags for users solved it.

---
Tags: users, caching
---


# Question
Title: In function hook_block_view, what is the use of '#theme'
In function hook\_block\_view, what is the use of `#theme`. As we code :

```
<?php
function hook_block_view($delta = '') {
 $block = array();
 switch ($delta) {
   case 'syndicate':
   $block['subject'] = t('Syndicate');
   $block['content'] = array(
       '#theme' => 'feed_icon',
       '#url' => 'rss.xml',
       '#title' => t('Syndicate'),
   );
   break;
 ?>

```

# Answer
When an element with the `#theme` property set is rendered, it invokes the `theme()` function, with all other properties on the element (i.e. all except `#theme`) as arguments.

So your example:

```
$block['content'] = array(
  '#theme' => 'feed_icon',
  '#url' => 'rss.xml',
  '#title' => t('Syndicate'),
);

```

Is equivalent to:

```
$block['content'] = theme('feed_icon', array(
  'url' => 'rss.xml',
  'title' => t('Syndicate'),
));

```
> 0 votes

# Answer
Setting `$block['content']` with that array is like using the following code.

```
$block['content'] = theme('feed_icon', array('url' => 'rss.xml', 'title' => t('Syndicate')));

```

`#theme` is followed by the theme name, and each index that would be passed in the `$variable` array to the theme function are prefixed with a `#` and used in the array together `#theme`.

The usage of `#theme` is shortly described in `drupal_render()`, where you can read:

> HTML generation for a renderable array, and the treatment of any children, is controlled by two properties containing theme functions, #theme and #theme\_wrappers.

Its usage is not limited to `hook_block_view()` but it can be used in every place Drupal expects also a render array being returned from a hook or another function, such as a page callback.
> 0 votes

---
Tags: blocks
---


# Question
Title: Update form attributes with javascript and get them on submit
Hi i have a textfield form with attribute of "data-updated" the default is 0 If user clicks on textfield and fill it, "data-updated" changes to 1 with jQuery. On form submit the attribute remains 0 even if it changed to 1, how can i fix it?

Here is the code:

```
    $form['name'] = array(
        '#title' => t('Name'),
        '#type' => 'textfield',
        '#attributes' => array('data-updated' => 0, 'onclick' => array('jQuery(this).attr("data-updated", 1);')),
    );

```

And here is the submit

```
print_r($form_state['complete form']['name']['#attributes']['data-updated']);
die();

```

I always get 0 even if the jQuery update the attribute to 1 :/

# Answer
As Clive said in the comment, you can't fix it. To do such things in the background of a form, use a hidden element:

https://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7#hidden
> 0 votes

---
Tags: javascript
---


title: Import the data into view

text:
# Question
Title: Import the data into view
I want to import data from excel to created view how can I do this? using what module I can achieve? I found some user import tutorial but in views how to import the data?

Your suggestions are valuable thank you.

# Answer
You can never import to created view. View is to create, manage, and display lists of content. So first you have to import the data from excel sheet to the content type which you are using into your view as a **content type filter**.

To import the data, install Feeds module.

> Import or aggregate data as nodes, users, taxonomy terms or simple database records.
> 2 votes

---
Tags: views
---


# Question
Title: Installing on CentOS 6 with Apache 2.2.15
I'm trying to install 8.0 RC4 on CentOS6 with Apache2.2.15 and I'm being stopped by this error message:

> Apache/2.2.15 The minimum version of Apache needed to run Drupal without mod\_rewrite enabled is 2.2.16. See the enabling clean URLs page for more information on mod\_rewrite.

I've made sure to have this on httpd.conf: AllowOverride All

And mod\_rewrite is in fact being loaded correctly. I tried httpd -M | grep rewrite and I get: rewrite\_module (shared)

I even tried copying the htaccess sample into httpd.conf. I restart apache, and I always still get the same error. Does Drupal 8 simply not support this version of Apache? Could it be the fact that I'm accessing the site via the server's IP rather than a host name?

I tried upgrading to Apache 2.4 but that was an ordeal since the package manager doesn't provide it and the end result gave me even more problems.

Any advice?

Edit: I've installed a wordpress site and tried using SEO friendly URLs, everything works fine. Clearly mod\_rewrite has to be working.

# Answer
If you are sure that mod\_rewrite is enabled and working you could try to get past the system requirements check if you change the url during the step "Verify requirements" like this:

```
Standard URL like this:
core/install.php?langcode=de&profile=standard
change it to:
core/install.php?langcode=de&profile=standard&rewrite=ok

```

You add

> &rewrite=ok

to the url. This will normally be done through .htaccess. Then reload the page or click try again and you should get past this warning.

But it seems that something is not working as expected with your mod\_rewrite, so you might encounter trouble later on.
> 1 votes

---
Tags: 8, installation
---


# Question
Title: How do I get an array of user roles to use in #options?
Trying to convert my module to D8 and running into a problem using the D7: `user_roles()` function. Here's my D7 module code:

```
$form['role_vis_settings']['tynt_roles'] = array(
  '#type'          => 'checkboxes',
  '#title'         => t('Add tracking for specific roles'),
  '#default_value' => variable_get('tynt_roles', array()),
  '#options'       => user_roles(),
  '#description'   => t('Add tracking only for the selected role(s). If none of the roles are selected, all users will be tracked. If a user has any of the roles checked, that user will be tracked.'),
);

```

And what I've got so far for D8:

```
$form['role_vis_settings']['tynt_roles'] = array(
  '#type'          => 'checkboxes',
  '#title'         => $this->t('Add tracking for specific roles'),
  '#default_value' => $settings['tynt_roles'],
  '#options'       => user_roles(),
  '#description'   => $this->t('Add tracking only for the selected role(s). If none of the roles are selected, all users will be tracked. If a user has any of the roles checked, that user will be tracked.'),
);

```

But get:

```
The website encountered an unexpected error. Please try again later.

```

I've looked at:

The second was closet but not a format the `#options` array would allow (https://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/8#options).

Anyone have any ideas?

# Answer
> 7 votes
The correct function name is:

```
user_role_names()

```

---
Tags: users, 8
---


# Question
Title: Display only the last submission per user of a webform in views
I have a webform. I want to create a view of all submissions to the webform, but I only want to display the last submission for any particular user based on the "Webform submissions: Completed" field. i.e. I only want one row per user if they have submitted the form multiple times.

Is it possible to create a filter that will do that?

# Answer
> 1 votes
I have worked out a simple solution to this - the Views Distinct module

# Answer
> 1 votes
Limit the Submission view result to 1. And sort "submission ID" by decending order.

---
Tags: views, users, webforms
---


title: Theme taxonomy term page based on depth

text:
# Question
Title: Theme taxonomy term page based on depth
Is there any solution on how theme the taxonomy term page per depth? Though this is doable with Views + TVI, we don't usually allow admin to manage TVI, but they're able to add new term and they're allowed to rearrange the terms. I would like that each depth has a different layout, but automatically changing based from its depth. This can done through hooks or how to achieve this in views?

For instance:

```
if ($depth == 0) {
  print $views_0;
}
elseif ($depth == 1) {
  print $views_1;
}
elseif ($depth == 2) {
  print $views_2;
}
else {
  print $views_default;
}

```

and so on...

# Answer
Create a funtion to retrive term depth

```
//Gets the depth of the term id
function MYMODULE_term_depth($tid) {
  $parent = db_query("SELECT parent FROM {taxonomy_term_hierarchy} WHERE tid = :tid", array(':tid' => $tid))->fetchField();
  if($parent == 0) {
    return 1;
  }else  {
    return 1+MYMODULE_term_depth($parent);
  }
}

```

And Print the views based on depth

```
$depth = MYMODULE_term_depth($tid)
if ($depth == 0) {
  print views_embed_view('views_0');
}
elseif ($depth == 1) {
  print views_embed_view('views_1');
}
elseif ($depth == 2) {
  print views_embed_view('views_2');
}
else {
  print views_embed_view('views_default');
}

```

pass the view machine name to `views_embed_view`
> 1 votes

# Answer
The easiest way is probably to use `taxonomy_get_parents_all()`:

```
$depth = count(taxonomy_get_parents_all($tid));

```
> 0 votes

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


title: Why do breadcrumbs just show "Home"?

text:
# Question
Title: Why do breadcrumbs just show "Home"?
Do breadcrumbs show by default in Drupal 8? I have created nodes, added them to the menu, and made some parent child relationships in the main menu. The breadcrumb in Bartik only shows 'Home'. Is there a trick or config to flag to get the breadcrumbs to show?

# Answer
Looks like 'path' is required.. maybe it's always been like this and I just didn't realize. Installing Pathauto (from GitHub) and Token (from Drupal.org) corrects the issue.
> 1 votes

---
Tags: theming, 8, breadcrumbs
---


# Question
Title: Using SQL how do I select the value of a translated field in a specific language?
Give an entity field that has been translated into the target language, how do I retrieve a specific language version using SQL - not php.

Give this query for instance (using an imaginary field called data on an entity form):

```
SELECT field_method_value
FROM entityform
LEFT JOIN field_data_field_method
ON entityform.entityform_id = field_data_field_method.entity_id

```

And assuming that we have a default language of English (en) and Spanish (es) enabled on our site, and that a translated value for the spanish version of the field is stored...

What SQL statement would return the Spanish version rather than the English one?

# Answer
The field language is stored in the `language` column of each row in the field table.

So you just need to add a simple condition to your SQL, e.g.

```
language = 'es'

```
> 0 votes

---
Tags: i18n-l10n, database
---


# Question
Title: Permissions on example payment method- Drupal commerce
This is probably something simple, but I'm having a hard time configuring the permissions that would only allow the administrators to see the example payment method of the Drupal Commerce module. I have example payment method activated for testing purposes but every time I activate it, the example payment methods appears public. How can I configure the permission so that only the administrators can see the example payment method. I appreciate any help.

# Answer
> 2 votes
You have to go admin/commerce/config/payment-methods And edit the example payment. In there you can set a condition that is on user. Data type of current user is admin and that will only allow admins to process the test payments.

# Answer
> 0 votes
@topCweb shows the way. In terms of details, here is an export of the condition that I ended up using. The "User has role(s)" condition seemed the easiest. The exact role number may vary for each site.

```
 "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } },
          "operation" : "OR"
        }
      }
    ],

```

---
Tags: users, commerce
---


# Question
Title: PHP cli script for flushing drupal cache
So I have created script that flushes drupal's cache and it's ran in CLI.

The problem is after first use, I can't use the script again, because some classes ('SelectQueryExtender' or 'DrupalDefaultEntityController') are missing. Clearing cache via drupal admin menu (admin\_menu/flush-cache) fixes it and I can rerun.

Now the question is why clearing cache from via HTTP works and from CLI doesn't?

I'm running on Drupal 7 and code can be found below:

```
define('DRUPAL_ROOT', '/srv/www/'); // Drupal root folder.

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';

drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
// Clear cache.
drupal_flush_all_caches();

```

EDIT: when I clear cache via drupal\_flush\_all\_caches and later make curl call for cache clearing through apc-status.php, then even website itself gives Fatal on above mentioned classes missing.

# Answer
> 1 votes
Install Drush. It's your friend. Then you can issue

```
drush cc all

```

To clear caches.

You can also rebuild registries if needed to if you have that module installed.

---
Tags: caching
---


# Question
Title: How to automate the replacement of special characters in URLs?
The standard behavior **(\*)** for friendly URLs in Drupal is replacing special characters by a hyphen in the friendly URL.

For instance, *without any input from the user*, `versão` becomes `vers-o` and `conteúdo` becomes `conte-do`. However, we need the character to be replaced by their corresponding non-accent ASCII values, such as `versao` and `conteudo`.

Currently, we manually edit the URL when creating content. Is there a way to automate it?

---

**(\*)**: I *assume* it's out-of-the-box behavior, but this Drupal instance had modules installed and configured by other persons, maybe it's not a default behavior.

# Answer
Have a look at the Transliteration module. Here is a quote from its project page:

> ... it takes Unicode text and tries to represent it in US-ASCII characters (universally displayable, unaccented characters) by attempting to transliterate the pronunciation expressed by the text in some other writing system to Roman letters.

As a sample, it transforms an URL like `mydomain.com/последние-новости-в-Украине-и-мире` in something like `mydoamin/poslednie-novosti-v-Ukraine-i-mire`.

However, to actually make this work, you also need to enable the Pathauto module. After that, go to the Pathauto setting page and check "Transliterate prior to creating alias". For more details on that, refer to "D7 Pathauto transliteration". **Attention**: this does not "fix" already created aliases (those need to be deleted and recreated).
> 4 votes

# Answer
Are you referring to how Path Auto will create node paths? Regardless, there's good reason not to have extended characters in your URL:

> The URI syntax has been designed with global transcription as one of its main considerations. A URI is a sequence of characters from a very limited set: the letters of **the basic Latin alphabet, digits, and a few special characters.** A URI may be represented in a variety of ways; e.g., ink on paper, pixels on a screen, or a sequence of character encoding octets. The interpretation of a URI depends only on the characters used and not on how those characters are represented in a network protocol.

You can alter how Path Auto generates it's paths found at /admin/config/search/path/patterns
> 1 votes

---
Tags: 7, uri
---


# Question
Title: How can I run a jQuery script in the admin overlay?
I'd like to modify the interaction with one (or more) of my admin overlay pages, but it doesn't seem like the scripts that works on the site are directly functional in the back-end? How do I run a jQuery script within the Drupal admin overlay?

As you might tell, I'm quite new to Drupal.

# Answer
You'll need to go in and do a form\_alter on the admin overlay pages that you are wanting to modify. You will need to add an item to the `['#attached']` attribute on the form to attach your JS. You can read more about attaching JS to forms in the Drupal Form API documentation.
> 0 votes

---
Tags: javascript
---


# Question
Title: People created by non-administrator role are not allowed to edit their content
I created a role called `site manager`. This role is allowed to create new users. The problem is that users created by this user are not allowed to edit their contents. The *Access denied* is reported. But people created by the *Administrator* or people who signup for the site, can edit their content.

This is the permissions of *site manager* (for *Users* and content type *Image*):

and this one

Do any of you know why this happens?

---

**UPDATE**

After installing devel node access module I see this for a node which its author is **z jafari**

**This user is allowed to delete its content but unable to edit it.**

I also tried content access module, gave appropriate permission but it didn't work again.

# Answer
> 0 votes
I found the answer, I installed Edit Limit module to limit the time which a user can edit its comment. But I made a mistake by checking the checkbox of node edit.

**many thanks to all the guys who helped me.**

# Answer
> 1 votes
Because they don't have any roles associated with them. You need to add a role to the new users giving them the permissions you want them to have.

# Answer
> 1 votes
The "Configure Block" button is confusing me a bit. But anyways, check to make sure the users are listed as the author of the nodes and use the devel module to compare an administrator created user and a site manager created user.

Also, give the edit any node permission to authenticated and check what happens.

# Answer
> 1 votes
I think the problem is coming from the "site manager" permissions and he is not able to created a user with the correct ones.

Have you tried to add: "Access the content overview page" and "Administer content" to site manager?

Use this code and log in as one of the users:

```
  global $user;
  dsm(user_role_permissions($user->roles));

```

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


title: Avoid change for users profile fields

text:
# Question
Title: Avoid change for users profile fields
Now in my site every logged user are able to change his profile fields (standard fields and custom fields). I am searching a way to avoid this capability for every 'normal' users (in other word i want that only the administrator have this ability).

There is a method to do this via code or via frontend?

# Answer
> 0 votes
I believe the Field Permissions module will do what you are wanting. It allows you to determine which roles can edit, view, and create values for any field.

# Answer
> 1 votes
You can use the project Edit Own User Account Permission. It adds a new permission to People \> Permissions called "Edit own user account". You can then allow specific roles the ability to edit their own account.

---
Tags: 7, entities, users
---


title: Not sure why I get Uncaught TypeError

text:
# Question
Title: Not sure why I get Uncaught TypeError
What I am trying to accomplish with this is to have a URL for the API accessible via Drupal.settings so I can get to it from PhP and js with Drupal 7.41.

I have put this at the top of my custombootstrap.module file:

```
function yourmodule_init(){
    $apiurl="http://dev3.ws.mysite.com/api"
    drupal_add_js(array('yourmodule' => array('myurl' => $apiurl)), array('type' => 'setting'));
    variable_set('myurl',$apiurl);
}

```

In a file called mapLayer.js I use the code like this:

```
var List_Users_Map = function(){
var userId = $('#uid-loged').val();
$('#list-users-gis-map').html('');
//linkedRequests(userId);   // RCD- CAll
$.ajax({
    url: Drupal.settings.yourmodule.myurl+'linked_users_gis/x-api-key/blahhhhhhhhhhTq4SWuCiLONePNfschNft',
    data:{uid:userId},
    type: 'GET',
    ...

```

Uncaught TypeError: Cannot read property 'myurl' of undefined can be seen here in chrome dev tools. It looks like it gets to 'yourmodule' but no further.

```
    http://imgur.com/cu4jtw6

```

# Answer
your init hook seems to be wrong, change the function name to `custombootstrap_init`, where the init hook is not the best choice for adding a js setting ..

in drupal it's good practice to use a behavoir, so wrap your js code like:

```
Drupal.behaviors.myModuleBehavoir = {
  attach: function (context, settings) {
    ..
  }
};

```

and then just use `settings.yourmodule.myurl`
> 0 votes

---
Tags: javascript
---


# Question
Title: How to solve the error while uploading image to nodes?
I have a content type and it has an image field. I'm using the File Field Paths module for the image field.

I **uploaded** images for some nodes via Drupal interface but then **deleted** them via **FTP**.

Then I'm trying to re-upload images to these nodes via Drupal but it gives this error and couldn't find anything to solve the problem.

How can I solve this problem via Drupal or via PHPMyAdmin etc.?

# Answer
Try the Upload QC module. Some details about it (from its project page):

> This module offers checks and validations for the process of uploading files. It extends the Drupal 7 core and helps avoid errors during file upload. You can now say good bye to ***PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry '' for key 2: INSERT INTO {file\_managed}.***
>
> WHO SHOULD USE
>
> This module is for you if:
>
> 1. you run into errors like this one PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry '' for key 2: INSERT INTO {file\_managed} OR PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry ... for key 'uri': INSERT INTO {file\_managed}.
> 2. you would like to add additional file upload validations that check for (a) file name length, (b) file name containing certain words/characters, (c) file name not containing certain words/characters.
> 3. Drupal and/or PHP upload size limit is not working for you and you would like to set it yourself in your admin section.

Looks like item "1." is pretty close to your issue, no?
> 1 votes

---
Tags: 7, media
---


# Question
Title: Is there a way of completely replacing the SQL of a View with my own custom string?
Recently I completed a rather complicated View, with plenty of relationships, filters, etc. I needed the View for its elegant page system. Is there a way, after seeing the SQL string, that I complete my string in MySQL, and with minimal change, use it in `db_query` standard format to replace the SQL string of the View? I know about `hook_query_alter` and `hook_view_query_alter` but it is too much abstract than a simple SQL-string, mainly if I already have the string almost complete from the Views UI.

# Answer
**Don't do that.** You've got two options: either use Views or don't.

# Option 1: Use a custom block/page handler

You can build your own query and theme it any way you want it. Just build it as a block or a custom page and do it the "old-fashioned" way. It will be much cleaner than trying to use views.

# Option 2: Use Views

If you want views, then you should build any additional plugins, handlers, or add any alters you need and do it right (that includes using the DB abstraction layer). This isn't hard and there is plenty of documentation floating around that can help you with this.

If you circumvent the systems you have (e.g. Views), you will end up producing code that isn't maintainable by someone else or could unknowingly introduce problems. Please don't look for shortcuts, do it well and do it right.
> 5 votes

---
Tags: 7, views, database
---


# Question
Title: Commerce Price Table: What would cause sporadic zeroing of prices when adding to cart?
I'm having an issue where the prices in the price tables are sometimes being applied when adding items to the cart, and later, other items are set to zero when added to the cart. First off, I must mention that I am working with products that have 3 price tables, and each price table has 4 price breaks. I wasn't exactly clear on if/why support for multiple tables was or wasn't possible, but I am worried that this might be the culprit. If it's not safe to have multiple price tables for a product, please let me know right away!

Other details: Each of the 3 price tables for a product is for a different user role. I use field permissions on a multipage view to make this possible. What may make it complicated is that not every product has a price for each role. That is to say, not all products are available to all roles. To combat this, I added a filter to only show items where the price is not $0.

I'm very deeply entrenched in this module, as I have several commerce feeds going and thus have spent many hours formatting the incoming data in the CSV files, so Commerce Pricelist would not be a good alternative.

# Answer
Obviously, something is wrong somewhere when the rules are firing to apply pricing. Read up on debugging rules and you'll likely find your problem.

One thing you may want to consider is just writing your own custom logic and then creating a new rule to call your custom logic, bypassing the logic of Commerce Price Table. You'll likely need to really spend your time adding your logic to `commerce_price_table_get_amount_qty` since that's where the actual field and price get determined.
> 1 votes

---
Tags: commerce, rules
---


# Question
Title: Populate node image field with files submitted by webform?
Just wondering if this can be done in any way.

I have a block webform which is shown in a give node, let call this node Page-1.

The Page-1 node has a multivalue image field.

You can attach files to the webform (using https://www.drupal.org/project/webform\_multiple\_file).

Now let's say I submit the webform with 3 images attached, then my question: is there any way to populate the image field of the Page-1 node with those images?

# Answer
> 1 votes
Any issues with using: hook\_webform\_submission\_insert and copy these images to current viewing node?

If node ID isn't available in webform submission, you can always put hidden field to webform with a NID.

---
Tags: entities, webforms, media
---