# Question
Title: How reset $form_state on ajax call for get real value in submit?
I have see some post about that,but i still have no real answer.

In my form, user can select a register address in a select field. When he select an address, the ajax set value on some other fields :

> The code :

```
  if($form_state->getTriggeringElement()['#name']=="mes_adresses")
  {
      $listAdresse = $this->adresse_service->getUserAdresseById($form_state->getValue('mes_adresses'));

  }

  $form['containerGeneral']['livraison']['adresseComplete']['nom_livraison'] = array(
      '#title' => 'Nom de livraison',
      '#type' => 'textfield',
      '#value' => $listAdresse['nom'],
  );

  $form['containerGeneral']['livraison']['adresseComplete']['prenom_livraison'] = array(
      '#title' => 'Prénom de livraison',
      '#type' => 'textfield',
      '#value' => $listAdresse['prenom'],
  );

  $form['containerGeneral']['livraison']['adresseComplete']['pays_livraison'] = array(
      '#title' => 'Pays de livraison',
      '#type' => 'select',
      '#required'=>true,
      '#options'=>$this->taxonomy_service->getTermsByVid('pays_livraison'),
      '#value' => $listAdresse['pays'],
  );

  $form['containerGeneral']['livraison']['adresseComplete']['adresse_livraison'] = array(
      '#title' => 'Adresse de livraison',
      '#type' => 'textfield',
      '#value' =>  $listAdresse['adresse'],
  );

  $form['containerGeneral']['livraison']['adresseComplete']['adresse2_livraison'] = array(
      '#title' => 'Adresse de livraison',
      '#type' => 'textfield',
      '#value' =>$listAdresse['adresse2'],
  );

  $form['containerGeneral']['livraison']['adresseComplete']['cp_livraison'] = array(
      '#title' => 'Code postal de livraison',
      '#maxlength'=>5,
      '#type' => 'textfield',
      '#value' => $listAdresse['code_postal'],
  );

  $form['containerGeneral']['livraison']['adresseComplete']['ville_livraison'] = array(
      '#title' => 'Ville de livraison',
      '#type' => 'textfield',
      '#value' =>$listAdresse['ville'],
  );

```

> And the callback :

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

    $form_state->setRebuild(TRUE);
    return  $form['containerGeneral']['livraison']['adresseComplete'];

}

```

So there are 2 things :

> **#value**

If you set value like that, user can never change the value because

```
$form_state->getValue()

```

ll keep the value set by the ajax.

> **#default\_value**

If you set the value like that, that doesn't work because the #default\_value parameter if use just the first time the form is loaded.

> The main problem is with $form\_state.

If you kint when you submit your form $form\_state-\>getValue() and $\_POST, $\_POST is good but not the $form\_state.

But the issue are in the validate function too, if user select the option new address, ajax reload the form, set empty everywhere, and when you submit, the validate function ll tell you you have empty value.

I know on D7 some people unset the $form\_state\['values\];

But on D8 ?

So how reset the $form\_state value ?

# Answer
> 0 votes
Thank to @4k4 for the solution posted here :

How do I change the default value of a field with AJAX?

For my problem, this is how i add this feature :

```
$form['containerGeneral']['livraison']['adresseComplete'] = array(
          '#type' => 'container',
          '#prefix'=>'  <div id="adresseComplete">',
          '#suffix'=>'</div>'
      );

      $form['containerGeneral']['livraison']['adresseComplete']['nom_livraison']['#tree']=true;
      $form['containerGeneral']['livraison']['adresseComplete']['prenom_livraison']['#tree']=true;
      $form['containerGeneral']['livraison']['adresseComplete']['pays_livraison']['#tree']=true;
      $form['containerGeneral']['livraison']['adresseComplete']['adresse_livraison']['#tree']=true;
      $form['containerGeneral']['livraison']['adresseComplete']['adresse2_livraison']['#tree']=true;
      $form['containerGeneral']['livraison']['adresseComplete']['cp_livraison']['#tree']=true;
      $form['containerGeneral']['livraison']['adresseComplete']['ville_livraison']['#tree']=true;

      if($form_state->getTriggeringElement()['#name']=="mes_adresses")
      {

          $_SESSION['compteur']++;

          $listAdresse = $this->adresse_service->getUserAdresseById($form_state->getValue('mes_adresses'));

          $key = $_SESSION['compteur'];

      }

      $form['containerGeneral']['livraison']['adresseComplete']['nom_livraison'][$key] = array(
          '#title' => 'Nom de livraison',
          '#type' => 'textfield',
          '#required'=>true,
          '#placeholder' => 'Nom',
          '#default_value' => $listAdresse['nom'],
      );

      $form['containerGeneral']['livraison']['adresseComplete']['prenom_livraison'][$key] = array(
          '#title' => 'Prénom de livraison',
          '#type' => 'textfield',
          '#required'=>true,
          '#default_value' => $listAdresse['prenom'],
      );

      $form['containerGeneral']['livraison']['adresseComplete']['pays_livraison'][$key] = array(
          '#title' => 'Pays de livraison',
          '#type' => 'select',
          '#options'=>$this->taxonomy_service->getTermsByVid('pays_livraison'),
          '#default_value' =>  $listAdresse['pays_livraison'],
      );

      $form['containerGeneral']['livraison']['adresseComplete']['adresse_livraison'][$key] = array(
          '#title' => 'Adresse de livraison',
          '#type' => 'textfield',
          '#required'=>true,
          '#placeholder' => 'Adresse de livraison',
          '#default_value' =>  $listAdresse['adresse'],
      );

      $form['containerGeneral']['livraison']['adresseComplete']['adresse2_livraison'][$key] = array(
          '#title' => 'Adresse de livraison',
          '#type' => 'textfield',
          '#default_value' =>$listAdresse['adresse2'],
      );

      $form['containerGeneral']['livraison']['adresseComplete']['cp_livraison'][$key] = array(
          '#title' => 'Code postal de livraison',
          '#maxlength'=>5,
          '#type' => 'textfield',
          '#placeholder' => 'Code postal de livraison',
          '#default_value' => $listAdresse['code_postal'],

      );

      $form['containerGeneral']['livraison']['adresseComplete']['ville_livraison'][$key] = array(
          '#title' => 'Ville de livraison',
          '#type' => 'textfield',
          '#placeholder' => 'Ville de livraison',
          '#default_value' =>$listAdresse['ville'],
      );

```

Don't forget to set $\_SESSION\['compteur'\] to 0 on submit and to set it to 0 on form load.

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


# Question
Title: How to use feeds tamper to set default value from importer node?
I've got a number of feeds that I want to be able to import regularly. I setup feeds and attached them to a content type, ex. "My Feeds" which imports into another content type, "Article".

I also need to make sure that when these feeds come in, that I can set the default values in the target node. The use case is that I will be importing from feeds in multiple languages and want them associated with an author so I have created a couple of new fields in my importer content type:

```
field_language
field_author

```

I want to be able to set the language and author value for each feed when I create the importer and have those associated every time I update but its not clear if any of the existing plugins do this.

I've also started writing my own custom plugin to pull in these values from the parent importer but I can't figure out how to access or load the importer object through a feeds tamper plugin.

Any pointers or is there a better way to acccomplish this task?

# Answer
> 0 votes
Currently, there doesn't appear to be any core method of achieving this, either through Feed's Tamper or core Feeds Module.

There's a patch here, but I'm still looking for a core solution.

---
Tags: 7, feeds
---


# Question
Title: How to associate the last image from gallery to user's profile picture
In Drupal 7 (Commons 7.x-3.46).

I've created a new content type, by which each user can upload images and build a personal picture-gallery.

How can I now associate the last-uploaded-image to the user's profile-picture?

Amodule-based solution is preferable. Is there a better way of doing this, ie without a new content type? Essentially I'm looking for a user-friendly way for users to upload and show their profile pictures.

# Answer
> 0 votes
> Amodule-based solution is preferable. Is there a better way of doing this, ie without a new content type? Essentially I'm looking for a user-friendly way for users to upload and show their profile pictures.

I would like to recommend field\_collection module as I already mentioned in the question's comments.

**Step # 1:** Enable field\_collection module.

**Step # 2:** go to `/admin/config/people/accounts/fields` and add a new field named as **User Gallery** (machine name should be **field\_user\_gallery**) and choose field type as "Field collection" and save. Note that you can set the field cardinality as you like.

**Step # 2:** Go to `admin/structure/field-collections` and add a new image field named as **Image** (machine name should be **field\_image**) and choose field type as "Image" and save. (It might already be added in the existing field list.)

**Step # 3:** Download custom module from custom\_user\_profile and extract to your module directory. Make sure extracted directory name is **custom\_user\_profile** and then enable it.

That's all. I hope it will work for you as works for me.

---
Tags: 7, users, media
---


# Question
Title: How can I create multiple cropped Media images without re-uploading them?
Solutions that I've found allow to crop Media, type Image when I've uploaded an image, but the media entity is not yet created (on the "Add media" page).

I need to upload a large full image once (and use it in full format on some nodes), and then crop it differently when I select it in different content types (to display small "zoomed" parts of the full image). So I need a manual crop to appear when I select a Media of type Image from a Media library. It can appear in Entity browser or on the node page.

Other solution is that I can create cropped images in advance being in my media library (`/admin/content/media`) or when adding a media (`/media/add/image`). The idea is that I do not want to reupload the image and add new title and alt.

Is this possible?

# Answer
Solution:

1. Install Crop API and Image Widget Crop modules
2. Configure Image Widget Crop as explained in the tutorial, for Image field situated in `Structure > Media types > Image`. The image style for this Image field should contain no effects.
3. There where you want to use cropped image, select the style for it (in content type, for example) that contain "Manual crop" effect and, if you need, "Crop and Scale effect" (to display square thumbnails in listings, for example).
4. There where you want to use full umage, select the style for it that contain no "Manual crop" effect.

How to use images:

1. Upload a large full image, crop manually the interesting part
2. Use the same image there where you need it cropped and there where you need it full. It will be displayed differently on front.

Note: if you try to clone the Image entity (for example with Entity Clone module), it will not help because the clone Image entity and the original Image entity will apply the same crop.
> 0 votes

---
Tags: 8, media
---


title: Get user role by user field

text:
# Question
Title: Get user role by user field
how can I access to my user role thanks to my user custom field ?

I have an user field called "custField" and it's value (example : 123456). I need to check all users that have "123456" as value.

Then, I need to check if this user as the role "director".

But I don't know how to access role thanks to another field.

EDIT :

See this loop :

```
foreach($retraitDoublons as $valUnique){
  $users = \Drupal::entityTypeManager()->getStorage('user')
    ->loadByProperties(['field_custVal' => $valUnique]);
  $user = reset($users);
  $user_has_role = $user && $user->hasRole('directeur_cr_');

  dump($user);
  dump($user_has_role);

  echo $valUnique . "<hr>";
}

