title: Check if user is flagged in rules

text:
# Question
Title: Check if user is flagged in rules
I want to make a rule that check if the user of the currently **viewed** profile, have flagged the currently **viewing** users profile.

So basicly, have viewing user been flagged by the profile owner of the viewed profile.

So lets say this rule returns true, then there will be a text box when user is viewing profile "This user have flagged you!!".

I have tried all sorts of things in the Data selector of "User who to check" (the field in the buttom of image.

# Answer
> 0 votes
You can create a Rule with the event "User account page is viewed". Then, you can add the required condition as follows:

So you select the current user as the user that should be Flagged and select the visited user as the person that should have done the Flagging.

---
Tags: rules, flags
---


# Question
Title: How to improve the speed of drupal website
I have tested my site with testmysite.thinkwithgoogle.com. I got the below report. Speed test score for mobile site and desktop site are not good. If you could help me pointing to right direction to fix this errors and bring the score higher, it would help me a lot. Resources they provided are in general. I am looking more drupal specific resources.

**MOBILE FRIENDLINESS** 98/100 GOOD
**MOBILE SPEED** 57/100 POOR
**DESKTOP SPEED** 52/100 POOR

Update New result:

---

# Answer
> 2 votes
First of all, I would recommend you a very popular module: https://www.drupal.org/project/advagg . This is better than the standard aggregation in Drupal, you need to configure it a bit after you install it.

For the images, you can you something like this: https://www.drupal.org/project/imageapi\_optimize . This will optimize your images and should help you pass that.

---
Tags: performance
---


# Question
Title: How can I users to register with their email only?
I need to force users to register with just their email. I cannot use the Email Registration module, which still sets the username basing on the user name part of the email; in case of conflicts with existing usernames, a number is added.

I have a number of subdomains where I am using the Bakery module; I need to be sure there isn't any conflicting account. The *Email registration* module will just create a tokenized username with appended unique IDs, creating conflicting accounts.

I imagine that, by forcing email addresses, I can bypass most of this as an issue. How can I completely eliminate the username field and just use the email field?

# Answer
> 4 votes
Use hook\_form\_alter to hide the username field

```
/**
 * Implementation of hook_form_alter.
 */
function mymodule_form_alter(&$form, &$form_state, $form_id){
  if($form['#form_id'] === 'user_register_form'){
    unset($form['account']['name']);
  }
}

```

Then you can use hook\_user\_presave to set the username using the convention you want (the md5 hash of the email is a good candidate):

```
/**
 * Implementation of hook_user_presave.
 */
function mymodule_user_presave(&$edit, $account, $category){
  $edit['name'] = md5($edit['mail']);
}

```

# Answer
> 1 votes
You could still use Email Registration and just implement a custom hook

```
function modulename_email_registration_name($edit, $account) {
 return $edit['mail'];
}

```

# Answer
> 1 votes
A simpler way is to create a new Rule in "Configuration site". You can set an event after creating a new user and then set an action as: user name set to value user email.

# Answer
> 0 votes
There is not usual way to force Drupal to only use email and not consider username field, there are some Way to achieve this job with hacking core of Drupal But Strongly NOT Recommended, So the ways remain is filling username field ( as other guys answered) with somethings, there are several ways to fill user name field,

Using Email\_registration module with custom hook

```
function modulename_email_registration_name($edit, $account) {
 return $edit['mail'];
  // OR
  // return "YOUR_DESIRE_STRING-".$edit['uid'];
}

```

---
Tags: 7, authentication-authorization
---


# Question
Title: How to have multiple users in a user reference field
I'm using Drupal 8.

Can I have multiple users by comma separating each users? When I was doing by this way, after I input a comma, I can choose another user again. But after I submit it. Only the last user I have chose that had been saved (only 1 value).

If I set the field as "Allowed number of values to Unlimit or a number". There will be many user reference text box. I only want one user reference text box and have multiple users with comma separating. How to do it?

# Answer
Yes, you can do that. You need to select "Autocomplete (Tags style)" as the widget you use in the Form display.

After you have done that, you can use commas to add multiple users in the same widget (provided you have set cardinality to \> 1).
> 5 votes

---
Tags: 8
---


# Question
Title: The installation directory "/root" is not writable - Error when install Drush
i want to install drush on my server .

I want to install drush-toolbox project globaly on my linux server box so all users can use it

My server: Cpanel , Litespeed , Cagefs , Cloudlinux (centos 6)

my drupal version 7.5x

I try this article CLick here and after run this command:

```
curl -sS https://getcomposer.org/installer | php

```

I get this error : **The installation directory "/root" is not writable**

I run this command : `chmod 640 /root` and `chmod 644 /root` but give same error (not writable)

Please help me.Is any guidance for me?

# Answer
> 1 votes
The composer method for installing drush works, but is outdated. Use the drush documentation for the right instructions: http://docs.drush.org/en/master/install/

```
# Download latest stable release using the code below or browse to github.com/drush-ops/drush/releases.
php -r "readfile('https://s3.amazonaws.com/files.drush.org/drush.phar');" > drush
# Or use our upcoming release: php -r "readfile('https://s3.amazonaws.com/files.drush.org/drush-unstable.phar');" > drush

# Test your install.
php drush core-status

# Make `drush` executable as a command from anywhere. Destination can be anywhere on $PATH.
chmod +x drush
sudo mv drush /usr/local/bin

# Optional. Enrich the bash startup file with completion and aliases.
drush init

```

---
Tags: drush, ssh
---


title: Access POST values

text:
# Question
Title: Access POST values
I want to know how i can access my submitted POST values from a form into a controller class. Do I need to access the `$form_state` variable or the request?

I am using the following code.

```
<?php

namespace Drupal\ps_response\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\ps_response\Services\DefaultService;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Class FilterForm.
 *
 * @package Drupal\ps_response\Form
 */
class FilterForm extends FormBase {

  private $indexGenerator;

  public function __construct(DefaultService $indexGenerator) {
    $this->indexGenerator = $indexGenerator;
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('ps_response.default')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'filter_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['survey_id'] = array(
      '#type' => 'select',
      '#title' => t('Survey'),
      '#required' => FALSE,
      '#options' => $this->indexGenerator->selectAllSurveys(),
      "#empty_option" => 'Selecteer Vragenlijst'
    );

    $form['question_id'] = array(
      '#type' => 'select',
      '#title' => t('Question'),
      '#required' => FALSE,
      '#options' => $this->indexGenerator->selectAllQuestions(),
      "#empty_option" => 'Selecteer Vraag in vragenlijst'
    );

    $form['pole_id'] = array(
      '#type' => 'select',
      '#title' => t('Pole'),
      '#required' => FALSE,
      '#options' => $this->indexGenerator->selectAllPoles(),
      "#empty_option" => 'Selecteer paal'
    );

    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Submit'),
    );

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    drupal_set_message(t('Zoekopdracht voltooid.'));
    // Do i need to return values here?
  }

}

```

My routing file :

```
ps_response.index_controller_index:
  path: '/ps_response/admin/dashboard'
  defaults:
    _controller: '\Drupal\ps_response\Controller\indexController::index'
    _title: 'Dashboard'
  requirements:
    _permission: 'access content'

ps_response.dummy_responses_dummy_responses:
  path: '/admin/content/polestarr/response/dummy-responses'
  defaults:
    _controller: '\Drupal\ps_response\Controller\DummyResponses::dummyResponses'
    _title: 'Dummy responses'
  requirements:
    _permission: 'access content'

ps_response.import_response_csv_files_import_response_csv_files:
  path: '/admin/content/polestarr/response/import-response-csv-files'
  defaults:
    _controller: '\Drupal\ps_response\Controller\ImportResponseCsvFiles::importResponseCsvFiles'
    _title: 'Import response CSV files'
  requirements:
    _permission: 'access content'

ps_response.index_controller_index_questions:
  path: '/ps_response/admin/dashboard/questions/request'
  defaults:
    _controller: '\Drupal\ps_response\Controller\indexController::selectQuestionsBySurvey'
  requirements:
    _permission: 'access content'

ps_response.filter.form:
  path: '/ps_response/Controller/indexController::index'
  defaults:
    _form: '\Drupal\ps_response\Form\FilterForm'
    _title: 'Conribute page'
  requirements:
    _permission: 'access content'

```

And this is my funciton inside of my controller :

```
public function index(Request $request) {
    $form = \Drupal::formBuilder()
      ->getForm('Drupal\ps_response\Form\FilterForm');

    $questionsByName = $this->indexGenerator->selectAllQuestions();
    $polesByName = $this->indexGenerator->selectAllPoles();
    $surveysByName = $this->indexGenerator->selectAllSurveys();
    $form_state = new FormState();
    $form_state->setRebuild();
    $form_state->getFormObject();

    /*
     * HOW DO I GET MY POST VALUES OVER HERE????????
     */

    if (!empty($_POST)) {
      $aList = $this->indexGenerator->selectResponses();

      $rating_totals = [];
      foreach ($aList as $row) {
        $rating = $row->option_value;
        $question_id = $row->question_id;
        if (!isset($rating_totals[$question_id])) {
          $rating_totals[$question_id] = [
            1 => 0,
            2 => 0,
            3 => 0,
            4 => 0,
            5 => 0,
            6 => $row->field_question_value
          ];
        }
        if (!isset($rating_totals[$question_id][$rating])) {
          $rating_totals[$question_id][$rating] = 0;
        }
        $rating_totals[$question_id][$rating]++;
      }

      return array(
        '#theme' => 'index',
        '#result' => $aList,
        '#ratings' => $rating_totals,
        '#request' => $_POST,
        '#questions' => $questionsByName,
        '#poles' => $polesByName,
        '#surveys' => $surveysByName,
      );
    }
    else {
      return array(
        '#theme' => 'index',
        '#questions' => $questionsByName,
        '#poles' => $polesByName,
        '#surveys' => $surveysByName,
        '#form' => $form
      );
    }
  }

```

# Answer
If you redirect to a controller this is a new request. But then the user input from the last request is lost. You have to do something useful with the user input while you are in submit, for example store the data in the database or some kind of temporary storage like a session. Then the controller can access the data from there.

Btw. the `drupal_set_message()` you have in submit uses a session to store the message for the next request.

If you don't want to store the data and only want to display a result, it might be a better solution to rebuild the form and do this in form build.
> 2 votes

---
Tags: 8, forms
---


# Question
Title: In a Rule, how can I prevent executing subsequent actions if the first action fails?
In a Rule, how can I prevent executing subsequent actions if the first action fails?

In my case, I want the order to be marked as Processing only if the order was successfully transmitted to the fulfilment center. I've tried returning FALSE from the action but this has no effect.

# Answer
> 2 votes
To provide conditional logic, you need the Rules Conditional module.

There's an open issue to document this further, and there's another meta issue which looks at integrating the conditional logic into the Rules module itself.

> This module provides Rules plugins for conditionally altering execution flow directly inside a group of actions. Provided plugins include:

```
Conditional
    If/(Else) If
    Else
Switch
    Case
    Default case
While

```

# Answer
> 0 votes
The answer to your question, may depend on what exactly you mean by the "***if first action fails***".

Have a look at the issue `"After updating existing content" runs before content is saved`, about an event which is a variation of your event here, and somehow explains that "after saving something" actually happens ... "before saving something" (which IMO is not a bug, simply how the Rules module works ...). That's probably not the reason why in your case the first Rules Action failed, but an even tougher scenario to get to work (in which even Conditional Rules cannot help you).

A possible compromise to avoid these kind of issues, is to transform what you're trying to do in your **Subsequent Rules Action** (for which you want to prevent its execution) in a Rules Component, so that after your **First Rules Action** you "schedule the execution" (using the Rules Scheduler submodule) of that Rules Component. For example after only a few seconds or minutes later on (if your cron job runs frequent enough, otherwise it'll be next time cron runs).

