# Question
Title: Add 'Or Condition' to specific field in Entity Query
I'm building an entity query and I would like to check if one field contains one string or another. I'm building the query like so.

```
$searchname = 'test';
$searchtype' = 'type_1';

$query->condition('status', NODE_PUBLISHED);
$query->condition('field_type', $searchtype);
$query->sort('created','DESC');

```

However I'd like to check if field\_type is either $searchtype or 'both' I attempted to do so using an orConditionGroup like so

```
$orCondition = $query->orConditionGroup();
$query->condition('status', NODE_PUBLISHED);
$orCondition->condition('status', NODE_PUBLISHED);

$query->condition('field_type', $searchtype);
$orCondition->condition('field_type','both');
$query->condition($orCondition);
$query->sort('created','DESC');
$nids = $query->execute();

```

However it acts like the orCondition isn't being considered at all. Using $orCondition it still does not produce nodes that have 'field\_type' = 'both'. How would you go about checking whether a field contains one string or another in an entity query?

UPDATE: I added the field name to the or condition because I figured I would need to add it to both if I want it checked in both conditions. If there's a way around that, that'd be even better.

UPDATE 2: I made a second attempt using this code but I receive a 504 Timeout error when loading the page

```
$searchtype = 'test';
$query        = \Drupal::entityQuery('node');
$conditionOne = $query->orConditionGroup();
$conditionTwo = $query->orConditionGroup();

$conditionOne->condition('status', NODE_PUBLISHED);
$conditionTwo->condition('status', NODE_PUBLISHED);

$conditionOne->condition('field_type', $searchtype);
$conditionTwo->condition('field_type','both');

$query->condition($conditionOne);
$query->condition($conditionTwo);
$query->sort('created', 'DESC');
$nids = $query->execute();

```

What I'm ultimately trying to accomplish is this logic

(status = true) AND (field\_type = 'foo' or 'both')

# Answer
So, the simplest way to rewrite this, would be:

```
$searchname = 'test';
$searchtype = 'type_1';

$field_types_array = [$searchtype, 'both'];
$query->condition('status', NODE_PUBLISHED);
$query->condition('field_type', $field_types_array, 'IN');
$query->sort('created','DESC');

```

The use of an array for the condition method forces the SQL query to be written as an `IN` query.

Reference documentation: QueryInterface::condition
> 2 votes

---
Tags: 8, entities, database
---


# Question
Title: How to sort the content types/bundles on /node/create page
I want to reorder the list of available content types on the create content page. I have node-add-list.html.twig and entity-add-list.html.twig inside my custom theme template folder. Twig then outputs the array of all types or bundles/content types in alphabetical order. How can I sort this a different way? And can I hard code the links I want in this file or can I output each content type individually?

# Answer
> 5 votes
You can do this in preprocess by overriding this code from *node.module*:

```
function template_preprocess_node_add_list(&$variables) {
  $variables['types'] = array();
  if (!empty($variables['content'])) {
    foreach ($variables['content'] as $type) {
      $variables['types'][$type->id()] = array(
        'type' => $type->id(),
        'add_link' => \Drupal::l($type->label(), new Url('node.add', array('node_type' => $type->id()))),
        'description' => array(
          '#markup' => $type->getDescription(),
        ),
      );
    }
  }
}

```

Or you can replace the foreach loop in the twig template

*node-add-list.html.twig*

```
  <dl>
    {% for type in types %}
      <dt>{{ type.add_link }}</dt>
      <dd>{{ type.description }}</dd>
    {% endfor %}
  </dl>

```

with a hard-coded list:

```
  <dl>
      <dt>{{ types.article.add_link }}</dt>
      <dd>{{ types.article.description }}</dd>
      <dt>{{ types.page.add_link }}</dt>
      <dd>{{ types.page.description }}</dd>
  </dl>

```

# Answer
> -1 votes
Unfortunately not so easy. Please take a look, I've already answered that in a previous question.

How to modify the page at admin/structure/types?

---
Tags: 8, nodes
---


# Question
Title: How to resolve the problems encountered when moving from local to server?
Which things do we need to be aware of and change when moving a site (in Drupal 8) from a local environment to a server?

In Drupal 7 I would just copy the files, change the database settings in settings.php, and import database, clear all caches, and that's it.

2 problems come up with the '*move files, move database*' method, which are:

1. All links on the server-side site use the local url. Where does it get that information?
2. When I navigate to `/user/login` I get this error on a white page:

> Redirects to external URLs are not allowed by default, use `\Drupal\Core\Routing\TrustedRedirectResponse` for it.

# Answer
> 1 votes
I'm assuming you're moving the files and database, as you state in your question:

Moving a site from MAMP should be pretty easy. One thing you may be missing is updating $settings\['trusted\_host\_patterns'\] in your settings.php or settings.local.php

```
$settings['trusted_host_patterns'] = array(
   '^mysite\.com',
   '^.+\.mysite\.com',
   '^mysite\.local',
   '^.+\.mysite\.local',
 );

```

Another thing you may have forgotten to do is to clear the cache once you move the files and database.

Usually I use the drush command line utility and then from the docroot of the site, or the /sites/default directly run "drush cr".

# Answer
> 1 votes
I had language detection by URL turned on, with the local url in the UI form at `admin/config/regional/language/detection`. :)

---
Tags: 8, migrations
---


title: Error on import multisite backup

text:
# Question
Title: Error on import multisite backup
I had to import a multisite (Drupal 7) to Acquia dev desktop. The import seemed to be successful. But the following error is displayed when the page is accessed:

> PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table 'kanu\_backup.semaphore' doesn't exist: ...

What should I do?

# Answer
Have you tried running your update.php file?

