# Question
Title: Show contact form in a pop-up window with Bootstrap classes
Can you please tell us how to create a modal window with a contact form, with the bootstrap classes?

I open the form with

```
<a class="use-ajax" data-dialog-options="{ "width":633 }" data-dialog-type="modal" href="/node">Open form</a>

```

And why is the modal window not working for anonyms? Thank you!

**UPD**

Happened!

Connected via theme, at the root of the theme there is a file **my-theme.libraries.yml** in it, we develop a library

```
drupal.dialog.ajax:
  version: VERSION
  js:
    /core/misc/dialog/dialog.ajax.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupalSettings
    - core/drupal.ajax
    - core/drupal.dialog

```

Followed by the root theme in the file **my-theme.theme** Insert function

```
function my-theme_preprocess_page(&$variables) {
    $variables['#attached']['library'][] = 'my-theme/drupal.dialog.ajax';
}

```

# Answer
> 1 votes
Bootstrap and Ajax are two different methods for modal dialogs.

If you want to open a popup with Bootstrap this would be client side. This means you deliver the form embedded in the page as a block and hide it by wrapping it in a Bootstrap modal container:

https://v4-alpha.getbootstrap.com/components/modal/

If you want to load a modal with Drupal Ajax, then use the link you've provided in the question, but target the url of the form, not that of the frontpage:

```
<a class="use-ajax" data-dialog-type="modal" href="/contact">Open form</a>

```

For this to work you have to attach a js library:

```
$build['#attached']['library'][] = 'core/drupal.dialog.ajax';

```

> And why is the modal window not working for anonyms?

It works for logged in users without attaching the library, because core code is doing this already for the admin dialogs.

---
Tags: 8
---


title: Admin menu issue with the modules tab

text:
# Question
Title: Admin menu issue with the modules tab
I am using drupal 7, and i have a problem with the modules.The problem is when I login as an administrator i cant enter to the modules tab in the admin menu. there is a message say "500 - Internal server error. There is a problem with the resource you are looking for, and it cannot be displayed." how can i enable a specific module?and how i fix this issue?

Thanks for your cooperation.

# Answer
> 0 votes
500 Internal server error is normally at Server level. To fix this, you'll first need to check is the actual error which you can check either **Drupal Logs** (located at "Admin =\> Reports =\> Recent Log message") or **Apache error log** (located at "/var/log" in Linux OS).

---
Tags: 7
---


# Question
Title: How to get the view count of taxonomy term pages in Drupal 8?
I'm running Drupal 8.3. Statistics module can count views of a node. But is there a way to find out view count of taxonomy term pages?

I'm looking for how many times a taxonomy term page is viewed, but not the count of how many times a taxonomy term is used in nodes.

**Edit:** In short, I'm looking for a similar module as below for Drupal 8. https://www.drupal.org/project/taxonomy\_term\_statistics

# Answer
> 0 votes
I found a Drupal patch for Statistics module, which tracks view count for all content entities. It seems like this feature will be integrated into the core.

After applying the patch, I can track view counts for taxonomy term pages.

Link to the patch: https://www.drupal.org/node/2532334

---
Tags: 8, nodes
---


title: Views block visibility

text:
# Question
Title: Views block visibility
I want to show the block only on this page `/category` and not show on every next like `/category?page=1`

As I see it's a big problem for Drupal 8?

# Answer
You can set the visibility of a block in the block page (admin/structure/block). In the visibility tab select 'Show for the listed pages' and in the 'Pages' just add /category. Use /category/\* to display the block in all the pages.
> 1 votes

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


# Question
Title: Why does YAML parser strippes out underscore?
In my Drupal project I have a yaml configuration file which contains an id with the value `16_9` (more precisely it is part of the Crop module configuration). When checking differences between the active Drupal configuration and this staged one, Drupal lists this config, although it should be identical:

As you can see, the YAML parser processes the id as an integer and stripes out the underscore.

This problem only exists in my Drupal-VM. In our testing and production environment (non Drupal-VM) with the identical code and data base the config sync is fine. It does not show any differences.

There might be different YAML parser (and/or extensions) in use which behave not the same way. But I don't know if this is a Drupal or VM issue. I don't think that it is specific to the Crop Module.

### My Environment

Vagrant 1.9.2
VirtualBox .1.18 r114002 (Qt5.6.2)
Drupal VM 4.5.0 (with Ubuntu)

# Answer
> 5 votes
It's actually a native YAML issue. As Saltstack's YAML Inconsistencies page observes:

> If a definition only includes numbers and underscores, it is parsed by YAML as an integer and all underscores are stripped. To ensure the object becomes a string, it should be surrounded by quotes.

It's fairly common practice; Java does it too, for example

So wrap your ID in quotes and it should be fine.

---
Tags: 8
---


# Question
Title: How do I properly delete a field collection?
I added a new field (*houses*) to user accounts. This field is a list of a collection fields.

I need to list all the fields in a user field collection (I can via the `FieldCollectionItem::loadMultiple(array(12,45,...)`) and remove all of them.

This is my code:

```
$array_of_fieldcollection = get_array_of_fieldcollection_of_user();

$fieldscollection = FieldCollectionItem::loadMultiple($array_of_fieldcollection);

foreach($fieldscollection as $fieldcollection){
  $fieldcollection->delete();
}

```

When I execute it and go to the user profile edit page, I get this error:

> The website encountered an unexpected error. Please try again later.
> More detail in the Apache log.
>
> TypeError: Argument 1 passed to Drupal\Core\Entity\Entity\EntityFormDisplay::buildForm() must implement interface Drupal\Core\Entity\FieldableEntityInterface, null given, called in /var/www/www.orlengine.com/modules/contrib/old\_field\_collection/src/Plugin/Field/FieldWidget/FieldCollectionEmbedWidget.php on line 71 in drupaldirectory/core/lib/Drupal/Core/Entity/Entity/EntityFormDisplay.php on line 159, referer: https://192.168.1.45/user/9

Isn't my code the proper way to delete all the field of a field collection?

# Answer
The code you've shared is correct. The problem is that when we attach a Field Collection field to "**User**" entity the Host Entity of Field Collection is not set.

Because of which when we delete a Field Collection Entity programmatically the Host Entity field value (i.e. User in this case) is not updated with deletion. This causes Drupal to load Field collection which doesn't exists in system.

Rewriting the deletion code below:

```
use Drupal\field_collection\Entity\FieldCollectionItem;

// Load all field collections to delete.
$field_collections = FieldCollectionItem::loadMultiple(array(1, 2));
foreach($field_collections as $field_collection){
  // Delete field collection.
  $field_collection->delete();
}

```
> 4 votes

# Answer
I encountered the same error when deleting `field collection items` on `User` entities. Below some code to unset the field manually on the `User` entity.

```
$id = 'Your FC field id';
$field = 'Your FC field name';

public function getFieldDelta($id, $field) {
  $fields = $this->get($field);

  foreach ($fields as $delta => $item) {
    if ($item->value == $id) {
      return $delta;
    }

  }
}

$delta = $this->getFieldDelta($id, $field);
unset($user->$field[$delta]);
$user->save();

```

The code sample above has a function `getFieldDelta()` that returns the delta of a field collection item if the provided item id matches one in the fields. With the delta the item in the user field is unset.
> 0 votes

---
Tags: users, 8, entities
---


# Question
Title: Views Pager, Can I change Items per page dynamically as provided input?
Is it possible to send `Items per page` limit in query string of view page url and get records according to that?

# Answer
I think this might help. I normally use hook\_views\_query\_alter in order to alter my view results.
> 0 votes

---
Tags: 7, views, paging
---


title: Google CSE autocomplete setup

text:
# Question
Title: Google CSE autocomplete setup
I'm new to using Google search on local website installations.

I have successfully installed the Google-CSE module and upon searching, results are successfully displayed from Google.

**However, my problem is there are no auto-suggestions when a user begins typing content into the search textfield.**

Can anyone tell me how to configure my Drupal textfield to show auto-suggestions when input is typed, please?

PS:

My Google site index has autocomplete enabled.

# Answer
The solution I used was to copy the **scripts/autocomplete.js** folder from Googles' **GSS** module into a custom module, include the autocomplete.js in *mymodule.info* and imitate the few lines of code in GSS.module which implements the autocomplete functionality.

If you ask me, Google left the CSE unfinished.
> 0 votes

---
Tags: search
---


# Question
Title: How do I add the JavaScript src file inside a block?
I have called the JavaScript source code, `<script scr=""></script>`, inside a block. And this code is working fine.

But I am not sure whether it's good practice or not.

If it's not a good practice, give me some suggestions for adding above code inside the block.

# Answer
> 3 votes
You should add javascript as a library, then attach it to your block in the build array or a preprocess function like this:

```
$block['#attached']['library'][] = 'mymodule/mymodule.search_filters';
$block['#attached']['drupalSettings']['mymodule'] = [
  'cats' => 'tabby',
  'dogs' => 'dalmation',
];

```

---
Tags: javascript, blocks
---


# Question
Title: Send Registration Emails To Non-Administrator role / Rules Data Selector By Role
I'm about to lose it here so hopefully someone here can help me.

I'm working in D8 and I would like to allow users of a certain role (Managers) administrate new site users. There is a permission for that and it works fine, but I can't find a way to send an email to users of the Managers role. It seems that they will only send to the Administrator account (me).

Some people online suggested that I might use Rules to get this to work for me, but this has made things even more confusing. I started down the path with the event being "After saving new user". I click "Add Action" and pick "Send Email". Some screenshots have shown me that in previous versions there might be a "Send Email to Role" option, but that's gone here for some reason.

I'm now at a "Send To" field, which can use the Data Selector. I can't quite use the Data Selector to get to a role. I can choose "user.role" or "user.roles", but then the autocomplete kind of gives up on me. "user.roles" will start giving me numbers after or "entity", but nothing gets me to sending an email to all users with a specific role.

Does anyone know how to get this to work? I'm not married to the Rules module. It just seemed to be the only option because Drupal won't send the default emails to anyone that isn't Account 1.

# Answer
> 0 votes
I highly recommend you don't do this, but if you put the following code into a file rules/src/Plugin/RulesAction/SystemSendEmailToRole.php then it'll give you a new action where you can enter the machine name of the role you want to send to (e.g. "myadmins") and it'll do what you want (I tested it, it works though no money back & no guarantee!):

https://gist.github.com/stevepurkiss/9b36eb79311d16c65e8d4d0ba9f1854b

