# Question
Title: computed field with product variation and content type
Using *Commerce Kickstart 2* distribution :

**Question 1**: Where should the computed field go to access fields from both the *Content Type* and *Product Variation*? Does the computed field belong to the content type or to the product variation?

**Question 2**: How do you reference one from the other?

ie - I thought...

```
$field_my_gauge = field_get_items($entity_type, $entity, 'field_needle_guage');
$field_my_type = field_get_items($entity_type, $entity, 'field_needle_type');
$field_my_st = field_get_items($entity_type, $entity, 'field_needle_style');
$field_my_len = field_get_items($entity_type, $entity, 'field_needle_length');
$vari_l = taxonomy_term_load($field_my_len[0]['tid']);
$vari_g = taxonomy_term_load($field_my_gauge[0]['tid']);
$vari_t = taxonomy_term_load($field_my_type[0]['tid']);
$vari_s = taxonomy_term_load($field_my_st[0]['tid']);
$vari_result =  $vari_l->name . $vari_g->name . $vari_t->name . $vari_s->name;
$vari_result = preg_replace('/[\s,.]{1,}/', '', $vari_result);
$entity_field[0]['value'] = $vari_result;

```

buuuut...

```
Notice: Trying to get property of non-object in eval() (line 9 of /Users/Robert/Sites/devdesktop/country_yarns/modules/computed_field/computed_field.module(468) : eval()'d code).

```

`$vari_g` is, or should, be based on the `field_needle_guage` field. But this is in the product variation of Needle, and not in the content type of Needle. All other fields are in the content type and work correctly.

So what's the right way to access members of a product variation in the content type - or is that even the right way around? (See Q1)

\[EDIT\]

Ok, so looking at the objects available in the wrapper:

```
$wrapper = entity_metadata_wrapper($entity_type, $entity);
// field_product_node is documented as the automatically created backreference to the content type.
$product = $wrapper->field_product_node;

// DrupalCommerce Kickstart 2 documentation says the below should work, but it does not - 'error: can't find getProduct function'. (WHY?)
$wrapper->getProduct();

// This comes out as an EntityDrupalWrapper
dpm($wrapper);
// This comes out as an EntityListWrapper
dpm($product);

// but below fails - can't find getIterator on object (WHY??)
$plist = $product->getIterator();
// and below returns an empty array!
$plitems = $product->value();

```

So all these auto-back-reference class things in DrupalContrib are not accessible in this manner, it seems. If they work, I'd love to find out how!

Looking at how the tables are set up: field\_revision\_field\_product is the link table between 'commerce\_product' 'commerce\_product\_revision' and 'node', and any particular field\_data\_field\_XXX field data table.

So I guess I need to use a sql query to get the field\_data\_field\_XXX value through an inner join. I guess I'll need to put that into a custom module and then make a field of that type that allows you to configure what field to grab from the CT

# Answer
> 0 votes
To clarify from the comment thread:

1. This is a question that is tough to answer on SE because it's just something you'll have to feel out. If you're doing 1:1 content types to product displays, it doesn't really matter where you put it (though it'd probably be easier to do it on the CT) in general I tend to put more on PV because it's data related to the product. If you're doing 1:N then you'll definitely want to put it on the PV and if you're doing M:N then you're going to have to do some customization.
2. You can put the computed field on the PV but you'll need something like Entity Backreference so that the PV has a link back to the content type so you can load it and grab it's fields.

---
Tags: commerce, entities
---


title: How to edit image URL in node field?

text:
# Question
Title: How to edit image URL in node field?
I am using Media Browser widget for uploading and editing images in nodes. My images are stored using image fields. Is it possible to edit URL of the image after uploading? I would need to achieve:

When I upload file named "foo.png" it has by default the following URL:

> /sites/default/files/media/.../foo.png

I would need to edit filename to "bar.png", so resulted path will be:

> /sites/default/files/media/.../bar.png

(only filename is changed in URL)

I tried to edit filename, since it is possible using Media browser widget. But editing filename does not have affect on change of URL for me. I also tried to use following hook: hook\_file\_presave I tried to programatically change uri parameter using this hook. But nor filename change neither uri change affected URL of the file. When I look in directory sites/default/files/.. I can see that filename is the same as I uploaded it, not affecting my later changes of filename or uri. When I load php $file object, I can see $file-\>filename and $file-\>uri properties changed.

Is it possible to change URL of the file (just last part of the URL - filename) after uploading the file?

//EDIT: I tried to do following changes in my hook\_file\_presave:

```
function mymodule_file_presave($file) {
 if ($file->type != 'image') {
  return;
  }
 if (!empty($file->filename)) {
   $uri_parts = explode('/', $file->uri);
   $count = count($uri_parts);
   $uri_parts[$count - 1] = $file->filename;
   $file->uri = implode('/', $uri_parts);
   $file->destination = $file->uri;
   }
 }

```

# Answer
To rename the file, you'll need to use PHP's rename() function. To do so, you'll want to get the file's full local path using drupal\_realpath() like so:

```
// Fetch the local absolute path of our image
$local_path = drupal_realpath($file->uri);

```

Once you've renamed the file, you'll need to modify the file URI (and potentially other attributes-- use print\_r($file) to check).

The wording in the docs is a little weird to me, it says "when a file has been added to the database" which means to me the file metadata has already been saved to the database. However, the example shown in the docs seems to edit this info (but without using &$file ...?) without having to return the file object. Strange.

Anyway, your code might look something like this:

```
function mymodule_file_presave($file) {
  if ($file->type != 'image') {
    return;
  }
  if (!empty($file->filename)) {

    // Will likely be 'public://'
    $scheme = file_uri_scheme($file->uri);

    // Get full path of image location
    $local_path = drupal_realpath($file->uri);

    // Create new name using drupal scheme format
    $new_uri = $scheme.'new_name_here.jpg';

    // Actual OS rename of file
    rename($local_path, drupal_realpath($new_uri);

    // Update $file object with new uri
    $file->uri = $new_uri;

    // Not sure if this is still needed...
    $file->destination = $file->uri;
  }
}

```
> 0 votes

---
Tags: 7, files, uri, media
---


title: Form API focus on first input

text:
# Question
Title: Form API focus on first input
When my form load I would like to set the focus on the first field in the form. I know I can use jquery to do this by doing `$('inout id').focus();`. Where would I put this code so that it only runs on a certain form?

Is there a simpler way?

**Updated**

Using a mixture of smile's answer and clive's comment the code that got it working in the end was:

```
$form['#attached']['js'] = array('(function ($){$(document).ready(function() { $(".form-item-field-name input").focus()});})(jQuery);' => array( 'type' => 'inline'));

```

# Answer
> 4 votes
You can attach js only to your form. Use hook\_form\_alter()

```
function your_module_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'my_form'){
  // Add JavaScript file
  $form['#attached']['js'] = array(drupal_get_path('module', 'your_module') . '/your_file.js');

  // Or for inline JavaScript
  $form['#attached']['js'] = array('/* some javascript here */' => array( 'type' => 'inline'));
  }
}

```

# Answer
> 1 votes
To add the HTML5 autofocus attribute from a module in D7, use this example for the user-login form. However, still not supported on iOS Safari as of this posting date.

```
function HOOK_form_user_login_alter(&$form, &$form_state, $form_id) {
    //should also add JS focus code for iOS Safari
    $form['name']['#attributes'] = array('autofocus' => '');
}

```

---
Tags: 7, javascript, forms
---


# Question
Title: How can I disable the form confirmation message?
I'm referring to the green box that informs the user that they have successfully submitted their form. In particular, I'm wondering if I can remove it without writing any php. Is there anything in the admin interface?

# Answer
> 0 votes
There is no option in Drupal's core that gives you the ability to disable messages but there is a module for that: disable\_messages.

Still, I like this approach, which uses drupal\_get\_messages function implemented in hook\_form\_alter:

```
/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, &$form_state, $form_id) {
  // Define the $form_id for the form which you want to suppress messages for.
  if ($form_id == 'hide_messages_form_id') {
    $form['actions']['submit']['#submit'][] = 'my_module_submit';
  }
}

/**
 * My custom submit handler.
 */
function my_module_submit($form, &$form_state) {
  // Hide drupal 'status' messages. Equally use 'error', 'warning' or 'NULL'.
  drupal_get_messages('status');
  // Or display your own message.
  // drupal_set_message(t('My message.'));
}

```

---
Tags: 7, webforms
---


# Question
Title: How to create a rule to combine the terms of 2 fields to create a new term and store it in a 3rd field?
I have a content type that has 3 term reference fields:

* Field A (required), which contains a single tag.
* Field B (required), which contains a single tag.
* Field C (not required), which contains a single tag.

The tags from those 3 fields all related to the same taxonomy.

When creating or updating a node, values are entered for field A and B. I want to have a rule ((using the Rules module) with some Rules Action to set a data value for field C, equal to the concatenation of the value entered for field A and B. But "set a data value" only sets one value.

What can I do to set multiple values?

Some more screenprints to explain all this:

And here is my current Rule I'm trying to get to work:

```
{ "rules_juhe_xieru" : {
    "LABEL" : "\u805a\u5408\u5206\u7c7b\u81ea\u52a8\u5199\u5165",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--mfpf" : { "bundle" : "mfpf" } },
    "DO" : [
      { "data_set" : { "data" : [ "node:field-juhe-fenlei" ], "value" : [ "node:field-diqu" ] } }
    ]
  }
}

```

# Answer
> 3 votes
Your question is not clear (enough), at least not yet, so I'll try with 2 variations ...

### Field C is about Single values

It think your rule needs at least 2 corrections:

* Add a Rules condition like "entity has field", for each "token" that you want to use in any rules Action, but which is not (yet) showing up to actually select it in some Rules Action.
* When using a Rules Action like "Set a data value", you can indeed only set such value for 1 variable. However if you want to "Set a data value" for another variable, just add a 2nd Rules Action to do so for that other variable.

### Field C is about Multiple values

Maybe your question is rather something like so:

> If this Rules Event happens, then I want to add the node reference in field A to field C, and I also want to add the node reference in field B to field C (and field C is a multi value node reference field".

In this case, using "Set a data value" is completely wrong. Instead you need to use an action like "Add item to a list". I.e.:

* Rules Action 1 is to add A to the list C (possibly you also need a Rules Condition like "Entity has field" (for A)).
* Rules Action 2 is to add B to the list C (possibly you also need a Rules Condition like "Entity has field" (for B)).

Refer to my answer to "How to set multiple values to an unlimited Term Refence field with Rules" for way more details about "*Add item to a list*".

# Recommendations to improve the alternative answer

Now (after about a day of extra questions/comments to the question from No Sssweat and myself), it finally became clear what the real question was ...

Here is a variation of the Rule in the alternative answer:

```
{ "rules_improved_combination_of_taxonomy_terms" : {
    "LABEL" : "Improved combination of taxonomy terms",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view--article" : { "bundle" : "article" } },
    "DO" : [
      { "drupal_message" : { "message" : "[node:field-a][node:field-b]" } },
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "[node:field-a][node:field-b]" },
          "PROVIDE" : { "variable_added" : { "variable_added" : "Added variable" } }
        }
      },
      { "entity_create" : {
          "USING" : {
            "type" : "taxonomy_term",
            "param_name" : "[variable-added:value]",
            "param_vocabulary" : "tags"
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "entity_save" : { "data" : [ "entity-created" ], "immediate" : "1" } },
      { "data_set" : { "data" : [ "node:field-c" ], "value" : [ "entity-created" ] } },
      { "entity_save" : { "data" : [ "node:field-c" ], "immediate" : "1" } }
    ]
  }
}

```

These are the extra refinements needed to make it work:

* Add an action to save an entity (twice), because since you used Rules Event to just wake up after viewing a node, you need to remind the Rules module to also save what you've been creating/updating.
* Remove the Fetch entity (no need for that).

By the way, the clue to debug the rule in the other answer can be found if you turn on rules logging: you'll see that the fetch entity didn't return any results, so blank, which is also what got saved in field C ...

**Demo**:

```
Field A: Bonjour
Field B: World
Field C: BonjourWorld

```

At least that's what happened in my tests. If I change A to `Hello` (or `No`), B to `Liu` (or `Sssweat`), then C gets updated to `HelloLiu` (or `NoSssweat`) ...

Be Aware: I can think of some further improvements of all this, but for now I consider this rule as "***Make it right before you make it better***" ... try it in your own setup to confirm it does answer the quetion (but please don't post enhancement requests via extra comments, instead post a new question if needed).

**Disclaimer**: I don't have a clue what those non-English "pictures" are (I bet they are characters in your native language ...).

# Answer
> 1 votes
Something like this is in the right path, I just can't get the field C to set to the `ab` tax term that gets created by Rules though.

```
{ "rules_combine_taxonomy_terms" : {
    "LABEL" : "combine taxonomy terms",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view--article" : { "bundle" : "article" } },
    "DO" : [
      { "drupal_message" : { "message" : "[node:field-a][node:field-b]" } },
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "[node:field-a][node:field-b]" },
          "PROVIDE" : { "variable_added" : { "variable_added" : "Added variable" } }
        }
      },
      { "entity_create" : {
          "USING" : {
            "type" : "taxonomy_term",
            "param_name" : "[variable-added:value]",
            "param_vocabulary" : "tags"
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "entity_fetch" : {
          "USING" : { "type" : "taxonomy_term", "id" : [ "entity-created:tid" ] },
          "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
        }
      },
      { "data_set" : { "data" : [ "node:field-c" ], "value" : [ "entity-fetched" ] } }
    ]
  }
}

```

As you can see the "helloworld" gets created, but somehow we would have to check in Rules if "helloworld" term name already exists using Conditional Rules but I am not yet sure if this is possible, haven't tried.

You would do get entity by property and pass the variable as the name I suppose, but what will that return? NULL or 0?

**NOTE:** This rule still comes up short, as mentioned in the begining, I still see

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


title: Image field with url

text:
# Question
Title: Image field with url
I'm searching for a image field in Drupal 8 with support to add images using url input. So when users has an image on his disk he can upload it and if the user has a image somewhere online he can link to it.

Does someone know a module that add this functionality to the image field?

# Answer
Found a module that just did the job that I wanted.

The module is called FileField Sources
> 0 votes

---
Tags: 8, entities
---


# Question
Title: How to correct my rule to update user info on login using HybridAuth?
I'm using Drupal 7.5x and the HybridAuth Social Login module.

I am aware a lot of users have done this using Rules and Rules Event **`HybridAuth login`**, combined with **`Set a data value`**. However no one explains what comes after, it seems the Hybridauth tokens are either not editable or just invalid.

So I am using the the Rules Event **`User logged in through HybridAuth`**, and I want to set a data value. Here is an export of the rule I have so far:

```
{ "rules_updateinfo" : {
    "LABEL" : "updateinfo",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "login" ],
    "REQUIRES" : [ "hybridauth" ],
    "ON" : { "hybridauth_user_login" : [] },
    "DO" : []
  }
}

```

I want to update the token `user:hybridauth:profileURL` with the new data provided by the API (= `hybridauth:profileURL`). However when trying to input any of these tokens into the data selector, either of the following errors show up:

* If I use **Data selector: hybridauth:profileURL**, the error is:

> "The selected data property doesn't support writing."
* If I use **Data selector: user:hybridauth:profileURL**, the error is:

> "Data selector user:hybridauth:profileURL for parameter data is invalid."

I'm sure I'm doing something wrong, can someone help me to get such rule to work? Is it even possible?

# Answer
> 0 votes
I'm going to answer myself here

Want to update the token **\[user:name\]** based on **\[hybridauth:displayName\]**? Here's the rule:

```
{ "rules_updateusername" : {
"LABEL" : "UpdateUserNameOnHybridAuthLogin",
"PLUGIN" : "reaction rule",
"ACTIVE" : false,
"OWNER" : "rules",
"TAGS" : [ "userupdate" ],
"REQUIRES" : [ "rules", "hybridauth" ],
"ON" : { "hybridauth_user_login" : [] },
"DO" : [
  { "data_set" : {
      "data" : [ "site:current-user:name" ],
      "value" : [ "hybridauth:displayName" ]
    }
  }
]

```

} }

Want to update the token **\[user:picture:url\]** using **\[hybridauth:photoURL\]**? You need to enable the core PHP Filter module, Here's the rule:

```
{ "rules_updateprofilepic" : {
"LABEL" : "UpdateUserPicture",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "userupdate" ],
"REQUIRES" : [ "rules", "hybridauth", "php" ],
"ON" : { "hybridauth_user_login" : [] },
"DO" : [
  { "hybridauth_url_managed_file" : {
      "USING" : { "url" : "[hybridauth:photoURL]", "directory" : "pictures" },
      "PROVIDE" : { "file" : { "pic" : "Managed file entity" } }
    }
  },
  { "php_eval" : { "code" : "global $user;\r\n$file = $pic;\r\n$user-\u003Epicture = file_load($file-\u003Efid);\r\nuser_save($user);" } }
]

```

} }

Want to update the token **\[user:hybridauth:profileURL\]** based on **\[hybridauth:profileURL\]**? You need to enable the core PHP Filter module, Here's the rule:

```
{ "rules_updateprofilelink" : {
"LABEL" : "UpdateProfileLink",
"PLUGIN" : "reaction rule",
"WEIGHT" : "1",
"OWNER" : "rules",
"TAGS" : [ "userupdate" ],
"REQUIRES" : [ "rules", "php", "hybridauth" ],
"ON" : { "hybridauth_user_login" : [] },
"DO" : [
  { "php_eval" : { "code" : "global $user;\r\n$user-\u003Edata[\u0027hybridauth\u0027][\u0027profileURL\u0027] = \u0027[hybridauth:profileURL]\u0027;\r\nuser_save($user);" } }
]

```

} }

Now I'm not sure if this brings any security issue, I'm not a Drupal expert, so if anyone has a better way to do this without executing a php code on rules I'd be glad to hear it.

Although it would be even better if this was part of the module itself, as users change their pictures and profile URLs all the time, so if anyone has enough knowledge they should contribute to the module.

# Answer
> 0 votes
Some more details about the errors you encountered:

With that, I'm fairly sure that the answer to the "***Is it even possible***"-part of your question is:

> **I'm afraid it is NOT** ... Though I'd love to see anybody tell me I'm wrong.

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


# Question
Title: Change default option of installation profile
I've created a new installation profile name ABCD and it is showing on a "select an installation profile" Page

But it shows standard as a default option. How could i make ABCD as default.

I added hook\_form\_alter and hook\_form\_FORM\_ID\_alter in abcd.profile file but it's not working. As I've read in Drupal.org that bootstrap is fully loaded before reading .profile file but still form alter in not being executed in my case. Any idea ?

# Answer
> 2 votes
In your profile .info file you can add the distribution name property in the following format:

```
distribution:
  name: ABCD

```

Notice: ADD this property but leave original top level "name" property in place.

This will totally omit the "Choose profile" step, and your profile will be auto selected for the entire process.

---
Tags: 8, installation-profiles
---


# Question
Title: Setting the default value of an entity form radio button using hook_form_FORMID_alter
I have written a custom Drupal 7 module which needs to set the value of a radio button of an entityform based on a value queried from the database. I have tested hook and it is working as i am able to set a text field with in the form using:

```
$form['field_sem_submitter_id']['und'][0]['value']['#value'] = $user->uid;

```

I have tried, to no avail, to set the radio using the following and various other suggestions:

```
$form['field_sem_pledge_currency']['und'][0]['value']['#value'] = '2';
$form['field_sem_pledge_currency']['und'][0]['value']['#value'] = 'currency_bitcoin';
v$form['field_sem_pledge_currency']['#default_value'] = 'currency_bitcoin';

```

I have searched and tried numerous other suggestions on the web with no success. Any suggestions greatly appreciated.

# Answer
> 0 votes
Can u please try below code:

```
$form['field_sem_pledge_currency']['und'][0]['#default_value']['value'] = 'currency_bitcoin';

```

# Answer
> 0 votes
I was able to set the default using:

```
$form['field_sem_pledge_currency']['und']['#default_value'] = 'currency_bitcoin';

```

---
Tags: forms
---


# Question
Title: Uc_product module for drupal 7 not found
In my Drupal 7 installation, i want to enable the ubercart feeds module but it says :"Requires: Uc\_product (missing), Feeds (enabled), Chaos tools (enabled), Job Scheduler (enabled)" . The problem is i cannot find the uc\_product module in the drupal website, or anywhere, any help?

# Answer
The uc\_product module is part of the Ubercart module. Based on you added as tag to the question, I assume you are using the Drupal Commerce module instead of the Ubercart module. In that case, uc\_product wouldn't be useful, unless you switched over to using the Ubercart module.

The Commerce Feeds module would likely be more useful if you are really using the Drupal Commerce module.
> 1 votes

---
Tags: commerce
---


# Question
Title: How to create missing rules event when user flags a statuses updates?
**The problem:**

Rules events are missing. **EVENT 1. user flagged a statuses** and **EVENT 2. user flagged a fbss\_comment**. Everything is available, just need to add these events. Status updates are created by statuses module. I want to log both events mentioned above using message module, but I Cannot unless and until this event is created. Conditions and actions are available by default.

**Important Note:**

> Statuses is not compatible with flag 3. It works with flag 2. When you install flag 2, status updates will show "like" button in status updates and status comments. Not only this, but you will also be able to see status updates of users you are following, in your status stream, when flagged with "follow" flag. Moreover, if you see rules conditions and actions, you will find out that **"fbss\_comment is flagged"** and **"statuses is flagged"** and similarly actions **"flag a statuses"** and **"flag a fbss\_comment"** are available. I am getting a feeling that the solution might be hidden within the statuses module folder and its submodules. Just need someone who has an eye to see it. Someone said, **"Everything is possible with drupal"**

**What I tried?**

Starting with "user flagged a fbss\_comment" event, I went to file **fbss\_comments\_rules.rules.inc** in the sub-module fbss\_comments. Under `function fbss_comments_rules_rules_event_info()` I pasted,

```
'fbss_comments_flag' => array(
      'label' => t('User flags a comment on a status'),
      'group' => t('Statuses Comments'),
      'variables' => array(
        'comment' => array(
          'type' => 'fbss_comment',
          'label' => t('The status comment.'),
        ),
      ),
    ),

```

Then under `function fbss_comments_rules_add_action` I added,

```
function fbss_comments_rules_flag_action($cid, $sid, $message, $uid) {
  fbss_comments_flag_comment($cid, $sid, $message, empty($uid) ? $GLOBALS['user']->uid : $uid);
}

```

Note: I do not know what I was doing. I just did it as a trial and error.

**Message type Export**

```
{
  "name" : "scomments_liked",
  "description" : "Status comments liked",
  "argument_keys" : [ "@scomments_liked_user", "!scomments_liked_statuses_url" ],
  "argument" : [],
  "category" : "message_type",
  "data" : {
    "token options" : { "clear" : 0 },
    "purge" : { "override" : 0, "enabled" : 0, "quota" : "", "days" : "" }
  },
  "language" : "",
  "arguments" : null,
  "message_text" : { "und" : [
      {
        "value" : "@scomments_liked_user liked your comment on the \u003Ca href=\u0022!scomments_liked_statuses_url\u0022\u003EStatus Update\u003C\/a\u003E",
        "format" : "plain_text",
        "safe_value" : "@scomments_liked_user liked your comment on the \u003Ca href=\u0022!scomments_liked_statuses_url\u0022\u003EStatus Update\u003C\/a\u003E"
      }
    ]
  },
  "rdf_mapping" : []
}

```

**Rules Export**

```
{ "rules_statuses_comments_flag" : {
    "LABEL" : "Statuses comments flag",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "statuses" ],
    "REQUIRES" : [ "fbss_comments_rules", "rules" ],
    "ON" : { "fbss_comments_flag" : [] },
    "DO" : [
      { "fbss_comments_rules_load_action" : {
          "USING" : { "cid" : [ "comment:cid" ] },
          "PROVIDE" : { "comment_loaded" : { "comment_loaded" : "Loaded status comment" } }
        }
      },
      { "entity_query" : {
          "USING" : {
            "type" : "user",
            "property" : "uid",
            "value" : [ "comment-loaded:uid" ],
            "limit" : "1"
          },
          "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
        }
      },
      { "entity_create" : {
          "USING" : {
            "type" : "message",
            "param_type" : "scomments_liked",
            "param_user" : [ "entity-fetched:0" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:arguments:scomments-liked-user" ],
          "value" : "[site:current-user]"
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:arguments:scomments-liked-statuses-url" ],
          "value" : "[comment:comment-status-url]"
        }
      }
    ]
  }
}

```

**Rules Export based on Nial Murphy's answer**

```
{ "rules_user_flagged_statuses" : {
    "LABEL" : "User flagged statuses update",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "statuses" ],
    "REQUIRES" : [ "fbss_rules", "rules", "flag" ],
    "ON" : { "flag_flagged_like" : [] },
    "DO" : [
      { "fbss_rules_load_action" : {
          "USING" : { "sid" : [ "flagged-status:sid" ] },
          "PROVIDE" : { "status_loaded" : { "status_loaded" : "Loaded status" } }
        }
      },
      { "entity_query" : {
          "USING" : {
            "type" : "user",
            "property" : "uid",
            "value" : [ "status-loaded:sender" ],
            "limit" : "1"
          },
          "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
        }
      },
      { "entity_create" : {
          "USING" : {
            "type" : "message",
            "param_type" : "flagged_status",
            "param_user" : [ "entity-fetched:0" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:arguments:statuses-flagged-user" ],
          "value" : "[flagging-user:name]"
        }
      }
    ]
  }
}

```

# Answer
> 3 votes
***Preface - start***

This answer assumes you're using the current version of Flag, i.e. 7.x.-3.x. Though a comment below this answer states:

> Statuses is not compatible with flag 3. It works with flag 2. When you install flag 2, status updates will show "like" button in status updates and status comments. Not only this, but you will also be able to see status updates of users you are following, in your status stream, when flagged with "follow" flag.

***Preface - stop***

---

---

I'm afraid there is **no way** to create either of those Rules Events (as in your question):

* a status update is flagged.
* a status comment is flagged.

At least not if you're using version 7.x.-3.x. of Flag. Read on to understand why ...

Use the Rules UI to have a look at the available Rules Events, located within the ***Flag*** group of events. The number of entries you will find there will vary, but each of them is similar to something like this:

> ***A `thing-ie` has been flagged, under "`something`"***.

Some more details:

* ***`thing-ie`*** refers to a Drupal **entity**, like node, user, group, message.
* ***`something`*** refers to the **title** of the flag, which you specify when you define (create or edit) your flag in administration.

But when you ***add*** a new flag, using `/admin/structure/flags/add`, the very first thing you are enforced to do is "*Select the type of flag to create*" (which will become your ***`thing-ie`***). And the possible options you can select are all **entities**, such as node, user, group, message, comment, etc. However, something that contains "status" cannot be selected, simply because it's missing in that list (and it is missing, because the Statuses module does NOT create entities).

If however, you'd select "comment" in that list (which sounds close to "status comment", worth trying), then in the next step (at `admin/structure/flags/add/comment`), you get another list within **Bundles**, where you can select the bundles that such flag may be used for. The available options in that list are like "ABC comments", whereas "ABC" corresponds to each of your content types. So this won't work either (there is nothing related to "Statuses" that can be selected).

What is above should not be a surprise, simply because of what's mentioned on the Flag's project page (I added the bold markup here):

> ... Using this module, the site administrator can provide any number of flags for nodes, comments, users, and any other type of **entity**.

Again, the Statuses module does NOT create entities, and therefor there is no way to come up with something like:

> ***A Status (= `thing-ie`) has been flagged, under "Some status related title" (= `something`)***.

So for all reasons mentioned above, I think you're asking the wrong question:

* You won't be able to use the Flag module to flag a ***Status***.
* Try to think of anything else related to the Statuses module that you can use for creating some custom Rules Events that you can use to create a log about something that happened related to Status updates or Status comments.

Maybe this helps you somehow: there are 4 Rules Events available for Statuses and 3 Rules Events for Status Comments. Try to use any of those Rules Events, to do what you'd want to do as extra Rules Actions, similar to what you have in mind if there was an answer to your question.

Sorry, but I'm afraid this is as good as it gets.

# Answer
> 3 votes
Umair, have you looked at the patches in drupal.org/node/1787930 and drupal.org/node/1311468 and *maybe* some others ? I got flag 3 working with the status + rules, but not the comments. It could be possible but I didn't want the comments flaggable so I didn't spend any time trying.

For some reason, I can't recreate the order of patches that got me my working module, here it is to download. It lets me create a new flag type for Status which integrates with Rules and then Message. I just tested it on a clean install and when a status was liked, the action fired.

While I wouldn't particulary trust someone to give me a module of Google Drive, Pierre.Vriens can probably vouch for me not being a bad person and if you do wish to use it in production after testing, I'd encourage you to find the combination / order of patches that results in a 45kb statuses.module file and then work from there. From looking at the .info file, I seem to have to started with the Dev release.

Side-note: You should look at the example files included with the Message module. I have some extremely complex Message scenarios where Rules wasn't good enough and it would be good for you to be aware of the added possibilities.