(https://www.drupal.org/upgrade/running-update-php)

II. Run update.php In your web browser navigate to the directory where Drupal is installed:

http://www.example.com/update.php

or

http://www.example.com/test\_site/update.php (if you are upgrading a test site) The update script should only be run once. It will complete all the updates at once. If prompted for which version, choose the closest starting version that makes sense for you.

This will update the default Drupal and contributed module database tables automatically (versions prior to 4.7 will require manual upgrade of the contributed modules). Once the script has stopped loading, be sure to scroll to the bottom to look for errors.
> 0 votes

---
Tags: acquia-dev-desktop
---


# Question
Title: How to replace add to cart button text in drupal commerce programatically?
I am getting this html of add to cart button

```
<button type="submit" id="edit-submit" name="op" value="Add to cart" class="btn btn-success form-submit">Add to cart</button>

```

I am using this code in `hook_form_alter()`.

```
$form['submit']['#attributes']['title'] = $form['submit']['#attributes']['value'] = t("Applied");

```

# Answer
Assuming `$form['submit']` is the correct element:

```
$form['submit']['#value'] = 'New value';

```
> 2 votes

---
Tags: commerce
---


# Question
Title: How do I make it easy for users to upload images into a text area?
**I would like to make it easy for users to add images to text areas.**

I enabled the "Image" plugin for a TinyMCE 3.5.11 WYSIWYG profile in Drupal 7.

It looks like this:

**It is unclear, to the end user, how to upload an image. How can I make it easier?**

# Answer
> 0 votes
It's relatively easy to install and enable the IMCE module.

Then, I enabled it in my WYSIWYG Profile.

That gives you a little button next to the Image URL field.

And that allows the user to upload images.

FWIW, TinyMCE 4.3+ supports image uploading natively.

---
Tags: 7, media, wysiwyg
---


# Question
Title: Untag/Remove a taxonomy term from a node
I am inserting and updating node programmatically in drupal 7.When am updating I want to delete the taxonomy terms tagged in that particular node and have to insert new terms.

Please help me to untag the taxonomy terms of that node.the unset($node-\>taxonomy\_field) is not working.Can anyone help me?

# Answer
With Views Bulk Operations for Drupal 7, you can execute arbitrary PHP scripts.

In order to bulk-delete a specific taxonomy term, you can make a View that shows all content with the particular term you want to remove: Be sure to add a Relationship in the View like "Content: Taxonomy terms on node" so you can filter out content with the terms you want to keep.

Then in the same View, you'd add a VBO field to execute an arbitrary PHP script. VBO no longer uses $node but rather $entity, so you can pass through the following script modified from Dave Parrish's answer above (where *field\_name\_of\_taxonomy\_term* would be the name of the Term Reference or Entity Reference field where you save the taxonomy terms on the node):

```
for ($i = 0; count($entity->field_name_of_taxonomy_term[$entity->language]) > $i; $i++) {
    if ($entity->field_name_of_taxonomy_term[$entity->language][$i]['tid'] == 'TID to Remove') {
        unset($entity->field_name_of_taxonomy_term[$entity->language][$i]);
    break;
    }
}
node_save($entity);

```
> 1 votes

# Answer
`unset` should do the trick. In my case, my taxonomy field was called `field_genre` and here is how I removed a taxonomy from a node.

```
for ($i = 0; count($node->field_genre[$node->language]) > $i; $i++) {
    if ($node->field_genre[$node->language][$i]['tid'] == $tid_to_remove) {
        unset($node->field_genre[$node->language][$i]);
        break;
    }
}
node_save($node);

```
> 0 votes

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


# Question
Title: $form_state does not follow same array structure as $form
I built a form in a form plugin like so.

```
public function buildForm(array $form, FormStateInterface $form_state) {
$array[0] = 'value1';
$array[1] = 'value2';
$array[2] = 'value3';
$array[3] = 'value4';

$form['field_1'] = [
    '#type' => 'value',
    '#value' => 'test value',
];

foreach($array as $item){
    $form['fields'][$item] = [
        '#type' => 'textarea',
        '#title' => $item,
    ];
}
    $form['actions'] = [
        '#type' => 'actions',
    ];

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

    return $form;
}

```

The form is built just fine and I can return the values upon submit like so,

```
public function submitForm(array&$form, FormStateInterface $form_state) {
    die(print_r($form_state->getValues()));
}

```

This is part of the output I receive

```
[field_1] => test value
[value1] => User input for value 1 text area
[value2] => User input for value 2 text area
[value3] => User input for value 3 text area
[value4] => User input for value 4 text area
[submit] => Drupal\Core\StringTranslation\TranslatableMarkup Object

```

The issue is, I want value1,value2,value3, and value4 to appear as children in the \['fields'\] part of the array.

To demonstrate, I'd want the output to appear like so.

```
[field_1] => test value
[fields] => [
    [value1] => User input for value 1 text area
    [value2] => User input for value 2 text area
    [value3] => User input for value 3 text area
    [value4] => User input for value 4 text area
]
[submit] => Drupal\Core\StringTranslation\TranslatableMarkup Object

```

The ultimate goal is to be able to use a foreach loop on the fields array, like this

```
foreach($fields as $key => $value){
    print_r('This is the key: '.$key.' and this is the value: '.$value);
}

```

I also attempted declaring 'fields' as a container first like so

```
$form['fields'] = [
    '#type' => 'container',
];

```

but it has no effect. How would I group form elements into an array when parsing the form state?

# Answer
If you group the fields below `$form['fields']` you also have to set `#tree` at the top of the array:

```
$form['fields']['#tree'] = TRUE;

```

Then the values will be structured in the same way as the form elements.
> 3 votes

---
Tags: 8, forms
---


# Question
Title: How do i change the button text "subscribe", from the "simplenews" module, in drupal 8?
I'm very new to drupal and programming.

I simply want to change some text on the simplenews "subscribe"/"unsubscribe" buttons.

From past questions I understand the only solution is programmatically? I've seen the hook\_page\_alter() method mentioned but I am not experienced enough to get it to work.

This is my poor attempt at utilizing it:

```
 function MYTHEME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'simplenews_subscriptions_block') {
       $form['New button text'] = array(
           '#markup' => '<p> New button text </p>',
       )
    }
}

```

# Answer
> 1 votes
I figured it out due to 4k4's comment

Basically you can translate it english-to-english under /admin/config/people/simplenews/settings/subscriber/fields/ It's a part of the configuration translation module.

If you get the error message "The configuration objects have different language codes so they cannot be translated:" look at this thread for the solution for that: How to change default language for configuration entities

---
Tags: 8, emails
---


# Question
Title: How to delete all duplicate node with the same field value in drupal type
I need to bulk delete the duplicate nodes based on the same field and keep just one node.

How can I do that ?

I tried that :

```
$query = \Drupal::entityQuery('node')->condition('type', "diffusion");
$query->groupBy('field_id_diffusion');
//$query->having('COUNT(field_id_diffusion) >= 1');
$duplicate = $query->execute();

```

# Answer
> 0 votes
If your nodes are not too many you can achieve it by something like following :

```
$query = \Drupal::entityQuery('node')->condition('type', "diffusion");
$query->groupBy('field_id_diffusion');
$nids = $query->execute();
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids);

$diffusion_checklist = [];
foreach ($nodes as $node) {
   $diff_id = $node->get('field_id_diffusion')->value;

   if (!in_array($diff_id ,$diffusion_checklist)) {
     $diffusion_checklist[] = $diff_id;
   }
   else {
     $node->delete();
   }
}

```

And if you have too many nodes another solution is implement the same strategy with setup a batch operations

---
Tags: 8, entities, database
---


# Question
Title: Using VBO and Rules to auto-delete entityform submissions
I'm trying to set a reaction rule that checks for previous submissions from a user and deletes them when new form data is submitted.

I had success getting the fields to delete using the Fetch action, but I only want to pull submissions from the current user, and I haven't quite figured out the right component rule set to make this work yet.

Whenever I introduce VBO to the equation, the rule stops deleting. The components work. The VBO works on itself. They just don't play nice together. I've tried every possible configuration under the sun (I think), but so far nothing works.

I've read a few older issues that suggest that VBO cannot be used to delete entityform submissions. Most of the replies that say you can actually address nodes, but don't work for entityforms specifically.

So, my question is: can I delete entityform submissions via VBO in rules? If not, should I be looking to do this programmatically instead, or is there another workaround?

For example: I can execute a basic entity-delete component like this:

`{ "rules_delete_current_project" : {
 "LABEL" : "Delete Old Current Project",
 "PLUGIN" : "rule",
 "OWNER" : "rules",
 "REQUIRES" : [ "rules" ],
 "USES VARIABLES" : { "current_project" : { "label" : "Current Project", "type" : "list\u003Centityform\u003E" } },
 "IF" : [
 { "data_is" : {
 "data" : [ "current-project:0:type" ],
 "value" : "myplatform_current_project"
 }
 }
 ],
 "DO" : [ { "entity_delete" : { "data" : [ "current-project:0" ] } } ]
 }
}`

Meanwhile, the following reaction rule with Fetch action deletes the last Entityform Submission, but won't respond to restrictions forcing it to address only current user content:

`{ "rules_delete_existing_current_project" : {
 "LABEL" : "Delete Existing Current Project",
 "PLUGIN" : "reaction rule",
 "OWNER" : "rules",
 "REQUIRES" : [ "rules", "entityform" ],
 "ON" : { "entityform_insert" : [] },
 "IF" : [
 { "data_is" : {
 "data" : [ "entityform:type" ],
 "value" : "myplatform_current_project"
 }
 },
 { "AND" : [
 { "entity_is_of_type" : { "entity" : [ "entityform" ], "type" : "entityform" } }
 ]
 },
 { "AND" : [
 { "data_is" : { "data" : [ "entityform:uid" ], "value" : [ "site:current-user:uid" ] } }
 ]
 }
 ],
 "DO" : [
 { "entity_query" : {
 "USING" : {
 "type" : "entityform",
 "property" : "type",
 "value" : [ "entityform:type" ]
 },
 "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
 }
 },
 { "LOOP" : {
 "USING" : { "list" : [ "entity-fetched" ] },
 "ITEM" : { "list_item_parameters" : "Current list item" },
 "DO" : [
 { "variable_add" : {
 "USING" : { "type" : "entityform_type", "value" : "myplatform_current_project" },
 "PROVIDE" : { "variable_added" : { "variable_added_type" : "Added variable" } }
 }
 },
 { "variable_add" : {
 "USING" : { "type" : "entityform", "value" : [ "entity-fetched:0" ] },
 "PROVIDE" : { "variable_added" : { "variable_added_submission" : "Added variable" } }
 }
 },
 { "variable_add" : {
 "USING" : { "type" : "user", "value" : [ "entity-fetched:0:user" ] },
 "PROVIDE" : { "variable_added" : { "variable_added_user" : "Added variable" } }
 }
 }
 ]
 }
 },
 { "LOOP" : {
 "USING" : { "list" : [ "entity-fetched" ] },
 "ITEM" : { "list_item" : "Current list item" },
 "DO" : [
 { "component_rules_vbo_current_project_select" : {
 "current_project_list" : [ "entity-fetched" ],
 "user" : [ "list-item:user" ]
 }
 },
 { "entity_delete" : { "data" : [ "entity-fetched:0" ] } }
 ]
 }
 }
 ]
 }
}`

This is one of the few reaction rule combinations I could get to work cleanly with the VBO and referencing the component above. It does not delete.

`{ "rules_another_rules_test" : {
 "LABEL" : "Another rules test",
 "PLUGIN" : "reaction rule",
 "OWNER" : "rules",
 "REQUIRES" : [ "rules", "views_bulk_operations", "entityform" ],
 "ON" : { "entityform_insert" : [] },
 "IF" : [
 { "data_is" : { "data" : [ "entityform:type" ], "value" : "myplatform" } }
 ],
 "DO" : [
 { "views_bulk_operations_action_load_list" : {
 "USING" : { "view" : "backend_current_project_edit|default" },
 "PROVIDE" : { "entity_list" : { "entity_list" : "A list of entities" } }
 }
 },
 { "LOOP" : {
 "USING" : { "list" : [ "entity-list" ] },
 "ITEM" : { "list_item" : "Current list item" },
 "DO" : [
 { "component_rules_delete_current_project" : { "current_project" : [ "entity-list" ] } }
 ]
 }
 }
 ]
 }
}`

**The view which works on its own is structured:**

Format:
Unformatted list | Settings
Show:Fields | Settings

Fields:
Entityform Submission: Entityform submission ID
Entityform Submission: Current Project
Entityform Submission: Select Project
Bulk operations: Entityform Submission

Filter criteria:
Entityform Submission: Entityform Type (= MyPlatform Current Project)
Entityform Submission: Uid (reference filter)

**I have Bulk Operations set to:**

Y Delete Current Project
Y Skip confirmation step
Y Skip permission step
Y Override label

I've been coding this in circles for a while, so the variable names might not match from one region to the next.

# Answer
> 0 votes
Got this to work in rules by creating a rule set, which relates the variables and actions to each other instead of processing them separately. Still haven't figured out how to delete entityform submissions via Views, but at this point, it's academic.

If anyone is interested, this is the code that worked:

`{ "rules_current_project_fetch_by_uid_rule_2" : {
 "LABEL" : "Current Project Fetch by UID Rule 2",
 "PLUGIN" : "reaction rule",
 "OWNER" : "rules",
 "REQUIRES" : [ "rules", "entityform" ],
 "ON" : { "entityform_presave" : [] },
 "IF" : [
 { "data_is" : {
 "data" : [ "entityform:type" ],
 "value" : "myplatform_current_project"
 }
 },
 { "AND" : [] },
 { "entity_is_of_type" : { "entity" : [ "entityform" ], "type" : "entityform" } }
 ],
 "DO" : [
 { "entity_query" : {
 "USING" : {
 "type" : "entityform",
 "property" : "type",
 "value" : [ "entityform:type" ]
 },
 "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
 }
 },
 { "LOOP" : {
 "USING" : { "list" : [ "entity-fetched" ] },
 "ITEM" : { "list_item" : "Current list item" },
 "DO" : [
 { "component_rules_current_project_fetch_by_uid_component" : { "current_project_submission" : [ "list-item" ] } }
 ]
 }
 }
 ]
 }
}`

The rule set looks like this:

`{ "rules_current_project_fetch_by_uid_component" : {
 "LABEL" : "Current Project Fetch by UID component",
 "PLUGIN" : "rule set",
 "OWNER" : "rules",
 "REQUIRES" : [ "rules" ],
 "USES VARIABLES" : { "current_project_submission" : { "label" : "Current Project Submission", "type" : "entityform" } },
 "RULES" : [
 { "RULE" : {
 "PROVIDE" : { "variable_added" : {
 "variable_added_type" : "Added variable",
 "variable_added_submission" : "Added variable"
 }
 },
 "IF" : [
 { "data_is" : {
 "data" : [ "current-project-submission:type" ],
 "value" : "myplatform_current_project"
 }
 },
 { "AND" : [] },
 { "entity_is_of_type" : { "entity" : [ "current-project-submission" ], "type" : "entityform" } },
 { "AND" : [] },
 { "data_is" : {
 "data" : [ "current-project-submission:user" ],
 "value" : [ "site:current-user" ]
 }
 }
 ],
 "DO" : [
 { "variable_add" : {
 "USING" : { "type" : "entityform_type", "value" : "myplatform_current_project" },
 "PROVIDE" : { "variable_added" : { "variable_added_type" : "Added variable" } }
 }
 },
 { "variable_add" : {
 "USING" : { "type" : "entityform", "value" : [ "current-project-submission" ] },
 "PROVIDE" : { "variable_added" : { "variable_added_submission" : "Added variable" } }
 }
 }
 ],
 "LABEL" : "Current Project UID Variables"
 }
 },
 { "RULE" : {
 "IF" : [
 { "data_is" : {
 "data" : [ "variable-added-type" ],
 "value" : "myplatform_current_project"
 }
 },
 { "data_is" : {
 "data" : [ "variable-added-submission" ],
 "value" : [ "current-project-submission" ]
 }
 },
 { "data_is" : {
 "data" : [ "current-project-submission:uid" ],
 "value" : [ "site:current-user:uid" ]
 }
 }
 ],
 "DO" : [ { "entity_delete" : { "data" : [ "current-project-submission" ] } } ],
 "LABEL" : "Current Project UID Delete"
 }
 }
 ]
 }
}`

---
Tags: rules, views
---


# Question
Title: Some images are not loaded - 404 not found
Some images on my Drupal site are not loading. In the folder sites/all/default/files and also in the folder sites/all/themes/mytheme/images some images are not loading.

When I rename the file and upload him again, the image is visible. And also when I copy the site to my localhost all images are showing.

I tried to change my settings.php `$conf['image_allow_insecure_derivatives'] = TRUE;` and my .htacces file:

```
The .htaccess file will look like this:

SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
Options None
Options +FollowSymLinks

Change it to:
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
#Options None
#Options +FollowSymLink

```

With no luck.

The error: `The requested URL "/sites/default/files/images/images1.jpg" was not found on this server.`

It's weird that the images wich are linked to my css file are also blocked.

# Answer
It sounds as though your paths are incorrect. If you developed the site on your local computer, it's mostly that you a path structure that has changed on your production site.

Based on the error you're receiving I'd also confirm that your site root is what you think it is. The path indicated in your error is \<site\_root\>/sites/default/images/image1.jpg
> 0 votes

# Answer
Try to change Options +FollowSymLink to Options +SymLinksIfOwnerMatch. Don't comment this line. I had similar problem on one shared hosting.
> 0 votes

---
Tags: 7, media
---


# Question
Title: Javascript libraries not loading from block class
I am working on porting module to drupal 8.

My block code is as follow `public function build() {
 $delta= $this->getDerivativeId();
 $num = str_replace('dexp_layerslider_block_', '', $delta);
 $sid = $this->configuration['dexp_layerslider_block_slide_'.$num];
 $block_id = $this->getDerivativeId();
 $slideshow = dexp_layerslider_load($sid);
 if (!$slideshow){
 return 'No slider selected';
 }
 $content = array(
 'id' => $sid,
 'slides' => $slideshow->slides,
 'settings' => $slideshow->settings
 );
 return array(
 '#theme' => 'dexp_layerslider_slides',
 '#items' => $content,
 '#attached' => array(
 'library' => array('dexp_layerslider/dexp.block'),
 ),
 );
}` my yaml file: `dexp.slides:
 version: 1.x
 css:
 theme:
 plugins/font-awesome/css/font-awesome.min.css: {}
 css/admin.style.css: {}
 plugins/rs-plugin/css/settings.css: {}
 js:
 js/dexp.layerslider.js: {}
 js/layeroption.js: {}
 js/admin.layerslider.js: {}
 plugins/rs-plugin/js/jquery.themepunch.revolution.min.js: {}
 plugins/rs-plugin/js/jquery.themepunch.tools.min.js: {}
 dexp.block:
 version: 1.x
 css:
 theme:
 plugins/rs-plugin/css/settings.css: {}
 css/layerslider.css: {}
 js:
 plugins/rs-plugin/js/jquery.themepunch.revolution.min.js: {}
 plugins/rs-plugin/js/jquery.themepunch.tools.min.js: {}
 dependencies:
 - core/drupal
 - core/jquery` my theme function : `$themes['dexp_layerslider_slides'] = array(
 'template' => 'slides',
 'path' => $path . '/theme',
 'pattern' => 'layerslider__',
 'preprocess functions' => array(
 'template_preprocess',
 'dexp_layerslider_preprocess_slides'
 ),
 'variables' => array('items'=>null),
 );` None of javascript and css files are load , when i try to access items in twig template {{ items }} nothing gets printed , though if write random string in the my slide.html.twig file it get printed. where i could be going wrong?

# Answer
> 1 votes
You don't have a "dexp.slide" defined in your libraries.yml file. Only "dexp.block".

You're trying to attach a library that doesn't exist.

---
Tags: theming, 8
---


title: Publish Blog Post command line

text:
# Question
Title: Publish Blog Post command line
I've been looking around the Internet trying to investigate how to publish a blog post via either rest APIs or other command line tools. However, I have not found a way to do this. How can I publish a blog post (or node) either through a command line, rest APIs, or another way programmatically?

# Answer
> 1 votes
Drupal 6 has a module to publish to a site via external GUI applications. It supports different XML-RPC based blogging APIs, such as the Blogger API, the new Blogger Data API, the MetaWeblog API, and most of the Movable Type API.

In Drupal 7, the module has been removed from core, and it is now a third-party module.

### Reference

---
Tags: 7, nodes
---


# Question
Title: How to have multiple exposed filters in a block that affects multiple views content panes in a panel?
I have a view with multiple content panes. One shows a table, other shows a chart and so on. On every content pane I have the same exposed filters and it's exposed as a block.

In a panel I add all thosse content panes and on top of the page I show the exposed block. How can I make the filter to affect all the content panes and not one individually?

# Answer
Select one of your displays (lets say table1) and add (or recreate) the other displays as attachments. Then only display table1 on your page and all other displays should tag along with it. Then expose the filter for table1.

Here's a good overview: http://nmc-codes.blogspot.co.nz/2012/10/views-attachment-in-drupal-7.html

**UPDATE:**

If you just want disconnected views to pick up on one exposed filter then this might do the trick: https://www.drupal.org/project/global\_filter

It gives you configurable blocks with filter options. These options are made available as contextual filters so your views don't need to have the exposed filters.
> 1 votes

---
Tags: 7, views, panels
---


# Question
Title: Adding another date using the date repeat API
I'm using the Date Repeat API in Drupal 7 to create an interface for a user to add in a recurring event. As it comes out of the box, it only allows for one date, then you have to save the node and re-edit. I've commented out the `date_form_field_ui_field_edit_form_alter()` in `date.module` which hides the multiples values option which I thought would allow the associated API to show the 'Add another item' button. When I go into the 'manage fields' form in the Content Type, I've set the form to 'unlimited' values and saved it. However when I load the content type, the normal date which still has the 'Add another item ' button but the recurring date time does not.

I'm trying to add this since the event that it is attached to might well have a second recurring time for that event, for example it happens every Monday and every second Wednesday. Whilst I am aware that you can do this through saving and re-editing, from a UI perspective it would easier to allow a user to add more than one form of recurring event if needs require.

I'd be grateful for any guidance in solving this issue. Thanks.

---

Update: I've been doing some more digging and it appears that the 'repeat' code is a form linked off the `date_request_api`, but I cannot see why the field created in the *Content Type* admin UI does not appear to pick up on the multiple values setting.

# Answer
If you select the repeat option in the field configuration, the Date module then declares to the Field API that it handles multiple values. There is a lot of discussion about it on drupal.org but sadly no patches for Drupal 7.
> 1 votes

---
Tags: 7, datetime
---


# Question
Title: What is the command that replaces 'drush variable-set'?
In Drupal 8 the Drush command `drush variable-set` no longer works.

From reading (here) it appears that Drupal 8 has a new "configuration" system that replaces the old (Drupal \<=7) "variables". But what is the new Drush command to achieve the same ends?

Specifically I want to convert the commands:

```
drush variable-set site_mail someone@email.com
drush variable-set update_notify_emails someone@email.com

```

to the new Drupal8/Drush8 equivalent...

# Answer
Following some more research it seems the new command is:

* `drush config-set <config-name> <key>` (where the old format was `drush variable-set <name> <value>`). Alias: `cset`.

So I'm not totally sure that I have this right (so comment and/or another answer from someone who does would be great...), but it seems that the config that includes emails are: `contact.form.feedback recipients`, `update.settings notification.emails` and `system.site mail`.

This update is the result for some good discussion (below). Note that some settings are arrays (rather than strings):

```
www/drupal8# drush config-get update.settings notification
'update.settings:notification':
  emails:
    - admin@example.com
  threshold: all

```

to update this you need to run:

```
drush -y config-set update.settings notification.emails.0 admin2@example.com

```

Source: Leverage Drush 7 for Drupal 8.

Note: Drush 7 no longer supports Drupal 8, but this still applies.
> 21 votes

# Answer
Additional follow-up,

To find the identifiers for the config to get or set,

* You can NO LONGER guess at the machine names of variables just by inspecting system settings forms. There used to be a 1:1:1 match between the form element seen on many config screens, the `$config['varname']` you could put into `$settings.php`, and drush vset/vget
* The config manager in the ui (found at `admin/config/development/configuration/single` ) provides something of a variable browser.

I wanted to update my `local.settings.php` to always disable css & js aggregation when downsyncing.

D7 :

```
$conf['preprocess_css'] = FALSE;
$conf['preprocess_js'] = FALSE;

```

D8 :

```
$config['system.performance']['css']['preprocess'] = 0;
$config['system.performance']['js']['preprocess'] = 0;

```

(And note that this type of override WILL NOT show up in your Admin UI, or in `drush config-get` ... though it will take effect)
> 6 votes

# Answer
This worked for me. It's a Drush PHP EVAL command.

```
drush ev '\Drupal::state()->set("MY_VARIABLE", "MY_VALUE")'

```

Here it's being used to set the state of MY\_VARIABLE

You can also *get* the state of a variable:

```
drush ev 'echo \Drupal::state()->get("MY_VARIABLE")'

```
> 5 votes

---
Tags: drush, 8
---


# Question
Title: How to create responsive rows and columns in node body
Add Content \> Basic Page \> In body field, I would like to create four responsive rows in bootstrap theme as shown in the following image:

Tablet/laptop/desktop:

Mobile:

I started writing the below html in the body field but I could not do it. Can you please help me on how to accomplish that?

```
 <div class = "col-md-12 col-lg-12 col-sm-12 col-xs-12">

</div>

```

# Answer
> 0 votes
This functionality is best handled with views. You can use views\_bootstrap to generate list like that. If you don't want to use views you can add your own HTML into body field but you will need to make sure that you select input format as Full HTML OR PHP. This will ensure that your HTML elements don't get stripped off.

---
Tags: theming
---


title: Drupal 8 - Taxonomy Menu with Hierarchy

text:
# Question
Title: Drupal 8 - Taxonomy Menu with Hierarchy
I have been looking searching for a while and couldn't find anything related to Drupal 8. There are Modules like Taxonomy Menu but unfortunately not for Drupal 8 which works accordingly.

Is there already any solution to build-up a menu out of the taxonomy terms for Drupal 8 without an individual development (php etc.)?

Further, I have realized when I create a taxonomy term and create a reference from a content I don't get the overview of contents linked to the term.

Hope my point is clear.

# Answer
I needed the same thing. Unfortunately there is nothing for it yet so I had to create something for time being. It is not pretty but it works so I don't care.

```
/**
 * Returns renderable array of taxonomy terms from Categories vocabulary in
 * hierarchical structure ready to be rendered as html list.
 *
 * @param int $parent
 *   The ID of the parent taxonomy term.
 *
 * @param int $max_depth
 *   The max depth up to which to look up children.
 *
 * @param string $route_name
 *   The name of the route to be used for link generation.
 *   Taxonomy term(ID) will be provided as route parameter.
 *
 * @return array
 */
function mymodule_categories_tree($parent = 0, $max_depth = NULL, $route_name = 'mymodule.category.view') {
  // Load terms
  $tree = \Drupal::entityManager()->getStorage('taxonomy_term')->loadTree('categories', $parent, $max_depth);

  // Make sure there are terms to work with.
  if (empty($tree)) {
    return [];
  }

  // Sort tree by depth so we can easily find out the deepest level
  uasort($tree, function($a, $b) {
    // Change objects to array
    return \Drupal\Component\Utility\SortArray::sortByKeyInt((array) $a, (array) $b, 'depth');
  });

  // Get the value of the deepest term
  $deepest = end($tree);
  $deepest = $deepest->depth;

  // Create a structured array
  $list = [
    $parent => [
      'items' => [],
      'depth' => -1
    ]
  ];
  foreach ($tree AS $term) {
    $list[$term->tid] = (array) $term;
  }

  // See if we're on a node page and if so open the menu
  // on the proper position.
  $node = \Drupal::request()->attributes->get('node');
  if ($node) {
    $categories = $node->get('categories')->getValue();
    // Go through each category to find out the least deep one.
    // That one will be the one we'll open.
    $open_category = $parent;
    foreach ($categories AS $target) {
      $tid = $target['target_id'];
      if ($list[$tid]['depth'] > $list[$open_category]['depth']) {
        $open_category = $tid;
      }
    }
  } else {
    // See if we're on a term page and set the corresponding item
    // as active so we don't have to rely on JS.
    $term = \Drupal::request()->attributes->get('taxonomy_term');
    if ($term) {
      $open_term = $term->id();
    }
  }

  for ($i = $deepest; $i >= 0; $i--) {
    foreach ($list AS $term) {
      if ($term['depth'] == $i) {
        $item = [
          '#type' => 'link',
          '#weight' => $term['weight'],
          '#title' => $term['name'],
          '#url' => Url::fromRoute($route_name, ['taxonomy_term' => $term['tid']]),
          '#options' => [
            'set_active_class' => TRUE
          ]
        ];
        // If we're on a node page and this category was chosen
        // as active, set the link's class.
        if (isset($open_category) && $open_category == $term['tid']) {
          $item['#attributes']['class'][] = 'active';
        }
        // If we're on term page, set the link's class to 'active'
        // and if this item is a parent, open it.
        if (isset($open_term) && $open_term == $term['tid']) {
          $item['#attributes']['class'][] = 'active';
          if (!empty($term['items'])) {
            $item['#wrapper_attributes']['class'][] = 'open';
          }
        }
        // If this item has children
        if (!empty($term['items'])) {
          $item['items'] = $term['items'];
          $item['#wrapper_attributes']['class'][] = 'parent';
          $item['#prefix'] = '<span></span>';
          // If any of the child items has 'active' class,
          // or is also a parent and has 'open' class
          // add the 'open' class to this wrapper too.
          foreach ($item['items'] AS $child) {
            if (
              isset($child['#attributes']['class']) && in_array('active', $child['#attributes']['class'])
              || isset($child['#wrapper_attributes']['class']) && in_array('open', $child['#wrapper_attributes']['class'])
            ) {
              $item['#wrapper_attributes']['class'][] = 'open';
              break;
            }
          }
        }
        foreach ($term['parents'] AS $pid) {
          $list[$pid]['items'][$term['tid']] = $item;
        }
        unset($list[$term['tid']]);
      }
    }
  }

  return [
    '#theme' => 'item_list',
    '#items' => $list[$parent]['items'],
    '#attributes' => [
      'class' => ['categories-tree']
    ],
    '#attached' => [
      'library' => [
        'mymodule/categories_tree'
      ]
    ]
  ];
}

```
> 5 votes

# Answer
I've created a VERY rough and full of bugs version of taxonomy\_menu for setting an existing menu parent for the terms to be appended to. Also, you can define a max depth.

I hope someday someone will review this and make it all magical.
> 1 votes

# Answer
There is now a Drupal 8 version of Taxonomy Menu. You can compliment it with Taxonomy Term Reference Tree Widget to get your desired results.
> 1 votes

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


# Question
Title: Deprecate multisite in 8.x for removal in 9.x
I am thinking about implementation of some sites with multi-site and idea of solution (one code-base) is perfect for me even if shared table is not supported any more (my question about shared table is here also i'm aware of domain module too).

After some search, I found this topic about plan to deprecate multi site in 8.x and removal in 9.x.

My questions are:

* How serious is deprecation in 8.x and removal plan of multi-site in drupal 9? the topic is in category of plan for two years.
* Even if removal happens in 9.x, we have to expect some migration path to removal of 9.x or not? In my idea this migration didn’t happen for shared tables.
* Proposed solution for removal of multisite in mentioned topic is

> The modern approach to multi-site is: git — Same code, different sites. Under your control. And well-maintainable.

I can’t understand it. How does it works?

# Answer
You have a few questions there, so I'll hit them individually:

> How serious is deprecation in 8.x and removal plan of multi-site in drupal 9? the topic is in category of plan for two years.

It's hard to say. Controversial topics like that can go in circles for years in the open source community. As you can see, that topic started over three years ago, and still has not reached a conclusion, and may well never reach one.

> Even if removal happens in 9.x, we have to expect some migration path to removal of 9.x or not? In my idea this migration didn’t happen for shared tables.

It will be fine even if you are sharing tables, as you can just migrate each multisite to a new individual site. You may have to do a special database dump and import to get the shared tables into your new system. I did this once when migrating from D6 to D7 for my company site - I was using multi site, and in the upgrade, I just created two sites out of the one.

> I can’t understand it. How does it works?

Git keeps all your code in a repository, which you can clone as necessary. So any time you need to spin up another site, you just clone the code, and you have a new Drupal instance. As you update sites over time, you can merge the code changes from one repository to another.

In my own company system, we have a central repository for each project. Any time someone new works on the project, they clone the code from the central repository, and they have an exact copy of the site. We then clone the repository to the webroot, so that it is available over the web. When people make changes to the code, they push the changes to that central repository, and then anyone can pull them at any time to their own repository, and/or the repository stored in the webroot of the public site.
> 9 votes

# Answer
I've used Aegir for multi site management, great tool!

If you have ever used Amazon Web Services, it's similar like that but for Drupal. With a click of a button you can launch specific site builds.

Here is a quick overview tutorial on it

All it takes to update your site is a click of a button (Migrate button, disabled by default, read docs on how to enable it).

Aegir behind the scenes uses Drush to accomplish the bulk of the work, such as drush make files for installation, drush dl to download modules, etc...
> 2 votes

# Answer
The Git solution solves the problem of cloning an existing site. Each clone will contain a complete copy of the Drupal environment, which has an overhead of 53 MB as of Drupal 8.1.1 (87 MB actual disk space used in my file system).

Given the cost per MB of today's disk and SS drives, this overhead is not a serious problem for most of us. However, during development we may have many experimental and pedagogical sites saved in our file systems. Drupal's multisite feature, properly configured, can save a lot of file space in this case. This is a strong argument against removal of the feature.
> 0 votes

---
Tags: multi-sites, 8
---


# Question
Title: hook_menu() doesn't work as expected. How can I fix that?
`hook_menu()` contains the following code.

```
//案件 >　インポート設定 > GMC_Subaccountの追加
$items[FEED_MANAGER_MENU_PATH.'/import/%import_id/gmc_subaccount/add'] = array(
    'title' => 'GMCサブアカウントの追加',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('feed_manager_import_gmc_subaccount_edit', 2),
    'access arguments' => array('feed import gmc_subaccount edit'),
    'type' => MENU_LOCAL_ACTION,
    'file' => 'feed_manager.import_gmc_subaccount.inc',
);
//案件 >　インポート設定 > GMC_Subaccountの編集
$items[FEED_MANAGER_MENU_PATH.'/import/%import_id/gmc_subaccount/%store_id'] = array(
    'title' => 'GMCサブアカウントの編集',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('feed_manager_import_gmc_subaccount_edit', 2, 4),
    'access arguments' => array('feed import gmc_subaccount edit'),
    'type' => MENU_CALLBACK,
    'file' => 'feed_manager.import_gmc_subaccount.inc',
);

```

When I visit /import/%import\_id/gmc\_subaccount/%store\_id, it does't show the edit page, but the list page, which is defined from the following code.

```
//案件 >　インポート設定 > GMC_Subaccount_設定
$items[FEED_MANAGER_MENU_PATH.'/import/%import_id/gmc_subaccount'] = array(
    'title' => 'GMCサブアカウント',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('feed_manager_import_gmc_subaccount_list', 2),
    'access arguments' => array('feed import gmc_subaccount edit'),
    'type' => MENU_CALLBACK,
    'file' => 'feed_manager.import_gmc_subaccount.inc',
);

```

The code I use to create the link to the edit page is the following.

```
$row['data'][] = l(t('Edit'), FEED_MANAGER_MENU_PATH.'/import/'.$data->import_id.'/gmc_subaccount/'.$data->store_id.'/edit');

```

How can I fix the fact that link shows the wrong page?

# Answer
> 0 votes
It was very simple problem-

I just added following line to my .module file-

```
function store_id_to_arg($args){
if(empty($args)){ drupal_goto('<front>'); }
return $args;
}

```

Thanks for your help.

---
Tags: routes
---


# Question
Title: How are .inc files actually utilised in a module?
I am trying to learn more about modules and have noticed several of the ones I've been investigating contain .inc files, eg: module\_name.inc or module\_name.theme.inc.

It's clear these contain hooks and functions and are probably separated out just for organisational purposes.

But how does the module/Drupal know these exist? How are they called upon? I see no reference to these files in the module\_name.module file. Does Drupal automatically include all .inc files within the module's directory?

# Answer
> 2 votes
There are multiple ways .inc files can be included.

Hooks in general should all be included in the .module file, as that is the only file loaded on every page load by default, and hooks should always be available. However, hook\_hook\_info() can be implemented, telling Drupal that the hook should be looked for in another file. For example:

```
function hook_hook_info()
{
  return array
  (
    // Tell Drupal to look in a different file
    // for hook_form_alter:
    'form_alter' => array
    (
      // Tell Drupal to look in MODULENAME.forms.inc
      // for hook_form_alter:
      'group' => 'forms',
    ),
  ),
}

```

Next, you can use hook\_menu() to look for a callback in an .inc file:

```
function hook_menu()
{
  $menu['some/path'] = array
  (
    ...
    'file' => 'includes/some_file.inc',
  );

  return $menu;
}

```

The same can be done with hook\_theme():

```
function hook_theme()
{
  $themes['some_theme_hook'] = array
  (
    ...
    'file' => 'includes/some_file.inc',
  );

  return $themes;
}

```

.inc files can also be directly included with module\_load\_include():

```
// The extension is given in the first argument, and
// left off the last argument:
module_load_include('inc', MODULENAME, 'includes/some_file');

```

Though in forms, form\_load\_include() should be used rather than module\_load\_include():

```
// The extension is given in the second argument, and
// left off the last argument:
form_load_include($form_state,'inc', MODULENAME, 'includes/some_file');

```

---
Tags: 7
---


title: Angular application and Drupal services

text:
# Question
Title: Angular application and Drupal services
I am creating an Angular application using headless Drupal. I am using Drupal services module for web services.

I am trying to implement login mechanism in this app. Login is working fine but to handle authenticated requests, it is necessary to use "Cookie" header in each service call.

My app doesn't allow to use cookie header. In my browser console it says as

"Cookie unsafe header is not allowed". Is there any other way to fix this?

# Answer
I have similar setup where i use drupal as back-end and connect to services with Angular app (Ionic App) and i am describing the sequence below; however, you need to consider the below reference if you are doing cross domain

https://stackoverflow.com/questions/35007572/angular2-xhrfields-withcredentials-true/

And you have to setup CORS (This is my config for reference)

API/\*||POST,GET|Content-Type,x-csrf-token,Authorization|true

1. Login to your drupal service

End Point: /user/login

Payload:{"username":"username","password":"userpass"}

Content-Type: application/json

Method:Post

Result: User information & Token

**Request**

2. Get the Token and use it in subsequent requests by setting the header to X-CSRF-Token

End Point: /node/100

Payload:Empty

Content-Type: application/json

Method:Get

Result: Node information

**Request With X-CSRF-Token header**

3. Logout from drupal service (Token must be set as well)

End Point: /user/logout

Payload:Empty

Content-Type: application/json

Method:Post

Result: \[true\]
> 0 votes

---
Tags: 7, services
---


title: How can I delete session?

text:
# Question
Title: How can I delete session?
I create `$_SESSION['loop'][$id]`.
When I unset `$id = 0` then all of `$_SESSION['loop']` are delete.
How can I do this?

```
$id = \Drupal::request()->query->get('id');

if (isset($_SESSION['loop']) & (isset($id)) & ( $_SESSION['loop'] > 0)) {
  $_SESSION['loop'] = $_SESSION['loop'] - 1;
  unset($_SESSION['label'][$id]);
  unset($_SESSION['code'][$id]);
  unset($_SESSION['price'][$id]);
  unset($_SESSION['sellercode'][$id]);
}

return header('Location: /basket');

```

# Answer
I would use this structure:

```
$_SESSION['mybasket'][$id] = [
  'label' => $label,
  'code' => $code,
  'price => $price,
];

```

Then you can delete one item

```
unset($_SESSION['mybasket'][$id]);

```

or the complete basket

```
unset($_SESSION['mybasket']);

```

You don't need the variable loop, to count the items use

```
$count = count($_SESSION['mybasket']);

```
> 0 votes

---
Tags: 8
---


title: node reference fail before submit

text:
# Question
Title: node reference fail before submit
I have custom\_form, with `node_reference_field`.. When I add Any node and leave some require field then I submit .. the `node_reference_field` fail and become \[nid:und\]

```
function custom_form_alter(&$form, &$form_state, $form_id) {
  $forms = array('register_node_form', 'session_node_form');
  if (in_array($form_id, $forms)) {
    if (empty($form['field_event_ref']['und'][0]['nid']['#default_value'])) {
      $form['field_event_ref']['und'][0]['nid']['#default_value'] = arg(3);
    }
    $form['field_event_ref']['und'][0]['nid']['#disabled'] = True;
  }
}

```

# Answer
> 0 votes
```
if ($form_id == 'register_node_form'){
    global $user;
    if(isset($form_state['build_info']['args'][0]->field_event_ref[LANGUAGE_NONE][0]['nid'])){
       $nid = $form_state['build_info']['args'][0]->field_event_ref[LANGUAGE_NONE][0]['nid'];
    }  else {
    $nid = $form_state['build_info']['args'][0]->field_event_ref[LANGUAGE_NONE][0]['nid'] = arg(3);
    }
     $form_state['build_info']['args'][0]->field_event_ref[LANGUAGE_NONE][0]['nid'] = $nid;

```

---
Tags: 7, nodes
---


# Question
Title: Auto Increment on users table is not functioning
I need to Create a new user programmatically. So, I have used `user_save` method, as shown here:

```
$usersave = array(
'name' => 'abc',
'pass' => 'abc',
'mail' => 'abc@gmail.com',
'status' => 1,
'roles' => array(
  DRUPAL_AUTHENTICATED_RID => 'authenticated user',
      5 => 'customer'
),
);

$save = user_save($usersave);

```

But it throws this error message:

> PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry '0' for key 'PRIMARY': INSERT INTO {users} (name, pass, mail, status) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3); Array ( \[:db\_insert\_placeholder\_0\] =\> abc \[:db\_insert\_placeholder\_1\] =\> abc \[:db\_insert\_placeholder\_2\] =\> abc@gmail.com \[:db\_insert\_placeholder\_3\] =\> 1 ) in drupal\_write\_record() (line 7383 of /home/vijay/public\_html/vssb/public/includes/common.inc).

What's the issue?

# Answer
This is a duplicate of Create a user programmatically and give they a role

```
// The first parameter should be blank so a new user is created.
user_save('', $new_user);

```

If you want to use `user_save($new_user);` you can set `$new_user->is_new` to TRUE or omit the $account-\>uid field.
> 1 votes

---
Tags: 7, users
---


# Question
Title: How to add a User Entity as a Field in Content Type?
How to add a User Entity as a Field in a Content Type?

So I can be able to display First/Last Name field.

# Answer
So the name of the author is already displayed in the Author information section in one of the tabs at the bottom of the form.

HOWEVER, if you really want to display the username of the logged in user for some reason, you can use `hook_form_alter`.

Create this in a custom module OR in your theme's template.php, if you won't be doing much customisation.

```
function mytheme_form_alter(&$form, &$form_state, $form_id) {
  // Use drupal_set_message($form_id); to figure out the form id
  // of the article edit form.
  if ($form_id == 'article_node_form') {
    global $user;
    // Check the content of the $form using dsm() or krumo().
    // You will have access to these functions if you have the devel module enabled.
    // Then insert your item into the form.
    $form['username'] = array(
      '#type' => 'item',
      '#title' => 'Username',
      '#value' => $user->name,
      // Adjust the weight so your field will appear in the order you like.
      '#weight' => 10,
    );

  }

}

```

Take note that this will NOT change the author of the form. To change that you have to actually alter the fieldset for author.

Reference: https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_form\_alter/7.x
> 0 votes

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


# Question
Title: Server Configuration causes file uploads to fail
I have a drupal 7 site running on a Redhat shared hosting environment that uses zend php. I am having problems with file upload on content types and webforms that accepts various file types up to 300MB. I have modified the server's php upload limit through the php.ini file, and can confirm that the limit is raised through `phpinfo()` and the drupal status report that `post post_max_size` and `upload_max_filesize`. I believe this is a server configuration error because the site functions as expected on both my ubuntu development machine and test server, so the only possibility is with the settings on the shared redhat server environment.

The errors occur when I try to upload files in the 30-80 MB range, either to my content type or through the webform. In either case when a file is uploaded the request takes an abnormally long time and then fails with the following errors:

```
An AJAX HTTP request terminated abnormally.
Debugging information follows.
Path: /file/ajax/field_training_materials/und/form-_TZM0uXFQeo35YReaxuUjeHprp2tr192kNHTucXffSM
StatusText: n/a
ResponseText:
Error
The website encountered an unexpected error. Please try again later.

ReadyState: undefined

```

Once, I received the following JS error while attempting the uploads: `"Blocked Script Execution in 'node/722/edit' because the document's frame is sandboxed and the 'allow-scripts' permission is not set"` and `"Blocked form submission to '/node/722/edit' because the form's frame is sandboxed and the 'allow-forms' permission is not set`. Googling these errors didn't turn up any useful information.

From what I can tell the files get almost completely uploaded to 57 of 58 MB and is placed in the correct directory without being attached to the content type. It seems to mostly have problems with audio files, but I don't have a range of different file types at different sizes to test for a pattern of breakpoint.

I researching the problem, I read that some people have trouble with the Suhosin PHP extension putting extra constrictions on PHP settings, but my live server doesn't have Suhosin running on it. Reading about the Suhosin issue, I have also tried upping the max\_input\_vars value, which only changed the error to the following.

```
An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (300 MB) that this server supports.

```

From running phpinfo(), I can see that all my php value settings are getting applied, but I suspect that maybe they don't take effect. Since the first error, the error has been failing silently, and nothing meaningful gets placed in my logs. I have also checked that all my php ini\_set statements are consistent between .htaccess, settings.php, and the php.ini files.

I have just spoken with tech support the following error was thrown when I tried the file upload: `[Thu Feb 02 07:29:10.729972 2017] [core:error] [pid 475229] [client 178.203.233.17:6690] Script timed out before returning headers: index.php, referer:path to my content edit page`. I also do not get anything meaningful in the watch dog logs.

The only difference between the file upload attempts with the content type and the webform is that the ajax error's path is different and I get the following JS error in the console: `Error: Syntax error, unrecognized expression: .error, #overlay-context=form/training-suggestions-`

So, the only thing I am sure of at this point is that it must be a server configuration error. My suspicion is that somehow the the php values settings are getting applied, but perhaps overwritten at some stage. Any advice on how to solve or diagnose this would be greatly appreciated.

Update: So, while trying this again I got a different ajax error, saying the mysql db went away:

```
   An AJAX HTTP request terminated abnormally.
    Debugging information follows.
    Path: /file/ajax/field_training_materials/und/form-66R_kY340Ob1IV3M9bRKvHevXAdePEElDr6cgwVf_DE
    StatusText: n/a
    ResponseText: Additional uncaught exception thrown while handling exception.OriginalPDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT nt.*
    FROM
    {node_type} nt
    WHERE  (disabled = :db_condition_placeholder_0)
    ORDER BY nt.type ASC; Array
    (
    [:db_condition_placeholder_0] =&gt; 0
    )
    in _node_types_build() (line 739 of /home/phislub9/public_html/modules/node/node.module).AdditionalPDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT 1 AS expression
    FROM
    {variable} variable
    WHERE ( (name = :db_condition_placeholder_0) ); Array
    (
    [:db_condition_placeholder_0] =&gt; drupal_css_cache_files
    )
    in variable_set() (line 1240 of /home/phislub9/public_html/includes/bootstrap.inc).Uncaught exception thrown in session handler.PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT 1 AS expression
    FROM
    {sessions} sessions
    WHERE ( (sid = :db_condition_placeholder_0) AND (ssid = :db_condition_placeholder_1) ); Array
    (
    [:db_condition_placeholder_0] =&gt; 1A5hUf8pjc2OA0iW8Nlom8qeFgG8rJPPKXwxBKKANBI
    [:db_condition_placeholder_1] =&gt;
    )
    in _drupal_session_write() (line 209 of /home/phislub9/public_html/includes/session.inc).
    ReadyState: undefined

```

**Update:** So, I've done some poking around in response to the first answer below. Here's the result of `SHOW VARIABLES;` in the mysql shell `max_allowed_packet | 268435456`

**Update2:** Here's the output

```
mysql> show global status like 'com_kill';
ERROR 2006 (HY000): MySQL server has gone away
No connection. Trying to reconnect...
Connection id:    3204869
Current database: *** NONE ***

+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| Com_kill      | 0     |
+---------------+-------+
1 row in set (0.01 sec)

```

**Update:** Checked with hosting tech support, apparently there is unlimited disk usage for website files, however the server reports that the /home folder is at 94%. This was due to serveral large zip files from the previous site maintainer/developer. I've backed up and removed these files, but it hasn't affected the file upload problem or the server's report on the size of the home folder. The only other thing I got from tech support was that the php values for the server MAYBE can't be overridden, or can't be set above certain upper bounds, but the support agent wasn't able to give me definitive answers on what those values were. I've followed up with a support ticket to get better answers to what's going on.

# Answer
So, Wim Mostrey's answers were right on point and would have solved the problem in a normal hosting environment. The issue came down to conflicts with Apache's modsecurity settings on the shared host as well as PHP's memory allocation per user on the shared host, taking longer than the MySQL wait time out setting allowed. It took ca. 70 seconds for the php script to write the files to disk and Mysql's wait timeout was only 30 seconds. It wasn't possible to see what was going on clearly until I addressed some other issues that were throwing warnings. In the end the problem was addressed by disabling modsecurity for our server and configuring the Mysql Wait Timeout Module. Hope this helps someone.
> 1 votes

# Answer
**Original answer**

Try this for your second, new error:

```
General error: 2006 MySQL server has gone away

```

You can try to fix this in two ways:

1. `my.ini`

Open your `my.ini` file and locate max\_allowed\_packet. By default this is 1M. Setting it to 16M and restart your MySQL server. If the problem persists, try setting it to 512M and restart your MySQL server.

2. `MySQL prompt`

Enter your MySQL prompt, log in as user root or as a user with the SUPER privilege. Run the following command:

```
SET GLOBAL max_allowed_packet = 1024 * 1024 * 512;

```

This method doesn't require you to restart the server.

**Update**

Since this doesn't seem to solve your problem, it might be possible that your SQL statement was killed. Some systems will proactively kill SQL statements that have been running too long. You can easily check if this may be happening proactively by looking at how many KILL statements have been executed.

What does the following MySQL command return?

```
show global status like 'com_kill';

```
> 1 votes

---
Tags: 7, entities, ajax, files
---


# Question
Title: Drupal 8 blocks content is not being translated
I've searched high and low but can't seem to find any question that has the same problem. We're experiencing blocks that have content that is not being translated. For example, a custom block that has a simple translatable string and is being translated into a different language, it will simply always show the source language. What's up with that?

```
$build['test_content']['#markup'] = $this->t('Test NL');

```

**Edit**: For the record; we have translated this string into the target language but still doesn't show up on the corresponding language.

# Answer
You need to navigate to admin/config/regional/translate. Try to search for "Test NL" in the input field. It will give you the string on the left side along with a text-field to the right. Enter the translation for the "Test NL" in the text field. and click save translations.

You are done. Clear the cache and check the interface.
> 1 votes

---
Tags: 8, blocks, i18n-l10n
---


title: Adding namespace to s3 module

text:
# Question
Title: Adding namespace to s3 module
I have a drupal 7 codebase which I downloaded from a production server and set up locally (using PHP version 7). There is this `amazons3.module` file in which I have to add an extra `namespace Drupal\amazons3` to get it running. If I remove the line, the code throws an error stating : `Error: Class 'Drupal\amazons3\StreamWrapperConfiguration' not found in amazons3_upload_location() (line 345 of /xxx/yyy/sites/all/modules/amazons3/amazons3.module).`.

Why am I having to add this code when it is not there in the production version and nor in the github codebase ?

# Answer
I solved this by linking to the correct path where the composer was placed (as suggested by Japo).

EDIT:

In another server setup, the same issue was fixed by adding php-curl module.
> 0 votes

---
Tags: 7
---


# Question
Title: How to stop twig debug from breaking HTML when inside tags?
Originally this was in a views field rewrite but i have since moved it to

```
views-view-fields--[view name]--[machine ID].html.twig

```

And behaviour seems to be the same:

```
 <a href="{{ fields.path.content}}" class="menu-item">{{fields.title.content}}<span data-background-image="{{ fields.field_image.content}}"></span></a>

```

This renders fine when twig debug is set to false in development.services.yml When twig debug is turned on, the markup becomes badly broken.

I.e.

```
<span data-background-image="

    <!-- THEME DEBUG -->
    <!-- THEME HOOK: 'views_view_field' -->
    <!-- BEGIN OUTPUT from 'themes/mytheme/templates/views/views-view-field.html.twig' -->

    <!-- THEME DEBUG -->
    <!-- THEME HOOK: 'image_url_formatter' -->
    <!-- BEGIN OUTPUT from 'modules/contrib/image_url_formatter/templates/image-url-formatter.html.twig' -->
    http://mysite.local/sites/default/files/styles/menus_image/public/menus/image.png?itok=1ZnZSCkX
    <!-- END OUTPUT from 'modules/contrib/image_url_formatter/templates/image-url-formatter.html.twig' -->

    <!-- END OUTPUT from 'themes/mytheme/templates/views/views-view-field.html.twig' -->

    "></span>

```

HTML does not support `<!-- -->` inside tags, which seems to be the core issue. Is there a workaround to this, or it's just a limitation of Twig debug?

# Answer
You can apply `|render|striptags|trim` twig filters:

```
<a href="{{ fields.path.content|render|striptags|trim }}" class="menu-item">{{ fields.title.content }}<span data-background-image="{{ fields.field_image.content|render|striptags|trim }}"></span></a>

```

> If you want to save (not delete) for example `div or img tags` you can also write:
>
> **`{{ fields.field_image.content|render|striptags('<div>, <img>')|trim }}`**

Seen here https://www.drupal.org/node/2672656#comment-11821896
> 17 votes

---
Tags: theming, 8, debugging
---


# Question
Title: Standard way of getting a form inside block
I'm using :

```
public function build() {

    $form = $this->formBuilder->getForm('Drupal\mymodule\Form\Myformclass');
    return $form;
  }

```

to get form inside block. But Drupal community doesn't find it as an appropriate way to get form inside a block.

According to Drupal community module reviewing team, Do not hard-code class names in strings. I tried calling class directly but that is not serving my purpose, giving 505 error.

What's the right way to get a form inside a block?

# Answer
You can get the fully qualified class name by using `ClassName::class`:

```
use Drupal\mymodule\Form\Myformclass;

  public function build() {

    $form = $this->formBuilder->getForm(Myformclass::class);
    return $form;
  }

```

If you want to avoid the full classname in code.
> 6 votes

# Answer
The following code will help to load the custom form SampleDataForm defined on the path Drupal\mymodule\src\Form\ SampleDataForm.php

```
namespace Drupal\mymodule\Form;

class MymoduleSearchBlockForm extends SampleDataForm
{
  protected $formIdentifier;

  public function setFormIdentifier($formIdentifier)
  {
      $this->formIdentifier = $formIdentifier;
  }

  public function getFormId()
  {
    $form_id = 'sample_form';
    if($this->formIdentifier)
    {
        $form_id .= '-' . $this->formIdentifier;
    }
    return $form_id;
  }
}

```
> 0 votes

---
Tags: 8, forms, blocks
---


# Question
Title: How can I get the tid (term id) using the id of my node in .theme
I need to get the id of the node category.

I try this:

```
$variables['tid'] = $node->field_category->target_id;

```

# Answer
*I wrote this answer thinking the question was for Drupal 7. This is not accurate for Drupal 8.*

If you debug the $node object, you will see that it's more complicated than that. It has a language and probably a value index. So, you could access the TID this way:

```
$variables['tid'] = $node->field_category[LANGUAGE_NONE][0]['target_id'];

```

But, don't do it that way. It would be better to use EntityMetadataWrapper. The code should look something like this:

```
$wrapper = entity_metadata_wrapper('node', $node);
$variables['tid'] = $wrapper->field_category->raw();

```

If you want the whole term object, you can do this:

```
$variables['term'] = $wrapper->field_category->value();

```
> 1 votes

---
Tags: 8, nodes, taxonomy-terms
---


title: How to customise Webform results table

text:
# Question
Title: How to customise Webform results table
So its Christmas eve and this is really dampening the Christmas spirit.

I need to be able to customise the submissions results page table to show the county taxonomy for the submission user. I have never really done anything with SQL before but I can get all the information I need by running the below select query in phpMyAdmin:

```
SELECT `sid`, `nid`, `serial`, `uid`, `is_draft`, `submitted`, `remote_addr`,
field_data_field_counrty.field_counrty_tid as CountryID ,

(select name from taxonomy_term_data where taxonomy_term_data.tid=field_data_field_counrty.field_counrty_tid) as Country

FROM `webform_submissions`

inner join field_data_field_counrty  on webform_submissions.uid =field_data_field_counrty.entity_id

```

And i know that the below code is where it generates the submissions table in webform.submissions.inc:

```
// Build the list of submissions and load their basic information.
$pager_query = db_select('webform_submissions', 'ws')
// Ensure only one row per submission is returned. Could be more than one if
// sorting on a column that uses multiple rows for its data.
->distinct()
->addTag('webform_get_submissions_sids')
->fields('ws', array('sid', 'nid', 'serial', 'submitted', 'remote_addr', 'uid', 'Country', 'is_draft'));
foreach ($filters as $column => $value) {
$pager_query->condition($column, $value);
}

// Join to the users table to include user name in results.
$pager_query->leftJoin('users', 'u', 'u.uid = ws.uid');
$pager_query->fields('u', array('name'));
if (isset($filters['u.uid']) && $filters['u.uid'] === 0) {
if (!empty($_SESSION['webform_submission'])) {
  $anonymous_sids = array_keys($_SESSION['webform_submission']);
  $pager_query->condition('sid', $anonymous_sids, 'IN');
}
else {
  $pager_query->condition('sid', 0);
}
}

```

But i have no idea what to do from there. If anyone could offer any advice, tips or anything, I would really appreciate the help.

Happy holidays everyone!!

# Answer
OK, so I solved it myself.

Open and edit the webform.submissions.inc file in the includes folder of the module

In the **Return all the submissions for a particular node.** section find the code with the comment "// Join to the users table to include user name in results."

```
 // Join to the users table to include user name in results.
  $pager_query->leftJoin('users', 'u', 'u.uid = ws.uid');
  $pager_query->fields('u', array('name'));
  if (isset($filters['u.uid']) && $filters['u.uid'] === 0) {
    if (!empty($_SESSION['webform_submission'])) {
      $anonymous_sids = array_keys($_SESSION['webform_submission']);
      $pager_query->condition('sid', $anonymous_sids, 'IN');
    }
    else {
      $pager_query->condition('sid', 0);
    }
  }

```

To add my country section I had to find the table in phpMyAdmin that contained my taxonomy data. In this case it was "field\_data\_field\_counrty" (I've spelled country wrong i know but I couldn't change it after).

From that I figured out that the entity ID was the the user ID in the Users table. This is because I had used the country taxonomy on the registration form.

The syntax for the inner join query is 'Table, Table Alias, Condition, Arguments'. From that my innerjoin became,

```
 $pager_query->innerJoin('field_data_field_counrty ', 'fld_Country', 'fld_Country.entity_id = ws.uid' );

```

The field syntax is 'Table Alias, Field Name', so my field selection became,

```
$pager_query->fields('fld_Country', array('field_counrty_tid'));

```

This gave me the country ID number that had been assigned to the taxonomy term. I then had to cross reference that field with the taxonomy data table to retrieve the name of the country the ID referred to. That was done with another innerjoin.

```
$pager_query->innerJoin('taxonomy_term_data ', 'taxonomy_Country', 'taxonomy_Country.tid = fld_Country.field_counrty_tid' );

```

This time the field I needed to retrieve was called name. However, 'name' had already been used further up in the original code for the user name. So to add an alias to the field I had to use addField instead of fields. The syntax for addField is 'Table Alias, Field, Alias'. My code became,

```
 $pager_query->addField('taxonomy_Country', 'name', 'tax_name');

```

The code as a whole is:

```
 // Join to the field country table to include Country ID in results.
  $pager_query->innerJoin('field_data_field_counrty ', 'fld_Country', 'fld_Country.entity_id = ws.uid' );
  $pager_query->fields('fld_Country', array('field_counrty_tid'));
  $pager_query->innerJoin('taxonomy_term_data ', 'taxonomy_Country', 'taxonomy_Country.tid = fld_Country.field_counrty_tid' );
  $pager_query->addField('taxonomy_Country', 'name', 'tax_name');

```

Further down in the code is the section:

```
 $result = $pager_query->execute();

  $sids = array();
  foreach ($result as $row) {
    $sids[] = $row->sid;
    $submissions[$row->sid] = new stdClass();
    $submissions[$row->sid]->sid = $row->sid;
    $submissions[$row->sid]->nid = $row->nid;
    $submissions[$row->sid]->serial = $row->serial;
    $submissions[$row->sid]->submitted = $row->submitted;
    $submissions[$row->sid]->remote_addr = $row->remote_addr;
    $submissions[$row->sid]->uid = $row->uid;
    $submissions[$row->sid]->name = $row->name;
    $submissions[$row->sid]->is_draft = $row->is_draft;
    $submissions[$row->sid]->preview = FALSE;
    $submissions[$row->sid]->data = array();

```

In this section I added the line:

```
        $submissions[$row->sid]->CountryID = $row->tax_name;

```

To display the data, we now need to edit the webform.report.inc file. Find the section near the top that says,

```
 foreach ($submissions as $sid => $submission) {
    $row = array(
      $submission->is_draft ? t('@serial (draft)', array('@serial' => $submission->serial)) : $submission->serial,
      format_date($submission->submitted, 'short'),

    );
    if (webform_results_access($node, $user)) {
      $row[] = theme('username', array('account' => $submission));
      $row[] = $submission->remote_addr;

```

I then added the following line after the format\_date section to add my new column after the submitted column.

```
      $submission->CountryID,

```

To add the header for the new column find the section with the comment,

```
 * Theme the header of the submissions table.

```

I then added the following line after the submitted section,

```
    array('data' => t('Country'), 'field' => 'tax_name'),

```

Save both files and view a webform results page (providing it has a submission). Your new column should now display.

I hope this helps anyone else that is confused on this subject!

Happy new year everyone!!!
> 0 votes

# Answer
Also, it turns out, that because I was using a customised version of Webforms, I didnt realise you could make this as a view-block.

Now I just feel stupid.
> 0 votes

# Answer
`function webformmanager_menu_alter(&$items) {
 $items['node/%webform_menu/webform-results/table']['page callback'] = 'webform_results_table_new';
 }`

`function webform_results_table_new($node, $pager_count = 0) {
 if($node->nid==16650 || $node->nid==16654 || $node->nid==16655){
 $shiftitems = array();
 $components = array();
 if($node->nid==16650){
 $shiftitems = array(37, 35, 7, 27, 28, 29, 36);
 }
 elseif($node->nid==16654){
 $shiftitems = array(31, 35, 34, 26, 28, 29, 27);
 }
 elseif($node->nid==16655){
 $shiftitems = array(50, 35, 7, 48, 27, 47, 28, 29);
 }
 if(!empty($shiftitems)){
 foreach($shiftitems as $val){
 $movecomponent = $node->webform['components'][$val];
 $components[$val] = $node->webform['components'][$val];
 unset($node->webform['components'][$val]);
 }
 foreach($node->webform['components'] as $key => $val){
 $components[$key] = $val;
 }
 $node->webform['components'] = $components;
 }
 }
 return webform_results_table($node, $pager_count);
}`
> 0 votes

---
Tags: 7, webforms
---


title: How to show upload date fore each file

text:
# Question
Title: How to show upload date fore each file
I have a content type called 'Documents' which has 2 fields: `title` and `file`. There can be attached multiple files the `file` field.

But how can I show the upload date for every single file? I have tried using Views, but could only get the upload date for the first file, not the rest of the files.

How can I do this?

# Answer
> 0 votes
I fixed it using this solution https://www.drupal.org/node/1578484

```
function mytheme_file_formatter_table($variables) {
  $header = array(t('Attachment'), t('Size'), t('Date'));
  $rows = array();
  foreach ($variables['items'] as $delta => $item) {
    $rows[] = array(
      theme('file_link', array('file' => (object) $item)),
      format_size($item['filesize']),
      format_date($item['timestamp'], $type = 'short'),
      );
  }
  return empty($rows) ? '' : theme('table', array('header' => $header, 'rows' => $rows));
}

```

---
Tags: 7, files
---


title: Unusual text inserted in the SQL

text:
# Question
Title: Unusual text inserted in the SQL
I am getting some unusual text which is getting added to my queries in views. I am referring to the part setting `view_name`.

```
SELECT users.name AS users_name, users.uid AS uid, 'cardinality_user_test:page' AS view_name
FROM
{users} users
LEFT JOIN {node} node_users ON (SELECT nodeINNER.nid AS nidINNER, ':default' AS view_name
FROM
{node} node INNER LEFT JOIN {users} users_nodeINNER ON nodeINNER.uid = users_nodeINNER.uid
WHERE (( (users_nodeINNER.uid = users.uid ) ))
ORDER BY nodeINNER.nid DESC
LIMIT 1 OFFSET 0) = node_users.nid
LIMIT 10 OFFSET 0

```

This additional SQL is creating an error:

> SQLSTATE\[21000\]: Cardinality violation: 1241 Operand should contain 2 column(s)

What is causing that text to be added in Drupal 7?

# Answer
> 1 votes
That extra field is added from the Views module itself, in particular its `views_plugin_query_default::add_signature()` method, which is described as:

> Add a signature to the query, if such a thing is feasible.
> This signature is something that can be used when perusing query logs to discern where particular queries might be coming from.

If you look at its code, it is setting the *view\_name* field.

```
function add_signature(&$view) {
  $view->query->add_field(NULL, "'" . $view->name . ':' . $view->current_display . "'", 'view_name');
}

```

---
Tags: views
---


title: Exporting Custom Menu Translation

text:
# Question
Title: Exporting Custom Menu Translation
Question: **How do I export/import translation of Custom Menu Items**

I have a module that takes all the .po files for custom strings and then uses locale to batch import them. This works great.

I was wanting to translate my custom menu links, but when I search for them in the translate interface (or searching the .po from exporting my translations) I am unable to find any of the menu items.

I've included my admin/config/regional/content-language settings below so you can see that Custom Menu Link (and it's menu link title) is ticked.

