# Question
Title: How to modify contents of drupal select form element based on what was selected in a preceeding select element
First off, I am not a Javascript guru so this may be easy to acccomplish but I just don't know how.

Here is my situation: I have created a form in Drupal 7 and I have two dropdown select box in that form. I would like to change the possible selections in the second dropdown based upon what the user has selected in the first drop down.

Is there a way to add a change listener in Drupal so as to trigger an ajax update of the form?

Thanks.

# Answer
You can create it with built-in Ajax Framework (you don't need to use javascript). Here is a nice example (and I'll include the code here):

```
function sandbox_ajax_dropdown($form, &$form_state) {
  $form['sandbox_ajax_dropdown']['province'] = array(
    '#title' => t('Province'),
    '#type' => 'select',
    '#options' => _load_province(),
    '#ajax' => array(
      'event'=>'change',
      'callback' =>'sandbox_ajax_dropdown_city',
      'wrapper' => 'city-wrapper',
    ),
  );

 $form['sandbox_ajax_dropdown']['wrapper'] = array(
    '#prefix' => '<div id="city-wrapper">',
    '#suffix' => '</div>',
  );

  $options = array('- Select city -');
  if (isset($form_state['values']['province'])) {
    $options = _load_city($form_state['values']['province']);
  }

  $form['sandbox_ajax_dropdown']['wrapper']['city'] = array(
    '#title' => t('City'),
    '#type' => 'select',
    '#options' => $options,
  );

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

  return $form;
}

function sandbox_ajax_dropdown_city($form, $form_state) {
  return $form['sandbox_ajax_dropdown']['wrapper'];
}

function sandbox_ajax_dropdown_city($form, $form_state) {
  return $form['sandbox_ajax_dropdown']['wrapper'];
}

function _load_province() {
  $province = array('- Select province -');
  $query = db_select("sandbox_province", "a");
  $query->fields("a", array('id', 'name'));
  $query->condition("a.status", 1);
  $query->orderBy("a.name");
  $result = $query->execute();

  while($row = $result->fetchObject()){
    $province[$row->id] = $row->name;
  }

  return $province;
}

function _load_city($province_id) {
  $city = array('- Select city -');
  $query = db_select("sandbox_city", "a");
  $query->fields("a", array('id', 'name'));
  $query->condition("a.status", 1);
  $query->condition("a.province_id", $province_id);
  $query->orderBy("a.name");
  $result = $query->execute();

  while($row = $result->fetchObject()){
    $city[$row->id] = $row->name;
  }

  return $city;
}

```

And also take a look at Examples module.
> 2 votes

# Answer
How to do this in Drupal 8? Above steps do not exactly work for Drupal 8. Also in my case the 2 select fields already exist (they were created in BaaseFieldDefinitions, so doing something like this:

```
$form['sandbox_ajax_dropdown']['wrapper']['city'] = array(
  '#title' => t('City'),
  '#type' => 'select',
  '#options' => $options,
);

```

doesnt work since the 'city' select already exists. My main issue is how to place the city select inside the target wrapper.
> 0 votes

---
Tags: 7, forms, ajax
---


# Question
Title: Template hook_preprocess_page not being called after duplicating website
I'me trying to duplicate a drupal website, using Druplal 7's multisite feature :

* I made a custom website folder (sites/site2.com) with correct settings.php for db
* I used backup & restore to transfer db content from site1 to site2
* I duplicated the theme (/sites/all/themes/site1theme to sites/all/themes/site2theme)
* I edited the theme.info, and changed the hooks in template.php (site2theme\_ ...) to match the new theme name

The front page is loading correctly, except that there is no CSS (and possibly some JS missing maybe)

template.php has a site2theme\_preprocess\_page function, whith some drupal\_add\_css() methods, but it looks like the hook function is not being called.

I've probably forgotten things in my website duplication process, and I'd be happy if you could give me some leads.

Thanks!

# Answer
> 0 votes
I hope you have tried clearing cache specifically for Drupal site2.

---
Tags: theming, hooks
---


# Question
Title: Render a view exposed filter in a region without exposing it as a block
I have already 20+ view pages that use exposed filter for filtering out content. What i want is to place the filter in the sidebar and not in the top of the page (different region).

I can exposed the view filters as a block and this will work fine but i have over 20+ view pages and that mean 20+ new blocks, increasing the load for the not dev users.

The better approach will involved using a hook to check the views id and if the match (1-20+ ids i will have) then move the exposed filter to a different region.

Is this possible?

# Answer
> 0 votes
That's interesting, there may be a possibility...

This would work if you 1) have the View object, or 2) if you can figure out which view to load via the url path or something...

You would put this code in a preprocess function for your region, or perhaps a template although that wouldn't be recommended. However you insert it into your region, the following code will generate the exposed filter form markup:

```
$view = views_get_view('view_name');
$form_state = array(
            'view' => $view,
            'display' => $view->display_handler->display,
            'exposed_form_plugin' => $view->display_handler->get_plugin('exposed_form'),
            'method' => 'get',
            'rerender' => TRUE,
            'no_redirect' => TRUE,
            'always_process' => TRUE, // This is important for handle the form status.
          );
          $form = drupal_build_form('views_exposed_form', $form_state);

          $exposed_filter_markup = drupal_render($form);

```

---
Tags: 7, views
---


title: Adding variables to all templates?

text:
# Question
Title: Adding variables to all templates?
I'm looking for a way to inject a feature flag variable so that it is accessible in all Twig templates, but I can't figure out how to do it. I've tried adding variables in preprocessing hooks in my .theme file, but this doesn't seem to do to the trick. For example:

```
function mytheme_preprocess_page(&$variables) {
  $variables['some_feature_flag'] = 'test_value';
}

function mytheme_preprocess_html(&$variables) {
  $variables['some_feature_flag'] = 'test_value;
}

```

My template for the node contains `{{dump(some_feature_flag)}}`, which evaluates to NULL. I can't find a way to get this working.

# Answer
So generally, preprocess hooks impact the specific theme item or template, so hook\_preprocess\_page() impacts the page.html.twig and hook\_preprocess\_html() does so for html.html.twig. You mentioned your twig template for node, to add variables to that you would need to implement hook\_preprocess\_node().

Your question was adding variables to all templates, I believe for that you would use just hook\_preprocess() (https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21theme.api.php/function/hook\_preprocess/8.2.x) - though I have never tried it. I imagine it would be called for every theme call so that could create a lot of overhead.

And don't forget to 'Clear all caches' under admin-\>config-\>development-\>performance when you create new preprocess hooks or template files.
> 5 votes

# Answer
If you want to add a variable to every template used from a theme, without implementing more than one preprocess function, you can:

Keep in mind that `hook_preprocess()` is invoked for a theme only when that theme is used for rendering the current page. That doesn't happen for modules; so, if those variables you are trying to set should be available to more than one theme, then it would be better to implement one of those hooks in a module.
> 1 votes

---
Tags: theming
---


title: hook_form_alter() adding ajax event

text:
# Question
Title: hook_form_alter() adding ajax event
I have a custom module that is adding a new field in the form in `hook_form_alter()`.

In my `hook_form_alter()` I have

```
function mymod_form_alter(&$form, &$form_state, $form_id) {
     $form['complaint']['complaint_category'] = array(
        '#type' => 'select',
        '#title' => t('Complaint'),
        '#options' => myfuc(),
        '#required' => TRUE,
        '#empty_option' => t('Choose complaint category'),
        '#default_value' => $selected_complaint_category,
        '#ajax' => array(
          'callback' => 'mymod_complaint_dependent_dropdown_callback',
          'wrapper' => 'dropdown-complaint-remark',
        ),
      );
}

```

If I add a break point in my code in the function `mymod_complaint_dependent_dropdown_callback()` it is not triggered. Another element in the form has a `#ajax`setting and a break point on it works.

In the UI no spinner is added to the page. So it looks to me like the ajax event is not being registered. Any ideas?

# Answer
> 0 votes
You could try adding an 'event' item to the ajax array in your FAPI code. The form needs to know when to trigger the ajax callback. The FAPI documentation says you don't have to specify it explicitly but try 'event' =\> 'change', and see if that works for you. Since you are not specifying it, perhaps the default one that Drupal uses is not right for a select type.

See https://api.drupal.org/api/drupal/developer%21topics%21forms\_api\_reference.html/7.x#ajax\_event

---
Tags: 7, forms, ajax
---


# Question
Title: Change form submit #access as a result of ajax callback
I have a form that requests some information first, then pre-populates other fields before a final submit. I'm trying to change the `#access` value for the buttons on the form. Both of the code snippets below come from the same form builder function.

Considering:

```
$form['actions'] = [
  'id_lookup' => [
    '#type' => 'submit',
    '#title' => 'Submit',
    '#value' => 'Lookup ID',
    '#ajax' => [
      'callback' => 'my_module_populate_id_info',
      'wrapper' => 'id_info',
      'method' => 'replace',
      'effect' => 'fade',
    ],
  ],
  'submit' => [
    '#type' => 'submit',
    '#title' => 'Submit',
    '#value' => 'Register for Event',
    '#access' => FALSE,
  ],
  '#weight' => 100
];

```

The above code provides two buttons, one which triggers the ajax callback (see below) and the other which will submit the final form.

The below code adds additional fields (they're all disabled) with information pre-populated. Everything works as expected, I just want to change `#access` on `id_lookup` to `false` and on `submit` to `true`, it's not working. I originally tried to just change the value, but I couldn't get that to work either.

```
if (!empty($form_state['values']['id'])) {
  $user_info = my_module_signup_get_id_info($form_state['values']['id']);
  $ldap_user = FALSE;
  $existing_user = FALSE;
  if (isset($user_info['ldap_user'])) {
    $ldap_user = TRUE;
    $first_name = $user_info['ldap_user']['givenname'][0];
    $last_name = $user_info['ldap_user']['sn'][0];
    $job_title = $user_info['ldap_user']['title'][0];
    $organization = $user_info['ldap_user']['department'][0];
    $email = $user_info['ldap_user']['mail'][0];

    $form['id_info']['first_name'] = [
      '#type' => 'textfield',
      '#title' => 'First Name',
      '#required' => TRUE,
      '#prefix' => '<div class="row"><div class="col-lg-6">',
      '#suffix' => '</div></div>',
      '#disabled' => TRUE,
      '#default_value' => $user_info['ldap_user']['givenname'][0],
  ];
  // ... some other fields
  // Try to change the #access on the actions
  $form['actions']['id_lookup']['#access'] = FALSE;
  $form['actions']['submit']['#access'] = TRUE;
} else {
  $form['id_info']['no_user'] = [
    '#type' => 'markup',
    '#markup' => '<p>No user was found for that ID</p>',
  ];
}

```

}

Everything works as expected *except* the access on those buttons - what am I doing wrong?

# Answer
> 0 votes
You really shouldn't alter the form in your ajax callback. What you want to do is set a variable in the form\_state in the ajax callback, and your form code should look for that variable to decide how to set #access