```

# Answer
Similar to this question:

I have an user field called "custField" and it's value (example : 123456). I need to check all users that have "123456" as value:

```
$users = \Drupal::entityTypeManager()->getStorage('user')
  ->loadByProperties(['field_custField' => '123456']);

```

Then, I need to check if this user:

```
$user = reset($users);

```

has the role "director":

```
$user_has_role = $user && $user->hasRole('director');

```
> 0 votes

---
Tags: users
---


title: Different registration form per role

text:
# Question
Title: Different registration form per role
I'm new to Drupal 8 and not sure how I should make this work.

I have two users:

1. User 1 is created by admin.
2. User 2 is created by User 1 with predefined role.

I want to have different registration forms for admin and User 1.

So far, I've tried multiple registration modules, including the Registration Types module. The only thing I managed to do is assigning a role to User 2 when a checkbox is checked with the Select Registration Roles module, but it would be better if the roles are assigned automatically when User 1 creates User 2.

# Answer
> 1 votes
Based on the 3rd answer on How to assign a specific role to each newly registered user?

I edited the code and tested this code:

```
/**
 * Implements hook_ENTITY_TYPE_presave() for user entities.
 */
function mymodule_user_presave(Drupal\Core\Entity\EntityInterface $entity) {
  $currentUser = Drupal::currentUser();
  if (in_array('administrator', $currentUser->getRoles())) {
    $entity->addRole('user_2_role');
  }
  else {
    $entity->addRole('user_1_role');
  }
}

```

---
Tags: 8, users, forms
---


# Question
Title: Outputting a link as a button in node.tpl.php
I am trying to rewrite the output of node.tpl.php.

I am using field link. I cannot figure out how to get the field to render as a button. I did find that the field is output as an array

I tried this but it just makes the link just a link to the page I am on:

```
<a class="btn btn-danger btn-lg" href="<?php print render ($content[field_amazon_link][LANGUAGE_NONE][0]['display_url']); ?>">Buy Now</a>

```

The devel module gives me this info. Keep in mind php is my week area. This is my first time rewriting a node file as I used to have a helper and he has moved on.

field\_amazon\_link (Array, 1 element)

```
0 (Array, 5 elements)
    url (String, 142 characters ) https://www.amazon.com/gp/product/B00ZGUBN3C/re...
    title (String, 83 characters ) https://www.amazon.com/gp/product/B00ZGUBN3C/re...
    attributes (Array, 1 element)
    html (Boolean) FALSE
    display_url (String, 83 characters ) https://www.amazon.com/gp/product/B00ZGUBN3C/re...

```

And this is from the object devel tool field\_amazon\_link (Array, 1 element)

```
und (Array, 1 element)
    0 (Array, 5 elements)
        url (String, 142 characters ) https://www.amazon.com/gp/product/B00ZGUBN3C/re...
        title (String, 83 characters ) https://www.amazon.com/gp/product/B00ZGUBN3C/re...
        attributes (Array, 1 element)
        html (Boolean) FALSE
        display_url (String, 83 characters ) https://www.amazon.com/gp/product/B00ZGUBN3C/re..

```

# Answer
> 0 votes
This is what ultimately worked for me. I don't really understand it completely, but if anyone can shed some light on why it worked, I would really like to know.

```
<a class="btn btn-danger btn-lg" target="_blank" href="<?php print $content['field_amazon_link']['#items']['0']['url']; ?>">Buy Now</a>

```

# Answer
> 0 votes
The gist of it is to add the correct classes `btn btn-danger btn-lg` to the array before rendering it. You could accomplish it like this, with in a '.tpl.php' file:

```
<?php
  $content['field_amazon_link']['#items']['0']['attributes']['class'][] = 'btn';
  $content['field_amazon_link']['#items']['0']['attributes']['class'][] = 'btn-danger';
  $content['field_amazon_link']['#items']['0']['attributes']['class'][] = 'btn-lg';
?>

```

Then you can use the Drupal API to render it to HTML using the *render* function the whole, and print it, like so:

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

```

---
Tags: nodes
---


title: form submitted value as token

text:
# Question
Title: form submitted value as token
I have created a form by extending FormBase class. In form, I'm having a field called "name" where user can input his name. While submitting form, I want that submitted name convert into token so that I can use that token sending emails.

example.com/admin/config/people/accounts, here is the Drupal default configuration email forms.

*What I want is to use custom form field value to be appear as a token inside drupal default email config forms.How can this be achieved?*

Any help is appreciated. Thanks.

# Answer
> 0 votes
Tokens are just a representation of some other data structure that exists.

You can not convert an arbitrary value into a token. What you need to do is store the value and then define a token for that stored value using hook\_token\_info()/hook\_tokens().

I understand it's a per-user value, so the simplest option seems to define a field on the user entity, I don't quite understand why you don't just show that in the profile. Then you can easily access it as a token when using the token module.

---
Tags: 8, forms, tokens
---


# Question
Title: Common meta tag description for a particular content type
I am working with meta tag module in drupal8.I want to add common meta title and description for a particular content type.How can i do this?

# Answer
* Visit `/admin/config/search/metatag`
* Click on "+ Add default meta tags" button
* On the next page, select the content type or entity you want
* Define your defaults there
> 0 votes

---
Tags: 8, meta-tags
---


# Question
Title: How to add an sms:number link to a menu?
In Drupal 8.5, when you're adding a menu item, you can add a telephone number by setting the **Link** to `tel:1-555-555-5555`.

However, if you try to add an SMS link like `sms:1-555-555-5555`, it fails validation and says "The path 'sms:1-555-555-5555\` is invalid."

What's the easiest way to override this so that I can add an sms link to the menu?

# Answer
> 7 votes
On the `sites/default/services.yml`

There is an option called `filter_protocols`

Add `sms` to it.

If file is not available, copy the file from `default.services.yml` to `services.yml`

---
Tags: 8, navigation
---


# Question
Title: Convert integer retrieved from node field to uid?
I've created a rule that sends a push notification to a specific user when a certain content type node is published. That said, in order to specify which user receives the notification, the 'Send Push Notification to Specific User' rule requires that I type in an existing uid.

That said, I've pulled an integer from a content type field, and I want to set that integer as the uid to send the notification to (as the user receiving a notification changes often). Naturally, Drupal won't let me do that, even after I convert the retrieved string (numeral, e.g. 7) to an integer.

Is it possible to achieve this? I'm stumped.

# Answer
You have to fetch the User entity by ID using the value from the content type field without any conversion.
Then in the "Send Push Notification to Specific User" rule, you can use the ID from the fetched entity.
Not sure why you can't use the variable directly, but this is the case.
> 1 votes

---
Tags: 7
---


# Question
Title: How to get the length of a field collection array
I'm using Drupal 7 and want to get the length of the field collection array. How can I get it? Can someone provide the code snippet for that?

This is the code that prints the table.

```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN"
  "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language; ?>" version="XHTML+RDFa 1.0" dir="<?php print $language->dir; ?>">
  <head>

    <title></title>
    <?php print $scripts; ?>
    <?php if (isset($sendtoprinter)) print $sendtoprinter; ?>
    <?php print $robots_meta; ?>
    <?php if (theme_get_setting('toggle_favicon')): ?>
      <link rel='shortcut icon' href='<?php print theme_get_setting('favicon') ?>' type='image/x-icon' />
    <?php endif; ?>
    <?php print $css; ?>
  </head>
  <body>
    <h2 style="text-align:center;font-size:10px;"><?php print"||S.S.D.||"?></h2>
    <h1 style="text-align:center;font-size:15px;"><?php print"S.K. GASES ENTERPRISES"?></h1>
    <h1 style="text-align:center;font-size:15px;"><?php print"DEALERS OF ALL TYPES OF INDUSTRIAL GASES"?></h1>
    <h1 style="text-align:center;font-size:15px;"><?php print"Distributors of Co2 Wires,Stockist and Suppliers of Lubricant Oil"?></h1>
    <h2 style="text-align:center;font-size:10px;"><?php print"Shop No. A/2/6/H- Block, MIDC, Pimpri, Pune-18, Mob.:9970107350 / 9822622134 / 8180061976"?><br>
    <?php print"<br>GST No. 27ACUFS8251K1Z8         E-mail:skgases01@gmail.com"?><br>

    </h2>

    <?php if (!empty($message)): ?>
      <div class="print-message"><?php print $message; ?></div><p />
    <?php endif; ?>
    <?php if ($print_logo): ?>
      <div class="print-logo"><?php print $print_logo; ?></div>
    <?php endif; ?>

    <?php if (!isset($node->type)): ?>

      <h2 class="print-title"><?php print $print_title; ?></h2>

    <?php endif; ?>

    <table border="0px">
      <tr>
        <td colspan="2">
          <?php
          print render(field_view_field('node', $node, 'field_challan_no_', array('label'=>'inline'))); ?>
        </td>
        <td style="text-align:right;">
      <?php
         // print render(field_view_field('node', $node, 'field_date_usg', array('label'=>'inline')));
          $temp_field = field_get_items('node', $node, 'field_date_sales');
    if ($temp_field) {
            $field = check_plain($temp_field[0]['value']);
        }
        $newDate = date("d/m/Y", strtotime($temp_field[0]['value']));
    ?>
        <strong><?php print("Date:");?></strong> <?php echo $newDate;?>

        </td>
      </tr>
    <tr>
      <td colspan="2">
          <?php
          print render(field_view_field('node', $node, 'field_customer_name_ref', array('label'=>'inline'))); ?>
        </td>
        <td style="text-align:right; float:right;">
            <?php
          print render(field_view_field('node', $node, 'field_address', array('label'=>'inline'))); ?>
          </td>
      </tr>

      <tr>
        <td colspan="3">
          <strong>Filled Cylinder Details:</strong>
        </td>
      </tr>
      <tr><table border="1" style="border-color:black;">
       <td style="width:25%;">Cylinder No
       </td>
       <td style="width:25%;">Cylinder Type
       </td>
       <td style="width:25%;">Qty
       </td>
       <td style="width:25%;">
            Unit
       </td>
      </tr>
       <tr>
        <td colspan="4">
        <?php
              //$temp_field = field_get_items('node', $node, 'field_cylinder_info');
             $j=count(field_cylinder_info);
            for($i=0;$i<$j;$i++)
            {
                /*$x=$node->field_cylinder_info['und'][i]['value'];
                print $x;*/
                print render(field_view_field('node', $node, 'field_cylinder_info', array('label'=>'hidden')));
                print("<hr>");
            }?>

          </td>

      </tr></table>

      <table>
        <tr>
          <td  colspan="3" style="text-align:center;">
              <?php print("Recieved above mentioned Cylinders in good condition complete with CAPS as per terms and conditions printed overleaf<br>");?>
          </td>
        </tr>
      </table>

      <table border="1" style="border-color:black;height:">
            <tr>
            <td colspan="6">
              <strong>Empty Cylinder Details:</strong>
            </td>
          </tr>

          <tr>
              <th style="text-align:center;color:black;">Cylinder No.</th>
              <th style="text-align:center;color:black;">Quantity</th>
              <th style="text-align:center;color:black;">Cylinder No.</th>
              <th style="text-align:center;color:black;">Quantity</th>
              <th style="text-align:center;color:black;">Cylinder No.</th>
              <th style="text-align:center;color:black;">Quantity</th>
          </tr>

          <tr>
              <td height="10"></td>
              <td height="10"></td>
              <td height="10"></td>
              <td height="10"></td>
              <td height="10"></td>
              <td height="10"></td>
          </tr>
          <tr>
            <td height="10"></td>
              <td height="10"></td>
              <td height="10"></td>
              <td height="10"></td>
              <td height="10"></td>
              <td height="10"></td>
          </tr>
          <tr>
            <td height="10"></td>
              <td height="10"></td>
              <td height="10"></td>
              <td height="10"></td>
              <td height="10"></td>
              <td height="10"></td>
          </tr>
          <tr>
            <td height="10"></td>
              <td height="10"></td>
              <td height="10"></td>
              <td height="10"></td>
              <td height="10"></td>
              <td height="10"></td>
          </tr>
          <tr>
              <td height="10"></td>
              <td height="10"></td>
              <td height="10"></td>
              <td height="10"></td>
              <td height="10"></td>
              <td height="10"></td>
          </tr>
          <tr>
              <td height="10"></td>
              <td height="10"></td>
              <td height="10"></td>
              <td height="10"></td>
              <td height="10"></td>
              <td height="10"></td>
          </tr>

      </table>
      <table border="0px">
      <tr>

        <td colspan="2">
          <strong><?php print("Customer's Signature:");?></strong>
        </td>
        <td style="text-align:right;">

        <strong><?php print("For S.K. GASES ENTERPRISES");?></strong>

        </td>
      </tr>
      </table>
    </table>
  </body>
</html>

```

