# Question
Title: How to log and display all the users that have edited a node (without revisioning)?
We need to keep the usernames of the latest editors of content, along with the edit date.

How can we do so? Or should we use custom code?

We do not want to enable revisioning, as it is more complex than we want.

# Answer
> 2 votes
The Activity module does some user activity logging that may covert your need.

> The Activity module keeps track of the things people do on your site and provides mini-feeds of these activities in blocks, in a specialized table, and via RSS. The module is extensible so that any other module can integrate with it. The messages that are produced are customizable via the admin interface and are context sensitive. Some theoretical example messages include:
>
> * You wrote a comment in response to "example comment title"
> * Jim wants to be your friend. Approve this friendship here
> * Nancy is Phil's latest fan

# Answer
> 1 votes
IMO the Message module would be a perfect fit to answer this question, and which doesn't require revisioning. Using this module, you can create your own custom "*Events logging*" (to register things that happened in a site).

Specific to this question here, I'd create a so called "Message type" that contains data about:

* the usernames (of the latest editors of content).
* the edit date.
* any data about the actual node you want to track, such as the node's id (of course), its title, author, some fields, etc.

You could even track how those node related data looked like before and after they got updated, a kind of "light" revisioning (only for those node attributes you want to know about).

About *Message types*: think of them as equivalent to Content types, whereas you create messages (instead of nodes) of a specific Message type (instead of Content type).

### Rules integration

A really interesting facility of the Message module is its perfect integration with the Rules module. Have a look at the answer to "How to implement a follow author (or user) function?" for way more details on that.

In your case, you'd simply create a (rather basic) custom rule which uses:

* a Rules Event like "Before saving a new node", of "After updating an existing node" (or variations of these events).
* a Rules Action to "Create a message" (of a selected Message type).

That's really it ...

### Example included in Commerce Kickstart