So in your ajax callback, lets say whatever conditions are met, and you want to disable access when it reloads...

So set a variable like, $form\_state\['access\_to\_field\_revoked'\] = TRUE

Then your form code:

```
$form['actions'] = [
  'id_lookup' => [
    '#type' => 'submit',
    '#title' => 'Submit',
    '#value' => 'Lookup ID',
    '#access' => empty($form_state['access_to_field_revoked']) ? TRUE : FALSE,
    '#ajax' => [
      'callback' => 'my_module_populate_id_info',
      'wrapper' => 'id_info',
      'method' => 'replace',
      'effect' => 'fade',
    ],
  ],
  'submit' => [
    '#type' => 'submit',
    '#title' => 'Submit',
    '#value' => 'Register for Event',
    '#access' => !empty($form_state['access_to_field_revoked']) ? TRUE : FALSE,
  ],
  '#weight' => 100
];

```

You will probably need another variable like $form\_state\['generate\_additional\_fields'\] = TRUE; and put your FAPI for those fields in the form callback, and not the ajax callback... so in your form callback:

```
if(!empty($form_state['generate_additional_fields']) {
// add your additional form fields now
}

```

Almost never a reason to alter the $form variable in the ajax callback. It is always best to set a variable in the form\_state and then look for that variable in the form callback to actually set the FAPI up.

**UPDATE:** Misread the post, so your code was in the form handler, not the ajax handler, and that will work.

One way that the #access property would not get updated is if the 'actions' buttons are outside of the wrapper div that ajax replaces. If they are, they would be showing via the '#access' value from initial form load. One solution would be to make sure that the wrapper that the ajax callback refreshes includes the action buttons, so that they are re-rendered.

In the FAPI inside your conditional, there is a suffix, with an extra /div . This maybe the closing div for your wrapper, and if that was placed after the form actions, perhaps they would get refreshed by the ajax callback, and it would work

---
Tags: 7, forms
---


# Question
Title: Display a view with exposed form programmatically
I show a view in my own module, like this: `$viewFromDrupal = views_embed_view('storage', 'block');`. The view is showing up, but the exposed filter is not working when I place the included view directly after an other view.

When the view `$viewFromDrupal` is showing at the top of the page the exposed filter works correctly.

Does someone have some experience with this?

*Should I include some extra files or something?*

# Answer
So better to say in your question more details of how it doesn't work, but I'll take a guess...

Try

```
$view = views_get_view('storage');
  $view->set_display('block');
$view_markup = $view->preview('block');

```

I've done this before to render the View, that will give you some markup...

Then I've noticed that the "action" of the form could be incorrect, so you have to do a hook\_form\_alter implementation and set the #action to the current page path...I'm guessing what the value of $form\['#id'\] will be, you will need to verify that ...

```
    function yourmodule_form_alter(&$form, &$form_state) {
    if($form_id == 'views_exposed_form' && $form['#id'] == 'views-exposed-form-storage-block') {
        $path = current_path();
        $form['#action'] = '/' . $path;
    }

  }

```
> 0 votes

---
Tags: 7, views
---


title: How do I access values using kint()?

text:
# Question
Title: How do I access values using kint()?
I am porting a module from Drupal 7 to Drupal 8. I was debugging using `kint()`.

I am using `hook_user_presave($account)` and trying to access the values of `$account` using `kint($account)`.

`kint()` is very confusing, compared to dsm() in Drupal 7.

How do I access values using `kint()`?

# Answer
> 1 votes
You can get the user entity from the proxy with `AccountProxy::getAccount`:

```
$entity = $account->getAccount();

```

And then the roles with `User::getRoles`:

```
$roles = $entity->getRoles;

```

If you don't need the entity for anything else in that method, it turns into a one-liner:

```
$roles = $account->getAccount()->getRoles();

```

---
Tags: debugging
---


# Question
Title: Can't populate integer value in title field using rules
I have a integer value that I'm trying to add to the title of a new node, but I can't figure out how to get it to work.

This the rule I have so far.

```
{ "rules_rule_create_bid" : {
"LABEL" : "Create a new Bid",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "button_field", "rules", "path" ],
"ON" : { "button_field_clicked" : [] },
"IF" : [
  { "button_field_compare_button" : {
      "clicked_field" : [ "field" ],
      "comparison_field_name" : "field_email_client"
    }
  },
  { "entity_has_field" : { "entity" : [ "entity" ], "field" : "field_client_email" } },
  { "entity_has_field" : { "entity" : [ "entity" ], "field" : "field_project_id2" } },
  { "entity_has_field" : { "entity" : [ "entity" ], "field" : "field_bid_count" } },
  { "entity_has_field" : { "entity" : [ "entity" ], "field" : "body" } }
],
"DO" : [
  { "entity_create" : {
      "USING" : {
        "type" : "node",
        "param_type" : "new_bid",
        "param_title" : "Default",
        "param_author" : [ "site:current-user" ]
      },
      "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
    }
  },
  { "data_set" : {
      "data" : [ "entity-created:field-bid-contractorname" ],
      "value" : "[site:current-user]"
    }
  },
  { "data_set" : {
      "data" : [ "entity-created:field-bid-projectid" ],
      "value" : [ "entity:field-project-id2" ]
    }
  },
  { "data_set" : {
      "data" : [ "entity-created:field-project-description" ],
      "value" : [ "entity:body:value" ]
    }
  },
  { "node_path_alias" : {
      "node" : [ "entity-created" ],
      "alias" : "p_[entity-created:field-bid-projectid]_u_[site:current-user]"
    }
  },
  { "entity_save" : { "data" : [ "entity-created" ], "immediate" : "1" } },
  { "data_set" : {
      "data" : [ "entity-created:title" ],
      "value" : "New Project #[entity-created:field-project-id2]"
    }
  },
  { "redirect" : { "url" : "p_[entity-created:field-bid-projectid]_u_[site:current-user]#overlay=node\/[entity-created:nid]\/edit" } },
  { "drupal_message" : { "message" : [ "entity:field-client-email" ] } }
]
}
}

```

I want the entity:field\_project\_id to show in the title, but all I get is the project number.

# Answer
> 1 votes
Title is a string, that's why, in your rule, before setting title value, add a variable, then set variable value to the integer value, then add an action: "convert a data type": your variable, from integer to string, then set a data value, your node title as variable name. else leave the same as it is.

---
Tags: rules
---


# Question
Title: When user.private_tempstore gets deleted
I've read about the

> \Drupal::service('user.private\_tempstore')-\>get('mymodule\_name');

and found similar to storing data in $\_SESSION.

I am using user.private\_tempstore in my module to store some data related to the user for a current session but when I logout and login again to the system found the value still persist in that variable. It is supposed to delete on logout.

To store data

```
  $userSession = \Drupal::service('user.private_tempstore')->get('user_profile');
  $userSession->set('user_profile', TRUE);

```

To get data

```
  $userSession = \Drupal::service('user.private_tempstore')->get('user_profile');
  $user_profile = $userSession->get('user_profile');

```

Is my understanding wrong?

# Answer
> 2 votes
Private tempstore data isn't deleted when you log out, it is usually deleted after a predefined, fixed amount of time.

If you want data that is deleted on logout, then either store in the session or store it somewhere with a random key that you put into a session (Useful when it is data that is no commonly needed on every request and/or larger than just a simple scalar value)

---
Tags: 8, sessions
---


# Question
Title: How to make a competition input form and a view?
I want to put scores in a form. See screenprint:

Some details about it:

* 2 pulldown menu's with players.
* 2 text boxes for the score, example: (8) and (2).

In the above example, the automatically calculated "comp score" will be `3` and `1`. If however the score is (6) and (6), then the comp score will be `1,5` and `1,5`.

So to summarize (about how to calculate the "comp score":

* When the score is equal both players get `1,5`.
* The winner gets `3`, the loser gets `1`.

They play in poules, several matches. Each match is put in like in the screenprint above.

The scores will be added up. And in a view they will be shown on the site as a ranking. The best on top.

I don't know how to imput the data, automatically give the comp score and how to add them up (to make the view will go).

# Answer
> 0 votes
To avoid writing a manual (to answer your question), here is a blueprint ...

### Content type Game

Create a content type "game", with 2 entity ref fields to another content type like "player", and the other fields like date, etc.

### 3 Rules Components

Create 3 similar rules components (with parameters the score for player 1, and another parameter for score of player 2):

* a 1st Rules Component with a Rules Condition to check if player1 has won, in which case you perform a 1st Rules Action to "set a data value" to set the "comp score" for player 1, and a similar 2nd Rules to set the "comp scrore" for player 2. Then add an extra Rules Action to save the entity (to ensure the comp value is also saved).
* a (similar) 2nd Rules Component to check if player2 has won.
* a 3rd , and one if the score was equal.

### Custom rule

Create a custom rule like so:

* Rules Event: before saving content of type "game"
* Rules Actions: Perform 3 Actions, whereas each of these action performs one of the Rules Components create as described above.

### Create a view games

Create a view of all your games. In doing so, use the Views Calc module to "add up the scores".

PS: I'm assuming this question is about D7.

---
Tags: forms, rules
---


# Question
Title: Drupal 7 LoginToboggan username or email or custom field
I have a Drupal 7 site and the client wants the user to be able to login using: email or username or a custom\_field that's unique to each user. I've scoured for solutions but can't find any. Any help would be appreciated. I'm using Logintoboggan to handle username or email, but can't find anything to validate and allow authentication for a custom field.

Thanks!

# Answer
> 1 votes
You can do that by using this contrib module: https://www.drupal.org/project/login\_custom\_field

It will allow you to log in using a (custom user field and password) along side with (username and password). Also, you can enable LoginToboggan module to allow using (email and password) as a 3rd option.

---
Tags: authentication-authorization
---


# Question
Title: Site redirects to old URLs after moving to a new server
I am in the process of moving a Drupal site to a new server. I copied the database and moved all the files.

The old URL for the site is http://www.sniffingmusicians.echidna-band.com/ and the new is http://www.sniffingmusicians.com/, which point to a different server.

Even though the frontpage of new is there, when I log in, I am redirected to the old domain.

Additionally, all the content is using the old URL. I changed the value of `$base_url` in settings.php, but there is no real impact.

Where else can I reconfigure my site's URL?

# Answer
I came up with the same error after did a server migration.

After all those try error, I just realised I didn't give apache permission to access the web folder. After added in apache config, everything works as charm
> 1 votes

# Answer
Maybe you can use this module:

Path Redirect (Drupal 6)

Redirect (Drupal 7)
> 1 votes

# Answer
Just in case someone else comes across this issue.

1) Check that the base URL is set or uncomment it in the settings.php around line 247. Mine was set to the old URL and did a www redirect.

2) Check your .htaccess file in case there are some hard coded redirects. Look for the full URL.

