# Question
Title: How can I reduce the cache_default table?
The views\_data:fr BLOB data IN THE cache\_default TABLE is too large, and I get this error when I try to import the table on a shared server (OVH).

> ERROR 1118 (42000) at line 3302: The size of BLOB/TEXT data inserted in one transaction is greater than 10% of redo log size. Increase the redo log size using innodb\_log\_file\_size.

```
INSERT INTO `cache_default` (`cid`, `data`, `expire`, `created`, `serialized`, `tags`, `checksum`) VALUES
('views_data:fr', 0x613a3135303a7b733a383a227761746368646f67223b613a31323a7b733a353a227461626c65223b613a343a7b733a353a2267726f7570223b4f3a34383a2244727570616c5c436f72655c537472696e675472616e736c6174696f6e5c5472616e736c617461626c654d61726b7570223a333a7b733a393a22002a00737472696e67223b733a383a225761746368646f67223b733a31323a22002a00617267756d656e7473223b613a303a7b7d733a31303a22002a006f7074696f6e73223b613a303a7b7d7d733a393a2277697a6172645f6964223b733a383a227761746368646f67223b733a343a2262617365223b613a333a7b733a353a226669656c64223b733a333a22776964223b733a353a227469746c65223b4f3a34383a2244727570616c5c436f72655c537472696e675472616e736c6174696f6e5c5472616e736c617461626c654d61726b7570223a333a7b733a393a22002a00737472696e67223b733a31313a224c6f6720656e7472696573223b733a31323a22002a00617267756d656e7473223b613a303a7b7d733a31303a22002a006f7074696f6e73223b613a303a7b7d7d733a343a2268656c70223b4f3a[...]

```

I know that increasing the value of *innodb\_log\_file\_size* solves problem, but it's impossible in a shared server.

Is it possible to reduce this table?

I tried disabling the view caching in the advanced settings, disabling the cache for that single view, but it has no effect.

I feel that the more views we have, the more space the *views\_data:fr* column takes.

# Answer
You might try compressing the data before sending it. There's a module for that: compressed\_cache
> 0 votes

---
Tags: views, database
---


# Question
Title: How do I submit call handler on radio button selection?
I use the advanced polls module in Drupal 7. I am trying to alter the behaviour so that the vote is submitted as soon as the radio button is selected (without having to hit *Vote*).

The module is using an ajax callback:

```
$form['submit'] = array(
'#type' => 'submit',
'#ajax' => array(
  'callback' => 'advpoll_form_submit',
  'wrapper' => 'advpoll-form-' . $values->nid,
  'name' => 'submit1',
),
'#id' => 'edit-submit-advpoll-' . $values->nid,
'#value' => t('Vote'),

```

);

How can I invoke this callback with radio buttons?

I am happy for a quick and dirty javascript/jQuery solution as time is a real factor.

I have tried a jQuery solution:

```
$('input[type="radio"]').change(function() {
  $('#advpoll-form-296').trigger('click');
});

```

However this is not invoking the action as expected.

I cannot call submit() as I don't want to cause a page reload.

I have managed to get my original code to fire by adding a click event to the ajax array in the .module file.

advpoll.module:

```
function advpoll_choice_form($form, &$form_state, $values) {

$form['submit'] = array(
'#type' => 'submit',
'#ajax' => array(
  'callback' => 'advpoll_form_submit',
  'wrapper' => 'advpoll-form-' . $values->nid,
  'name' => 'submit1',
  'event' => 'click', //Added click event
),
'#id' => 'edit-submit-advpoll-' . $values->nid,
'#value' => t('Vote'),

```

);

I am aware I should not override code within the module. How would I go about getting this into a theme hook?

# Answer
> 2 votes
This should do it:

```
$(function() {
  $('input[type="radio"]').on('change', function() {
    $(this).parents('form').submit();
  });
});

```

You might want to qualify the selector for `$('input[type="radio"]')` to the scope of the form you're working with, else if you include this in a JavaScript file that's accessed on many different pages, you'll definitely run into problems!

Demo: http://plnkr.co/edit/8448bjiywnVtbT3CV6s6?p=info

# Answer
> 1 votes
It's been a while since this was posted but I hope this answer can help anyway

The simple way I found to do it (I'm using the advpoll module as well) is to add the same AJAX handler to the options dropdown using `hook_form_alter`

So, in my custom module:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  // The submit form has ID advpoll_choice_form
  if ($form_id == 'advpoll_choice_form') {
    foreach ($form as $key => &$value) {
      // It seems that the radio buttons are under an array labelled 'choice_X'
      // where X is the number of options you have, so this just checks
      // it's doing it to the correct one
      if (substr($key, 0, 7) == 'choice_') {
        // Apply the same AJAX handler the submit button has to the radio buttons
        $value['#ajax'] = $form['submit']['#ajax'];
      }
    }
  }
}

```

Hope this helps someone in the future

---
Tags: 7, javascript, hooks, polls
---


# Question
Title: How do I display data in a dynamically created page
I have a form on the page that has multiple fields, one of which is a path (www.sample.com/PATH). With form data that I have, I need to forward to that dynamic page, and display form data (5 nodes for example).

This is the code I am using.

```
function MODULE_menu() {
  $items = array();
  $items['admin/URL_TO_SEE_FORM'] = array(
    'title' => 'Some title',
    'description' => 'Desc',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('MODULE_form'),
    'access arguments' => array('administer users'),
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

function MODULE_form($form, &$form_state) {

  $form['form_path'] = array(
    '#type' => 'textfield',
    '#title' => t('Path'),
    '#size' => 60,
    '#maxlength' => 128,
    'autocomplete_path' => FALSE,
    '#required' => TRUE,
  );

  // other code that get's different data with ajax etc.

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

  return $form;
}

function MODULE_form_validate($form, &$form_state) {
  // some validation
}

function MODULE_form_submit($form, &$form_state) {

  $form_path = trim($form_state['values']['form_path']);

  $nodes = $form_state['values']['nodes'];
  // I need to get content from nodes ids whic should be easy

  // Need to set content to page under www.sample.com/$form_path

  $form_state['redirect'] = $form_path;
}

```

How can I do it?

# Answer
I've managed to do it by using Views module.

On first submit, I would dynamically create view, and on each concurrent submit I would create additional view display (page).
> 0 votes

---
Tags: 7
---


# Question
Title: How to upgrade Acquia desktop to php 7.1?
Drupal 8.4 requires php version greater than 7.1 . In acquia devdesktop default we are getting php 7.0. How to upgrade php 7.0 to php 7.1 in Acquia dev desktop?

Thank you.

# Answer
DevDesktop 2 now supports PHP 7.1.

Updated components in the latest version:

> * Added option to use **PHP 7.1**
> * MySQL Windows build) updated to 5.6
> * Percona (Mac build) updated to 5.6
> * Drush updated to 8.1.15
> * In addition, the feedback submission function within the app has been fixed.
> 3 votes

# Answer
You can't at the moment. It's in Dev Desktop's known issues

> * **Incompatible with Drupal 8.4.0 and greater**
>
> The following issues affect attempts to use Drupal 8.4.0 and greater with Acquia Dev Desktop:
>
> + Acquia Dev Desktop includes Drush version 8.1.10, but does not include Drush version 8.1.14 (which is required by Drupal versions 8.4.0 and greater).
>     + If you execute composer update for a website, Composer will also attempt to update the Doctrine library to a version that requires PHP 7.1, which is incompatible with Acquia Dev Desktop.
> * **Incompatible with PHP 7.1**
>
> Acquia Dev Desktop includes PHP version 7.0, but does not include PHP 7.1.
> 2 votes

# Answer
It is possible to continue to use Acquia Dev Desktop with Drupal 8.4. It doesn't require PHP 7.1, and can run in the PHP 7.0 within Dev Desktop. The real issue is the bundled version of Drush. Assuming you're on a Mac, make sure you have a brew install of Composer running on your machine. For more on that go here:

https://pilsniak.com/install-composer-mac-os/

Once that's done all you need to do is go here:

/Applications/DevDesktop/tools/

Edit the composer.json file within there, and update the drush version to the one below:

```
{
    "require": {
        "drush/drush": "8.1.15"
    }
}

```

Once you save that run a composer update and you should be good to go.

The alternate route is to require drush in your project's composer.json file which is a simple

```
composer require drush/drush

```
> 1 votes

# Answer
It's true. DevDesktop 2 now supports PHP 7.1

You must to update to the latest version (December 2017). I do not know why, but from the DevDesktop panel it did not give this update. Also I was still using the April 2017 version.
> 1 votes

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


# Question
Title: Update all nodes with a default field after adding a new field to the content type
I have an existing content type with a number of nodes. I have just added a new boolean field with a default value of "off."

However, until I re-save each node the default value is not set, so a view that should shown only those nodes where the new field is using the default value is currently empty.

How can I update the existing nodes, created before the field has been added, to set that field to its default value?

# Answer
Sadly, there's no very simple way to do this (besides VBO/rules), but here's the code I use in update functions in my custom module install files when I need to prepopulate field values for a certain node type after adding a new field (in this case, 'page' nodes):

```
<?php
// Get all nodes of 'page' type, populate the field with a value of '1'.
$pages = db_query("SELECT nid, vid FROM {node} WHERE type = 'page'")->fetchAllAssoc('nid');
foreach ($pages as $nid => $values) {
  $fields = array(
    'entity_type' => 'node',
    'bundle' => 'page',
    'deleted' => 0,
    'entity_id' => $values->nid,
    'revision_id' => $values->vid,
    'language' => LANGUAGE_NONE,
    'delta' => 0,
    'field_page_new_field_value' => 1,
  );
  db_insert('field_data_field_page_new_field')
    ->fields($fields)
    ->execute();
  db_insert('field_revision_field_page_new_field')
    ->fields($fields)
    ->execute();
}
?>

```

Another manual method mentioned in this answer uses EntityFieldQuery and loads/saves each node. More Drupal-y, but way less performant... (requires a full node load and save operation for each node!).
> 11 votes

# Answer
Best bet is directly in the MySQl. The tables would look like:

```
field_data_field_newbooleanfieldname
field_revision_field_newbooleanfieldname

```

If you look at them it's pretty straightforward - do you need me to get you started on what the query would look like or are you ok from here?
> 2 votes

# Answer
I found an easy way to update field(s) in content type with this module : Field Defaults

See screen shot. You can update existing content with the default value(s) or keep existing values.

I’ve tested it on D7 and it works.
> 1 votes

# Answer
Just try the bellow logic. its much faster and its by pass all the hook implementations also. more details. you can writes a simple direct db\_select query to get the all the nid's and loop it with this sample code.

```
$node = new stdClass();
$node->nid = $val;
$node->type = 'NODETYPE';
$node-field_whatever[LANGUAGE_NONE][0]['value'] = 'VALUE';
field_attach_presave('node', $node);
field_attach_update('node', $node);

```
> 0 votes

# Answer
using sql , considering that nodes with the field value not set are

```
SELECT nid,vid
 from node where type='procedure' and nid not in (select entity_id from field_data_field_pr_choix_du_document)

```

field\_data\_field\_pr\_choix\_du\_document being the table corresponding to my field and containing one entry par value set with entity id referinng the node

i did using SQL insert...select syntax

https://dev.mysql.com/doc/refman/5.5/en/insert-select.html

```
INSERT INTO `field_data_field_pr_choix_du_document` (`entity_type`, `bundle`, `deleted`, `entity_id`, `revision_id`, `language`, `delta`, `field_pr_choix_du_document_value`)
SELECT 'node','procedure',0,nid,vid,'und',0,'Importer un document'
from node where type='procedure' and nid not in (select entity_id from field_data_field_pr_choix_du_document)

```
> 0 votes

# Answer
Install and enable the Views Bulk Operations module and create a view with a page display.

Add =\> Bulk operations: Content (Content) field in view.

Refer

Select the Fields you want to set the default value.

Save the view, and go to the page it created. If you have more than one page of results, you can choose to select all items on the current page, all items on all pages, or you can manually check boxes corresponding to individual nodes. At least one checkbox must be checked to proceed.

Now you set the default value and save it.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Common Custom PHP Library: Drupal 8 and Stand-alone Shell Scripts
I have a Drupal 8 custom module that contains 5K of php in 10 classes. This code is production ready for the launch of a new website.

I also have code that runs from non-drush shell scripts. One example is the creation and distribution of a newsletter that runs from crontab. This pulls data from Drupal and creates a multi-part (html & plain text) email in multiple languages.

There is overlap between these two sets of code that would like to eliminate. How can I create a single php code library that can be shared between Drupal 8 and also used in standalone shell scripts?

There seems to be two approaches here:

(1) place all code in the custom module and Include it in shell scripts

I understand how to accomplish the custom module part of this. I don't know how to do the include into a stand-alone shell script from the Drupal directory.

(2) place all code in an external library and Include it in the custom module, the shell scripts and anywhere else I need it

This approach seems to have more flexibility. It addresses my original issue of sharing code between Drupal custom modules and stand-along scripts. It also allows the same code to be used in multiple projects -- separate Drupal 8 installs perhaps for difference clients.

How can I pull a custom php library (not on packalist.org) into my Drupal custom module? If this is possible, I will likely move most/all of my Drupal and Shell Script PHP code to a common external library that is under github change control.

# Answer
> 4 votes
It's possible to pull custom php libraries into your project with composer. You'll need to define the repository in the repositories section. Checkout handling private packages and repositories in composer's documentation. It's really fairly easy. If you have a single github repo you can include the repository info like below:

```
"repositories": [
    {"type": "composer", "url": "https://packages.drupal.org/8"},
    {"type": "vcs", "url": "https://github.com/myorg/mypackage"}
]

```

You should include a `composer.json` file in your repo as you'd probably expect. Here is a simple one to get you started:

```
    "name": "myorg/mypackage",
    "description": "My Package is the greatest!",
    "license": "proprietary",

    "autoload": {
        "psr-4": {"Myorg\\Mypackage\\": "src/"}
    }

```

Now your code can by placed in scr/Myclass.php with a

```
namespace Myorg\Mypackage;

Class Myclass {}

```

Choosing which version to pull in is a little but confusing. When you include a branch you need to prefix the branch nave with `dev-`, e.g. `dev-master` for the master branch. Otherwise, you can create tags and pull them in by their name, e.g. `1.0.0`, etc. I've used this technique successfully with bitbucket.

Some inclusion examples where your composer.json in your repo defines your package name as `myorg/mypackage`:

```
// This will pull whichever branch is marked as the "default" branch in your repo
composer require myorg/mypackage

// This will pull the "develop" branch
composer require myorg/mypackage:dev-develop

// This will pull in the "2.1.3" tag
composer require myorg/mypackage:2.1.3

// You can also use "^" and "~" with tags
composer require myorg/mypackage:^2.1.0

```

You can tell composer where to put your package by adding a new item to the `extra.installer-paths` section of composer.json. For example, if you want to install your package to `web/modules/custom` add a line like:

```
"extra": {
    "installer-paths": {
        "web/modules/custom/{$name}": ["vendor:myorg"],
        ...
        "web/core": ["type:drupal-core"],
        ...
    }
}

```

If your repos are private, you may have some issues pulling your repo as a package. I've worked around this issue by using my ssh key for access to the repos and making sure anyone who runs `composer require myorg/mypackage` also uses the ssh key method.

An alternate technique is to create a zip release of your package and include it as a repository as the chosen module's README explains.

---
Tags: 8, theming
---


# Question
Title: Change the submit handler of a form of a module
I installed base cart module and I need to totally overwrite the submit handler of one of its forms and not to execute its default functionality at all. From what I searched, I wrote this code in `template.php` :

```
function ThemeName_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'order_node_form'){
    $form['#submit'] = 'submit';
    $form['#validate'] = '';
  }
}