I **am** able to translate the menu items only by going to `admin/structure/menu/item/#/edit/translations`, but this isn't (seemingly) exportable in either the .po files (via locale export), nor the config management system (via drush cex).

Anyone know how to do this? Thanks in advance.

# Answer
> 0 votes
So what I ended up doing was to create a module that reads from a json file, and adds the translation. (Import controller + drush command)

a) Load up the custom menu items by menu name:

```
$main_menu_items = \Drupal::entityTypeManager()->getStorage('menu_link_content')->loadByProperties(array('menu_name' => $menu_name));

```

b) Go through your menu items, foreach of them check if your menu link title matches one in your json/po file/config.

c) Check if you already have a translation on that menu item, then remove the old translation or skip.

```
if ($menu_item->hasTranslation('fr')) {

```

d) Finally add the translation that exists in your file.

```
  $menu_item_fr = $menu_item->addTranslation('fr');
  $menu_item_fr->title = $translation_json[$menu_name][$link_title];
  $menu_item_fr->description = '';
  $menu_item_fr->save();

```

This is essentially what my json looked like:

```
{"menu_name": {"english_link_title":"french_link_title"}}

```

Do hope this helps someone else, or someone can think up a better answer.

---
Tags: 8, i18n-l10n, configuration
---


# Question
Title: Is there any way to alter the response of JSON API module?
I am using JSON API module to expose data using REST API. I want to alter its response. I am trying to altering it using `hook_ENTITY_TYPE_load`. If I change any existing property it shows the updated value. But if I try to add custom property it doesn't show the custom property in response. The two hooks I used are below:

```
function my_custom_entity_type_alter(array &$entity_types) {
  $entity_types['node']->set('flag_count', 10);
}

function my_custom_node_load($nodes) {
  foreach ($nodes as &$node) {
    $node->flag_count = 10;
  }
}

```

I need to know if there is any possible way to alter the json api response with custom properties?

# Answer
Please see how `jsonapi_entity_base_field_info` adds a computed property to the `file` entities. That should do.

If you don't want to create a *virtual* field, you can add a normalizer that only acts for that specific content type as a service. You'll need to use a higher priority than `serializer.normalizer.entity.jsonapi` (set to 21). Your custom normalizer can inherit from `Drupal\jsonapi\Normalizer\ContentEntityNormalizer` and add your custom stuff in `getFields`.
> 4 votes

# Answer
You can create your own custom normalizers to alter the JSON response.

Some good resources:
> 1 votes

# Answer
I suppose you should be using `hook_entity_type_build` rather than `hook_entity_type_alter`, which states:

> Do not use this hook to add information to entity types, unless one of the following is true:
>
> * You are filling in default values.
> * You need to dynamically add information only in certain circumstances.
> * Your hook needs to run after hook\_entity\_type\_build() implementations.
>
> Use hook\_entity\_type\_build() instead in all other cases.

And EntityTypeInterface states