3) As mentioned before in the accepted answer, check permissions are correct. Some really good help here: https://www.drupal.org/node/244924

4) If you have the global redirect module enabled turn it off.

```
drush pm-disable globalredirect
drush cc all

```

or use SQL and truncate the cache tables manually:

```
UPDATE system SET status=0 where name='globalredirect';

```

5) Apparently mobile tools can also cause the redirect. https://www.drupal.org/node/1713462#comment-6312804

```
drush pm-disable mobile_tools
drush cc all

```

Or with SQL

```
UPDATE system SET status=0 where name='mobile_detect';

```

6) Secure pages can also cause the redirect. This is what it was in my case. You can set the base path variable to your new domain using either drush:

```
drush vset securepages_basepath 'http://example.com'
drush vset securepages_basepath_ssl 'http://example.com'
drush cc all

```

Or disable secure pages entirely via drush:

```
drush pm-disable securepages

```

And here via SQL and truncate the "cache\_\*" tables yourself:

```
UPDATE system SET status=0 where name='securepages';

```
> 1 votes

# Answer
If you are using domain access, be sure to check the table PREFIX\_languages. I had the exact same problem and wasted 2 days before I found the problem. The old domain was hard coded in the PREFIX\_languages table and once I changed it everything worked perfectly.
> -1 votes

---
Tags: 6, migrations
---


title: Entity query for distinct field

text:
# Question
Title: Entity query for distinct field
I have an entity line\_item with the following fields:

* id
* uid (entity reference)
* product (entity reference)
* ...

I would like to get all distinct products (product ids) for a specific user.

I tried with entity query:

```
$query = $this->entity_query->get('line_item');
$query->condition('uid.entity.name', $username);
$entity_ids = $query->execute();

```

Unfortunately this results in all line\_items from the given user, with multiple times the same product. But what I am interested in is just getting all different products for the given user.

# Answer
I don't think it's possible to write a single entity query to accomplish this. You could take your $entity\_ids result, use loadMultiple to load all the line\_item entities, and then iterate through them to get all the products. Something like this:

```
$line_items = $this->entity_type_manager->getStorage('line_item')->loadMultiple($entity_ids);

$products = [];
foreach ($line_items as $line_item) {
  $product = $line_item->getProduct();
  if ($product && !isset($products[$product->id()])) {
    $products[$product->id() = $product;
  }
}

```

Another possibility would be to use the database service to construct a select query with actual database table names and fields (\Drupal\Core\Database\Connection).

See: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Connection.php/function/Connection%3A%3Aselect/8.2.x

and for the list of methods you can use to construct the select: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Query%21SelectInterface.php/interface/SelectInterface/8.2.x
> 0 votes

---
Tags: 8, entities
---


# Question
Title: How to create a single View with 2 different, optional contextual filters?
I need to check whether there is already a registered user having the same user email **or** username. Right now I have two Views (one with passing the username and one with passing the user email as contextual filter). When there is no user with the username, the second view is called.

There is the "allow multiple values" setting for the contextual filter, but this allows me to pass 2 emails, but not an email or a username for instance.

**Is there a way to create one View where the user enters a value (name or email) as filter?**

**SOLUTION:**

As suggested by Marco that works well:

# Answer
> 1 votes
You can create a view with a context filter for username and a context filter for usermail.

Then check the input of the user, if it is a email adress. If it is a email you can redirect to the view and set the context filter for the username to "all" and the context filter for the mail to the user input.

If it is no mail adress you can set the context filter for the usermail to "all" and the context filter of the username to the userinput and redirect to this path.

---
Tags: 7, views
---


title: Accesslog functionality?

text:
# Question
Title: Accesslog functionality?
Accesslog was removed from the Statistics module in Drupal 8: https://www.drupal.org/node/1446956. Does this functionality now exist somewhere else in core?

# Answer
As reported in Accesslog removed from the Statistics module, the module with that functionality is the Better Statistics module, which (at the moment I am writing this answer) doesn't have a Drupal 8 version.

> The accesslog and all associated reports have been removed from the core Statistics module. This functionality exists in contrib at http://drupal.org/project/better\_statistics.

There is a issue open for porting the module to Drupal 8, Port Better Statistics to Drupal 8, which was created after the change record.

The History module in Drupal core doesn't keep a log for the access to all the pages, but it keeps a log for the access to nodes. If you are interesting just to the users who accessed a node, that could help you.
> 1 votes

---
Tags: 8
---


# Question
Title: Work around to getting Backup and Migrate to work with Acquia Dev Cloud?
Currently, when you host a site onto Acquia Dev Cloud, they disable the ability to install backup and migrate module due to it affecting their "server" setup. This proves to be a big nuisance when trying to create a quick backup of a site and to even make scheduled hourly backups. The suggest us to use the Acquia platform to do backups, but it's totally inefficient since it cannot schedule your own backup times. And doing this via drush is troublesome if you just want to do a quick backup because you wanted to make a change on a site just in case it breaks it.

How would one go around this problem of backing up a site with Acquia dev cloud?

# Answer
> 1 votes
The best is enable your access to the command line to their server.

For this you need to store your public ssh\_key in your profile on their platform.

Then to find the exact server and username to connect do :

* Sign in to the Acquia Cloud interface.
* Select your application and environment.
* In the menu to the left, click Users and Keys, to see your exact command :

What follows is using drush ... but wait ... you can automate the use of drush : I explain.

Once logged, you can use drush from the command line, like this :

`cd dev/livedev/docroot`

`drush ard`

Since you have access to the command line, you can also use scp to transfer your backup.

By the way you won't have the possibility to access crontab -e there, however, you can write a script and execute from your computer to connect via ssh, do the backup, and get it using scp.

Once this script is written, you can use the cron from your computer to execute it every hour if you want.

That script would look like :

`cd ~/dev/livedev/docroot
drush ard
cd drush-backups/archive-dump/
cd `ls -Art | tail -n 1`
mv `ls -Art | tail -n 1` ~/last_backup.tgz`

You can store it remotely as ~/backup.sh locally in your cron you put

`ssh -t -t yourlogin@youraddress '~/backup.sh && exit' && scp yourlogin@youraddress:~/last_backup.tgz /home/yourself`

For an explanation of the -t -t, see https://serverfault.com/questions/224307/ssh-fails-to-execute-remote-command-when-run-from-cron-bash-script-works-from

If any other issue, with ssh from cron, please watch also : https://serverfault.com/questions/186448/crontab-to-run-bash-script-ssh-command-in-it-not-working

Another solution is to use the scheduled job from their interface, as explained there : https://docs.acquia.com/acquia-cloud/manage/cron

If any other problem please comment.

# Answer
> 1 votes
Correction : The install of Backup And Migrate works.

Follow the procedure explained before to enable ssh access. Once logged in, do

`cd ~/dev/livedev/docroot`

Then

`drush -y en backup_migrate`

That's all. I tried. It just works. Here is screenshot :

---
Tags: drush, backups, acquia-cloud
---


# Question
Title: How to exclude items from search api solr by negative keywords field
Drupal 8, Search API SOLR.

I'd like to not return nodes if there are any matches between a field of negative keywords (on the node) and the **query string** the user has entered.

Module `search_api_solr` currently set up with several fields, matching in node titles, body and keyword fields.

e.g. node titled "I can't find my elephant" with a negative keyword field containing "wallet" to not show up in a search "I can't find my wallet".

# Answer
> 0 votes
This is the solution I came to:

Add the field in search API

Add a filter query in hook\_search\_api\_solr\_query\_alter to exclude nodes with the negative keywords.

```
    // Generate a filter query to do a negative search for each word in the search string.
    $search_words = explode(' ', trim($query_string));
    $filter_query_parts = [];
    for ($x = 1; $x <= count($search_words); $x++) {
        $filter_query_parts[] = '-ts_field_negative_keywords:%' . $x . '%';
    }

    $filter_query_text = '( ' . implode(" OR ", $filter_query_parts) . ')';

    // Apply the filter query to the search.
    $solrQuery->createFilterQuery('ts_field_negative_keywords')->setQuery($filter_query_text, $search_words);

```

# Answer
> 2 votes
You don't need to do this in solr, you can do it in the query or with views filters.

Something like this:

```
$solrIndex = \Drupal::entityTypeManager()->getStorage('search_api_index')->load('global');
$query = $solrIndex->query();
$query->addCondition('title', $search_string);

$search_terms = explode(' ', $search_string);

// Don't match items where elements in the title match the stop words
// for an entity.
foreach ($search_terms as $term) {
  $query->addCondition('field_stop_words', $term, '<>');
}

```

# Answer
> 0 votes
Please check the following screenshots.

---
Tags: 8, search
---


# Question
Title: Entity Metadata Wrapper ->set saving data in incorrect language
I'm using entity\_metadata\_wrapper to programatically create some nodes. I noticed that some of the fields weren't showing in the node/edit form after doing this, even though they are shown on the frontend. After lots of digging I found in the database that the field data is being saved with 'und' instead of my chosen language ('en'). What is the way to fix this?

The field 'introduction' is definitely translatable before anyone asks (otherwise it would show in the backend just fine).

```
$entity = entity_create('node', array(
    'type' => 'my_bundle',
    'uid' => $user->uid,
    'status' => 1,
    'comment' => 0,
    'promote' => 0,
    'language' => 'en'
  ));

$ewrapper = entity_metadata_wrapper('node', $entity);
$ewrapper->language('en'); // Thought this would do it, but no dice
$ewrapper->title->set('This works fine');
$ewrapper->field_introduction->set('This doesnt');
$ewrapper->save();

```

# Answer
Test the following described here:

```
$ewrapper = entity_metadata_wrapper('node', $entity, [
  'langcode' => 'en',
]);

```

instead of

```
$ewrapper->language('en');

```
> 0 votes

---
Tags: 7, entities
---


title: How to delete invalid token?

text:
# Question
Title: How to delete invalid token?
After a recent migration from D6 to D7 some of the product descriptions made in the body of certain content types contains technical data like this:

```
[0...+70°C: ±0,2°C]

```

This is interpreted as tokens by the site and I get this message when I try to edit the content and then save the changes:

```
The Body is using the following invalid tokens: [0...+70°C: ±0,2°C]

```

How can I get around this, since it is not possible to save changes? I have tried to change the value directly in the database and then clear all cache, but the problem is still the same.

What to do?

# Answer
> 0 votes
Finally found out what the problem was. It was the Metatag module that copied the content in the body (using tokens) and used it as metatag description text. So by simply editing the metatag description field I got rid of the problem.

---
Tags: 7, tokens
---


title: Coupon redemption form

text:
# Question
Title: Coupon redemption form
I just updated the Drupal Commerce installation to beta 7 which includes support for promotions and coupons. I just can't seem to get the coupon redemption form in the cart to test this functionality. I checked the cart view, there is a field 'Coupon' in the global footer, but that is just meant to show the already activated coupons I believe. At least it didn't do anything for me.