---
Tags: 7, rules, flags, notifications, message-subscribe
---


title: Using views to display complex content

text:
# Question
Title: Using views to display complex content
I am using Drupal 8 to build a little complex website. Here is an example of what the content is like:

Content Types: Books, Chapters, Paragraphs For instance a book content type would contain fields to hold author, cover pic, etc. then the chapter will have a link to the related book, and paragraphs will have links to its related chapter and an ordering number.

Now I'd like to have the website to have pages as following:

* `/books` \- will show all books by cover photo with links to go to the contents
* `/books/<book-name>` \- will show info about a specific book with list of chapters each with a link to go to the content of that chapter
* `/books/<book-name>/<chapter-number>` \- Will show all paragraphs in that chapter

My question is can this be achieved just by the view module that is installed with d8 vanilla? Can I achieve all of this with one view? If multiple views are needed, can they all use the same path structure (/books is common in that case)?

# Answer
> 1 votes
Yes this can be achieved by using views module. And the structure should go something like: a. Content Type Book. b. Content Type Chapter.

Now chapter CT will have node references field of CT Book.

Create a view of books content type which will show all books then create a page within same view with some changed filters to show /books/book-name.

Now create another view with link /books/book-name/chapter-number where book-name will match the node reference field or /books/book-name/ from previous view to get book name.

---
Tags: 8
---


# Question
Title: How come javascript:void(0) is creating a 404 page?
We have a need to have an to have href="javascript:void(0);" so that some action can take place on the page without refreshing the page. HOwever, this is generating a 404 page and we need assistance in how to best get rid of the 404 but also keep the functionality so that the action can take place without page refresh.

Code in question:

```
<a href="javascript:void(0);">Some action</a>

```

# Answer
> 0 votes
If you are writing some JS, you can add something like:

```
$('a#the_link_ID').click(function(event) {
  event.preventDefault(); // This prevents to follow the link.
  // ...
  // Here goes your code.
});

```

---
Tags: 7, theming, nodes, javascript, navigation
---


title: Adding new menu items to hook_menu

text:
# Question
Title: Adding new menu items to hook_menu
I am building a module which already has the function `Mymodule_menu()` at the beginning of the code. I was wondering if it is possible to use `hook_menu_alter()` to add new menu items (i.e. building new pages) somewhere down the code.

What I'm trying to do is build a form module whereas when the user presses "Submit", the code inside the `form_submit()` function will build a new page using the form values the user entered, and then redirects the user to that page.

Is that even possible. Appreciate the help from anyone. Thank you all in advance!

# Answer
No, `hook_menu_alter()` is not thought to dynamically add new routes. As any similar alter hook, it is thought to alter the routes defined from other modules.
It would not work for dynamically adding new routes for the simply fact that, similarly to `hook_menu()` is only invoked in specific cases, for example, when a module is installed, uninstalled, enabled, or disabled.

If you need to have dynamic pages, you need to do what Drupal does for nodes: You define a route with wildcards, which is similar to the node/%node route defined for nodes.
`hook_menu()` has some example for this kind of routes, under *Wildcards in Paths*.

For example, a route definition as the following could be used to serve a page like my-module/1, my-module-2, etc. `mymodule_abc()` would recive the wildcard value as argument, and it could use that argument to access data from a database table, which is essentially what Drupal does when a user visits node/1: It loads the node whose ID is equal to 1 from the node table, and it shows it to the user who requested that page.

```
  $items['my-module/%'] = array(
    'page callback' => 'mymodule_abc',
    'page arguments' => array(1),
  );

```

As side note, as said in *Auto-Loader Wildcards*, instead of my-module/%, you could use my-module/%mymodule\_abc, and `mymodule_abc_load()` will be called every time a page like my-module/1 is accessed, getting the wildcard value (1) as argument; it could then return the object saved in the database from the form submission handler.
See `node_load()` as example. That function returns the object saved in the database from the form submission handler of the node edit form.

Auto-Loader wildcards are helpful when there are more routes that your module defines. For example, the Node module uses them because the routes it defines using wildcards are node/%node, node/%node/edit, and node/%node/delete. Instead of putting the code to load the node in 3 different page callbacks, it puts the code in a single function (`node_load()`) automatically called from Drupal.
> 1 votes

# Answer
From your question it seems, you're trying to add new menu entry in custom module where we should be using `hook_menu`. The only thing to avoid is adding new menu entry in Core or Contributed module(s). `hook_menu_alter` is used in custom module to alter existing menu item defined by Core or Contributed modules.

Below is descripton taken from `hook_menu` API page.

> Define menu items and page callbacks.

Below is descripton taken from `hook_menu_alter` API page.

> Alter the data being saved to the {menu\_router} table after hook\_menu is invoked.
> 0 votes

# Answer
I also found the thread "Sending results of form to new page" which was talking about exactly what I need.
> -1 votes

---
Tags: routes
---


# Question
Title: Can't find the place to add in image caption
I installed image caption module and enable 'Image caption filter' under Home » Administration » Configuration » Content authoring » Text formats.

But I can't the place to add in the image caption.

# Answer
> 1 votes
The project page is somehow missleading and most of the info there is for D6 version. But at the bottom, it clearly states:

```
jQuery caption
  Less module code
  No configuration needed
  Better javascript captioning logic

```

You can also refer to this issue for more info.

---
Tags: 7, media
---


# Question
Title: How to add a region to display only on a specified page?
So, I have a region, which should only display on a specific page. Is there a way to have a page-checking condition in the page template to only display the region on the specified page, or do I need to create a page specific .tpl file which should have the region in it?

The issue I'm having is that region is being added to pages without content in them. This is evident, because the CSS border property for the region is being applied despite their being no content in it. . You can see in the images that there is border applied to the element, which shouldn't be loaded into the page.  Here is the relevant excerpt from my page.tpl

```
<div id="navigation">
  <div class="base-grid-container">
    <?php print render($page['navigation']); ?>
  </div>
</div>

<div id="page">

  <!-- B11: Don't display the message that content is needed on the front -->
  <?php if(drupal_is_front_page()) {unset($page['content']['system_main']['default_message']);} ?>

  <div id="header">
    <div class="base-grid-container">
      <div id="header-left">
        <?php if ($logo): ?>
          <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home" class="header__logo" id="logo"><img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" class="header__logo-image" /></a>
        <?php endif; ?>
      </div>
      <div id="header-right">
        <?php print render($page['header']); ?>
      </div>
    </div>
  </div>

  <div id="main">
    <div id="hero">
      <?php print render($page['hero']); ?>
    </div>

    <div id="content" class="container">
      <div class="base-grid-container">
        <?php print render($page['highlighted']); ?>
        <?php print $breadcrumb; ?>
        <a id="main-content"></a>

        <?php print render($title_prefix); ?>
        <?php if ($title && !drupal_is_front_page()): ?>
          <h1 class="page__title title" id="page-title"><?php print $title; ?></h1>
        <?php endif; ?>
        <?php print render($title_suffix); ?>

        <?php print $messages; ?>
        <?php print render($tabs); ?>
        <?php print render($page['help']); ?>
        <?php if ($action_links): ?>
          <ul class="action-links"><?php print render($action_links); ?></ul>
        <?php endif; ?>
        <?php print render($page['content']); ?>
        <div id="blog_side">
          <?php print render($page['blog_sidebar']); ?>
        </div>
        <div class="blog-feed">
          <?php print $feed_icons; ?>
        </div>
      </div>

    </div>

```

# Answer
So, there's multiple ways to approach this: 1) views theme preprocess functions; 2) creating a page specific tpl; 3) jquery/js hacks to only show the content on the specified pages.

For the sake of maintenance and simplicity, I chose to re-build the page as a basic page and add the necessary views to the page and add the region to a page specific tpl. I chose the basic page option for simplicity as well as simplifying other tasks down the line such as breadcrumbs. I copied the page.tpl.php, and renamed it page--my-node-id.tpl.php and flushed the theme registry, restoring the original page.tpl. Just an FYI, going the node page route forced me to set the display for the article class inserted into the page to none, to keep my styling the same.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: How to exclude current page from Views results when "taxonomy term ID (with depth)" is set?
I have a Views block that has the intention to display all nodes that share the same parent term.

For example:

* Queensland
    + Cairns
    + Brisbane
    + Gold Coast
    + Port Douglas

If I'm on the Cairns page, then it will show all the children of Queensland. The problem with this is, I need to exclude Cairns, as I'm already on this page.

I already tried the solution from "How to list similar products using views in Commerce Kickstart?", but it didn't work. I had an issue where the query preview wouldn't even show, even though I entered the term ID to attempt to get the query.

Any ideas why this would happen?

**Notes**:

* I already entered the term ID to update the preview, but it didn't show anything. If I take the nid filter out, then it works fine, with the caveat that it shows the current page in the results.
* I notice something weird where checking exclude in the nid contextual filter shows all the results including Cairns, yet when I uncheck it, then all the results disappear. Is there a reason this would happen?

# Answer
Thanks for getting back to me with your answers.

In my case, it turns out that, as my view had a sort criteria set for weight of the node, I had to make sure that all the relevant nodes had a unique value for weight set (hope that makes sense!). As this was displaying only nodes for one content type, this ended up being a relatively easy fix.

Thanks
> 0 votes

# Answer
Query Preview will not be show when you add contextual filters.

You will need to add 'nid/termid' in "Preview with contextual filters:"

In short, Contextual filters will take nodeid/termid from URL.
> 1 votes

# Answer
Oops. I had the same kind of issue last year, making this site: http://notonlymakeup.net

There are two steps (as I see you are on the right track):

* Add a contextual filter for taxonomy term: Use default value as taxonomy term ID from content being displayed on the page. After this step, you should be able to see all related nodes which share the taxonomy term field you chose to apply the filter on.
* Add contextual filter for the node being diaplayed: Use default value as content id from the url. This would help you exclude the node being viewed.