> Additional information can be provided by modules: `hook_entity_type_build()` can be implemented to define new properties, while `hook_entity_type_alter()` can be implemented to alter existing data and fill-in defaults.

You might want to try something like this instead:

```
function my_custom_entity_type_build(array &$entity_types) {
  /** @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */
  $entity_types['node']
    ->set('flag_count', 10);
}

```
> 0 votes

---
Tags: 8
---


# Question
Title: node_load_multiple does not respect node access grants
I used `$nodes = node_load_multiple(NULL, array("title" => "Foo Bar"));` to fetch nodes by titles. But after going through **Drupal security standards**, `node_load_multiple` is not the right way to load all nodes.

`node_load_multiple()` will load ALL nodes regardless of access, so that must not be used here.

**Solution suggestion is:**

> Use an entity query instead. "When adding a node listing to your module, be sure to use an entity query, which will add a tag of "node\_access". This will allow modules dealing with node access to ensure only nodes to which the user has access are retrieved"

But I'm not sure how to apply above statement programmaticly?

Is below query the right way that solves security issues?

```
\Drupal\node\Entity\Node::loadMultiple(NULL, array("title" => "Foo Bar"));

```

**If not, please suggest an appropriate alternate of loading nodes by title that respects node access grants.**

# Answer
You can do it like this. First, query the NIDs, with a query that is tagged for node access, then load the nodes with the found NIDs.