function submit() {
  return "submit";
}

```

But it is not working. Is it possible to do this in `template.php` or I need to build a module to do this? or the problem is from anything else?

Thanks

# Answer
> 2 votes
I think that it solves the problem to do like this

```
$form['#submit'] = array("my_module_form_submit_handler");

```

Here's the whole function:

```
function my_theme_form_alter(&$form, $form_state, $form_id) {
  $form['#submit'] = array("my_module_form_submit_handler");
}

function my_theme_form_submit_handler($form, &$form_state) {
  drupal_set_message("The form is being submitted, do some extra stuff now...");
}

```

---
Tags: 7, forms
---


title: Disable links on Forum Containers

text:
# Question
Title: Disable links on Forum Containers
Using Drupal 8, is there a way to disable the links of the Forum Containers on the Index Page of the Forum (Forum is activated via the Forum core Module)?

# Answer
You can do this with jQuery, like this:

```
$(".link-class").click(function(event){
    event.preventDefault();
});

```
> 1 votes

---
Tags: 8, nodes
---


# Question
Title: AJAX call, hook_menu the requested url does not exist
I want to create an AJAX request. I first implemented `hook_menu()` and added this code in that hook.

```
$items['aug_store_front/get-products/ajax'] = array(
  'title' => t('Get products from specific product group'),
  'page callback' => 'aug_store_get_products',
  'access callback' => array('access content'),
);

```

The code for the page callback is the following one.

```
function aug_store_get_products($value) {
  if($_POST['id'] = 6) {
    return drupal_json_output(array('status' => 'success'));
  }
  return drupal_json_output(array('status' => 'failure'));
}

```

I added this codein a JavaScript file.

```
jQuery(function($) {
  $(".view-aug-store-frontpage li a").click(function(e) {
    e.preventDefault();
    $.post('/aug_store_front/get-products/ajax', {
      id: 6,
    });
  });
});

```

When I click on the list element, the request is made, but I get a 404 error.

>

What did I do wrong?

# Answer
> 1 votes
You've confused `access arguments` with `access callback`. It should be:

```
$items['aug_store_front/get-products/ajax'] = array(
  'title' => t('Get products from specific product group'),
  'page callback' => 'aug_store_get_products',
  'access arguments' => array('access content'),
);

```

---
Tags: javascript, ajax
---


# Question
Title: How to add the "user role field" in View showing users
I created a view showing users. Then I have a list of users. I need to add a field to show the user role. I clicked **add field** but I don't see this field. Do I need to add a relationship to have this field available?

**Update:** I have Aggregation enabled.

# Answer
> 3 votes
So you need to add 2 field into your view `User uid`(exclude from display) and `Custom text`, next go to your `template.php` and do next

```
//implement hook_preprocess_views_view_fields
function YOURTHEME_preprocess_views_view_fields(&$vars) {
    $view = $vars['view'];
    $fields = $vars['fields'];

    if ($view->name == 'usr1') { // change on your view name
        $results = $view->result;
        $roles = array();
        foreach ($results as $row) {
            $user = user_load($row->uid);
            $roles = implode(', ',$user->roles ); //get all user roles
            //check if user name from field equal to current user in array
            if ($fields['name']->raw === $row->users_name) {
                $fields['nothing']->content = $roles;//put that roles to custom text field
            }
        }
    }
}

```

THIS CODE NEED IMPROVEMENTS, cuz it iteracts on every field of your view, so you can work on this :D.

# Answer
> 2 votes
Try to **disable Aggreegation, enable the Role field and then enable again the Aggreegation**.

Notice that the Role field is a multi-value one (Roles is a list).

So if I understand well you should better use a module like https://www.drupal.org/project/views\_aggregator.

# Answer
> 0 votes
There should be User:Roles available in field list.

---
Tags: 7, views, users
---


# Question
Title: How to record a log message when saving a Commerce Order via Drupal EntityWrapper?
I'm modifying a set of orders programmatically and want to record a log message when doing so.

Is there an existing method to add a revision and log when doing so?

```
$order_id = 800;
$order = commerce_order_load($order_id);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->uid->set(1);
$order_wrapper->mail->set('test@example.com');
// $order_wrapper->log->set('Changed order owner and mail');
// $order_wrapper->revision->set(true);
$order_wrapper->save();

```

Currently if I try `$order_wrapper->log->set('x');` I see *EntityMetadataWrapperException: Unknown data property log.*, but I believe this is a property of the order (based on getPropertyInfo() etc).

Does Commerce Order + Entity Metadata Wrappers have support for creating a new revision on save, or recording an order log message?

# Answer
> 3 votes
You may need to set the `revision` and `log` properties on the default order object, instead of the wrapper.

e.g:

```
$order_id = 800;
$order = commerce_order_load($order_id);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->uid->set(1);
$order_wrapper->mail->set('test@example.com');
// Set revision details on order object
$order->revision = TRUE;
$order->log = t('Changed order owner and mail');
$order_wrapper->save();

```

As the order object is passed by reference, from memory the revision log info can be set that way.

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


title: Loading in iframe on ajax form submit

text:
# Question
Title: Loading in iframe on ajax form submit
I've a form with couple of buttons, on submit it redirect to third party site for authentication. On the submit I want to load that inside iframe on same page. How I can do that?

# Answer
I think that you can do it with jQuery.

1. Add this code in your template: `<iframe id="frame-id" src="" frameborder="0"></iframe>`
2. Add this jQuery:

```
$("#SUBMIT-ID").click(function(e) {
  e.preventDefault();//This prevents the site from being redirected.
  var a_href = $('.A-THAT-HAS-REDIRECT-CLASS').attr('href');
  $("#frame-id").attr("src", a_href);
});