All I did was copy the send email action, swap the 'to' string field to 'role', then load up all user ids with that role, foreach loop through them and insert their email address one by one as it loops through.

Looks like it could be extended to cope with multiple roles like the original code copes with multiple email addresses but this is the best you get in the half hour since I saw your post, and for free ;)

Of course it'll break if you update rules, there's no guarantees, but I did a bit of Rules 7-\>8 upgrading actions a couple of years back so know my way around a little. Not a lot, but a little ;)

Please also consider supporting rules too, this stuff doesn't appear from thin air, it's a collaboration!

HTH

Steve

# Answer
> 0 votes
I managed to solve this with hook\_mail\_alter rather than using Rules. For posterity, here's my code:

```
function ptapp_mail_alter(&$message) {

  if($message['id'] == 'user_register_pending_approval_admin') {

    $query = \Drupal::entityQuery('user')
      ->condition('status', 1);

    $group = $query->orConditionGroup()
    ->condition('roles', 'manager')
    ->condition('roles', 'administrator');

    $ids = $query->condition($group)->execute();
    $users = User::loadMultiple($ids);

    foreach($users as $u) {
      $message['to'] .= ', '.$u->getEmail();
    }
  }
}

```

---
Tags: users, rules, emails
---


title: How to access fields in a view template

text:
# Question
Title: How to access fields in a view template
so, I really got stuck. I did a lot of discussion in the IRC and reading but I just fail at it. It should be very easy since it's very simple.

I have a content-type "foo" and I use a view (as a block) to query them from the DB. Now, I'd like to create HTML in one big template. Currently, I created a node template for that content-type and a view template but this doesn't allow to build proper html, instead it forces me to use rather ugly html since it just passes the html created in the node template to my view template.

What I need is to mix the HTML. E.g. if my content-type has the fields "field1, field2, field3" and 3 items, then I'd like to create a html like this:

```
<div>
   item1-field1
   item2-field1
   item3-field1
</div>
<div>
   item1-field2
   item2-field2
   item3-field2
</div>
<div>
   item1-field3
   item2-field3
   item3-field3
</div>

```

so how can I do that? How can I access all items and their fields within a view template? I'd like to have full control over the rendered html of the block. I'm on D7.

# Answer
> 0 votes
There are a couple ways you can do this. The easiest way and probably the way you will end up doing it is in your view you need to change the format to a table and then output as fields. It sounds like you are outputting a rendered entity instead of the fields. Then under theme information you will see the available templates that you can overwrite.

The one you will want is under Style. Notice the naming convention. For a view named test and a block the view would be views-view-table--test--block-1.tpl.php.  Create this template and put it into your theme folder and clear your cache. Inside that template you have access to the $rows variable that will contain all of your output.

```
<?php
dpm($rows); // If you have devel module enabled see your rows;
?>

```

This should then allow you to style your HTML as needed.

I would advise against this unless you have a special need. A better way to do this would be to use Display Suite in which you can create your own view mode and manage the fields like that. I wont go into detail on how to do that but research would be good to see if it is a good way to go for you.

---
Tags: views
---


title: How do I attach new images to a node?

text:
# Question
Title: How do I attach new images to a node?
Will try to be brief.

I have a node with "n" images asigned to it, now i want to add new images (and keep the currents) to the node, i've tried this but no success until now. The next code does nothing:

```
$node = Node::load($node_id);
$node->field_car_picture[] = $new_images;
$node->save();

```

Also tried this and removes the current pictures and leave only the new images:

```
$node = Node::load($node_id);
$node->field_car_picture->setValue($new_images);
$node->save();

```

Any help will be appreciated

# Answer
You can try to merge the existing field items array and the new one, but I would use a loop to add one image at a time:

```
$node = Node::load($node_id);
foreach ($new_images as $new_image) {
  $node->field_car_picture[] = $new_image;
}
$node->save();

```

If you want to merge the arrays get the existing one

```
$existing_images = $node->field_car_picture->getValue();

```

combine it with the new array and replace the fields content with it.
> 2 votes

---
Tags: nodes, media
---


# Question
Title: hook_image_effect_info_alter() doesn't change effect callback
I'm trying to patch the image effect from the Kraken module. I'm doing so by using hook\_image\_effect\_info\_alter() to point the 'effect callback' to my patched function, like this:

```
function patch_image_effect_info_alter(&$effects) {
  $effects['kraken_optimize']['effect callback'] = 'patch_kraken_optimize';
  watchdog('patch_kraken', print_r($effects, TRUE)); // logging for debug
}

```

The problem is that this the hook doesn't seem to really change the effect defined on the Kraken module. Even though I'm getting the log message I defined in the hook with the updated *effect callback*, the original Kraken module effect is still being applied.

Am I using this hook the right way?

# Answer
> 0 votes
I found the issue.

It turns out there was another custom module "restoring" the original callback.

---
Tags: 7, media
---


title: blank page with views for mobile app

text:
# Question
Title: blank page with views for mobile app
We are building an app. Tried DrupalGap but not going to work with our host. I need a page that is just a view, for example one that only shows our news items or our cartoons. But no header and no sidebar. We'll need to make a bunch so that we can set them up on the app. If we use the url for our news, then we get the header and sidebar. We made views pages for all our content, but that url also comes up with header and sidebar.

Our rss is fine for newsletter, but really not attractive for an app.

We downloaded the blank page project, but that seems to want to be a home page only, and we need a bunch of them, not at all related to our site, but downloading content from our site.

Hmmmm. Any ideas?

https://thegreeneconomy.com/app-news

# Answer
In your theme directory, look for a file named views-view.html.twig Create a new file, `views-view--yourviewmachinename.html.twig`.

Render your data as you like. Unless you specifically mention it to load base elements, it won't load them.

These articles might help : http://redcrackle.com/blog/drupal-8/theme-views-templates https://www.drupal.org/docs/8/theming
> 0 votes

---
Tags: views, theming
---


title: Drupal Commerce Extra Login required

text:
# Question
Title: Drupal Commerce Extra Login required
I've enabled the Commerce Extra Login module and the login form now now appears when an anonymous or a user who is not yet logged in checks out.

Is there a settings which will make login required before a user can continue through the checkout process? I don't want users continuing without logging in or creating an account.

# Answer
I needed the same thing and couldn't get Commerce Extra Login to do it.

Fortunately, there's Commerce Checkout Redirect which does the trick:

> This module redirects anonymous users to a page where they can login or create a new account when they try to checkout. After the user logs in or registers, he is redirected to the checkout in order to finalize his order.
> 1 votes

# Answer
To fix that just comment out the if statement:

```
if (!empty($username) && !empty($password)) {

```

on

```
function commerce_extra_login_page_login_pane_checkout_form_validate

```
> 0 votes

---
Tags: commerce, users
---


title: State: are they permanent?

text:
# Question
Title: State: are they permanent?
I'm using StateAPI to store some variables that shouldn't be exported as configurations.

These values are stored in the database, in the *key\_value* table.

Is this a "secure" table? Are there tasks (cache-clear or other) that could automatically remove values from this table?

Is it a good idea to create a custom form to let users to set some states? They could be simple strings, or url, and I think that create nodes for this information is too "heavy".

# Answer
> Is this a "secure" table?

Depends on what you mean by secure.

> Are there tasks (cache-clear or other) that could automatically remove values from this table?

No.

> Is it a good idea to create a custom form to let users to set some states?

This is kind of looking at it from the wrong direction. States are a solution to an issue. If you have something that is to be stored, for which states are a good solution, then they are good to use. In other words, if you have a form that does something that states would be good for, then use states. Deciding to use states then creating forms for them doesn't really make sense.
> 4 votes

# Answer
The state service is never used to store data that is edited by users; it is used to store data necessary for a module the module doesn't expose to users through a form for its settings.
The classic example of using the state service is storing the last time cron tasks have been executed, or the last time a feed has been checked. Those values aren't exposed to users (even the users with a specific permission), and users don't have the possibility to reset those values. They are values required from a site to work, but they aren't imported and exported to a different site.

As for the difference between content and configuration, I would follow this simple rule: If you are storing information about your site that doesn't change so frequently, then it is probably configuration; if then it's information a *site editor* role would want to edit, then it's content.

To answer your question, no: The information stored with the *state* service is not automatically deleted after X minutes are passed.
> 1 votes

---
Tags: 8
---


# Question
Title: How do I set up a default value for a text field?
I am trying to setup a default value according to drupal API (http://take.ms/sSbow) in case if the form is empty (before use filled any data) and not successful. In hook\_form\_alter() I already added the code via `$form['#info']['filter-field_geoaddress_proximity']['label'] = t('Distance');` and it works well. Hovewer if I try like these

```
$form['#info']['filter-field_geoaddress_proximity']['value']['#default_value'] = 21;
$form['field_geoaddress_proximity']['widget'][0]['value']['#default_value'] = 21;

```

nothing happens.

This my debug info:

```
Array
(
    [operator] => field_geoaddress_proximity_op
    [value] => 2ield_geoaddress_proximity
    [label] => Drupal\Core\StringTranslation\TranslatableMarkup Object
        (
            [string:protected] => Distance
            [translatedMarkup:protected] =>
            [options:protected] => Array
                (
                )

            [stringTranslation:protected] =>
            [arguments:protected] => Array
                (
                )

        )

    [description] =>
)

```

Could somebody help me? Doesn't matter it is in hook\_form\_alter() or any other hook.

Thank you.

# Answer
Usually you setup the default value when configuring the filter -- if you've got an exposed content:type filter, then you set the default values by selecting one or more content types in the *Configure filter criterion* dialog.

I wouldn't do this via `hook_form_alter` (or similar) as you'll be fighting Views the whole way.
> 0 votes

---
Tags: views
---


# Question
Title: Cant get views_exposed_form to submit correctly
I needed to have all taxonomy vocabularies available to filter on, without adding all of the taxonomies one at a time.

I did this using the Content: Has taxonomy terms (Multiple) Filter - which renders out as a multiple select list.

I needed to change the select list to checkboxes, but BEF didnt allow me to do that for this type of field, so i did the following...

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'views_exposed_form') {

      $options = $form['filter']['#options'];
      unset($form['filter']);

      foreach($options as $vocab => $terms) {

        foreach ($terms as $key => $value) {
            $newkey = $options[$vocab][$key]->option;
            $termoptions[$vocab][key($newkey)] = $newkey[key($newkey)];
        }
        $form[$vocab] = array(
          '#type' => 'checkboxes',
          '#options' => $termoptions[$vocab],
          '#title' => $vocab,
          '#multiple' => TRUE,

        );

      }

  }

}