# Answer
You can find lenght of your field collection field by this code.

```
$node = node_load(1);
$items = field_get_items('node', $node, 'field_fc');
$length  = count($items);

```
> 2 votes

# Answer
Another alternative for you could be,

```
$nid = '123'; //nid of the node;
$node = node_load($nid);

$fc_field_name = 'fc_field_name'; //your fc field name
$length = count($node->{$fc_field_name}); //Your fc field name.

```
> 0 votes

# Answer
Its very simple:

```
  $items = count(field_get_items('node', menu_get_object(), 'FIELD_NAME'));
  print_r($items);

```

Hope, this will help you.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Remove "Main navigation " label from view source
I am working with drupal8. I want to prioritise the h,h2 nd h3 tags when checking view source for SEO purpose.I have "Main navigation" before h1 tag.Either i want to remove the below html or hide from the view source.Is it possible for me to solve this issue?

# Answer
Page structure is controlled by the theme you're using. It is possible to structure your HTML so that navigation comes after content in HTML source, even though it may appear to be visually "above" content (with the use of CSS).

You may want to change your templates and CSS to reorganize the order of things in your HTML, or use a theme that already does this out of the box.

You can completely remove the Block titles by entering `<none>` in the Block title configuration.

You can also change your theme output so Blocks don't use headings as their titles, although it's not clear how important that is for SEO.

There have been indications that if you have your main content properly structured with headings, having navigation before the content in HTML won't have negative consequences.

Related: Should block titles be \<h2\>?

How To Use H1-H6 HTML Elements Properly

D8: Cleanup HTML heading structure

How it started (D7): Navigation menus should be preceded by headings of the appropriate level (usually `<h2>`)
> 0 votes

---
Tags: 8
---


# Question
Title: Design views display and views filters separately?
Looking of the exported views code it looks like the code for the filters is usually in a separate section from the fields and their layout.

With that in mind I want to separate out the aspect of views which cover the selection of fields and their display from the design of the filters, so I can continue to improve the filters on one page, whilst designing the data selection and presentation on another. I would then merge them into a new view later.

Is something like this feasible? Of course that means when designing a view I should not remove any of the fields in the display view which are used in the filters.

# Answer
Views results (sometimes in Fields Format), Exposed Filters, Attachments are all output into their own HTML containers. But you can override each View output in templates (look under Theme: Information under Advanced View settings).

For whatever purpose you can create two different Views, or two Displays in the same View, define Fields in one, and define Filters in the other. Then later you can export both, combine and replace the relevant parts of the export into one and Import with an override of the existing View so you end up with a combined configuration.

But why would you want to separate them in the first place? You can add exposed Filters to a View, work on CSS to style them, then later add Fields and style them.

It isn't necessary to have the exact same Fields a in View that you want to use as Filters. Fields and Filters are independent. Maybe this is what has been tripping you up?

You can have Filters that filter out one Content type and also filter by creation date. While in Fields show Titles, Author and Taxonomy terms. A completely different set of information in those sections.

A lot of confusion may be coming from nomenclature. Views Displays are the different outputs you create according to your needs (Page Display, Block Display). Fields are bits of information defined in Content types. Views Results can be displayed as Fields. Filters control qualitatively what is shown in Views, if you expose them then users can change that themselves (Exposed Filters you usually see above Results that let you control the filters on the fly).
> 1 votes

---
Tags: 7, views, importing-exporting
---


title: Adding meta tag to a view

text:
# Question
Title: Adding meta tag to a view
I am working with Drupal 8. I want to add meta tags for title and description for a view. Is there any option?

# Answer
> 1 votes
1. Enable the Metatag Views module (part of Metatag)
2. Visit a View edit page
3. Configure your meta tags

---
Tags: 8, meta-tags
---


# Question
Title: How to use hook_form_alter in the .theme file to alter the form fields?
I need to know how to use hook\_form\_alter in .theme file as i have to alter the form fields related to user\_register\_form.

I tried putting the below code in the .theme file but it does not even reach the function

```
/**
 * Implements hook_form_alter().
 */
function hook_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  // Adding custom validation for the welcome page type field.
  if ($form_id == 'user_register_form') {
     print_r('Reaching in here');exit;
  }
}
```

# Answer
If you want to alter a specific form, and you know the ID, use `hook_form_FORM_ID_alter()` rather than the generic version:

```
function THEMENAME_form_user_register_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Add alterations specific to the user registration form
}

```

Make sure you clear the cache after renaming the function.
> 1 votes

---
Tags: forms, hooks
---


title: Condition on $user_storage

text:
# Question
Title: Condition on $user_storage
I am using the following code.

```
  $user_storage = \Drupal::service('entity_type.manager')->getStorage('user');

    $ids = $user_storage->getQuery()
      ->condition('status', 1)
      ->condition('roles', 'directeur_cr_')
      ->execute();
    $users = $user_storage->loadMultiple($ids);

```

I want to add a condition that is verified when the role is *directeur\_cr\_* or *comptable\_cr\_*.

How can I add this condition?

# Answer
You can use orConditionGroup, but the IN operator is a shorthand for OR conditions on the same field:

```
->condition('roles', ['role1', 'role2'], 'IN')

```
> 2 votes

# Answer
You can do like this:

```
  $user_storage = \Drupal::service('entity_type.manager')->getStorage('user');

    $ids = $user_storage->getQuery()
      ->condition('status', 1)
      ->condition('roles', array('directeur_cr_','comptable_cr_'),'IN')
      ->execute();
    $users = $user_storage->loadMultiple($ids);

```
> 1 votes

---
Tags: 8, database
---


# Question
Title: How can I render multiple values which belong to the same field?
I have a content type with a text field "Person", which assumes up to 3 possible options. I am trying to render a block, where I would display this field with three presons.

```
if(\Drupal::routeMatch()->getRouteName() == 'entity.node.canonical'){
  $node = Node::load(\Drupal::routeMatch()->getRawParameter('node'));
  if($node->bundle() == "people"){

    // CONTACT
    $render = array();
    if($field = $node->field_contact_person->first()){
      $field = $field->getValue()['value'];
      $render['#markup'] = '<div>'.$field.'</div>';
      $render['#prefix'] = '<div class="block institution"><h3>'.$this->t('Contact person').'</h3>';
      $render['#suffix'] = '</div>';
      $block['#markup'] .= render($render);
    }

  }
}

```

The issue is that it fetches only first value. How can I fetch all values and render them in the block?

# Answer
Just don't use `first()` \- that gets the first item.

```
if ($field = $node->field_contact_person) {
  foreach ($field->getValue() as $value) {
    $item_value = $value['value'];
  }
}

```
> 1 votes

---
Tags: views, 8
---


# Question
Title: "InvalidArgumentException: Field field_participant_email is unknown" although it exists
We're working on a custom module where we are creating participant content types programatically. We then have some queries to check for where a participant exists.

However although the field `field_participant_email` exists and is defined, the below code results in the error `InvalidArgumentException: Field field_participant_email is unknown`.

```
$query = \Drupal::entityQuery('node');
$query->condition('type', 'participant');
$query->condition('field_participant_meeting', $meeting_id);
$query->condition('field_participant_email', $email);
$ids = $query->execute();

```

We've tried clearing cache, deleting and re-adding the field to no avail.

Does anyone have any suggestions or experiencing with this type of issue?

Much appreciated.

**Update 1**

For clarity, I've also checked the following:

* checked the spelling of the field
* deleted all the content types and reinstalled them through features
* tried `$query->condition('field_participant_email_value', $email);`
* tried `$query->condition('field_participant_email.value', $email);`

**Update 2**

Looking into the `core/lib/Drupal/Core/Entity/Query/QueryInterface.php` interface documentation, it seems that adding a condition against a custom field is not supported. This would explain why the error occurs. However I'm yet to find an alternative. I've also experienced the same error when trying to set the value of the field `$node->set('field_participant_email', 'name@domain.com');`.

# Answer
> 0 votes
The syntax for the field condition(s) is missing a column name (and potentially an operator)

`$query->condition('field_participant_email.value', $email, '=');`

Here is a useful tutorial on Entity Queries for Drupal 8 I always refer to:

The Drupal 8 version of EntityFieldQuery

---
Tags: 8
---