This approach will allow that, at the time the Rules Component is executed, you can try to add any relevant Rules Conditions in that Rules Component also. I.e to validate if the result of your First Rules Action is what you wanted/expected it to be. In certain scenarios (where you know something went wrong), you might even implement additional Rules logic to just delete the scheduled Rules Component so that it even doesn't actually get scheduled.

BTW, there are also scenarios where it is sufficient to just execute the Rules Component (containing the equivalent of your "subsequent Rules Action"), instead of using the Rules Scheduler to schedule its execution. In this case you can add similar Rules Conditions in that Rules Component also to validate the results of your First Rules Action.

---
Tags: rules
---


# Question
Title: Views hook query alter, change the DatabaseCondition Object
I am trying to alter views filters with hook\_views\_query\_alter like

```
function custom_views_query_alter(&$view, &$query) {
     foreach($query->where[1]['conditions'] as $idx => $condition) {
      dpr($condition);
     }
}

```

And below is the output I get from DPR function

```
Array
(
    [field] => node.status
    [value] => 1
    [operator] => =
)
Array
(
    [field] => node.type
    [value] => Array
        (
            [0] => pricing
        )

    [operator] => in
)
Array
(
    [field] => DatabaseCondition Object
        (
            [conditions:protected] => Array
                (
                    [#conjunction] => AND
                    [0] => Array
                        (
                            [field] => field_data_field_zip_range.field_zip_range_from
                            [value] => 65000
                            [operator] => <=
                        )

                    [1] => Array
                        (
                            [field] => field_data_field_zip_range.field_zip_range_to
                            [value] => 65000
                            [operator] => >=
                        )

                )

            [arguments:protected] => Array
                (
                )

            [changed:protected] => 1
            [queryPlaceholderIdentifier:protected] =>
        )

    [value] =>
    [operator] =>
)

```

So the first 2 filters are not a problem, you just edit the field and you set new values. Problem is the DatabaseCondition Object with this conditions:protected part. I just don't have a clue how to change values there.

There was similar questions here How to change the query value using hook\_views\_query\_alter? but it was not solved. It only solves problems for first 2 filters and doesn't do anything for DatabaseCondition Object.

# Answer
> 1 votes
The conditions may be altered by getting them by reference:

```
function custom_views_query_alter(&$view, &$query) {
   $conditions = &$query->conditions();
   foreach($conditions as $idx => $condition) {
     if ($condition['field'] == 'node.type') {
       $conditions[$idx]['value'] = array("Some other type");
     }
   }
}

```

Don't forget to modify the object/arrays by reference with the `&` character.

# Answer
> 0 votes
solutions above didn't work for me since $query-\>conditions() results in php error.

but here's how how i solved something similar:

i have a view which has a list/text filter (multivalue) which has default values. it is not exposed, but i change the values dynamically, depending on few $\_GET values...

solution:

in hook\_views\_query\_alter, $query-\>where\[1\]\['conditions'\]\[5\]\['field'\] is a DatabaseCondition object--which i didn't manage to update, but i did override it's default value(s).

```
DatabaseCondition Object
(
[conditions:protected] => Array
    (
        [#conjunction] => OR
        [0] => Array
            (
                [field] => field_data_field_category_value_0.field_category_value
                [value] => apartment
                [operator] => =
            )
    )

[arguments:protected] => Array
    (
    )

[changed:protected] => 1
[queryPlaceholderIdentifier:protected] =>
)

```

what i did was to create a new DatabaseCondition and replace the old one:

```
<?php

// create db or
$db_or = db_or();
// add new condition
$db_or->condition('field_data_field_category_value_0.field_category_value', 'office', '=');
// assign new value
$query->where[1]['conditions'][5]['field'] = $db_or;
?>

```

also, you need to update $query-\>table\_queue in order to match the new conditions. in my case:

```
<?php

$query->table_queue['field_data_field_category_value_0']['join']->extra[0]['value'] = 'office';

?>

```

of course, table alias, field name, and index (0 in my example) should match your settings...

---
Tags: views
---


# Question
Title: Excluding empty(Null) fields when using EntityFieldQuery query condition
Is it possible to select all of the entities who's xyz field is empty?

I tried soemthing like this:

```
->fieldCondition('field_name', 'value', NULL, 'IS NOT NULL');

```

However, this doesn't seem to work.

Any ideas?

# Answer
If you look on the fieldCondition documentation page you will see the following warning:

> Note that entities with empty field values will be excluded from the EntityFieldQuery results when using this method.

Checking whether a field exists or not has been added to entityFieldQuery in Drupal 8, but unfortunately won't be backported to Drupal 7.

There are various methods to achieve this:

1. Using a tag and hook\_query\_TAG\_alter as mentioned by @Clive, see comment 4 on the Drupal issue for an example ;
2. First query all non NULL entries, then query all entries excluding the previous ones, as described in @seddonym's answer and in comment 5 on the Drupal issue ;
3. You can write your query using SelectQuery rathen than EntityfieldQuery as such:

_

```
$q = db_select('node', 'n');
$q->fields('n', array('type'))
  ->condition('n.type', 'my_node_type', '=')
  ->addJoin('LEFT', 'field_data_field_my_field', 'f', 'f.entity_id = n.nid');
$q->isNull('f.value');
$r = $q->execute();

```
> 20 votes

# Answer
You can use `!= NULL`, but you can't use `= NULL` for some reason.

This is my workaround.

```
  //Get all the entities that DO have values
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'MY_TYPE')
    ->fieldCondition('field_MY_FIELD', 'value', 'NULL', '!=');
  $result = $query->execute();

  if (is_array(@$result['registration'])) {
    //Now get all the other entities, that aren't in the list you just retrieved
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'MY_TYPE')
      ->entityCondition('entity_id', array_keys($result['MY_TYPE']), 'NOT IN');
    $result_two = $query->execute();
  }

```
> 15 votes

# Answer
The short answer is that directly, no you can't (see EntityFieldQuery does not support isNull or isNotNull). If I remember rightly this is a side-effect of the fact that `EntityFieldQuery` uses only `INNER JOIN`s to join tables.

There is a workaround, though, which involves using `hook_query_TAG_alter()` and adding a tag to your `EntityFieldQuery`, there's an example in the last comment on the page I linked to above.
> 10 votes

# Answer
According to the documentation you can use null and isnull; it just has a specific way to write it.

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('status', 1)
  ->fieldCondition('field_news_types', 'value', 'spotlight', '=')
  ->fieldCondition('field_photo', 'fid', 'NULL', '!=')
  ->fieldCondition('field_faculty_tag', 'tid', $value)
  ->fieldCondition('field_news_publishdate', 'value', $year. '%', 'like')
  ->range(0, 10)
  ->addMetaData('account', user_load(1)); // run the query as user 1

$result = $query->execute();

if (isset($result['node'])) {
  $news_items_nids = array_keys($result['node']);
  $news_items = entity_load('node', $news_items_nids);
}

```
> 10 votes

# Answer
In Drupal 7 please check the following workaround proposed here:

> Register the tag to alter the query instance:

```
<?php
/**
 * Implements hook_query_TAG_alter()
 */
function MYMODULE_query_node_is_not_tagged_alter(QueryAlterableInterface $query) {
  $query->leftJoin('field_data_field_tags', 'o', 'node.nid = o.entity_id AND o.entity_type = :entity_type');
  $query->isNull('o.field_tags_tid');
}
?>

```

> Obs.: This query tag alter only works for the "node" entity type. Don't confuse "field\_tags" related to the "Tags" vocabulary, can be any other like "Categories".
>
> Get all the nodes from that doesn't been tagged yet using EntityFieldQuery, look at the addTag() method:

```
<?php
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'news')
  ->addTag('node_is_not_tagged')
  ->propertyCondition('status', 1);
$result = $query->execute();
?>

```

Other example:

```
  $result = $query
    ->entityCondition('entity_type', 'node')
    ->propertyCondition('type', 'my_content_type')
    ->fieldCondition('field_mine_one', 'value', '', '<>')
    ->fieldCondition('field_mine_two', 'value', '', '<>')
    ->addTag('my_custom_tag')
    ->deleted(FALSE)
    ->propertyOrderBy('changed', 'DESC')
    ->range(0, $my_range_value)
    ->execute();

```

> Then I implemented `hook_query_TAG_alter` leveraging the fact that `my_custom_tag` is only set by me:

```
/**
 * Implements hook_query_TAG_alter()
 */
function MYMODULE_query_TAG_alter(QueryAlterableInterface $query) {
  $query->leftJoin('field_data_field_other', 'o', 'node.nid = o.entity_id');
  $query->isNull('o.field_other_value');
}

```

Another example:

```
<?php
  //Get all the entities that DO have values
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'MY_TYPE')
    ->fieldCondition('field_MY_FIELD', 'value', 'NULL', '!=');
  $result = $query->execute();

  if (is_array(@$result['registration'])) {
    //Now get all the other entities, that aren't in the list you just retrieved
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'MY_TYPE')
      ->entityCondition('entity_id', array_keys($result['MY_TYPE']), 'NOT IN');
    $result_two = $query->execute();
  }
?>

```

---

More complete example below which loads bunch of nodes on cron task which empty taxonomy term references and apply some changes:

```
/**
 * Implements hook_cron().
 */