I tried to add 'Coupon' to my relationships in the view, but this broke down the website (incorrect query generated).

In the code I also noticed the CouponRedemption FormElement. I'm not sure how to add this to my cart (view), but that seems to be what I need.

# Answer
I finally figured out the answer: the functionality has simply not been coded. Applying the patch from this issue: https://www.drupal.org/node/2792653 (patch #95 is the latest right now) will add a checkout pane for entering coupon codes. It is still not available on the cart page as you would expect in a webshop, but at least visitors can enter a coupon code.

You can place the checkout pane using Commerce-\>Configuration-\>Checkout flows-\>pick your flow by clicking 'edit'-\>Coupon redemption pane.
> 0 votes

---
Tags: commerce
---


title: How do I use Git when using Composer?

text:
# Question
Title: How do I use Git when using Composer?
I am working on an OpenSocial project and its installed via composer. I am having a folder structure as below:

* composer.json
* composer.lock
* html
(Drupal Installation.)
* vendor
(Dependencies)

When creating, should I add the all files including composer.json and vendor to the Git repository, or just the *html* directory?

In some cases, for example in a normal Drupal 8 installation the Composer files and the *vendor* directory are in the same directory as the Drupal files.

# Answer
> 4 votes
Short answer: no, you do not need to commit the vendor folder, because the contents are built using composer.lock and composer.json (both should be committed) when running `composer install`. *Some* people have to commit vendor due to their hosting constraints and/or having no build process (where the application is built for deployment).

IMO management via Composer with vanilla D8 tarball is very difficult as it lacks the structure to facilitate solid version control, project management and patching workflow that others like Drupal Project or Acquia BLT offer.

---
Tags: version-control, composer
---


# Question
Title: View display nodes with taxonomy term found in URL
**Using Drupal 8**

I have a *working setup* my problem is when I try to access a taxonomy term that is made up of **two words.**

Set up.

* `View` : shows nodes of content type A
* Has `relationship` (required) with a field in the content type that stores the `taxonomy term` (one or more terms need to be associated to each content type)
* Has `contextual filter` (that uses previous relationship) to get the taxonomy term from the URL. The filter gets the default value from `Raw value from URL` with `Path component: 2` , and it has `Use path alias` instead of internal because the URL has the taxonomy term name. It also has `Specify validation criteria` by `Taxonomy term name` by `Transform dashes in URL to spaces in term name filter values` so that **fan-art** can be correctly matched to taxonomy term **fan art**.

I have no problem with taxonomy terms made up of one word, it's the ones made up of two words that are giving me a headache, any ideas?

# Answer
> 0 votes
I gave up trying to understand why it doesn't work and resorted to using `Has Taxonomy term ID` instead.

* The URL contains the taxonomy term ID so *only* a **Contextual Filter** is needed. In **raw value** the URL is **taxonomy/term/\[id\]** , so all that needs to be done is tell the **Contextual Filter** to `Provide default value` from *Type* `Raw value from URL` and *Path Component* `3`. I also added a `Specify validation criteria` *WhenThe Filter Value is available or a default is provided*, of *Validator* `Taxonomy term ID` and chose the appropriate *Vocabulary*.

# Answer
> 0 votes
I'm not sure if this meets the requirements of your specific use case, but for anyone else who ends up here looking for something similar here it is: In the contextual filter select **'Name'** instead of **'Taxonomy Term ID'** and then check the box **'Specify validation criteria'** and select **'Taxonomy term name'** as your validator. Then check the box **'Transform dashes in URL to spaces in term name filter values'**

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


# Question
Title: Modification on what appears to be a 'Category View' page
I am a Joomla developer by default but have been asked to make some minor changes to an old Drupal site to tidy up what I can only describe as a category page.

The page can be found here

I need to try and add a line/border underneath each category and align the images so that they have the same layout/vertical alignment as each other.

Can anyone advise the best way to do this? The site is not being updated due to it being migrated to Joomla in the future, thus a quick fix is all that is required at the moment.

Any suggestions would be most welcome. I'm still having a look around the site trying to figure this out, but any pointers would be most welcome.

Update: I have some custom css which may well do the job

```
    .node-sale-item {
    margin-bottom: 30px;
    border-bottom: 1px solid;
    padding-bottom: 30px;
}

```

I'm now looking at how to implement it. If there are any better suggestions however i'd be happy to hear them.

Regards Donna

# Answer
I've tried your css code for the classes `.node-promoted` and `.node-sale-item` on your page, using web-inspect. It works, all you need to do is to apply the CSS to any of the classes in your theme's .css

Navigate to http://hutchesonsofportsoy.co.uk/admin/appearance (as an admin) to find out your enabled theme (usually on the top) and then copy the styles to-

**root \ sites \ all \ themes \ \[enabled-theme\] \ css \ \[file.css\]**
> 0 votes

---
Tags: views
---


# Question
Title: How can you remove the edit lock on a node?
When I try to save a node I am working on I get this error message.

> The content on this page has either been modified by another user, or you have already submitted modifications using this form. As a result, your changes cannot be saved.

What is causing that issue and how can I remove the lock?

# Answer
Did you use the back button to get to your edit page? Have you tried manually going to the node and clicking the edit tab again to see if it reoccurs?

This message is caused when either (1) two users access the edit page and one user saves changes before the other user gets a chance or (2) when a user edits content, saves it, and clicks the back button to get back to the edit page.

https://obrienmedia.co.uk/kb/drupal-website-management/avoiding-the-the-content-on-this-page-has-either-been-modified-by

Are there other users signed in? When all else fails (or rather the first step of troubleshooting always) Flush all cache. Clear your browser cache. Close your browser out. Re-open your browser. Attempt to recreate problem. Is it still happening?
> 6 votes

# Answer
I had the same problem on an international site and here it was the "Administration Language Module" that caused the troubles. JFYI.
> 2 votes

# Answer
If the problem is related to two users editing the same record (node), it can be related to max\_input\_vars in your php.ini

There are two solutions to solve the problem (I recommend trying both of them):

1. Edit phpi.ini and increase max\_input\_vars (find max\_input\_vars = ... and increase it). php.ini can be found in different locations for example in an ubuntu conventional setup it can be at /etc/php5/apache2/php.ini
2. Clear cache (depend on your browser this is a pretty easy routine and you already do not know it, just google it).
> 2 votes

# Answer
Try to :

truncate the 'cache\_form' table.

clear caches.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Using jquery mmenu, how to close one submenu when I open another submenu?
I'm building a (Drupal 7.5) site where I use mmenu (Mobile Sliding Menu) module to create the menu. When I click the trigger, the main menu items appears. Some of the main items have a submenu. When I click the trigger for those submenus, the submenu opens, so far so good.