```

The exposed form looks good, but it doesnt work.

I think its because the name of the query is wrong. As i have split up the heirarchy into separate fields, the url used to look like

> mysite.com/category?filter\[\]=123

Now it looks like...

> mysite.com/category?Brand\[123\]=123

So theres how far ive got, any ideas how i can make this exposed form work?

I had a poke around at changing the submit handler views\_exposed\_form\_submit but i dont know what i would need to change.

# Answer
> 0 votes
Please take a look at https://www.drupal.org/node/2882381 and let me know if the patch in comment #6 meets your needs.

If so, please test that patch and report back the results of your tests in that issue.

Thanks!

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


# Question
Title: error: Fatal error: Class 'Drupal\syslog\Logger\SysLog' not found in /lib/Drupal/Component/DependencyInjection/Container.php on line 272
I just activated the module syslog in an almost fresh D8 install and now it has crashed. =( How do I deactivate a core module like this manually or fix the issue?

# Answer
If this is a local install, you could install Drush, and then: `drush dis module`. Or you can go here for more sophisticated solutions.
> 0 votes

---
Tags: 8, debugging
---


# Question
Title: Drupal 8 Ajax Form Submit works only once?
I am trying to create a simple form in D8 that submits with a submit button and then replaces the entire form content via ajax.

For some reason, my AJAX submit works perfectly on the first click but then kicks in a normal submit handler.

**This Works**

```
  public function getFormId() {
    return 'my_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {

  $form['#prefix'] = '<div id="form-test">';
  $form['#suffix'] = '</div>';
  $form['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Title'),
    '#required' => TRUE,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit ').time(),
    '#ajax' => [
      'callback' => [$this, 'loadStep'],
      'wrapper' => 'form-test',
      'effect' => 'fade',
    ],
  );

return $form;
}

public function loadStep(array &$form, FormStateInterface $form_state) {
$response = new AjaxResponse();
$form['submit']['#value'] = time();

$response->addCommand(new HtmlCommand('#form-test', $form));
return $response;

}

public function validateForm(array &$form, FormStateInterface $form_state) {

}

public function submitForm(array &$form, FormStateInterface $form_state) {
// TODO: Implement submitForm() method.
}

```

**This Does NOT work**

```
  public function getFormId() {
return 'my_form';
}

public function buildForm(array $form, FormStateInterface $form_state) {
  $form['#prefix'] = '<div id="form-test">';
  $form['#suffix'] = '</div>';
  $form['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Title'),
    '#required' => TRUE,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit ').time(),
    '#ajax' => [
      'callback' => [$this, 'loadStep'],
      'wrapper' => 'form-test',
      'effect' => 'fade',
    ],
  );

return $form;
}

public function loadStep(array &$form, FormStateInterface $form_state) {
$response = new AjaxResponse();
$form['#prefix'] = '<div id="form-test">';
$form['#suffix'] = '</div>';
$form['title'] = array(
  '#type' => 'textfield',
  '#title' => t('Title'),
  '#required' => TRUE,
);
$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Submit ').time(),
  '#ajax' => [
    'callback' => [$this, 'loadStep'],
    'wrapper' => 'form-test',
    'effect' => 'fade',
  ],
);
$response->addCommand(new HtmlCommand('#form-test', $form));
return $response;

}

public function validateForm(array &$form, FormStateInterface $form_state) {

}

public function submitForm(array &$form, FormStateInterface $form_state) {
// TODO: Implement submitForm() method.
}

```

It seem like as soon as I add something more substantially than just changing the label on the submit button, it seems to fail from the second submit where it just invokes a regular submit.

I want to replace the entire form on every submit (basically creating a multistep form).

I am running 8.3.2 btw

Many thanks for all help.

# Answer
> 0 votes
Your problem is probably here:

```
$form['submit']['#value'] = time();

```

You are changing the value of the submit button in the ajax callback. However, Drupal has already cached the form before the Ajax callback is hit. Why that matters is that Drupal uses the value of the submit button to determine which button was clicked, comparing it to the values in the cache. Since your cached value will be different than the submitted value, it cannot properly determine what it needs to do.

You need to change the value of the submit button either in the form definition, or in a form\_alter hook.

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


# Question
Title: Administrator verification for user role type
Is it possible to add admin verification for specific user roles. For instance, my site has three user roles, one of which would should get verified before gaining access to the content. I realise there is an option " Visitors, but administrator approval is required" in the people \> administration tab, but this would be for all users.

I'm managing roles directly through Drupal 7 and not using any modules such as profile2.

Thank in advance,

Cheers,

# Answer
> 1 votes
For the record, the option you refer to ("Visitors, but administrator approval is required") is not for all users. It only applies to the *Anonymous* user role, and means that the Anonymous user is allowed to register at the site (gaining the *Authenticated* user role), but only after the administrator has approved the registration.

The "standard" way of doing this in Drupal is to set up the site so that the "Anonymous" user role does not get access to the content you want to reserve for verified users.

Then, to gain access the anonymous user must 1) register; and 2) the administrator must approve the registration (using the option you refer to).

How would this model work for your site?

# Answer
> 1 votes
http://drupal.org/project/apply\_for\_role The Apply for Role module allows users to apply for roles and allows role administrators to approve the role applications.

Maybe this module can help you https://www.drupal.org/project/autoassignrole

# Answer
> 0 votes
An alternative would be the Registration Role With Approval, which sounds like it does exactly what you need it to. I've used it before with success.

> This module lets administrator to select roles that will be available for selection on registration form. It also allows to select which roles needs admin approval.
>
> During registration user will be presented with optional checkboxes where he can select a one or more of available roles. If role needs admin approval, user account will be blocked until approved by admin. Email will be sent to administrator (configurable) with roles that are requested and username of user who request it.

https://www.drupal.org/project/registration\_role\_with\_approval

---
Tags: users
---


# Question
Title: How do I alter the page title after a controller sets the title?
Is it possible to modify a page title after a controller sets `#title` in the main element?

Normally you can modify the page title by setting `_title` or `_title_callback` in the route. However it seems that you cannot alter the page title if a controller sets `#title`.

(A correct answer would affect both the HTML `<title>` and the system title block.)

# Answer
Yes, `#title` from the controller overrides the title set in the route. There doesn't seem to be another override to override `#title`.

Though you could try to alter the controller output in a KernelEvents::VIEW with a priority higher than 0 like this:

```
$result = $event->getControllerResult();
// change the controller output
$event->setControllerResult($result);

```

---

**Metatag**

Working on a project I found out, that the metatag module in default configuration gets the title with the token `[current-page:title]`, which retrieves the title from the route, ignoring `#title` set in the controller. Most times this would be considered as an unwanted side effect, but in your case you get the title you want from the route title callback in HTML `<title>` and only have to take care of the page title block, which should be no problem in a preprocess hook.
> 2 votes

---
Tags: 8
---