```
$nids = db_select('node_field_data', 'n')
  ->fields('n', ['nid'])
  ->condition('title', $my_title)
  // The node_access tag will check access rights.
  ->addTag('node_access')
  ->execute()
  ->fetchCol();

$nodes = Node::loadMultiple($nids);

```

Untested in D8, but it should work.
> 2 votes

# Answer
You could get all the node titles with a SQL query like:

```
  $row = db_query('SELECT nid FROM {node} WHERE title = :mytitle',   array(':mytitle' => $myNewTitle))->fetchField();
   if(!isset($row['nid'])) {
//safe to continue
     } else {
//that title is already there and its in node with node id "nid"
 }

```

And if there are no results returned then you may assume you're good to go.
> 0 votes

---
Tags: 8, nodes, security
---


title: hook_theme with custom path

text:
# Question
Title: hook_theme with custom path
I need choose different template based on the path (current\_path()?)

user/register/\* AND user/register/recruiter/\*

I started with hook function

```
function ohm_theme(){
    $hooks = array();
    $hooks['user_register_form'] = array (
        'render element' => 'form',
        'path' => drupal_get_path('theme','ohm')."/layouts/hero",
        'template' => 'user-register-form',
        'preprocess functions' => array('ohm_preprocess_user_register_form'),
    );
    return $hooks;
}

```