A great sample of this can be found in Commerce Kickstart, which uses the Commerce Message module, to create such "*Events logging*". In that case in the format of an Order History, as shown in this screenprint (from this module's project page).

### Replicate/replace the Activity module

Should you want to do so, it seems perfectly possible to build a view (report) that contains the data similar to what you can do with the Activity module as shown in this screenprint (from this module's project page).

### More info about the Message module

The Message module is an amazing module, it is fully entity based, which implies that it perfectly (out of the box) integrates with modules such as Views and Rules.

Though there is ***not a lot of documentation about it*** (which is what makes it a hidden D7 gem ...). A possible way to get started with it, and to get an idea of the kind of things it can be used for, is to have a look at the answers to:

**Tutorials:**

# Answer
> 1 votes
One option is the Event Log module:

> This module logs specific events. The events are saved in the database and can be viewed on the page admin/reports/events. Furthermore, a views integration is provided in which you can relate for instance a node to its events. You could use this to display the total number of views, or the number of times that the node has been modified and by which users.
>
> Currently, the following events are supported:
>
> * User authentication (login/logout/request password)
> * Node operations (CRUD)
> * User operations (CRUD)
> * Menu operations (custom menu's and menu items CUD operations)
> * Taxonomy operations (vocabulary and term CUD operations)
>
> The event log can be easily extended with custom events. For more information please have a look at the API documentation and the available sub modules.

There is no configuration required except for enabling/disabling the sub-modules you require - there is a sub-module for each of the 5 event types in the module description above.

---
Tags: 7, nodes, log-messages
---


title: Modify code to use batch api?

text:
# Question
Title: Modify code to use batch api?
I have a custom module written to import data from a Salesforce API and update organic group info by adding/updating/removing members from groups. I originally wrote it as a drush command for ease of development, and now I've moved it to a set of functions initiated from hook\_cron() using a cron queue. An additional requirement is that the import process have the ability to be run from a form submission. The process is long running enough that it times out when running from a simple form submission, so I need to use the batch api. Looking at all the examples, it looks like I need to have one function handle each item so that the batch process can call that function for each individual item. Here's what's working so far:

```
/**
 * Main function to get data from Salesforce and put it into an array.
 * Called both from a form and drush command.
 */
function naa_committee_get_salesforce_data() {
  $base_url = 'https://api/url';
  // The web service expects the body to be in JSON format, so we create it as an
  // array and convert it to JSON.
  $url_data = array(
    "Name" => "GetCommittees",
    "AuthenticationKey" => "my_secret_key"
  );
  $url_data = json_encode($url_data);
  // Set the Content-Type header.
  $headers = array('Content-Type' => 'application/json');
  // Query the URL and get the returned data.
  $data = drupal_http_request($base_url, array('headers' => $headers, 'method' => "POST", 'data' => $url_data));

  $records = drupal_json_decode($data->data);

  $sf_members = array();
  foreach ($records['Records'] as $record) {
    $user_id = $record['NU__Account__r']['Id'];
    $user_name = $record['NU__Account__r']['Name'];
    $email = $record['NU__Account__r']['PersonEmail'];

    // If array doesn't yet exist for this user, create it.
    if (!$sf_members[$user_id]) {
      $sf_members[$user_id]['user_name'] = $user_name;
      $sf_members[$user_id]['email'] = $email;
    }
    // Add committee to committees element.
    $sf_members[$user_id]['committees'][] = array(
      'committee_name' => $record['NU__Committee__r']['Name'],
      'committee_id' => $record['NU__Committee__r']['Id'],
      'committee_code' =>  $record['NU__Committee__r']['NU__CommitteeShortName__c']
    );
  }

  // Pass data to parsing function.
  if (naa_committee_parse_records($sf_members)) {
    return TRUE;
  }
  else {
    return FALSE;
  }
}

/**
 * Parse returned records
 *
 * @param records
 *   An array of committee member records returned from Salesforce.
 *
 */
function naa_committee_parse_records($sf_members) {
  // Loop through returned records.
  foreach ($sf_members as $user_id => $member) {
    // Do an EntityFieldQuery to see if user already exists.
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'user')
          ->propertyCondition('name', $user_id);
    $result = $query->execute();

    if ($result) {
      // Since user_id is distinct, we're just taking the first
      // one from $result['node'];
      $uid = current(array_keys($result['user']));
      $account = entity_load('user', array($uid));
      $user = $account[$uid];
      $groups = og_get_entity_groups('user', $user);

      // Need to filter groups to make sure they are committees.
      if ($groups) {
        foreach ($groups['node'] as $key => $group_nid) {
          $group_node = entity_load('node', array($group_nid));
          if ($group_node[$group_nid]->type != 'committee') {
            unset($groups['node'][$key]);
          }
        }

        // Check to see if user should be removed from any memberships.
        naa_committee_check_removed($user, $groups['node'], $member['committees']);
      }

      foreach ($member['committees'] as $committee) {
        if (!$member['email']) {
          $name_array = explode(' ', $member['user_name']);
          $member['email'] = strtolower($name_array[0] . '.' . $name_array[1] . '@naahq.org');
        }
        naa_committee_update_membership($user, $committee, $groups);
      }
    }
    else {
      // Doesn't exist, so create user.
      naa_committee_create_user($user_id, $member);
    }
  }

  return TRUE;
}

```

So what I have now is one function that loops through all of the records, and for each one determines if it exists, and then hands the record off to the appropriate function. In order to do the batch api, do I need to do something like move the code that loops through the results array to naa\_committee\_get\_salesforce\_data() and then pass each individual record to naa\_committee\_parse\_records()? Or can I use it with what I have now?

Thanks.

# Answer
I assume that you have solved your issue by now but I was just doing some batch API work and found your question. Hopefully, this answer helps.

I added code to create the batch in the first function. The second function will be called by the batch API while processing the batch.

```
/**
 * Main function to get data from Salesforce and put it into an array.
 * Called both from a form and drush command.
 */
function naa_committee_get_salesforce_data() {
  $base_url = 'https://api/url';
  // The web service expects the body to be in JSON format, so we create it as an
  // array and convert it to JSON.
  $url_data = array(
    "Name" => "GetCommittees",
    "AuthenticationKey" => "my_secret_key"
  );
  $url_data = json_encode($url_data);
  // Set the Content-Type header.
  $headers = array('Content-Type' => 'application/json');
  // Query the URL and get the returned data.
  $data = drupal_http_request($base_url, array('headers' => $headers, 'method' => "POST", 'data' => $url_data));

  $records = drupal_json_decode($data->data);

  $sf_members = array();
  foreach ($records['Records'] as $record) {
    $user_id = $record['NU__Account__r']['Id'];
    $user_name = $record['NU__Account__r']['Name'];
    $email = $record['NU__Account__r']['PersonEmail'];

    // If array doesn't yet exist for this user, create it.
    if (!$sf_members[$user_id]) {
      $sf_members[$user_id]['user_name'] = $user_name;
      $sf_members[$user_id]['email'] = $email;
    }
    // Add committee to committees element.
    $sf_members[$user_id]['committees'][] = array(
      'committee_name' => $record['NU__Committee__r']['Name'],
      'committee_id' => $record['NU__Committee__r']['Id'],
      'committee_code' =>  $record['NU__Committee__r']['NU__CommitteeShortName__c']
    );
  }

  // If there is data to process then setup a batch.
  if (count($sf_members)) {
    $operations = array();
    // Add an operation for each user to be processed.
    foreach ($sf_members as $user_id => $member) {
      $operations[] = array(
        'naa_committee_process_record',
        array(
          $user_id,
          $member,
        )
      );
    }

    $batch = array(
      'operations' => $operations,
      // If desired set the function to be executed when the batch finishes processing.
      'finished' => 'naa_committee_batch_finished',  // remove this line if not desired.
    );

    batch_set($batch);
    return TRUE;
  }
  else {
    return FALSE;
  }
}

/**
 * This function is called by the batch API
 */
function naa_committee_process_record($user_id, $member, &$context) {

  // Use native drupal function user_load_by_name rather than EntityFieldQuery
  // to load user or return false.
  $user = user_load_by_name($user_id);
  if ($user) {
    $groups = og_get_entity_groups('user', $user);

    // Need to filter groups to make sure they are committees.
    if ($groups) {
      foreach ($groups['node'] as $key => $group_nid) {
        $group_node = entity_load('node', array($group_nid));
        if ($group_node[$group_nid]->type != 'committee') {
          unset($groups['node'][$key]);
        }
      }
      // Check to see if user should be removed from any memberships.
      naa_committee_check_removed($user, $groups['node'], $member['committees']);
    }

    foreach ($member['committees'] as $committee) {
      if (!$member['email']) {
        $name_array = explode(' ', $member['user_name']);
        $member['email'] = strtolower($name_array[0] . '.' . $name_array[1] . '@naahq.org');
      }
      naa_committee_update_membership($user, $committee, $groups);
    }

    // Add information to the $context for use by the naa_committee_batch_finished function
    // if desired
    $context['results'][$user->uid] = 'User record updated.';
  }
  else {
    // Doesn't exist, so create user.
    naa_committee_create_user($user_id, $member);

    // Add information to the $context for use by the naa_committee_batch_finished function
    // if desired
    $context['results'][$user->uid] = 'User record created.';
  }
}

```

Hopefully this helps.

Additional information about passing data to the finished function.
> 0 votes

---
Tags: 7, importing-exporting, batch-operations
---


title: How to make author field required?

text:
# Question
Title: How to make author field required?
In Drupal 8. I noticed that I can create a new node or edit a current node and delete the "Authored By" name, it's blank and when I hit save the node is authored by Anonymous.

How can I make this Author field required to be a current user in the system?

And the page will show a message and will not save until a name is entered. I tried this but it does not work:

```
use Drupal\Core\Form\FormStateInterface;

function demo4_form_alter(&$form, $form_state, $form_id) {
$form['author']['name']['#required'] = TRUE;
}

```

I also tried this:

```
function demo4_form_alter(&$form, $form_state, $form_id) {
if ( $form_id == 'page_node_form'){
$form['author']['name']['#required'] = TRUE;
}
return $form;
}

```

This works only in Drupal 7 not in Drupal 8, And I changed `page_node_form` to `node_page_form` for Drupal 8

```
function demo4_form_alter(&$form, $form_state, $form_id) {
if ($form_id == 'page_node_form') {

$form['author']['name']['#required'] = TRUE;
 }
   return $form;
}

```

# Answer
> 2 votes
What you're looking for is this:

`$form['uid']['widget'][0]['target_id']['#required'] = TRUE;`

(Devel is your friend!)

You were on the right track as `$form['author']['#required'] = TRUE;` will make the "Authoring Information" have a red star (\*), but won't make your authored by field required.

Complete code:

```
function hook_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'your_form_id') {
    $form['uid']['widget'][0]['target_id']['#required'] = TRUE;
  }
}

```

---
Tags: 8, forms
---


title: Create rule to Set Default Value

text:
# Question
Title: Create rule to Set Default Value
Here my query is that, I have created one field in product type "Time(Interval)" and another field created in Line item types "(Default Time)" field. My requirement is when user saves a new commerce order, Product type (Time(Interval) field) value auto saves in Line item field (Default Time) value. how we can do this, any idea.

# Answer
You can implement hook\_commerce\_cart\_product\_add() The product which user is adding to cart and the line item is available with in this hook. you can fetch the Time(Interval) field value from product and save it to line item.

```

function my_module_commerce_cart_product_add($order, $product, $quantity, $line_item) {
   $commerce_line_item = commerce_line_item_load($line_item->line_item_id);
   $product_time = $product->time_interval['und'][0]['value'];
   $line_item->default_time = $product_time;
   commerce_line_item_save($line_item);
}

```
> 3 votes

---
Tags: commerce, rules
---


# Question
Title: Not able to assign value to hidden form field using form_alter hook
I have a form in which field `my_consultant_id` is "Hidden integer" type field and having widget type as "Hidden field".

I am assigning the value to this field by using hook\_form\_alter

```
function threebl_summary_report_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'eck__entity__form_add_summary_report_comparative_client_group') {
        global $user;
        $form['field_created_by']['und'][0]['#default_value'] = (int) $user->uid;
    }
}

```

But not able to set the value for that field.

If I inspect the form it shows html code for field like:

```
<div class="field-type-field-hidden-integer field-name-field-my-consultant-id field-widget-field-hidden form-wrapper" id="edit-field-my-consultant-id">

```

Thanks in advance.

# Answer
I managed to do it by validate handler of the form. Using validate handler I assigned my value to the form variable before submit.

In form alter hook call validate handler like below

```
$form['#validate'][] = 'my_module_name_form_validate';

```

And following is the validate handler function code

```
function my_module_name_form_validate(&$form, &$form_state) {
$form['field_my_field']['#parents'] = array('field_my_field');
form_set_value($form['field_my_field'],array('und' => array(0 => array('value' => $new_value))),$form_state);

```

}

For reference please go through link
> 3 votes

# Answer
I think you are missing default value.

try

```
$form["my_consultant_id"][LANGUAGE_NONE][0]['value']['#default_value'] = (int)$user->uid;

```
> 0 votes

---
Tags: 7, entities, forms
---


# Question
Title: How db_query works when I pass query parameter directly
I have one doubt for db\_query in drupal 7, as in documentation db\_query syntax is like

```
$result = db_query('SELECT n.nid, n.title, n.created
FROM {node} n WHERE n.uid = :uid', array(':uid' => $uid));

```

But what happens when I write query like.

```
$result = db_query("SELECT n.nid, n.title, n.created
FROM {node} n WHERE n.uid = $uid");

```
* **Is it still convert in PDO prepared statements?**
* **Is it still reliable as first query?**
* **Will it handle SQL injection?**

# Answer
> 4 votes
1. No
2. Do you mean "is it a syntactically valid query"? If `$uid` is an integer or string that forms the remainder of a syntactically correct query then yes, otherwise no
3. Very much no

In short, don't do that. Use the API as the documentation says to, or you'll be susceptible to bugs and security holes.

# Answer
> 4 votes
According to Writing secure code for Drupal 8 (same for D7)

> ## Use the database abstraction layer to avoid SQL injection attacks
>
> Use the database layer correctly. For example, never concatenate data directly into SQL queries.
>
> **Don't do this:**
>
> ```
> db_query('SELECT foo FROM {table} t WHERE t.name = '. $_GET['user']);
>
> ```
>
> **Instead, use proper argument substitution with db\_query**. The DB layer works on top of PHP PDO and uses an array of named placeholders:
>
> ```
> db_query("SELECT foo FROM {table} t WHERE t.name = :name", [':name' => $_GET['user']]);
>
> ```

---
Tags: 7, database
---


title: UI can't be accessed

text:
# Question
Title: UI can't be accessed
I noticed 3 issues with my site and I feel they are all related:

1. The context link is absent from admin/structures. When i type www.example.com/admin/structure/context, it redirects back to www.example.com/admin/structure.
2. Also Views is missing from the structure menu

Both the Context and Views U.I modules are enabled.

3. When I go to the /admin/reports/dblog page, the message and operations column are blank as in the image below.

The UI issues started after i re-enabled the modules. I previously disabled them on my site but now need to make some edits.

I have tried clearing cache a couple of times. I have also manually emptied the cache menu table in the Database.

I am logged in as User 1.

I would be grateful if anyone could point me in the right direction.

Thank you.

# Answer
> 0 votes
As per your "*after I re-enabled the modules*": try to (temporary) increase your PHP memory limit (eg with 25%) to see if you get different results ... Doing so *might* get to work it as normal again.

That's one of the typial things I (temporary) do if such kind of issues come up (typically after enable of 1 or more extra modules due to which the current memory limit is not sufficient anymore).

---
Tags: views
---


# Question
Title: How to pass query parameter in form submit?
I have a form :

```
function buildForm(array $form, FormStateInterface $form_state) {
    $form['edit'] = array(
          '#type' => 'textfield',
    );
    $form['submit'] = array(
          '#type' => 'submit',
          '#value' => t('Go'),
          //'#markup' => "<div><a href='?word=1'>Go</a></div>",
        );
    return $form;
}

```

Now I want is; when I submit form,`$form_state->getValue('edit');` should get appended as a query parameter in form route.

Let's say my form route is:

```
mymodule.admin_page:
  path: '/mypage'
  defaults:
    _form: '\Drupal\mymodule\Form\myform'

```

And when I hit submit button of form, the route should get changed to `/mypage?word=$form_state->getValue('edit')`.

I tried below approach, but it is throwing error:

Created 1 more route with a parameter:

```
mymodule.word:
  path: '/mypage/{word}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\AdminController::myfunction'

```

And in my form submit function,

```
function submitForm(array &$form, FormStateInterface $form_state) {

    $data = $form_state->getValue('edit');
    $url = Url::fromRoute('mymodule.word',['word'=>$data]);
    $form_state->setRedirectUrl($url);
   }

```

But when I hit submit button, it is giving me error,

> Uncaught PHP Exception Symfony\Component\Routing\Exception\MissingMandatoryParametersException: "Some mandatory parameters are missing"

# Answer
Stick with your original route definition:

```
mymodule.word:
  path: '/mypage'
  defaults:
    _controller: '\Drupal\mymodule\Controller\AdminController::myfunction'

```

Then set your submit handler to this:

```
function submitForm(array &$form, FormStateInterface $form_state) {

  $data = $form_state->getValue('edit');
  $url = Url::fromRoute('mymodule.word', [], ['query' => ['word' => $data]]);
  $form_state->setRedirectUrl($url);
}

```
> 5 votes

---
Tags: 8, forms
---


# Question
Title: cache : "drush cr" versus admin toolbar "flush all caches"
What the drush cr would do that the flush all caches would not? Particularely regarding block caching?

I got mad trying to set a custom block twig template for eventually figuring out that nothing was wrong with my code but flush all caches was not enough and drush cr would do the job.

https://www.drupal.org/node/2640110

EDIT: could there be a bias of my local dev settings ?

```
$settings['cache']['bins']['render'] = 'cache.backend.null';

$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

```

# Answer
Drush's cache-rebuild command does the following:

* Clears the APC cache
* Bootstraps Drupal
* Calls drupal\_rebuild()
* Clears the Drush cache (to maintain consistency with Drupal 7's drush cache-clear command)

Source: https://drupalize.me/tutorial/clear-drupals-cache?p=2512.

In drupal 8 it is recommended to use cache-rebuild instead of cache-clear. Your dev settings shouldn't matter for this.

in drupal 8 the drush cc all is deprecated and yo should always use drush cr.
> 1 votes

---
Tags: theming, 8, blocks, caching
---


# Question
Title: What is the right way to print variables with Twig?
I want to know what is the right way to print with Twig.

Example:

node.field\_related\_articles.entity.**get('field\_color\_theme')**.value node.field\_related\_articles.entity.**field\_color\_theme**.value

What is the difference? Which one we should use and why?

Example 2:

When we need to access variables through **node.field\_something** and when with **content.field\_something** in node-something.twig.html?

Example 3:

When we are printing plain text in html like:

"\< h4\>Related articles\< /h4\>"

How should we print it with twig right way so that if in future we want multilanguage site we don't need to track all plain text in html to change it?

# Answer
> 2 votes
PHP

`->get('field_example')` and `->field_example`

are the same and so is TWIG

`.get('field_example')` and `.field_example`

both get the field object (field item list) from which you can get the field value(s).

This only works for the variable `node` (or other entities when you are in a different template) and returns the raw values from the database. For example a date field would return a unix timestamp.

In contrast the `content` variable contains formatted data ready to be rendered. A date field would be rendered as configured in the content type in a human readable format.

So the answer is, you print variables by using `content`:

```
{{ content.field_example }}

```

Use `node` only when you need to process the raw data in some way where the formatted output won't work, like for example if you compare two dates you want to use a unix time stamp and not the formatted output.

Both methods are language aware, so there shouldn't be any problem from this side.

If you want to translate static text in twig use the `|t` filter:

```
<h4>{{ 'Related articles'|t }}</h4>

```

---
Tags: theming, 8
---


# Question
Title: How to rearrange the sort buttons in a view
There don't appear to be any Twig templates that allow you to move the exposed sort buttons to a different location in the view display. Does anybody know if these templates do actually exist?

# Answer
> 0 votes
Sure there is a twig for the exposed sort form. But normally you rearrange form elements inside of a form by adjusting the weight property. If you want to move the button outside of the form in another place of the view you need some tricks, look here https://stackoverflow.com/questions/7020659/submit-form-using-a-button-outside-the-form-tag/23456905

If you want to rearrange the view in general, like moving the complete exposed section to another place, you can do this in `views-view.html.twig`:

```
{{ title_prefix }}
  {{ title }}
  {{ title_suffix }}

  {% if header %}
    <header>
      {{ header }}
    </header>
  {% endif %}

  {{ exposed }}
  {{ attachment_before }}

  {{ rows }}
  {{ empty }}
  {{ pager }}

  {{ attachment_after }}
  {{ more }}

  {% if footer %}
    <footer>
      {{ footer }}
    </footer>
  {% endif %}

  {{ feed_icons }}

```

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


# Question
Title: Get user register form fields in edit profile form page
So the user register form fields are not displaying in the corect order in the edit profile form page. I have set the order of the fields from admin panel user manage fields `admin/config/people/accounts/fields`

The fields are rendering properly in the register form however in the edit profile page, the order is messed up. Is there a way to get the register form fields by using `drupal_get_form('user_register_form')` in the edit profile page and then render it from the from array? I have tried loading the register form fields but it gives me no result.

# Answer
You can edit all forms in drupal using hook\_form\_FORM\_ID\_alter

So The only thing you need is the FORM\_ID , to get that you can open any desired form , then using firebug or some tool like that you can recognize the ID of form.

in your special case the form ID of user edit form is : "user\_profile\_form" , so you can create a custom module and implement YOURMODULE\_form\_user\_profile\_form\_alter()

inside print elements as you desire.
> 0 votes

---
Tags: 7, forms, users
---


title: Views settings Menu Tabs not working

text:
# Question
Title: Views settings Menu Tabs not working
**I think module views have problem with menu tabs.**

I was created a simple views with settings menu tabs like this.

### Custom view for user

>

### Custom path

>

### Settings menu Tabs

>

### Contextual filter and settings

>

After i go to url: examples.com/user/1/display and get error

> RuntimeException: Callable "Drupal\contact\Access\ContactPageAccess::access" requires a value for the "$user" argument. in Drupal\Component\Utility\ArgumentsResolver-\>handleUnresolvedArgument() (line 142 of core/lib/Drupal/Component/Utility/ArgumentsResolver.php).

and url examples.com/user/1 with error:

> Symfony\Component\Routing\Exception\MissingMandatoryParametersException: Some mandatory parameters are missing ("arg\_0") to generate a URL for route "view.user.page\_1". in Drupal\Core\Routing\UrlGenerator-\>doGenerate() (line 171 of core/lib/Drupal/Core/Routing/UrlGenerator.php).

I was doing something wrong? Can you help me?

# Answer
This a documentation error.

The correct path for users is `user/%user/display`

In case of nodes should be `node/%node/something`
> 3 votes

# Answer
the view considers 'user' as a parameter in your custom path, so instead make use of

> 'users/%/display'

Hope this will help you.
> 0 votes

---
Tags: views, 8
---


# Question
Title: Stuck. Installing Drush via Composer not working
It looks like I installed Drush, following the directions in the documentation.

Here's what I did.

```
Jens-MacBook-Air:~ jensimmons$ composer --version
Composer version 1.0.0-alpha8 2014-01-06 18:39:59
Jens-MacBook-Air:~ jensimmons$ composer global require drush/drush:dev-master
Changed current directory to /Users/jensimmons/.composer
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing pear/console_table (1.1.5)
    Downloading: 100%

  - Installing symfony/yaml (v2.2.1)
    Downloading: 100%

  - Installing d11wtq/boris (v1.0.8)
    Downloading: 100%

  - Installing drush/drush (dev-master a2c7030)
    Cloning a2c703071e2c3374e1b3855e24d29468b9069b5c

pear/console_table suggests installing pear/Console_Color (>=0.0.4)
d11wtq/boris suggests installing ext-pcntl (*)
Writing lock file
Generating autoload files
Jens-MacBook-Air:~ jensimmons$ drush help
-bash: drush: command not found

```

When I change directories, to inside a Drupal installation, I get the same result. drush: command not found.

What am I missing??

# Answer
> 11 votes
Try adding the following to the end of your /Users/jensimmons/.bashrc file:

```
export PATH="$HOME/.composer/vendor/bin:$PATH"

```

and then run

```
source $HOME/.bashrc

```

Edit:

I just noticed there was a section in the Install/Update - Composer section of the Drush README.md file that mentions this:

https://github.com/drush-ops/drush#installupdate---composer

It's the second point "Make sure Composer's global bin directory is on the system PATH (recommended)"

Hope that helps.

# Answer
> 4 votes
I don't know why they don't include this in the directions, but you can use symbolic link to make `drush` a globally executable command:

```
sudo ln -s /home/YOU/.composer/vendor/drush/drush/drush /usr/local/bin

```

This way you don't have to worry about running `source $HOME/.bashrc` everytime you login.

Adjust your home directory as needed. ;)

# Answer
> 1 votes
**for ubuntu version**

first check is your composer path is successfully added with in your environment variable,

In your terminal type **evn** and hit enter to check available paths. composer path should be added with in "PATH=..." variable

if composer path missing add your path by this approach

if your composer working fine then follow the steps to install latest drush

Step 1: use this cmd **composer global require drush/drush:dev-master**

check your drush version.

# Answer
> 0 votes
An answer to jensimmon's question in ylynfatt's answer:

> Hm. Wait. So I leave, quit, stop working on a thing. And come back to it later. And crush doesn't work again. If I run source $HOME/.bashrc again, it works. What can I do to make this permanent?

(I can't post comment there, not enough points yet):

short answer: try putting in .bash\_profile: source ~/.bashrc

Long answer (from my notes, can't remember original sources):

> When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists.
> After reading that file, it looks for ~/.bash\_profile, ~/.bash\_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. ... When an interactive shell that is not a login shell is started, bash reads and executes commands from ~/.bashrc, if that file exists. \[/etc/profile is global, the next 3 files are local. The above might change depending on how the shell is invoked, though. So...\] By default, Terminal starts the shell via /usr/bin/login, which makes the shell a login shell. On every platform (not just Mac OS X) bash does not use .bashrc for login shells (only /etc/profile and the first of .bash\_profile, .bash\_login, .profile that exists and is readable). This is why put "source ~/.bashrc in your .bash\_profile" is standard advice.

# Answer
> 0 votes
### Composer

Try the following one-liner (if you've root privileges):

```
sudo COMPOSER_HOME=/var/lib/composer COMPOSER_BIN_DIR=/usr/local/bin COMPOSER_VENDOR_DIR=/var/lib/composer/vendor composer require drush/drush:dev-master

```

which would install the recent `drush` straight into `/usr/local/bin` (you can free to change `COMPOSER_BIN_DIR` wherever you want to install it, so `composer` would create a proper symbolic linking for you).

---

If you prefer to run it as a user, try:

```
COMPOSER_BIN_DIR=~/bin composer require drush/drush:dev-master

```

which would install the recent `drush` into your local `~/bin` (some OS recognise this directory as having executable binaries), otherwise add the following line into your `~/.bashrc` or `~/.profile`:

```
export PATH=$PATH:$HOME/bin

```

---

### Phar

Alternatively try installing Phar binary as shown below.

Download latest stable release using the command below:

**Linux**:

```
sudo install <(curl http://files.drush.org/drush.phar) /usr/local/bin/drush

```

**OS X/Unix**:

```
sudo wget -O /usr/local/bin/drush http://files.drush.org/drush.phar
sudo chmod +x /usr/local/bin/drush

```

**Windows and other**

Download manually at https://github.com/drush-ops/drush/releases

# Answer
> 0 votes
Try adding this to .bashrc

export PATH=~/.config/composer/vendor/bin:$PATH

---
Tags: drush
---


# Question
Title: Rules - Use data from webform field in new entity type
I currently have a webform with the following fields:

* Your Email
* Your Name
* Your Idea

Alongside this I have setup a rule that when a webform is submitted it creates a new node of a new content type I have created 'Idea'. A view then pulls in all these 'Ideas' to display.

The title of the node pulls in the **Your Idea** field using the value \[data:your\_idea-value\] which works fine.

But I am trying to set the author of the node as the **Your Name** field but I am struggling, it doesn't allow a value to be used and can't figure it out.

I've managed to get it working where it sets it to Anonymous and then I setup another action on the rule to rename the author:name but it does it for all of the content, not just the new node.

I'm sure I'm just missing something simple, would be great if someone could assist.

Currently setup to set author as anonymous for the time being.

# Answer
Below is something I learned about using webform data in Rules, which may help you to get this to work (assuming your question is about D7) ...

You have access to all ***labels*** and all ***values*** of any field of a webform, ie:

* `[data:MachineFieldName-title]` contains the **Label** of a field with machine name MachineFieldName.
* `[data:MachineFieldName-value]` contains the **Value** of a field with machine name MachineFieldName

So try to use similar tokens.

For way more details on this, and a prototype rule about this, refer to the answer to "How to create a node from a Webform using rules?":

* the *1st attempt* relates to using "Entity has field" (which doesn't work for Webform)
* the *2nd attempt* explains what to do in case of Webform.
> 2 votes

# Answer
The problem is with the Author section is it can only be a **Data selector** or **Direct Input**, it can't use the **Value** field that the Title section can.

Otherwise I would just be using **\[data:your\_name-value\]**
> 1 votes

---
Tags: entities, rules, webforms
---


title: Use $_POST after submit form

text:
# Question
Title: Use $_POST after submit form
I create a form and a page with controller in Drupal 8.

I want print value of my example input after submit form.

For example my input name is "Tel\_number".

My code in controller page is:

```
<?php
namespace Drupal\mymodule\Controller;
use Drupal\Core\Controller\ControllerBase;
class MymoduleController extends ControllerBase {
    public function mymodule() {
      $form['test'] = array (
         '#markup' => \Drupal::request()->request->get('Tel_number'),
      );
    return $form;
    }
}
?>

```

But no resault print.

# Answer
I use this code in form submit:

```
$_SESSION['Tel_number'] = $form_state->getValue('Tel_number');

```

And use this code in controller:

```
$TelNumber = array(
   '#markup' => $_SESSION['Tel_number'],
);
return $TelNumber ;

```
> 0 votes

# Answer
Your controller is in a new request. If you stored the data in the database retrieve it from there. If you did not store the data in submit in some place it is no longer available. You could use a session variable or a url query parameter to transfer the data from the form submit to the controller:

```
public function myFormSubmit($form, FormStateInterface $form_state) {
  ...
  $form_state->setRedirect('route_to_controller', [], ['query' => [
    'Tel_number' => '123456789',
  ]]);
}

```

and the controller

```
public function showNumber(Request $request) {

  $build['test'] = ['#markup' => $request->query->get('Tel_number')];

  return $build;
}

```
> 3 votes

---
Tags: 8, forms
---


title: Query in URL not affecting view filters

text:
# Question
Title: Query in URL not affecting view filters
I currently have a view that has a page display and a block display. The page is disabled, but I have exposed the form in a block, which is then displayed on the homepage of the site.

When the user selects the filters and submits, it then goes to another page with the results in the block view (filters included).

The problem I'm facing is that when the user submits the form from the homepage, the results aren't showing on the subsequent page. The query shows in the URL but it doesn't change the results.

This was working before, but has suddenly stopped working. Any ideas why this may be?

# Answer
Sounds like a common mistake with views.

On you filter's settings, under More make sure you have the Filter identifier set with the same name, in both your page and your block.
> 0 votes

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


# Question
Title: How do I pre / post process aggregated css or js files?
I want to declare the character encoding of our aggregated css files - how would I be able to pre or post process the aggregated css files in Drupal 8?

E.g. injecting `@charset "UTF-8";` on top of all css files.

# Answer
Using dependency injection we are able to inject a modified Asset Dumper, which can contain custom code.

Add to a custom module / or create a new module:

mymodule/mymodule.services.yml

```
services:
  asset.css.dumper:
    class: Drupal\mymodule\Asset\Utf8CssAssetDumper
  asset.css.collection_optimizer:
      class: Drupal\Core\Asset\CssCollectionOptimizer
      arguments: [ '@asset.css.collection_grouper', '@asset.css.optimizer', '@asset.css.dumper', '@state' ]

```

mymodule/src/Asset/Utf8CssAssetDumper.php

```
<?php
namespace Drupal\mymodule\Asset;

/**
 * Dumps a CSS asset and injects a utf-8 encoding string at beginning.
 */
class Utf8CssAssetDumper extends \Drupal\Core\Asset\AssetDumper {

  /**
   * {@inheritdoc}
   *
   * Injects utf-8 encoding statement at start of data string.
   */
  public function dump($data, $file_extension) {
    if ($file_extension == 'css') {
      // Don't override existing charsets.
      if (FALSE === strpos($data,'@charset ')) {
        // Charset string not found prepend.
        $data = "@charset \"UTF-8\";\n" . $data;
      }
    }
    return parent::dump($data, $file_extension);
  }
}

```

A short note on this: since this kicks in for all aggregated css files you might want to add additional checks to existing encodings etc.. If you have everything encoded the same way (which is very much suggestible) then this shouldn't cause weird side effects.

This approach also works for javascript (js) files:

```
services:
  asset.js.dumper
  asset.js.collection_optimizer

```
> 2 votes

---
Tags: theming, 8, javascript, css-js-aggregation
---


# Question
Title: How to know when to use $config or $settings overrides in settings.php?
I want to be able to disable certain options of modules on non-production environments.

For example:

* Disable XMLSitemap from running
* Set "Read Only" mode for Search API indices to TRUE
* Set robots.txt string to

```
User-agent: *
Disallow: /

```

How do you know whether you should override `$config` or `$settings` in `settings.php`?

Would it be:

```
$config['search_api.index.acquia_search_index']['readonly'] = TRUE;

```

or

```
$settings['search_api.index.acquia_search_index']['readonly'] = TRUE;

```

Also, how can you confirm if these overrides are working? Is there an admin overview page that lists these things?

# Answer
From settings.php, regarding $settings:

> Settings:
>
> $settings contains environment-specific configuration, such as the files directory and reverse proxy address, and temporary configuration, such as security overrides.
>
> @see \Drupal\Core\Site\Settings::get()

From settings.php regarding $config:

> Configuration overrides.
>
> To globally override specific configuration values for this site, set them here. You usually don't need to use this feature. This is useful in a configuration file for a vhost or directory, rather than the default settings.php. Note that any values you provide in these variable overrides will not be viewable from the Drupal administration interface. The administration interface displays the values stored in configuration so that you can stage changes to other environments that don't have the overrides.
>
> There are particular configuration values that are risky to override. For example, overriding the list of installed modules in 'core.extension' is not supported as module install or uninstall has not occurred. Other examples include field storage configuration, because it has effects on database structure, and 'core.menu.static\_menu\_link\_overrides' since this is cached in a way that is not config override aware. Also, note that changing configuration values in settings.php will not fire any of the configuration change events.
> 3 votes

# Answer
The answer is `$config`. Module options are configuration and this is what you override in `$config`.

`$settings` is the name space for which `settings.php` is the primary source, so this is not an *override*.

The question how to tell whether the overrides are working is indeed pointing to a real problem. You can't see the overrides. The admin UI shows the original values and you can even edit and save them, while the overridden configuration is active in the background.
> 3 votes

# Answer
Your question is not clear, but dev and stage environnemnts have differents settings.php, so you can modify your config in each file as you like, $config contains all globals variables to drupal, and in same time are config variables in data base ...
> -1 votes

---
Tags: 8, configuration
---


# Question
Title: How to perform redirect after login with the Modal Forms module?
I have some pages in my website with links using the Modal forms (with ctools) module to login. I want to redirect users after logging in using these modals to the same page that have the link to this modal form

Any idea how do this?

# Answer
The page callback of the login URL provided by the Modal Forms module is `modal_forms_login`.

```
/*
 * A modal user login callback.
 */
function modal_forms_login($js = NULL) {
  // Fall back if $js is not set.
  if (!$js) {
    return drupal_get_form('user_login');
  }

  ctools_include('modal');
  ctools_include('ajax');
  $form_state = array(
    // 'title' => t('Log in'),
    'ajax' => TRUE,
  );

  $output = ctools_modal_form_wrapper('user_login', $form_state);
  if (!empty($form_state['executed'])) {
    // We'll just overwrite the form output if it was successful.
    $output = array();
    ctools_add_js('ajax-responder');
    $output[] = ctools_modal_command_dismiss(t('Login success'));
    if (isset($_GET['destination'])) {
      $output[] = ctools_ajax_command_redirect($_GET['destination']);
    }
    elseif(module_exists('login_destination')) {
      $destination = login_destination_get_destination('login');
      $output[] = ctools_ajax_command_redirect($destination['path']);
    }
    else {
      $output[] = ctools_ajax_command_reload();
    }
  }
  print ajax_render($output);
}

```

At a quick glance, you can tell that you can either set your destination in the query string of your login link, like so:

```
drupal_add_library('system', 'drupal.ajax');
$login_link = l('Login', 'modal_forms/nojs/login', array(
  'query' => array('destination' => 'redirect-here'),
  'html' => TRUE,
  'attributes' => array(
    'class' => array('ctools-use-modal'),
  )
));

```

Or, install and configure the Login Destination module
> 0 votes

# Answer
I had the same issue and this is my solution:

1) create a module mymodule

2) override menu item using `hook_menu`

```
function mymodule_menu(){
    $items['modal_forms/%ctools_js/login'] = array(
        'title' => 'Log in',
        'page callback' => 'mymodule_modal_forms_login', // your custom callback function
        'page arguments' => array(1),
        'access callback' => TRUE,
        'file' => 'mymodule.module', // file with the mymodule_modal_forms_login function
        'type' => MENU_CALLBACK,
    );
    return $items;
}

```

3) copy and paste from model\_forms.page.inc on your mymodule.module file and change the name y the body of the function

```
function vdf_modal_forms_login($js = NULL) {
global $user;

// Fall back if $js is not set.
if (!$js) {
    return drupal_get_form('user_login');
}

ctools_include('modal');
ctools_include('ajax');
$form_state = array(
    // 'title' => t('Log in'),
    'ajax' => TRUE,
);

$output = ctools_modal_form_wrapper('user_login', $form_state);
if (!empty($form_state['executed'])) {
    // We'll just overwrite the form output if it was successful.
    $output = array();
    ctools_add_js('ajax-responder');
    $output[] = ctools_modal_command_dismiss(t('Login success'));

    if (in_array("custom_role_1", $user->roles)) {
        $output[] = ctools_ajax_command_redirect("custom_page_1");
    } elseif (in_array("custom_role_2", $user->roles)){
        $output[] = ctools_ajax_command_redirect("custom_page_2");
    }else {
        $output[] = ctools_ajax_command_redirect("custom_page_3");
    }
}
print ajax_render($output);
}

```
> 0 votes

---
Tags: javascript, redirection
---


title: GMAP views: Use marker field

text:
# Question
Title: GMAP views: Use marker field
I have a working GMAP view and I'd like to customize the markers basing on a list field.

I can't find documentations about this feature, in the settings of my view I setted

```
Marker Handling--> Use marker field

```

and

```
Field --> "myfield"

```

What I'd like to know is: does "myfield" has to be an image field or whatelse?

# Answer
> 2 votes
Have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

> Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
>
> The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (**Google**, **OpenLayers** or **Leaflet**) with any location storage module of your choice, e.g.:

> This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
>
> Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
>
> But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
>
> These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).

Head over to its (impressive) project page for even more information about it (it would be way too long to include a quote of it all here). That project page also includes various screenshots.

**Note**: Uploading custom markers should be possible also, similar to what you can see in the screenprint in the feature request about Custom markers.

---
Tags: 7, views, google-maps
---


# Question
Title: views and contextual filter with entity reference to current user
I have a view that I need to filter based on the current logged in user, however a secondary entity reference is in-between the two. Pretty sure I need to add in PHP contextual filter code but not exactly sure what is needed.

Scenario:

1. inventory has an entity reference to retail\_location.
2. retail\_location has an entity reference to users.
3. I need to display inventory based on the retail\_location of the logged in user.

D7.

# Answer
> 0 votes
Was able to get it working using the following code, it does however only allow for one retail location, which is all I need for this scenario.

```
  global $user;
  $query = new EntityFieldQuery;
  $query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'rnm_principal')
      ->fieldCondition('field_principal_retailer', 'target_id', array($user->uid));
  $results = $query->execute();
  return current($results['node'])->nid;

```

---
Tags: entities, views
---


# Question
Title: What does the "Empty srcset[]" breakpoint in Picture Module?
I'm using the Picture Module.

What does the `Empty srcset []` breakpoint exactly do? Why should I use it, and why shouldn't I use?

# Answer
> 1 votes
The empty srcset is to be used when there is a breakpoint where you don't want to display your image. An example might be where the image in question, or a parent div, is `display:none` in the css. The image would normally be downloaded anyway, but by having an empty srcset at that breakpoint, no images will be downloaded.

---
Tags: media, theming
---


# Question
Title: In which template file is a node title supposed to be?
I have to add a *Title* field to each content type to ensure a title appears on the node view.

This makes me wonder: Maybe I'm missing the *title* variable in my implementation of page.twig.html or something, but I don't see a *title* variable anywhere in the default page.html.twig.

1. In which template should my title variable be displaying?
2. What should the code in the template look like to display the title?

# Answer
> 4 votes
> **Page title is now a block**
>
> The page title is now provided by a block so it can be easily moved without editing the page template.
>
> The markup for the page title can be edited in page-title.html.twig, and template\_preprocess\_page\_title() can be used in conjunction with the template

Source: https://www.drupal.org/node/2568563

---
Tags: theming, 8
---


title: Webform file attachment

text:
# Question
Title: Webform file attachment
I've been struggling with an issue today that I just can't seem to figure out.

I have a webform that includes a file upload that I want to email upon submission.

The email sends correctly (using MIMEmail modules) but there is no attachment.

The webform is for job application.The user will upload the resume and portfolio. The hr and manager want to get mail along with attachment.How they can always be logged into site that is quite impossible. Now the issue is the who ever logged into the site only can see the attachment when click on the link. How to sent attachment from private folder as attachment not just in link(want proper attachment)

I'm running drupal 8. USed modules are webform, mime mail, mail system and also tried swift mailer.

But in webform module mail settings , there is "Include files as attachments" i checked that option. Still it is not working.

# Answer
> 1 votes
Out of the box Drupal 8 doesn't support file attachments. Take a look at this module and read the steps on the page: https://www.drupal.org/project/swiftmailer\`

> The Swift Mailer module extends the basic e-mail sending functionality provided by Drupal by delegating all e-mail handling to the Swift Mailer library. This enables your site to take advantage of the many features which the Swift Mailer library provides, such as :
>
> * Sending e-mails directly through a SMTP server of your choice, a locally installed MTA agent such as sendmail or the mail functionality provided by PHP.
> * Sending HTML (MIME) e-mails.
> * Adding file attachments to e-mails.
> * Adding inline images to e-mails.

Also take a look at this: https://www.drupal.org/node/2821590

---
Tags: 8, webforms
---


# Question
Title: How to create a redirection programmatically?
I try to create a redirection 301 with the redirect module. For example, I want to redirect an URL source to an internal URL through my custom module.

I want to create a redirection when I create a node. Import old content, create a new node and keep the old path.

Anyone have an idea?

# Answer
> 33 votes
If you want to store redirects in database use the module Redirect. This module provides a user interface to add redirects. The redirects are stored in a content entity, which you can also create programmatically:

```
use Drupal\redirect\Entity\Redirect;

  Redirect::create([
    'redirect_source' => 'redirects/redirect1',
    'redirect_redirect' => 'internal:/node/1',
    'language' => 'und',
    'status_code' => '301',
  ])->save();

```

You can do this at the time you create nodes from imported data or in entity hooks when inserting, updating or deleting nodes.

# Answer
> 7 votes
You can change your .htaccess by adding this code :

```
#custom redirects
RewriteRule ^old/URL/path$ http://example.com/new/path [R=301,L]
#end custom redirects

```

Or if you want do this in Drupal :

```
return new RedirectResponse(Drupal\Core\Url::fromUri('route_name'));

```

---
Tags: 8, redirection
---


# Question
Title: How do I add authentication to a POST request on an implementation of hook_menu?
I have a list of lesson plans, sorted by category. Underneath each category, I have a link called "Add new lesson/category/root term".

I would like it so that when the user clicks on "Add new category" or "Add new root term", they are prompted with a message box to get the name of the new term to add. Then, that message box will make an ajax call to **mysite.com/add-new-term**, with the name of the new term as a POST argument.

I know how to make an HTTP POST request using `jQuery.post()`. I know how to implement `hook_menu()` to enable requests to **mysite.com/add-new-term**. And I know how to use PHP's superglobal array `$_POST` to get the data from the request.

BUT, I don't know how to add user authentication to the request.

How can I ensure that only logged-in admins can make these requests? I don't want just *any random person on the web* to be able to create new terms.

# Answer
Turns out this is actually really easy.

You can get the current user's roles with:

```
global $user;
$roles = $user->roles;

```

That returns an associative array with the roles as values. Getting the values is trivial with in\_array():

```
if (in_array("Teacher", $user->roles)) {
  // allow the post request to have effect
}
else {
  // don't go through with the request; return an error
}

```

Because the module is called during the lifecycle of the Drupal structure, you have access to the whole environment.
> 0 votes

---
Tags: 7, users, javascript, ajax
---


# Question
Title: How can I add a separate template for the user login form?
So I want to create a separate user login page for my website.

I create a twig file called page--user--login.html.twig which is great for the outer container. I still want to edit the form divand or the block div. But with debugger on It doesn't give me suggestions for creating a custom form or block twig file just for just the login form.

I can create individual form elements for the login but I want to edit the form div or block div itself without affecting anything else.

Any suggestions?

# Answer
You can add a theme name suggestion in a hook\_theme\_suggestions\_HOOK\_alter:

```
function mytheme_theme_suggestions_form_alter(&$suggestions, $variables) {
  if ($variables['element']['#form_id'] == 'user_login_form') {
    $suggestions[] = 'form__user_login_form';
  }
}

```

If you want to add suggestions for form elements you need some more code. See the file themable\_forms.module from the module Themable forms. This is the only code file in this module and it is a good example how you can approach this in form alter, preprocess form element and theme suggestions hooks.
> 1 votes

---
Tags: 8, theming
---


# Question
Title: Upgrading procedures and what essential directories to copy over?
When I upgrade my Drupal 7 core I do the following process:

1. Download and unzip d7 release as d7\_upgrade
2. Delete the sites folder in the d7\_upgrade
3. Move the sites folder from my original site into d7\_upgrade
4. Rename the old D7 folder to d7\_old
5. Rename the d7\_upgrade to original folder name
6. drush updb

Majority of the non-core files reside in /sites for D7.

I know D8 has a different structure, but is the same upgrade process going to be the same? I know I would have to move over /themes /modules /sites

Is there anything else I need to move over? Or is there a better method of doing this? I want to upgrade to D8.3 beta to test on my site.

# Answer
As Kevin has stated in the comment, the "official" procedure should be found here, and it's ever evolving. I don't believe any safe automated way currently exists 100% of the time (such as with Drush/Drupal Console/Composer/etc.)

In short, upgrading D8 sucks. At least as far as I can tell. If you plan on using composer with it, you can't rely on "drush up", lest you want it all to get wiped, etc. (Actually, I'm kind of confused as to why you're not using "drush up" on your D7 sites, since you clearly have drush installed.)

In short, the process is still very similar to what you're already doing with D7. The file structure has changed in D8 though, and you need to be aware of things like modules/themes/libraries being in the root directory, rather than the sites/ directory. All that is covered in the documentation.
> 1 votes

---
Tags: 8, upgrading
---


# Question
Title: How do I allow date-time filtering on my custom entity's ISO date field
I have a custom entity with a datetime field. This datetime is saved in the database as an ISO string. I would like to use Views on this entity, and select entities with dates before, after, or between certain dates. I see if I make a view against the system log, these options are presented when filtering on Timestamp. How can I enable the same filtering options on my field?

The field definition is:

```
$fields['set_datetime'] = BaseFieldDefinition::create('datetime')
  ->setLabel(t('Set DateTime'))
  ->setDescription(t('Date and time fermentor was set.'))
  ->setSettings(array(
    'datetime_type' => 'datetime',
  ))
  ->setDefaultValue('')
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'type' => 'string',
    'weight' => -4,
  ))
  ->setDisplayOptions('form', array(
    'weight' => -4,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

```

# Answer
> 2 votes
I posted the following as a bug report to Drupal Core

> When a custom entity is created, and one of the fields is a datetime FieldType, views filters are not treating this field like a datetime field, but, instead, like a string. Timestamp Fieldtypes on the other hand are presented with the correct filter options.

The response I received was:

> Yes, it does default to a string. I think the underlying reason is this:
>
> Datetime support comes from the datetime module, so if you want your entity to use that, add a dependency to datetime and override any defaults for your entity in an extension of \Drupal\views\EntityViewsData.
>
> The Views 'date' filter only works for timestamps (hence your timestamp fields work out-of-the-box), so just setting the filter plugin\_id to 'date' won't help either.
>
> So this works as designed I think.

# Answer
> 1 votes
After checking your module provided for me on github and some reverse-engineering I find out the problem is on `create('datetime')` and you should use `create('created')` So the following code

```
$fields['date'] = BaseFieldDefinition::create('created')
  ->setLabel(t('DateTime'))
  ->setDescription(t('Date and time.'))
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'type' => 'timestamp',
    'weight' => -4,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'datetime_timestamp',
    'weight' => -4,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

```

Results the below image for me. it seems it's Ok now.

---
Tags: views, 8, entities
---


# Question
Title: Drupal 8 Equivalent of Drupal 7's disabling a module without Uninstalling it
I noticed that I can't just "disable" a module in Drupal 8. As disabling it deletes all the config data of that module and completely uninstalls it. There are times I just want to disable a module to see if that is causing issues, but I have no way to keep its config data intact like how D7 can just disable, but not uninstall.

How would one do something like this in D8?

# Answer
https://www.drupal.org/node/2225029

The long and the short of it is that you cant. This option is no longer available in Drupal and it was a conscious decision to remove the ability to disable a module because:

> * Because upgrades of some contrib module don't actually work (and can't be made to work) if upgrading when they are disabled.
> * Because data left behind by a disabled module that is later re-enabled causes integrity issues and cruft.
> * Some upgrades left behind data loss due to things like unexpected dependencies, plugins or hooks being unavailable at key times - when things were disabled. .. that issue (https://drupal.org/node/1199946) is several hundred arguments long, so It's unfair to over-summarize.
> 6 votes

---
Tags: 8, installation
---


title: Use condition in my views

text:
# Question
Title: Use condition in my views
I have a content type "event".I show all my events rejected or validated. Now in my view I want to show fontawesome icon like "cancel" to signal that the event is rejected and another fontawesome icon like "okey" to signal that the event is validate. How to use Global text to make it? I don't like to use page.tpl.php. But if there are a solution base it I can accept it.

# Answer
> 2 votes
Assuming you have a boolean field which stores if event is rejected or validated, you can read this information from PHP and print the fontawesome icon based on a condition.

The standard way in **Drupal 7** would be to use Views PHP module and do something like:

```
if ($data->field_field_event_validated['0']['raw']['value'])
  echo '<i class="fa fa-check"></i>';
else
  echo '<i class="fa fa-ban"></i>';

```

This module still isn't ported to **Drupal 8**, and actually it's really bad in terms of security and stability to use this module as this article states. The same article describes how to include PHP in your views. In resume you have to create a module, generate a custom views field with the PHP code printing your icon and use this module in Views.

---
Tags: views, theming
---


# Question
Title: How do I combine multipe hook form alter functions
How can I combine multiple functions inside one hook form alter. If I try to use them separate I get the error Cannot redeclare mymod\_form\_alter()previously declared.

i want to combine this function

```
use Drupal\Core\Form\FormStateInterface;

 function mymod_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
 if ($form_id == 'node_page_form' || $form_id == 'node_page_edit_form') {

$form['uid']['widget'][0]['target_id']['#required'] = TRUE;
 }
   return $form;
}

```

and this function

```
use Drupal\Core\Form\FormStateInterface;

function mymod_form_alter(&$form, &$form_state, &$form_id) {
$form['field_short_description']['widget']['#after_build'][] =

'_allowed_formats_remove_textarea_help';
}

function _allowed_formats_remove_textarea_help($form_element, FormStateInterface $form_state)

{

  if (isset($form_element[0]['format'])) {
    // All this stuff is needed to hide the help text.
    unset($form_element[0]['format']['guidelines']);
    unset($form_element[0]['format']['help']);
    unset($form_element[0]['format']['#type']);
    unset($form_element[0]['format']['#theme_wrappers']);
    $form_element[0]['format']['format']['#access'] = FALSE;
  }
  return $form_element;
}

```

# Answer
> 4 votes
You can do switch statements based on the form ID:

```
function hook_form_alter(array &$form, FormStateInterface $form_state, $form_id)
{
  switch($form_id)
    case 'form_id_1':
      // Alter the form with an id of form_id_1
      break;
    case 'form_id_2':
      // Alter the form with an id of form_id_2
      break;
    case 'form_id_3':
      // Alter the form with an id of form_id_3
      break;
}

```

---
Tags: 8, forms
---


# Question
Title: Site Time Zone = field time zone but != database time zone
My site time zone setting under Admin\>config\>regional... is set to Chicago time.

My field date setting is set to use my site time zone.

My user account is set to Chicago, but when I look at the database, it is recording my time as a totally different time zone.

What am I missing? I really need to resolve an issue with Drupal resource-conflict module and the fact that my all-day events don't conflict with my hourly events. There is a topic here - https://www.drupal.org/node/2270533, but I can't seem to get my dates straitened out to even try it. Anyone offer some advice?

# Answer
This is normal and expected. When you look in the DB, the Date API contrib module saves them as **UTC time**.

Drupal then fetches your Unix time UTC value, and converts it to your time zone.
> 2 votes

# Answer
When entering data into the field, the data entered is assumed to be in the site's time zone. When the data is saved to the database, it is converted to UTC. When retrieved from the database, the data is converted to the Site's time zone for anonymous users or the User's time zone for logged in users when User-configurable time zones is enabled. More info https://www.drupal.org/node/767182
> 1 votes

---
Tags: datetime
---


title: Twig template breaks when adding blocks

text:
# Question
Title: Twig template breaks when adding blocks
Here's the issue:

I have a custom content type for the contact page. Twig template: `page--node--9.html.twig`. When I add blocks to this template, e.g. `{{ page.contact-first }}`, it breaks. How can I display blocks on it?

# Answer
> 0 votes
The solution was simple: the naming of the regions need to use underscores, not dashes.

In `theme.info.yml`

```
regions:
  contact_first: 'Contact (First column)'

```

In the twig template:

```
{{ page.contact_first }}

```

---
Tags: theming, 8, blocks
---


# Question
Title: How to remove a specific term page link?
I have taxonomy term list page..

* Apple
* Banana
* Sweets
* Cake

These are the terms listed with links to default term page.

suppose I want to remove the link for Apple only but listed how do I go about it?

I have tried this

```
  function mytheme_node_view($node, $view_mode, $langcode) {
    if (isset($node->content['field_fruit_name'])) {
      foreach ($node->content['field_fruit_name']['#items'] as $delta => $item) {
         if (count(taxonomy_select_nodes($item['taxonomy_term']->tid)) < 2) {
           $title = $node->content['field_fruit_name'][$delta]['#title'];
           $node->content['field_fruit_name'][$delta] = array();
           $node->content['field_fruit_name'][$delta]['#markup'] = $title;
         }
      }
    }
  }

```

its not working... so if i can remove the link for each term individually it would be great.

# Answer
> 2 votes
Little bit tricky but you can achieve without code.

1. Add a new boolean field to taxonomy term.(eg: show link(field name))

Save for each term show link value either true or false. Depend you wants to show the link or hide the link for that term.

2. Add three fields like shown in the image in your views.

3. Taxonomy term: Name \[hidden\] -- **Exclude from display** and deselect link to taxonomy term

4. Taxonomy term: Term ID \[hidden\] -- **Exclude from display**

5. Taxonomy term: show link

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


# Question
Title: Send mail with attachment using the MIME Mail module
I am not able to send mails with an attachement using the MIME Mail module.
There isn't munch documentation about this module, but some people claim they have successfully used the module, and sent a mail with an attachment.

I've enabled and successfully configured:

I think I configured the modules correctly.

No mail with attachement is delivered. I call `drupal_mail()` in a cron job with the following code.

```
drupal_mail('mymodule', 'notice', $user_email, $lang, $params, $admin_email);

```

It should invoke any `hook_mail()` implementations, which it does, but without the attachment.

```
function mymodule_mail($key, &$message, $params) {
  $data['user'] = $params['from'];
  $account = $data['user']->name;

  $file_content = file_get_contents('some/file/path');

  $attachments = array(
     'filecontent' => $file_content,
     'filename' => 'example-' . $account,
     'filemime' => 'application/pdf',
   );

  switch($key) {
    case 'notice':

      $langcode = $message['language']->language;
      $message['subject'] = 'example submission from '. $account;
      $message['body'][] =
        '<p>'. $account .' has submitted an example.</p>';
      $message['params']['attachments'][] = $attachments;
      break;
  }
}

```

# Answer
The solution I've found is to use hook\_mail\_alter to attach the file to the email after it's generated and before it's sent. The key to that is making an array of details about your attachment and adding that to $message\['params'\]\['attachments'\].

hook\_mail will send mail, but if you're using another program to send (Swift Mailer or PET), then I believe you'll need hook\_mail\_alter to alter the mail instead of sending it yourself.

I also suggest using the Form API (also this) to keep track of your file. That's not required, however, just provide the necessary info.

```
function myhook_mail_alter(&$message) {

  print "message id: {$message['id']}\n";

  // if this email is one of the ones I want to alter:
  if (!empty($message['id']) && (preg_match('/^message-id-set-by-formmail[\d]{1,2}/', $message['id']))) {

    // $message['params']['body'] is a single string, not an array
    $result = preg_match('/\[my dumb string with node id# (\d+)]/', $message['params']['body'], $matches);

    print "Message body: \n {$message['params']['body']} \n\n Matches:\n";
    print_r($matches);

    if (!empty($matches[1])) {
      $file_id = $matches[1];
      $my_pdf = file_load($file_id);
      $original_attachments = $message['params']['attachments'];
      // $original_attachments is an array of associative arrays, each bearing details about an attachment.
      // Add an associative array about this desired attachment.
      $my_attachment = array(
        'filecontent' => file_get_contents($my_pdf->uri),
        'filemime' => $my_pdf->filemime,
        'filename' => $my_pdf->filename,
        'filepath' => NULL,
      );
      $message['params']['attachments'][] = $my_attachment;
    }

  }
}

```
> 4 votes

# Answer
My working Drupal 7 solution with module MimeMail without invoking hook\_mail():

```
// Load attachment.
$file = file_load($fid);

$to = 'something@email.com';
$from = 'something@email.com';
$subject = 'Invoice ' . $file->filename;

$module = 'mimemail';
$token = time();

$message = array(
  'id' => $module . '_' . $token,
  'to' => $to,
  'subject' => $subject,
  'body' => array('something text...'),
  'headers' => array(
    'From' => $from,
    'Sender' => $from,
    'Return-Path' => $from,
    'MIME-Version' => '1.0',
    'Content-Type' => 'text/html; charset=UTF-8',
  ),
  'params' => array(
    'attachments' => array(
      0 => array(
        'path' => file_stream_wrapper_get_instance_by_uri($file->uri)->realpath(),
        'filecontent' => file_get_contents($file->uri),
        'filename' => $file->filename,
        'mime' => $file->filemime,
        'encoding' => 'base64',
        'disposition' => 'attachment',
        'list' => TRUE,
      ),
    ),
  ),
);

$system = drupal_mail_system($module, $token);
$message = $system->format($message);

if ($system->mail($message)) {
  return TRUE;
}
else {
  return FALSE;
}

```
> 3 votes

# Answer
Try this, it should work, good luck!

```
function mymodule_mail($key, &$message, $params) {
  $data['user'] = $params['from'];
  $account = $data['user']->name;

  $file_content = file_get_contents('some/file/path');

  $attachments = array(
     'filecontent' => $file_content,
     'filename' => 'example-' . $account,
     'filemime' => 'application/pdf',
   );

  switch($key) {
    case 'notice':

      $langcode = $message['language']->language;
      $message = drupal_mail($module, $key, $to, $language, $params, $from, $send);
      $message['subject'] = 'example submission from '. $account;
      $message['body'][] =
        '<p>'. $account .' has submitted an example.</p>';
      $message['params']['attachments'][] = $attachments;
    $system = drupal_mail_system($module, $key);
    // Format the message body.
    $message = $system->format($message);
    // Send e-mail.
    $message['result'] = $system->mail($message);

    if($message['result'] == TRUE) {
        drupal_set_message(t('Your message has been sent.'));
    }
    else{
        drupal_set_message(t('There was a problem sending your message and it was not     sent.'), 'error');
    }
      break;
  }
}

```
> 2 votes

# Answer
Swift Mail has a nice documentation on this, check this out. And below I did a small custom function to grab the full uri path of the attachments.

```
/**
 * Send an e-mail.
 */
function test() {

  //load the file by fid
  $file_one = file_load(1);

  //create the file details manually.
  $file = new stdClass();
  $file->uri = file_create_url($file_one->uri);
  $file->filename = $file_one->filename;
  $file->filemime = $file_one->filemime;

  if (!empty($file)) {
    // set parameters
    $params = array(
    'subject' => $subject,
    'body' => $body,
    'to' => $to,
    'cc' => $cc,
    'files' => array($file)
    );
  }
  // Send message
  $message = drupal_mail('singtel_kms', 'send', $to, language_default(),$params);

  // Check the email result array to make sure an email was sent.
  if(!empty($message['result'])) {
     drupal_set_message(t('Your email has been sent.'));
  } else {
     drupal_set_message(t('There was a problem with the application. Please send again or contact administrator.'), 'error');
  }
}

```

In your hook\_mail()

```
/**
 * Implementation of hook_mail().
 */
function modulename_mail($key, &$message, $params) {

  switch($key) {
    default:
        $text[] = t('<strong>Hi</strong>');
        $text[] = t('<p>This is an e-mail.</p>');

        if (isset($message['params']['files'])) {
            $message['params']['files'][] = $params['files'];
        }

        $message['subject'] = t('Test');
        $message['body'] = $text;
        break;
    }

}

```
> 0 votes

---
Tags: 7, emails
---


title: Can I stay on Drupal 7 forever?

text:
# Question
Title: Can I stay on Drupal 7 forever?
I've been using Drupal 8 for a while now and while it's not bad, it does slow down development a bit, as the whole framework is more strict. Which is a good thing to some, but I know of many people like me, who prefer having the freedom of easily creating modules, versus having to set up the new folder structure etc.

So my question is, can one survive without upgrading for the foreseeable future? And what is the longest time one can realistically go without upgrading?

# Answer
IF the current version of Drupal is working out for you and you don't need more features added than you can stick around on 7 for a long time.

The problem is that D7 will not receive any feature updates and most modules will not be updated for D7 aswell.

It is hard to say the exact date of when D7 will not be supported anymore but most likely in 3-4 years.

but the bug/security fixes will continue till the end of this year most likely.

source: https://www.ostraining.com/blog/drupal/drupal-7-end-of-life/
> 2 votes

---
Tags: 7
---


# Question
Title: Why does my Rules Action about booking a time slot appear to not be executed?
I recently installed the Booking time slot module and got it to work as expected.

The issue I have is that its "Rules event" does not trigger a Rules Action. Here is my rule (for now it only includes a Rules Action to show a Drupal message):

```
{ "rules_booking" : {
"LABEL" : "Booking",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "entity" ],
"ON" : { "booking_insert" : [] },
"DO" : [ { "drupal_message" : { "message" : "Success!" } } ] } }

```

I have tried using various events (After saving a new booking, After updating an existing booking) but none appears to work.

I wondering if anyone has had this kind of experience or knows what could be wrong.

### Update

Here is a screenshot of the Rules Events I can select:

# Answer
> 0 votes
I'm about sure that the answer to your question can be found here. And to be 100%, I recommend you do some Rules **debugging**, as explained in the answer to "How can I display the value of a variable inside a condition?".

### Update

Your (1st) comment confirms what I wrote in my answer even more. Have a look at the source code and let me know where I can find more details about any of those "Various events" that you try to use are actually coded. I trust they are somewhere (since your question says you use them), but with my limited knowledge of Rules (hm, hm) I cannot find them ... in the typical ".inc\* file where the Rules module expect them to be located. But since "I" cannot find them, it may well be that that also explains why the Rules module cannot find them ...

---
Tags: 7, rules, bookings
---


# Question
Title: What may cause Undefined index in drupal_retrieve_form when uploading an image?
I have a developed custom plugin in my Drupal 7.54 site for panels where user can upload image. It works locally, however when I trigger same functionality on production nothing happens and I see in logs following errors.

```
Notice: Undefined index: hero_block_search_box_edit_form in drupal_retrieve_form() (line 807 of /Users/dpa/Sites/e1/includes/form.inc).
Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'hero_block_search_box_edit_form' not found or invalid function name in drupal_retrieve_form() (line 842 of
/Users/dpa/Sites/e1/includes/form.inc).
Notice: Undefined index: content in file_ajax_upload() (line 271 of /Users/dpa/Sites/e1/modules/file/file.module).
Notice: Undefined index: #suffix in file_ajax_upload() (line 280 of /Users/dpa/Sites/econ-websites/econ1/modules/file/file.module).
Notice: Undefined index: #prefix in file_ajax_upload() (line 283 of /Users/dpa/Sites/econ-websites/econ1/modules/file/file.module).

```

I read about similar issues in google any many people say it could be related to permissions (and it has sense, since locally everything works but not on production side).

Would anybody give me a hint where to look?

# Answer
You need to either move `hero_block_search_box_edit_form()` from `hero_block_search_box.inc` to your `.module` file, or at the top of your form definition (or `hook_form_alter()` if that's what you are using), you need to add the following:

```
form_load_include($form_state, 'inc', MODULENAME, 'hero_block_search_box');

```

where `MODULENAME` is the module key (machine name) of your module. Make sure you don't include the `.inc` in the last parameter - I didn't forget it, I left it out on purpose.
> 3 votes

---
Tags: panels, media
---


# Question
Title: How to change form submit button value after form submission?
I want to change the value of the submit button after the the form is submitted successfully without any validation errors.

And then when the page is reloaded the button's value will be changed to its original value?

I think its not possible with any javascript or jquery but I can't find a value in the `$form_state` array to set a js variable.

**Edit:** The form is submitted without ajax. The button should be replaced with that text after the form is submitted. And then when the user comes back to page again or reload it again then the text should be reverted.

# Answer
You can do this with two steps. The first is to check whether `$form_state['values']` has been set, and change the value accordingly:

```
if(!isset($form_state['values'])) {
  $form['submit'] = array (
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
}
else {
  $form['submit'] = array (
    '#type' => 'submit',
    '#value' => t('Submit Again'),
  );
}

```

The next step is in your submit function, where you have to tell Drupal to rebuild the form (rather than build it from scratch)

```
$form_state['rebuild'] = TRUE;

```
> 2 votes

---
Tags: 7, forms
---


title: How to set the price without decimals?

text:
# Question
Title: How to set the price without decimals?
in my store, I want to set the products price without decimals, e.g. "$500.00" ==\> "$500" I put following codes in the template.php:

```
function roomify_travel_commerce_currency_info_alter(&$currencies){
  $currencies['TWD']['format_callback'] = 'roomify_travel_commerce_currency_format';
}

function roomify_travel_commerce_currency_format($amount, $currency, $object = NULL, $convert = TRUE) {
  $price = number_format(commerce_currency_round(abs($amount), $currency), 0, $currency['decimal_separator'], $currency['thousands_separator']);

  $replacements = array(
    '@code_before' => $currency['code_placement'] == 'before' ? $currency['code'] : '',
    '@symbol_before' => $currency['symbol_placement'] == 'before' ? $currency['symbol'] : '',
    '@price' => $price,
    '@symbol_after' => $currency['symbol_placement'] == 'after' ? $currency['symbol'] : '',
    '@code_after' => $currency['code_placement'] == 'after' ? $currency['code'] : '',
    '@negative' => $amount < 0 ? '-' : '',
    '@symbol_spacer' => $currency['symbol_spacer'],
    '@code_spacer' => $currency['code_spacer'],
  );

    return trim(t('@code_before@code_spacer@negative@symbol_before@price@symbol_spacer@symbol_after@code_spacer@code_after', $replacements));
}

```

then the price became correct, but my admin page was broke! and apache error log showed:

```
[Thu Feb 09 07:20:41.168665 2017] [proxy_fcgi:error] [pid 25564:tid 139845024192256] [client **.**.**.**:40368] AH01071: Got error 'PHP message: PHP Fatal error:  Call to undefined function mytheme_currency_format() in /opt/bitnami/apps/drupal/htdocs/profiles/roomify/modules/contrib/commerce/commerce.module on line 641\n', referer: http://**.**.**.**/drupal/?q=admin

```

please tell me where I went wrong! thank you!!

# Answer
> 2 votes
Your callback function is in your theme's template.php file, which is only loaded when that theme is being used.

I'm assuming your admin backend uses a different theme, so it can't find your callback function on admin pages.

The best solution would be to move the logic into a custom module; it's not theme related functionality so best practice would be to move it there anyway, even if it wasn't causing a problem.

---
Tags: commerce
---


title: node_mass_update will not update field

text:
# Question
Title: node_mass_update will not update field
Cannot get `node_mass_update();` to update Votes field. `$node_ids` is an array of node ids and `$votes` is a number.

```
    $updates = array('field_votes' => $votes);

    node_mass_update($node_ids,$updates);

```

My module fires and it tells me that nodes are being updated and gives me a progress bar, but the fields in the nodes are not updated.

# Answer
> 1 votes
I've never used (or even seen) that function before, but following the trail down to `_node_mass_update_helper()`, I think you need to use a format like this:

```
$updates = array('field_votes' => array(0 => array('value' => $votes)));

```

That array format is the standard way to update CCK fields in Drupal 6, and since the helper function does this:

```
foreach ($updates as $name => $value) {
  $node->$name = $value;
}

```

immediately before calling `node_save()`, I think that's what the problem is.

# Answer
> 0 votes
I've never used (or even seen) that function before, but following the trail down to `_node_mass_update_helper()`, I think you need to use a format like this:

```
$updates = array('field_votes' => array(0 => array('value' => $votes)));

```

That array format is the standard way to update CCK fields in Drupal 6, and since the helper function does this:

---
Tags: nodes
---


# Question
Title: D7 how to check does the uploaded photo have EXIF data?
I'm using Drupal 7 with module EXIF. I want to check if uploaded photo have EXIF data if not then don't allow the user to add this content.

# Answer
> 1 votes
If you want to check a file that is being added through a file field on a content type you can use hook\_node\_presave. Unless you need the exif module for other reasons you can do without this module and just use the exif\_read\_data function. Make sure to enable to the exif extension in php.

```
function mymodule_node_presave($node) {
  if ($node->type == 'article') {
    // Still needs some checking here to see if a file is provided
    $fid = $node->field_file['und'][0]['fid'];
    $file = file_load($fid);
    $hasExif = exif_read_data($file->uri, 0, true);
  }
}

```

---
Tags: 7, media
---


# Question
Title: Why am I unable to send an email order using the Ubercart and Smtp Authentification module?
After Ubercart checkout submitting order, I get this error:

> Unable to send email. Contact the site administrator if the problem persists.

I am using the SMTP Authentication Support module, I configured it correctly. Test mails work. So the error lies probably within Ubercart.

On Drupal `/admin/reports/dblog`, I get this interesting error log:

> Error on sending e-mail (from admin@xxxxx.com to admin@xxxxx.com.com).

**it tries to send the mail to the sender mail? Very weird!**

How to get this resolved?

# Answer
> 1 votes
Okay I found the solution using the instructions at "Drupal – Ubercart and SMTP Authentication Support".

1. I installed Mail System module.
2. In the Mail System configuration, I updated the Cart module class, Order module class and Store module class so that they all use the SmtpMailSystem rather than UbercartMailSystem, as shown in the screenprint below:

---
Tags: emails, ubercart
---


# Question
Title: How to make full text search case Insensitive
I'm using Search api (8.x-1.0-beta3) and Database Search (8.x-1.0-beta3). I have created DBIndex Server and created index for content type 'Test' and then created search index view with filter 'Full text search'. But I observed search is case sensitive. How to make this search as case insensitive.

Thank you in advance.

# Answer
> 5 votes
Please follow the below steps:

1. Click on Configuration \> Search and metadata \> Search API
2. Click on Index and go to Processors format . Enable the checkbox Ignore case Makes searches case-insensitive.
3. Clear the index and reindex the items

---
Tags: views, 8, search
---


# Question
Title: Create link (url) to the full node from a Solr view (search results) with rewrite results
In `admin/config/search/search-api/index/default_index/fields` I added URI field.

But how can I create a link to the full content? In the view, when I click on *Add fields* I am able to select: `URI (indexed field) Index Default index A URI where the item can be accessed`

But in the field settings, when I select:

```
Link this field to its item
Display this field as a link to its original entity or item.

```

It doesn't become a link? How do I create a link to the full content in a Solr view?

# Answer
I found the solution by Checking Retrieve result data from Solr in the solr server configuration (Advanced tab). After checking this box I am able to use {{ url }} in my view.
> 2 votes

---
Tags: 8, uri, navigation, search
---


# Question
Title: How to change an existing theme to a responsive bootstrap theme?
I wonder how to update an existing non-responsive Drupal 7 theme to a responsive bootstrap theme? Any hints for that?

The following steps are required:

* Install bootstrap theme.
* Create a bootstrap subtheme.
* Make sass tools ready to compile scss files.
* Start theming.
* Create a new bootstrap subtheme that looks like the old non-responsive theme.

So how can I create such a new responsive subtheme?

# Answer
If you want to create a responsive site in drupal with bootstrap.then follow steps:

1. Install bootstrap theme.(https://www.drupal.org/project/bootstrap).
2. Copy the bootstrap\_subtheme, Place in theme folder and rename with your subtheme. 3.Copy and include the css and js of the existing site to the bootstrap\_subtheme.
3. See the structure of the existing site and create regions in the new theme according to requirement and apply the css.
4. Check the section one by one and apply the css according.
5. Like this you can easily convert the non-responsive site to responsive.

**Notes**:

* You will be create a regions in the `tpl.php` , this Link will help you.
* In this theming there is no that much different to normal theming . if you install bootstrap then it automatically give you the responsive platform, only one difference you can use the bootstrap class in html structure and also use the bootstrap module. Follow This.
> 2 votes

---
Tags: 7, theming
---


title: Nginx Clean URLs don't work

text:
# Question
Title: Nginx Clean URLs don't work
I tried this: How do I enable clean URLs with Nginx?

And I tried this: https://www.digitalocean.com/community/questions/how-do-i-enable-clean-urls-with-nginx-for-drupal

So, I tried these:

```
 location / {
    index index.php;
    # This is cool because no php is touched for static content
    try_files $uri $uri/ @rewrite;
    expires max;
  }

  location @rewrite {
    # Some modules enforce no slash (/) at the end of the URL
    # Else this rewrite block wouldn't be needed (GlobalRedirect)
    rewrite ^/(.*)$ /index.php?q=$1;
  }

  location ~ \.php$ {
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME /srv/www/www.example.com/public_html$fastcgi_script_name;
    fastcgi_intercept_errors on;
    fastcgi_pass unix:/var/run/php-fpm.sock; # fastcgi_pass unix:/tmp/php5-fpm.sock;
 }

```

And I tried these:

```
server {
     listen       80;
     server_name  example.org;

     location / {
         root   /path/to/drupal;
         index  index.php;
         error_page 404 = @drupal;
     }

     location @drupal {
         rewrite ^(.*)$ /index.php?q=$1 last;
     }
 }

```

And clean URL's don't work. The site runs at ip address in a subdir 127.0.0.1/dev

It has its own config at /etc/nginx/sites-available/dev and symlinked to /etc/nginx/sites-enabled/dev

This is my current `sites-available/default` config:

```
 root /var/www;

 # Add index.php to the list if you are using PHP
 index index.html index.htm index.php;

 server_name _;

 location / {
 # First attempt to serve request as file, then
 # as directory, then fall back to displaying a 404.
 # try_files $uri $uri/ =404;
 try_files $uri $uri/ @rewrite;
 expires max;
 }

 location @rewrite {
   # Some modules enforce no slash (/) at the end of the URL
   # Else this rewrite block wouldn't be needed (GlobalRedirect)
   rewrite ^/(.*)$ /index.php?q=$1;
 }

 # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
 #
 location ~ \.php$ {
 include snippets/fastcgi-php.conf;

 # With php7.0-cgi alone:
 # fastcgi_pass 127.0.0.1:9000;
 # With php7.0-fpm:

 fastcgi_pass unix:/run/php/php7.0-fpm.sock;

 }

 # deny access to .htaccess files, if Apache's document root
 # concurs with nginx's one
 #
 location ~ /\.ht {
  deny all;
 }
}

```

This is my current `sites-available/dev` config:

```
server {

        server_name dev;
        root /var/www/dev; ## <-- Your only path reference.

        # Enable compression, this will help if you have for instance advagg module
        # by serving Gzip versions of the files.
        gzip_static on;

        location = /favicon.ico {
                log_not_found off;
                access_log off;
        }

        location = /robots.txt {
                allow all;
                log_not_found off;
                access_log off;
        }

        # This matters if you use drush prior to 5.x
        # After 5.x backups are stored outside the Drupal install.
        #location = /backup {
        #        deny all;
        #}

        # Very rarely should these ever be accessed outside of your lan
        location ~* \.(txt|log)$ {
                allow 192.168.0.0/16;
                deny all;
        }

        location ~ \..*/.*\.php$ {
                return 403;
        }

        # No no for private
        location ~ ^/sites/.*/private/ {
                return 403;
        }

        # Block access to "hidden" files and directories whose names begin with a
        # period. This includes directories used by version control systems such
        # as Subversion or Git to store control files.
        location ~ (^|/)\. {
                return 403;
        }

  location / {
    index index.php;
    # This is cool because no php is touched for static content
    try_files $uri $uri/ @rewrite;
    expires max;
  }

  location @rewrite {
    # Some modules enforce no slash (/) at the end of the URL
    # Else this rewrite block wouldn't be needed (GlobalRedirect)
    rewrite ^/(.*)$ /index.php?q=$1;
  }

  location ~ \.php$ {
    include fastcgi_params;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_param SCRIPT_FILENAME $request_filename;
    fastcgi_intercept_errors on;
    fastcgi_pass unix:/run/php/php7.0-fpm.sock;
 }

        # Fighting with Styles? This little gem is amazing.
        # This is for D6
        #location ~ ^/sites/.*/files/imagecache/ {
        # This is for D7 and D8
        location ~ ^/sites/.*/files/styles/ {
                try_files $uri @rewrite;
        }

        location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
                expires max;
                log_not_found off;
        }

}

```

I restart nginx server by running `sudo service nginx restart`

# Answer
Your question is about Drupal 7 right ? Try replacing

```
# For Drupal <= 6
location / {
    index index.php;
    try_files $uri $uri/ @rewrite;
    expires max;
  }

```

by

```
# For Drupal >= 7
location / {
    try_files $uri /index.php?$query_string;
}

```

Then reload nginx.

This is a full example working vhost fir Drupal 7 :

```
server {

    listen 1.2.3.4:8000;
    server_name example.com www.example.com
    root /var/www/example.com /web;

    location = /favicon.ico {
        log_not_found off;
        access_log off;
    }

    location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }
    #Drupal private folder (see https://github.com/perusio/drupal-with-nginx#private-file-handling)
    location ^~ /sites/default/protected {
      internal;
    }

    # Very rarely should these ever be accessed outside of your lan
    location ~* \.(txt|log)$ {
        allow 192.168.0.0/16;
        deny all;
    }

    location ~ \..*/.*\.php$ {
        return 403;
    }

    location ~ ^/sites/.*/private/ {
        return 403;
    }

    # Allow "Well-Known URIs" as per RFC 5785
    location ~* ^/.well-known/ {
        allow all;
    }

    # Block access to "hidden" files and directories whose names begin with a
    # period. This includes directories used by version control systems such
    # as Subversion or Git to store control files.
    location ~ (^|/)\. {
        return 403;
    }

    location / {
        try_files $uri /index.php?$query_string;
    }

    location @rewrite {
        rewrite ^/(.*)$ /index.php?q=$1;
    }

    # Don't allow direct access to PHP files in the vendor directory.
    location ~ /vendor/.*\.php$ {
        deny all;
        return 404;
    }

    location ~ '\.php$|^/update.php' {
        fastcgi_split_path_info ^(.+?\.php)(|/.*)$;
        include fastcgi_params;
        # Block httpoxy attacks. See https://httpoxy.org/.
        fastcgi_param HTTP_PROXY "";
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_param QUERY_STRING $query_string;
        fastcgi_intercept_errors on;
        fastcgi_read_timeout 180;
        # PHP 7 socket location (change it to fit your config)
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
    }

    # Fighting with Styles? This little gem is amazing.
    location ~ ^/sites/.*/files/styles/ {
        try_files $uri @rewrite;
    }

    # Handle private files through Drupal. Private file's path can come
    # with a language prefix.
    location ~ ^(/[a-z\-]+)?/system/files/ {
        try_files $uri /index.php?$query_string;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
        expires max;
        log_not_found off;
    }
}

```
> 1 votes

---
Tags: 7, uri
---