# Question
Title: Issues with the title for a custom entity
I have a custom content entity in which I have defined all the fields in the annotation (and it shouldn't need to be altered through the UI in any way that I can think of).

In the annotation I have the standard keys defined:

```
 *   entity_keys = {
 *     "id" = "MY_ID_FIELD",
 *     "label" = "MY_LABEL_FIELD",
 *     "uuid" = "uuid"
 *   },

```

MY\_LABEL\_FIELD is a field used for the "title" but I also need it presented in the content. In the entity class, I have it defined as I would need it displayed in the content:

```
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'type' => 'string',
    'weight' => 3,
   ))

```

Without any theme overrides, in the page content, MY\_LABEL\_FIELD renders as expected (and as defined in the annotation) with some basic field wrappers.

```
<div class="field ...">
  <div class="field--label ..."> [the field's label...] </div>
  <div class="field--item ..."> [the field's value...] </div>
</div>

```

But...

It renders the same way in the title block, with the field wrappers, in addition it is wrapped in `<h1>` tags by page-title.html.twig

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21PageTitle.php/8.2.x

https://api.drupal.org/api/drupal/core%21modules%21system%21templates%21page-title.html.twig/8.2.x

And...

It renders as `[the field's label...] [the field's value...]` inside the HTML `<head><title>` tags.

https://api.drupal.org/api/drupal/core%21includes%21theme.inc/function/template\_preprocess\_html/8.2.x

https://api.drupal.org/api/drupal/core%21modules%21system%21templates%21html.html.twig/8.2.x

And...

I need to use the title value in my page template (page.html.twig). There is a title value available in `$variables['page']['#title']` in https://api.drupal.org/api/drupal/core%21includes%21theme.inc/function/template\_preprocess\_page/8.2.x but this title value is the same as HTML above, it is `[the field's label...] [the field's value...]`

In all 3 places, I simply want `[the field's value...]` \- without the label, without the wrappers. The only place I do want the label and wrappers is inside the content.

One solution is to implement a couple of HOOK\_preprocess functions. Another is to implement a title callback.

This issue has been discussed here a number of times:

I tried implementing a title callback...

In my implementation of EntityRouteProviderInterface

```
$route = (new Route('/MY_PATH/{MY_ENTITY}'))
  ->addDefaults([
    '_entity_view' => 'MY_ENTITY',
    '_title_callback' => '\Drupal\MY_MODULE\Controller\MY_CONTROLLER::titleCallback',
  ])
  ->setRequirement('_entity_access', 'MY_ENTITY.view');
$route_collection->add('entity.MY_ENTITY.canonical', $route);

```

And in a controller

```
public function titleCallback() {
  $entity = \Drupal::routeMatch()->getParameter('MY_ENTITY');
  return $entity ? $entity->label() : 'SOME VALUE FOR FALSE';
}

```

And in my entity class, I implemented the label() method (override the parent class)

```
/**
  * {@inheritdoc}
  */
public function label() {
  return $this->get('MY_LABEL_FIELD')->value;
}

```

But I couldn't get this titleCallback() to ever get called. I started poking around a bit... I found that if I removed the "label" definition from the entity annotation, then the titleCallback() worked fine.

So this...

```
*   entity_keys = {
*     "id" = "MY_ID_FIELD",
*     "label" = "MY_LABEL_FIELD",
*     "uuid" = "uuid"
*   },

```

became...

```
*   entity_keys = {
*     "id" = "MY_ID_FIELD",
*     "uuid" = "uuid"
*   },

```

Then everything seemed OK. MY\_LABEL\_FIELD was rendered with wrappers in the body and just the value was used in the page title block, the HLML `<head><title>` and was a simple string available in `$variables['page']['#title']`.

I moved on to other things.

I continued working on my module. This entity will hold nearly a million records and I started working on methods for loading all that data. After getting to a nice place with several hundred thousand records, I was doing some tests and getting some weird results, in particular entity reference autocomplete widgets pointing to this entity would just display a spinner (with only a few records it seemed fine). At first I thought it was a database issue with so many records, but eventually I discovered that if I put the "label" definition back into my annotation, all was fine again - except of course the title was being rendered with label and field wrappers.

I am guessing that the "label" definition is pretty important. I know it's not required, as my module would work without it. Also, a basic example https://www.drupal.org/docs/8/api/entity-api/create-a-custom-content-entity doesn't show it defined.

So I am not sure where to turn next:

Thoughts?

# Answer
OK I found the solution to my problem (why it took me so long is another issue - but of course, it was found in a controller).

Posting as an answer instead of an update (as the question is so long, I think it might get lost).

The "offending" code is in **EntityViewController** (https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21Controller%21EntityViewController.php/8.2.x).

```
public function buildTitle(array $page) {
  $entity_type = $page['#entity_type'];
  $entity = $page['#' . $entity_type];
  // If the entity's label is rendered using a field formatter, set the
  // rendered title field formatter as the page title instead of the default
  // plain text title. This allows attributes set on the field to propagate
  // correctly (e.g. RDFa, in-place editing).
  if ($entity instanceof FieldableEntityInterface) {
    $label_field = $entity->getEntityType()->getKey('label');
    if (isset($page[$label_field])) {
      $page['#title'] = $this->renderer->render($page[$label_field]);   <---------HERE
    }
  }
  return $page;
}

```

I imagine that is fine in most use cases, but not in mine. And plus 1 for Drupal devs not losing the documentation on this. https://www.drupal.org/node/2498849

So I need my own controller (node module has an example as well, see NodeViewController) in which I can implement the function `buildTitle(array $page)` and leave the title as the default plain text.

In my implementation of **EntityRouteProviderInterface**, the canonical route is defined:

```
$route = (new Route('/path/{my_entity}'))
  ->addDefaults([
    '_controller' => '\Drupal\my_enitity\Controller\MyEntityViewController::view',
    '_title_callback' => '\Drupal\my_entity\Controller\MyEntityViewController::title',
  ])
  ->setRequirement('my_entity', '\d+')
  ->setRequirement('_entity_access', 'my_entity.view');
$route_collection->add('entity.my_entity.canonical', $route);

```

And this is the content of the file with my controller

```
namespace Drupal\my_module\Controller;

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\Controller\EntityViewController;

/**
 * Defines a controller to render a single my_entity.
 */
class MyEntityViewController extends EntityViewController {

  /**
   * {@inheritdoc}
   */
  public function buildTitle(array $page) {
    // the parent implementation of this method overrides the default plain text title
    // and sets the title as the fully rendered field (as defined by the field template)
    // we want the default plain text, so we just need to return $page as is.
    return $page;
  }

  /**
   * {@inheritdoc}
   */
  public function view(EntityInterface $my_entity, $view_mode = 'full', $langcode = NULL) {
    // this needs to be implemented to change the name of the first paramater to our entity name
    // but we can return the parent's output
    $build = parent::view($my_entity, $view_mode, $langcode);
    return $build;
  }

 /**
   * The _title_callback for the page that renders a single my_entity.
   *
   * @param \Drupal\Core\Entity\EntityInterface $my_entity
   *   The current my_entity.
   *
   * @return string
   *   The page title.
   */
  public function title(EntityInterface $my_entity) {
    // this copies how node implements its title callback.
    return $this->entityManager->getTranslationFromContext($my_entity)->label();
  }

}

```
> 0 votes

---
Tags: theming, entities
---


title: Declaring highwater property in Migrate

text:
# Question
Title: Declaring highwater property in Migrate
I would like to know how to correctly define the highwater property when using Migrate for Drupal 8. I am doing an import from a legacy non drupal database and I should be able to update only the relevant nodes whenever a column highwater changed. According to the official documentation, the solution is to use a highwater property. How to declare it? Is it a property to be set in the Plugin mapping class or is it an entry in the migrate.migration.\*.yml file? Thanks!

# Answer
You can add "high\_water\_property" in your migration config entity:

```
id: my_migration
source:
  high_water_property:
    name: changed
    alias: n

```

From the documentation: \- high\_water\_property: (optional) It is an array of name & alias values (optional table alias). This high\_water\_property is typically a timestamp or serial id showing what was the last imported record. Only content with a higher value will be imported.

Note: The high\_water\_property and track\_changes are mutually exclusive.

Note: If you're not using SqlBase in your source, you might also want to implement something similar as shown there.
> 3 votes

# Answer
highWaterProperty renamed to high\_water\_property, and moved from the top-level migration plugin configuration into the source plugin configuration.

```
id: my_migration
source:
  high_water_property:
    name: changed

```

For more information, see: https://www.drupal.org/node/2795403
> 4 votes

---
Tags: 8, migrations
---


# Question
Title: Unable to jump to a specific spot (seek) when mp4 or mp3 is in private field
I'm serving .mp4 videos and .mp3 audios using private download (field's upload destination: Private files), and they play OK on native html5 player, but seeking doesn't work, as in I can't jump to the middle of a video or audio.

This happens on Chrome and doesn't happen on Firefox. Also no problem playing and jumping on public download or when the file is saved on local drive and played from there.

After comparing the response headers in several different scenarios I have concluded that the only consistent difference between working and non-working is that Accept-Ranges and Last-Modified headers are missing when seeking is not working. These can be added at hook\_file\_download but then the media won't play at all.

This a pain to test with Chrome Developer Tools \> Networking as Chrome pulls old headers from its memory, so you never know which input is producing which output.

**Solution**

Install https://www.drupal.org/project/resumable\_download. Despite its name and the fact that it's at beta1 (it gives some notices) it does the job. It takes completely care of feeding the media to the browser.

Edit: If the module doesn't work, check out this patch: https://www.drupal.org/node/2362393

# Answer
> 1 votes
### Problem

Chrome makes multiple HTTP request with **Range** header for media file and expects HTTP **Content-Range** and **Content-Length** response header with **206 Partial Content** status (read this). If server send '200 OK' status Chrome will not play the media file, but Firefox will. If server send '200 OK' status with response header **'Accept-Ranges: none'** then Chrome will play media file, but jumping will not work. I assume you have implemented hook\_file\_download() already. That hook should return array of appropriate HTTP headers. It's enough to return **Accept-Ranges** header (only if your module should handle the media file and current user has permission):

```
return array(
  'Accept-Ranges' => 'bytes',
);

```

### Solution - Drupal 7

Accept-Ranges response header with value 'bytes' is a signal to client that server supports Range request. If you don't want to support Range request you should use 'none' instead of 'bytes'. There is no server support for Range request for private files. Therefore you should install Resumable Download module which will setup other HTTP response headers like: Content-Range, Content-Length and ETag, and set HTTP status 206 Partial Content. Drupal core module **File** will setup other HTTP response header like Content-Type.

---
Tags: 7, files
---


# Question
Title: Delete or unpublish content from old migration, if source rows no longer exist
I am using Migrate API to import products from a CSV file that is updated every week or so.

Every time the CSV file is updated,

* new products may be introduced
* existing products may be modified
* old products may disappear

Migrate currently does not seem to have a mechanism to remove or unpublish orphan content from the site, where the source record no longer exists.

See e.g.

What kind of solution or workaround could be used to deal with this old content?

"Deal with" could mean one of the following:

* Delete "old" entities from the site.
* Unpublish "old" entities.
* Have a property or field that tells us when an entity was last seen in a migrate source record. This would allow e.g. to filter such entities in Views.

## Notes

Please consider that migrations do not always process the complete source data. E.g. you could use the --limit parameter, or manually stop the migration, before all source rows are processed. Of course the typical nightly or weekly migration will process the complete source data. But manual migration runs often do not.

Also consider that a migration will usually not update rows that are unchanged. If we would store a "last import date" in a field, this would cause a lot more entity\_save() operations, so it would significantly slow down migrations.

# Answer
Here is the solution that I came up with.

TLDR: Drush command to compare source data vs existing products, and activate or deactivate products accordingly.

## Use case / goal

I am focusing on a specific use case, to make this easier to explain. Something similar could be done for other use cases.

Commerce products are imported with a migration. Both source and destination have one numeric primary key. The migrate map is MigrateSQLMap, so there is a migrate\_map\_\* table in the database with destid1 and sourceid1.

Goal: Change the "status" property of commerce products which are no longer in the source data.

## Considerations

A migration run can be incomplete. In such a case, we do not want remaining products to be deactivated.

Updating an entity (commerce product) in Drupal takes time. We do not want to update every entity just to change a timestamp.

We have to assume that the entire list of products can be quite big, so it can be problematic to have them all in memory at once. However, in this solution, I assume that having the ids (source id mapped to destination id) in memory is still acceptable.

## Solution: Custom drush command

Create a custom drush command that does the following:

Query the database, join the `commerce_product AS cp` table with the `migrate_map_MYMIGRATION AS mm` table. For each row we want `mm.sourceid1`, `mm.destid1` and `cp.status`. Load the complete list into an array as `$maps[$row->status][$row->sourceid1] = $row->destid1`.

Assign the two parts of the array to new variables `$inactiveIdsMap = $maps[0];` and `$activeIdsMap = $maps[1];`.

Create two additional associative arrays, each with format `$[$sourceid] = $destid`:

* `$idsToActivateMap = [];`. Start value: empty array.
* `$idsToDeactivateMap = $activeIdsMap`. Start value: All ids for active products.