function MYMODULE_cron() {
  $query = new EntityFieldQuery();
  $query
    ->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'property')
    ->propertyOrderBy('changed', 'DESC')
    ->addTag('type_is_null')
    ->range(0,50); // Maximum of 50.
  $result = $query->execute();

  if (!empty($result['node'])) {
    $nids = array_keys($result['node']);
    $nodes = node_load_multiple($nids);

    foreach ($nodes as $node) {
      // do_some_stuff($node);
    }
  }
}

/**
 * Implements hook_query_TAG_alter()
 */
function MYMODULE_query_type_is_null_alter(QueryAlterableInterface $query) {
  $query->leftJoin('field_data_field_foo', 'f', 'node.nid = f.entity_id AND f.entity_type = :entity_type');
  $query->isNull('f.field_foo_tid'); // Check name by SQL: DESC field_data_field_foo

  $query->leftJoin('field_data_field_bar', 'b', 'node.nid = b.entity_id AND b.entity_type = :entity_type');
  $query->isNull('b.field_bar_tid'); // Check name by SQL: DESC field_data_field_bar
}

```
> 6 votes

# Answer
You need to wrap Null in quotes.

```
->fieldCondition('field_name', 'value', 'NULL', '!=');

```
> 3 votes

# Answer
Please correct me if I'm wrong. It seems that it simply needs to be

`$query->fieldCondition('field_name');`

to exclude all nodes with an empty `field_name` field o\_O

Tested in Drupal `version >= 7.43`.
> 2 votes

---
Tags: 7, database
---


# Question
Title: Show specific submenu and mark specific item as active when front page or specific node type is opened
My front page is basically a view that lists teasers of node type article. How can I show a specific submenu and mark one item in this submenu as active (+ its parent) when

1) the front page is opened or

2) any article is opened?

I know 2) can be done with the module "Context Active Trail" and "Context UI", but I want to do it without a module and I think the module can't do 1) anyway.

# Answer
> 0 votes
So finally I used the Menu Position Module, which works perfectly.

---
Tags: 8, navigation
---


title: Create node using services

text:
# Question
Title: Create node using services
I want to create a mobile application using my drupal application. For the communication I use the module services. The connection system works with success. This return this result.

```
    {
  "sessid": "98gnwpE1GeguxN1y4t0WkWhDzK-C-Ashbn5GExj9l7M",
  "session_name": "SESS7609adb25a00cf561a9d882a31e81d29",
  "token": "aK4L6D1APRH16lGSAirIaZVGR02T5gs8DeE5jffYCKI",
  "user": {
    "uid": "30",
    "name": "admin",
    "mail": "zinalacina@gmail.com",
    "theme": "",
    "signature": "",
    "signature_format": "filtered_html",
    "created": "1486745824",
    "access": "1487091377",
    "login": 1487154223,
    "status": "1",
    "timezone": "Africa/Ouagadougou",
    "language": "en",
    "picture": null,
    "init": "zinalacina@gmail.com",
    "data": {
      "ckeditor_default": "t",
      "ckeditor_show_toggle": "t",
      "ckeditor_width": "100%",
      "ckeditor_lang": "en",
      "ckeditor_auto_lang": "t",
      "contact": 1
    },
    "uuid": "14899bf3-1a0d-42b5-934e-650471d7da54",
    "roles": {
      "2": "authenticated user",
      "3": "administrator"
    },
    "rdf_mapping": {
      "rdftype": [
        "sioc:UserAccount"
      ],
      "name": {
        "predicates": [
          "foaf:name"
        ]
      },
      "homepage": {
        "predicates": [
          "foaf:page"
        ],
        "type": "rel"
      }
    }
  }
}

```

Now I want to create a node type article and I use this method

```
POST: http://localhost/drupal-7/?q=my_endpoint/node.json
{"type":"article","title":"BEVVtDcZmL","language":"und"}
```

But the result

```
[
  "Access denied for user anonymous"
]
```
. I know it normal because he don't know who wants to create the node. Now I question is how to parse sessionId or token to have the permission to create my node? Thanks

# Answer
1. First thing you need to do is login via Services (unless you allow anonymous users permission to create content), which is a `POST` call to `?q=[my-endpoint]/user/login.json`
2. Once logged in, you need to retrieve a new CSRF token (this new token should be returned within the login result)
3. Then make a `POST` call to `?q=[my-endpoint]/node.json`, sending along something like this:

-

```
{
  title: "Hello world",
  type: "article",
  uid: 123,
  body: {
    und: [
      { value: 'How are you?' }
    ]
  }
}

```

Attach an `X-CSRF-Token` header to the request using the new token value generated after logging in.

That should then return something like this to you:

```
{
  nid: 456,
  uri: /* ... */
}

```

I have a blog post with examples of most of the Services Resources here: http://tylerfrankenstein.com/code/drupal-services-examples
> 1 votes

---
Tags: nodes, services
---


# Question
Title: How do you change the default sort in apachesolr?
I've been trying to get this figured out for a couple days now, and I feel like I'm close, but as of yet no cigar. I need to make the apache solr search on the site I'm working on to have two sorts, 'created' and 'score'. The default search sort is score, but I need to change it to created.

I've got as far as changing the default itself, but then change is added unconditionally, so obviously it will always occur over score. Do I have to rebuild all the URLs to use arg, or is there an easier way? Here's my code:

Note: there's some code to remove some filters, but that's not related to the problem. I included them just in case.

```
   function myhook_apachesolr_prepare_query(&$query, &$params) {
     // Remove sorts
     $query->remove_available_sort('type');
     $query->remove_available_sort('sort_title');
     $query->remove_available_sort('sort_name');
     // Rename/Reorder sorts
     $query->remove_available_sort('created');
     $query->remove_available_sort('score');
     $query->set_available_sort('created', array('title' => t('Most Recent'), 'default' =>     'desc'));
     $query->set_available_sort('score', array('title' => t('Most Relevant'), 'default' => 'asc'));

     // Change the default sort to by date
     $query->set_solrsort('created', 'desc');
   }

```

# Answer
You can implement hook\_apachesolr\_query\_alter() and add new sort criteria as below

```
/**
 * Implements hook_apachesolr_query_alter().
 */
function my_module_apachesolr_query_alter($query) {
  $query->addParam('sort', 'ss_date_field asc');
}

```
> 2 votes

# Answer
I was able to do it in 6, using the following:

```
<?php

function MYMODULE_apachesolr_prepare_query($query, $caller) {

  $query->remove_available_sort('sort_name');
  $query->set_available_sort('changed', array('title' => t('Date'), 'default' => 'desc'));

}
?>

```

See this d.org page for more: http://drupal.org/node/715276
> 1 votes

# Answer
The way we are using the sort options is to expose the sort options block, which I am not sure you have done. If you have, then it will generate the correct links for you - you don't have to do anything else than consider that the so

```
<?php
// solrsort is the query parameter the block uses
if (!isset($_GET['solrsort']) || empty($_GET['solrsort'])) {
  $query->set_solrsort('created', 'desc');
}
?>

```
> 1 votes

---
Tags: 6, search
---


title: Sending Contact Form Emails

text:
# Question
Title: Sending Contact Form Emails
I am trying to configure a site to send emails using the Contact Us form. At the moment, my understanding is that some PHP modules are required for that. I have already created the Contact Us forms and entered the 'recepient' addresses.

Could someone tell me how I should configure the PHP to do that? The site is running PHP 7.0.12

# Answer
> 1 votes
If you're running on localhost there is a great chance your emails will not be sent.

I would recommend using webform for your form modules as this is a very good tool for this.

And test the email part on an actual server. If you want to send emails locally you will need to set up your php.ini file:

See more info on that here: explanation here

---
Tags: 8, forms, emails, configuration
---


title: How to add up rows in a view?

text:
# Question
Title: How to add up rows in a view?
I would like to show a "cumulative total" of nodes by date. For example, it should look like this:

```
date number total
1/1  1      1
1/2  3      4
1/3  2      6
1/4  4      10

```

I've tried views\_php without luck:

# Answer
> 3 votes
Your solution is correct. However, there's a bug in PHP code fields. You must access the $data variable because $row is (surprisingly) empty.

This issue will help you.

How to use PHP Code field

# Answer
> 7 votes
Have you tried the Views Calc module? I think you will get what you want from it. Here is an excerpt about it from the module's project page:

> ... adds simple calculations to a views table. Requires the Views module.
>
> You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns. A plug in theme makes the view look more spreadsheet-like (right justifies numeric fields, shades calculated columns and rows, and underlines calculated rows).

# Answer
> 3 votes
I built a module for this specific issue, as even the maintainers of Views PHP say it shouldn't be used. My module is Views Cumulative Field, and there are versions for D7 and D8.

Some more details about it (from its project page):

> This module creates a Views field handler that enables you to calculate the cumulative value of another field in your view. This is great for Views displays created by the Charts module, but can be used for any View that allows fields.
>
> It was inspired by this comment on the Views PHP module page:
>
> `While this module allows you to directly use PHP inside views which may be useful for quick and easy solutions, it is highly advisable to use regular handlers and plugins when available (or even to create one yourself).`

---
Tags: 7, views
---


# Question
Title: How to hide views UI reaching number of limits of searches
I'm developing a D8 site. I am using a custom views plugin to query data from a remote api by searching a business ID.

My scenario: User is only allowed to enter 3 attempts of business ID in a search view. If 3 attempts fails, I want to hide the views UI from the page for 24 hours. What's my purpose? To give difficulty for others to guess my business ID.

This is a duplicate question with: How to use Rules to limit the number of searches to pull data from a remote API, but on another perspective.

I wasn't able to implement it using Rules, and I'm guessing if we can do it on front-end coding. Does anyone have an idea to implement this?

# Answer
> 0 votes
You can Set a configuration variable for each user (it's equal variables on drupal 7 ) and for each search increase it,reset it each day,**But** another and simple method is implement it by `cookie` , create a cookie for user, set expire to 24 hours, and every time user search, first check it's cookie and if not do it more that three times show results for him/her else there is nothing to him/her.I think cookie solution is good for you.

---
Tags: 8, views
---


# Question
Title: How to use entityQuery to select if a multiple value entityReference field does not contain the id
I have an entity with a user entityReference field, which may contain multiple values. I wish to select using EntityQuery the nodes that do NOT contain the uid in the query.

```
$query
  ->condition('field_shared_with_user.target_id', $uid, '<>');