```
> 1 votes

---
Tags: 8, forms, ajax
---


# Question
Title: Is it possible to alias paths for contextually generated page views?
I have a content type with a path pattern (*\[category\]/\[english\_title\]*) that is generated based on its field values.
In the node's page there is a block with referencing news items and a count based more link to a page with more news items.The path generated from the more link is the same as the node's alias but with /news appended to it (*\[category\]/\[english\_title\]/news*).

For that I passed the English title as token through a hook to the more link which was fetched from the page side as an argument to be matched against. It was fine until I had some fields with special characters, especially titles with apostrophes of possessive 'S's. I am unsure about how to proceed. An easier way would be since there. There is already a news section to do something like /news?nid, but it got me thinking.

Is it possible to alias contextually generated views pages or substitute an already patterned portion of a URL with its alias?

# Answer
This is the use scenario behind the Sub-pathauto module. In your scenario, you're creating a "more link" page View with a */node/%/news* path and a contextual filter for the NID to retrieve that specific node's contextual news view. With the sub-pathauto module installed, that page view should be viewable via `[category]/[english_title]/news` alias.
> 1 votes

---
Tags: views, 8, path-aliases
---


# Question
Title: Hooking into updates to an entity reference field within Parent node
Let's say I have a Structure Content type called "Fruit", and it only has a title.

And I have another Structure Content type called "Color" which is a dropdown menu with a few colors in it.

And i have an "entity reference" for Color on Fruit. So when I go to add a new Fruit, I can input in the Fruit title field "Apple", and then choose from the Color dropdown menu "Red".

I have a hook for `node_update()` which triggers when I change the Title of the Fruit. But when I change the Color, this trigger is not executed.

Which hook should I use if I want to track the Color changing on a Fruit?

This is for Drupal 7. Thanks so much in advance for your time and insight.

# Answer
You don't have a direct connection for those(the same way some entities work at least) so best approach would be to have a node\_update for Color and then inside it to query (can use entityQuery) and see which fruits have that color, from here you can do your stuff.

the following pulled out of my head since I haven't touch D7 for over a year so here we go

```
function node_update($node){
  if($node['type'] == 'color'){
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'fruit')
    //value or target_id
    ->fieldCondition('field_photo', 'value', $node['nid']);

    $result = $query->execute();
  }
}

```
> 1 votes

---
Tags: entities, hooks
---


title: drush8 for D7&D8

text:
# Question
Title: drush8 for D7&D8
I posted the below on the Drush git, but I got redirected here. So here we go :).

With the recent core update I installed drush8 on all of my websites and updated 24 cores, both D7 and D8, using drush 8.1.16. As Drupal seems to release new cores more frequently than before (and since I was around for Drupalgeddon1) this was the first time using Drush on all of them to save time. But I did read the instructions, apparently I should have used Drush9 for Drupal8 updates.

First question: **can existing Drupal8 websites be updated using Drush8?** It seems I didn't run into any problems doing so. But then why does the drush site not mention D8.3+ is supported by drush 8? On drupal.org I found:

> if you are a long-time Drush user, you may still use Drush 8 (8.14 or newer) to update Drupal 8

This information is either correct, in which case it should be pointed out on the drush docs that using drush8 is fine, or it isn't in which case Drupal has to update this section. When reading the following (they use dev8.5 in the example) I'm assuming these are all drush8 compatible commands: https://www.drupal.org/docs/8/update/update-core-via-drush I also checked the last commits to drush8 which seem to mention uodates for the D8.5 release.

Second question: **how do I use drush9 on an existing website?** Actually, I did look this one up and the process seems very cumbersome. Most of my D8 websites are quite small and from what I understand it's best to start from scratch again... What I found most usefull in drush was that it allows you to make a complete code dump and it stores updated files in the drush backups directory. So let me rephrase the question: **Will drush9 and composer ever reintroduce the backup functionality in the future**? The docs state: *archive-dump has unfortunately been removed from Drush 9, so you'll have to use a standard CLI tool to backup the needed directories - typically excluding the vendor directory.* Why did this functionality not make it into 9? Is there a way to specify which drush composer should use while keeping drush8 global for backup-purposes?

Story of my life (I didn't write it, but some will relate) can be found here: https://www.drupal.org/forum/support/post-installation/2017-03-24/how-do-i-migrate-existing-d8-site-into-a-composer-managed#comment-12328927

Thanks to anyone able to help me and many others keeping their websites safe (the easy way ;)).

# Answer
> 2 votes
**Can existing Drupal8 websites be updated using Drush8?**

Yes, you can. But use a globally installed Drush 8 version. Simply download the phar file, make it executable and copy it to /usr/local/bin/drush, see http://docs.drush.org/en/8.x/install/

**How do I use drush9 on an existing website?**

A composer based Drupal 8 installation includes Drush 9 by default and when you run `drush` inside of such an installation the site-local Drush 9 runs automatically. The global Drush 8 or 9 works in this case only as a launcher.

If you have a non composer based Drupal 8 and you want to run Drush 9 on it, then I would recommend to convert it first to a composer based one.

---
Tags: drush, composer
---


# Question
Title: Drush shell update to newer version on Drupal 7
I haven't found explanation of how to upgrade this shell to 8.x for drush itself not a module using drush and the site is on Drupal 7.x site. I'm fairly new to all of this and do know how to use drush but was wondering if I should keep this shell updated. I saw there are versions 8.xx that work for Drupal 7 but didn't see instructions on updating. The version running is 8.0.x.dev so I'm guessing I should update to current 8. Version. Thanks in advance.

# Answer
> 2 votes
First of all, Drush is not a module. It is a shell companion tool for Drupal sites so that you can (for example) use the command line to download and enable modules; clear/rebuild cache; check site info; etc...

Its also worth pointing out that Drush 8 does not care what version of Drupal you are using. In fact you can use the same drush installation with lots of your sites.

If you are using Drush for just the basics you don't have to be too vigilant about keeping it up to date, but of course it is always a good practice to do so.

That all said: this question has been asked/answered here: How do I update Drush to the latest available version?

---
Tags: 7
---


# Question
Title: How to trigger/run/execute scheduled task manually?
Is there a way to run a scheduled task manually without any programming?

If not, this way seems not to work properly Manual execution of scheduled rule. After executing a rule, having another one on the list, clearing caches and running the cron, this feature automatically disappears somehow. There is something wrong in the code.

# Answer
This is how i do it, I use flags module, i create a user flag for each "run manualy my special rule" assigning flag/unflag access only to admin user and i display link on user profile page, flagging or unflagging myself to trigger my special rule, then, most of the time i use views rules module to load content, products, orders or users and perform any kind of stuff with it.
> 1 votes

# Answer
You need to use Scheduler module. This is a way : How to use.
> 0 votes

---
Tags: rules
---


# Question
Title: Restricting a part of a site according to IP
This question is closely related with GDPR, and having done my research I've come across this module which seems to offer a checklist type functionality for overall GDPR compliance.

However as part of a solution which I'm working on, we need can't afford to permanently block traffic from EU countries. Therefore I want to know of the best approach which I could take to setup IP redirect to,

1. Block access to our primary domain from any EU country
2. Allow access only to URLs in /eu sub folder for visitors from EU countries
3. Setup relevant redirects to and from /eu for "a" and "b" above
4. Provide a way for internal users to be able to access any URL of the site
5. The /eu portion of the site should have its own configuration for web analytics, subscriptions, forms etc

I found a couple of modules in drupal.org which could help with blocking the IPs but I'm not quite sure about the redirects and the other requirements in 4 and 5 above. Also I do not want to compromise on performance and speed, so any ideas and suggestions on the best way to get this implemented is greatly appreciated.

The last thing I want to do is to setup /eu as a separate Drupal site, but let me know if that is a better option

# Answer
> 0 votes
This module smart ip it saves the users location from the ip in `$_SESSION`.

The features section, says that it integrates with rules, so it might be possible to create a rule that redirects the user.

# Answer
> 0 votes
Sounds like this answer takes care of your redirects. Maybe you could use the domain access module to get unique settings for the EU and non EU sections?

---
Tags: redirection
---


# Question
Title: Web form Report crashes upon adding date field
I'm using the Webform Report module (version 7.x-1.0) alongside Webform module (7.x-4.16) on Drupal 7.22. When I add Date column to Webform report then save it and view ,Report crashes with message ..website is currently unable to handle this request.HTTP ERROR 500. no matter what format(yyyy/mm/dd..) I enter in date field or leave it empty same happens, If I create report in View by adding all fields including Date fields it works. Also in Webform-Results -Table it works. Any suggestions.. Also can we in drupal 7 enter date and time both in same textbox so it lands in db in one field or it must be separated as I see drupal has it as separate types?

Thank you, Nikola

# Answer
I'm not in situation where we can easily update Drupal because of work environment, the solution was forena reports, which offer full freedom in sql queries(not limited by Webform report or Views limits when creating sql) also result(report) based on query can be shown in drupal interface, just needs some more css adjustment in table header/table data widths for columns

Nikola
> 0 votes

---
Tags: entities, webforms
---


title: How to increment variable in Twig file?

text:
# Question
Title: How to increment variable in Twig file?
I'm using a view grid template and a `views-view-fields--view-machine-name.html.twig` template file in order to render some pictures in grid format. I want to assign dynamic CSS classes to every picture that is being rendered, for example, using the following markup.

```
<div class="profile-pic pic{{id}}">{{ fields.field_picture.content }}</div>

```

I have set a variable in Twig with the following code, but since there is no loop, it doesn't get incremented.

```
{% set id = 0 %}

```

So for every picture I have the same CSS classes (profile-pic pic0).

I want to get the following.

* Picture 1
profile-pic pic0
* Picture 2
profile-pic pic1
* Picture 3
profile-pic pic2
* Picture 4
profile-pic pic3

If I use the following code, the same imagine is rendered instead of the pictures I have.

```
{% for field in fields -%}
  <div class="profile-pic pic{{id}}">{{ fields.field_picture.content }}</div>
{%- endfor %}

```

How do I get the counter to be increased, and all the images to be rendered?

# Answer
As you mentioned, there's no loop, so you can't do this in the template file (well you could, but it wouldn't be worth the effort).

Instead, you could maintain a static variable in a preprocess function:

```
function MYTHEME_preprocess_views_view_fields__view_machine_name(&$vars) {
  static $counter = 0;
  $vars['counter'] = $counter++;
}