You may want to `unset($activeIdsMap);` to free memory. (We could have reused this variable instead of declaring a new one, but I like having variable names that are accurate throughout a variables's life.)

Iterate through the source data. You can get the migrate source from the migration. It is a bit tricky but it can be made to work.

For each source row:

* If the id exists in `$inactiveIdsMap`, add the source + dest id to the `$idsToActivateMap` array.
* In any case, unset this entry from the `$idsToDeactivateMap` array.

Now deactivate all to-be-deactivated products, and activate all to-be-activated products.

You ideally do this in chunks, so e.g. you load 20 products at once with commerce\_product\_load\_multiple(), set each one's status, and save them individually with commerce\_product\_save().

This drush command can be executed after the migration.

## Memory impact?

You can measure memory use with `memory_get_usage()` or `memory_get_peak_usage()`. If you use `memory_get_usage()`, you need to call it in the place where you expect memory usage to be highest. Memory pretty print: http://codeaid.net/php/convert-size-in-bytes-to-a-human-readable-format-(php)

The way to check for the impact of this specific operation is to run the command with a subset of data. E.g. put a `->range()` on the select query for loading the migrate map. This should make all arrays smaller.

## Why? Alternatives?

Another solution that I found tempting at first was to maintain a "lastseen" timestamp in a separate table.

However, this would mean either having to update each product on every migration run, or at least reindex the search index each time, because we would want to filter by "lastseen".

With the solution presented here, in the average case, only few products have to be updated.

It turned out that the memory impact was very manageable.
> 1 votes

---
Tags: 7, migrations
---


title: Facetapi: Rewrite facet machine names?

text:
# Question
Title: Facetapi: Rewrite facet machine names?
I am working on a website with facetapi + search\_api, with some facets for taxonomy term references.

One of my facets is getting the machine name `field_xyz_parents_all` or `field_xyz:parents_all`, which in the URL this becomes `field_xyz%253Aparents_all`.

I want this facet to replace the older facet with machine name `field_xyz`, so that old URLs still work. So I would like to change the machine name or url query key of the new facet.

Any idea how to do this?

One idea I have would be to implement hook\_entity\_property\_info\_alter() and define my own entity property with the desired machine name, overwriting the existing entity property field\_xyz. I imagine this would work, but it somehow seems wrong, because in other places I might want to keep the original meaning of this property. Ideally I would only change the facet query key, not the property.

*EDIT: The original intent I had with this was to change the facet alias used in the url. However, changing the question to clarify this would make it a "chameleon question". Hence, I don't.*

# Answer
For completeness: If what you need is to change the facet alias, not the machine name, then the FacetAPI Alias module seems to do exactly this.

If you also consider using facetapi\_pretty\_paths, this issue might be interesting: Is facetapi\_alias compatible with facetapi\_pretty\_paths ? (compatible, overlapping functionality, compliment one another?)
> 1 votes

# Answer
Short version: Use hook\_facetapi\_facet\_info\_alter():

* To only change the key used in the url query, just use the hook to change the 'field alias' of the field\_xyz:parents\_all facet.
* To actually remap the machine name, as the original question implies, use the more complex implementation in "To remap the machine name".

## To only change key used in url query

1. On `admin/config/search/search_api/index/INDEXNAME/fields`, enable the `field_xyz:parents_all` field to be indexed.
2. Maybe you need to disable the base field, 'field\_xyz'. But maybe this is not necessary.
3. Re-index the search index.
4. Implement hook\_facetapi\_facet\_info\_alter() to change the 'field alias' of 'field\_xyz:parents\_all'.
5. Flush all caches. Otherwise the change from the hook will not be picked up.
6. On `admin/config/search/search_api/index/INDEXNAME/fields`, activate the 'field\_xyz:parents\_all' facet.
Deactivate the base facet 'field\_xyz' to prevent name clash.
7. Optionally, on `admin/config/search/facetapi/search_api%40INDEXNAME/block/field_xyz%3Aparents_all/edit`, override the facet title (\*).
8. Activate the facet block.

Here is the code:

```
/**
 * Implements hook_facetapi_facet_info_alter().
 *
 * @param array $facet_info
 * @param array $searcher_info
 */
function MYMODULE_facetapi_facet_info_alter(array &$facet_info, array $searcher_info) {

  // Change the field alias.
  if (!empty($facet_info['field_xyz:parents_all'])) {
    $facet = $facet_info['field_xyz:parents_all']['field alias'] = 'field_xyz';
  }
}

```

## To remap the machine name.

(This is the older version of this answer, which I am not deleting.)

1. On `admin/config/search/search_api/index/INDEXNAME/fields`, enable the `field_xyz:parents_all` field to be indexed.
2. Re-index the search index.
3. (Optional: I also enabled the original field, `field_xyz`. I don't think this is necessary, but I did it anyway.)
4. Implement hook\_facetapi\_facet\_info\_alter() to rewrite the facet machine name. See code below.
5. Flush all caches. Otherwise the change from the hook will not be picked up.
6. On `admin/config/search/search_api/index/INDEXNAME/fields`, activate the facet with the funny name (\*).
7. On `admin/config/search/facetapi/search_api%40INDEXNAME/block/field_xyz/edit`, override the facet title (\*).
8. Activate the facet block.

Here is the code:

```
/**
 * Implements hook_facetapi_facet_info_alter().
 *
 * @param array $facet_info
 * @param array $searcher_info
 */
function MYMODULE_facetapi_facet_info_alter(array &$facet_info, array $searcher_info) {

  // Re-map field_xyz.
  if (!empty($facet_info['field_xyz:parents_all'])) {
    $facet = $facet_info['field_xyz:parents_all'];
    // Optional: Remind the site builder that this facet is overridden in code (*).
    $facet['label'] .= ' (see MYMODULE.module)';
    $facet['name'] = 'field_xyz';
    // @todo Much better would be to JUST change the 'field alias'.
    $facet['field alias'] = 'field_xyz';
    $facet_info['field_xyz'] = $facet;
    // Optional: Unset the *:parents_all facet.
    unset($facet_info['field_xyz:parents_all']);
  }
}

```

(\*) Why the funky title " (see MYMODULE.module)"?

Simply because it is too easy to forget that some custom module messed with the facets. Better to have the funky title which you then override in the UI.
> 0 votes

---
Tags: 7, search, entities
---


# Question
Title: Custom search_api query for categories block
A site I am building has products that are indexed with search\_api + facetapi + search\_api\_solr.

One of the indexed fields is a (hierarchical) taxonomy term reference. In case this is relevant, I am indexing the "parents all" version of this field.

On the frontpage I want to show some kind of "doormat navigation" showing the most important categories. Something similar for the footer. And for the sidebar maybe.

What I found so far is this article, Display facets on non-search pages

I am not really happy with the options there, and would much rather do a solution with custom code, where I have full control on everything.

The missing part is how to do the search\_api query? I need a search\_api or SOLR query that returns a list of category ids, each with the number of indexed products for this category.

How would I build such a query?

# Answer
The following code does what we need.

```
  /**
   * @return int[]
   */
  function getCountsByTid($indexName, $facetFieldName) {

    $options = [];
    $options['search_api_facets'][$facetFieldName] = [
      'field' => $facetFieldName,
      // No limit.
      'limit' => -1,
      'operator' => 'and',
      'min_count' => '1',
      'missing' => '0',
    ];

    $q = search_api_query($indexName, $options);
    $q->range(0, 0);
    $q->fields([]);

    // Skip hook_search_api_query_alter().
    $result = $q->getIndex()->server()->search($q);

    if (!isset($result['search_api_facets'][$facetFieldName])) {
      return [];
    }

    $countsByTid = [];
    foreach ($result['search_api_facets'][$facetFieldName] as $item) {
      // The tid comes in a weird format.
      $tid = (int)substr($item['filter'], 1, -1);
      $count = $item['count'];
      $countsByTid[$tid] = $count;
    }

    return $countsByTid;
  }

```

Normally, the `$options['search_api_facets']` would be set in `search_api_facetapi_search_api_query_alter()`. However, this adds ALL facets, instead of just a specific facet. Also it limits the number of facet counts to 50. See #12132878: search\_api\_facetapi pollutes and slows all queries

Instead we set this option manually, and then skip the `$q->execute()` that would trigger `hook_search_api_query_alter()`.

SearchApiService classes always add quotes around the search values, which seems quite pointless to me.

We could get the raw tids from `$result['search_api_solr_response']->facet_counts->facet_fields->$propkey`, with `$propkey = 'im_' . str_replace(':', '$', $facetFieldName)`, but this only applies to search\_api\_solr.
> 0 votes

---
Tags: 7, search
---


title: Calculate tax before discount

text:
# Question
Title: Calculate tax before discount
I have created a rule in Drupal with the following conditions/actions.

With this rule, I give 10% discount on a specific product type, but the tax (21% in The Netherlands) is still calculated on the old price (without the discount).

For example, without discount I get the following.

* Sub total €28.93
* Tax €6.07
* Total price €35,00

With the discount, I get the following.

* Sub total €25.43
* Tx €6.07
* Total price €31.50

I tried to change the weight of the rule, but it didn't help.

I used the default tax module of Drupal Commerce and all the default settings. Is there something I can do about it?

I tried also the Commerce Discount module, but with the same behavior.

PS: Prices on this website are shown included of taxes.

After the patch, it is still not working. The Tax should be the following. (The product price is €0.90 with 10% discount; normally the price is €1.00 without the discount.)

* €0.74 (excluded tax)
* €0.16 (tax)
* €0.90 (total)

# Answer
> 1 votes
I think it is not possible, because Drupal Commerce calculate the prices/taxes before the discount. I had the same issue a while ago.

# Answer
> 1 votes
Your question seems a variation of the issue about Order discounts are not taken into account during tax calculation. Have a look at this patch attached to comment nr 22 of that issue.

Without the patch, you get a result similar to this, while after applying the patch it changes to this.

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


# Question
Title: How to load a entity or node in form builder class?
I want to load default values in my form. I am fetching the node of the table row from form list and passing it into route.

```
my_form_eform:
 path: '/edit/{bar}'
 options:
 parameters:
  bar:
  type: entity:node
 defaults:
  _form: '\Drupal\my_form\Form\EditForm'
  _title: 'Edit Item'
 requirements:
  _permission: 'access content'

```

and code for editform.php is

```
namespace Drupal\my_form\Form;

use Drupal\Core\Session\AccountInterface;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Form\NodeInterface;

class EditForm extends FormBase{

// public function content(AccountInterface $index, Request $request) {

public function getFormId() {
return 'edit_form';
}

public function buildForm(array $form, FormStateInterface $form_state , NodeInterface $bar = NULL){

 // $id = $bar;
//  $result = db_select('my_form','t')
// ->fields('t',array('id','title','author','stream','description','price'))
// ->condition('id',$id)
// ->execute()->fetchAssoc();

// $dtitle = $result['title'];
// $dauthor = $result['author'];
// $ddesc = $result['description'];
// $dstream = $result['stream'];
// $dprice = $result['price'];

$form = array();

$form['title'] = [
  '#type' => 'textfield',
  '#title' => t('Title of your book.'),
   '#default_value'=> $dtitle
];
$form['author'] = [
  '#type' => 'textfield',
  '#title' => $this->t('Author.'),
   '#default_value'=> $dauthor
  ];
$form['stream'] = [
  '#type' => 'select',
  '#title' => t('Stream'),
  '#options' => array(
  'ECE' => t('ECE'),
  'CSE' => t('CSE'),
  'ME'=> t('ME'),
),
   '#default_value'=> $dstream
  ];
  $form['desc'] = [
  '#type' => 'textfield',
  '#title' => t('Description'),
   '#default_value'=> $ddesc
  ];
  $form['Price'] = [
  '#type' => 'textfield',
  '#title' => t('Price'),
   '#default_value'=> $dprice,
  ];
$form['ADD'] = [
  '#type' => 'submit',
  '#value' => $this->t('Update'),
];
return $form;

```

}

I read about parameter upcasting, but its not required for node instance.

If I am passing the id in function itself through account interface it's giving the error

> must be compatible with formbuilder class

Now I am using NodeInterface argument but its also giving the error

> Argument 3 passed to Drupal\my\_form\Form\EditForm::buildForm() must be an instance of Drupal\Core\Form\NodeInterface

Please help. How can I load my id so that default values for form fields can be fetched from db?

# Answer
> 1 votes
You need to make it an optional argument. Annoying but unavoidable workaround with the current design.

And to have it already upcasted to a node, you need to name your variable {node}.

# Answer
> 0 votes
Your routing definition contains a little mistake: please add 2 spaces before `type: entity:node` for Drupal to pick it up.

Also, I suggest you to extend `ConfigFormBase` instead of `FormBase`. Then, you can use `$bar = $this->getRequest()->get('bar')` to get the Node object of type `\Drupal\node\Entity\Node`. You have to drop the 3rd parameter of `buildForm`.

Because `ConfigFormBase` is an abstract class, you will also have to add a function body for `getEditableConfigNames`, e.g.:

```
protected function getEditableConfigNames() {
  return [];
}

```

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


# Question
Title: How to sync a taxonomy between Drupal and a 3rd-party system?
I have a custom made system (non Drupal) that has a taxonomy like:

```
Element 1
   Element 1.1
   Element 1.2
   Element 1.3
Element 2
   Element 2.1
   Element 2.2
Element 3
   ...

```

And I have a Drupal site that I would like to be able to:

1. Use this taxonomy for tagging content, and
2. Add more terms that the non-Drupal system can use too.

Is there a popular way to ***sync*** a taxonomy in a Drupal system with an external system?

# Answer
You can import taxonomies, and even nested taxonomies, with CSV data generated from your source data. I have been done before and it works quite well with module Feeds.

As for your taxonomy system, you must generate dynamical CSV files (in fact, a PHP or a Drupal node with some custom code), which feeds the Imports you generate in Drupal and which are associated to a vocabulary. In that way you can generate taxonomies with children.
> 2 votes

# Answer
> Is there a popular way to sync a taxonomy in a Drupal system with an external system?

Actually yes the Migrate module can be setup to ingest new terms from the old system.

Migrate is a general use migration framework (which happens to have a lot of boilerplate Drupal classes) can also be used to set Drupal as the Source of a migration and the external system as Destination of the system. In general only the SQL Table destination plugin will be use of for migrations TO the legacy system out of the box. If you want to create special Migration classes similar to MigrateDestinationNode but specific to your external systems data entities -- that's up to you.

So you could have 2 custom migrations you write in PHP:

* MigrateTermsFromLegacySystem - which ingests any unknown terms into Drupal.
* MigrateDrupalTermsToLegacySystem - which sends any unknown terms to your legacy systems "terms" tables.

You would run these migrations via Cron, or a Rule.

As 1 real world example I've taken a 3rd party .NET SOAP request and used Migrate to take it's XML based output and feed it into a 3rd party non-drupal mysql database. I'm simply using Migrate and Drupal as a visual, interactive frontend to develop the migration code.
> 2 votes

# Answer
You can use the Taxonomy Manager module. The module does not synchronize terms but you can add the terms massively. See the description:

> This module provides a powerful interface for managing taxonomies. A vocabulary gets displayed in a dynamic tree view, where parent terms can be expanded to list their nested child terms or can be collapsed.

Some of their operations and key features are:

* dynamic treeview
* mass deleting
* mass adding of new terms
* moving of terms in hierarchies
* fast weight changing with up and down arrows (and AJAX saving)
* AJAX powered term editing form
* CSV Export of terms
* Double Tree interface for moving terms in hierarchies, adding new translations and switching terms between different vocabularies
> 2 votes

# Answer
### Drupal 7

In Drupal 7, you can use Features with UUID Features Integration module for easier to share and integrate content between sites. Check also Features Extra module.

### Drupal 8

In Drupal 8 all core entities support UUIDs and it's advised to use core configuration management system for that, unfortunately it doesn't support syncing of Taxonomy terms. The best would be to export them into CSV format and import on hook\_update.
> 0 votes

---
Tags: taxonomy-terms
---


title: How do I use a contextual filter?

text:
# Question
Title: How do I use a contextual filter?
I have two content types: Medical Records and Resident Profile. Each *Medical Records* node is associated to a *Resident Profile* through an *Associated Resident* entity reference field added to the first content type.

>

In the node display page for the *Resident Profile* nodes, I want to have a block on the side that displays all the associated *Medical Records* nodes.

I know I have to do something with the contextual filters and relationships settings of a view, but I am not sure how to proceed.

How can I achieve what I described?

# Answer
> 0 votes
After creating a view, you can follow these steps to accomplish what you need:

Add a contextual filter, Search for nid - So you will have Content: Nid.

In When the filter value is NOT available:

* Select Provide default value -\> Type -\> Content ID from URL.
* Apply

Add a relationship in your view:

* Search for field\_associated\_resident (your machine name), if there are two things come up. choose the one which says something like this: A bridge to the Content entity that is referencing Content via field\_associated\_resident (Language can differ).
* Check Require this relationship.
* Apply

Now go to your field selection, for example, you may want to display title. Add a field title and choose the relation you just created and Save.

To test this, you can use the nid of the Resident profile where you want to display it in the view itself. You should get your expected results there itself.

---
Tags: views, navigation
---


title: Code Problem in my template.php

text:
# Question
Title: Code Problem in my template.php
Hello i have an awful feeling im just simply doing something fundamentally wrong. I think they are both the same function possin;y Can anyone tell me how to get it all together possibly? thanks

```
<?php

function ukf2_preprocess_page(&$vars) {
 if (isset($vars['node'])) {
$vars['theme_hook_suggestion'] = 'page__'.$vars['node']->type; //
}
}
// Finish copy Template for Content type

function ukf2_preprocess_page(&$variables) {

if (!empty($variables['page']['sidebar_first'])) {
    $variables['content_column_class'] = ' class="col-sm-10"';
  }

 else {
    $variables['content_column_class'] = ' class="col-sm-12"';
  }

if (!empty($variables['page']['sidebar_second'])) {
    $variables['content_column_class2'] = ' class="col-sm-8"';
  }

 else {
    $variables['content_column_class2'] = ' class="col-sm-12"';
  }

}

```

# Answer
You just need to put all that logic into a single function:

```
function ukf2_preprocess_page(&$vars) {
  if (isset($vars['node'])) {
    $vars['theme_hook_suggestion'] = 'page__'.$vars['node']->type; //
  }

  if (!empty($variables['page']['sidebar_first'])) {
    $variables['content_column_class'] = ' class="col-sm-10"';
  }

  else {
    $variables['content_column_class'] = ' class="col-sm-12"';
  }

  if (!empty($variables['page']['sidebar_second'])) {
    $variables['content_column_class2'] = ' class="col-sm-8"';
  }

  else {
    $variables['content_column_class2'] = ' class="col-sm-12"';
  }

}

```
> 0 votes

# Answer
Also I have a feeling like this theme suggestion should be something like:

```
$vars['theme_hook_suggestion'][] = 'page__'.$vars['node']->type;

```

And also you can make your code little short by something like this:

```
function ukf2_preprocess_page(&$vars) {
  if (isset($vars['node'])) {
    $vars['theme_hook_suggestion'][] = 'page__'.$vars['node']->type; //
  }
  // Do your comment here.
  $variables['content_column_class'] = !empty($variables['page']['sidebar_first']) ? ' class="col-sm-10"' : ' class="col-sm-12"';
  $variables['content_column_class2'] = !empty($variables['page']['sidebar_second']) ? ' class="col-sm-8"' : ' class="col-sm-12"';
}

```
> 0 votes

---
Tags: theming
---


# Question
Title: How to safely render node body on a custom variable?
I created a custom template for my programmatically created block.

I defined a variable for the template called test

so in my render array I have

```
'#test' => $node->get('body')->value

```

Problem is when I print `{{ test }}` in my twig template, it literally prints the html rather than rendering it. Ex: `<p> My node body </p>`

I've also have tried:

```
'#test' => $node

```

Then on twig `{{ test.body.value }}`

but same result, the html does not get rendered.

The only way I found to make render is by doing `{{ test.body.value|raw }}` but **raw filter should never be used on user entered data**.

How can I make Drupal stop escaping the html safely?

# Answer
Build a render element `processed_text` and set the text format from the body field, so that the right text filters are applied before you print the field with {{ body }}:

If you have the `node` in `#test` like in your second example:

```
'#test' => $node

```

then you can build the render element in twig:

```
{% set body = {
  '#type':   'processed_text',
  '#text':    test.body.value,
  '#format':  test.body.format,
} %}

{{ body }}

```

This is the preferred method, see the documentation of `check_markup()`:

> Note: this function should only be used when filtering text for use elsewhere than on a rendered HTML page. If this is part of a HTML page, then a renderable array with a #type 'processed\_text' element should be used instead of this, because that will allow cacheability metadata to be set and bubbled up and attachments to be associated (assets, placeholders, etc.). In other words: if you are presenting the filtered text in a HTML page, the only way this will be presented correctly, is by using the 'processed\_text' element.

https://api.drupal.org/api/drupal/core%21modules%21filter%21filter.module/function/check\_markup/8.2.x

---

Render element in php:

```
'#test' => [
  '#type' => 'processed_text',
  '#text' => $node->body->value,
  '#format' => $node->body->format,
],

```

and print in twig:

```
{{ test }}

```
> 18 votes

# Answer
I believe you should use:

```
'#test' => check_markup($node->get('body')->value, $node->get('body')->format);

```

At which point the data will be safely escaped, and therefore this is safe:

```
{{ test.body.value|raw }}

```
> 4 votes

---
Tags: theming, 8
---


# Question
Title: I have logged out and the login block is missing,how do I login back?
I had created a block that has replaced the default block on the frontpage i.e. the login block and I have logged out of the site so how do I log in back?

I have tried:

1. sitename/user/login
2. sitename/?q=user
3. sitename/?q=admin
4. sitename/subdirectory/?q=user

All it shows is "Page not found" or "Access Denied" Is there any other way I could log in back to my site?

And I'm using Drupal 8

# Answer
> 1 votes
You can get the one time login url with drush command: **drush uli;**

---
Tags: users
---


# Question
Title: Trying to import an Aegir backup to new server
I've been following the instructions http://community.aegirproject.org/content/importing-existing-aegir-backups/ on how to import a site.

I have the backup .tar.gz from another hosting provider on my server but I cant get the drush command to run?

When I check the `drush sa` for the platform it does not get listed but in the aegir admin it show up under platforms?

Should I be running the drush command in a specific directory? I have been using `/var/aegir/hostmaster-7.x-3.9/sites/aegir.domain.name`

Regards

Keith

# Answer
After trying many directory's the correct one to run appears to be `/var/aegir/platforms`

The `drush sa` now lists the installed profiles and the `drush provision-save ...` and `drush provision-deploy ...` now run.
> 0 votes

# Answer
You should be able to use the drush alias for hostmaster here:
`drush @hostmaster sa`

You may need to switch to the aegir user first.
> 0 votes

---
Tags: drush, aegir
---


title: Copy a content type from another site

text:
# Question
Title: Copy a content type from another site
I am the owner of 2 sites that are running Drupal 8. In Site\[X\] I have *news* nodes.
In Site\[Y\], I want to automatically get all the *news* nodes that are posted on Site\[X\] (title, body, images etc.).

Scenario:

1. Site\[X\] making new content (news) article
2. Site\[Y\] checking for new nodes, copying them, and saving them in the database to show them on Site\[Y\]

How can I do this the best/easiest/safest way in Drupal 8, with what methods, languages and how do I start?

# Answer
Although not yet a full release for D8, Feeds is perfect for this type of thing.

That said if you have the know-how, when saving a node, you could post to the second site, and consume the data using the built-in REST API.
> 0 votes

---
Tags: 8, nodes
---


# Question
Title: Theming two instances of an input field in one form
I have two instances of the Search form in one page. The search field needs to have different CSS classes in each instance.

Instance 1:

```
<input type="text" class="form-control input-foo" placeholder="Search">

```

Instance 2:

```
<input type="text" class="form-control input-bar" placeholder="Search">

```

All the relevant theme templates and preprocess functions that I can find to edit the classes output on the field, apply to both instances. E.g. input--search.html.twig.

For the time being I have instead applied a class on the block that each of these forms is contained in, but I'd like to know if there's another solution.

# Answer
Is there a reason having the class on the input would be better than having it on the block? e.g. does it make some CSS/JS awkward by not being able to target the input directly?

If not, having the class on the block seems like the ideal solution both in terms of ease-of-development and semantics...you want the **search input** to be styled based on **where it is**. That feels like a natural separation for a hierarchy of selectors: `.block .input`

If the blocks are in different regions, you could use the region class instead, which is there by default in most themes; that would avoid even having to alter the blocks themselves.
> 0 votes

---
Tags: theming
---


title: Create a menu that expands on click

text:
# Question
Title: Create a menu that expands on click
I want to create a menu that expands on click . ( For example, facebook, gmail, twitter all have menus at the top right where onl click the we get account settings , log out etc.)

What is the best way to do this in drupal? Is there any module for this or do I need to do it in theme?

Also, is there any special name for such menus? Thanks!

# Answer
Which drupal 6/7 ? See here http://www.pixelclever.com/custom-drupal-themes-drupal-5-and-drupal-6 and this JQuery menu module.

Jquery menu uses simple, cross browser compatible jquery to transform your multilevel menus into click and expand menus. Yes this module is similar to dhtml menus and active menus, but it is different in a couple of key ways.

1. Unlike dhtml menus (which requires you to click twice on a link to actually follow an expanded link) Jquery menus separates the link from the expanding mechanism (there is a small plus symbol that you click instead to expand the menu). This makes for a more natural navigation.
2. Unlike active menus, which makes ajax calls to fill in the lower level menus when you click the plus symbol, Jquery menu creates the menu in full on the initial page load. I personally have used active menus for several months and have found that those ajax calls sometimes fail, and are not as stable as jquery.
3. Unlike Active menus which transforms all menus into active menus once the module is turned on, Jquery menu only creates a jquery block for the menus that you specify. To chose which menus you want to be active you just have to visit the admin page at 'admin/settings/jquerymenu' .
4. Jquery menu is easily themable. Since the jquery menu blocks only use a small number of styles, and don’t use the default list styles, overriding it with your own css is easy. Also the important display elements are contained in themable functions so you can tinker with the layout if you like.
> 1 votes

# Answer
EDIT: I originally suggested Nice Menus (60,000+ installs) and Superfish (30,000+ installs). However, Nice Menus does not have onclick behavior. There is an onclick Superfish library but I don't know how difficult this would be to integrate into Drupal.

An alternative that can do onclick would be Dynamic Persistent Menu.
> 1 votes

# Answer
if you need light and customized menu I suggest you write your own, follow this steps:

1. create your menu via admin interface
2. mark as expanded your parents items in menu
3. some css to hide child
4. some javascript to reveal childs on parent click or hover

if you have menu with `#menu` as ID then css example:

```
css rule for parents
css rule for childs (level 2)
css rule for childs (deeper levels)
css rule for initiate menu like:
ul#menu ul {
  display: none;
  position: absolute;
  top: ??px;
  width: ??px;
  z-index: 100;

```

}