Which works fine only for user/register page

Then I would like to specify the new template suggestion user/register/recruiter/\* using

```
function ohm_preprocess_user_register_form(&$vars) {
   dsm($vars);
}

```

but I can't figure out how to add condition using current\_path() inside this.

Thank you

# Answer
> 1 votes
Is this Drupal 7? If so, you can do this:

```
function ohm_preprocess_user_register_form(&$vars) {
   $current_path = current_path()
   $variables['theme_hook_suggestions'][] = 'user_register_form__' . str_replace('/', '-', $current_path);
}

```

This should allow you to use user-register-form--user-register-recruiter.tpl.php

---
Tags: theming, users
---


# Question
Title: Import to Entityform via Feeds? Feeds entity processor module?
I've built an Entityform and now would like to use Feeds importer to add entries. Feeds does not seem to offer a processor for Entityform. I've done some digging and found the Feeds entity processor module.

Will this module allow me to target my Entityform via a Feeds importer?

The Feeds entity processor page offers this info:

> This module provides a generic processor for all entity types that support CRUD operations through the Entity API module.

I've done some digging into this too, but can't quite determine if this will do what I need. If there are other ways/modules that will help, I'm all ears!

---

**FYI:** *Due to restrictions in my development environment, I can't simply give it try (wish I could!). I need to make requests for new modules to be installed... so I need to be pretty darn sure something is going to do what I need before I make the request.*