```

And refer to it in the template as normal:

```
<div class="profile-pic pic{{ counter }}">{{ fields.field_picture.content }}</div>

```

You might need to tweak that, for example if the View is rendered twice on the same page.
> 3 votes

# Answer
You don't need another preprocess function anymore as you can easily do this in only Twig now. But you need another template. The one you are currently using loops through *all fields of one row*. Not just your image field. But you want to have the template that targets exactly this one image field, where you want to loop through all items of this field's `.content`.

For mere demonstration purpose I'll leave that untouched for now and only show you how to increment variables in a for-loop in Twig:

```
{% set id = 0 %}

{% for field in fields -%}
  <div class="profile-pic pic{{ id }}">{{ fields.field_picture.content }}</div>
  {% set id = id + 1 %}
{%- endfor %}

```

You might also wanna have a look at the loop variable where `{{ loop.index }}` or `{{ loop.index0 }}` simply gives you the current iteration of a loop. Two more lines saved.

```
{% for field in fields -%}
  <div class="profile-pic pic{{ loop.index0 }}">{{ fields.field_picture.content }}</div>
{%- endfor %}

```

---

And last but not least this little gem: slice – to display a subset of items. Let's say only the first five ones.

```
{% for field in fields|slice(0, 5) -%}
  <div class="profile-pic pic{{ loop.index0 }}">{{ fields.field_picture.content }}</div>
{%- endfor %}

```
> 4 votes

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


# Question
Title: How to execute the code at certain time without relying on Cron
I have a custom entity with a `timestamp` field which can be populated by the user.

At these specific "times" I have to "react" and update(execute some code) on some other entities related to this time.

First thing coming to mind is to implement it as a Cron job but, I'm not satisfied with this solution as I need to execute the code at a very specific time(any minute) while I don't want to set up the Cron(even a specific Cron job) to run every minute as it's sound quite overwhelming.

Are very any other ways to smartly manage a code execution based on specific(not hardcoded interval) time?

# Answer
> 1 votes
Running cron every minute is perfectly acceptable. But if you really want a different solution you could (for example) create a Drush command to do what you want and then call that every minute with something like Jenkins or RunDeck. If you really need this command to run at the exact times users specify and only at those times, then you could write code to publish out the time (and other contextually relevant info) to some external system which is constantly running with some Daemon.

This solution will work but it is:

* a) hard because there is a lot of custom work to do
* b) tricky because you have to worry about publishing, but you also have to worry about updates and deletes in case your users ever make changes to the time or the contextually relevant data
* c) unnecessary since frequent cron runs sounds like it can solve your problem.

---
Tags: 8, cron
---


# Question
Title: Customising Views Serializer JSON Output
I have created a Views Rest Export that looks like this:

```
{
   "id":"10",
   "title":"Plot 10",
},
{
   "id":"20",
   "title":"Plot 20",
}

```

But I would like to wrap some extra bits around it like this:

```
{
   "mapwidth":"690",
   "mapheight":"982",
   "levels":[
      {
         "id":"uk",
         "title":"United Kingdom",
         "locations":[
            {
               "id":"10",
               "title":"Plot 10",
            },
            {
               "id":"20",
               "title":"Plot 20",
            }
         ]
      }
   ]
}

```

I have created a php file with this in it, which seems to work:

```
{
    "mapwidth":"690",
    "mapheight":"982",
    "levels":[
        {
            "id":"uk",
            "title":"United Kingdom",
            "locations":
            <?php $locations = file_get_contents('/api/plots?_format=json');
            echo $locations; ?>
        }
    ]
}

```

But I was wondering what the better way of doing this would be.

Thanks in advance.

# Answer
> 4 votes
You can create a module and extend ContentEntityNormalizer to provide a custom structure.

Example:

```
<?php

declare(strict_types = 1);

namespace Drupal\mymodule\Normalizer;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Url;
use Drupal\image\Entity\ImageStyle;
use Drupal\serialization\Normalizer\ContentEntityNormalizer;
use Drupal\node\NodeInterface;

/**
 * Converts the Drupal entity object structures to a normalized array.
 */
class NodeEntityNormalizer extends ContentEntityNormalizer {

  /**
   * The interface or class that this Normalizer supports.
   *
   * @var string
   */
  protected $supportedInterfaceOrClass = [
    'Drupal\node\NodeInterface',
  ];

  /**
   * The entity manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * {@inheritdoc}
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public function normalize($entity, $format = NULL, array $context = []) {
    $type = $entity->getType();

    $methods = [
      'library' => 'normalizeLibrary',
      'collection' => 'normalizeCollection',
    ];

    if (isset($methods[$type])) {
      return $this->{$methods[$type]}($entity, $format, $context);
    }

    return parent::normalize($entity, $format, $context);
  }

  /**
   * Normalize a library content type.
   */
  protected function normalizeLibrary($entity) {
    $attributes['id']       = $entity->id();
    $attributes['featured'] = !empty($entity->get('field_is_coming_soon')->value);
    $attributes['external'] = !empty($entity->get('field_is_stub')->value) && !empty($entity->get('field_website_link')[0]);
    $attributes['name']     = $entity->label();
    $attributes['subTitle'] = !empty($entity->get('field_subtitle')->value) ? $entity->get('field_subtitle')->value : '';

    return $attributes;
  }

  /**
   * Normalize a collection content type.
   *
   * @param \Drupal\node\NodeInterface $entity
   *   The node entity.
   *
   * @return array
   *   The item attributes.
   */
  protected function normalizeCollection(NodeInterface $entity) : array {
    $attributes = [];
    $attributes['id'] = $entity->id();
    $attributes['title'] = $entity->label();
    $attributes['subtitle'] = $entity->get('field_subtitle')->value;
    $attributes['summary'] = $entity->get('field_summary')->value;
    $attributes['card_type'] = $entity->get('field_directory_view')->value;
    $attributes['list_image'] = NULL;
    $attributes['card_image'] = NULL;
    $attributes['url'] = Url::fromRoute('entity.node.canonical', ['node' => $attributes['id']])->toString();

    $media = $entity->get('field_featured_image')->getValue();

    if (!empty($media)) {
      $item = $this->entityTypeManager->getStorage('media')->load($media[0]['target_id']);
      $image = $item->get('image')->getValue();

      $attributes['list_image'] = [
        'src' => ImageStyle::load('collection_listing')
          ->buildUrl($item->image->entity->getFileUri()),
        'alt' => $image[0]['alt'],
      ];

      switch ($attributes['card_type']) {
        case 'wide':
          $attributes['card_image'] = [
            'src' => ImageStyle::load('collection_listing_wide')
              ->buildUrl($item->image->entity->getFileUri()),
            'alt' => $image[0]['alt'],
          ];
          break;

        case 'tall':
          $attributes['card_image'] = [
            'src' => ImageStyle::load('collection_listing_tall')
              ->buildUrl($item->image->entity->getFileUri()),
            'alt' => $image[0]['alt'],
          ];
          break;

        case 'standard':
          $attributes['card_image'] = $attributes['list_image'];
          break;

        default:
          break;
      }
    }

    return $attributes;
  }

}

```

This code only applies to Node entities, and only for two content types (you will want to specify them, since this will override anything matching the `$supportedInterfaceOrClass` property.

You will need to add it to your custom modules services.yml file:

```
services:
  mymodule.node_entity:
    class: Drupal\mymodule\Normalizer\NodeEntityNormalizer
    arguments: ['@entity_type.manager']
    tags:
      - { name: normalizer, priority: 8 }

```

The View will now use this normalizer if the conditions match and you can structure the output however you like. This gives you the power say, to reach into entity references and pull in values or do conditional things (like the custom image size I am passing in `normalizeCollection` depending on a field value).

Note that my example is custom and does not do things like check field level access for the user, since we do not have any restricted fields.

---
Tags: views, 8
---


# Question
Title: Updating Node Field using drupal_write_record doesn't show changes until cache flush
Problem is in the title basically, I'm trying to update a specific field in my node and I have to do it by using drupal\_write\_record rather than loading and modifying the node object itself, or by using node\_save etc, but my changes aren't being reflected until I flush the caches for the site.

Is there something I need to do to have Drupal immediately aware of the changes?

Code:

```
$next_delta = db_query('SELECT MAX(delta) + 1 AS del FROM {field_data_my_field} WHERE entity_id = :nid', array(':nid' => $nid))->fetchField();
  $data = array(
    'entity_type' => 'node',
    'bundle' => $node->type,
    'deleted' => 0,
    'entity_id' => $node->nid,
    'revision_id' => $node->vid,
    'language' => LANGUAGE_NONE,
    'delta' => $next_delta,
    'field_my_data' => 1,
  );
  drupal_write_record('field_data_my_field', $data);
  drupal_write_record('field_revision_my_data', $data);

```

I've tried adding `entity_get_controller('node')->resetCache(array($node->nid));` into the code but that's not doing it either.

# Answer
When you write directly to the table (which drupal\_write\_record() does), it bypasses any APIs that are called. As such, you should really only use drupal\_write\_record() for tables you've created yourself, that don't have any APIs to be bypassed. In this case, you are better off changing the values in the $node, then calling node\_save() on it. This will not bypass any APIs.
> 1 votes

---
Tags: 7, caching
---


# Question
Title: How to set a node reference programmatically?
I'm creating a new node and attempting to the values of the fields programmatically. I cannot seem to figure out how to set a value for a node reference field, the widget type is autocomplete and it is set to unlimited values.

Here is my code to create the new node and an entity metadata wrapper

```
// Create the communication node and set the current user as the author
$new_comm = entity_create('node', array('type' => 'comm', 'uid' => $uid));
// create a wrapper for the new communication
$nc_wrapper = entity_metadata_wrapper('node', $new_comm);
// then I set some other field values via the $nc_wrapper

```

I cannot seem to set the value for the node reference field `field_comm_relationship`. I have tried all manner of setting the value including the following (`$oc_wrapper` wraps a different node type that also has a node reference):

**I tried inserting it straight from the `$oc_wrapper`**

```
$nc_wrapper->field_comm_relationship = $oc_wrapper->field_call_site_ref->value();

```

**I tried using the set method**

```
$nc_wrapper->field_comm_relationship->set($oc_wrapper->field_call_site_ref->value());

```

**I tried both of the previous while accessing the actual `nid` value**

```
$nc_wrapper->field_comm_relationship->set($oc_wrapper->field_call_site_ref->value()->nid);

```

**and**

```
$nc_wrapper->field_comm_relationship = $oc_wrapper->field_call_site_ref->value()->nid;