and some javascript like:

```
jQuery(function(){
  jQuery('ul#menu>li').hoverIntent(function(){
    jQuery(this).find('>ul').fadeIn('fast');
  },function(){
    jQuery(this).find('>ul').fadeOut('fast');
  });
});

```
> 0 votes

# Answer
I have contributed a module which integrates with Drupal Nice Menus and provide "on-click" support for nice menus.

https://www.drupal.org/project/nice\_menus\_onclick

You can try it in your project without changing your theme files or write any CSS.
> 0 votes

---
Tags: routes
---


title: Programmatically update a taxonomy term

text:
# Question
Title: Programmatically update a taxonomy term
```
$term = Term::load($_tid);
$term->field_league_id = 'ID value';
$term->Save();

```

I am updating the terms by the code above but it's not working. Create the term by term-\>Save() is works normally. Everyone had experienced with that please help.

Updated:

```
$term = Term::load($_tid);
$term->field_league_id->setValue($league_id);
$term->Save();

```

This solution is not working, it's throwing:

> Call to a member function setValue() on a non-object in..

At the top, I declared ref. already.

```
use Drupal\taxonomy\Entity\Term;

```

The code for create new taxonomy is working fine, but not for updating.

```
$term = Term::create([
            'name' => $league->caption,
            'vid' => 'league',
            'field_league_id' => $league_id,
            'field_league_code' => $league->league,
            'field_league_year' => $league->year,
            'field_league_numberofteams' => $league->numberOfTeams,
        ]);

        $term->Save();

```