Here is a video tutorial: https://www.daymuse.com/blogs/drupal-guide-related-content-term-views

If the tutorial does not help, please export your view and share it with us so that we can try to recreate the scenario and help you figure out what's going wrong.
> 0 votes

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


title: Backup and migrate exhausts memory

text:
# Question
Title: Backup and migrate exhausts memory
I have a new Drupal 8 site, where I installed few minor modules and Commerce 2.0 beta3, but the site has only 2 nodes so far, even the commerce tables are empty.

However even with PHP memory limit set to 2048M it exhausts it all giving me this message:

```
Fatal error: Allowed memory size of 1073741824 bytes exhausted (tried to allocate 10464376 bytes) in /var/www/website/public_html/modules/backup_migrate/vendor/backupmigrate/core/src/Source/MySQLiSource.php on line 347

```

For this example the PHP memory limit was 1024M, I tried database only backup with cashe tables excluded.

I remember being able to run B&M with 256M allocation on D7 and hundreds of nodes, loads of modules and content types.

As I don't see this issue anywhere on the internet or reported as an issue on the module page, I'm left to believe there has to be something specific to what I may have done wrong?

In the log I also find the following (with full error reporting on):

```
Notice: Undefined index: settings_profile_id in Drupal\backup_migrate\Form\BackupMigrateQuickBackupForm->submitForm() (line 84 of /var/www/website/public_html/modules/backup_migrate/src/Form/BackupMigrateQuickBackupForm.php)

```

System specs:

> Ubuntu server 16.04
>
> Running Apache server
>
> With PHP7
>
> Drupal version 8.2.3

**EDIT:**

I found a few extra errors on different tests:

```
Notice: Undefined index: groups in BackupMigrate\Drupal\Config\DrupalConfigHelper::addFieldsFromSchema() (line 91 of /var/www/website/public_html/modules/backup_migrate/src/Config/DrupalConfigHelper.php)

Warning: Invalid argument supplied for foreach() in BackupMigrate\Drupal\Config\DrupalConfigHelper::addFieldsFromSchema() (line 91 of /var/www/website/public_html/modules/backup_migrate/src/Config/DrupalConfigHelper.php)

Notice: Undefined index: #description in BackupMigrate\Drupal\Config\DrupalConfigHelper::addFieldsFromSchema() (line 116 of /var/www/website/public_html/modules/backup_migrate/src/Config/DrupalConfigHelper.php)

```

Where the last one appears twice in a row every error sequence.

Appreciate all help!

Alari

# Answer
I managed to reduce the memory exhaustion with remedying the last edit's errors in the following matter:

I added a not empty check for the "groups" index in the array around the foreach function on the 91-st line of code in DrupalConfigHelper.php

```
static public function addFieldsFromSchema(&$form, $schema, ConfigInterface $config, $parents = []) {
// Add the specified groups.
// Temp fix for "Undefined index: groups..."
if(isset($schema['groups']) && !empty($schema['groups'])){
  foreach ($schema['groups'] as $group_key => $item) {
    // If the group is just called 'default' then use the key from the plugin as the group key.
    // @TODO: make this less ugly.
    if ($group_key == 'default' && $parents) {
      $group_key = end($parents);
    }
    if (!isset($form[$group_key])) {
      $form[$group_key] = [
        '#type' => 'fieldset',
        '#title' => $item['title'],
        '#tree' => FALSE,
      ];
    }
  }
}

```

And fixed the "undefined index #description" error on line 116 by checking if the "#description" index exists, and if not create it with empty value to be processed on the initial 116 line.

```
switch ($item['type']) {
    case 'text':
      $form_item['#type'] = 'textfield';
      if (!empty($item['multiple'])) {
        $form_item['#type'] = 'textarea';
        // Temp fix for "Undefined index #description..."
        if (!isset($form_item['##description'])) {
          $form_item['##description'] = '';
        }
        $form_item['#description'] .= ' ' . t('Add one item per line.');
        $form_item['#element_validate'] = ['BackupMigrate\Drupal\Config\DrupalConfigHelper::validateMultiText'];
        $value  = implode("\n", $value);
      }
      if (!empty($item['multiline'])) {
        $form_item['#type'] = 'textarea';
      }
...

```

Now backup works nicely.
> 0 votes

---
Tags: 8, backups
---


# Question
Title: Filtering date fields in Views - How can I test for NULL
When I add a date field to the filter criteria, I get a choice of operators "Is less than", "Is less than or equal to" etc, but no way to test is or is not NULL.

How do I test for these conditions?

# Answer
I must not have scrolled down far enough. For future reference, if you add a Filter Criterion to a View, and the field in question is a Date, the **Operator** selector allows you the options `Is not empty (NOT NULL)` and `Is empty (NULL)`. But you have to scroll right down the list to find them.

Note this is in Drupal 7 with **Views 3.13**, **Date Views** and **Date API** modules enabled.
> 0 votes

# Answer
For User "Last access" or "Last login" dates the "Is empty (NULL)" option is not available.

For those particular dates, an alternative is to test for "Greater than 1970-01-02".
> 1 votes

---
Tags: views, datetime
---


# Question
Title: Extending forms (or views, or something else?!)
If creating something like a form, but also perhaps any piece of front-end UI, what is the correct approach for adding things like extra Javascript (or HTML, or anything)?

I'm putting together a registration form using the Entity Registration module and would like to know if, say, I wanted to have a 'Delivery address is the same as invoice address' checkbox that dynamically hid/revealed the delivery address part of the form, what would be the Drupal way of achieving that?

# Answer
> 0 votes
You could implement hook\_form\_alter for adding a checkbox field to your form.

The most simple thing to do after that is to handle the display of the form elements with JS/CSS (checked or not). You have to handle the validation of the different submissions of the form (with or without the delivery address part).

Here you can find a tutorial for adding custom validation to a form.

For the JS/CSS part, you can put your code in the main files of your theme, or add specific files for this form. Check this answer for the second solution.

---
Tags: javascript
---


# Question
Title: Print image field with multiple entries from field in twig template
I have a twig template for a custom content type. And it is able to render most fields just fine, but I am unable to print an image field with multiple images.

node--mycontenttype.html.twig contains

```
{{ content.field_mytitle }}
{{ content.field_myheaderimage }}
<div class="row expanded">
    {% for galleryimage in content.field_gallery_images %}
           <div class="gallery-image-item"> {{ galleryimage }} </div>
    {% endfor %}
</div>

```

content.field\_mytitle and content.\_field\_myheaderimage outputs the title and image just fine. But when I use the for loop

```
    {% for galleryimage in content.field_gallery_images %}
           <div class="gallery-image-item"> {{ galleryimage }} </div>
    {% endfor %}

```

I receive an error

```
Exception: Object of type Drupal\node\Entity\Node cannot be printed. in Drupal\Core\Template\TwigExtension->escapeFilter() (line 443 of core/lib/Drupal/Core/Template/TwigExtension.php).

```

When I just use

```
{{ content.field_gallery_images }}

```

It's able to output each image, but this does not allow me to wrap each item in divs and add content to each one.

# Answer
Print the image field in the node template like any other field:

```
{{ content.field_gallery_images }}

```

And then use a field twig to loop through multiple field items:

**field--field-gallery-images.html.twig**

```
<div class="row expanded">
  {% for item in items %}
    <div class="gallery-image-item">{{ item.content }}</div>
  {% endfor %}
</div>

```
> 10 votes

# Answer
On D8 I was able to make a foreach loop on my images in a way to generate a carousel.

```
<!-- Wrapper for slides -->
  <div class="carousel-inner" role="listbox">
    {% for i in 0..content.field_accueil_image_slide|length %}
     {%if content.field_accueil_image_slide[i]['#item'].entity.uri.value != "" and content.field_accueil_image_slide[i]['#item'].entity.uri.value is not empty %}
        <div class="item {{ (i == 0) ? 'active' : '' }}" style="">{{ content.field_accueil_image_slide[i]}}</div>
     {%endif%}
    {%endfor%}
  </div>

```
> 2 votes

---
Tags: theming, 8, media
---


# Question
Title: Adding array of objects to javascript from PHP
This is a part of my script in template file where php code is used to generate js field of objects:

```
<?php $count = count($events); $counter = 1; ?>

<script>
  var events = [

  <?php foreach($events as $event) { ?>

    {
      date: '<?php echo $event['date']; ?>',
      linkTarget: "_blank",
      content: "<?php echo $event['content']; ?>",
      class: "<?php echo $event['class']; ?>"
    }
    <?php if($counter!=$count) { echo ','; $counter++; } ?>
  <?php } ?>

  ];
<script>

```

I know that we can add js variable by `drupal_add_js(array('myModule' => array('key' => 'value')), 'setting');` but how can we create the same js array as in example above in order not to use php code in js?

# Answer
You can pass an array to JS like this:

`drupal_add_js(array('my_module' => array('events' => $events)), 'setting');`

In javascript you can get the values like this:

```
Drupal.settings.my_module.events;

```
> 2 votes

# Answer
You can try something like this in your custom module:

```
// build your associative array into $events variable
$events = json_encode(join(',', $events);
drupal_add_js(array('custom_module' => array('events' => $events)), 'setting')

```

And then in your template:

```
<?php print $events; ?>

```
> 0 votes

---
Tags: 7, javascript
---


# Question
Title: Control fields of views on different pagination
I use pager (as **1** 2 3.. 9 \>\>Next \>\>Last) in a views and displaying only 3 articles on one page with the fields title and body.

**I need to hide body of the articles on 3-6 pages.**

**Note:** *It should be done by only using views or views handler but not with css or JS.*

Kindly guide me to do that.

Thanks

# Answer
> 0 votes
The simplest solution I can think of is this:

Here's the code:

```
function test_views_pre_render(&$view) {
  // Current page in Views is 0 based.
  $currentPage = $view->query->pager->current_page + 1;

  // Exit early if not in the 'to be modified' page.
  if ($currentPage < 3 || $currentPage > 6) {
    return;
  }

  // Exclude the body from display.
  $view->field['body']->options['exclude'] = TRUE;
}

```

---
Tags: views
---


# Question
Title: In a twig, how do I access different fields of a specific content type in a taxonomy term page
I have some `taxonomy` terms like `Computer and Accessories`, `Games`, `Furniture` etc. which I am able to access as `/camera-and-accessories`, `/furniture` and so on. These taxonomy terms are associated with my Product content type.

A `taxonomy page` is always displaying default `Product title` and `Body` fields. But I want to customize this page so that it displays additional fields like `field_product_price`, `field_product_photo` from my Product content type. I was hoping for something like `{{ content.parent }}` but I don't think such a thing does not exist (yet!)

**Template suggestion by Twig debug**

```
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'taxonomy_term' -->
<!-- FILE NAME SUGGESTIONS:
   * taxonomy-term--1.html.twig
   * taxonomy-term--category.html.twig
   x taxonomy-term.html.twig
-->
<!-- BEGIN OUTPUT from 'themes/custom/ezone/templates/taxonomy-term.html.twig' -->

```

According to the above output I first overrode default `taxonomy-term.html.twig` with `taxonomy-term--category.html.twig`. In `taxonomy-term--category.html.twig` I did not put anything but just "Hello World!" to check whether this file is being hit. After rebuilding cache the page renders this static text but surprisingly along with that the actual content also got rendered on the page, which I don't know why.

I deleted `taxonomy-term--category.html.twig` and copied `taxonomy-term.html.twig` from `stable` theme to my theme's templates folder. Removed all entries in that file and again tried the same thing with a static text block. Same thing happened again!

**Somebody please help with these.**
1. How to access fields of a content type on a `taxonomy term` page
2. Why overridden templates shows taxonomy content when custom template has nothing written in it.

I am sorry if above questions looks stupid or childish. I am a newbie to Drupal.

# Answer
> 3 votes
When you display a taxonomy term the output is produced by this View:

**admin/structure/views/view/taxonomy\_term**

The taxonomy term itself is in the header

```
HEADER
Global: Rendered entity - Taxonomy term (Global: Rendered entity - Taxonomy term)

```

and uses the taxonomy term template shown in your question, where you have only access to the fields of the term, not the content.

The format of the content is configured in the main part of the View. Default is to display the content as Teaser:

```
FORMAT
Format:Unformatted list | Settings
Show:Content | Teaser

```

If you want to change the fields, you can customize the Teaser in UI:

**admin/structure/types/manage/article/display/teaser**

Or in this node template (this targets the View, so it would also work, if you changed the view mode):

**node--view--taxonomy-term.html.twig**

Or switch to a field based View and configure the fields inside of the View.

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


# Question
Title: How to correct my rule to prevent duplicate taxonomy terms to be created?
This is a followup of my question at How to create a rule to combine the terms of 2 fields to create a new term and store it in a 3rd field?.

How can I prevent that each time a node is viewed, it creates duplicate taxonomy terms, as shown in this example:

Any suggestions?

# Answer
> 2 votes
# Part 1 - About the actual challenge

I'm assuming you're using a rule that looks similar (equal?) to the rule in the accepted answer in that related question, which looks like so:

```
{ "rules_improved_combination_of_taxonomy_terms" : {
    "LABEL" : "Improved combination of taxonomy terms",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view--article" : { "bundle" : "article" } },
    "DO" : [
      { "drupal_message" : { "message" : "[node:field-a][node:field-b]" } },
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "[node:field-a][node:field-b]" },
          "PROVIDE" : { "variable_added" : { "variable_added" : "Added variable" } }
        }
      },
      { "entity_create" : {
          "USING" : {
            "type" : "taxonomy_term",
            "param_name" : "[variable-added:value]",
            "param_vocabulary" : "tags"
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "entity_save" : { "data" : [ "entity-created" ], "immediate" : "1" } },
      { "data_set" : { "data" : [ "node:field-c" ], "value" : [ "entity-created" ] } },
      { "entity_save" : { "data" : [ "node:field-c" ], "immediate" : "1" } }
    ]
  }
}

```

The above rule does not perform any verification if the term `[node:field-a][node:field-b]` (= the value that gets stored in "field C") already exists. Instead each time the Rules Actions are triggered (ie each time "an Article is viewed"), it unconditionally creates that term (which may already exist) another time. So that is why you get all those duplicate terms (like `helloworld` in your example).

The solution (fix) for that is that you add some extra logic in your rule to only perform the 3rd (= `entity_create`) and 4th (= `entity_save` of the created term) Rules Action so that those 2 Rules Actions are only performed if the term does not exist yet.

There are basically 2 solutions/approaches to implement such exta logic:

* Use the the Conditional Rules module, which allows to include the equivalent of a Rules Condition within a Rules Action.
* Move those 2 Rules Actions to an appropriate (new) Rules Component, in which you can add the required Rules Conditions. And then in your rule you just call (perform) that Rules Component.

The advantage of the first solution is that the entire logic is contained in a single Rule, though (disadvantage) it requires yet another module.

With either of both solutions, you basically improve this rule with something like "If the term for field C does not exist yet, then let's quickly create it now, so that we can use that term as the value for field C".

Easy enough, no? ... All you need to know is how to actually perform a check in Rules to verify "If that term is already contained in the list of terms of your taxonomy".

# Part 2 - Solution using Conditional Rules

Below is a possible solution using Conditional Rules. The improved rule looks like so:

```
{ "rules_combine_taxonomy_terms_without_creating_duplicates" : {
    "LABEL" : "Combine taxonomy terms without creating duplicates",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional" ],
    "ON" : { "node_view--article" : { "bundle" : "article" } },
    "DO" : [
      { "drupal_message" : { "message" : "Value of term for field C will be set to: \u003Cstrong\u003E[node:field-a][node:field-b]\u003C\/strong\u003E." } },
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "[node:field-a][node:field-b]" },
          "PROVIDE" : { "variable_added" : { "combined_term" : "Combined Term" } }
        }
      },
      { "entity_query" : {
          "USING" : {
            "type" : "taxonomy_term",
            "property" : "vocabulary",
            "value" : [ "node:field-a:vocabulary" ]
          },
          "PROVIDE" : { "entity_fetched" : { "existing_terms" : "Existing Terms" } }
        }
      },
      { "variable_add" : {
          "USING" : { "type" : "boolean", "value" : "0" },
          "PROVIDE" : { "variable_added" : { "new_term_exist" : "New term exists" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "existing-terms" ] },
          "ITEM" : { "current_term" : "Current term" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "text_matches" : { "text" : [ "current-term:name" ], "match" : "[combined-term:value]" } },
                  "DO" : [
                    { "data_set" : { "data" : [ "new-term-exist" ], "value" : "1" } },
                    { "data_set" : { "data" : [ "node:field-c" ], "value" : [ "current-term" ] } },
                    { "drupal_message" : { "message" : "Term \u003Cstrong\u003E[node:field-a][node:field-b]\u003C\/strong\u003E already exists (no need to create it now)." } }
                  ]
                }
              ]
            }
          ]
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "data_is" : { "data" : [ "new-term-exist" ], "value" : "0" } },
            "DO" : [
              { "entity_create" : {
                  "USING" : {
                    "type" : "taxonomy_term",
                    "param_name" : "[combined-term:value]",
                    "param_vocabulary" : "tags"
                  },
                  "PROVIDE" : { "entity_created" : { "term_created" : "Created term" } }
                }
              },
              { "entity_save" : { "data" : [ "term-created" ], "immediate" : "1" } },
              { "data_set" : { "data" : [ "node:field-c" ], "value" : [ "term-created" ] } },
              { "drupal_message" : { "message" : "Term \u003Cstrong\u003E[node:field-a][node:field-b]\u003C\/strong\u003E did not yet exist and was created just now." } }
            ]
          }
        ]
      },
      { "entity_save" : { "data" : [ "node:field-c" ], "immediate" : "1" } },
      { "drupal_message" : { "message" : "\u003Cstrong\u003ENote\u003C\/strong\u003E: After updating field A or B, a page refresh is needed to actually SEE a value of field C = \u003Cstrong\u003E[node:field-a][node:field-b]\u003C\/strong\u003E." } }
    ]
  }
}

```

Even though it's not an obvious rule to digest (I think), it mostly does these things:

* Perform an `entity_query` to create a list of existing terms (stored in `existing_terms`), for the vocabulary used in Field A (as per the `node:field-a:vocabulary` in that `entity_query`). So the assumption is that Field A and Field C use the same vocabulary (there are no details about that in the question). If that's not the case, just replace that vocabulary with whatever fits, or maybe just hardcode it.
* Calculate a boolean variable with machine name `new_term_exist`, which verifies if the term to be saved in Field C already exists.
* Set the value for field C to an existing term (if it already exist).
* Create the term for field C on the fly (if it does not yet exist) and then use that to set the value for field C.

However, there is 1 minor detail to be aware of, as detailed in the message of the very last Rules Action ... For anybody interested in addressing that (to make that message obsolete), please post an extra answer and feel free to use this rule here to start from.

**Note**: even though, in theory, you should also be able to use Rules Components instead of Conditional Rules (refer to the answer to "What's the alternative to using the Conditional Rules module?" for more details on that), the key challenge with that is that you run in a tough-to-debug issue when passing values to such Rules Components, in the cases where the value of Field C is still blank (eg when creating a new node).

PS: **Q:** How do you eat an elephant? **A**: 1 bite at a time ... (though there is ***only 1*** bite left of it now).

# Answer
> 3 votes
I think the Rules condition, **URL Alias Exists** is perfect for this scenario if put into two rules, one for *yes* and one for *no*. Taxonomy terms will have an alias once created so it's easy to check if `/taxonomy_vocabulary/[A][B]` exists before doing anything with `C`.