```

**I tried to make the input an array**

```
$site_nid = ['und' => [ 0 => ['nid' => (int) $oc_wrapper->field_call_site_ref->value()->nid]]];
$nc_wrapper->field_comm_relationship = $site_nid;

```

**I tried using the `node_load` function instead of EMW**

```
$node = node_load('node', $nc_wrapper->nid->value());
$site_nid = $oc_wrapper->field_call_site_ref->value()->nid;
$node->field_comm_relationship['und'][0]['nid'] = $site_nid;
node_save($node);

```

As suggested I do call `save()` later in my code, but it's not making it there because it hits a fatal error. For instance if I run this code

```
$nc_wrapper->field_comm_relationship = (int) $oc_wrapper->field_call_site_ref->value()->nid;

```

I get this error

```
EntityMetadataWrapperException: Invalid data value given.
Be sure it matches the required data type and format.
Value at node()->field_comm_relationship: 713511. in EntityMetadataWrapper->set()
(line 122 of /vagrant/sites/all/modules/contrib/entity/includes/entity.wrapper.inc)

```

# Answer
After updating the value in your entity metadata wrapper you need to be sure to also call the `save()` method to save your change. See this documentation on drupal.org.

Since you have an object, and not an id, the following should work.

```
// Set value for a single value field.
$nc_wrapper->field_comm_relationship = $oc_wrapper->field_call_site_ref->value();

```

or

```
// Set value for a multivalue field. Make sure to pass an array of objects.
$nc_wrapper->field_comm_relationship = [$oc_wrapper->field_call_site_ref->value()];

```

or

```
// Append an additional value to a multivalue field.
$nc_wrapper->field_comm_relationship[] = $oc_wrapper->field_call_site_ref->value();

```

and finally

```
// Save the host entity.
$nc_wrapper->save();

```

If you have ids, check out this answer. You can get an id instead of an object from the entity metadata wrapper like `$oc_wrapper->field_call_site_ref->raw()` instead of `->value()`;

Additional info for entity metadata wrappers can be found in this Death to Field Arrays! article.
> 1 votes

---
Tags: 7, nodes, entities
---


# Question
Title: Views Contextual Filters: Using node's URL alias as a conditional filter
I have Drupal content whose nodes have URL aliases;

/node/1 routes to /bar

I also have a View which passes a NID as a contextual filter:

WHEN THE FILTER VALUE IS NOT AVAILABLE:

\[selected radio\] Provide default value

TYPE

\[selected dropdown\] Raw value from URL

PATH COMPONENT:

\[selected dropdown\] 1

\[checked\] Use path alias

View's Path is set for /foo/%

So:

/node/1 returns node

/bar returns node

/foo/1 returns view

/foo/bar returns a white screen

How do I allow the View to access the node's URL alias as a conditional filter?

Thank you

# Answer
Maybe the View Url Path Arguments module. I am seeing it recommended in this thread, but I'm really not sure if that's your issue or not.

Alternatively, you can implement hook\_views\_pre\_view and alter the argument passed to the view based on the value in the url, i.e. do the conversion from alias to id manually. If you have an issue when your alias contains a `/`, an alternative may be to use a query string for the contextual argument.
> 1 votes

---
Tags: 7, views
---


# Question
Title: How to remove ul li formatting from list of attributes in Ubercart order email template?
I would like to update my customer order email and printable invoice so that each product line item looks like this:

> 1 x SHIRTRED | Red | Tshirt

* 1 is the quantity ordered
* SHIRTRED is the SKU
* Red is the attribute option that was chosen
* Tshirt is the product name

I have already updated my uc-order--customer.tpl.php code to look like this:

```
<b><?php print $product->qty; ?> x </b> <?php print $product->model; ?> | <?php print $product->title; ?> | <?php print $product->details; ?>

```

The attribute options are printed as a ul list, which causes them to wrap to the next line below the other info for this product. I would like to remove the ul li formatting from the product's attributes in the customer order email and the printable invoice so that the info can be on a single line/table row. I found this in uc\_order.module:

```
$product->details .= theme('item_list', array('items' => $attributes));

```

Would I just change 'item\_list' to something else in a template.php function? If so, what would I change it to? If not, how else can I accomplish this change?

Thanks!

# Answer
Not exactly what I was asking for, but I did find a workaround that works for the most part. I copied the uc-order--customer.tpl.php file into my theme dir and added css for the ul to the head in that file. (display: inline-block and a few padding, margin, and list-style styles). The only issue now is the emailed order invoice. The CSS doesn't follow along into the email, so it's a bit of a mess. Open to any suggestions on how to handle that, or a better way overall.

EDITED TO ADD: I ended up copying the product line items from the uc-order--admin.tpl.php file. The attributes therein are not styled as a list, so it was a breeze to use that code.
> 0 votes

---
Tags: 7, ubercart
---


# Question
Title: How to reduce options for units of measurement to just miles and km for proximity search
Using geofield with Views and exposed filters to the user to search for things on the map within a certain radius of a particular location.

I only require miles and kilometres as units of measurement, not: Yards, Feet, Nautical Miles. Any way to omit these?

They are defined in the module geofield's file, `geofield.elements.inc` code:

```
/**
 * Returns options for radius of the Earth.
 */

function geofield_radius_options() {
  return array(
    GEOFIELD_KILOMETERS => t('Kilometers'),
    GEOFIELD_METERS => t('Meters'),
    GEOFIELD_MILES => t('Miles'),
    GEOFIELD_YARDS => t('Yards'),
    GEOFIELD_FEET => t('Feet'),
    GEOFIELD_NAUTICAL_MILES => t('Nautical Miles'),
  );
}

```

But I don't want to hack this and remove them.

The approach I am expecting to use would be to implement `hook_form_alter` in my own module and remove the options from there.

But is there a better way?

# Answer
Another approach is simply using CSS.

The select list is built like this:

```
<select>
  <option value="6371">Kilometres</option>
  <option value="6371000">Metres</option>
  <option value="3959">Miles</option>
  <option value="6975175">Yards</option>
  <option value="20925525">Feet</option>
  <option value="3444">Nautical Miles</option>
</select>

```

You could hide the undesired values with the following style (in this case only "kilometres" and "miles" remain):

```
option[value="6371000"],
option[value="6975175"],
option[value="20925525"],
option[value="3444"]{
  display: none;
}

```

**If you're only using one value**, it may look a bit silly to have a select box of it. You could disguise it as regular text though. Make sure the font is identical to the rest, remove the border, set a width to the container of the select list and hide everything seeping out of it, whilst making the select list a tad longer (thus the dropdown arrow gets hidden by the overflow):

```
.form-item-field-geofield-distance-unit{
    width: 90px;
    overflow: hidden;
}

select{
    width: 120px;
    border: 0;
    cursor: text;
}

```

Alternatively (Bootstrap 3):

```
.form-item-field-geofield-distance-unit select{
    border: 0 !important;
    box-shadow: none;
    cursor: text;
    -moz-appearance: none;
    -webkit-appearance: none;
    appearance: none;
}

```

Adjust the margins or paddings if necessary…
> 2 votes

# Answer
This isn't really in the form, via hook\_form\_alter(). It's an element of a form component, so you really need to implement hook\_element\_info\_alter(), and add a "process" callback to the stack.

In that process callback you can then update the options:

```
 /**
 * Implements hook_element_info_alter().
 */
function YOURTHEMEORMODULE_element_info_alter(&$type) {
  $type['geofield_proximity']['#process'][] = '_alter_proximity';
}

function _alter_proximity($element, &$form_state, $form) {
  //Create dropdown for units
  $reduced_options = array(
    GEOFIELD_MILES => 'Miles',
    GEOFIELD_KILOMETERS => 'Kilometers'
  );
  $element['unit'] = array(
    '#type' => 'select',
    '#options' => $reduced_options,
    '#title' => t('Unit'),
    '#default_value' => !empty($element['#default_value']['unit']) ? $element['#default_value']['unit'] : GEOFIELD_KILOMETERS,
    '#title_display' => 'invisible',
  );
  return $element;
}

```
> 1 votes

# Answer
My own answer (incomplete *so far* \- will update when I've figured it out (feel free to chip in ;) ) but "on the right track" I think. Incomplete because I haven't figured out how to access the menu option elements from the hook module, `Devel` module `dpm()` is not helpful at directing me as to how to 'get at' the menu drop down form options in the $form array.)

I have started to write this hook override - which I have confirm is called in my custom module `cgformutils` in file `cgformutils.module` :-

```
/**
 * Implements hook_form_views_exposed_form_alter().
 */
function cgformutils_form_views_exposed_form_alter(&$form, &$form_state) {
  if($form['#id'] == 'views-exposed-form-locally-page')
  {
     dpm($form);
  }

  // menu modifying code to go here:

  // I need to figure out what to put here,
  // dpm() is not helpful at directing me as to how
  // to 'get at' the menu drop down form options in the $form array
  // in order to remove some - php unset them

  return $form;
}

```

Here's an annotated screen shot for my explanation as to why `Devel` module `dpm()` function is not helping me work out how to access the menu drop down options from the `$form` array:
> 0 votes

---
Tags: 7, views, forms, location
---


# Question
Title: How to add addition settings in node edit page on rightside bar
I want to add additional settings in node edit page (node/\*/edit) on right side bar. How can i achieve this drupal 8?

**Update**

To be more clear, I have installed url\_redirect module and it is showing settings in node edit page in drupal 7. But in drupal 8 there is no such settings. So I want add those settings by myself, but on right side bar.

# Answer
The key is to implement `hook_form_node_form_alter` function to add settings to node edit page. I did this by applying patch specified in https://www.drupal.org/project/redirect/issues/2702353.

I specified a wrong module in my question (There were confusion, because both the modules showing same text), actual module that was showing settings in admin pane was redirect module not url\_redirect.

I keep this answer here that may help someone who come across the same question I had.
> 0 votes

---
Tags: 8, nodes, forms
---


# Question
Title: Form API Ajax trigger callback with size of input
I use the API Form of Drupal 8 to create my form. I had an ajax callback on a field:

```
$form['association']['numero'] = array(
        '#type' => 'textfield',
        '#title' => t('foo'),
        '#size' => 10,
        '#maxlength' => 10,
        '#suffix' => '<div id="ajax_error"></div>',
        '#ajax' => [
            'callback' => '::fetchApiData',
            'event' => 'change',
            'prevent' => 'click',
        ],
    );

```

with my callback function :

```
public function fetchApiData(array $form, FormStateInterface $form_state)
{
    return 'foo';
}