# Answer
> 10 votes
```
$term = Term::load($_tid);
$term->field_league_id->setValue('ID value');
$term->Save();

```

---

Additional info (requested in comments):

If you print out the object, you'll see that fields use the class core/lib/Drupal/Core/Field/FieldItemList.php.

By browsing through the methods, you'll see a few functions for interacting with the FieldItemList object, such as setValue(),

When I'm developing in Drupal 8, in order to learn the API, I use the

dump() function a lot to see what type of object I'm dealing with, and to inspect it's methods.

```
dump($term); die();

```

In fact, in my settings.local.php file I have an include

```
include 'my_settings.php';

```

and in there I have this function:

```
function nprint($obj) {
  dump($obj);
  die();
}

```

This is something I've been using for years to inspect objects. Now that drupal is much more object-oriented, printing out objects to find what class they use is essential.

Another essential tool for me is using an editor that allows searching by file name (I use the free software Aptana Studio 3).

So if you see you're dealing with a "FieldItemList", you can do "command + t" to search by file name and type in "FieldItemList". This saves a lot of web-based research. And it helps you learn the code base.

# Answer
> 3 votes
Here is a simple example:

```
$term = \Drupal\taxonomy\Entity\Term::load($tid);
if (!empty($term)) {
  $term->field_league_id = 123; // For multivalue fields, use array().
  $term->save();
}

```

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


# Question
Title: Views archive page showing year and months of article content type
I am trying to build a view page that shows archives (content type is article) only by dates:

year (e.g.2016) february (post count) june (post count) etc ..

year (e.g. 2017) march (post count) june (post count)

To top it off, months being linked to the respective posts.

i tried with contextual filters using content: created year and content: created month but I only end up with the year.

Using Drupal 8.3.3.

I am not sure if my set up is missing something because when using fields and/or contextual filters I do not have a date option ...

Any kind soul who can help me out?

# Answer
> 0 votes
you can use calendar module, from module page:

> This module will display any Views date field in calendar formats, including CCK date fields, node created or updated dates, etc. Switch between year, month, and day views. Back and next navigation is provided for all views. Lots of the Calendar functionality comes from the Date module, so any time you update the Calendar module you should be sure you also update to the latest version of the Date module at the same time.

this video is for D7, for D8 is very similar, you can change display format in any view, for example a table and add a special field that you can find ir in views UI under "global" named "views reasult counter"

---
Tags: views
---


# Question
Title: How to send email custom module drupal 7?
I've looking for in google then finally I got some example working for me but when I start to manualy code making my cutom module send email it doesnt work ? then I try to copy paste in the new module just modif the name of module still doesnt work it says

> Unable to send e-mail. Contact the site administrator if the problem persists.

Here's the original code that working