```

This only works to exclude $uid if there is only ONE value in the field. If $uid is present but some other uid is also present, it incorrectly includes this node in the result.

What is the correct syntax for writing a condition for a multiple value field?

The most I can find about writing these queries is here:

https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Entity!Query!QueryInterface.php/function/QueryInterface%3A%3Acondition/8

# Answer
> 5 votes
gapple put me on the right track (at least a solution for my specific problem), and its a combination of his two ideas.

I needed to query for all the nodes that reference my user, then query for all the entities that match my main query. that gives me two arrays of node ids, and if I array\_diff the first from the 2nd, I end up with the array of node ids i want.

so, a separate entityQuery is needed, but its not too computationally expensive in my case, I think.

```
$my_contacts = \Drupal::entityQuery('node')
  ->condition('type', 'sc_card')
  ->condition('field_shared_with_user.target_id', $user->id())
  ->execute();
$public_contacts = \Drupal::entityQuery('node')
  ->condition('type', 'sc_card')
  ->condition('field_public_directory', true)
  ->execute();
$public_not_in_my_contacts = array_diff($public_contacts, $my_contacts);

```

# Answer
> 5 votes
From what I understand the Entity Query will just perform a join operation on the tables, resulting in data like the following:

```
entity.id | field_user.target
        1 |                 5
        1 |                 6
        2 |                 5