```

It's all working fine, but i want to trigger the callback when the user **writes 10 characters precisely**. Does anyone has a solution for that?

# Answer
You can do this:

1) Decide on an event name. In this code, the event name will be 'overminlength'

2) In the form element being defined using the Form API, set your #ajax as normal, but set the #ajax 'event' to the event name chosen in step 1:

```
'#ajax' => [
  'wrapper' => 'some_wrapper',
  'callback' => 'some_callback',
  // Set the custom event here:
  'event' => 'overminlength',
],

```

3) Create a custom JS file and attach it to the field

```
'#attached' => [
  'library' => ['mymdodule/mylibrary'],
],

```

4) Add a $.keyup() listener to the field.

* In the callback, count the number of characters in the field
* If it's more than X characters, call $.trigger(), and trigger the event from step 1

```
(function($, Drupal) {

  "use strict";

  function fieldwatcher(context) {
    $(context).find("#edit-myfield").once("fieldwatcher").each(function() {
      $(this).keyup(function() {
        // Change '3' to the number of characters after which you want to
        // trigger the ajax.
        if ($(this).val().length > 3) {
          $(this).trigger("overminlength");
        }
      });
    });
  }

  Drupal.behaviors.testScript = {
    attach: function(context) {
      fieldwatcher(context);
    }
  };

}(jQuery, Drupal));

```
> 5 votes

---
Tags: 8, forms, javascript, ajax
---


# Question
Title: Multiple forms in same page from single form builder returning the first form's value in submit
I have written a single form builder and a form submit handler corresponding to that form.

What I have done is that I have rendered the form multiple times using for loop and then concatenated them into a single variable and then displayed it on a single page.

Each form has separate submit buttons.

But the problem is that whenever I press the submit button of any of the forms I am only getting the form that was built first in the form\_state\['values'\] in the submit handler.

For now, I have made it work by taking the form\_state\['input'\] which seem to have the correct set of values based on the form submit clicked.

I need the corresponding form values in the submit handler. How can I achieve this?

Is this some kind of bug or am I doing it wrong?

```
$form_markup = '';
  foreach ($ids as $key => $value) {
    $req_form = drupal_get_form('_request_form', $value, $key, $node);
    $form_markup .= render($req_form);
  }

```

My form and form\_submit

```
function _request_form($form, &$form_state, $value, $key, $node) {
    $form['name'] = array(
      '#type' => 'item',
      '
    );
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => 'Ask',
    );
    return $form;
  }
}

    function _request_form_submit($form, &$form_state) {
      dpm(form_state['values']);
      dpm(form_state['input']);
    }

```

Any help is much appreciated. thanks.

# Answer
You'll need to implement hook\_forms(), so that you can create 'aliases' of your forms.

For example, let's imagine a form named 'message\_form', that you want to include multiple times on the page. To do this, you append a unique number to the form name each time when calling the form:

```
$page = [
  'form_1' => drupal_get_form('message_form-1'),
  'form_2' => drupal_get_form('message_form-2'),
];

return $page;

```

Next, you implement hook\_forms() to watch for form names in the format above:

```
function hook_forms($form_id, $args) {
  // Act on form IDs that match the pattern message_form-[NUMBER].
  if (preg_match('/^message_form-\d+$/', $form_id)) {
    // The key is the form ID that has been passed.
    $forms[$form_id] = [
      // The callback is the actual form definition to be called.
      'callback' => 'message_form',
    ];
  }
}

```

Now each form being put on the page will have a custom form ID and therefore the system will know which form the submitted data refers to.
> 2 votes

---
Tags: 7, forms
---


# Question
Title: pass variable from custom module file to twig template in d8
How to pass variable from controller to twig template in Drupal-8? I have tried to pass variable on module theme folder, but I want to use this variable on global theme?

# Answer
> 2 votes
First create a function that returns the variable, something like this:

```
function my_function() {
return $var_name;
}

```

Then you must create a preprocess function, for the template, like this:

```
function MY_MODULE_preprocess_TEMPLATE(&$variables) {
  $V_NAME = my_function();
  $variables['v-name'] = $V_NAME;
}

```

Remember to clear the cache.

---
Tags: 8
---


# Question
Title: Check access to entity for logged in user in Drupal 8
I have added private message module for one of my project which has it's own entity. I need to check whether the user is having access to that entity content or not. The module has it's menu item defined in the module's routing.yml

e.g.:

```
entity.private_message_thread.canonical:
  path: '/private_messages/{private_message_thread}'
  defaults:
    _entity_view: 'private_message_thread'
    _title: 'Private Messages'
  requirements:
    _entity_access: 'private_message_thread.view'

```

How could I check whether the user has view access to the above menu path?

# Answer
> 4 votes
I have tested the entity access and $entity-\>access('view', $account); that worked in my case. I earlier used the optional $account parameter so that it could check the currently logged in user.

I loaded my entity with:

```
$entity_manager = \Drupal::entityTypeManager();
$thread_entity = $entity_manager->getStorage('private_message_thread')->load('private_message_thread_id');

```

I wanted to check whether the user has permission to view entity by code. Below is the code for the same I did in my case:

```
$account = \Drupal::currentUser();
$entity_manager = \Drupal::entityTypeManager();
$entity = $entity_manager->getStorage('private_message_thread')->load('private_message_thread_id');
$check = $entity->access('view', $account);

```

Please let me know if you have a better answer over the same.

# Answer
> 2 votes
You can check annotations of those entities and find access handler.

e.g.

```
/**
 * Defines the Private Message Thread entity.
 *
 * @ContentEntityType(
 *   id = "private_message_thread",
 *   label = @Translation("Private Message Thread"),
 *   handlers = {
 *     "view_builder" = "Drupal\private_message\Entity\Builder\PrivateMessageThreadViewBuilder",
 *     "views_data" = "Drupal\views\EntityViewsData",
 *     "access" = "Drupal\private_message\Entity\Access\PrivateMessageThreadAccessControlHandler",
 ...

```

As you can see, there is access handler. Now you know how it works.

```
  protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
    if ($account->hasPermission('use private messaging system')) {
      switch ($operation) {
        case 'view':
          if ($entity->isMember($account->id())) {
            $messages = $entity->filterUserDeletedMessages($account);
            if (count($messages)) {
              return AccessResult::allowed();
            }
          }
          ...

```

---
Tags: 8, entities, privatemsg
---


title: How do I filter by node ID in views?

text:
# Question
Title: How do I filter by node ID in views?
I am trying to add Node ID in contextual filters but it seems there isn't Node ID anymore.

# Answer
You must use `content ID`, which is now the same thing.

That is the one to use as contextual filter, in Drupal 8.
> 9 votes

# Answer
In view contextual filters add Node Id through content id .
> 1 votes

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


title: Link to webform submission

text:
# Question
Title: Link to webform submission
I have Drupal civiCRM installed. I am using webforms to create contact in civiCRM.

To display these contacts I am using civiCRM views, which gives me civiCRM contact details properly but I am not able to link these records to drupal webform submission.

I am listing civiCRM contacts firstname lastname through views. Now needs to link it to its submission view page

eg: node/2/submission/4

node/\[webform-id\]/submission/\[sibmission-id\]

# Answer
In view webform have option Link to Webform submission. I am not sure it will help for you, but hope this will help\]
> 0 votes

---
Tags: views, civicrm, webforms
---


# Question
Title: Is there a way to get the list of JavaScript files that are getting loaded on the page?
I want to load the JavaScript files using `document.createElement()`, since that is better for the page load. Is there a way, maybe in a preprocess hook, to get the list of JavaScript files that are getting loaded on the page?

# Answer
> -1 votes
Hi By using drupal\_get\_js.You can get the list of Javasript files in drupal7.

function mytheme\_preprocess\_page (&$vars, $hook) { if (true) { drupal\_add\_js (drupal\_get\_path('theme', 'mytheme') . '/mytheme.js'); $vars\['scripts'\] = drupal\_get\_js(); // necessary in D7? } }

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


title: Get Post Data from drupal_http_request

text:
# Question
Title: Get Post Data from drupal_http_request
I have two websites use Drupal.

**In Websites ONE:** I have code

```
$data = array(
  'key1' => 'value1',
  'key2' => 'value2',
);
$request = array(
  'headers' => array(
    'Content-Type' => 'application/json',
    'Accept' => 'application/json',
  ),
  'data' => drupal_json_encode($data),
  'method' => 'POST',
  'max_redirects' => 3,
  // We set a lower timeout since we don't want the user waiting for the page too long
  'timeout' => 30,
);

$url = 'http://examplesitetwo.com/return-data';
$response = drupal_http_request($url, $request);

```

**In Website TWO:** i have code

```
function my_module_menu() {
  $items = array();

  $items['return-data'] = array(
    'page callback' => 'return_data_pcb',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function return_data_pcb() {
  // How to get post data form drupal_http_request in website one;
}

```

How to get post data form drupal\_http\_request() in website one? Thank you!

# Answer
Sorry. It's not answer. But i try debug in function

```
function return_data_pcb() {
  watchdog("debug", '<pre>' . print_r( $_POST, true) . '</pre>');
  // But $_POST is empty array. It's show in admin/reports/dblog, when in website one // call function drupal_http_request.
}

```

**I don't know my problem by when call drupl\_http\_request data post doesn't not send. Or problem with hook\_menu in website two. Please help!**
> 2 votes

# Answer
To receive RAW post data in PHP, you can use the php://input stream like so:

```
$content = file_get_contents("php://input");

```

Then you can decode JSON

```
$decoded = json_decode($content, true);

```

So your full function can be something like this:

```
function return_data_pcb() {
  // Make sure that it is a POST request.
  if (strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0) {
    throw new Exception('Request method must be POST!');
  }

  // Make sure that the content type of the POST request has been set to application/json.
  $contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
  if (strcasecmp($contentType, 'application/json') != 0) {
    throw new Exception('Content type must be: application/json');
  }

  // Receive the RAW post data.
  $content = trim(file_get_contents("php://input"));

  // Attempt to decode the incoming RAW post data from JSON.
  $decoded = json_decode($content, TRUE);

  // If json_decode failed, the JSON is invalid.
  if (!is_array($decoded)) {
    throw new Exception('Received content contained invalid JSON!');
  }

  // Process the JSON.
}

```
> 2 votes

# Answer
So, as far as I know Drupal handles post data the same way other php applications do with the `$_POST` variable. I just did something similar against an external server and it was helpful to print\_r every step of building your request and step through to make sure everything is working the way you think. If your post variable is empty than you're probably not sending it correctly. I would try something like this for your 2nd site's page callback:

```
function return_data_pcb() {
  dpm($_POST);
}

```
> 1 votes

# Answer
What is your drupal version? I think this will be different between version 7 and version 8 as symphony provides helpers for the standard super globals I think. I'm still not up to speed on Drupal 8 yet.

You can always access the post data through the `$_POST` super global. Drupal is still a php engine.

Check out this other drupal answers case.
> 0 votes

---
Tags: 7
---


title: Show url attibuts in twig

text:
# Question
Title: Show url attibuts in twig
I have this in my routing page

```
function_adh_apport.adh_apport:
  path: '/collecte/apports/{date}'
  defaults:
    _controller: '\Drupal\function_adh_apport\Controller\RapportsController::filtrer'
    date: ''
  requirements:
    _permission: 'access content'
    date: \d+

```

I got this url : ../web/collecte/apports/2016

but now, i'm trying to show in twig the value of {date}

So i do this in twig :

```
{{ path('function_adh_apport.adh_apport', { 'date': apports.date}) }}

```

but it return "../web/collecte/apports" and not just "2016"

# Answer
> 0 votes
I have do a preprocess function in my file ".module" like this

```
/**
 * Implements hook_preprocess_page()
 */