```
<?php

function test_menu() {
  $items['test'] = array(
    'title' => t('Send Email Using Drupal mail'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('test_custom_form', 1),
    'access arguments' => array('access content'),
  );
  return $items;
}
function test_custom_form($form, $form_state) {
  $form = array();
  $form['subject'] = array(
    '#type' => 'textfield',
    '#title' => t('Subject'),
    '#required' => TRUE,
    );

  $form['email'] = array(
    '#type' => 'textfield',
    '#title' => 'To Email',
    '#prefix' => '<div id="email-field-wrapper">',
    '#suffix' => '</div>',
    '#required' => TRUE,
  );
  $form['from_email'] = array(
    '#type' => 'hidden',
    '#title' => 'From Email',
    '#value' => 'iupin5212@gmail.com',
    '#prefix' => '<div id="from-email-address">',
    '#suffix' => '</div>',
    '#required' => TRUE,
  );
  $form['email_body'] = array(
    '#type' => 'textarea',
    '#title' => 'Email Body',
    '#prefix' => '<div id="email-body">',
    '#suffix' => '</div>',
    '#required' => TRUE,
  );
  $form['submit_form'] = array(
    '#type' => 'submit',
    '#value' => t('Send Email'),
    '#submit' => array('test_custom_form_submit'),
  );
  $form['#validate'] = array('test_custom_form_validation');
  return $form;
}
/**
 * validation function for custom form
 * check for vadlidation for email address.
 * @param type $form
 * @param type $form_state
 */
function test_custom_form_validation($form, &$form_state) {
  $mail = $form_state['values']['email'];
  $from_email = $form_state['values']['from_email'];
  if (!valid_email_address($mail)) {
    form_set_error('email', t('Please Enter a valid to email address.'));
  }
  if (!valid_email_address($from_email)) {
    form_set_error('from_email', t('Please Enter a valid from email address.'));
  }
}
function test_custom_form_submit($form, &$form_state) {
  drupal_set_message("form is submitted, thanks");
  $email_content = get_mail_content($form_state);
  $params = array('body' => $email_content,
    'subject' => $form_state['values']['subject']);
  $key = 'test_email';
  $to = $form_state['values']['email'];
  $from = $form_state['values']['from_email'];
  $mail = drupal_mail('test', $key, $to, language_default(), $params, $from);
  // for better understanding,you can uncomment the following
 // dpm($mail);
}
/**
 * Implements hook_mail()
 * @param
 *   type $key to decide which email body to sent on basis of key parameter inacese of multiple email content
 * @param
 *   type $message the email content to be sent.Message array contains 'subject and body ' for the email.
 * @param
 *   type $params using to get the cusotm email content from a function.This can be used in my other ways aslo as per need.
 */
function test_mail($key, &$message, $params) {
  $language = $message['language'];
  switch ($key) {
//switching on $key lets you create variations of the email based on the $key parameter
    case 'test_email':
      $message['subject'] = $params['subject'];
//the email body is here, inside the $message array
      $message['body'] = $params['body'];
      break;
  }
}
/**
 * function to get the html formatted email content
 * @param
 *   type $form_state to get values from form fields.
 * @return
 *   $body type string return the html email content
 */
function get_mail_content($form_state) {
  $email_to = $form_state['values']['email'];
  $body = '';
  $body .= $form_state['values']['email_body'];
  return $body;
}

```

this my code doesnt working

```
    <?php
    function email_permission() {
      return array(
        'administer my module' => array(
          'title' => t('Administer my module'),
          'description' => t('Perform administration tasks for my module.'),
        ),
      );
    }

    function email_menu() {
      $items['email'] = array(
        'title' => t('Kirim Email'),
        'page callback' => 'email_output',
        'access arguments' => array('administer my module'),
        );
      return $items;
    }

    function email_output() {
      $output = drupal_get_form('email_form');
      return $output;
    }

    function email_form($form, &$form_state) {
      $form = array();
      $form['subject'] = array(
        '#type' => 'textfield',
        '#title' => t('Subject'),
        '#required' => TRUE,
        );
      $form['email'] = array(
        '#type' => 'textfield',
        '#title' => t('Ke Email'),
        '#required' => TRUE,
        );
      $form['dari_email'] = array(
        '#type' => 'hidden',
        '#value' => 'iupin5212@gmail.com',
        );
      $form['pesan'] = array(
        '#type' => 'textarea',
        '#title' => t('Pesan'),
        '#required' => TRUE,
        );
      $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Kirim email'),
        );
      return $form;
    }

    function email_form_validate($form, &$form_state) {
      $mail = $form_state['values']['email'];
      $dari_email = $form_state['values']['dari_email'];
      if (!valid_email_address($mail)) {
        form_set_error('email', t('Silahkan Masukan format email yang benar'));
      }
      if (!valid_email_address($dari_email)) {
        form_set_error('dari_email', t('Silahkan Masukna Format email yang benar.'));
      }
    }

    function email_form_submit($form, &$form_state) {
      drupal_set_message("Pesan telah terkirim");
      $email_pesan = email_ambil_pesan($form_state);
$subject1 = $form_state['values']['subject'];
      $params = array('body' => $email_pesan
'subject' => $subject1);
      $key = 'email_email';
      $to = $form_state['values']['email'];
      $from = $form_state['values']['dari_email'];
      $mail = drupal_mail('test', $key, $to, language_default(), $params, $from);
    }

    function email_mail($key, &$message, $params) {
      $language = $message['language'];
      switch ($key) {
        case 'email_email':
          $message['subject'] = $params['subject'];
          $message['body'] = $params['body'];
          break;
      }
    }

    function email_ambil_pesan($form_state) {
      $ke_email = $form_state['values']['email'];
      $body = '';
      $body .= $form_state['values']['pesan'];
      return $body;
    }
    ?>

```

What really mean Unable send email contact administrator ? please help..

# Answer
If you are seeing that message, it means that your code to send the email is properly going through all the way to the sending of the mail. It's either Drupal or your server that is unable to send the mail after that point. Do you have a mail server on your server? If not, then try downloading the SMTP module, and using a remote mail server (gmail for example).
> 1 votes

---
Tags: 7, emails
---


title: composer and Lightning

text:
# Question
Title: composer and Lightning
I have composer.jon to require

```
"acquia/lightning": "2.1.3",

```

This installs Drupal core 8.3.3. Can I change this to Drupal core 8.3.2 or does Lightning force you to use the Drupal version its packaged with?

I updated this post after fixing the problem. I changed the composer.json file and specified what drupal core version to use like this.

```
    "acquia/lightning": "2.1.3",
    "drupal/core": "8.3.2",

```

# Answer
> 1 votes
Looks like you've largely answered your own question. But to confirm, Lightning generally does not pin to a specific version of core in it's composer.json file. The current constraint is `~8.3.1` (note the tilde) which means the current release of Lightning should work with core 8.3.1 to 8.3.9(repeating) but not 8.4.0.

Core is the exception to the rule. Lightning normally pins to specific versions of dependencies if they are patched (see Lightning's dependency constraint logic). But since core follows SemVer, has predictable releases, and Lightning releases every time core does, Lightning doesn't pin core - even when it is patched (which is pretty much always).

Lightning increments the second digit of its release numbers (the minor release) when Drupal makes a minor release. In the current release of Lightning (2.1.4) the `one` relates to the `three` in the current release of core (8.3.3). So Lightning 2.1.x should run on any core 8.3.x. That's why Lightning uses the tilde (~) modifier and three digits when specifying Drupal core constraints.

---
Tags: 8, composer
---


title: Does Composer patch core automatically?

text:
# Question
Title: Does Composer patch core automatically?
I am using Composer on a Lightning drupal distro. In my composer.json file I set enable-patching true. And I added one core patch for /patches/core-file\_upload\_ajax\_message-1489692-68.patch. WHen I run composer update it applys 3 other patches. See output. Is Composer doing this by itself?

```
Applying patches for drupal/core
./patches/core-file_upload_ajax_message-1489692-68.patch (Incorrect handling of file upload limit exceeded - file widget disappears)
https://www.drupal.org/files/issues/no_hook_to_edit-2822460-2.patch (multi-value field widget hook)
https://www.drupal.org/files/issues/2652138-41.patch (2652138 - ImageFormatter does not support SVGs)
https://www.drupal.org/files/issues/1356276-303.patch (1356276 - Allow profiles to provide a base/parent profile and load them in the correct order)

```

# Answer
Composer doesn't patch core automatically, but the cweagans/composer-patches plugin allows dependencies to patch other dependencies if:

1. You have `enable-patching` set to `true` in the "extra" section of your root composer.json file, or
2. You have at least one patch defined in your root composer.json file

In your case, it looks like Lightning is pulling in those other core patches.
> 4 votes

---
Tags: 8, composer
---


title: Changing the value to negative

text:
# Question
Title: Changing the value to negative
I have a content type of invoice. This also has a drop down list (list text) to let the user pick one of three types - receivable , payable and proforma.

I also have it so I'm getting the amount, vat and total of the invoice.

However, what I need to do is change the value of the invoice amount, vat, and total when the user picks payable from the drop down menu to a negative value. For example, I fill out the invoice make it payable and I enter 2000 in the amount, 230 in vat and 2300 in total fields. I need these values to become negative when I run aggregator plus on them so instead of adding these numbers it subtracts them instead.

I was wondering if I can do this using rules, or do I create a new module to do this, or if I add a function to the template.php file. Any ideas of what is easiest and best

# Answer
In my opinion, the most elegant solution would be to leave the original values and to define how you operate with them (adding, substracting, etc.) at the Aggregator Plus level, but I am not familiar with that module, and I don't know how easy it would be to extend it.

If you want to modify the value of these fields before saving the node, there are at least two possibilities I can think of:

* Using Rules (it involves creating some custom PHP code). The following example (using increment instead of changing the sign) can give you a hint: https://www.drupal.org/node/1389074
* Creating a custom module and implementing hook\_node\_presave(), in order to modify the fields before they are written to the database.

Hope that helps,
> 0 votes

# Answer
use rules module, condition: entity\_has\_field\[yournumericfield\], condition: \[yournumericfield\] \> 0 (ensure is not already negative), actions: calculate\_a\_value, \[yournumericfield\] x \[-1\] , variablename=my\_new\_negative\_value, action:set\_a\_data\_value, \[yournumericfield\]=my\_new\_negative\_value, action:save\_entity.

be sure to set a low rule\_weight to ensure this rule runs before other rules involved.

footnote: multiply any number by -1 changes number sign
> 0 votes

---
Tags: nodes
---


title: Sort Criteria - sort by user role

text:
# Question
Title: Sort Criteria - sort by user role
I have 7 roles in my project. I arranged them by weight in admin/people/permissions/roles page Add the sort criteria Global:PHP with code

```
return $row1->rid;

```

But users display with no sort on role weight on page.

# Answer
> 2 votes
Look for these solutions:

In Views, how can I show users with one role before all other users?

Role Weights

This way you can get your desired result. Hope this helps.

---
Tags: views, users
---