# Answer
> 0 votes
**CONFIRMED!** Feeds entity processor module will allow importing directly into an Entity form via a feeds importer.

---
Tags: entities, feeds, importing-exporting
---


# Question
Title: Regions missing on page templates defined in a controller
I have two custom blocks that I created in files placed in the modules/custom/mymodule/src/Plugin/Block folder.

I defined two extra regions in the mytheme.info.yml file I placed the blocks in the regions using the 'Block layout' page in the admin area.

It's all working great on all pages that use the "normal" twig template naming conventions, such as page.html.twig, page--front.html.twig and other templates I created based on the suggestions in the comments twig debug outputs.

My problems started when I created templates via a Controller. Here is an example from my routing.yml file:

```
mytheme.bikes:
  path: '/catalog/Bikes'
  defaults:
    _controller: '\Drupal\mytheme\Controller\MyPageController::catalog_bikes'
    _title: 'Bikes'
  requirements:
    _permission: 'access content'

```

And the controller:

```
public function catalog_bikes() {
  return array(
    '#type' => 'page',
    '#theme' => 'page__bikes',
  );
}

```

If i go on mysite.com/catalog/Bikes the page--bikes.html.twig template is loaded, BUT, without the extra regions I added to mytheme.info.yml file

# Answer
Are you rendering the regions in your twig template?

Like

```
{{ page.custom_region }}

```
> 0 votes

# Answer
You've got a fundamental misunderstanding here on how the controller will work. When you return a response from a controller, it becomes the content on that page. You cannot assign the template for the page in your controller. If you want to use page--bikes.twig.html on that path, then you need to implement hook\_theme\_suggestions\_HOOK\_alter(), using the current path to determine the template suggestion(s):

```
hook_theme_suggestions_HOOK_alter(array &$suggestions, array $variables)
{
  $current_path = \Drupal::service('path.current')->getPath()
  $path_args = explode('/', $current_path);
  // Check if we are on a catalog path, and that there is an
  // specific element on that page
  if($path_args[0] == 'catalog' && isset($path_args[1]))
  {
    $suggestions[] = 'page__catalog__' . $path_args[1];
  }
}

```

This will allow you to use page--catalog--bikes.twig.html if you are on the /catalog/bikes page. I would suggest using 'catalog' as part of the template name, to prevent potential collisions with other modules.
> 0 votes

---
Tags: 8
---


# Question
Title: Using page field value in a metatag in <head>
I would like to edit my `html.html.twig` template to assign a value to a metatag in `<head>` according to the value of a field of a page. Is that possible?

I was trying things like `{{ page.myfield.value }}`, but with no success and haven't found anything helpful online.

# Answer
You need to attach the tag in hook\_node\_view() (which is derived from hook\_ENTITY\_TYPE\_view(), when the view mode is full (which makes the assumption that the full view mode is only ever used on node pages).

You can do that as follows:

```
function hook_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $mpde, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode)
{
  // Check if the view mode is full
  if($view_mode == 'full')
  {
    // Create the tag. You can set the content of the
    // metatag from the node
    $tag = [
      '#tag' => 'meta',
      '#attributes' => [
        'name' => 'name attribute of metatag',
        // Note that 'value' will differ depending on the
        // field type.
        'content' => $node->get('field_something')->value,
      ],
    ];

    // Attach the meta tag to the header.
    $build['#attached']['html_head'][] = [$tag, 'some_key_to_represent_tag'];
  }
}

```
> 1 votes

---
Tags: theming, 8
---


# Question
Title: feeds importer importing from several sources
Is it possible to run one feed importer on several sources?

Currently my code is as follow:

My importer module file is

```
function myModule_import_feeds_plugins() {
  $info = array();
  $info['xml_parser'] = array(
    'name' => 'XML feed parser',
    'description' => 'Imports XML feed.',
    'help' => '',
    'handler' => array(
      'parent' => 'FeedsParser',
      'class' => 'myXmlParser',
      'file' => 'my_xml_parser.inc',
      'path' => drupal_get_path('module', 'myModule_import') . '/plugins/feeds',
    ),
  );

```

My parser is:

```
class myXmlParser extends FeedsParser {

  /**
   * Implements FeedsParser::parse().
   */
  public function parse(FeedsSource $source, FeedsFetcherResult $fetcher_result) {
    $feed = new SimpleXMLElement($fetcher_result->getRaw());
    $source_feed = $source->config['FeedsHTTPFetcher'];
    $user_tags = isset($source_feed['user_tags'][0]) ? explode(',', $source_feed['user_tags']) : array('tag1', 'tag2');

    $result = new FeedsParserResult();
    $result->title = 'feed importer';
    $result->items = array();
    #$fetcher_result->
    foreach ($feed->channel->item as $item) {
      // Skip if title doesn't
      if ((string) $item->title) {
        $result->items[] = array(
          'title' => (string) $item->title,
          'callout' => '<p>'.(string) $item->description.'</p>', // wrap light_html in P tags
          'pubdate' => (string) $item->pubDate, // _parser_common_syndication_parse_date()
          'url' => (string) $item->link,
          'image_url' => (string) $item->thumb, // http://placekitten.com/g/200/300
          'image_alt' => (string) $item->alt,
          'published' => 1,
          'tags' => $user_tags,
        );
      }
    }

    return $result;
  }

```

feed screen looks like this

I would like to add an additional field for an optional URL. This way the user can include several sources and import from different places at the same time.

I could not find a way to do so. Ideas?

# Answer
> 1 votes
Yes, there is. The supported way of importing multiple sources for one importer is to attach the importer to a content type (which can be configured under the "Basic settings"). Attaching an importer to a content type means that a node must be created to import content. Since you can create multiple nodes, you can import multiple sources with one importer configuration.

Be sure though that if you are importing nodes (using the Node processor) that the nodes you create are of a different type than the node type that you attach an importer to. It is wise to create a new content type that is specifically only used for your importer.

See also my answer at https://www.drupal.org/node/2854548#comment-11948926 for more information about why you should not attach an importer to the same content type as the one you select on the processor settings.

---
Tags: feeds
---


title: ordering cron of cloned feeds importer

text:
# Question
Title: ordering cron of cloned feeds importer
I have two simple feed importers (one is the clone of the other, Feeds Admin UI and clicked clone under structure/feeds).

I would like to run both of them via cron.

if I go to

```
admin/structure/feeds/feed1/settings

```

and to `basic setting`, I can set `Periodic import` to every X hours.

Is there a way to set it that feed1 will run first every X hours, and feed2 will run right after feed1?

# Answer
No, but you could try Feeds Ultimate Cron to achieve what you want: https://www.drupal.org/project/feeds\_ultimate\_cron
> 1 votes

---
Tags: feeds
---


# Question
Title: Determine conditions for Rules when changing field value
I've a Rule with below specification

**Events:**
`After updating an existing user account`

**Conditions:**
`???`

**Actions**
`Create a Message`

But I don't know how can I set a condition on field in rule condition part that return true when the field changed,any body know how can I add condition on specified field that return true when the field changed?

# Answer
You need to create the rule for **Before saving content** rather than **After saving content**.

**Before saving content** has both the original node values and the new updated values which allows you to compare the values.

**After saving content** only has the updated values, so you won't be able to see what the old values are.
> 9 votes

# Answer
Condition: **Data comparison**

**DATA TO COMPARE**

In **Data selector** you have two different states "*account (updated user)*" and "*account-unchanged (unchanged user)*".
Check field from *account (updated user)* and click "Continue".

On next screen click "Switch to data selection" button and find your field but from *account-unchanged* state.

Select **Value** to *equals* and don't forget to check "Negate" at very bottom.
> 1 votes

---
Tags: 7, users, rules
---


# Question
Title: How to do System Tests / Functional Tests with an existing database
the last few weeks and days I have been reading into Drupal 8 testing with phpunit.

For a project I want to use Unit testing to test out functionality and services and the cooperation between different components.

Run the tests against an **existing database / installation** and **not** against a fresh Drupal installation, since we have configured a lot already and I need to make sure the new code does work with the whole configuration and data.

I can Unit tests to test out simple functions or classes but what I cannot use is the BrowserTests or KernelTest bases since they all create a new, fresh installation.

Maybe I have misunderstood something or I am on the wrong path.

Can anybody help me out or has an example on how to do that?

# Answer
I have once answered this exact same question for Drupal 7. Though some things have changed, the concept remains the same; extend the test class.

The normal setup of a BrowserTest would look something like this:

```
  /**
   * {@inheritdoc}
   */
  public function setUp() {
    parent::setUp();

    // Create an article content type that we will use for testing.
    $type = $this->container->get('entity_type.manager')->getStorage('node_type')
      ->create([
        'type' => 'article',
        'name' => 'Article',
      ]);
    $type->save();
    $this->container->get('router.builder')->rebuild();
  }

```

All you need to is to remove the database definitions from `parent::setUp();`

So copy `setUp()` from core/tests/Drupal/Tests/BrowserTestBase.php and remove the database definitions. That should make the test run on the current database.

Though this is very simplistic and you might run into more problems along the way. All is in the `BrowserTestBase` class. Make sure to read my other answer, make sure to implement the teardown properly. And most of all, make proper backups!
> 2 votes

---
Tags: 8, testing
---