```

A join condition can limit the rows returned, but restricting by `field_user.target <> 6` can only remove the one row (`1:6`), leaving the `1:5` row remaining. Without a subquery, I don't think there is a way to exclude both rows with `entity.id = 1`.

Two alternatives:

* Perform an initial query to find all of the entities that reference the user you would like to filter, and then filter your query by those entity ids (essentially doing your own subquery).
* Get all results, and filter them in PHP afterwards.

# Answer
> 1 votes
If you want to check for the lack of a value, you need to use notExists() instead of `condition()`. There's also an exists().

---
Tags: 8, entities
---


title: Twig string variable changing to int(0)

text:
# Question
Title: Twig string variable changing to int(0)
I have twig variables inside an array called social\_media that contain colors. When I perform {{ dump(social\_media) }} I can see all the information like so

```
array(10) {
["facebook"]=> string(39) "https://www.facebook.com/myfacebook/"
["facebook-color"]=> string(7) "#2d5f9d"
["twitter"]=> string(33) "https://twitter.com/mytwitter"
["twitter-color”] => string(7) "#51acef"
["youtube"]=> string(56) "https://www.youtube.com/channel/myyoutube"
["youtube-color"]=> string(7) "#e52d27"
["instagram"]=> string(35) "https://instagram.com/myinstagram"
["instagram-color"]=> string(7) "#f77737"
["linkedin"]=> string(83) "https://www.linkedin.com/company/mylinkedin"
["linkedin-color"]=> string(7) "#0077b5"
}

```

Performing {{ social\_media.facebook }} works fine like so

```
https://www.facebook.com/myfacebook/

```

but {{ social\_media.facebook-color }} outputs

```
int(0)

```

In fact every single color variable outputs this same value, while the others work fine. I considered the possibility that the # was causing a problem, but changing the colors to colors like 'Black' or 'Red' as a test, but I received the same outcome. I even tried using

```
{{ social_media.facebook-color|raw }}

```

But that did not have any effect. What could possibly cause some of my twig variables to only output int(0) while others output just fine?

# Answer
It turns out that twig can't handle hyphens in their variable names. Changing the variable names from

```
{{ social_media.facebook-color }}

```

to

```
{{ social_media.facebook_color }}

```

resolved the issue
> 2 votes

---
Tags: theming, 8
---


# Question
Title: What other files belong in the root site folder?
My employer maintains a server for several Drupal sites. They inherited these sites without having much expertise in Drupal. I'm more front end than back end so my knowledge of hosting is limited. My question relates to the folders that reside in the root folder alongside the Drupal site folders. I could tell that some folders didn't belong, such as 'backups' and 'libraries'. I moved those folders and there was no problem. (By the way I verified that some of these files could be called up in a browser.) There were two remaining folders I am not sure about. The 'logs' folder has server logs but the individual files cannot be called up in an anonymous browser. Does anybody know the rule as to where server log files belong and how to secure them? I do not see an htaccess file in this folder, BTW. The other questionable folder is a folder labelled 'internal', and it has database stuff in it, such as an 'aspnet\_client' folder. I'm afraid to just move this file even though the content is several years old with no recent changes. That tells me it's not important, but I'm wondering if any server people can tell me this folder doesn't look right, it was probably stored there by mistake at one point as a backup.

Thanks in advance for your help.

# Answer
The simple answer is: none. The public files folder is an area Drupal uses to store files. It shouldn't be manipulated manually or by non-Drupal processes (unless you're configuring an advanced workflow, really know what you're doing, and can accept the risk that Drupal could theoretically annihilate any "extra" files it finds as it has write perms).

If you're certain the folders you're talking about aren't managed by Drupal, and you don't need the contents, you can assume they're safe to delete.

Obviously you'll need to perform sanity checks to ensure other processes outside of Drupal don't rely on them first. Hopefully your infrastructure is documented (if not, now's the time to start)

FYI You can check whether individual files are managed by Drupal by interrogating the `file_managed` table.
> 0 votes

---
Tags: files
---


# Question
Title: What data type to use for Commerce price field in a rule with a Views Loop (Views Rules)?
I want to create duplicates of some Commerce Products with the goal of giving these products a new Product type. With great help (How to change the product type of selected Drupal Commerce products (without direct DB updates)?), I have managed to use the Views Rules module to create a Views loop that should iterate through a selection of Commerce Products and duplicating them (creating new entities) with the new product type.

All fields except one accept the data type "Text", and the variables created looks like `[sku:value]`, `[title:value]` and so forth.

The problem is that I keep getting PHP errors like this:

> Unable to create entity commerce\_product": Invalid data value given. Be sure it matches the required data type and format. Value at commerce\_product()-\>commerce\_price: .

... telling me that the data format for the Commerce **price field** is wrong though. I have tried using "text" as data type (and also "Price", "Commerce product" etc.).

Whatever I do in the action part of the Views loop, I keep getting a numeric field for the price (I can't just paste \[price:value\] in the field). I can switch to "Data Selection input mode", and add something like `commerce-price:base-price` (if I use Price as data type for the price field in the variable settings for the Rules View in question) but that also ends with a PHP error like I described above.

What to do with the variable for the commerce price here?

EDIT: this is the price field I get in the Action part of the Views loop, no matter what data type I assign to the price field in the Rules View, including Integer (in the variables configuration). I have also tried to add an action that converts the price into an integer jag before the action that creates the new entity. If I switch to Data Selection there are no price fields to be found.

And if I toggle to Data Selection mode this is what I get. No price field can be selected.

It really seems impossible to use the price field in a views loop.

# Answer
Have a look at the Drupal Commerce issue about "Revise the way we handle price amount values". Especially comment nr 37 in it, which states:

> The price field is and will continue to store price amounts as integers ...

So give it a try to use "***`integer`***" for your Commerce price field. If needed, also use a Rules Action like "convert the data type" (of that price field) to convert your actual input to an integer.
> 1 votes

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


# Question
Title: Daily cron job send email Webform submissions file
create an automatic excel extract of all requests and send it a specific email address every day.

How would I do this? Is there any existing Module to do this in Drupal 7?

# Answer
You could create a view that shows the days submissions, use the data export module to convert it to excel, filter it by day (currrent day). Use rules module to send an email (not sure how to attach it, may need to send link). Not sure if this would work exactly how you need it.
> 1 votes

# Answer
There is a module for this: Webform Scheduled Export

From the project page:

> Allows you to schedule a webform submission export to run at a set point in time and repeat on a daily, weekly or monthly basis. The exports use all the options available to Webform's "Download" tab and they're attached to the email sent to the configured users.
> 1 votes

---
Tags: webforms
---


# Question
Title: How to count the number of checked Checkboxes with Rules?
I have a Drupal Commerce site which uses user points (= coins) for paying.

I have a special case - the product, which the user should buy with his/her coins, needs some fields filled out by the user. So I used a content type for this case and when the user adds a new one, 10 coins will be reduced from the user's account - this works already fine.

Now I have also a taxonomy in this content type and the user can add terms to it, which are shown later in the form when the user fills it.

**Problem :**

I need to count how many checkboxes of the taxonomy terms are checked and multiply the costs with them. So if 3 of 5 are checked, then 10 coins * 3 = 30 coins will be the final price when the user adds a new content type.

Is this possible with Rules? I have no clue how to realize that (I´m front-end developer and no PHP coder).

# Answer
Yes this is perfectly possible with Rules, and you don't need any PHP to get the job done. In your case, the crucial part of such rule is a Rules Action to perform a **Loop**. If you're not familiar with such loops, then I strongly recommend to have a look at the tutorial titled "Lists and loops".

In your case, you should use (at least) these Rules Actions:

* "Add a variable" (say with a machine name like `nr_of_checked_terms`), with initial value "0".
* Add a loop related to your taxonomy terms. After you do, you should iterate over each item in that list (= each taxonomy term). And for each iteration you should then perform a Rules Action to "Set a data value", whereas you actually increment the value of `nr_of_checked_terms` with "1".

After the loop finished, the value of `nr_of_checked_terms` will be the actual number of terms that were checked. Just add another Rules Action near the end to do your actual multiplication using `nr_of_checked_terms` as one of the available tokens.

***Done***

PS 1: Refer to my answer to "How to set multiple values to an unlimited Term Refence field with Rules" for some sample rules that are like a variation of your question here.

PS 2: I assume this is about D7 ...
> 2 votes

---
Tags: commerce, taxonomy-terms, rules, userpoints
---


title: Why can I not login on my live site?

text:
# Question
Title: Why can I not login on my live site?
I am not able to login on my site. All the times I try, I get this error:

> Sorry, unrecognized username or password. Have you forgotten your password?

I checked 10 times, but the password I use is correct.

I am not sure what happens; even if I try to create a new account, and login, I still get the same error.

I was able to login with that username and password previously, even on live, where I am still able. It is just on local where I cannot login anymore.

`mod_rewrite` is enabled on the server, so the problem cannot be that. I noticed that the session is automatically destroyed, for the administrator user.

Why does this happen?

# Answer
> 2 votes
Please check:

* your `cookie_domain` value in your settings file

Normally it should work when it's empty, however if you're using across multiple domains or protocols (e.g. form is HTTP, but you're submitting to HTTPS), you should set it to its full domain name, so Drupal automatically generates a unique session cookie name for each site. E.g.

```
$cookie_domain = '.www.example.com';

```

or assign it dynamically like (not recommended):

```
$cookie_domain = @$_SERVER["SERVER_NAME"];

```
* watchdog logs, e.g. `drush ws --tail`,
* if you're using LoginToboggan or similar, check whether you should use username or e-mail to login,
* whether cookies are created fine in *DevTools* console,
* if you're using Varnish, check whether cookies are deleted,
* try login to the site using one time login link, e.g. via `drush uli` command and verify that your account works (it's not blocked or something),
* try in another browser or in incognito mode,
* disable any 3rd party authentication modules (ldap, openam, etc) which may override the default logic,
* debug your code using XDebug.

# Answer
> 0 votes
It is likely that your multiple login attempts have resulted in an entry in the flood table which is blocking your IP address.

You can access the database using drush and then delete the records from the flood table.

```
drush sql-cli

```

Will open a command line interface (cli) for your database.

To see entries in the flood table:

```
select * from flood;

```

To delete all entries from the flood table:

```
delete from flood;

```

To exit the cli:

```
exit;

```

(The above commands will work in MySQL. They may be different in other DBs.)

Helpful Documentation on Drupal.org

---
Tags: 7
---


# Question
Title: How can I loop through checked entity reference values with a taxonomy condition?
I'm using Drupal 7 and Commerce. We have several product displays: Caramel, Chocolate, Cinnamon, Cheddar, etc. Each of these product displays has 5 SKUs (5 products) for the 5 different sizes we offer. Each product display also gets tagged as either "premium" or "standard."

I'm trying to then build a "sampler" where they choose up to three of those flavors. To do this, I'm using an *entity reference* field so that that list always has the current flavors. i.e. If they had Hazelnut, the sampler gets updated with Hazelnut.

If they choose a premium flavor, it should add $5 to the total price *per premium flavor*, but if there are no premium flavors, then it should stay the same price.

I have a rule set up that is halfway there. Problem is, if there is even just *one* premium flavor, it charges $5 *per item checked*, regardless of whether they're premium or standard.

I can't figure out how to only apply the upcharge per premium flavor. Any help is greatly appreciated. Willing to help fund this some if needed.

# Answer
The first (crucial) part of your rule is a Rules Action to perform a **Loop**. If you're not familiar with such loops, then I strongly recommend to have a look at the tutorial titled "Lists and loops".

So add a loop related to the flavors that got selected. After you do, you should iterate over each item in that list (= each flavor).

And for each iteration you should then perform an appropriate verification if it is a premium flavor (in which case you want to add $5). **But**, within Rules Actions, you cannot just add another Rules Condition (as you may have noticed) ... Except if you use the Conditional Rules module (which is exactly the purpose of this module ...).

***Done***

PS: are those *funds* still available?
> 0 votes

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


# Question
Title: Programmatically Setting Content Ranking Factors For Drupal Search
I've added a dropdown to Drupal search page interface. I would like for users to be able to select this control to sort results according to Date or Keyword Relevance.

I'm able to get the dropdown value in a submit handler, however, I don't know how to programmatically alter the weight of '*keyword relevance*' and '*date*'.

Here is my submit handler. Any help would be greatly appreciated.

```
function test_sort_form_submit_handler($form, &$form_state) {
  drupal_set_message("Drop Down Value Is: " . $form_state['values']['search_sort']);
}

```

# Answer
> 0 votes
I would do this with a view instead of trying to tweak Drupal's search page:

1. Create a view
2. Add the filter "Search: Search Keywords" and expose it
3. Add two sort criteria: your date field and the "Search: Score" field and expose both of them
4. In Advanced \> Exposed form \> settings, check "Allow people to choose the sort order" if you want to give people that option
5. Add the fields or setup the display as you prefer

You can set the default sort option by ordering the sort criteria and the asc/desc setting by choosing that option for the top criteria. You can also use the Better Exposed Filters module (full disclosure: I'm the maintainer) to combine the sort field and direction into a single dropdown and/or rewrite the text of the options.

---
Tags: search, forms, 7
---


title: Problem with Javascript ad code

text:
# Question
Title: Problem with Javascript ad code
I am trying to add a Javascript ad code on our Drupal based website through a block and when I do this, the page doesn't display but only ads display. Please see this sample page: http://circuitdigest.com/forums/circuits-and-projects-help/arduino

I tried adding on different blocks and even added the ad code by directly inserting in the codes but no changes. Other Javascript based ad codes from other ad networks are working fine but only had problem with this one.

Could someone let me know what could be the problem? Here is the ad code.

```
    <script id="mNCC" language="javascript">
    medianet_width = "600";
    medianet_height = "120";
    medianet_crid = "455208315";
    medianet_versionId = "111299";
    (function() {
    var isSSL = 'https:' == document.location.protocol;
    var mnSrc = (isSSL ? 'https:' : 'http:') + '//contextual.media.net/nmedianet.js?cid=8CUWJ3143' + (isSSL ? '&https=1' : '');
    document.write('<scr' + 'ipt type="text/javascript" id="mNSC" src="' + mnSrc + '"></scr' + 'ipt>');})();
    </script>

```

# Answer
Advanced CSS/JS Aggregation Module has several option for inline CSS and JAVASCRIPTS, you can resolve this problem with disabling **Deferred JavaScript Execution** in sub-module 'AdvAgg Modifier' settings.
> 0 votes

# Answer
If you are working on Drupal 8, create a twig like html.html.twig in your themes templates folder and the put your script in there.

```
<!DOCTYPE html>
<html{{ html_attributes }}>
<head>
    <head-placeholder token="{{ placeholder_token }}">
    <title>{{ head_title|safe_join(' | ') }}</title>
    <script id="mNCC" language="javascript">
    medianet_width = "600";
    medianet_height = "120";
    medianet_crid = "455208315";
    medianet_versionId = "111299";
    (function() {
    var isSSL = 'https:' == document.location.protocol;
    var mnSrc = (isSSL ? 'https:' : 'http:') + '//contextual.media.net/nmedianet.js?cid=8CUWJ3143' + (isSSL ? '&https=1' : '');
    document.write('<scr' + 'ipt type="text/javascript" id="mNSC" src="' + mnSrc + '"></scr' + 'ipt>');})();
    </script>

</head>
<body></body>
</html>

```
> 0 votes

---
Tags: 7, javascript
---


# Question
Title: hook_menu access argument returns 3 instead of data
I am trying to access an api that I wrote, with an access that is limited to administrators only.

My code is:

```
mymodule_menu() {
/**
 * Create api callback to return list of users in a give site
*/
  $items['api/v1/userslist'] = array(
    'type' => MENU_CALLBACK,
    'page callback' => 'mymodule_api_userslist',
    'access arguments' => array('administer permissions'),
    'delivery callback' => 'mymodule_json',
  );

  return $items;

```

this just return the value "3" for no reason.

If I remove access argument and put `'access callback' => TRUE`, everything is working. So it is a problem with the permission.

Any ideas?

```
function mymodule_json($data) {
  if (isset($data['error'])) {
    drupal_add_http_header('Status', '400 Bad Request');
  }

  echo drupal_json_output($data);
}

```

# Answer
> 2 votes
Your delivery callback is not right. The default delivery callback is `drupal_deliver_html_page($page_callback_result)`.

From that page:

> `$page_callback_result`: The result of a page callback. Can be one of:
>
> * NULL: to indicate no content.
> * An integer menu status constant: to indicate an error condition.
> * A string of HTML content.
> * A renderable array of content.

So there is no such thing as `$data['error']`. You are probably encoding the error code `3`.

In the default callback they catch integers as errors:

```
// Menu status constants are integers; page content is a string or array.
if (is_int($page_callback_result)) {
  ...
}

```

You might want to do the same:

```
function mymodule_json($data) {
  if (is_int($data)) {
    drupal_add_http_header('Status', '400 Bad Request');
  }

  echo drupal_json_output($data);
}

```

---
Tags: hooks
---


# Question
Title: Manipulating Theme Suggestion Priorities
I'm adding in some theme suggestions using `mytheme_theme_suggestions_alter()`, when certain criteria is met. My issue is, for some reason these additional theme suggestions are appearing at the top of the theme suggestions list whilst debugging.

Basically my theme suggestion is ignored, as Drupal believes my additional theme suggestions aren't a priority over the default ones.

```
<!-- FILE NAME SUGGESTIONS:
   * views-view--venues-grid-rows.html.twig
   x views-view.html.twig
-->

```

I've tried some 'dirty' solutions, such as trying to clear or reverse the `$suggestions[]` array without any luck.

My guess is that the hook I'm using is actually running too early, however I'm unable to find a more appropriate one. Something dedicated to hooking into view theme suggestions would be great.

Thanks in advance.

# Answer
> 1 votes
You shouldn't need to add a theme suggestion if you're trying to override the view template for a given view ID. The confusing thing is the fact that Views' suggestions don't show in the debug code (see: https://www.drupal.org/node/2118743).

If you add a file named `views-view--view-machine-name.html.twig` (replacing `machine-name`, of course) in your theme's `templates` directory and clear caches, it should pick it up. Note: it has to be `templates` and not in your theme's root or `my_templates` or anything else. Drupal is picky that way.

You should not need to worry about module/theme weights as all module alter functions run before theme alter functions.

Finally, if you are adding theme suggestions, I would recommend using the more targeted `hook_theme_suggestions_HOOK_alter`. (For views, the HOOK is `views-view` so your function would look like:

```
function mytheme_theme_suggestions_views_view_alter(array &$suggestions, array $variables) {
  $suggestions[] = ...
}

```

Hope that helps.

---
Tags: 8, theming
---


# Question
Title: Getting content type data from twig view template
I have a custom content type, view and block all setup and working properly. When I attempt to use kint to access `node` or anything else from my block template file: `views-view--testimonials--block_1.html.twig` i keep getting NULL values returned.

Prior to attempting to customize my block template, in my `content-types` folder, i had a file to directly access my content type: `node--testimonials.html.twig` which could access the values like so: `{{ node.field_testimonial_author.value }}`

My question is, how can I get access to `node.field_testimonial_author` from my block template file? (which is `views-view--testimonials--block_1.html.twig`)

I may be approaching this entirely wrong. If so, please feel free to offer any educational resources that will help me out. Coming from Drupal 7 the learning curve here for me is essentially a brick wall.

Thanks in advance.

# Answer
> 3 votes
Blocks don't have the same variables as other entity types do. They will vary in their theme hook implementations. That is why there is no `{{ node.field }}` concept for blocks, the information does not exist. The same principle applies to Views, Media, Paragraphs and other entities. For example, to reference fields on the paragraph in its template, you wouldn't call `{{ node.field_foo }}` you would call `{{ paragraph.field_foo }}`.

Just because a view block is rendering on a node detail page doesn't mean that the same twig template automatically sees a node object.

If the View is building this block display, I would say add the field to the View that you want to output (Author).

If you want to blow your own mind, if the view you have is returning fields on a node, change the display to use the rendered content mode, and choose a display mode (start with Teaser). This approach *will* allow you to use `node--node-type` twig templates, as Views is rendering the entity instead of printing fields into the View. The View output is then driven by the display mode on the node type itself and is a much more manageable result in most cases.

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


# Question
Title: How do I remove white space from Bartik?
I like to move the left hand side further left to remove the white space, as well as move the right hand side towards the right, so that the centre has more space. I like to remove line wrapping with entries and with the majority of my endusers using widescreen monitors it doesn't look that great.

Essentially I like to move the left and right sidebars towards the edges of their respective edges so the centre can become wider. I tried using the inspector and grepping for the relevant CSS code to modify but none of it seems to work. Nothing else has been modified it is out of the box Bartik theme with no extensions.

**Update**

```
.layout-container {

  max-width: 95%;  /* 860px */
  margin-left: auto;
  margin-right: auto;
  box-sizing: border-box;
}
@media all and (min-width: 95%) {
.layout-container {
max-width: 95%;
 }
}

/**
  * Main
  */
  .layout-main-wrapper {
   min-height: 300px;
  }
 .layout-main {
   margin-top: 20px;
   margin-bottom: 40px;
 }

```

This works if I edit the `/core/themes/bartik/css/layout.css` if I copy the theme and place it in the `/themes` folder it doesnt work.

# Answer
> 0 votes
First, you should not attempt to manually override and of Drupal's core files (or any other module or theme for that matter) because your changes will be overwritten during updates. So do not search for the CSS and attempt to alter it.

Make a copy of the bartik theme instead, move it to sites/all/themes and rename the folder and the `.info` file. Finally alter the info file to give your theme a new name.

All Bartik lay-out code can be found in layout.css. So you will have to modify widths and margins there.

Finally, I wanted to make you aware of the Responsive Bartik theme which is already slightly wider for widescreen monitors, but also optimized for mobile phone usage. You might find it usefull to use that instead, or use it as a base theme for your modifications.

**Update for Drupal 8**

You have the core/themes/bartik/css/layout.css file where you have to alter the max-width for wide screens:

```
/**
 * Container
 */
.layout-container {
  max-width: 860px; /* <- This is the default width. */
  margin-left: auto;
  margin-right: auto;
  box-sizing: border-box;
}
@media all and (min-width: 851px) { /* <- Bigger than this means it is a wide screen */
  .layout-container {
    max-width: 1290px; /* <- This is the max-width for wide screens. */
  }
}

```

Most of the CSS properties are defined in percents and so they should scale along.

---
Tags: theming, 8
---


# Question
Title: Different Theme for Current URL - Using Javascript?
I know that you can have different themes for different parts of the site, assigning specific URLs to different themes by using **hook\_custom\_theme()** or the **themekey** module - I've used both solutions to do this at one time or another.

However, is there a way to modify/update what theme is being used on the current page by using Javascript?

I'm asking because I want to A/B test an upcoming UI fix. In my test, 50% of visitors in the control group would see *"old pages using theme A"* (without fix) and the other 50% would see *"new pages with theme B"* (with fix). Then I can see whether the fix improves performance/conversion and by how much.

The thing is the testing tool I use needs to have a way to change the theme for that latter group **only**. That tool (Optimizely) doesn't have access to the PHP hooks and functions, but it can alter the on-page JS code for the control/treatment groups.

Any advice would be much appreciated. If this is a bit confusing, I can clarify any questions ...

# Answer
> 1 votes
You couldn't select a Drupal theme through JS, unless you reloaded the entire page using JS after the initial load.

The better way to do this would be to use hook\_custom\_theme() to set the theme. Since you need to track the theme with Optimizely, you can send a JS variable from PHP and then pass that to Optimizely in order to track which theme is being viewed.

You could do this in hook\_custom\_theme() to have 50% of the users use one theme, 50% use the other:

```
function hook_custom_theme() {
  $theme = variable_get('switch_custom_theme', 'theme_1');
  $new_theme = $theme == 'theme_1' ? 'theme_2' : 'theme_1';
  variable_set('switch_custom_theme', $new_theme);
  return $new_theme;
}

```

Then you can get the theme in JS at `Drupal.settings.ajaxPageState.theme` (Drupal 7). I can't help you with the Optimizely side of things as I don't use it, you'd have to look at their documentation.

---
Tags: javascript, theme-negotiation
---


# Question
Title: Hide the actual location of a node on Views with GMap Module
What I'm trying to achieve is to hide the actual location of a node, either by replacing the marker with a circle, overlaying or inserting a radius(`circle`) around the actual location. Tried to do this with the help of macro builder but it doesn't accept replacement patterns in order to send the coordinates to the `circle` macro.

Any help is welcome, thanks in advance

# Answer
Resolved the issue by adding a marker in a circle format, setting `maxzoom` and clearing all cache.
> 0 votes

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


# Question
Title: How to setup Recaptcha on pages cached by Varnish?
On a site where a contact form is displayed at the bottom of each page, I implemented **Varnish** caching. To do so I had to deactivate Recaptcha to avoid 'no cache -must revalidate " headers.

I tried other antispam solutions such as **Honeypot** or **Botcha**, but Honeypot is not efficient (at least with time limit disabled), and Botcha also invalidates cache. I'd really prefer to go on with Recaptcha

I tried also Boost Captcha dev version : as per this related Varnish issue, it should be quite straightforward to make it work for Varnish. But this doesn't help, cache is still invalidated.

Did anybody could make Recaptcha work with Varnish ?

# Answer
> 1 votes
CAPTCHA and reCAPTCHA modules are incompatible with page caching.

---
Tags: 7, caching, proxies, captcha
---


# Question
Title: Some HTML tags are not displaying in body(ckeditor) of content type
I am trying to put HTML file content into a body part of a content type.

**Procedure:** When user uploads a zip file I will extract and replace `<img src="path"` with different path and put that replaced content into body of the content type. This will be done in `hook_node_presave()`.

**Code:**

```
               if(trim($unzipped_filename) == 'index.html') {
                    $renamed_filename = $unzipped_path . '/testing.html';
                    //rename the index.html
                    $renaming_index = rename($unzipped_files[0],$renamed_filename);

                    //open file and get data
                    $htmldata = file_get_contents($renamed_filename);
                    //Match all img src tags from html file
                    preg_match_all('/<img\s.*?\bsrc="(.*?)".*?>/si', $htmldata, $matches);
                    $i = '';
                    $replacewith = array();
                    for ($i = 0; $i < count($matches[1]); $i++) {
                     //Store replacing strings in an array
                      $replacewith[] = base_path() . $unzipped_path . $matches[1][$i];
                    }
                    //Replace all img src tags from html file
                    $replacedhtml = str_replace($matches[1], $replacewith, $htmldata);

                    file_put_contents($unzipped_path . 'renamed.html', $replacedhtml);
                    $node->body['und'][0]['value'] = $replacedhtml;

                  }

```

In the above code `$node->body['und'][0]['value'] = $replacedhtml;` like this I am placing replaced content of HTMl into body part.

**Problem:** In database I can see all the Tags: etc. But in content its not displaying these tags. Because of this, its not taking JS and css files to load the content. Below html content is not displaying in body.

```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>TEXT Example</title>
<link href="css/Academy-style.css" rel="stylesheet" type="text/css"/>

<script src="js/jquery.min.js"></script>
 <script src="js/css3-animate-it.js"></script>

```

So where I am going wrong please suggest.

# Answer
> 1 votes
Have a look at your configured input format settings. It is likely the input format or a specific filter are stripping HTML tags out.

# Answer
> 0 votes
As Vincent said, its a logic of configuration part of CkEditor.

`Advanced Content Filter` was stripping these tags.

Hope it helps somebody..

---
Tags: 7, javascript
---


# Question
Title: How to add Colorbox to a field in a twig template?
I have a site with various products on it. So I created node--product.html.twig. I then removed this from my twig template:

```
{{content}}

```

Because I want to display fields myself in a custom format, without relying on Drupal's built-in display. So for the most part this was easy, as I could do this:

```
<img src="{{ file_url( node.field_product_images.0.entity.uri.value | image_style('shop_thumb_400_x_400')  ) }}" alt="" />

```

This works perfectly. But my problem is that I want the user to be able to click on this image and see it in a modal view, but USING the Colorbox module.

Is there another way to output this field in the twig template so that it automatically loads colorbox and everything that is needed?

# Answer
> 2 votes
You really would want to use:

`{{ content.field_product_image }}`

The field display setting will pass the image style to it, and I assume colorbox has a field formatter or tie in here as well. Supply a field Twig template to strip extraneous markup divs.

---
Tags: theming, 8, javascript
---


# Question
Title: How insert values from client page to database by use custom module
Help me pls. I need update database table in Drupal 8. Exemple on image.

When user click on button "ADD PRODUCT TO CART", cart value must update on page (its not a problem), cart value and user ip-address must be write to database. Im try use ajax for this logic, but values do not write to database. Js code:

```
jQuery('.cart button').on('click', function () {
var price = jQuery('.price').text();
var priceValue = parseInt(price.substring(0, price.length - 1));
var cart = jQuery('#cart');
var cartValue = parseInt(cart.text().substring(0, cart.text().length - 1));
cart.text(cartValue + priceValue + '$');

jQuery.getJSON("http://jsonip.com/?callback=?", function (data) {
    var ip = data.ip.toString();

    jQuery.ajax({
        type: "POST",
        url: "../myupdate.php",
        data: ["ip="+ip, "cart="+jQuery('#cart').text()]
    }).done(function () {
        console.log('done');
    }).error(function () {
        console.log('error');
    });

});

```

});

php code:

```
<?php
$ip = $_POST[ip];
$cart = $_POST[cart];
db_insert('abweb')
    ->fields(array('ip' => $ip, 'product' => 'some product', 'price' => $cart))
    ->execute();

```

This logic is implemented in the custom module. HELP PLS!!

# Answer
Here is way to do this. use line item type and create your filed. Hook\_commerce\_cart\_product\_add() call in custom module.

```
  function mymodule_commerce_cart_product_add($order, $product, $quantity, $line_item) {

         $commerce_line_item = commerce_line_item_load($line_item->line_item_id);

         $field_main = $product->field_main['und']['0']['value'];

         $line_item->field_update[LANGUAGE_NONE][0]['value'] = $field_main;

         commerce_line_item_save($line_item);
     }

```

When user click on button "ADD PRODUCT TO CART", cart value add/update your commerce line item field.
> 0 votes

---
Tags: 8, database, ajax
---


# Question
Title: How to hide a views result item based on role?
I have a View based on taxonomy vocabularies and terms. The view only contains 2 fields, `taxonomy vocabulary` and `taxonomy term` and the output is HTML list.

How can I hide **one of the terms** in one of the vocabs in the **view result** based on the role of the logged in user?

UPDATE: With the help from No Sssweat below, this is how the final snippet looks like:

```
function mytheme_preprocess_views_view_fields($vars){
  global $user;
  if ($vars['view']->name == "view name" && strip_tags($vars['fields']{rendered_entity}->raw) == tid && in_array('user role', array_values($user->roles))){
    $vars['fields']{rendered_entity}->content = NULL;
  }
}

```

... in case anyone else need something like this snippet.

# Answer
Assuming you added `Taxonomy term: Name` as the field, which you want to hide.

Add this to your theme's **template.php** file.

```
function mytheme_preprocess_views_view_fields($vars){

  $global user;

  if ($vars['view']->name == "name_of_view" && strip_tags($vars['fields']['name']->content) == "Term Name" && in_array('role name', array_values($user->roles))){
    $vars['fields']['name']->content = NULL;
  }

}

```
* change `mytheme` to your actual theme name.
* change `name_of_view` to your view name.
* change `Term Name` to the name of the term.
* change `Role Name` to the specific role name.
> 2 votes

# Answer
You can achieve this using Views PHP module as well.

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

**While this module allows you to directly use PHP inside views which may be useful for quick and easy solutions, it is highly advisable to use regular handlers and plugins when available (or even to create one yourself). Take note that filtering and sorting a view using PHP always has a considerable perfomance impact.**

Steps:

Add Global PHP filter in view.
Load global user.
Get User role.
Get the term id
After getting both values, Put in condition.
If condition satisfy return False else return TRUE.
> 1 votes

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


# Question
Title: How can I include some functions globally?
I've created a few helper functions specifically for a project and I want them to be available globally.

I know I can include them via composer with the `files` key. I was wondering if there was a more "drupal way" sort of ...way, to include them?

# Answer
> 1 votes
The Drupal 8 way to define helper methods is to put them in a class as static methods.

Example from core:

```
namespace Drupal\Component\Utility;
/**
 * Provides helper methods for byte conversions.
 */
class Bytes {

  const KILOBYTE = 1024;

  /**
   * Parses a given byte size.
   *
   * @param mixed $size
   *   An integer or string size expressed as a number of bytes with optional SI
   *   or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G, 6GiB, 8 bytes, 9mbytes).
   *
   * @return int
   *   An integer representation of the size in bytes.
   */
  public static function toInt($size) {
    // Remove the non-unit characters from the size.
    $unit = preg_replace('/[^bkmgtpezy]/i', '', $size);
    // Remove the non-numeric characters from the size.
    $size = preg_replace('/[^0-9\.]/', '', $size);
    if ($unit) {
      // Find the position of the unit in the ordered string which is the power
      // of magnitude to multiply a kilobyte by.
      return round($size * pow(self::KILOBYTE, stripos('bkmgtpezy', $unit[0])));
    }
    else {
      return round($size);
    }
  }

}

```

and use it in code:

```
$upload_max = Bytes::toInt(ini_get('upload_max_filesize'));

```

# Answer
> 0 votes
Any functions you put in the .module file will be available globally and can be called from anywhere.

---
Tags: 8
---


# Question
Title: How to show/hide textfield according to the change in drop down using jquery?
```
$(".form-select").change(function () {
  if (this.value == "1") {
    $('.form-item-example').stop(true,true).show(700);
  }
  else{
    $('.form-item-example').stop(true,true).hide(700);
  }
});

```

This is what i have used in my js file but it is hiding the text fields when any of the drop down in the form is changed, I'm having 3 drop downs in the form.

# Answer
I have done something similar using conditional fields module which is an interface for the States API or you can use States API if you are comfortable writing custom code.
> 2 votes

---
Tags: 7, javascript
---


# Question
Title: Views CSV export, not exporting complete data
I have one CCK field called "Questions" with type "Long text".

I'm trying to export this value using views data export in CSV format.

Below is the text to export.

> Some text, trying to export.

While export in CSV, I have got only partial data. ie, `"Some text"`.

After comma `"trying to export"` value is missing in CSV.

Is there any way to get complete data?

Note: Other than `"views_pre_render"`

# Answer
> 0 votes
As an alternative to the 2 modules you're using, you could also try to use the Forena module (Disclosure: I'm a co-maintainer of it). Here is a quote from that page:

> ... built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.

And here is another quote from Reasons for considering Forena, related to the "CSV" in the question here:

> Reports created by Forena ... can be saved (exported) as PDF documents with embedded graphs. Other supported formats for saving a report are **CSV**, XLS, DOC, HTML, etc.

These are the steps for creating such CSV files are:

* Create a custom **SQL query**, in which you have the full power of SQL at your fingertips (and various extra features related to it provided by Forena).

Here is a (basic) SQL I'd use for answering this question:

> `SELECT nid, title, type, uid`
>
> `FROM node`
* Create a custom **report**, either by an admin, or by just any regular user who is either familiar with creating what is called 'FRX files', or otherwise using the WYSIWYG report editor.

Using the WYSIWIG editor, in about 10 secs (= a few mouse clicks later on) you'd have a report for which the layout (in XHTML) would look like this:

> ```
> <body>
> <div id="nodes_block" class="FrxTable FrxTable" frx:block="drupal_cust/nodes">List of all nodes in this site
>
>
> <table>
>   <caption>Report caption</caption>
>   <thead>
>     <tr>
>       <th>nid</th>
>       <th>title</th>
>       <th>type</th>
>       <th>uid</th>
>     </tr>
>   </thead>
>   <tbody>
>     <tr id="nodes" frx:foreach="*">
>       <td>{nid}</td>
>       <td>{title}</td>
>       <td>{type}</td>
>       <td>{uid}</td>
>     </tr>
>   </tbody>
>   </table>
> </div>
> </body>
>
> ```

As part of "designing" this report, you should enable (within what is called "Document types") the option to export to CSV files (possible other options like XLS, DOC, PDF, etc also if appropriate).

At then end just "Save" the design of such report. This will be used later on, to retrieve all the specs of your report, when you want to browse (run, execute) your report.
* Browse the report (= enter its relative path, or click some menu link if your design included such link) and then use the CSV link in it to actually save (= export) the report in (eg) CSV format.
* Note: These steps do not require any PHP coding.

**Bonus**: instead of CSV format, you also have an option to format it as either XML or JSON. For more details on that, refer to "How to add a link to the CSV download to my module page, for a report created with Forena?".

### Example

Here is an example of (part of) a CSV file I created using the above approach:

> `nid,title,type,uid`
>
> `33,Demo title,article,19`
>
> `39,"Demo, with some commas in the title, just a test",article,1`
>
> `72,Yet some other Article,article,8`
>
> `73,Article with some field collection data,article`

The above CSV file contains:

* the typical CSV header in record 1 of it, whereas the values in this record correspond with what was requested in the report design, as specified with the `<th>...</th>` tags in the report layout.
* 1 record for each result that was selected.
* 1 specific record with a node title containing commas (shown with surrounding `"..."`).

### More info

For more info (prior to installing/testing Forena), checkout these links:

---
Tags: views, importing-exporting
---


# Question
Title: Is it possible to have different domains for each node?
I have some nodes that I want to access them by different URL domains. For example:

```
XX.XX.XX.XX/node/1 --> domain1.com
XX.XX.XX.XX/node/2 --> domain2.com
XX.XX.XX.XX/node/3 --> domain3.com

```

Also the nodes have a file field where the admins can upload a pdf file and the users can download it, so:

```
XX.XX.XX.XX/PATH-TO-UPLOADED-PDF --> domain1.com/PATH-TO-PDF
XX.XX.XX.XX/PATH-TO-UPLOADED-PDF --> domain2.com/PATH-TO-PDF
XX.XX.XX.XX/PATH-TO-UPLOADED-PDF --> domain3.com/PATH-TO-PDF

```

Is that possible to do with Drupal? I will buy the domains only if I know that is 100% possible.

Of course, I know that there are better solutions than Drupal, but I want to know if it is possible.

# Answer
> 1 votes
You can use the Domain module, but since you say there are better solutions than Drupal, you should probably go with one of them.

# Answer
> 0 votes
You can customize your node table by adding a field called node\_domain for example, and then you can filter display of your nodes by this field compared to current domain of your application.

Hope this can help you.

---
Tags: 7
---


# Question
Title: Redirect Using Rules Based on Account Role
Further to this previous question, https://drupal.stackexchange.com/questions/1790/redirect-users-after-login-depending-on-the-users-roles I am trying to accomplish a similar redirect on a D7 whereby once a user with a specific role type has logged in, they are redirected to a homebox (using the Homebox module) page of 1 of 2 types (1 Teacher; 2 Student) and the homeboxes nodes are named accordingly: 1) teacherhomebox, 2) studenthomebox using URL aliases. I have been following Johan Falks tutorial http://vimeo.com/28804544 (many times now!) and thought I understood what appears to be a simple task, but after testing either of the said roles, my redirects do not show the relevant (after login) user homebox as the primary page and simply stays on my custom Panel 'landingpage' I have setup as the primary welcome site homepage. Of course they do log in and it shows their account link on the header (which I'll remove later) I'm not sure what or why the redirects are not working, maybe I've not put the correct account select in the Rules UI but FYI and for testing purposes (using a student role) the setup is as such:

Event: User has logged in

Condition: User has role(s) (parameter: Role= student, match=ANY)

Actions: Element: Page Redirect (parameter: URL: studenthomebox)

I have in the URL redirect Value, put "studenthomebox"

I would also like to add that I am trying to create a 'homebox' dashboard as per drupal.org and would be happy to acheive the same along with using the Rules module (with homebox) and would prefer to stay using Rules given the option.

Any help is very much appreciated as I'm after many hours, rather confused now.

# Answer
Check that you are not using any other contrib modules like Login Toboggan which may be setting a redirect after log in.

Failing that, turn on Rules Debugging by going to admin/config/workflow/rules/settings and ticking the 'Log debug information to the system log' checkbox.

Log out and log back into your site as a student user. Then go to admin/reports/dblog and check the debugging messages set by Rules.

You will then be able to see which of your conditions is failing.
> 0 votes

# Answer
### Solution if no other redirect facilities are enabled

Here is the rule (in Rules import format) that will redirect a user with the role that matches "`role id = 5`" to the page `teacherhomebox`:

```
{ "rules_redirect_role_id5_to_selected_page" : {
    "LABEL" : "Redirect role ID5 to selected page",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_login" : [] },
    "IF" : [
      { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "5" : "5" } } } }
    ],
    "DO" : [ { "redirect" : { "url" : "teacherhomebox" } } ]
  }
}

```

Just import the above rule and adapt the value (=5) of the role id to fit your role for "Teacher". With that you solved your question for roles with role ID = 5.

To also make it work for other values of role ID, and because of the fact that a Rules action cannot contain "conditions", you basically have 2 possible approaches:

* Create a similar rule for each possible value of role ID.
* Use the Conditional Rules module to enhance the *Rules Action* in the above rule to alter the flow, using either ***Conditional*** (if/else) of ***Switch*** logic.

### Solution if other redirect facilities are enabled

The rule above should solve your question, unless some other module also does a redirect after login. If you have other redirect-logic enabled, then try to experiment with a rule using Rules Event "Drupal is initializing", combined with a Rules Condition that checks the "current path". For an example of such rule, refer to the answer to "How to make the permissions of a module more granular?".
> 0 votes

---
Tags: 7, rules, redirection
---


title: Check the current page is a view

text:
# Question
Title: Check the current page is a view
Is there a way to determine if you are on a view page, similar to `\Drupal::request()->get('node')` used to check if the current page is a node page?

I need to adjust breadcrumbs for view generated pages with `hook_system_breadcrumb_alter()`.

# Answer
> 7 votes
You could use the name of the current route:

```
$current_route_name = \Drupal::service('current_route_match')->getRouteName();

```

The route names from views are built like this `view.[view_name].[display_id]`.

You can list the existing routes with Drupal Console:

```
drupal router:debug

```

---
Tags: views, 8, breadcrumbs
---


title: Getting a 403 error in REST

text:
# Question
Title: Getting a 403 error in REST
So I'm giving REST a try. Installed drupal-8.0.0-beta12 in a VM. cURL works fine using `curl http://testing.dev/drupal8/node/1?_format=json` but I'm not sure why I'm getting a `403` error message using dev HTTP client:

Any ideas?

# Answer
> 2 votes
Have you got correct permissions for anonymous users to access the resource ?

`testing.dev/drupal8/admin/people/permissions` under the RESTFul Web Services ensure that `Access GET on Content resource` is ticked for Anonymous User. Clear cache and try your request again.

Also you might not have the format type exposed for that resource in your `rest.settings.yml` file. This file sets the supported\_formats and auth. Here is what is should look like in your case:

```
resources:
  'entity:node':
    GET:
      supported_formats:
        - hal_json
        - json
      supported_auth:
        - cookie

```

# Answer
> 2 votes
@dibs and @bluesky\_still I hope this will help you guys out, if not the original poster:

I think REST UI is just a no-go for 8.2.3.

Here is what I did to get some GET and POST requests to work:

### Setting up the REST configurations

You need to edit the yml for the entity type you're trying to change the REST configurations for. For example, the node entity would use rest.resource.entity.node.yml. I've been given the impression that RESTUI really just isn't useful with 8.2+, so you gotta do it by hand. Once you've created this file to your liking, you need to import it to your site.

I still can't figure out how to do this "correctly"; I don't know if you need to use the configuration importer (which will throw a UUID error) or include it in a theme or in your default settings or what. I *did* get the configuration to work. I ended up using the Features Module to create a feature package for REST Resource Configuration (admin/config/development/features/edit), downloaded the feature, unzipped the package, and installed the module created by the changes.

I then manually edited the config files in the created module's directory (DRUPAL\_ROOT/modules/MODULE\_NAME/config/install/rest.resource.entity.node.yml) to have the settings I wanted. Finally, I implemented the changes by updating the feature from the features config page (admin/config/development/features/ click on the "changed" next to the module you created, click on the checkbox next to the changes, and click "Import Changes").

There HAS to be a simpler way to handle the import, but it works for me on 8.2.3.

### User Permissions

Once your REST configurations are set up, the entity types should follow the permissions you have set in /admin/people/permissions/. So, if anonymous users can view published nodes, they should be able to GET published nodes as well, etc. (At least, according to the documentation.)

If you're still having problems, you need to make sure to include the csdrToken in the header of your request.

### The csrfToken

A GET request to the endpoint YOUR\_SITE.DOMAIN/rest/session/token will provide you with a token which you can set as the X-CSRF-Token' header on your GET or POST request. A typical and simple example using jQuery to GET the first entry might look like this:

```
function getFirstNode() {
  jQuery
    .get('YOURSITE/rest/session/token')
    .done(function (data) {
      var csrfToken = data;
      jQuery.ajax({
        url: 'YOURSITE/web/node/1?_format=hal_json',
        method: 'GET',
        headers: {
          'Content-Type': 'application/hal+json',
          'X-CSRF-Token': csrfToken,
        },
        success: function (node) {
          console.log(node);
        }
      });
  });
}

```

### If all else fails

I've also had success setting up GET endpoints using the Views Module. This article does a pretty good job explaining the process: http://redcrackle.com/blog/rest-export-views-drupal-8. It won't work for POST requests, but it should help.

I hope this helps. It's a really sticky problem for what should be a simple request, and the documentation does NOT do a great job of making this accessible. Good luck!

---
Tags: 8
---


title: Save image to node via form API

text:
# Question
Title: Save image to node via form API
I am having trouble figuring out how to attach an uploaded image to a node in my form submit handler. I've been searching for a while now and nothing I've tried has worked. For instance:

```
$image = $form_state['storage']['image'];
unset($form_state['storage']['image']);
$image->status = FILE_STATUS_PERMANENT;
$file = file_save($image);
$node->field_image['und'][0] = $file;

```

does not work.

Any help on this would be much appreciated. Thanks.

# Answer
It's been a while since I've done this but this link should be a good start. File Load

Assuming $form\_state\['storage'\]\['image'\] is the image's fid, what you may want to do is.

```
$image = $form_state['storage']['image'];
$file = file_load($image);

// Change status to permanent.
$file->status = FILE_STATUS_PERMANENT;

// Save.
file_save($file);

// add image back
$node->field_image['und'][0] = $image;

```

Depending on what your doing you may want to add the file to the usage table. Details here. File Usage Add
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Need a more specific price calculation rule in Drupal Commerce
I have a price calculation rule like this:

**Event**: Calculating the sell price of a product

**Conditions**: Order contains products of particular product types AND User has roles

**Actions**: Multiply the unit price by some amount

Now, the problem is that when the cart contains products of the type that I selected as a condition AND the user has a specific role, the multiplication in the Action element is executed also on products of other product types. I only want to affect the prices of products with a specific type.

The cart can contain a mix of products of different types, but the rule should only affect the line items with the specific type.

How do I do that?

# Answer
> 1 votes
Depending on your multiplication factor (I suppose you want to give a discount), you might want to try Commerce discount which has support for discounts per order and discounts per product.

> Commerce Discount provides a new user interface for defining and managing product and order level discounts. Using just the core pricing system of Drupal Commerce requires knowledge of how to use the Rules UI, which is beyond the capabilities of most merchants. Additionally, the core system cannot support order level discounts or certain types of shipping / product discounts. This module addresses all of those things.

The role based discount condition is provided by Commerce discount extra.

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


title: Can't save data for Address field

text:
# Question
Title: Can't save data for Address field
I am trying to save data programmatically to an address field from the Address module.

I am not successful.

First, when I dsm() a node with the address field filled out, it looks like this:

```
        [field_addr] => Array
            (
                [x-default] => Array
                    (
                        [0] => Array
                            (
                                [langcode] =>
                                [country_code] => US
                                [administrative_area] => CA
                                [locality] => San Diego
                                [dependent_locality] =>
                                [postal_code] => 91945
                                [sorting_code] =>
                                [address_line1] => 123 main st
                                [address_line2] => apt 2
                                [organization] =>
                                [given_name] =>
                                [additional_name] =>
                                [family_name] =>
                            )

                    )

            )

```

However, no matter how I try to save it to my node, it doesn't work.

I create an array that looks like this:

```
Array
(
    [x-default] => Array
        (
            [0] => Array
                (
                    [address_line1] => Australian Club
                    [address_line2] => Royal Lane
                    [locality] => Sydney
                    [administrative_area] => NSW
                    [country] => Australia
                )

        )

)

```

Let's say with the name, `$address_save`

And then do the following:

```
$node->set('field_addr', $address_save);

```

No luck. My node saves with other fields, but this one doesn't. I've also tried it without the x-default key around it as well as without a delta, but neither of those work either.

How can I save values to an Address field inside of a node?

# Answer
> 0 votes
The problem here was due to Drupal failing silently (or obfuscating the error - maybe because I was running this in cron) but it was due to the address not having all of the required fields set to the correct values for the country in question - mainly using the actual country name instead of the country code.

Once the country code was swapped in it worked. I switched the country around to the country code like this:

```
function MY_MODULE_get_country_code($country) {
  $countries = MY_MODULE_country_list();
  $flipped_countries = array_flip($countries);
  $country_code = $flipped_countries[$country];
  return $country_code;
}

function MY_MODULE_country_list() {
  $countries = \Drupal\Core\Locale\CountryManager::getStandardList();
  foreach ($countries as $key => $value) {
    $countries[$key] = $value->__toString();
  }
  return $countries;
}

```

It worked correctly.

---
Tags: nodes
---


# Question
Title: Why are custom User Account fields not shown after account is saved?
Just upgraded to Drupal 7.54 and now when a user account is saved, any other users (other than admin 1 user) are unable to view or update the custom fields associated with the user account. They just see the core fields. The admin 1 user is still able to see all fields.

When the updated user account is viewed or edited by any other user than the admin 1 user (they do have 'administrator' role assigned), they only see the following fields:-

* email
* password
* status
* roles
* locality

I have disabled modules that act on fields, such as Field Permissions and Conditional Fields, but still getting this behaviour.

Any ideas why this could be happening would be much appreciated!

# Answer
> 0 votes
Turns out a developer had enabled the "og\_field\_access" module and this was preventing users from viewing custom fields on the user account pages.

We removed the module dependencies (they weren't needed!) and disabled the og\_field\_access module and the fields now appear again!

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