When the node is created or updated, the rules check for A and B added together to see if that AB taxonomy term already exists since every taxonomy term has an alias. If it already exists *(yes)*, the rule fetches it and uses it and if not *(no)*, it creates it.

For example, the first time a node is created or updated with A: New and B: York, "/cities/newyork" wouldn't exist so we create it. The next time we use A: New and B: York, the rule finds the existing term and fetches it.

The below assumes a single-language taxonomy vocabulary. **The nodes can be multi-lingual.**

```
PSUEDO-RULES

Rule 1 - Taxonomy C exists
Events: Node is saved / Node is updated
Condition: URL Alias Exists > Use replacement patterns to join A and B in Value field
              eg. taxonomy/[a][b]
Action: Create variable > [a][b]
Action: Fetch Entity by Property > Taxonomy Term > Name > Created Variable
Action: Set Data Value > C: Fetched Entity:0

Rule 2 - Taxonomy C doesn't exist yet
Events: Node is saved / Node is updated
Condition: NOT URL Alias Exists > Use replacement patterns to join A and B in Value field
Action: Create entity > Taxonomy Term > "AB" using replacement patterns
              (not the drop-down list!)
Action: Set Data Value > C: Created Entity

```

Rules exports
To test these rules, you'll need a Drupal install with Articles, Tags and no Pathauto messing with the urls.
Add three term reference fields to Article for the Tags Vocabulary.

```
Machine Names
field_tax_tags_a
field_tax_tags_b
field_tax_tags_c

```

Rule 1 - AB Term exists so fetch it

```
{ "rules_exists" : {
    "LABEL" : "Exists",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "path" ],
    "ON" : {
      "node_insert--article" : { "bundle" : "article" },
      "node_update--article" : { "bundle" : "article" }
    },
    "IF" : [
      { "path_alias_exists" : { "alias" : "tags\/[node:field-tax-tags-a][node:field-tax-tags-b]" } }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : {
            "type" : "text",
            "value" : "[node:field-tax-tags-a][node:field-tax-tags-b]"
          },
          "PROVIDE" : { "variable_added" : { "variable_added" : "Added variable" } }
        }
      },
      { "entity_query" : {
          "USING" : {
            "type" : "taxonomy_term",
            "property" : "name",
            "value" : [ "variable-added" ],
            "limit" : "1"
          },
          "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
        }
      },
      { "data_set" : { "data" : [ "node:field-tax-tags-c" ], "value" : [ "entity-fetched:0" ] } }
    ]
  }
}

```

Rule 2 - AB Term doesn't exist so create it

```
{ "rules_doesn_t_exist" : {
    "LABEL" : "Doesn\u0027t exist",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "path" ],
    "ON" : {
      "node_insert--article" : { "bundle" : "article" },
      "node_update--article" : { "bundle" : "article" }
    },
    "IF" : [
      { "NOT path_alias_exists" : { "alias" : "tags\/[node:field-tax-tags-a][node:field-tax-tags-b]" } }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "taxonomy_term",
            "param_name" : "[node:field-tax-tags-a][node:field-tax-tags-b]",
            "param_vocabulary" : "tags"
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : { "data" : [ "node:field-tax-tags-c" ], "value" : [ "entity-created" ] } }
    ]
  }
}

```

After that, create and edit some articles only using A and B. C matches and instead of duplicating, will fetch the existing term.

---
Tags: 7, taxonomy-terms, rules
---


# Question
Title: How can I recreate the default frontpage view?
I accidentally deleted my default frontpage view I was using on a Drupal 8 site, and I can't find how to either recreate it or which path to set on a new view to have it as front page.

How can I achieve this?

# Answer
You can recreate new view with any path and then just make it your default front page.

Steps:

1. Log into your Drupal 7 dashboard
2. In the top menu, click Configuration
3. Under System click Site Information
4. Under FRONT PAGE, adjust the Default front page setting **(Put you new page view path)**
5. Click the Save Configuration button at the bottom of the page to save these settings.

Follow this link for proper steps with images.
> 1 votes

# Answer
Find the file **/core/modules/node/config/optional/views.view.frontpage.yml**

Next import its content by pasting this at **/admin/config/development/configuration/single/import**
> 4 votes

---
Tags: views
---


title: How it's safe migrate fid and uid?

text:
# Question
Title: How it's safe migrate fid and uid?
I'm working on a content migration between a d7 and a d8 sites. I'm trying to use migration and I've a doubt: the d8 site is empty and every user, content, file, term will be filled with migration from the d7 installation.

Is it safe to migrate also ID (uid, nid, tid, fid) from d7 to d8? Or is better to migrate UUIDS and use them to match content relations?

# Answer
The core migrations from D6/D7 to D8 do preserve IDs by default. But, it is fragile, you have to be careful not to create *any* content on the D8 side before you've completed all migration. Unless you depend on public-facing addresses (e.g., /node/\[nid\]), it's simpler to just allow IDs to be assigned on migration. See https://www.drupal.org/node/2748609#comment-11293627 for more.
> 2 votes

---
Tags: 8, migrations
---


title: Drush config-import/export

text:
# Question
Title: Drush config-import/export
I'am trying to export menu items but the generated yaml files does not contains any reference to this elements. All menu files look like this:

```
uuid: 12....04
langcode: en
status: true
dependencies: {  }
id: how-works
label: 'How it works'
description: 'Menu description'
locked: false

```

Is there a way to export/import menu elements?

# Answer
> 0 votes
Menu items, content nodes, taxonomy terms, etc. are not handled through the Configuration API. Configuration API is meant to handle... well, configuration.

A fast Google search returned Config menu link. I have not tested that module, but if it works, it should do what you need there.

# Answer
> 0 votes
Well I found this other question that also explains that menus are not exportable. It also says that I may write menus in `.links.yml` that makes it versionable from git. It is not really import/export, but it works for me.

---
Tags: 8, drush, configuration
---


title: curl nor wget was found

text:
# Question
Title: curl nor wget was found
When I use drush to download modules, I get this weird error:

`drush dl registry_rebuild
exec(): Unable to fork [wget --version 2>&1] exec.inc:150 [warning]
exec(): Unable to fork [curl --version 2>&1] exec.inc:150 [warning]
exec(): Unable to fork [which curl 2>&1] exec.inc:150 [warning]
wget nor curl executables found. [error]`

which wget gives me /usr/bin/wget and which curl gives me /usr/bin/curl. /usr/bin/ is in my PATH. This seldom works if I do drush cc drush. How do I solve this permanently?

# Answer
> 1 votes
On Centos, to install wget:

```
sudo yum install wget

```

To install curl the following should suffice:

```
sudo yum install php-curl
sudo service httpd restart

```

++++++++++++++++++++ EDIT +++++++++++++++++++++++++

According to this post, "unable to fork" errors are likely to result from too many processes running. They recommend increasing the limit like so:

```
sysctl -w kern.maxprocs=1000000

```

# Answer
> 0 votes
On nginx on aws, I've found the php-fpm can get out of hand. To tell if that's happened, `ps -ef |grep php-fpm|wc -l`. If the number is more than 10 or so, you can reset php-fpm with: `sudo service php-fpm restart`

# Answer
> 0 votes
I fix the "Unable to fork could" with Drush by restarting my server. I think @Ollie's anwser is right.

---
Tags: drush
---


# Question
Title: How to use official documentation to figure out what namespace to use
I'm attempting to create a taxonomy term inside a Form plugin like so

```
$term = Term::create([
    'name' => 'my taxonomy term',
    'vid'  => 'vocabulary_to_put_it_in',
]);
$term->save();

```

When I do so I receive an error

> Fatal error: Class 'Drupal\my\_module\Form\Term' not found

My gut is telling me that I'm not including the namespace like I should but I'm not sure how to actually figure out how to discover that. I'm creating nodes by using

```
\Drupal\node\Entity\Node::create

```

And I receive no errors for that. I'm assuming that it's because I'm using \Drupal\node\Entity\ before it, but I was only able to figure that out by looking at examples. I looked at this page https://api.drupal.org/api/drupal/core%21modules%21taxonomy%21src%21Controller%21TaxonomyController.php/class/TaxonomyController/8.1.x and saw the class hierarchy class \Drupal\taxonomy\Controller\TaxonomyController but when using

```
\Drupal\taxonomy\Controller\TaxonomyController\Term::create

```

I still get an error saying

> Fatal error: Class 'Drupal\taxonomy\Controller\TaxonomyController\Term' not found

If it is true, that the reason why it is failing, is because I'm not including the right namespace, then how do I use the official documentation to figure out what I should be including? Or is there something else I'm missing entirely?

# Answer
I was able to discover the namespace by finding the documentation for the Term class here.

https://api.drupal.org/api/drupal/core%21modules%21taxonomy%21src%21Entity%21Term.php/class/Term/8.1.x

And on that page there's a namespace section that said Drupal\taxonomy\Entity so I used

```
\Drupal\taxonomy\Entity\Term::create

```

and that worked.

So I believe in order to find the right namespace to use, you have to find the page for the class that is using the method. In this case Term. And then find the namespace section and put that before the class when you are using a method of it.

(This might be obvious to everyone else, but it took me a bit to figure out)
> 3 votes

---
Tags: forms, 8, taxonomy-terms
---


# Question
Title: How to get custom indexed field to show up in view?
I have a custom field I have added to my search index, and I have confirmed that there is data being indexed there, and I can query against it in a view using my global index. But when I add the custom field as a display field, the field doesn't render.

I'm noticing the same behavior when I add the urls with the AddURL processor.

I can see the fields are there, and I can query against them with filters, but when added to a view as a field, they won't display.

I noticed that if I go into SearchApiQuery.php on line 527 and change this:

```
foreach ($result->getFields(FALSE) as $field_id => $field) {

```

to this

```
foreach ($result->getFields() as $field_id => $field) {

```