When I then click another submenu trigger, that submenu opens, but the previously opened submenu stays open as well. What do I need to change to have only ever one submenu open at any one time (i.e. triggering a new submenu closes one that was opened before)? There is no setting for this in the mmenu configuration (drupal module), and no instructions on this on the mmenu website (http://mmenu.frebsite.nl).

Many thanks for any help on this.

# Answer
The easiest method I can think of is to use JS or jQuery to trap the click for every sub-menu item then, onclick, cache a reference to the clicked item, then programmatically close all of the open sub-menus with a loop, skipping the clicked item.

Try something like this:

```
(function ($, undefined) {

  // Execute once the DOM is loaded.
  $(document).ready(function () {
    // List of expandable sub-menu items.
    var subs = $('.mm-subopen');

    // Iterate through each sub-menu item...
    $(subs).each(function () {

      // Set up onclick handler...
      $(this).click(function () {

        // Cache reference to clicked item.
        var clicked = this;

        // Iterate through list of sub-menu items...
        for(i=0,c=subs.length;i<c;i++) {

          // If current item is not the clicked item...
          if (subs[i] !== clicked) {

            // Get reference to parent <li>, then remove the mm-opened class.
            var parent = $(subs[i]).closest('li');
            $(parent).removeClass('mm-opened');
          }
        }
      });
    });
  });
})(jQuery);

```

You might need to modify for nested sub-menus, but I hope this helps!
> 1 votes

# Answer
HTML

\<nav\>
\<ul\>
\<li\>\<a\>\</a\>\</li\>
\<ul class="sub-menu"\>
\<li\>\<a\>\</a\>\</li\>
\<li\>\<a\>\</a\>\</li\>
\<li\>\<a\>\</a\>\</li\>
\</ul\>
\</li\>
\</ul\>
\</nav\>

CSS

.sub-menu { display: none; }

JQUERY

```
$("ul > li > a").click(function () {
   var _parent      = $(this).parents("ul");
   var _children    = $(".sub-menu", _parent);
   var _nextElement = $(this).next();

   _children.css({ "display":"none" });
   _nextElement.css({ "display":"block" });

});

```
> -1 votes

---
Tags: theming, javascript, navigation
---


# Question
Title: How can I act on a taxonomy term in my twig template?
I'm trying to use two taxonomy items to build a button on my template. The logic is:

```
If this node is exactly equal to taxonomyTermFromVocabularyA
Print a button on the page with a URL built out of taxonomyTermFromVocabularyB

```

I thought I was doing well when a simple test proved that my terms were available. In the template, I tested by adding:

```
<h3>{{ content.field_taxonomy_resource_type }}</h3>
<h3>{{ content.field_taxonomy_topic }}</h3>

```

And out came the expected values on the page:

> Topic Page
>
> Oral Health

However, once I tried to actually use the terms I captured it never worked. The first part of the logic, where the button will eventually be built, I wrote as:

```
{% if content.field_taxonomy_resource_type == "Topic Page" %}
  <p> hello, it's working! </p>
{% endif %}

```

produces no content at all. I expected to see my test paragraph sentence "hello, it's working!" appear on the page.

My best google-foo hasn't helped me at all and, alas, my soul is being crushed. I fear it's something completely obvious that I am just ignorant about.

Can anyone point me to the error of my ways? Why doesn't my twig `if` statement work?

@clive was absolutely right in the suggestion below that I was naming the array and not the particular item I needed when constructing my `if` statement. His correction to my code:

```
{% if node.field_taxonomy_resource_type.entity.label == "Topic Page" %}

```

is not working though, and the best I can tell is that the variable is unavailable to me. When I dump the variable using `{{ dump(node.field_taxonomy_resource_type.entity) }}`, I just get NULL.

Clive's answer worked as soon as I changed out node to paragraph. Thanks!

`{% if paragraph.field_taxonomy_resource_type.entity.label == "Topic Page" %}`

# Answer
> 4 votes
`content.field_taxonomy_resource_type` is a render array, which you're comparing against a string. Instead, you need to get access to the label, and extract the term name.

Try this instead (if in a node template):

```
{% if node.field_taxonomy_resource_type.entity.label == "Topic Page" %}

```

Or, as we know it's a paragraph template:

```
{% if paragraph.field_taxonomy_resource_type.entity.label == "Topic Page" %}

```

# Answer
> 0 votes
I've been looking for something like this as well. I just tested

> {% if node.field\_taxonomy\_resource\_type.entity.label == "Topic Page" %}

and it worked for me after a couple of cache refreshes though - I also got null dumps initially when testing.

---
Tags: theming, 8
---


# Question
Title: Service module user update request payload
I am using postman to update user. Please suggest me what headers need to be send and what should be the payload structure in JSON format. Should I send user object in params OR in body in postman.

# Answer
> 1 votes
To update a user with the Services module, utilize these:

HTTP Method: **PUT**

URL: `?q=[endpoint-name]/user/123.json`

**Headers**

* **Content-type**: `application/json`
* **X-CSRF-Token**: use value available from `?q=services/session/token`

**Data payload**:

```
{
  "uid":"123",
  "mail":"new-email-address@example.com",
  "current_pass":"superSecret"
}

```

---
Tags: services
---


title: Change Administrative theme

text:
# Question
Title: Change Administrative theme
I have changed my Administrative Theme to a theme I don't like and now I cannot change it back. There is a drop down to change, but no save configuration option anymore.

# Answer
> 0 votes
You can change it back with drush:

```
drush vset admin_theme seven

```

Or PHP:

```
variable_set('admin_theme', 'seven');

```

Or if you're in a real bind, via the settings.php file temporarily:

```
$conf['admin_theme'] = 'seven';

```

Replace "seven" with the machine name of the theme you want to use for the admin pages.

---
Tags: theming
---


# Question
Title: How can i set this redirect only for anonymous users?
```
namespace Drupal\project_extras\EventSubscriber;

use Drupal\Core\Url;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class RedirectAnonymousSubscriber implements EventSubscriberInterface {

  public static function getSubscribedEvents() {
    // This announces which events you want to subscribe to.
    // We only need the request event for this example.  Pass
    // this an array of method names
    return([
      KernelEvents::REQUEST => [
        ['redirectMyContentTypeNode'],
      ]
    ]);
  }

  /**
   * Redirect requests for my_content_type node detail pages to node/123.
   *
   * @param GetResponseEvent $event
   * @return void
   */

  public function redirectMyContentTypeNode(GetResponseEvent $event) {

    $request = $event->getRequest();

    // This is necessary because this also gets called on
    // node sub-tabs such as "edit", "revisions", etc.  This
    // prevents those pages from redirected.
    if ($request->attributes->get('_route') !== 'entity.node.canonical') {
      return;
    }

    // Only redirect a certain content type.
    if ($request->attributes->get('node')->getType() !== 'specific_content_type') {
      return;
    }

    // This is where you set the destination.
    $redirect_url = Url::fromUri('entity:node/10');
    $response = new RedirectResponse($redirect_url->toString(), 301);
    $event->setResponse($response);
  }
}

```

# Answer
You can load a user and check for authentication

```
$currentUser = \Drupal::currentUser();

// Do nothing if the user is authenticated.
if ($currentUser->isAuthenticated()) {
  return;
}

```
> 0 votes

---
Tags: 8
---


title: How to turn off Captcha for search?

text:
# Question
Title: How to turn off Captcha for search?
I've installed the Captcha module and I need to remove it from the search button and form (just an unnecessary nuisance there). Captcha configuration allows me to turn it off for specific values of a "Form\_ID". I tried that with "search", but I guess the form ID is more complicated than that. What Form\_ID(s) do I need to use to get Captcha to stop showing up in search?

Thank you.

# Answer
> 1 votes
For a block, the form\_id should be:

> search\_block\_form

and for a page:

> search\_form

To easily find this information, install the Devel module:

> A suite of modules containing fun for module developers and themers

and use something like this in your theme's template.php file:

```
function myTheme_form_alter(&$form, &$form_state, $form_id)
{
    dpm($form);

}

```

This will show a hierarchical display of all forms on the page - you can then scroll quickly through the info to find what you need. Very handy for searching arrays.

# Answer
> 1 votes
Simple uncheck this "Default challenge on non-listed forms." on admin/config/search/settings

---
Tags: search, captcha
---


title: locally host a working website

text:
# Question
Title: locally host a working website
I'm trying to locally host an already working/hosted website using wampp to try and edit it without messing up the site. But every time I try to open the site using localhost/example, it automatically redirects to the hosted domain(https://www.example.com). Can someone help me solve this issue?

# Answer
> 0 votes
You have an .htaccess rewrite rule / PHP redirect moving all traffic to https://www.example.com when the domain/protocol doesn't match.

If it's in .htaccess look for these lines and comment them out:

```
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

```

If there's an http -\> https redirect that will have been set up manually (the above is included in the core .htaccess), so you'll need to locate and remove that separately.

If it's in PHP, it typically happens in settings.php. You should be able to see what's doing it fairly easily and comment out/remove for your local environment.

Failing that, you'll probably need to trawl the code to find out what's responsible for the redirect.

# Answer
> 0 votes
Check if the URL is hardcoded in **.htaccess** file, any re-direct module or rule enabled. Also try opening in a different browser as Firefox apparently per this thread tries to fix the address if there's a bad connection. If nothing fixes the redirect, try a re-install following the steps here.

---
Tags: migrations, importing-exporting
---


# Question
Title: 7 - HTTP error 400 when calling system_retrieve_file()?
I'm using `hook_feeds_after_save` and the `simpleHTMLdom` library to migrate inline images for a feed import. After I detect that an image tag exists and the url is qualified/valid I build a stream wrapper for the image file and call `system_retrieve_file`.

```
  $dirPrefix = 'archive';
  $uri = file_build_uri($dirPrefix . '/' . $filepath);

  if (file_prepare_directory($uri, FILE_CREATE_DIRECTORY)) {
    $destination = $uri . '/' . $filename;
    system_retrieve_file($img_url, $destination, TRUE, FILE_EXISTS_REPLACE);
  }

```

However, I receive 400 errors on each image; `HTTP error 400 occurred when trying to fetch http://DOMAIN.COM/C8B195/assets/images/01 Grapes 3.jpg.`

If I just plop this url into a browser I get a 200 and the image is displayed. Same when I test this in something like the Advanced Rest Client application.

Also, I'm developing this site in a local environment.

Anyone have any clue how to debug this or why I may be receiving a 400 response?

# Answer
> 0 votes
In my case, I needed to encode urls, but not how you may expect with PHP's `urlencode` or `rawurlencode`. For example, I needed to convert `http://DOMAIN.COM/C8B195/assets/images/01 Grapes 3.jpg` to `http://DOMAIN.COM/C8B195/assets/images/01%20Grapes%203.jpg`. I'm not sure why `system_retrieve_file` or `drupal_http_request` had a problem with the spaces.

```
  $encodedPath = rawurlencode($path);
  $encodedPath = str_replace('%3A', ':', str_replace('%2F', '/', $encodedPath));

```

---
Tags: hooks, feeds, importing-exporting, files
---


# Question
Title: Integrating Commerce Feeds and Physical Field. (Drupal Commerce)
I'm importing over 40K of products from a .csv file. The file includes weights and dimensions (height,width,length). I use physical field module to define my fields for weight and dimension. I'm having problem mapping weights and dimensions from my .csv file to my product table where I define the weights and dimensions as Physical Field (Physical Field Module) because it's not showing as the target field. I will appreciate any help. Thank you in advance.

# Answer
> 2 votes
If you can't find Physical Field integration with Commerce Feed module for mapping your fields such as height, width or length, please have a look on a discussion started by bmx269 at http://drupal.org/node/1293820. Apply the patch & you will be able to find the field to map with your CSV file header.

Good luck...

# Answer
> 0 votes
A patch was committed to the dev version as of Nov. 26, 2016 (Drupal 7). If there is a release after that date it should be included, otherwise you'll need to use the dev version.

---
Tags: commerce
---


# Question
Title: Site aliases: Use a different PHP path on remote
### The Problem:

For reasons I'm not gonna get into, the path to my php executable is ***NOT*** `/usr/bin/php` but is instead something else (let's say it's `/local/path/to/php`).

My staging and production servers ***do*** use `/usr/bin/php`, however; Moreover, the non-standard php path doesn't exist on those servers.

The problem is that whenever I run a Drush command for a remote site, I get an error:

```
$ drush @mysite.remote status
bash: /local/path/to/php: No such file or directory

```

Since `/local/path/to/php` *definitely* exists on my local machine (or else my local sites wouldn't work and drush would fail) I can only assume that error is coming from the remote server.

I know I can pass `--php=/usr/bin/php` to Drush, but there are some less Drupal-savvy devs on my team, so I want to get it configured for them so they don't have to think about it.

I also know about the `$DRUSH_PHP` environment variable, but setting that to `/usr/bin/php` breaks drush on my dev machine entirely, so that's not an option either. It just straight-up breaks Drush.

### The Question:

Is there a way to configure my remote aliases to use a specific path to PHP that is different to my local machine's PHP path? (And why is a remote server trying to use a local path to PHP in the first place?)

If not, what workarounds are there? (I'm hoping I won't have to create a symlink at `/non/standard/php` to `/usr/bin/php` on my servers, because that feels fragile and hack-ish, but if there are no alternatives, it'll have to do.)

---

Drush 7.4.0

# Answer
From **example.aliases.drushrc.php**:

> Although most aliases will contain only a few options, a number of settings that are commonly used appear below:

...

> 'php': path to custom php interpreter. Windows support limited to Cygwin.

So try somtehing like:

```
$aliases['example'] = array(
  'uri' => 'example.com',
  'root' => '/var/www/example.com',
  'remote-host' => 'www.example.com',
  'remote-user' => 'user',
  'php' => '/path/to/php/on/the/server'
);

```

You could try that. If this doesn't work I would suggest to update your drush version (locally and on the server) and try again, before doing any strange symlinking on the server.
> 2 votes

---
Tags: drush
---


# Question
Title: Entity Browser Widget for Video Embed Media Entity
I have a few different Entity Browsers setup for uploading or selecting Media Entities on my Drupal 8.3.x site.

I have Image, Document & Video media bundles setup on the site.

The Image & Document providers include widgets to add to an Entity Browser.

Video bundle is setup via the video\_embed module through media\_entity module.

I can not find any documentation or method of adding an 'Add New Video' type of widget for Entity Browser – ie. A simple text field in which you paste in the URL of a Vimeo/Youtube video to create an entity for it.

My Video Entity is working fine on the standalone creation form.

I also have a View (Entity browser widget plugin) I'm using for selecting **Existing** videos on the site, and that works fine.

Are there any existing methods for an 'Add Video'

# Answer
I could not find any way to implement an 'Add New Video' widget to an Entity Browser.

There is a solution using Inline Entity Form. https://www.drupal.org/project/inline\_entity\_form

With Inline Entity Form, you can have an entity creation option, or add existing entity option. You can then use an Entity Browser for selecting existing entities, and leave the adding of new entities up to Inline Entity Form.

It's quite a clean User Interface / User Experience once implemented:
> 1 votes

# Answer
Amended Solution:

At the time of writing the question, for some unknown reason, the 'Entity Form' widget was unavailable from the Add Widget dropdown.

After a fair bit of work on other areas, the 'Entity Form' option is now available.

It's now fairly trivial to add a basic form for creating a single video:
> 1 votes

---
Tags: 8, entities, media
---


# Question
Title: How to change placement of block or region on events?
I want to change the placement of 2 regions based on window size. I know that I can print 2 blocks and use css `dipslay:none` based on window size, but I prefer not to double print a block.

Is there any way I can change the placement of blocks / regions based on events, such as screen size, using JS or similar?

# Answer
> 0 votes
You can use the flexbox order property: https://css-tricks.com/almanac/properties/o/order/

# Answer
> 0 votes
I managed to do this using js `$('#source').appendTo('#destination');` I'm not sure if this is the drupalish way to do it? But at least it works!

I found it from this page; https://stackoverflow.com/questions/1279957/how-to-move-an-element-into-another-element

---
Tags: theming, 8
---


title: orConditionGroup() - unexpected result

text:
# Question
Title: orConditionGroup() - unexpected result
```
$query = \Drupal::entityQuery('node');

$group = $query->orConditionGroup()
 ->condition('field_ref1_user.entity:user.uid', $user->id())
 ->condition('field_ref2_user.entity:user.uid', $user->id());

$ids = $query
 ->condition('status', 1)
 ->condition('type', 'mynodetype')
 ->condition($group)
 ->execute();

```

The first condition in $group met 3 nodes and the second condition met 1 additional node (different from 3 nodes of condition 1) so since it is OR condition I expect to get 4 node IDs but I receive only 3 node IDs that met the first $group condition.

If I switch the conditions within the $group, I get 1 node ID, that met the first condition. It's seems that the second condition in the group is ignored.

What is wrong with my code? Is there a way to see the query that actually executed?

**Edit** I have activated WebProfiler to see the actual query.

```
WHERE (node_field_data.status = '1') AND (node_field_data.type = 'mynodetype') AND ((users_field_data.uid = '11') or (users_field_data.uid = '11'))

```

These are 2 different user reference fields but for both of them the query checks `users_field_data.uid = '11'`

# Answer
I can't see any issues with your code, and this might be a dumb answer, but a while back I was having trouble with chaining together entity query conditions. I got everything working by splitting it into individual statements. It didn't seem logical that that should make a difference, but it did. (Though, I'm sure it's possible I had some other logical problem that was the actual issue, and separating into statements was just incidental.) But maybe try...

```
$group = $query->orConditionGroup();
$group->condition('field_ref1_user.entity:user.uid', $user->id());
$group->condition('field_ref2_user.entity:user.uid', $user->id());

$query->condition('status', 1);
$query->condition('type', 'mynodetype');
$query->condition($group);
$ids = $query->execute();

```
> 0 votes

# Answer
Meantime, until I get more elegant solution from community here, I will go for the following ugly but working solution

```
$query1 = \Drupal::entityQuery('node');
$ids1 = $query1
 ->condition('field_ref1_user.entity:user.uid', $user->id())
 ->condition('status', 1)
 ->condition('type', 'mynodetype')
 ->execute();

$query2 = \Drupal::entityQuery('node');
$ids2 = $query2
 ->condition('field_ref2_user.entity:user.uid', $user->id())
 ->condition('status', 1)
 ->condition('type', 'mynodetype')
 ->execute();

```

$ids1 and $ids2 arrays to be merged into $ids and then I will sort the $ids and remove duplicates
> 0 votes

---
Tags: 8, database
---


title: Get state list of a country

text:
# Question
Title: Get state list of a country
In drupal 8 we can get country list using following code.

```
$countries = \Drupal::service('country_manager')->getList();

```

But how can I programatically get the list of state of each country?

# Answer
Drupal core only keeps a record of countries, not all the states/administrative areas within each country.

However the CommerceGuys addressing library has that functionality. Example from their readme:

```
use CommerceGuys\Addressing\Subdivision\SubdivisionRepository;

$subdivisionRepository = new SubdivisionRepository();

// Get the subdivisions for Brazil.
$states = $subdivisionRepository->getAll(['BR']);
foreach ($states as $state) {
    $municipalities = $state->getChildren();
}

```

If need to get list of states as indexed array use the function 'getList()':

```
$states = $subdivisionRepository->getList(['BR']);

```

Then if you print the $states, you will get:

```
Array
(
    [AC] => Acre
    [AL] => Alagoas
    [AP] => AmapÃ¡
    [AM] => Amazonas
    [BA] => Bahia
    [CE] => CearÃ¡
    [DF] => Distrito Federal
    [ES] => EspÃrito Santo
    [GO] => GoiÃ¡s
    [MA] => MaranhÃ£o
    [MT] => Mato Grosso
    [MS] => Mato Grosso do Sul
    [MG] => Minas Gerais
    [PA] => ParÃ¡
    [PB] => ParaÃba
    [PR] => ParanÃ¡
    [PE] => Pernambuco
    [PI] => PiauÃ
    [RJ] => Rio de Janeiro
    [RN] => Rio Grande do Norte
    [RS] => Rio Grande do Sul
    [RO] => RondÃ´nia
    [RR] => Roraima
    [SC] => Santa Catarina
    [SP] => SÃ£o Paulo
    [SE] => Sergipe
    [TO] => Tocantins
)

```
> 7 votes

# Answer
The state list is not in drupal core. You need to get a feed from somewhere else.

Consider using the address module. This uses the commerce addressing library, providing you the state lists.
> 2 votes

---
Tags: 8, symfony-services
---


# Question
Title: Create taxonomy reference field programatically in Drupal 8
How to create taxonomy reference field programatically in a custom form?

```
$tags = array();// get taxonomy terms from a vocabulary.

$form['custom_tags'] = array(
  '#type' => 'select',
  '#options' => $tags,
  '#title' => $this->t('Preffered Tags'),
  '#default_value' => $this->store->get('custom_tags') ? $this->store->get('custom_tags') : '',
);

```

How can I get taxonomy terms from a vocabulary? Or how to create a term reference field in custom form?

# Answer
I did it by following method. If any other better way to achieve this, please suggest.

```
$tag_terms = \Drupal::entityManager()->getStorage('taxonomy_term')->loadTree('tags');
$tags = array();
foreach ($tag_terms as $tag_term) {
    $tags[$tag_term->tid] = $tag_term->name;
}

$form['custom_tags'] = array(
  '#type' => 'select',
  '#options' => $tags,
  '#title' => $this->t('Preffered Tags'),
  '#default_value' => $this->store->get('custom_tags') ? $this->store->get('custom_tags') : '',
);

```
> 2 votes

---
Tags: 8, forms
---


# Question
Title: Build a form dynamically with the results of a view?
I'm working on a view block in which I load several nodes.
I don't know how many nodes will be loaded because it depends on an exposed filter.
I have twig file for the display, I also have a twigExtension php file to call custom functions.

For example, the output of my view looks like this :

```
Reference
ABCD
BCDE
CDEF

```

I would like to get a form :

```
Reference | Quantity (Select dropdown)
ABCD | 0
BCDE | 1
CDEF | 0
<Submit Button>

```

Once the user clicks on the Submit Button, it creates 3 nodes of a Custom Content Type.

The lead I'm investigating for now is to use a form but I don't know how I could pass the results to this form, build it with these results and get something like :

```
public function buildForm(array $form, FormStateInterface $form_state) {
    $form['ref_1'] = array(
        '#type' => 'textfield',
        '#title' => t('Reference 1'),
        '#default_value' => 'ABCD'
        '#attributes' => array('readonly' => 'readonly')
    );
    $form['quantity_1'] = array(
        '#type' => 'select',
        '#title' => t('Quantity 1'),
        '#options' => array('00', '01', '02', '03'),
    );

    $form['ref_2'] = array(
        '#type' => 'textfield',
        '#title' => t('Reference 2'),
        '#default_value' => 'BCDE'
        '#attributes' => array('readonly' => 'readonly')
    );
    $form['quantity_2'] = array(
        '#type' => 'select',
        '#title' => t('Quantity 2'),
        '#options' => array('00', '01', '02', '03'),
    );

    $form['ref_3'] = array(
        '#type' => 'textfield',
        '#title' => t('Reference 3'),
        '#default_value' => 'CDEF'
        '#attributes' => array('readonly' => 'readonly')
    );
    $form['quantity_3'] = array(
        '#type' => 'select',
        '#title' => t('Quantity 3'),
        '#options' => array('00', '01', '02', '03'),
    );

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

    return $form;
}

```

Or maybe should I look at the exposed filter function, maybe is there a way to modify the way it works to call my own function before display ?

How would you do it ?

Thanks.

# Answer
Build the custom form from inside the view and attach it to the view before rendering:

*mymodule.module*

```
/**
 * Implements hook_views_pre_render().
 */
function mymodule_views_pre_render($view) {
  if ($view->id() == 'myview') {
    // get field values from the view result
    $values = [];
    foreach ($view->result as $row_id => $row) {
      foreach ($view->field as $field_id => $field ) {
        $values[$row_id][$field_id] = $field->getValue($row);
      }
    }
    // build form with the view result
    $form = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\MyForm', $values);
    // attach the form to the view
    $view->attachment_after = $form;
  }
}

```

Use the view result for building the form:

*/src/Form/MyForm.php*

```
class MyForm extends FormBase {

  public function buildForm(array $form, FormStateInterface $form_state, array $values = NULL) {
    // build form with $values
  }

```
> 0 votes

---
Tags: views, forms
---


# Question
Title: How do I display a taxonomy term, without a link, in a node template?
In learning, I've created a custom content type called story and a custom taxonomy called story\_category. In story I have a term reference for story\_category.

I can render a taxonomy term associated with a node however it automatically renders as a link to the URL alias instead of my custom taxonomy field.

How can I display a taxonomy term with no link?

My current result is the following.

>

These are the fields for the *Story* content up.

1. title
2. body
3. field\_impactful\_story
4. field\_related\_fund
5. field\_term\_reference
6. field\_summary

These are the fields for the **Story Category** vocabulary.

1. name
2. description
3. field\_story\_category\_link

This is my page--front.tpl.php template.

```
<main>
  <div class="container">
    <div class="row">
      <div class="col-sm-8">
        <?php // ------ impactful stories ------ // ?>
        <?php
          $impactfulStoriesQuery = new EntityFieldQuery();
          $impactfulStoriesQuery
            ->entityCondition( 'entity_type', 'node' )
            ->entityCondition( 'bundle', 'story' )
            ->propertyCondition( 'status', 1 )
            ->fieldCondition( 'field_impactful_story', 'value', 1, '=')
            ->propertyOrderBy( 'created', 'DESC' )
            ->range( 0, 2 );
          $impactfulStoriesQueryResults = $impactfulStoriesQuery->execute();
          if ( isset( $impactfulStoriesQueryResults[ 'node' ] ) ) {
            $impactfulStoriesNodeIDs = array_keys( $impactfulStoriesQueryResults[ 'node' ] );
            $impactfulStoriesNodes = node_load_multiple( $impactfulStoriesNodeIDs );
            $impactfulStories = node_view_multiple( $impactfulStoriesNodes, 'full' );
            print render( $impactfulStories );
          }
        ?>
        <?php // ------ end impactful stories ------ // ?>
      </div>
      <div class="col-sm-4">
        <p>Some other content</p>
      </div>
    </div>
  </div>
</main>

```

This is my node--story.tpl.php template.

```
<article class="story u-clearfix">
  <img class="story-image u-floatLeft" src="http://lorempixel.com/image_output/people-q-c-200-200-4.jpg" alt="">
  <div class="u-floatRight">
    <h3 class="story-title">
      <?php print render( $title ); ?>
    </h3>
    <p class="story-summary">
      <?php if ( $impactfulStorySummary ): ?>
        <?php print render( $impactfulStorySummary ); ?>
      <?php endif; ?>
    </p>
    <div class="story-meta u-clearfix">
      <?php if ( $impactfulStoryCategory ): ?>
        <?php if ( $impactfulStoryCategoryLink ): ?>
          <a class="u-floatLeft" href="<?php print render ( $impactfulStoryCategoryLink ); ?>">
            <?php print render ( $impactfulStoryCategory ); ?>
          </a>
        <?php endif; ?>
      <?php endif; ?>
      <?php if ( $impactfulStoryRelatedFund ): ?>
        <a class="u-floatRight" href="https://www.giveto.osu.edu/makeagift/?fund=<?php print render( $impactfulStoryRelatedFund ); ?>">
          Give
        </a>
      <?php endif; ?>
    </div>
  </div>
</article>

```

This is the template.php file for my theme.

```
<?php
  function osu_preprocess_node( &$variables ) {
    // ------ preprocess impactful story nodes ------ //
    if ( $variables[ 'node' ]->type == 'story' ) {

      // get summary for the story content type
      $summaryItem = field_get_items( 'node', $variables[ 'node' ], 'field_summary' );
      $summaryView = field_view_value( 'node', $variables[ 'node' ], 'field_summary', $summaryItem[ 0 ] );
      $variables[ 'impactfulStorySummary' ] = $summaryView;

      // get the taxonomy term associated with a particular story
      $categoryItem = field_get_items( 'node', $variables[ 'node' ], 'field_term_reference' );
      $categoryView = field_view_value( 'node', $variables[ 'node' ], 'field_term_reference', $categoryItem[ 0 ] );
      $variables[ 'impactfulStoryCategory' ] = $categoryView;

      // get the term id so we can get term.
      // once we have the term when can get a field of that term
      $categoryID = $categoryItem[ 0 ][ 'tid' ];
      $category = taxonomy_term_load( $categoryID );

      $categoryLinkItem = field_get_items( 'taxonomy_term', $category, 'field_story_category_link' );
      $categoryLinkView = field_view_value( 'taxonomy_term', $category, 'field_story_category_link', $categoryLinkItem[ 0 ] );
      $variables[ 'impactfulStoryCategoryLink' ] = $categoryLinkView;

      // get the related fund field associated with a story
      $item = field_get_items( 'node', $variables[ 'node' ], 'field_related_fund' );
      $view = field_view_value( 'node', $variables[ 'node' ], 'field_related_fund', $item[ 0 ] );
      $variables[ 'impactfulStoryRelatedFund' ] = $view;
    }
    // ------ end preprocess impactful story nodes ------ //
  }
?>

```

# Answer
It is considered best practice to keep your template files organized and simple by placing all complicated PHP logic inside of preprocess functions. This will make you happy when you revisit your code down the road. Try `hook_preprocess_page()` to pass your EntityFieldQuery results as a new variable to your page--front.tpl.php.

Try to preprocess the term via `template_preprocess_taxonomy_term()`; if that fails you could preprocess the field you are using to display your term via `template_preprocess_field()`.

If you just want to render the term as text you can visit the manage display tab when managing your content type and change the display formatted from link to plain text.
> 0 votes

# Answer
Under manage display you can uncheck link label to the reference entity
> 0 votes

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


# Question
Title: How to change the page path being reported to Google Analytics as a pageview
I would like a certain page path to be reported as a different page path, IF it has a hash on it.

```
/page-name#hash-name

```

should be reported as

```
/page-name/hash-name

```

Thing is that with the Google Analytics module I end up reporting two pageviews if I add this to custom js:

```
ga('send', 'pageview', '/pagename/' + window.location.hash.substr(1));

```

# Answer
> 0 votes
In the Google Analytics configuration (admin/config/system/google-analytics) under the collapsed fieldset "Advanced" \> "Custom JavaScript code" there is a field "Code snippet (before)" where you can add javascript (pure, no jQuery).

In this case I added the following:

```
if(window.location.pathname === '/pagename') {
  if(window.location.hash) {
    ga('set', 'page', '/pagename/' + window.location.hash.substr(1));
  }
}

```

Essentially any Google Analytics variable can be pre-set or changed before the pageview fires.

---
Tags: javascript, google-analytics
---


# Question
Title: Alternate page for mysql connection error
I have a drupal 7 site. Recently I changed my mysql password but forgot to update the settings.php file. My website showed **Cannot connect to mysql server** for 3 days before I noticed and changed the settings.php file. My question is

**Is there a way to display a custom HTML page (Like a maintenance page) when there is a mysql connection error ? Is there a module for that purpose ?**

# Answer
> 1 votes
Having a look in drupal\_bootstrap() for D7 it looks like hook\_boot comes after the database "phase" so you'd need to put something in the cache phase or the configuration phase if you want to trigger a redirect before Drupal tries to bootstrap the database.

Easiest way would probably be to attempt to open a connection to the database yourself near the bottom of settings.php with the connection string defined earlier in settings.php and then if you detect a fail adapt this approach for "fast 404 pages" - http://2bits.com/drupal-planet/reducing-server-resource-utilization-busy-sites-implementing-fast-404s-drupal.html

You could print some html straight to the screen and exit().

# Answer
> 1 votes
As per David Meister's answer I've posted the code below for those who are new to Drupal. Copy and paste it at the bottom of the settings.php file. I know this is not a very elegant code but it gets the job done. If you have a better code please post your answer below.

```
$mysqli = new mysqli($databases['default']['default']['host'],$databases['default']['default']['username'],$databases['default']['default']['password'],$databases['default']['default']['database']);

    if (mysqli_connect_error()) {
     echo "Your HTML here";
     exit();
    }

```

# Answer
> 0 votes
I have added this code in settings.php and working fine.

```
try {
  require_once DRUPAL_ROOT . '/includes/database/database.inc';
  Database::getConnection();
}
  catch (Exception $e) {
  header("Location: $base_url/YOUR_HTML_PAGE.html");
  die;
}

```

---
Tags: 7
---


title: Use Chart.js in Drupal page

text:
# Question
Title: Use Chart.js in Drupal page
I am new to Drupal. I created a page and I want to embed charts in that page. I am trying to use chart.js and I have question regarding how to import the script of chart.js in the page i created?

is it like this

```
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.min.js"></script>

```

or some other way to do it? I also dont understand how you add javascript code to a drupal page. Thank you.

# Answer
> 1 votes
You need to define it in either a module, or the libraries.yml file of your theme. Then you need to attach it to the page. See the "CDN / externally hosted libraries" of this doc page:

https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module

Then you need to attach the library - this is fairly straightforward in mytheme.theme.

Example `mytheme.theme` file:

```
function mytheme_page_attachments(array &$attachments) {
  $attachments['#attached']['library'][] = 'mytheme/chartjs';
}

```

---
Tags: javascript
---


# Question
Title: How can I add markup to a link in node links?
I am trying to add some markup around the number of comments link in the standard node links. I want to do this so I can theme the number of comments as a little comment bubble and hide the text (possibly only on mobile).

I can get this far:

```
function mytheme_preprocess_links__node(&$variables) {

 if (isset($variables['links']['comment-comments'])) {
    $title = $variables['links']['comment-comments']['text'];
    $count = 7 // need to get the actual count in here.

    $variables['links']['comment-comments']['link']["#title"] = \Drupal::translation()->formatPlural($count, ''<span class="comment-count">1</span> <span class="comment-text">comment</span>', '<span class="commment-count">@count</span> <span class="comment-text">comments</span>');
  }
}

```

When I dsm the $title variable I can see that the comment count is in there, I just can't figure out how to get it out into the $count variable. Any help?

# Answer
> 3 votes
Unfortunately the object `PluralTranslatableMarkup` has no method to get the protected value `count`. The serialization was fixed to provide the count value, see issue https://www.drupal.org/node/2844181, but the class is still missing it's own `getArguments()` to extend it with the count value. You could file an issue and wait for a fix or use this work around with reflection:

```
  if ($title instanceof \Drupal\Core\StringTranslation\PluralTranslatableMarkup) {
    $reflection = new ReflectionClass($title);
    $property = $reflection->getProperty('count');
    $property->setAccessible(TRUE);
    $count = $property->getValue($title);
  }

```

---
Tags: theming, 8
---


# Question
Title: Migrate only taxonomy terms from a specific vocabulary
When doing a D7-\>8 migration, my taxonomy term migration template imports all the taxonomy terms found in the source D7 site. How to filter only the terms that belong to a specific vocabulary? For a node, I simply said:

```
source:
 plugin: d7_node
 node_type: article

```

But for terms? Is there something similar?

```
source:
 plugin: d7_taxonomy_term
 ????

```

Thanks in advance!

# Answer
```
source:
  plugin: d7_taxonomy_term
  bundle: tags

```
> 1 votes

---
Tags: taxonomy-terms, migrations
---


# Question
Title: How do I disable the "Review step" page?
I do not want to show the *Review step* page which comes after the *Cart* page. Is there any way to disable/skip that page?

# Answer
> 1 votes
Just remove any checkout panes from it in the checkout form configuration.

---
Tags: 7, commerce
---


title: How do I display two blocks separately?

text:
# Question
Title: How do I display two blocks separately?
In my header region, I have two blocks: menu and search. I want to add some other HTML between them. I tried using `{{ content.menu}}`, but it doesn't actually do return anything.

I can split up the content with `{{ content.field_type }}`, but this approach doesn't seem to be working in region.html.twig.

# Answer
> 3 votes
Never mind! By using `{{ dump() }}` I was able to see that I can get the individual blocks by using:

```
{{ elements.search }}

{{ elements.menu }}

```

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


# Question
Title: How to select sub-terms in taxonomy when creating content?
In creating a document management system I've created a taxonomy vocabulary with this structure:

```
Accounting
  Client 1
  Client 2
Client 1
  Contacts
Client 2
  Contacts
  Correspondance
Leasing
  Client 1
  Client 2

```

Then, in my Document content type I've created a term reference field called Tags which uses autocomplete. The autocomplete part works great, but I don't know how to differentiate Accounting:Client 1 from Leasing:Client 1 from Client 1 (parent level). When loading a new document, is there a way to reference these terms properly?

# Answer
Simple Hierarchical Select is the module for the job.

> Simple hierarchical select defines a new form widget for taxonomy fields to select a term by "browsing" through the vocabularies hierarchy.

Just change the widget-type of field **Tags** to **"Simple hierarchical select"** after you install the module. This guide might come handy if you're running 7.
> 1 votes

# Answer
You can try using multilevel autocomplete module. If that help you.
> 0 votes

---
Tags: taxonomy-terms, entities
---


title: Add a canvas form element

text:
# Question
Title: Add a canvas form element
I am developing a module and I have this HTML markup.

```
<canvas id="cnv" name="cnv" width="500" height="100"></canvas>

```

I want to add it in a form. Looking at the Form API reference documentation page, I don't see any canvas form element.

What should I instead use?

# Answer
> 0 votes
The form api does not support every tag in HTML. For special cases use a form key of `#markup` to embed raw HTML. Scan the form APIs for that keyword for examples.

# Answer
> 1 votes
This document page might help you.

Here is a sample code that I wrote to create a canvas in my form in Drupal 8.

```
$form['canvas']=array(
      '#type' => 'html_tag',
      '#tag' => 'canvas',
      '#attributes' => array(
                    'style'=>'border: 1px solid #000000;
                              width: 200;
                              height: 100;'
                            ),
      );

```

---
Tags: 7, forms
---


title: Image style generating hook

text:
# Question
Title: Image style generating hook
I'm using Drupal 7. Is there a hook for generating image from image style? For example. I upload an image. When image is displayed for the first time, drupal generates image style. Can I hook to that event somehow?

# Answer
> 2 votes
The image style hooks are documented here:

http://api.drupal.org/api/drupal/modules%21image%21image.api.php/7

* hook\_image\_default\_styles: Provide module-based image styles for reuse throughout Drupal.
* hook\_image\_effect\_info: Define information about image effects provided by a module.
* hook\_image\_effect\_info\_alter: Alter the information provided in
* hook\_image\_effect\_info.
* hook\_image\_styles\_alter: Modify any image styles provided by other modules or the user.
* hook\_image\_style\_delete: Respond to image style deletion.
* hook\_image\_style\_flush: Respond to image style flushing.
* hook\_image\_style\_save: Respond to image style updating.

Nothing for the actual image generation process, if that's what you're looking for.

See image\_style\_deliver for the details on the image generation

# Answer
> 1 votes
You can define any number of custom image styles (presets). You can then call an image to be embedded using a specific image\_style with theme\_image\_style

# Answer
> 0 votes
Hooking your own code into the image derivative generation, image link generation and menu routing is very difficult. In the imagecache\_actions contrib module we have had a lot of questions about it. I think that comments 12, 13 and 14 of issue "Change file format :: Doesn't change the file extension" best answer what can be done and what trouble you will probably run into.

---
Tags: 7, media
---


# Question
Title: Why field is double when I print it in node.tpl.php
I have a issue. I created a field in "content types \> article". Then I went to node.tpl.php and added next code:

```
<?php print render($content['field_like']); ?>

```

after that, I cleared cache and saw double field in my article. I tried to hide this field in "manage display" but it didn't successful, my field disappeared at all.

I just want to render my field in a certain place in the node.tpl.php

# Answer
Try wrapping the field in the hide function.

```
hide($content['field_like']);

```

Do this after you have output your field but before you call render($content).

see https://api.drupal.org/api/drupal/includes%21common.inc/function/hide/7.x
> 1 votes

---
Tags: 7, theming, entities
---


# Question
Title: How do I pass parameters from a form redirect to a controller?
I feel like it should be easier to find this stuff out. I'm trying to pass some data from a form submission to a controller, and do something based on that data. What is the most *Drupal* way to do this (i.e. without accessing the request object directly)?

The form in a custom module that extends `FormBase` has this method.

```
public function submitForm(array &$form, FormStateInterface $form_state) {
    $var_to_send = $form_state->getValue('val_to_get');
    $form_state->setRedirect('my.route', [ 'sent_var' => $var_to_send ]);
}

```

In this case, my.route is configured like this.

```
my.route:
  ...
  defaults:
    _controller: '\Drupal\custom_module\Controller\MyController::index'
    ...

```

I have the following method in \Drupal\custom\_module\Controller\MyController.php.

```
public function index() {
    $params = \Drupal::request()->query->all();
    $this->myfunc($params['sent_var']);
}

```

This page says that what I'm doing is highly discouraged. So how should I access URL parameters in a controller?

# Answer
In a route callback like a controller you can pull the request with a typed function parameter:

```
use Symfony\Component\HttpFoundation\Request;

  public function index(Request $request) {
    $query_parameters = $request->query->all();

  }

```
> 3 votes

---
Tags: forms, redirection, page-controller
---


title: Redirect based on query string

text:
# Question
Title: Redirect based on query string
I'm migrating a legacy blog from a home-grown CMS to Drupal 7 and I need to wrap my head around how I'm going to redirect URLS to a new aliased pattern.

The legacy site's URLs use query strings `/?t=40&an=49187&anc=570&format=xml` which then redirect to an aliased url like `/blog/i-know-this-is-not-ideal`. Most of the listing pages on the site use the query parameters to link to pages, though others use the aliased urls. The `an` parameter appears to refer to their version of a Node ID, which I'm able to parse and store in my migration.

The company who owns this platform was kind enough to sent me an Excel spreadsheet with aliases in one column and query strings in another — so I have something at least.

Maintaining SEO juice is critical for this client — and Google has parsed these query parameters in many cases.

Should I look towards writing a custom module for this, as the Redirect module appears not to provide support for query parameters? Or should I look into htaccess rewrite rules?

# Answer
> 3 votes
I think a small custom module will probably be the method with the least overhead. You could store the legacy ID in a field during the migration and access it from there if the appropriate query string is set.

Very rough examples...

**Drupal 7:**

mymodule.module

```
function mymodule_init() {
    if (!empty($_GET['an'])) {
        $query = new \EntityFieldQuery();
        $result = $query->entityCondition('entity_type', 'node')
            ->fieldCondition('field_old_id', 'value', $_GET['an'])
            ->execute();

        if (!empty($result['node'])) {
            $nids = array_keys($result['node']);
            $nid = reset($nids);
            drupal_goto(url("node/$nid"), [], 301);
        }

    }
}

```

**Drupal 8:**

mymodule.services.yml:

```
services:
  mymodule.redirect_subscriber:
    class: Drupal\mymodule\RedirectSubscriber
    arguments: ['@entity_type.manager', '@path.alias_manager']
    tags:
      - { name: 'event_subscriber' }

```

src/RedirectSubscriber.php:

```
namespace Drupal\mymodule;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Path\AliasManagerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class RedirectSubscriber implements EventSubscriberInterface
{

    protected $nodeStorage;

    protected $aliasManager;

    public function __construct(EntityTypeManagerInterface $entity_type_manager, AliasManagerInterface $alias_manager)
    {
        $this->nodeStorage = $entity_type_manager->getStorage('node');
        $this->aliasManager = $alias_manager;
    }

    public function Redirect(GetResponseEvent $event)
    {
        $old_id = $event->getRequest()->get('an');

        if (!empty($old_id)) {
            $ids = $this->nodeStorage->getQuery()
                ->condition('field_old_id', intval($old_id))
                ->execute();

            if (!empty($ids)) {
                $nid = reset($ids);
                $url = $this->aliasManager->getAliasByPath("/node/$nid");
                $event->setResponse(new RedirectResponse($url, 301));
            }
        }
    }

    static function getSubscribedEvents()
    {
        $events[KernelEvents::REQUEST][] = array('Redirect', 20);
        return $events;
    }
}

```

---
Tags: redirection, uri
---


# Question
Title: Where are the content types stored in the database?
In Drupal 7 with this query:

```
SELECT * FROM node_type;

```

I can obtain the list of all my content types, now in Drupal 8 I can't find the `node_type` table.

I know that with this code:

```
$content_types = \Drupal::service('entity.manager')->getStorage('node_type')->loadMultiple();

$content_types_list = [];
foreach ($content_types as $content_type) {
  $content_types_list[$content_type->id()] = $content_type->label();
}

```

I can obtain the info, but where is this information stored now in the database?

# Answer
It's configuration. Like any other config entity and simple configuration, it is stored in the {config} table.

But using the entity API is the only supported way to load that information, do not query that table directly.
> 6 votes

# Answer
As answered earlier, it is stored in the {config} table. To be more specific:

* If the machine name for a content type is "blogpost", there will be a record in the {config} table with name="node.type.blogpost".
* The data field will contain a PHP serialized array with the configuration details of the content type. This must be reasonably valid in order for the content type to be listed on the /admin/structure/types page.
* If you create a content type via the UI, it will also create the following {config} records (though these are not necessary to be listed on the /admin/structure/types page):
    + core.entity\_form\_display.node.{type}.default
    + core.entity\_view\_display.node.{type}.default
    + core.entity\_view\_display.node.{type}.teaser
    + field.field.node.{type}.body

For writing production code, I would echo the earlier recommendation not to directly query the {config} table. However, using these details to query the table could be helpful for things like debugging a failed migration.
> 1 votes

---
Tags: 8, database
---


title: How do I crop only height?

text:
# Question
Title: How do I crop only height?
I want to crop an image that is anchored at the center, but only crop the height. How can this be done in Drupal 7?

EDIT: The process needs to be automated. Basically I desire the functionality of the existing crop process for an image style, but without the requirement for having to enter a value for both width and height.

EDIT #2: The width needs to be variable :)

# Answer
> 2 votes
You'll have to use custom GD methods I think.

Have a look at this module : https://drupal.org/project/imagecache\_actions

With the embed "Custom Actions" module you'll be able to use any gd method you want.

Add a custom filter to an image filter, and find the gd function to use.

In example, to get a B&W picture, the php code to use is :

```
return imagefilter($image->resource, IMG_FILTER_GRAYSCALE);

```

# Answer
> 2 votes
Just came across this, and I had a similar issue: crop an image to a fixed height, but leave the width untouched.

ImageCache Actions has a "Define Canvas" option that can take a percentage for one axis ("100% width") and a pixel measurement ("450px") for the other.

I was all set to dig in and monkey with the "Custom Actions" module when I stumbled across "Define Canvas".

# Answer
> 1 votes
I had the same problem today, and luckily found the Image max size crop module.

> This module adds an image-style which crops an image when the image dimensions are larger then the given dimensions.
>
> In contrary to the core image style crop only one dimension is required.

In my own tests it does work as advertised. Although more accurate would be:

* ... adds an "image effect", not an "image-style".

---
Tags: 7, media
---