function MYTHEME_preprocess_page(&$vars) {
  $vars['get']['date'] = \Drupal\Component\Utility\XSS::filter($_GET['date']);
}

```

but not sure that correct

# Answer
> 0 votes
According to your preprocess :

> `$vars['get']['date'] = \Drupal\Component\Utility\XSS::filter($_GET['date']);`

Your template should be :

```
{{ path('function_adh_apport.adh_apport', { 'date': get.date }) }}

```

PS : better to use `\Drupal::request()->query->get('date');` than `$_GET['date']`

---
Tags: 8, theming, routes
---


# Question
Title: Drupal 7 prepopulate form values for embedded field collection
I need to prepopulate my embedded field collection values in a specific form. Here is what I've got so far:

```
<?php
// Hook form alter
function mp3_template_form_alter(&$form, &$form_state, $form_id)
{
  // Pre fill profile mp3 form with mp3 template data
  if (isSet($form_id) && $form_id == 'profile_mp3_node_form')
  {
    global $user;
    $user_full = profile2_load_by_user($user->uid, 'artists_profile');

    // Get field collection entity ids from the user
    $entity_ids = $user_full->field_copyrights_mp3[LANGUAGE_NONE];

    // Load field collection entities
    $entities = entity_load('field_collection_item', $entity_ids);

    // Here I want to prepopulate the $form['field_copyrights_mp3'] form field with my collection items that contain the data for field_copyrights_mp3
    $form['field_copyrights_mp3'][LANGUAGE_NONE][0] = $entities[0]; // 1 field collection
    $form['field_copyrights_mp3'][LANGUAGE_NONE][1] = $entities[1]; // 2 field collection
    // etc...
  }
}

```

I have searched a lot and tried multiple approaches to prefill my field collection with multiple rows of data. Hopefully someone can point me into the right direction of what I should do next.

Image of what I'm trying to prepopulate with multiple owners:

# Answer
> 0 votes
you can use the MODULENAME\_form\_alter hook to achieve this, by iterating through its nested array, maybe this can help

If this help, awesome, ping me if not, I can share some snippets that achieve that :)

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


# Question
Title: Drupal 8 Forms/Webforms Ajax Callback Elements
I'm looking to add/edit elements on a Drupal 8 webform with Ajax Callbacks, I've read up on the buildForm technique, however my problem is a little more complicated, in that I am actually trying to do all of this inside of a custom composite element, not a form object.

Adding a new element via HtmlCommand is no problem, however any '#ajax' callbacks I add to this new element do not get initialised.

Thanks.

# Answer
> 2 votes
You can't add elements in an ajax callback:

> Note, that as part of the Form APIs security system, you **cannot** create new form elements in the callback function, as they will throw errors upon submission, and any #ajax on elements created in the callback will also not work. If you need to create new elements on ajax submit, they must be added in the form definition.

from https://www.drupal.org/docs/7/api/javascript-api/ajax-forms-in-drupal-7 (still valid for D8).

It should be possible to find a method in the composite element which is part of the form building process where you can add the form element.

---
Tags: 8, forms, webforms
---


title: Clearing contextual links'cache

text:
# Question
Title: Clearing contextual links'cache
I'm listing nodes in a block view which is located in a panel managed by page\_manager.

I need for these nodes somes custom opérations in contextual links, so i implmented hook\_contextual\_links\_alter() to add some operations.

All works.

**Problem :** my custom contextual links are appearing in new nodes of this list (or modified nodes) but not in old ones. To make them appear, i need to flush my browser's cache (i'm also using memcache). Editing all these nodes or clearing browser's cache are the only ways i currently found to get contextual links working for old nodes.

I need to achieve this during the update of my app with hook\_update of my module without editing all these nodes or asking users to clear their cache.

*PS : i tryed to clear all cache with & without drush -individually or not-, by all ways, all modules are last stable version, drupal 8.5.2*

# Answer
This cache is located in sessionStorage on modern browsers.

I'm just clearing the entire sessionStorage with `window.sessionStorage.clear();` on logout to solve this problem. I could be more precise on this deletion, but it does not matter in this app.
> 1 votes

---
Tags: 8, caching, navigation
---


title: update node field Programmatically

text:
# Question
Title: update node field Programmatically
I want to learn to alter node fields after a migration. I have a custom module and inside is a .inc file I use as a script that I will run once using drush eval module\_load\_include. I want to learn a simple task like replacing text inside all nodes body field. First I load all nodes, then search the body fields for all nodes for the word "red" than I want to replace that word with "blue" How would I write this? This is my starting point

```
<?php

use Drupal\Component\Utility\Html;
use \Drupal\node\Entity\Node;