Then the view displays the results, but it also causes a lot of lag, and is obviously a hack I don't want to do.

What am I doing wrong? Why can't I display a custom solr indexed field in a view?

# Answer
> 2 votes
It took a while, but I figured the issue out.

You have to set your solr server configuration within Drupal to return fields at /admin/config/search/search-api/server/

Here's the text on that settings page:

"Retrieve result data from Solr: When checked, result data will be retrieved directly from the Solr server. This might make item loads unnecessary. Only indexed fields can be retrieved. Note also that the returned field data might not always be correct, due to preprocessing and caching issues."

Basically, if you want to pull data directly out of solr, you have to have this checked. I don't think you can do this at the view level.

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


title: 8 - Hide title in render array

text:
# Question
Title: 8 - Hide title in render array
i must render entities but it render the node title / author / creation\_date etc... and i want to show only fields of my node. In D7 we can set a #access property to not render the field but in D8, i don't know how to do this. Can you help me please ?

I render my entities by this way :

```
// Get all content observable
            $query = \Drupal::entityQuery('node');
            $query->condition('status', 1);
            $query->condition('type', $ctype_observable);
            $query->condition('field_scm_tag', $this->getPluginDefinition()['tag']['machine_name']);
            $entity_ids = $query->execute();
            $entities = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($entity_ids);

            // render the entity
            $view_mode = 'default';
            $view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
            foreach ($entities as $nid => $entity) {
                $build = $view_builder->view($entity, $view_mode);
                //kint($build['#node']);
                dsmr($build['#node']->get('title'));
                $build['content'][$nid]['#markup'] = render($build);
            }

```

# Answer
> 2 votes
This doesn't work anymore like this and the reason is render caching.

After calling view(), you only get a minimal render array, that will use #pre\_render callbacks to complete itself in case of a cache miss. On a cache hit, it will return the cached HTML, without having to build all the fields.

The information you want to hide is in the template, both the title and the authored by information (which can be hidden for a node type for all bundles but not per view-mode).

The correct way to deal with that is to define your own view mode (default is wrong anyway, you should use 'full', not 'default', default is the fallback view display, not a view mode).

For that view mode, you can then provide a template/preprocess hook/hook\_entity\_view/hook\_entity\_view\_alter hook, use any of those or a combination of it to achieve the desired result. To not show the authored by information, you can for example unset `$variables['display_submitted']` as it uses that in the default `node.html.twig` template. Or provide a template suggestion for your view mode that removes that part completely. Both work, a preprocess is a bit easier from a module.

The important part is that you need your own view mode for that unless it is ok that full should never show that information, then that's fine too. The default cache key is entity type/entity id/view mode. There are other ways, you could add a cache context or you could even add another cache key, but you still need to do it within those hooks/template and the most obvious way to flag it for that is a view mode, that's what they exist for.

---
Tags: 8, entities
---


# Question
Title: How to change the image style used in a field in specific view results?
In Drupal 7 I used `hook_views_pre_render()` to update the image style for specific results. I'm trying to do the same for a view in Drupal 8 but I don't have the same options available in the field.

An example of the code I used before: `$view->result[4]->field_field_image[0]['rendered']['#image_style'] = 'image_style_name';`

There's no longer a 'rendered' array, just an ImageItem object with the target\_id, title, width and height.

# Answer
> 1 votes
The bad news is that you can't use that approach anymore. Due to the performance improvements like this one, fields are all rendered via `#pre_render` callbacks, and run through the same build process as normal entity rendering.

The good news is that `hook_entity_display_build_alter()` will run, the very same hook that runs for displaying an entity.

Views doesn't pass any additional context to this hook. Depending on how you were deciding which one to alter, you may still be able to accomplish this.

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


# Question
Title: Importing a bunch of users from csv spreadsheet file into Drupal 8
I have a large csv spreadhseet list of users with name, email, phone and username. The passwords can be the same for all as they will be blocked anyway.

I know there is an old tutorial of importing users via the migrate api in drupal 8 from here: http://www.metaltoad.com/blog/migrating-users-drupal-7-to-drupal-8

But that article is from 2014. Is there a new upto date way of doing this without the need to create a custom module? Is there a simple gui interface to get this imported? Or is there no choice but to make that custom migrate module?

# Answer
> 3 votes
Check out the Migrate Source CSV

I know that it uses drush and can import nodes through mapping it in a twig file and I'm pretty sure that it supports users too.

Full steps located here.

---
Tags: 8, users, migrations, importing-exporting
---


# Question
Title: Pass exposed filters values from one view to another view
I have a view that lists some nodes, has some exposed filters, like countries and search and a registered path **without** any contextual filters.

I also have a second view with the same exact exposed filters, but with a different registered path, again **without** any contextual filters.

At the first view I have a link that points to that second view.

The question is how can I pass the filters values (if any) selected from the first view to that second view when I click to the link of the first view?

After trying some things didn't managed to solve that but only by using the `$_SESSION` variable, however I'm not sure how optimal is this?!

# Answer
Option 1: Views Global Filter. I've never used it but it sounds like a good but very heavy solution.

Option 2: Create the url for the second view dynamically with jQuery every time the exposed filters are changed. If you disable Ajax in the second view, you can see the url change and then use that as basis. The url will still work if you switch on Ajax again.

Option 3: Tokenise the exposed filters and create the link like option 2 in the header or footer. There seems to be a couple of modules / sandboxes that could help.

I'd probably pick option 2 but of course, there are probably other solutions like your session variable and some views hook.
> 1 votes

---
Tags: 7, views
---


# Question
Title: What to do about an 'illegal Choice' error in views?
I have a view with an exposed filter and it isnt working correctly. I am trying to change the options on the exposed filter but all that happens is I get is 'An illegal choice has been detected. Please contact the site administrator. ' I cant find anything logging anywhere. This error is incredibly vague and tells me nothing about which choice is illegal or what legal options may be.

Is there somewhere this may be logged that I am not looking?

# Answer
> 0 votes
> 'An illegal choice has been detected. Please contact the site administrator. '

This type of issue generally arises when, for example, you have 2-3 select list, select list 'second' is dependent on 'first' select list. Now if you get empty result (say) in your first select list, second select list will not get populated correctly and throw this type of exceptions.

This is just an example so that you might get an idea, the sequence of selecting values is not right.

Try the whole procedure again, and this message will get disappeared.

---
Tags: views
---


# Question
Title: How to get the original value of a field that is inside a field collection?
I can get the entity reference field node id from my field collection like this:

```
function mymodule_node_update($node){

    if ($node->type == 'article'){

    $node_wrapper = entity_metadata_wrapper('node', $node);

        $before = array();

        foreach ($node_wrapper->field_collection_ingredients->value() as $key => $field_collection_wrapper) {

          $before[$key] = $field_collection_wrapper->field_ingredient[LANGUAGE_NONE][0]['target_id'];

        }
  }

```

Doing:

```
$before[$key] = $field_collection_wrapper->original->field_ingredient[LANGUAGE_NONE][0]['target_id'];

```

Causes an error.

---

Basically I have an entity reference, which allows unlimited values, inside the the field collection.

When someone removes a value from the entity reference field, I need to know which value was removed as I need the Node ID to update that node that was removed from the entity reference.

# Answer
> 1 votes
Try comparing `field_collection_ingredients` field value of `$node->field_collection_ingredients[LANGUAGE_NONE]` and `$node->original->field_collection_ingredients[LANGUAGE_NONE]`, this will give exactly which field collection was removed, you can then try loading that field collection (*see note below*) and then load `$fc->field_ingredient[LANGUAGE_NONE][0]['target_id']`; field value to update *Node* referenced in `field_ingredient` field.

***Note:*** If your node does not has revision enabled, the removed field collection will be removed from Drupal database as well, which will cause the error when trying to load the Field Collection Entity. So you might need to enable revision for your main node, to make sure that if field collection is removed from `field_collection_ingredients` field, it will not get removed from Database.

# Answer
> 0 votes
If i understand your question in the right way field collections create entities. So you can try to use hook\_entity\_update to track when your field collection entities are updated (i mean when someone deletes values from entity reference field of your field collection) `hook_entity_update($entity, 'field_collection_item')`. You also can use `entity_metadata_wrapper('field_collection_item', $your_field_collection_entity_id)` to get data from field collection entity.

---
Tags: 7, entities
---


# Question
Title: Keep menu open for custom content entities
I am writing modules that define content entities in Drupal 8. The Drupal console creates the menu items for the list builder. I would like the menu to stay open (having the `menu-item--active-trail` class) when I access the view or edit form page of, say, the content entity with id 4.

The breadcrumb navigation works perfectly out of the box, but the menu is completely closed for the content entity with id 4.

I am ok with writing a Menu Plugin or using a contributed module.

# Answer
> 0 votes
My solution turned out to be the contributed module Menu Trail By Path: because I can fine-tune the actual URLs in all of my entities' YAML files, I can define the hierarchy easily.

---
Tags: 8, navigation
---


# Question
Title: Disable pre-emptive validation of empty textfield
On my form I have some fields and I set form\['#required\_error'\] to generate a message on empty fields. Works OK on select and option fields, but not on textfields.

It seems there is a (kind of ajax) validation before, which gives a pop-up with "fill in this field".

How can I disable pre-emptive validation of empty text fields, so that I can generate my onw messages

# Answer
The 'fill in this field' message is browser specific HTML5 error handling. Which is triggered before the form is submitted. Only modern browsers show this, and it may currently not be consistent between browsers.

About this behaviour is an interesting discussion here: https://www.drupal.org/node/1797438.

If you have your own logic in place to assist the user with problems in the form you can disable HTML5 validation altogether by setting the `novalidate` attribute on the `<form>`. More specific is setting the `formnovalidate` attribute on a submit button.

In a hook\_form\_alter you can add the following line:

```
$form['#attributes'] += ['novalidate' => TRUE];

```
> 2 votes

---
Tags: forms
---