# Question
Title: What's the workflow behind [user:display-name] token?
I have seen in an email template, a token named **\[user:display-name\]**. Further noted that this token is not global, its value will only get rendered in email templates (correct me if I'm wrong).

How these specific tokens specially designed for only email tokens have been created?

In which file its logic is been written, I'm so curious, as the current user does not store any value of email receiver to whom email has to be sent. Then from where it picks the value of display name when current user is sending mail.

# Answer
> 2 votes
As Clive said, the tokens are generated from `hook_token_info()` and `hook_tokens()`. For the `User` entity, those hooks are implemented from the *User* module. Token values aren't available just for email templates, but for every function/method that uses the *token* service. For example, in a controller, I could use code similar to the following one.

```
$bubbleable_metadata = new BubbleableMetadata();
$build['#markup'] = $this->tokenService->replace('Tokens: [node:nid] [current-user:uid]', ['node' => $node], [], $bubbleable_metadata);
$bubbleable_metadata->applyTo($build);

```

As for getting the display name of a user account, that is easy: When user tokens are generated, `user_tokens()` gets a user object; calling `User::getDisplayName()` on that user object returns its display name.
See the code used from `user_tokens()`; in particular, see the following code. (Comments are mine.)

```
// Retrieves the user object passed to the hook.
$account = $data['user'];

```

```
// Generates the value for the display name token.
$replacements[$original] = $account
  ->getDisplayName();
if ($account->isAnonymous()) {
  $bubbleable_metadata->addCacheableDependency(\Drupal::config('user.settings'));
}

```

It is true there are user tokens available only for email templates, but that are generated from a callback used when replacing tokens in email templates. See `user_mail()` and `user_mail_tokens()`.

```
  // user_mail()
  $token_service = \Drupal::token();
  $language_manager = \Drupal::languageManager();
  $langcode = $message['langcode'];
  $variables = ['user' => $params['account']];
  $language = $language_manager->getLanguage($params['account']
    ->getPreferredLangcode());
  $original_language = $language_manager->getConfigOverrideLanguage();
  $language_manager->setConfigOverrideLanguage($language);
  $mail_config = \Drupal::config('user.mail');
  $token_options = [
    'langcode' => $langcode,
    'callback' => 'user_mail_tokens',
    'clear' => TRUE,
  ];
  $message['subject'] .= PlainTextOutput::renderFromHtml($token_service
->replace($mail_config->get($key . '.subject'), $variables, $token_options));
  $message['body'][] = $token_service
    ->replace($mail_config->get($key . '.body'), $variables, $token_options);

```

```
function user_mail_tokens(&$replacements, $data, $options) {
  if (isset($data['user'])) {
    $replacements['[user:one-time-login-url]'] = user_pass_reset_url($data['user'], $options);
    $replacements['[user:cancel-url]'] = user_cancel_url($data['user'], $options);
  }
}

```

`user_mail()` says to `Token::replace()` that `user_mail_tokens()` must be called after all the tokens are generated, and `user_mail_tokens()` replaces *\[user:one-time-login-url\]* and *\[user:one-time-cancel-url\]* (not replaced from `Token::replace()`) with the right values.

Similar code can be used from any module to generate tokens that must be available only in specific context.

# Answer
> 1 votes
> its value will only get rendered in email templates

Not true, that token is available any time the system gathers token for the user entity type.

> How these specific tokens specially designed for only email tokens have been created?

As mentioned they're not just for emails, but they're defined in `user_token_info()`, and generated in `user_tokens()`.

> Then from where it picks the value of display name when current user is sending mail.

The token hook has access to the user account, so it simply uses `$account->getDisplayName();` to populate the data.

---
Tags: 8, users, tokens
---


title: View, flag, and followers

text:
# Question
Title: View, flag, and followers
I have a user flag that is called "follow" and am trying to setup the following views in Drupal 8.

I want to create 3 views for my website's user profile pages:

1. A list of users flagged by a user (for example, a "people I'm following" block)
2. A list of users flagging a user (for example, a "my fans" or "my followers" block)
3. A list of nodes from all the users that have been flagged by a user (for example, a news feed for nodes created from the users a user flagged)

This has been done before for older versions of Drupal (see View of users flagged by a user, users flagging a user, and nodes from users flagged by a user), but I can't get it to work on Drupal 8 because many of the fields are different.

Even after playing around with different values, I can only get to the point where I display the users the currently logged-in user is following, but that is not what I need.

How do I get a list of users flagged from a user account when I am watching its profile?

# Answer
Whether you're creating content or user Views, you have to add the Flags Relationship (**User flag** in your case). This is the first step to introducing the flags information into the Views, and in most cases you'll want to set that Relationship to **Any user**, and use Contextual filters to restrict the results to your needs.

## List users flagged by a user

This answers your first question, a page you can add to user profile pages (as a Drupal tab for example).

1. Create user Views, Page Display
2. Add the **User flag** Relationship and configure it:
Include only flagged content
Follow
Any user
3. Add the Contextual filter **User ID** from the **Flagging** category (not the `User` Category!) and configure it:
It will use the Flags Relationship by default
`When the filter value is NOT in the URL`
Show "Page not found"
`When the filter value IS in the URL or a default is provided`
Specify validation criteria
User ID
4. Change the Path to `user/%user/flags`
5. Add a Menu tab if you wish to show on user profiles
6. Add No results behaviour `This user is not following any others.`
7. Add a Field **Created** from the Flagging Category to show when the flagging occured.

When you visit a person's page you'll see a list of users they follow.

## List followers of a user

1. Duplicate the Page from above
2. Override the Contextual filters, remove the flagging one, and add **User ID** Contextual from the **User** Category and configure like the one above
3. Change Path to `user/%user/followers` and Menu tabs
4. Adjust the Title, No results text etc.
5. Override Fields, remove the Name (it will always show the user who's page you're viewing so it's redundant)
6. Add a Field **User ID** from **Flagging** Category (Label it `Who flagged`)

## List content from users that are Followed

1. Duplicate the first Page from above (List users flagged by a user)
2. Add a new Relationship **Content authored** from the User Category, require it so you don't see people in the results that haven't authored any content
3. Edit the Path to `user/%user/flags/content` or whatever makes sense to you, add the Menu tab
4. Override the Fields and add the **Title** Field from Content Category
5. Remove the Field showing the date when Flag was created
6. You can Group by user Name under Format, to group Content by authors if you like

You can create Blocks instead of Page using similar logic, just configure the Contextual filters to react to use a default value from context, when it's not in URL.
> 8 votes

---
Tags: views, 8, flags
---


title: How are hooks implemented?

text:
# Question
Title: How are hooks implemented?
Are hooks a thing in their own right, or are they actually implemented as events under the hood?

# Answer
> 2 votes
Hooks aren't Symfony events. They are PHP functions with a specific name that Drupal calls in very specific cases.

For example, `hook_cron()` is invoked when Drupal cron tasks are executed, from `Cron::invokeCronHandlers()`, which uses the following code.

```
  // Iterate through the modules calling their cron handlers (if any):
  foreach ($this->moduleHandler
    ->getImplementations('cron') as $module) {
    if (!$module_previous) {
      $logger
        ->notice('Starting execution of @module_cron().', [
        '@module' => $module,
      ]);
    }
    else {
      $logger
        ->notice('Starting execution of @module_cron(), execution of @module_previous_cron() took @time.', [
        '@module' => $module,
        '@module_previous' => $module_previous,
        '@time' => Timer::read('cron_' . $module_previous) . 'ms',
      ]);
    }
    Timer::start('cron_' . $module);

    // Do not let an exception thrown by one module disturb another.
    try {
      $this->moduleHandler
        ->invoke($module, 'cron');
    } catch (\Exception $e) {
      watchdog_exception('cron', $e);
    }
    Timer::stop('cron_' . $module);
    $module_previous = $module;
  }

```

A module whose machine name is *spam\_checker* could implement this hook adding the following function to its code.

```
function spam_checker_cron() {
  // Delete the nodes from the list of nodes to check after 96 hours are passed.
  Drupal::database()
    ->delete('spam_checker_list')
    ->condition('timestamp', REQUEST_TIME - 3600 * 96, '<')
    ->execute();
}

```

# Answer
> 1 votes
They're not events (think you have symfony in mind), they are called like here in EntityStoreBase:

```
// Call hook_TYPE_load().
foreach ($this->moduleHandler()->getImplementations($this->entityTypeId . '_load') as $module) {
  $function = $module . '_' . $this->entityTypeId . '_load';
  $function($entities);
}

```

# Answer
> 1 votes
To put it simply, I would say the *hook system* is a naming convention that allows you to extend the Drupal functionalities.

The core of the implementation is something like this:

```
// $vars is an array with the basic page variables that Drupal provides.
$hook = 'preprocess_page';
for ($modules as $module) {
  call_user_func_array("${module}_${hook}", $vars);
}
// Now, $vars could have new variables or a number of modifications.
// You have effectively tampered the default workflow,
// without changing the code in the Drupal Core.

```

**Hooks as a Software Engineering Design Pattern**

According to the Drupal 4 Documentation (Programming from an Object-Oriented Perspective) Hooks are the procedural equivalents of the Abstraction and Inheritance OOP Concepts and the Decorator, Observer and Command Design Patterns.

This view seems to be well accepted:

Other sources say the *Hooks are an implementation of the Mediator pattern*. Mediator pattern Hooks vs. Events

**Object Oriented Programming is the Future, not Hooks**

Implementing a Form, Block or Content Entity is easier and cleaner with the new Object Oriented model in Drupal 8. The related hooks were removed.

Some other removed hooks are: hook\_watchdog, hook\_boot, hook\_init, and hook\_exit.

Related Issues and links:

---
Tags: 8, hooks, event-subscribers
---


# Question
Title: Unable to remove label field from the registration form
I am unable to remove the label from a form element of the registration form.

I have:

* Enabled the kint module for debugging
* Implemented `hook_form_alter()` and tried to change the form variables

```
function drupalfresh_form_user_register_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  kint($form);
  $form['field_company_name']['#attributes']['widget'][0]['#title'] = t('');
}

```

This doesn't change the form.

This is how the form element appears.

>

# Answer
You try the code below:

```
$form['field_company_name']['widget'][0]['value']['#title']='';

```
> 0 votes

# Answer
Actually the can be changed using this code:

`$form['field_company_name']['widget'][0]['value']['#title'] = $this->t('WHATEVER');`
> 1 votes

---
Tags: forms
---


# Question
Title: media entity browser base view is missing
What happened to the base view for Media Entity Browser?

Following this tutorial:

https://www.easternstandard.com/blog/2017/12/drupal-media-bundles-media-browser-cropping

I made all the changes since Media Entity is now in core, but I googled and could no mention of what happened to Media Entity Browser. Is it now in core too?

# Answer
> 0 votes
No, the Media Entity Browser is still in contrib. If you are using core media then use the 2.x branch, see https://www.drupal.org/project/media\_entity\_browser. If this is only about the question in the title, see Revert views missing. Any workarounds? how to import a View from a module folder. If the View is missing you don't need to look for the UUID of the existing View.

---
Tags: views, 8
---


# Question
Title: Managed File is stuck with a temporary URI, even after saving it as permanent file
I was having this problem: Files uploaded via custom configuration form are eventually lost.

So, I used the solution, basically:

```
$file->setPermanent();
$file->save();

```

But then, even thou `$file->isTemporary()` is `FALSE`, the URI and URL seem to indicate that the file is still temporary:

URI: `$file->getFileUri()` yields `temporary://filename.jpg`

URL: `file_create_url($file->getFileUri())` yields `/system/temporary?file=filename.jpg`

# Answer
You need to mark file as "used", there is `file.usage` service for that, you can do it by next code: `\Drupal::service('file.usage')->add($file)`, but after removing file from config or changing it by another file don't forget to remove file usage by `\Drupal::service('file.usage')->delete($file)`, otherwise file would not be removed from file system.

In drupal 8.3 default behavior about unused files was changed and by default all unused files should not be deleted, until variable `make_unused_managed_files_temporary` is true.
> 1 votes

---
Tags: 8, files
---


title: Using multiple parameters in Forena

text:
# Question
Title: Using multiple parameters in Forena
I'm trying to pass multiple parameters from one Forena report to another one. Currently my link looks like this:

```
reports/aen_multi?startdate={eventdate}&enddate={eventdate}

```

but this does not work ("Invalid or malformed report document").

For links with only one parameter this works:

```
reports/aen_multi?startdate={eventdate}

```

What is the correct way of linking to a report with several parameters?

# Answer
After searching a lot more, I came across this discussion which shows that `&` needs to be encoded as `&`. So the working link is:

```
 reports/aen_multi?startdate={eventdate}&enddate={eventdate}

```

I'll leave the question up as this might help others.
> 1 votes

---
Tags: 7, forena
---


title: conditional visible form field

text:
# Question
Title: conditional visible form field
How can i make the second field visible depending on the value selected in the first field ?

i have tried this but it does not work :

```
 $form['call-to-actions-widget']['call-to-actions-widget_select'] = [
      '#type' => 'select',
      '#title' => $this->t('widget options'),
      '#description' => $this->t('choisir un widget'),
      '#options' => [
        'none'=>$this->t('none'),
        'year_navigation' => $this->t('exposed filter :year'),
        'row_max_unset' => $this->t('more publications ( block refresh )'),
        'internal_link' => $this->t('more publications ( internal link )'),
      ],
      '#default_value' => (!empty($config['call-to-actions-widget_select'])) ? $config['call-to-actions-widget_select'] : 'none'
    ];

    $form['call-to-actions-widget']['internal_link'] = [
      '#type' => 'textfield',
      '#title' => $this->t('internal link'),
      '#description' => $this->t('de type /node/56'),
      '#default_value' => (!empty($config['internal_link'])) ? $config['internal_link'] : ''
    ];

    $form['call-to-actions-widget']['internal_link']['#states'] = [
      'visible' => [
        [
          [':input[name="call-to-actions-widget_select"]' => ['value' => 'internal_link']]
        ],
      ],
    ];

```

# Answer
> 1 votes
Try this

```
$form['call-to-actions-widget']['internal_link']['#states'] = [
  'visible' => [
    ':input[name="call-to-actions-widget_select"]' => ['value' => 'internal_link'],
  ],
];

```

In case when it doesn't work use another selector

```
':input[name="call-to-actions-widget[call-to-actions-widget_select]"]'

```

Or check in the browser name of the needed field. See e.g. where the name is password\[pass1\]

---
Tags: 8
---


# Question
Title: How does a PaymentGateway signal a completed order
I'm trying to implement the Commerce Ingenico payment gateway for a Drupal 8 Commerce site. As this module is still in unfinished for Drupal 8, I'm fixing it up as I go. Most of the implementation is located in Composer packages, so it's mostly plumbing.

I'm hitting a bit of a wall now though. I'm using the off-site payment gateway, and I've configured the IPN (server to server notification). The values for the payment in the database look good\*, but the Cart never turns into an Order. Somehow the trigger for signaling a completed payment to the order is missing.

The results is that after returning from the offsite payment (and the onNotify has already been triggered, so the payment is marked as completed), I end up back at the start of the payment flow; the order summary.

How are these parts supposed to fit together?

Here's the code to the onNotify method in the PaymentGateway:

```
public function onNotify(Request $request) {
    parent::onNotify($request);

    // Common response processing for both redirect back and async notification.
    $payment = $this->processFeedback($request);

    // Let's also update payment state here - it's safer doing it from received
    // asynchronous notification rather than from the redirect back from the
    // off-site redirect.
    $state = $request->query->get('STATUS') == PaymentResponse::STATUS_AUTHORISED ? 'authorization' : 'completed';
    $payment->setState($state);
    $payment->setAuthorizedTime(REQUEST_TIME);
    if ($request->query->get('STATUS') != PaymentResponse::STATUS_AUTHORISED) {
      // setCapturedTime has been relegated to the mists of history
      $payment->setCompletedTime(REQUEST_TIME);
      // $payment->setCapturedTime(REQUEST_TIME);
    }
    $payment->save();
  }

```

And this is the resultant row in the commerce\_payment table:

```
 payment_id
13

type
payment_default

uuid
payment_default

payment_gateway
ogone_offsite

payment_gateway_mode
test

payment_method
NULL

order_id
29

remote_id
3039111240

remote_state
9

amount__number
26.400000

amount__currency_code
EUR

refunded_amount__number
0.000000

refunded_amount__currency_code
EUR

state
completed

authorized
1534516744

expires
0

completed
1534516744

test
NULL

captured
NULL

```
* Of course I don't know what these values are supposed to look like. I'm actually a little concerned about payment\_method being NULL in this row. Is that normal for an offsite payment gateway, or should that be set to something?

# Answer
A similar scenario has been discussed on #commerce Slack on Monday. In contrast to `onReturn()` no transition is triggered after `onNotify()`.

@bojanz says:

> it's a safeguard we'll need to add to Commerce, but won't have the resources to do so before october
>
> once we have $order-\>balance and an order paid in full event, we can use it to auto-place the order
>
> at least those two parts could land in september for 2.10

---

TL;DR

`onReturn()` must create a Payment, as suggested in a comment from @No Sssweat. In case `PaymentGatewayException` is thrown Commerce will redirect to the previous checkout step. `onNotify()` can register info about payment but, at the current state, it won't **place** the order for you.
> 1 votes

---
Tags: 8, commerce
---


# Question
Title: How to use drupal_write_record for updating a custom table?
I am using the following code to add rows to a custom table used from the module I created.

```
$my_query = db_query("SELECT to_date FROM table_name where to_date = '$to'");
$num_of_results_service = $my_query->rowCount();
if ($num_of_results_service == 0) {
  try {
    $result1 = drupal_write_record('table_name', $value_array[$proj_title]);
    drupal_set_message('data saved successfully.');
  }
  catch(Exception $e) {
    echo 'Message: ' .$e->getMessage();
  }
}
else{
  // Code to update the table.
}

```

How can I update a row of that database table?

# Answer
> 0 votes
You need to pass in a 3rd parameter if you want to update the record: https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal\_write\_record/7.x

So thats a $primary\_keys array with the column names in your table you want it to match against so in your case you might need to pass "to\_date" which would update all rows that have the same $to value you're using

# Answer
> 0 votes
I used db\_update although it is bit lengthy and it solved my problem. The code is as follows,

```
$entry = db_update('table_name')
  ->fields(array(
  'column_name' => $variable1,
  'column_name2' => $variable2,
  ))
  ->condition('column_name', $variable, '=')
  ->condition('to_date', $newDate, '=')
  ->execute();
drupal_set_message('Data updated successfully.');

```

It worked and I Hope this helps someone.

---
Tags: 7, database
---


# Question
Title: How to load a library only once, or how to check if a library has been loaded?
I am making an asynchronous single page application in Drupal 8. So far everything is working nicely. However, it has a lot of libraries that are needed for a lot of different things, depending on what the user decides to do.

The libraries are different depending on which content type is loaded. I want to only load the library ONCE when a user loads a content type for the first time.

Using the below code the library is attached every time the content type gets loaded. Leading to multiple instances of each library.

```
function mytheme_preprocess_node(&$variables) {
    $node = $variables['node'];
    switch($node->getType()){
        case 'nodeone':
            $variables['#attached']['library'][] = 'mytheme/liba';
            break;
        case 'nodetwo':
            $variables['#attached']['library'][] = 'mytheme/libb';
            break;
        case 'nodethree':
            $variables['#attached']['library'][] = 'mytheme/libc';
            break;
        default:
            break;
    }
}

```

I can't do a preproccess\_**page** as the content types are loaded asynchronously and would imply loading everything at once. I can't attach the library to the twig template as again, it happens at the node level, not the page. I have tried to attach the library to a view template, but the same issue remains, it gets loaded multiple times.

If I could do some form of check to see if the library has already been loaded, I think that would be sufficient.

# Answer
EDIT: Sorry didn't see you were doing it via AJAX, my below example might not be the same. But the theory of the JS triggering multiple times rather than the actual files loading might still be valid

I don't think it's the piece of code you've showed is causing your issue. Is the library files definitely getting loaded multiple times into the source code? Or is it that the effects of the library are happening multiple times? (e.g. a JS being trgiggered multiple times) as thats a different issue

Drupal handles this situation and when it aggregates all the required libraries so any duplicates are removed. For example I'm just working on a news listing page that has 10 nodes coming out and just replicated your code to print "hi" add a library and the "hi" comes out 10 times but the library files only once
> 1 votes

---
Tags: 8, ajax
---


title: Alter admin theme

text:
# Question
Title: Alter admin theme
I would like to make a small change in the `admin/structure/taxonomy/` page.

I need to add one more operation to the edit button on the page.

Its the `template_preprocess_links()` function I need to alter I believe. I have created a sub theme of the admin theme (Seven). Set it default admin theme. Created `mytheme_preprocess_links()` function but it does not run.

Any ideas?

# Answer
> 3 votes
To add/alter entity operations you can use `hook_entity_operation_alter`:

```
function hook_entity_operation_alter(array &$operations, \Drupal\Core\Entity\EntityInterface $entity) {

  if ($entity instanceof \Drupal\taxonomy\TermInterface) {
    $operations['foo_operation'] = [
      'title' => 'Foo',
      'url' => \Drupal\Core\Url::fromRoute('bar', ['taxonomy_term' => $entity->id()]),
      'weight' => 10,
    ];
  }
}

```

---
Tags: 8, theming
---


# Question
Title: Adding a delete button to node edit form
I need to add a delete button to a node edit form, so in case I open a edit form of the node I want to have a possibility to delete it as well. This edit node form is genereted from a view using *Link to edit Content* and displayed in modal window, which adds the following markup to the page.

```
<a href="/node/597/edit" class="use-ajax" data-dialog-type="modal" >Link to edit node</a>

```

How can I programmatically achieve this in Drupal 8?

# Answer
There is a "Delete" Link right to the "Save" Button. If you can't see it, you're missing the "delete content of type x" permission. If you need the Link styled as button, use the matching css classes of your theme.
> 1 votes

---
Tags: 8, forms
---


# Question
Title: Rest File upload octet-stream uploaded file is corrupted
I use rest to post upload file (no file\_entity, but core file) following direction in https://www.drupal.org/project/drupal/issues/1927648

In the app I use FileRider to get file binary for post body.

```
  reader.onload = () => {
    let data = reader.result;
    let file_name = event.target.files[0].name;

    this.rest.postFile(uri, data, file_name).subscribe(res => {
      this.saved_file = res;
    });

  }

  reader.readAsBinaryString(event.target.files[0]);

```

post uri

```
  let uri = `/file/upload/${entity_type_id}/${bundle}/${field_name}?_format=json`;

```

rest.postFile is

```
  postFile(uri: string, file: File, filename) {
    return this.http.post(`${this.api_endpoint}${uri}`, file, {
      headers: new HttpHeaders()
        .set('Content-Type', 'application/octet-stream')
        // Content-Disposition:file;filename="example.txt"
        .set('Content-Disposition', `file;filename="${filename}"`)
        .set('api-key', this.api_key)
    });
  }

```

File is uploaded and saved in proper place set in bundle field. File object is properly set filename, mimetype, status, uri and saved in drupal. The file itself is saved with a proper filename, size, mimetype application/octet-stream which cause system it is corrupted.

```
  $ file -i file-name.png
  file-name.png: application/octet-stream; charset=binary

```

The same is for .docx, .pdf, .txt, .jpg - all files are uploaded, saved and attached to node (and changes staus to true), but they are corrupted - $ file -i show filename.png: application/octet-stream; charset=binary

What also I miss?

Environment:

xubuntu-16.04 latest

Apache/2.4.34 (Ubuntu)

PHP Version 7.2.9-1+ubuntu16.04.1+deb.sury.org+1 FPM/FastCGI

Drupal-8.5.6 patch applied https://www.drupal.org/project/drupal/issues/1927648?page=1#comment-12685734, patch link https://www.drupal.org/files/issues/2018-07-13/1927648-581.patch

# Answer
> 0 votes
All work as expected when 'data' is file = event.target.files\[0\] No need of FileRider.

---
Tags: files, 8
---


# Question
Title: Is there a way to provide theme name suggestion for form elements?
I'm trying to look for a way to modify the markup for a form element without touching the default theme/template. Upon checking the source code, Drupal does not seem to recommend any theme suggestions for editing form elements. I have multiple views using the same field on the exposed filter. If I try to edit the form-element-label.html.twig it will affect all of the elements with the same field.

```
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'form_element_label' -->
<!-- BEGIN OUTPUT from 'themes/iom/templates/layout/form-element-label.html.twig' -->
<label for="edit-field-themes-target-id" class="label">Themes</label>
<!-- END OUTPUT from 'themes/iom/templates/layout/form-element-label.html.twig' -->

```

# Answer
> 2 votes
Seems you have to implement two hooks. One to add the suggestion, and one to define a template. `hook_theme_suggestions_HOOK_alter` and `template_preprocess_form_element` (aka `hook_preprocess_HOOK`).

```
/**
 * Implementation of hook_theme_suggestions_form_element_alter().
 */
function MYTHEME_theme_suggestions_form_element_alter(array &$suggestions, array $variables) {
  if (\Drupal::service('path.current')->getPath() == '/user/login') {
    $suggestions[] = $variables['theme_hook_original'] . '--user-login';
  }
}

/**
 * Implementation of hook_preprocess_form_element().
 */
function MYTHEME_preprocess_form_element(&$variables, $hook, &$info) {
  $info['template'] = 'form-element--user-login';
}

```

---

Source: Form element template suggestion has no effect.

---
Tags: 8, theming, forms
---


# Question
Title: How can I sort a view based on a date value in a multi-value paragraph reference field?
I have a custom entity type that uses an entity reference revisions field that accepts multiple values. The referenced paragraphs contain a date field. I would like to sort the entities (descending) by the most recent date in a paragraph referenced from their fields. E.g.:

* Entity 1

+ Paragraph 0
        - Date: 1/1/2016
    + Paragraph 1
        - Date: 1/1/2017
    + Paragraph 2
        - Date: 1/1/2018
* Entity 2

+ Paragraph 0
        - Date: 2/1/2017
    + Paragraph 1
        - Date: 2/1/2018
* Entity 3

+ Paragraph 0
        - Date: 3/1/2016
    + Paragraph 1
        - Date: 3/1/2017

...should sort to: Node 2, Node 1, Node 3.

Thanks!

# Answer
Sounds like you need to do a relationship to the paragraph reference field on your node. Which will then open up the fields on the paragraph into views. Then you might need to turn the field aggregation on in your view and add a sort on your date field selecting the MAX value
> 1 votes

---
Tags: views, 8, paragraphs
---


# Question
Title: How do I redirect users and show a message?
I want to redirect users with `RedirectResponse` and display a message, but the message is not displayed.

```
$response = new RedirectResponse($url);
$response->send();

```

After little debugging I found that my initial (source) URL is loaded twice, and the messages (added with `drupal_set_message()`) are removed from the session in `drupal_get_messages()`. So I have no messages on my target `$url`.

How can I achieve this?

I'm doing it in `hook_field_widget_form_alter()`.

# Answer
After some investigation I have found that I should interrupt script right after the response. You should be very careful with this approach, because it can break some important actions.

```
$response = new RedirectResponse($url->toString());
$response->send();
exit;

```
> 2 votes

# Answer
Set the repeat parameter in `drupal_set_message()` to TRUE and it will work:

```
$response = new RedirectResponse($url);
$response->send();
drupal_set_message(t('My message after redirect'), 'status', TRUE);

```
> 7 votes

# Answer
I would say that the solution, is not to send the response yourself but in your return.

```
return $response;

```
> 4 votes

# Answer
I had this same issue, but using an exit to end the script is not a good idea. Drupal has shutdown functions that it runs at the end of a page load which can be important. Instead I just had to return the redirect response directly:

```
public function buildForm(array $form, FormStateInterface $form_state) {
  $wizard_data = $form_state->getTemporaryValue('wizard');

  if (empty($wizard_data['csv_data'])) {
    drupal_set_message($this->t('Please upload a file first.'), 'error');
    return $this->redirect('my.route')->send();
  }

```
> 3 votes

# Answer
Works for me inside Controller callback. Should not use send(), but just return RedirectResponce object.

```
drupal_set_message(t('Please log in or create new account.'));
$url = Url::fromRoute('user.login');
$response = new RedirectResponse($url->toString());
return $response;

```
> 2 votes

# Answer
**Redirect:**

```
use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\RedirectResponse;

$url = Url::fromUri('internal:/');
$response = new RedirectResponse($url->toString());
$response->send();

```

**Messages using static service:**

`\Drupal::messenger()->addStatus($message);`

**Other equivalents:**

`addMessage()`
`addError()`
`addWarning()`

**References:**

RedirectResponse
Url
Drupal::messenger
MessengerInterface
> 2 votes

# Answer
Don't use send() function, just return $response and it works.

```
$response = new RedirectResponse(\Drupal::url('user.login'));
// $response->send();
return $response;

```
> 1 votes

# Answer
Recreate the logout functionality. It's just calling `user_logout()` function.

For this, I create:

**A method in `SomeController`**

```
public function logout() {
  user_logout();
  return $this->redirect('<front>', [], ['query' => ['logout' => 1]]);
}

```

**An event subcriber, subscribe to `KernelEvents::REQUEST`**

```
$queryLogout = \Drupal::request()->query->get('logout');
if (!empty($queryLogout) && $queryLogout == 1) {
  drupal_set_message("You are logged out");
}

```

**A router subcriber, altering user.logout route's controller**

```
protected function alterRoutes(RouteCollection $collection) {

  // Change controller who handle logout.
  if ($routeLogout = $collection->get('user.logout')) {
    $routeLogout->setDefault('_controller', '\Drupal\my_module\Controller\SomeController::logout');
  }
}

```
> 0 votes

---
Tags: 8, redirection, status-messages
---


# Question
Title: Help solve this error: Class CommerceLicenseEntityController does not exist
When I install the Commerce Licence module, in D7, I get this error. I think it might have to do with my Drupal installation, I'm not sure. What steps can I take to find out what causes this?

The whole warning texts is (2 warnings):

```
Warning: class_implements(): Class CommerceLicenseEntityController does not exist and could not be loaded in entity_entity_info_alter() (line 1480 of /data/disk/o1/distro/002/drupal-7.54.2-dev/sites/testsite.com/modules/entity/entity.module).

Warning: in_array() expects parameter 2 to be array, boolean given in entity_entity_info_alter() (line 1480 of /data/disk/o1/distro/002/drupal-7.54.2-dev/sites/testsite.com/modules/entity/entity.module).

```

# Answer
The error I got was a bit different, so this may not work for you. My error was

```
Exception 'ReflectionException' with message 'Class CommerceLicenseFile does
not exist' in [filepath]/entity_bundle_plugin.module:46

```

I disabled the Commerce License module and renabled it. I can now clear cache without error. Hope that works for you if you have not solved the problem.
> 0 votes

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


# Question
Title: Add a condition to show menu link in YML
how should I do if I need to show to a link menu based on a condition ?

This is my YML for my menu link :

```
double_vue_klesia.backuserswitch:
  title: 'Retour user précédent'
  menu_name: navigation-principale
  description: 'Switch back to your user account.'
  route_name: double_vue_klesia.backuser.switch
  weight: 1

```

I want to show this link only :

```
if (\Drupal::service('userswitch')->isSwitchUser())

```

This is in PHP, but I need this to be on YML (unless there a way to intercept it in php and hide it ?).

If my isSwtichUser is true (from my service), I want to show the link. But I can find a way to do it.

EDIT :

I'm using this module : https://www.drupal.org/project/userswitch

I "just" need to display a link to go back to the original user (link accessible from my frontend)

# Answer
you can add custom access on route\_name: double\_vue\_klesia.backuser.switch

```
double_vue_klesia.backuser.switch:
  path: '/path-of-you'
  defaults:
    _form:  '\Drupal\my_module\Form\DemoForm'
    _title: 'title'
  requirements:
    _custom_access: '\Drupal\my_module\Controller\ApplicationController::accessCustom'

```

Inside \Drupal\my\_module\Controller\ApplicationController:

```
 /**
   * Check user has permission.
   *
   * @return \Drupal\Core\Access\AccessResult
   */
  public function accessCustom() {
    if (if (\Drupal::service('userswitch')->isSwitchUser())) {
      return AccessResult::allowed();
    }
    return AccessResult::forbidden();
  }

```
> 2 votes

---
Tags: 8, users, services
---


title: Adding translation to a custom module

text:
# Question
Title: Adding translation to a custom module
I cannot make the module translation strings to be considered, unistalling and installing the module again.

Is the indicated .po relative path correct?

in my module blockForm function i have :

```
  $form['retrieval_method'] = array(
    '#type' => 'fieldset',
    '#title' => $this->t('Retrieval Method'),
  );

```

my .info.yml

```
name: 'amu hal'
type: module
description: display publications from HAL
core: 8.x
version: 8.x-3.0
package: AMU
project: 'amu_hal'
interface translation project: amu_hal
interface translation server pattern: modules/amu_hal/translations/%language.po

```

and in

> /sites/mysite/modules/amu\_hal/translations/fr.po :

```
msgid "Retrieval Method"

msgstr "Méthode d'extraction"

```

i have activated the core interface traduction module and the

> /fr/admin/reports/translations

tells me Missing translations for 11 projects:

> ```
> amu hal (8.x-3.0). File not found at modules/amu_hal/translations/fr.po
>
> ```

# Answer
Thanks to comments and doc , i have moved the whole module in modules/custom/ and for info file:

```
name: 'amu hal'
type: module
description: display publications from HAL
core: 8.x
version: 8.x-3.0
package: AMU
project: amu_hal
'interface translation project': amu_hal
'interface translation server pattern': modules/custom/amu_hal/translations/amu_hal-%language.po

```

Placing the po file at

> modules/custom/mymodule/translations/mymodule-fr.po

now i could update the translation at

> /fr/admin/reports/translations

and make string translations

Note that the same po file is not found if the module is placed in sites/mysite/module
> 7 votes

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


title: Create New User Display

text:
# Question
Title: Create New User Display
I am looking for a way to create new user Display.

When I go to Admin \> Configuration \> People \> Acount Setting \> Manage Dispaly

there are only three display modes: Default / Compact / User Account

How do I create a custom display mode?

See attached picture.

# Answer
On the page shown in the screenshot (*Administration \> Configuration \> People \> Account settings \> Manage display* or /admin/config/people/accounts/display) click on *Custom display settings*. It will show further settings, including the *Manage view modes* link.

>

Click on the *Add new mode* button.

>

Click on *User*

>

Enter the name for the new display mode, and click on *Save*.

>

When you go back to /admin/config/people/accounts/display, you will find the new display mode listed together the other ones.
> 1 votes

# Answer
In drupal 8 you can easily create a new view mode via backoffice : Administration \> Structure \> Display modes \> View \> User and click Add new User view mode.
To go further see documentation : https://www.drupal.org/docs/8/api/entity-api/display-modes-view-modes-and-form-modes
> 2 votes

---
Tags: 8
---


# Question
Title: Recovering a failed Commerce installation
Scenario:

* existing site
* 1G PHP memory
* install commerce modules locally
* do some dev and configuring
* cex my config and deploy upstream
* deployment fails with "php out of memory"
* try deployment again (4 times)
* eventually "succeeds"

Failure:

* "Success" is actually a farce.
* Drupal config shows commerce\* modules as installed, but the commerce database tables don't exist.
* "drush pmi" reports modules as not installed
* "drush en" reports modules as already installed
* "drush pmu" fatals with "missing database tables"

Any tips on recovering from this? I need to preserve all my existing content and whatnot.

# Answer
> 0 votes
Here's how i fixed the issue. This was a Drupal Commerce problem, but I think the general process could be applicable to other failed module installations:

* Identify module which failed to install correctly (commerce\_product)
* Spin up a new vanilla Drupal site, and install the missing module (and its dependencies). In the case of limited resources, Drupal Commerce may need to be enabled one module at a time.
* After enabling the module successfully on the vanilla site, identify the database tables which exist in vanilla but not in the corrupted site. (In my case, there were 9 commerce\_product\* tables)
* Create those tables on the corrupted site manually: do a `mysqldump --no-data` against the vanilla site, then import it to the corrupt site.
* Now uninstall, then re-install the failed module from the corrupted site.

---
Tags: 8, commerce, installation, wsod
---


# Question
Title: How to insert the title of the group in a message?
I created a custom module using the example in:

https://www.drupal.org/project/message

When a node is created, it is associated with a group:

https://www.drupal.org/project/group

Here is my module. I created in my template a reference field to the group `field_group_reference`

How to insert the title of the group in the message ?

Thank you

```
<?php

/**
 * @file
 * Holds hook implementation for the Message Activity Stream module.
 */

use Drupal\Core\Entity\ContentEntityBase;
use Drupal\node\Entity\Node;
use Drupal\comment\Entity\Comment;
use Drupal\user\Entity\User;
use Drupal\message\Entity\Message;

/**
 * Implements hook_group_insert().
 */
function message_activity_stream_group_insert(Node $node) {
  $message = Message::create(['template' => 'mas_create_node', 'uid' => $node->get('uid')]);
  $message->set('field_group_reference', $node);
  $message->set('field_published', $node->isPublished());
  $message->save();
}

```

# Answer
For this, you need to know that a node can be in multiple groups and there is also a midlevel entity between a node an a Group called a GroupContent entity.

To retrieve the Groups for a given node you can use this code:

```
 $plugin_id = 'group_node:' . $node->bundle();

 // Only act if there are group content types for this node type.
 $group_content_types = GroupContentType::loadByContentPluginId($plugin_id);

  // Load all the group content for this node.
  $group_contents = \Drupal::entityTypeManager()
        ->getStorage('group_content')
        ->loadByProperties([
        'type' => array_keys($group_content_types),
        'entity_id' => $node->id(),
  ]);

  /** @var \Drupal\group\Entity\GroupInterface[] $groups */
  $groups = [];
  foreach ($group_contents as $group_content) {
    /** @var \Drupal\group\Entity\GroupContentInterface $group_content */
    $group = $group_content->getGroup();
    $groups[$group->id()] = $group;
  }

```

You can see this code in action in gnode\_node\_access() which works out access permissions for a node by checking the Groups it is attached to.

Now you have a list of groups, you can load the first one from the list and use its title.

```
  $group = reset($groups);
  $title = empty($group) ? '' : $group->label();

```
> 2 votes

---
Tags: 8, nodes, group, message-subscribe
---


title: Numbering table rows

text:
# Question
Title: Numbering table rows
Views are normally formatted as unformatted list. I would format a view as HTML list, and choose between `<ul>` or `<ol>` markup.

Since I use the DraggableViews module, I need to format the view as table. I would like to have some automatic numbering for the view's table rows, similar to the HTML list, which uses `<ol>` and `<li>` markup.

How could I get each row in the view table to have a number that is automatically increased?

# Answer
> 3 votes
You can add the global *view result counter* field to the view, whose description in the *Add fields* dialog box is the following.

> Displays the actual position of the view result.

>

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


title: Include Json file into Twig template

text:
# Question
Title: Include Json file into Twig template
I'm trying to run this library ParticleJS which requires me to download a Json.

I added this file into *`theme/libraries.yml`* this way:

```
global-js:
  js:
    assets/js/particles.min.js : {}
    assets/js/particles.json : {}

```

But that gives me this error:

> Refused to execute script from 'https://www.example.com/themes/nexus/assets/js/particles.json?pem8cm' because its MIME type ('application/json') is not executable, and strict MIME type checking is enabled.

So I'm added:

```
<script src="themes/nexus/assets/js/particles.json"></script>

```

And it is giving me the same error.

Can someone help me with this problem, please? How should I include any other file into twig templates? Thank you

# Answer
> 2 votes
You need use hook\_page\_attachments\_alter

```
function mytheme_page_attachments_alter(&$attachments){
  $attachments['#attached']['html_head'][] = [
    // The data.
    [
      '#type' => 'html_tag',
      // The HTML tag to add, in this case a  tag.
      '#tag' => 'script',
      // set attributes like src to load a file
      '#attributes' => array('src' => '/themes/mytheme/assests/js/particles.json'),

    ]
  ];

}

```

# Answer
> 1 votes
I would load it with javascript on the front-end

According to the example in the GitHub Page, this javascript should work:

```
/* particlesJS.load(@dom-id, @path-json, @callback (optional)); */
particlesJS.load('particles-js', '/themes/nexus/assets/js/particles.json', function() {
  console.log('callback - particles.js config loaded');
});

```

In general, you could use this:

```
(function($){
  $.get( "/themes/nexus/assets/js/particles.json", function( data ) {
    console.log(data);
    alert( "Data Loaded: " + data );
  });
})(jQuery);

```

Also, note that the best practice is to encapsulate your JS in Drupal Behaviors, as described in the Drupal JS API, but it has a learning curve. In your case, it should work just as it is in the example.

---
Tags: 8, theming
---


# Question
Title: How does data propagate from the formElement of a Widget to the properties of a FieldItem?
Here is my custom Widget:

```
<?php

namespace Drupal\scripture\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;

use Drupal\my_module\Plugin\Field\FieldType\MyFieldItem;

/**
 * Plugin implementation of my custom widget.
 *
 * @FieldWidget(
 *   id = "my_widget",
 *   label = @Translation("My Widget"),
 *   description = @Translation("A Widget belonging to me"),
 *   field_types = {
 *     "my_field_type"
 *   },
 *   multiple_values = FALSE,
 * )
 */
class MyWidget extends WidgetBase {

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {

    $element['#type'] = 'fieldset'; // just to show the title and put a nice frame around it

    $element['verse'] = array(
      '#type' => 'verse_picker', // This is a custom Element defined elsewhere.
    );

    /** @var MyFieldItem $item */
    $item = &$items[$delta];

    // If the item is not empty, populate the form element
    if (!$item->isEmpty()) {
      // ...
    }

    return $element;
  }

}

```

And here is my custom FieldType:

```
<?php

namespace Drupal\scripture\Plugin\Field\FieldType;

use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\TypedData\DataDefinition;

/**
 * Plugin implementation of my field type.
 *
 * @FieldType(
 *   id = "my_field_type",
 *   label = @Translation("My field Type"),
 *   description = @Translation("A FieldType belonging to me."),
 *   default_widget = "my_widget",
 *   default_formatter = "my_formatter"
 * )
 */
class MyFieldItem extends FieldItemBase {

  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    // Prevent early t() calls by using the TranslatableMarkup.
    $properties['from'] = DataDefinition::create('integer')
      ->setRequired(TRUE);

    $properties['to'] = DataDefinition::create('integer')
      ->setRequired(TRUE);

    $properties['abbr'] = DataDefinition::create('string')
      ->addConstraint('Length', [
        'max' => 8,
      ])
      ->setRequired(FALSE);

    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
    $schema = [
      // ...
    ];
    return $schema;
  }

  /**
   * {@inheritdoc}
   */
  public function isEmpty() {
    return empty($this->get('from')->getValue()) || empty($this->get('to')->getValue());
  }

}

```

Whenever I save a field, the properties stay NULL. Even when I use xdebug to inspect every call to isEmpty(), `$this` never has any populated properties. *How does the user input get from the form element to the field item's properties?* I could not find Drupal documentation on the matter.

# Answer
submitForm() of the content entity form calls via several other methods (which you find in the call stack) this method of the field widget, which then sets the values of the field items.

*WidgetBase::extractFormValues():*

```
  public function extractFormValues(FieldItemListInterface $items, array $form, FormStateInterface $form_state) {
    $field_name = $this->fieldDefinition->getName();

    // Extract the values from $form_state->getValues().
    $path = array_merge($form['#parents'], [$field_name]);
    $key_exists = NULL;
    $values = NestedArray::getValue($form_state->getValues(), $path, $key_exists);

    if ($key_exists) {
      // Account for drag-and-drop reordering if needed.
      if (!$this->handlesMultipleValues()) {
        // Remove the 'value' of the 'add more' button.
        unset($values['add_more']);

        // The original delta, before drag-and-drop reordering, is needed to
        // route errors to the correct form element.
        foreach ($values as $delta => &$value) {
          $value['_original_delta'] = $delta;
        }

        usort($values, function ($a, $b) {
          return SortArray::sortByKeyInt($a, $b, '_weight');
        });
      }

      // Let the widget massage the submitted values.
      $values = $this->massageFormValues($values, $form, $form_state);

      // Assign the values and remove the empty ones.
      $items->setValue($values);
      $items->filterEmptyItems();

      // Put delta mapping in $form_state, so that flagErrors() can use it.
      $field_state = static::getWidgetState($form['#parents'], $field_name, $form_state);
      foreach ($items as $delta => $item) {
        $field_state['original_deltas'][$delta] = isset($item->_original_delta) ? $item->_original_delta : $delta;
        unset($item->_original_delta, $item->_weight);
      }
      static::setWidgetState($form['#parents'], $field_name, $form_state, $field_state);
    }
  }

```
> 1 votes

# Answer
To complement the answer given by 4k4: Further up the call stack from `WidgetBase::extractFormValues`, you will reach `Map:setValue`. This is where my form values got lost:

```
public function setValue($values, $notify = TRUE) {
  if (isset($values) && !is_array($values)) {
    throw new \InvalidArgumentException("Invalid values given. Values must be represented as an associative array.");
  }
  $this->values = $values;

  // Update any existing property objects.
  foreach ($this->properties as $name => $property) {
    $value = isset($values[$name]) ? $values[$name] : NULL;
    $property->setValue($value, FALSE);
    // Remove the value from $this->values to ensure it does not contain any
    // value for computed properties.
    unset($this->values[$name]);
  }
  // Notify the parent of any changes.
  if ($notify && isset($this->parent)) {
    $this->parent->onChange($this->name);
  }
}

```

The line `$value = isset($values[$name]) ? $values[$name] : NULL;` looks for values with the same name as the property. In my situation, those values are nested inside an array called `verse` like this:

```
Array
(
    [0] => Array
        (
            [verse] => Array
                (
                    [abbr] => AOV
                    // ... other stuff that doesn't get saved
                    [from] => 10172019
                    [to] => 10172381
                )

            [_original_delta] => 0
        )

)

```

Then I implement `MyWidget:massageFormValues` to make it look like this:

```
Array
(
    [0] => Array
        (
            [verse] => Array
                (
                    // ... doesn't matter
                )

            [_original_delta] => 0
            // the following three are used by Map:setValue()
            [from_vid] => 10172019
            [to_vid] => 10172381
            [translation] => AOV
        )

)

```

Here is the code:

```
public function massageFormValues(array $values, array $form, FormStateInterface $form_state)
  {
    foreach ($values as $delta => &$value) {
      // Place the values that should end up in the FieldItem's properties directly under the delta.
      $value['from'] = $value['verse']['from'];
      $value['to'] = $value['verse']['to'];
      $value['abbr'] = $value['verse']['abbr'];
    }
    // No call to parent needed.
    return $values;
  }

```
> 1 votes

---
Tags: 8, plugins
---


# Question
Title: Inside drop-down menu child menus are not working
I am using bootstrap sub-theme and created a drop-down menu and set it's menu levels they are working correctly but when i extend to child menus it's not working. I have searched Expand menu links down in a tree and Child navigation sidebar or drop-down navigation displaying child items but not found any solution.

Any Help?

# Answer
Bootstrap 3 and 4 have dropped support for nested (multilevel) menus

One has to include the relevant code (that was excluded) in their own custom theme to make it work.

Check this stackoverflow answer for relevant code to add to your theme

NOTE: the reason the support was dropped is that multilevel nesting is problematic in mobile or smaller screens so you have to implement solutions for small screens on your own.
> 0 votes

---
Tags: 8, navigation, bootstrap-theme
---


# Question
Title: How to exclude Views results for custom entities for which a user has no permission to view them?
I have a custom entity which I list in views. I set access control for them, but when I list in views these entities, all entities shows up, those one too, which the user does not have permission to access.

What do I need to implement to filter out those entities, which the user does not have right to view?

# Answer
After reviewing the list of Views hooks, I think hook\_views\_pre\_render() is the one you can use to filter results before they are rendered.

```
/**
 * Implements hook_views_pre_render().
 */
function MODULE_views_pre_render(ViewExecutable $view) {
  if (!empty($view->result)) {
    $entities = [
      'your_custom_entity_id',
      'another_entity_id',
    ];

    foreach ($view->result as $key => $result) {
      if (empty($result->_entity)) {
        continue;
      }

      if (!in_array($result->_entity->getEntityTypeId(), $entities)) {
        continue;
      }

      $access = \Drupal::entityTypeManager()
        ->getAccessControlHandler($result->_entity->getEntityTypeId())
        ->access($result->_entity, 'view', NULL, TRUE);

      if (!$access->isAllowed()) {
        unset($view->result[$key]);
      }
    }
  }
}

```
> 1 votes

# Answer
Actually my final solution was this: https://www.drupal.org/project/drupal/issues/2997705 which maybe not the best, but it works.
> 1 votes

---
Tags: 8, entities
---


title: Hook to fetch data after a node update

text:
# Question
Title: Hook to fetch data after a node update
I have used editable views module to get a single page to edit the nodes. I want to store the updated details to an external table.

I have used `hook_node_update` but it only saves the first node's value to my external table not the rest of nodes(I have 18 nodes in a single page to edit).

```
function pmr_data_table_node_update($node) {

  if($node->type == 'upload_data'){
    $node_id = $node->nid;
    $profit = $node->field1['und'][0]['value'];
    $satisfaction = $node->field2['und'][0]['value'];
    $from = $node->field3['und'][0]['value'];
    $to = $node->field3['und'][0]['value2'];

    $newDate = date("Y-m-d H:i:s", strtotime($to));

    $entry = db_update('table_name')
     ->fields(array(
     'profitability' => $profit,
     'customer_satisfaction' => $satisfaction,
     ))
     ->condition('nid', $node_id, '=')
     ->condition('to_date', $newDate, '=')
     ->execute();
    drupal_set_message('Data updated successfully.');

  }

}

```

The above code only saves the first node in the editable view list. Can anybody suggest how can I save all the field values in a single round? Is there any hook where I can use to save the all the changed field values to the external table?

OR

Is there any hook by which I could get the data just after the set of nodes are updated?

# Answer
The thing I didn't understand is how are you updating the nodes? you said in a single page edit? what does this mean? do you mean vbo? or is it in node page view?

Because your code seems right and should run on every node and if you are using vbo so it would be an issue related to it!

if you can explain more I'd be happy to help
> 0 votes

---
Tags: 7, hooks, views
---


# Question
Title: Send Mail After Checking Date Field Value
My content type (product) has a date field named Expired Date. All I want is like this:

check value of expired date field from content type product. If value equal to 7 days from now, send mail with list of node title and node url.

How to do this with Rules? or any suggestion modules?

# Answer
> 0 votes
Yes you could do this through rules granted the product expiration date is a field.

1. Create a new rule to run on cron maintenance tasks
2. Condition--\> has field name
3. Pick your field name
4. Action--\> execute custom PHP.

I don't know what your level of PHP experience is so I'll hold off on putting any code down, but the next step would be to write a short snippet of PHP that takes the sites current datetime and checks the values of your chosen field for values that are 7 days away from expiration (rules should give you tokens for both items).

1. Then in that same custom PHP area use rules\_action\_mail() to send the email out with the results (for reference: https://drupal.org/node/322834).

You could also do this with a SQL query in the PHP area: http://www.barnettech.com/content/dbquery-drupal-creating-sql-queries-drupal-way . Just run through your field in the database and check for the values you need, then return the results in the mail message.

If I were to do something like this, I would implement hook\_cron() in a custom module: https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook\_cron/7 vs. using Rules since it would require less steps.

Edit: As requested:

See here to make a Drupal 7 module: https://drupal.org/node/1074360

Using hook\_cron would go something like:

```
function mymodule_cron(){
 myfunctions();
}

function myfunctions(){
//do cool stuff
}

```

As far as what would go into "myfunctions", it would probably be a query on the database, returning those results, then sending those results in an email with mail(). That would be it.

# Answer
> 0 votes
yes, it's posible only with rules and one more module, first you have to calculate in days the difference betwen date fields, here the solution, then, with rules-conditional module add an if, add a condition: your diff value calculated is \> than 7, send your email.

# Answer
> 0 votes
I've saved this(Someone's else answer I can't remember) earlier because its the best way to do publish/unpublish content based on a date feild (which you can replace it with Send Mail) using Rules and sub-module (Rules Scheduler)

After you enable them follow these steps:

* at /admin/config/workflow/rules/components/add
* Create a ruleset (name it "Unpublish Content")
* In the Settings/Variables:
* Data type = "Node"
* Label = "node"
* Machine name = "node"
* Save
* ...next screen...Add rule
* Name = "Unpublish Content Rule"
* Save Conditions:
* Content is published
* Data selector = node
* Save
* Content is of type = node
* Value = your-content type
* Save Actions: \- Unpublish content
* Data selector = node
* Save at /admin/config/workflow/rules
* Create a rule (name it "Unpublish Rule" \- React on event = After saving new content
* Save Conditions:
* Content is of type
* Data selector = node
* Value = your-content-type
* Save Actions: \- Schedule component evaluation \- Component Value = Unpublish Content \- Data selector = node:field-your-node-date-field
* Identifier value = unpublish \[node:nid\] \- node Data selector = node
* Save

Good luck!

---
Tags: 7, rules, datetime
---


# Question
Title: Core update installs 8.6.0-beta1 instead of 8.5.6
Using composer I tried to update Drupal 8 to 8.5.6. The update wasn't working, so I changed the dependencies to explicitly require 8.5.6. The update began, but it installed Drupal 8.6.0-beta1. The command I used was `composer update drupal/core --with-dependencies -v`.

The updates page still says Drupal 8.5.6 is required. I'm not sure where to go from here.

Should I try to roll it back? I tried requiring Drupal 8.6.0-beta2 and Drupal 8.6.0-rc1, but an error suggested not to update to these versions. I want the site live ASAP, and updated to Drupal 8.5.6.

# Answer
> 1 votes
Solution for me was start from 8.5.0, upgrade to 8.5.5 then run:

```
composer update drupal/core symfony/* --with-dependencies

```

I'm now on 8.6.0 ! :)

---
Tags: 8, updating
---