function _update_node() {

// load nodes
foreach($nids as $nid) {
    $node = Node::load($nid);

// do the work  here

  $node->save();

}

```

Then I want to run this script once. My module name is create\_content. So I can run the command.

```
drush eval "module_load_include('inc', 'create_content', 'create_content'); _update_node();" > debug.txt

```

# Answer
> 2 votes
Here is how to update body field :

```
$nodes = Node::loadMultiple();
foreach($nodes as $node){
  $html = $node->body->value;
  $html = str_replace('blue','red',$html);
  $node->set('body', [
          'summary' => 'the summary',
          'value' => $html,
          'format' => 'full_html', // probably,
          /**
           * Correspond with format you need in admin/config/content/formats
           */
   ]);
   $node->save();
}

```

---
Tags: 8
---


# Question
Title: How do I prefill a paragraph field in a node form?
I have a content type with a paragraph entity reference field and every time a user is going to add a node of this type I want to have the paragraph field already open and prefilled. I've tried with hook\_form\_alter, but it's not opening the paragraph form with prefilled values.

# Answer
In the form display for that content type you can tell the paragraph field to have a default paragraph selected. So when new nodes are created it will appear there

Then on your actually paragraph you'd need to set the default values for each field it contains (Just by editing those fields on the paragraph and setting the defaults)
> 0 votes

---
Tags: 8, forms, paragraphs
---


# Question
Title: Drush remote sql-dump starts with "stdin: is not a tty"
When I run `drush @SITEALIAS.live sql-dump > db.sql` on some servers or in fact any remote drush command I get:

`stdin: is not a tty` as part of the return.

This is difficult when doing sql dumps as then you have to edit a multi megayte file to remove that from the head.

# Answer
> 1 votes
I'm reading from here: https://stackoverflow.com/questions/7062521/rsync-exits-with-the-message-stdin-is-not-a-tty

> You need to add:
>
> \[ -z "$PS1" \] && return
>
> to the beginig of .bashrc that is located in your home dir. That command checks to see if the shell is running interactively. If so, it exits immediately. This makes sense since stuff in the bash configuration file isn't needed for non interactive processes, like rsync

"in your home dir" meaning the user used to login on your @SITEALIAS.live server. So you need to SSH into your server as that user, and add the above line to the beginning of your `~/.bashrc` on that server.

An explanation from another answer:

> The error message "stdin: is not a tty" is due to something in the startup script on your server attempting to process an action that should only happen for interactive logins (when you connect with ssh direct to the server, etc).

---
Tags: drush
---


# Question
Title: How do I embed an "EVA" view display in a twig template?
I installed the "Twig Tweak" module for Drupal 8

I created an "EVA" display. The view id is "contenu\_relation\_groupe" and the display id is "entity\_view\_1".

I added the following in the twig template for my nodes:

```
{{ drupal_view('contenu_relation_groupe', 'entity_view_1') }}

```

But nothing is displayed. Any idea why?

I've never managed to embed an "EVA" view in a twig template.

# Answer
> 1 votes
EVAs get added as a field with name like `VIEW_ID`_`DISPLAY_ID`. They should appear in the `content` variable like any other field.

If you've added your EVA to the node's display you should be able to render your EVA, with the configuration from the Manage Display screen, like

`{{ content.contenu_relation_groupe_entity_view_1 }}`.

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


# Question
Title: How to get subsequent fields to populate after creating a node using webform rules?
I've been going crazy trying to figure this out. I think I am close, but seem to be missing something with the rule actions. Any help would be most appreciated.

**Background:**

I’m trying to create nodes from webforms that will pull in certain fields from the webform, namely, first and last names (text fields), affiliation (from an entity filed), and conference to attend (check box list). The reason for this node content type is to pull the conference registrants names and affiliations into a view that will list on each conference page. The content type for the attendees is called “Conference Participants.” The reason for doing this is so the staff in my department does not have to manually enter each person who register.

**Present Status:**

I started using this process last year with minor success. That is, I was able to use Rules to take a submitted webform and create a node with the participants last, first name as the title. I set the content type to not publish so either I or the staff members could verify the information and publish. As it now stands, the workflow is:

* Events - Event: After a webform has been submitted
* Conditions – Elements: Webform has a name – Parameter: The form id of the submitted form: \[form-id: value, Webforms: Summer Conference
* Actions – Elements:
    + Create a new entity – Parameter: Entity type: Node, Content type: Conference Participants, Title: \[data:last\_name-value\], ..., Author: \[node:author\] Provides variables: Created entity (entity\_created)

**Issues:**

I have not been able to pull any of the text fields (first and last name) from the webform into the node. For my testing, I’ve created a new “email” text field in the node because it is a standard field with most forms. There is a check box list of conference names in which more than one can be checked. I also have an entity type filed (auto complete) of universities around the world which are not pulling in. I suspect this one may be a bit more complicated since it is an entity type field and I may need to use another type of action, e.g. loop. I should add that there are other fields in the content type (Conference Year and a text box for participants to manually type in an institution that is not listed in the entity filed). I have the conference year checked automatically for 2018 (see screen shot below).

**Drupal and Module Background:**

* Drupal 7
* Rules Module
* Webform Rules
* Conditional Rules

**What I’ve tested:**

• Conditionals

* NOT an authenticated user
* Entity has field
* Set a data value
* Add a variable (with webform tokens using raw and just the value)

**Posts I’ve looked at:**

**Screen shots**

Summer Conference Participant Rule workflow

Conditions: Elements: Webform has name

Actions: Elements: Create a new entity

Actions: Elements: Add a variable

Actions: Elements: Save Entity

**Rule Export**

```
{ "rules_summer_conference_participants" : {
"LABEL" : "Summer Conference Participants",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "webform_rules", "rules", "rules_conditional" ],
"ON" : { "webform_rules_submit" : [] },
"IF" : [
  { "webform_has_id" : {
      "form_id" : [ "form-id" ],
      "selected_webform" : { "value" : { "webform-client-form-86866" : "webform-client-form-86866" } }
    }
  }
],
"DO" : [
  { "entity_create" : {
      "USING" : {
        "type" : "node",
        "param_type" : "conference_participants",
        "param_title" : "[data:last_name-value], [data:first_name-value]",
        "param_author" : [ "node:author" ]
      },
      "PROVIDE" : { "entity_created" : { "conference_participant_webform" : "Conference Participant Webform" } }
    }
  },
  { "CONDITIONAL" : [
      {
        "IF" : { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_email" } },
        "DO" : [
          { "variable_add" : {
              "USING" : { "type" : "text", "value" : "[data:email-value]" },
              "PROVIDE" : { "variable_added" : { "field_email" : "email" } }
            }
          }
        ]
      }
    ]
  },
  { "entity_save" : { "data" : [ "node" ], "immediate" : "1" } }
]  }}

```

**Debug Info**

Rules debug information:

" Reacting on event After a webform has been submitted.

* 0 ms Reacting on event After a webform has been submitted.
* 10.813 ms Evaluating conditions of rule Summer Conference Participants.
* 11.057 ms The condition webform\_has\_id evaluated to TRUE
* 11.067 ms AND evaluated to TRUE.
* "Rule Summer Conference Participants fires.
    + 0 ms Rule Summer Conference Participants fires.
    + 28.914 ms Evaluating the action entity\_create.
    + 29.263 ms Added the provided variable conference\_participant\_webform of type node
    + 31.59 ms Evaluating the action variable\_add.
    + 31.649 ms Added the provided variable field\_email of type text
    + 31.747 ms Evaluating the action entity\_save.
    + 31.8 ms Saved node of type node.
    + 727.681 ms Rule Summer Conference Participants has fired.
* 738.827 ms Evaluating conditions of rule Conference Participant.
* 741.628 ms The condition webform\_has\_id evaluated to FALSE
* 741.639 ms AND evaluated to FALSE.
* 741.68 ms Saved conference\_participant\_webform of type node.
* 861.009 ms Finished reacting on event After a webform has been submitted.

# Answer
> 1 votes
I'm not sure if these are the only issues you need to address to get the subsequent fields to populate, but I'm pretty sure these are 2 things within your Rules Actions that don't seem right to me:

1. You don't need that "Conditional Rules"-condition, which IMO always evaluates to FALSE (and hence no variable ever gets "added", with an initial value as in your rule). To QA-test this, just (temporary) also display some "hello"-Drupal message within that CONDITIONAL, I bet you will not ever get such message (which proofs the CONDITIONAL should not be there).
2. After you removed the CONDITIONAL (Rules Action), try to assign an initial value of `[data:email-value-raw]` to the variable you added, instead of the `[data:email-value]` in your current rule.
3. The machine name `field_email` for the variable you added seems suspecious to me ... If that is ALSO the machine name of your node's field (for the node being created), then try to rework this Rules Action like so:

* use whatever other machine name for the variable being added (let's assume you name it `email_entered_on_form`), with an initial value of `[data:email-value-raw]`.
    * add another rules action to "set a data value", whereas you should set a value for `field_email`, and with a value equal to `email_entered_on_form`.

---
Tags: 7, rules, webforms
---


# Question
Title: Is it safe to allow domain.com/username?
Are there any security risks if we create pathauto roule so that the user account pages are at domain.com/username

# Answer
> 4 votes
On a site that is not using a mechanism like the one implemented from the *Two-factor Authentication (TFA)* module, letting visitors know usernames of existing accounts is giving out half of the credentials. It doesn't mean it is easier to log in on somebody else's account, though.
Somebody who got my password for a site could probably try to use the same password for another site's account where I am using the same username. If I were using the same credentials for more sites, that could work, but somebody could argue it is my fault for using the same credentials on different sites.

On my experience on Drupal.org, the bigger issue was not the username being publicly available, but third-party software used on the server, which caused unauthorized access to account information to emails, usernames, and hashed passwords.

That said, Drupal 8 core code is being changed to use the output of `User::getDisplayName()` every time links to user accounts are given in a page. `User::getAccountName()` should be used when displaying the name to administrator users, the user who owns the account, or for the username in the login context.
Using domain.com/username for the user account pages is going on the opposite direction. I would rather use the output of `User::getDisplayName()` to build the path alias of user accounts pages.

As you are asking for a Pathauto pattern, this would mean using the *\[user:display-name\]* token when creating the pattern on admin/config/search/path/patterns.

>

Instead of domain.com/username, I would rather use domain.com/users/username or domain.com/u/username to avoid conflict with existing routes, or other path aliases.

To make an example of what could happen, I created a test site on simplytest.me where the user #1 is set with admin as username. I installed the Pathauto module and its dependencies, and I created a pattern for user entities using \[user:display-name\]. The result is that the URL for the user #1 became (after I bulk-updated the path aliases) https://dqth.ply.st/admin-0. (See the *-0* part added not to create conflicts between the registered route and the path alias).
This is happens when the route is already defined when the path alias is created. I cannot predict what would happen when a module using a route with a path that already exists as path alias is installed.

Also, if you look at the code of `User::getDisplayName()`, you will notice that by default it returns the username (the output of `User::getAccountName()`). It will return something different only if there is a module that implements `hook_user_format_name_alter()` and that module does alter the value of the `$name` parameter it gets.

```
$name = $this
  ->getAccountName() ?: \Drupal::config('user.settings')
  ->get('anonymous');
\Drupal::moduleHandler()
  ->alter('user_format_name', $name, $this);
return $name;

```

This means that you need to use the *\[user:display-name\]* token in the Pathauto pattern, but also install a module that implements `hook_user_format_name_alter()`. For example, you could use the Real Name module which adds a *Real name* field to user entities, containing the value Drupal 8 will use as display name. You can also implement a custom module for that.

---
Tags: 8, path-aliases, security
---


# Question
Title: Echo taxonomy description based on specific value of a field in a custom template
I'm trying to check the value of a field on my content type that is a list of taxonomy terms to see if it matches a specific taxonomy term, then if it does match, echo the description field of the taxonomy term I checked. Else, if it does not match, then nothing is to be printed out.

Here is the code I've been experimenting with, but thus far have been unsuccessful getting to work properly:

```
if ( isset($facil->field_facility_type['und']) &&
 $facil->field_facility_type['und'][0]['value'] == "Hospital")) {
foreach ($facil->field_facility_type['und'] as $description ) {
    echo '<span><p> Say something wild and crazy!</p>'.$description["value"].'</span>';
    echo '<br/>';
}

```

}

I'm confused on how to get it to check the value of the field of taxonomy terms, of which the specific one I'm trying to target for this piece is one of about 15 different terms.

# Answer
> 0 votes
So, here's what we ended up with:

```
$fterm = taxonomy_term_load( (int)$facil->field_facility_type['und'][0]['tid'] );
        $fname = $fterm->name;
        $description = $fterm->description;

        if( $fname == 'Hospital' ) {
            if( !empty($description) ) echo '<div>' . $description . '</div>';
        }

```

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


title: Unblock an automated blocked user

text:
# Question
Title: Unblock an automated blocked user
I used Login Security module to block users after some login failures. It works fine however I need to unblock such users after certain time like after 1 hour/day. How would I do that as it has configurations to *delete attempt* from database but user isn't unblocked and it has to be *active* manually.

Please see below attached screen shot of module configuration.

# Answer
> 0 votes
I just developed a small module named as Auto Unblock Users to unblock users.

This will only work if the user is blocked by Login Security module.

# Answer
> -1 votes
What about unblocking the blocked user after an hour using Rules module?

Edited:

Use Rules module.

Create custom event for your particular module event (for example, "User Blocked after login failure"

Unblock users after one hour.

---
Tags: 7, users, security
---


# Question
Title: How do I add a basic FlexSlider to the body?
I only need a very simple slider on a single page and so I just want to use Flexslider's most basic HTML options. But I cannot get it to work!

My code is pasted from http://flexslider.woothemes.com/basic-slider-with-custom-direction-nav.html except that I'm using images from my test server. I have triple and quadrupal (pun intended) checked that my styles are correct.

Here is the first bit of HTML:

```
<div class="flexslider optionset-default">
   <ul class="slides">

```

I have confirmed that FlexSlider is working by creating a View and adding it as a block.

One clue: My images all disappear on my test page when the flexslider block is active, which suggests to me that the flexslider JS is NOT being loaded normally (I presume it's loading its CSS dynamically).

Without hacking my theme files or adding JQuery code to my theme, is there a way to get FlexSlider to load in this scenario?

# Answer
Just copying HTML-part won't work as the page needs FlexSlider java script. So add it either by calling drupal\_add\_js() or modifying the html.tpl.php file of your theme.
> 0 votes

# Answer
I ended up using JS Injector to add the FlexSlider configuration code to my page and a block with a tag to add the FlexSlider library (adding it to the body, Drupal escaped the whole thing).

As I said in my question, I wanted a solution that didn't require modifying the theme. This is clunky, but it worked.

Too bad the Flexslider module doesn't add this simplest implementation. But I'll definitely use it on sites where I have nodes that correspond to slides.
> 0 votes

---
Tags: javascript
---


# Question
Title: Create content that is related to blocks
I need you to help me with a type of content.

I want to create a content that when you enter to publish it has related or referenced blocks created in the different views. Thus the administrator assigns the different blocks to a basic page.

Within my content, I refer to the block created with that structure. The format of the block is to display grid-type content.

I tried doing it by adding a field type in this way

> I hope it gets better understood now. thank you very much

# Answer
I have solved it this way

Inside my Content "Basic Page"

in Display, I see the blocks created with their styles. And then in my content it is visualized how they are made in the block view.

In "manage Display" I can move the created field, giving different locations without modifying the block structure. And remove or add block in my content.

I hope that it serves you thanks.
> 0 votes

---
Tags: views, blocks
---