title: Help with view filters

text:
# Question
Title: Help with view filters
I have a view using one content type: fee\_schedule The view contains fields for species, keywords (hidden), and the title.

The filters need to show ALL species except when searching by keywords. The keywords field and the title field are combined using Global Combine fields filter that is exposed.

Here's the issue: When someone uses the exposed species drop down, it works as expected. It shows the 'All' species and which ever species they selected. But when they put in keywords (like 'bulk') then it still shows All species (even though these species do not have 'bulk' as a keyword), along with the species that do have the keyword 'bulk'. When searching using keywords, I need the view to display ONLY the species with the keyword. When searching by species, I need it to show the content with All species and the specific species they selected.

Here's the link to the view: https://vdl-dev.umn.edu/services-fees

I am using and/or filtering as follows:

Content Published: yes AND Content Type: Fee Schedule AND Global Combined fields filter exposed (title and keywords) AND Content Species (each specific species but not All)

OR

Content Species (All is only selected)

Maybe I can't do what I need to do using views. Any help much appreciated.

# Answer
Your description is very confusing, I hope I was able to understand your problem in the end.

You've framed it as if you're applying the exposed filters and then looking at the views results. But in the end you're looking back at the Exposed filters.

The module that can help you is Views Selective Filters.

> you get dynamic dependent filters, that is, when the value of one filter is changed, the list of options of the selective filters are updated accordingly to the trimmed down result set.
> 0 votes

---
Tags: views
---


# Question
Title: Why am i getting this Drush error after updating a site?
I use Drush 8.1.17 to update my Drupal 7 sites, and as I have been updating my sites today after the latest security update I have noticed that after I update a site if I try to run any update related command (ex: drush up -n | grep available) I get this error:

```
The external command could not be executed due to an application error.                                      [error]
The command could not be executed successfully (returned: PHP Fatal error:  Uncaught                         [error]
TYPO3\PharStreamWrapper\Exception: Unexpected file extension in "phar:///usr/local/bin/drush/includes/.." in
/srv/www/htdocs/fac-dev/misc/typo3/drupal-security/PharExtensionInterceptor.php:39
Stack trace:
#0 /srv/www/htdocs/fac-dev/misc/typo3/phar-stream-wrapper/src/Behavior.php(72):
Drupal\Core\Security\PharExtensionInterceptor->assert('phar:///usr/loc...', 'url_stat')
#1 /srv/www/htdocs/fac-dev/misc/typo3/phar-stream-wrapper/src/Manager.php(83):
TYPO3\PharStreamWrapper\Behavior->assert('phar:///usr/loc...', 'url_stat')
#2 /srv/www/htdocs/fac-dev/misc/typo3/phar-stream-wrapper/src/PharStreamWrapper.php(412):
TYPO3\PharStreamWrapper\Manager->assert('phar:///usr/loc...', 'url_stat')
#3 /srv/www/htdocs/fac-dev/misc/typo3/phar-stream-wrapper/src/PharStreamWrapper.php(401):
TYPO3\PharStreamWrapper\PharStreamWrapper->assert('phar:///usr/loc...', 'url_stat')
#4 [internal function]: TYPO3\PharStreamWrapper\PharStreamWrapper->url_stat('phar:///usr/loc...', 2)
#5 phar:///usr/local/bin/drush/includes/filesyste in
/srv/www/htdocs/fac-dev/misc/typo3/drupal-security/PharExtensionInterceptor.php on line 39
, code: 255)
pm-updatestatus failed.

```

Does anyone know why this error only appeared after I updated the site and how I can fix it?

# Answer
> 2 votes
It looks like they just released Drupal 7.63 and in the release notes they say, "This is a hotfix release for a regression affecting some Drush installations that was introduced by the fix for SA-CORE-2019-002. No other fixes are included."

---
Tags: drush, updating
---


# Question
Title: How to embed a node's NID in the title of a node?
I know the Automatic Nodetitles module exists, but it is only for Drupal 7.

Is there a method of automatically assigning the title with the NID upon clicking submit? I know that the NID doesn't exist until the submit button is hit. How would one embed the NID in the title?

What hook would one use?

# Answer
> 5 votes
You need to do two step:

**Step one:** auto generate the title and hidden form. use hook\_field\_widget\_form\_alter() with code

```
function MY_MODULE_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
  $field_definition = $context['items']->getFieldDefinition();
  $bundle = $form_state->getFormObject()->getEntity()->bundle();
  // You can check with other bundle
  if ($field_definition->getName() == 'title' && $bundle == 'page' && $element['value']['#default_value'] == '') {
    $element['#required'] = FALSE;
    //hidden title
    $element['#type'] = 'hidden';
    $element['value']['#required'] = FALSE;
    // Set default value
    $element['value']['#default_value'] = 'Default Title';
  }
}

```

with step one you can cross submit form.

**Step two:** Override new title with default value. Use hook\_node\_insert()

```
function MY_MODULE_node_insert(Drupal\node\NodeInterface $node) {
  if ($node->bundle() == 'page') {
    $new_title = 'New title ' . $node->id();
    $node->setTitle($new_title);
    $node->setNewRevision(FALSE);
    $node->save();
  }
}

```

# Answer
> 1 votes
You can use the Hook Post Action module

> So this module introduces several new Drupal hooks to overcome this limitation
>
> * hook\_entity\_postsave
> * hook\_entity\_postinsert
> * hook\_entity\_postupdate
> * hook\_entity\_postdelete
> * hook\_node\_postsave
> * hook\_node\_postinsert
> * hook\_node\_postupdate
> * hook\_node\_postdelete

and one you have it installed you can use the `hook_node_postsave()` hook

In the Automatic Nodetitles module page says:

> Be advised that there is a better maintained alternative available: https://www.drupal.org/project/auto\_entitylabel

# Answer
> 0 votes
This may be an old issue, but here's my take. Let's say you need this for node add article.

```
<?php

use Drupal\Core\Form\FormStateInterface;
use Drupal\node\NodeInterface;

function MYMODULE_form_node_article_form_alter(&$form, FormStateInterface $form_state, $form_id) {

    // Hide title field to avoid confusion
    $form['title']['#access'] = FALSE;
    // Set a temporary title because it's always required on node save.
    $form['title']['widget'][0]['value']['#default_value'] = 'Dummy title';

}

function MYMODULE_node_insert(NodeInterface $node) {
  if ($node->bundle() == 'article') {
    $new_title = 'Title ' . $node->id();
    $node->setTitle($new_title);
    $node->setNewRevision(FALSE);
    $node->save();
  }
}

```

---
Tags: 8, hooks, nodes
---


title: Adding extra buying option to product

text:
# Question
Title: Adding extra buying option to product
I need to add extra buying option with some price in Create Product (Add a product). If a user checks on extra buying option then they need to add the price and that price will be again added to product price. I am trying to achieve this using commerce pricing attributes but no success so far.

Any suggestions?

# Answer
> 0 votes
use Product Attributes & Variations. full documentation is here: https://drupalcommerce.org/user-guide/product-attributes-variations

# Answer
> 0 votes
I have used Commerce Product Add-on and it worked like a charm

---
Tags: commerce
---


# Question
Title: Notice: Undefined variable: node in eval() and Notice: Trying to get property of non-object in eval()
After upgrading to Drupal 7, I get the following error on my recent log messages:

> Notice: Undefined variable: node in eval() (line 24 of /home/scode/public\_html/modules/php/php.module(74) : eval()'d code). Notice: Trying to get property of non-object in eval() (line 24 of /home/scode/public\_html/modules/php/php.module(74) : eval()'d code).

The user accessing the page is "Anonymous (not verified)."

Do you have any idea?

# Answer
> 4 votes
Something is trying to run the php\_eval() function in php.module. Most likely you have something configured in your site (such as a block) to use the PHP input filter, which evaluates PHP code and prints the output as text. I would check all the blocks you have defined first.

You can also temporarily put a call to debug\_print\_backtrace() at the top of the php\_eval() function and print it's results while browsing your site as an anonymous user to see what exactly is calling that function.

# Answer
> 0 votes
Or you can put if condition with eval print in php.module file.
+if(is\_object('?\>' . $code)){
print eval('?\>' . $code);
+}

---
Tags: 7
---


# Question
Title: Show View When Empty and Hide View When Not Empty!
I have a webform as a block which sets a value connected to the logged in user. I want to display the webform if it hasn't been filled in yet by authenticated users, and hide it when it has (based on whether the value has been set or not).

I thought I could do it by using views with the Views Block Area to display the webform as a block when there is no result. But I want to hide the view when there is a result, which seems impossible?

If anyone can suggest how I might be able to achieve this, not necessarily using views.

# Answer
> 1 votes
Limit submissions to "1 ever" when you configure the Webform. I'm not sure if Webform Block module would automatically hide the block if the form is not shown, but it should. Webform will not show the form if it cannot be submitted.

# Answer
> 0 votes
In the end I used code in the block page visibility settings to only show the block based on whether users had set a value in their CiviCRM profile (a Drupal module). I am posting the code in case it helps others:

```
<?php

    civicrm_initialize( );

  //variable used to set if block should be displayed or not - default to not
    $show = 0;

    //get current logged in user civi id
    $contact = CRM_Core_Session::singleton()->getLoggedInContactID();

    //get employer id
    $org = civicrm_api3('Relationship', 'get', [
        'sequential' => 1,
        'return' => ["contact_id_b"],
        'relationship_type_id' => 5,
        'contact_id_a' => $contact,
    ]);

    if(isset($org['values'][0]['contact_id_b'])) {

        //get field value
        $result = civicrm_api3('Contact', 'get', [
            'sequential' => 1,
            'return' => ["custom_958"],
            'id' => $org['values'][0]['contact_id_b'],
        ]);

        // only show on the members home page
        if(drupal_get_path_alias() == 'members/organisation-profile') {
            $show = 1;
        }

        // don't show if they have set a value
        if(isset($result['values'][0]['custom_958'])) {
            $show = 0;
        }

        // do show if the value is ''
        if($result['values'][0]['custom_958'] == '') {
            $show = 1;
        }
    }

    return $show;

?>

```

---
Tags: 7, views, blocks, webforms
---


# Question
Title: Automatic username generation from name fields at registration
Drupal core 8.6.5

I am trying to change the user registration process to omit the username field and generate the username from the first name and last name.

Since I am new to Drupal and want to learn more I try to go without project modules for that task.

So far I set up a custom module and deactivated the username field. Now I should set a default value for it.

How can I set the username built of first name and last name before the process is going on?
And strip some blanks, unallowed characters, ...

I was thinking of hooking into function user\_validate\_name Is that possible?

My module so far:

```
<?php
use \Drupal\Core\Form\FormStateInterface;

/**
* Implements hook_form_FORM_ID_alter().
*/
function my_register_form_user_register_form_alter(&$form, FormStateInterface $form_state, $form_id)
{
    $form['account']['name']['#access'] = FALSE;
    $form['account']['name']['#default_value'] ='tbd'; und
}

```

Thanks for your help!

# Answer
This is an interesting case in Drupal 8. Previously we could look at the user registration form's validation processes, which in Form API were callback strings in the `#validate` property array (or attached to each element in the `#element_validate` property. Note that the Drupal term "element property" means an item in a form array prefixed with a "#".

A basic strategy is similar: alter the form's `#validate` property and *add*, not replace, a string referencing a valid PHP callable. Again, probably best to re-order validate callbacks for first-in, first-out.

```
// Probably best to add this as the first element of #validate
$form['#validate'][] = 'my_register_form_validate';

```

Then implement the function or callable.

```
function my_register_form_validate($form, FormStateInterface $formState) {
  // This should do the trick.
  $formState->setValue('name', $name);
  // But you might need to get the entity from form state storage?
}

```

But we also need to make sure that the user account form doesn't let you change user name, of it does, then add the same validation/form alter.

In Drupal 8, entities often have their properties validated not in the form but as part of Symfony Constraints as part of their Typed Data data definition. This is so that Drupal is more API-first rather than form-driven (like in Drupal 7).

So I think you're on the right track to look kind of into `user_validate_name`, but it appears to be unused except in the installer. I think that modifying the entity's base field definition and adding a new constraint would work too.

To do this implement hook\_entity\_base\_field\_info\_alter. Also see the following question How to easily alter an entitys base field definition per bundle?.

```
function my_register_form_entity_base_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  if ($entity_type->id() === 'user') {
    $fields['name']->getConstraints()
  }
}

```

Then implement a Constraint plugin and its corresponding ConstraintValidator class. The ConstraintValidator class might have a validate method like this:

```
public function validate($items, Constraint $constraint) {
  // The entity should be available on all fields as a parent typed data via FieldItemListInterface::getEntity method
  $entity = $items->getEntity();
  // Generate user name as say $name.
  $items->set($name);
}

```
> 2 votes

# Answer
Thanks for your help. Worked great for me.

I have already deactivated the possibility to change the username. If lastname changes (e.g. marriage) I want to keep the username.

```
<?php
use \Drupal\Core\Form\FormStateInterface;

/**
* Implements hook_form_FORM_ID_alter().
*/
function my_register_form_user_register_form_alter(&$form, FormStateInterface $form_state, $form_id)
{
    $form['account']['name']['#access'] = FALSE;
    $form['account']['name']['#default_value'] = 'tbd';
    array_unshift($form['#validate'],'my_register_form_validate');

}

function my_register_form_validate($form, FormStateInterface $formState)
{
    $firstname = $formState->getValue('field_firstname');
    $lastname = $formState->getValue('field_lastname');
    $name = $firstname[0]['value'].$lastname[0]['value'];
    $formState->setValue('name', $name);
}

```
> 1 votes

---
Tags: forms, hooks
---


# Question
Title: How to load paragraphs fields in hook_form_alter to disallow access?
I have a field inside a paragraph referenced in an taxonomy term.

```
/**
 * Implements hook_form_alter()
 */
function custom_general_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){
  switch ($form_id) {
    case 'taxonomy_term_application_category_form':
        $entity = $form_state->getFormObject()->getEntity();
        kint($entity);
        break;
  }
}

```

Inside Paragraph field named field\_test\_para,
I have a text field named field\_text,
how can I fetch array structure of field\_text in order to hide the
field\_text and how can disallow access to the text field. So far, I
have managed to get the taxonomy entity and looking on how I can fetch
paragraph entity and then alter the #access parameter of text field
within it.

# Answer
```
/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  switch ($form_id) {
    case 'taxonomy_term_application_category_form':
      // Hide the Button Text as its value is autopopulated from the term name.
      if (isset($form['field_test_para']['widget'][0]['subform']['field_test_para2']['widget'][0]['subform']['field_button_text'])) {
        $form['field_test_para']['widget'][0]['subform']['field_test_para2']['widget'][0]['subform']['field_button_text'] = FALSE;
      }
      break;
  }
}

```
> 0 votes

# Answer
Maybe you can use a preprocess paragraphs function which will target it more easily

```
function mymodule_preprocess_paragraph__myparagraph(&$vars)
{
    if ($vars['view_mode'] == 'full') {
        $parag = $vars['paragraph'];
        if (SOME LOGIC HERE){
        unset($vars['content']['myfield']);
        $var['field_removed']=true;
    }
}

```

The key point is to replace `__myparagraph` with the id of your paragraph

This example show you:

* How to access the paragraph object `$parag = $vars['paragraph'];`
* How to handle your logic only for a view mode `($vars['view_mode'] == 'full')`
* Remove a field `unset($vars['content']['myfield']);`
* You can test the variable `field_removed` in your twig template to not run the code to display the field (optional)

Oups, it looks like you are asking to alter a paragraph's form... For this you can use `hook_field_widget_paragraphs_form_alter`

```
function maymodule_field_widget_paragraphs_form_alter(&$element, FormStateInterface &$form_state, $context)
{
    switch ($element['#paragraph_type']) {
        case 'myparagraphs':
            $term = $form_state->getFormObject()->getEntity();
            //Check if paragraph is inside a form term
            if($term && ($term->getEntityTypeId()=='taxonomy_term')){
                $voc=$term->bundle();
                //Check if it is the desired voc
                if($voc=='my_voc'){
                    //unset($element['subform']['field_to_be hidded']); //to hide only one field
                    $element=[]; //to hide all the form
                }
            }
            break;
    }
}

```

Hope this help
> 1 votes

---
Tags: 8, hooks, paragraphs
---


title: Highcharts not working

text:
# Question
Title: Highcharts not working
I am using the Charts module for displaying charts in my Drupal project. When I took the `chart API example module page`, it's not displaying any. It throws me this error (in the console):

> Uncaught TypeError: $(...).highcharts is not a function

Any idea on how to resolve this issue? Or is there anything additional to do after installing the module?

I enabled all the sub-modules of the Chart module:

And I selected `Highcharts` as the Charting library option:

Notes:

* I added the chart js file inside `charts/modules/charts_api_example` and referenced the `charts_highcharts.js` file in the `charts_api_example.libraries.yml` file.
* I think the issue may be because jQuery must be loaded before Highcharts when checked the view source on the API examples page the jQuery is loaded at last after the Highcharts library. Not sure though that's the issue.

# Answer
I was thoroughly mistaken about the installation of the charts. After installation, I was editing the repositories section in `composer.json` and running the composer command to install the specific library (eg: `composer require --prefer-dist highcharts/highcharts:6.0.4`) from the particular sub-module. But **it has to be done from the Drupal project root directory**. Appreciate your valuable time and expecting this will help others.
> 1 votes

---
Tags: 8, charts
---


# Question
Title: single exposed filter for two displays in same view
I have three displays in same view. Every display has exposed form filter and in every pages ajax was set yes. How to use a single exposed filter for these three displays in same view?

I placed these three displays in to three quick tabs. For example, the three quicktabs names are test1, test2, test3. If I apply filter in test1, it should apply all other displays (test2, test3) also.

# Answer
1. Under Advanced \> Other You have to set the "Use AJAX:Yes" for both the views.
2. At the Quick tab setting page select the following radio button - Yes: Load only the first tab on page view".
> 0 votes

---
Tags: ajax, views
---


# Question
Title: How to customize order confirmation e-mail
I am experimenting with Commerce 2 and it is amazing, however one thing that I am unable to resolve customizing store e-mails? The default confirmation is not adequate and should be easy to customize using tokens or whatever like drupal core email messages. Can anybody provide a high level overview how to customize the order summary e-mail? Any tips will be greatly appreciated not only by myself, but certainly many other site builders who are stumped over this.

# Answer
> 5 votes
Order receipt emails are powered by Twig templates, just like regular pages. This helps us avoid the inflexibility of tokens and their lack of conditional support ("Only show the Shipping information heading if the token has data"), which were big problems for D7 sites.

You can override the commerce-order-receipt.twig.html template in your theme to customize it.

See https://github.com/drupalcommerce/commerce/blob/8.x-2.x/modules/order/templates/commerce-order-receipt.html.twig

# Answer
> 2 votes
The docs page is obviously still a work in progress (as in, it's stubbed but has no real content at https://docs.drupalcommerce.org/commerce2/developer-guide/orders/customize-order-receipt-emails), but the basic idea is we depend on Swiftmailer for sending HTML e-mails and expect developers to override the default e-mail template we provide. Keep an eye on those docs, as we'll be fleshing them out during DrupalCon week. If you end up with a successful customization, would love to see a blog post about it that we can share with others! : )

# Answer
> 0 votes
This is the link which you can follow =\> https://docs.drupalcommerce.org/commerce2/developer-guide/orders/customize-order-receipt-emails

Another solution is to copy the default twig from =\> commerce/modules/order/templates/commerce-order-receipt.html.twig and then placed into root theme folder of your Drupal 8 project =\> your\_project\_name/themes/your\_current\_theme/templates/(place the default file here)

make the changes as per your requirements. I hope this will work for you guys have a nice day :).

---
Tags: 8, commerce, emails
---


title: How to Install Prism Module

text:
# Question
Title: How to Install Prism Module
Prism.js is a useful syntax highlighter that is good for displaying code samples on web pages.

I have installed the Prism module, and I have followed all of the instructions in the module's README.txt file. When publishing an article node with the following HTML, the resulting web page does not include the syntax highlighting provided by `prism.js`.

What is the correct way to use prism syntax highlighting in Drupal?

```
[prism:css]
    a { color: #7BC673; }
    p a { color: #22272A; }
    p a:hover { color: #7BC673; }
[/prism:css]

```

# Answer
I've followed following steps and getting that `prism` works fine, you can verify your steps as below:

1. Install Prism and Libraries module (*Libraries module is required by prism*).
2. Download prism.js and prism.css from here, then put both files in 'sites/all/libraries'. So, The library path should be like as follows:
`sites/all/libraries/prism/prism.js`
`sites/all/libraries/prism/prism.css`
See screenshot:
3. Check or Enable 'Prism (syntax highlight)' check box from `Full HTML` Text format configuration page (`admin/config/content/formats/full_html`) then click on the `Save Configuration` button to save changes.
4. Create a node/content with and put your css code in a field whose `Text Format` is `Full HTML`.
Output/Result (though it includes `<br>` but it can be removed by configure text format):
> 1 votes

---
Tags: installation
---


# Question
Title: Why is "drush make" installing a library in /sites/all/libraries instead of /libraries?
I am trying to allow prospective users to demo my module on simplytest.me, however, it requires an external javascript library. I recently created a drush make file for the D7 version of this module, and it is working fine. The D8 version is downloading the library, but placing it in drupalroot/sites/all/libraries instead drupalroot/libraries. Is there a way to change this behavior? Here is my make file.

```
api=2
core = 8.x
projects[drupal][type] = core
libraries[flot][download][type] = get
libraries[flot][download][url] = https://github.com/flot/flot/archive/master.zip
libraries[flot][destination] = libraries
libraries[flot][directory_name] = flot

```

I tried using `libraries[flot][destination] = /libraries` but that did not change the behavior.

Edit: I changed to a make.yml file, but this does not even download the library.

```
api: 2
core: 8.x
projects:
  - drupal
libraries:
  flot:
    destination: "libraries"
    directory_name: "flot"
    download:
      type: "get"
      url: "https://github.com/flot/flot/archive/master.zip"

```

# Answer
`drush status` tells me that I have version 5.10.0, so that's likely the issue. D8 support was not added until drush 8. Now I need to get upgraded.
> 0 votes

---
Tags: 8, drush
---


title: Clear region with menu's per url cache

text:
# Question
Title: Clear region with menu's per url cache
I have a region with menus, a menus displays depending on the url example if on the about page(sitename/about-us), display about menu and links as a sub menu.

It works, but the problem is after navigating through the site a couple of times, the region caches. is the anyway i can clear the regions cache on page reload.

I tried the below in my .theme

```
   /**
   *  Implements hook_preprocess_HOOK() for block.html.twig.
   */
  function themename_preprocess_block(&$vars) {
    //the menu block id name in the region
    if ($vars['derivative_plugin_id'] == 'submenu') {
      //-- This stops the block being cache in drupal 8
      $vars['#cache']['max-age'] = 0;

    }
  }

```

also tried

```
  /**
   * Implements hook_preprocess_HOOK() for block.html.twig.
   */
  function themename_preprocess_block(&$vars) {
    if ($vars['derivative_plugin_id'] == 'theme-block-branding') {
      //-- This stops the block being cache in drupal 8
      $vars['#cache']['max-age'] = 0;
    }
  }

```

not sure what steps I can follow to achieve the above

# Answer
> -1 votes
Add code below:

```
class MYCUSTOMBLOCK extends BlockBase {
  public function build() {
    return array(
      '#markup' => '', // the content of your block
    );
  }
  public function getCacheMaxAge() {
   return 0; // No caching gets applied here
  }
}

```

---
Tags: 8, blocks, navigation
---


# Question
Title: How to print paragraph field values in paragraph template?
I'm trying to output paragraph field values in a sample paragraph template, but it does not work. I created a twig template in paragraph/paragraph--article--default.html.twig

I have a field called field\_action and I tried:

```
{% block paragraph %}
    <div{{ attributes.addClass(classes) }}>
      {% block content %}
        {{content.field_action}}
        {{content.field_action.value}}

      {% endblock %}
    </div>
{% endblock paragraph %}

```

Nothing happens.

If I write {{content}} everything is fine, but I would like to customize output.

# Answer
To print out single fields I usually use, `{{ paragraph.field_action.value }}`. That should also work for you.

In the case of an entity reference field, you need to use `{{ paragraph.field_action.entity.field.value }}`.
> 2 votes

---
Tags: 8, theming, paragraphs
---


# Question
Title: How can I show the user login block on the 403 page?
With D8, I have a node (content type: basic page) that I use as a custom 403 (access denied) page.

I set this as the custom 403 page on: `/admin/config/system/site-information`. The path is `/node/21`, and the alias is `/error/403`.

On the block admin page, I added the **user login block** to the **content** region. I added the restriction "show only on certain pages":

* /error/\*
* /view/\*
* /node/21

I have a view that requires "add content type ABC permission" to access. The path to the view is `/view/abc`. The anonymous user does NOT have this permission.

So, as an anonymous user, I go to `/view/abc` and am shown the content of `/node/21`. BUT, the user login block is not shown.

If I go to the block administration screen and remove the "show only on certain pages" restriction, then I see the block as the anonymous user on `/view/abc`, but I don't want to show the login block on every single page; I only want to show it on the pages that are 403s.

What is the "path" to use for the user login block to only show it on a custom 403 page?

# Answer
One approach is to add page templates to your theme registry:

```
function MYMODULE_theme_suggestions_page_alter(array &$suggestions, array $variables) {

  //Allow theming the site error pages
  $route_name = \Drupal::routeMatch()->getRouteName();

  switch ($route_name) {
    case 'system.401':
    // Unauthorized Access.
    $error = 401;
    break;

    case 'system.403':
    // Access Denied.
    $error = 403;
    break;

    case 'system.404':
    // Page Not Found.
    $error = 404;
    break;
  }

  if (isset($error)) {
    $suggestions[] = 'page__' . $error;
  }

}

```

Then in `page--403.html.twig` you can render a specific block with Twig. See: How to embed a view in a specific node? and Programatically print blocks in twig

\*A reason I like this approach is that the Login block is a Drupal core block, not a custom one. You can just carry around a nice `403` template file and always know it will render out this block. The preprocess function above seems like the least invasive and time consuming (from looking at different approaches), plus it gives the ability to theme these error pages. I think it is ideal to utilize template files for error pages.
> 2 votes

# Answer
If you can code, you should go for a ConditionPlugin.

Just like RequestPath\*(ConditionPlugin) we built a custom RouteCondition plugin. That allows us to have granularity on each route.

In your case, a simple ConditionPlugin could be the proper starting point.

Here is an example * (www/modules/custom/{your\_module}/src/Plugin/Condition/NotFoundCondition.php)

```
<?php

namespace Drupal\{your_module}\Plugin\Condition;

use Drupal\Core\Condition\ConditionPluginBase;

/**
 * Provides a 'Error Pages 403' condition.
 *
 * @Condition(
 *   id = "error_403_pages",
 *   label = @Translation("Error 403 Pages"),
 * )
 */
class ErrorPages extends ConditionPluginBase {

  /**
   * @return bool
   */
  public function evaluate() {
      //  Retrieve the current route
      $route_name = \Drupal::service('current_route_match')->getRouteName();

      // Does we have a match
      return strpos( $route_name, 'system.403') === 0 * $this->isNegated();

    // EDIT: the negate concept might be a bit overwelming at first.
    // Maybe you don't need it right now

  }

  public function summary() {
    if (!empty($this->configuration['negate'])) {
      return $this->t('Do not return true on 403 pages');
    }
    return $this->t('Return true on 403 pages');

  }
}

```

After a cache rebuild you should be able to place the login block on 403 page using structure\>block layout
> 0 votes

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


# Question
Title: Permission restrictions deny you access to this broken link
In Reports -\> Broken links page for some records it is showing

> *permission restrictions deny you access to this broken link*

Site have only one language also, some of the broken links are showing with https link also. So I don't think the problem with protocol or language.

What is the part of link-checker cron. It was not running and i tried running it manually? But still the broken link is not showing (which I intentionally put some broken link).

What else could be the problem? How to resolve this issue?

Please suggest other than "Re-Analyze link data", that removes all old records also not showing the new one.

# Answer
I was able to view what the links were by modifying **linkchecker.pages.inc** line 158 to be the following:

```
if (empty($nids) && empty($cids) && empty($bids) && !user_access('bypass node access')) {

```

With this change, assuming that you have bypass node access, you will be able to see the links instead of the annoying message. Unfortunately, the "Edit Link Settings" option will not work for these rows still, because the link data may be out of date. (There are no nodes, comments, or blocks that have the link.)

In order to fix the result list for real, I ran the following drush commands, one after the other. They are defined in **linkchecker.drush.inc**:

```
drush linkchecker-analyze

```

*Reanalyzes content for links. Recommended after module has been upgraded.* This can also be done from the settings page: `/admin/config/content/linkchecker`

```
drush linkchecker-check

```

*Check link status.* (Note that this doesn't check them all, only the batch number set in your linkchecker settings.)

---

If necessary, you may also try running this first:

```
drush linkchecker-clear

```

*Clears all link data and analyze content for links. WARNING: Custom link check settings are deleted.* This can also be done from the settings page: `/admin/config/content/linkchecker`
> 2 votes

# Answer
One possible reason for your manual edit/test run not being flagged by Linkchecker is that the linkchecker scan didn't include your edit in the batch of content/data scanned.

The Linkchecker module's cron job only processes batches of content at a time (similar to Drupal's built-in search index), and may need to be run several times if there's a lot of content being generated during the course of the day.

---

With respect to the error message you're seeing

> permission restrictions deny you access to this broken link

on the Broken Links report page, you should check to make sure the module is up-to-date.

1. If your site is still running version 7.x-1.1, then LinkChecker may be showing the error because of the cross domain issue previously reported here: https://www.drupal.org/project/linkchecker/issues/2264181
2. If your site is running a more recent/current version of LinkChecker, you may still be encountering the language issue if the site is old. Some content may have no language attribute (undefined), while others reflect (**en**glish). If this is the case, you can bulk set the language attribute of all the nodes. Refer to How can I set the language of nodes in bulk to existing content when making a site multilingual?
3. This error message is also known to occur when a link points to an unpublished node or any content/view pages that require authentication/sign-in.
> 0 votes

---
Tags: 7, navigation
---


# Question
Title: Unable to fetch paragraph's multi field values inside node twig
I have a content type as "worker". I have a Paragraph "test" and I am referencing "test" paragraph inside my content type "worker". This allows multiple values to be saved.

How can I get the multiple "test" paragraph's `field_name` inside my node--worker.html.twig file directly?

I am able to get the single value of that field like below:

```
{{ node.field_test.entity.field_cdsfasdf.value }}

```

But, unable to fetch the multiple values for this field inside my node--worker.html.twig. I tried using for loop to fetch the multiple values like the code below:

```
{% for key, item in node.field_para %}
    {{ key }}
    <div class="item"> {{ item.entity.field_cdsfasdf.value }} </div>
{% endfor %}

```

But, I am facing the following error:

```
Exception: Object of type Drupal\entity_reference_revisions\Plugin\Field\FieldType\EntityReferenceRevisionsItem cannot be printed. in Drupal\Core\Template\TwigExtension->escapeFilter() (line 465 of DRUPAL_ROOT\exp\core\lib\Drupal\Core\Template\TwigExtension.php).

Exception: Object of type Drupal\node\Entity\Node cannot be printed. in Drupal\Core\Template\TwigExtension->escapeFilter() (line 465 of DRUPAL_ROOT\exp\core\lib\Drupal\Core\Template\TwigExtension.php).

```

# Answer
> 1 votes
Off the top of my head...

For multiple value fields you either render out the paragraph field itself:

```
{{ content.field_paragraph_field_name }}

```

and let Drupal handle the multiple value rendering, or do your own loop:

```
{% for item in content.field_paragraph_field_name %}
  {{ item.your.array.keys.here.value }}
{% endfor %}

```

Try:

```
{% for item in content.field_paragraph_field_name %}
  {{ dump(item | keys) }}
{% endfor %}

```

to see what keys you need to follow to your value.

---

I *do* recommend doing this kind of theming in a paragraph--paragraph-name.html.twig file, and then just printing the field in node.html.twig.

For a paragraph template file, it would look something like:

```
{% for item in content.field_paragraph_field_name['#items'] %}
  <div>{{ item.value }}</div>
{% endfor %}

```

---

For the error, looks like you're cycling through the reference field, but you need to cycle through the values of a field inside the reference field. (I'm sure someone could explain this better, but entity holds the field values you want to loop)

Instead of:

```
{% for item in node.field_para %}
    {{ item.entity.field_cdsfasdf.value }}
{% endfor %}

```

try something more like:

```
{% for item in node.field_para.entity.field_cdsfasdf %}
    {{ item.value }}
{% endfor %}

```

---
Tags: 8, theming, paragraphs
---


# Question
Title: Insert Revision log message programmatically after form submission
I am trying to pragmatically set the revision log message after values of certain fields are changed (thus if a user has edits certain fields). More information is in the code comments

```
 function home_hub1_form_alter(&$form, FormStateInterface $form_state, $form_id){

//    Hide Revisions log message text box
$form['revision_log_message']['#access']= FALSE;

//set revision check box to false since we are creating a revision progeammatically
$form['new_revision'] = array(
    '#type' => 'hidden',
    '#value' => FALSE
);

// monitor every field if its from edit
if ($form_id == 'device_entity_edit_form'){

    $form['actions']['submit']['#submit'][] = 'home_hub1_form_device_entity_edit_submit';

  }
}

function home_hub1_form_device_entity_edit_submit(array &$form, FormStateInterface $form_state){

$form_state->setTemporaryValue('entity_validated', TRUE);

//check if a field has changed and if it has write a revision log message
if ($form['field_city']['widget']['0']['value']['#value'] != $form['field_city']['widget']['0']['value']['#default_value']) {

    $message = 'CITY changed from: ' . $form['field_city']['widget']['0']['value']['#default_value'] . ' to: ' . $form['field_city']['widget']['0']['value']['#value'];

   $form_state->setValue('revision_log_message', $message);

}

```

I am getting the following error: `Error: Cannot unset string offsets in Drupal\Core\Field\WidgetBase->extractFormValues()`

I also tried to get the node object so that i create a revision directly from it like below:

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

$node = $form_state->getFormObject()->getEntity();

//check if a field has changed and if it has write a revision log message
if ($form['field_city']['widget']['0']['value']['#value'] != $form['field_city']['widget']['0']['value']['#default_value']) {

$message = 'CITY changed from: ' . $form['field_city']['widget']['0']['value']['#default_value'] . ' to: ' . $form['field_city']['widget']['0']['value']['#value'];

  $node->setRevisionUserId(\Drupal::currentUser()->id());
  $node->setRevisionCreationTime(REQUEST_TIME);
  $node->setNewRevision(TRUE); // enabling revision for the entity save.
  $node->setRevisionLogMessage($message);

```

}

How can I create a revision after form submission?

# Answer
I found the solution. I should have used `hook_form_BASE_FORM_ID_alter()` instead of `hook_form_FORM_ID_alter`

Also the call back function should be `home_hub1_my_entity_builder`
> 0 votes

# Answer
I would just go with this module: Try this module: https://www.drupal.org/project/revision\_log\_default
> 0 votes

---
Tags: 8, hooks
---


# Question
Title: How to deactivate keyboard navigation when using the “Views Slideshow: Swiper JS” module
So I am using the Views Slideshow (7.x-3.9) module in conjunction with the Views Slideshow: Swiper JS (7.x-4.0) under Drupal 7.61 and it’s working great for my needs. But have run into an issue. The version of the Swiper JS library I have installed is 4.4.6.

While the “Format \> Slideshow \> Settings” clearly has an option that you need to check a checkbox to enable keyboard navigation, and I have that option unchecked, I can assure you that keyboard navigation is clearly enabled.

Looking at this issue request on the Drupal page for Views Slideshow: Swiper JS shows a similar issue where the Drupal module settings seem to not be respected by Swipe JS when loaded, but the “solution” (kludge?) of downgrading to a 3.x.x version (such as 3.4.2) doesn’t work for me. Beyond not wanting to be behind the curve in patches and development on Swiper JS, when I attempted to swap my 4.4.6 version to 3.4.2 made the slideshow go a bit haywire.

So what can practically and simply be done to disable the keyboard functionality of Swiper JS under Drupal?

# Answer
Okay, so I solved this. It’s clear to me that the Views Slideshow: Swiper JS is somehow not passing all the config options it claims to handle to the final Swiper JS instance that gets loaded on the page.

So my solution that—works directly in the view—is to go to the Swiper JS settings “Format \> Slideshow \> Settings” scroll down and select “Events” and then add the following to the `swiper.on('init', function() {}` event:

```
this.params.keyboard.enabled = false;

```

Apply the settings, save the view and… et voilà! It works and cleanly disable keyboard navigation.
> 1 votes

---
Tags: 7, views
---


# Question
Title: Can we move a module from the directory "/modules" to the directory "/modules/contrib" without uninstalling it?
We have a Drupal 8 application which has modules directly in the directory "/modules" on the file system. I want to move a contributed module from the directory "/modules" to the directory "/modules/contrib". Do I need to uninstall the module before doing it?

Are there any steps that need to be performed before and after moving the module?

# Answer
> 1 votes
As with most things, I suggested testing it out on a development/test site before trying on the live site. It's likely that the specific set of contribs and the libraries they use will affect the success of this operation.

How did you install the modules? Do you use a composer workflow?

In general, some paths stored in different places are going to be wrong. To fix that, you will need to edit those paths or have Drupal figure out the new paths. I believe doing a cache rebuild (e.g. `drush cr`) will fix that problem.

---
Tags: 8
---


# Question
Title: redirecting midway out of a webform wizard
I am building a webform that has multiple pages. The idea is that the user leaves the wizard after each page that he submits. When he later returns, he automatically starts the form on the unanswered page.

The reason for this behaviour is that doing so, we can keep the records of all the 'sub-surveys' together as one single submission.

I successfully have set up custom handlers based on the example module. I can see that the handler is working.

To accomplish the desired scenario, I thought that it is probably best to log the user out in the {submitForm} function of the handler and set the redirect ($form\_state-\>setRedirect).

The redirect doesn't happen, but the logout does. What I end up with now, is that the user sees his next page, but can't submit it because he is actually logged out. It's fine that he can no longer submit. But it's not ideal that he sees the next page in the form. That is why i try to redirect.

I read in another question on stackexchange that the redirect should be set in the confirmForm, but that doesn' work either. Maybe because confirmForm only happens at the end of the wizard or something.

Any suggestions on how to redirect after (each, or some based on a condition) pages from the wizard?

Thanks.

# Answer
The logout is probably losing the user's session with the $form\_state

A very simple solution is to redirect the form to /user/logout?destination=REDIRCT\_PATH.
> 0 votes

---
Tags: 8, webforms
---


# Question
Title: Save content with current user roles and add filter to show only content with current user role
Using drupal 7, when creating new content of the type "Document" the current user roles must be added so I can later on show only Documents of his current role.

For example, we have the following user: this is Jake, he is a Firefighter. He creates a document about the dangers and pitfalls of being a firefighter. This is only relevant for Firefighters. So in the list of documents (view) I want Jake and all other Firefighters only to see Firefighter Documents.

So if Jake create new content of the type "document" I want to add his user roles and later on add a filter in the view so only Firefighters get to see Firefighter Documents

I want to have the following filter for the list Document view:

* Published = true
* Content type = Document
* User role = current user roles (Firefighter in this case)

Access must be restricted for every user based on their role. For example, Jake the Firefighter is **not allowed** to view Policemen Documents

# Answer
You don't have to add author's role to a node directly.
You can add user's role based **Exposed Filter** option in a view by using relationship. To do this please follow steps of below:

1. Create your view as usual (like configure view name, display type etc)
2. From **Fields** section add all desire fields.
3. From **Filter Criteria** choose appropriate node type.
4. Click on the **Advanced** button (indicated by an arrow on right side of the view).
5. Click on the Add button of the **Relationship** section and add `Content: Author` as a relationship.
6. Now Click on the Add button of the **Filter Criteria** section and add `User: Roles` as a filter. In this filter settings pop-up form, enable or check `Expose this filter to visitors, to allow them to change it` option then choose `Is one of` option as an operator.

Output/result:
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: REST API Guzzle POST gives timeout but the same call works if I run it on the server cli
I have Drupal running in a docker container and nginx running in another container.

When I do the login call through postman or directly on the webserver cli it works perfectly. But when I do call from within my application I get a timeout after 30 seconds.

From server:

> wodby@php.container:/var/www/html $ curl -X POST \ 'http://api.swappr.localhost/user/login?\_format=json' \ -H 'Postman-Token: a9c80844-ed69-4d24-b205-6475b7e469dc' \ -H 'cache-control: no-cache' \ -d '{"name":"logintest2@gmail.com", "pass":"password"}' {"current\_user":{"uid":"21","name":"logintest2@gmail.com"},"csrf\_token":"yf5YBYyY4YvXCcufLyTWeKnvbhq5sdcZHpgmsVDeSRY","logout\_token":"PEarVS7vPi5idARarGQzrrXAYcJL9YkiXmoHw\_a7yJE"}

In code:

```
$response = \Drupal::httpClient()->post(
            'http://api.swappr.localhost/user/login?_format=hal_json',
            ['name' => 'logintest2@gmail.com', 'pass' => 'password']
        );

cURL error 28: Operation timed out after 30001 milliseconds with 0 bytes received (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)

```

Anyone knows what could cause this problem?

# Answer
Okay turns out it was xdebug. I had to allow more simultaneous connections in the PHP Debug settings of PHP Storm.
> 0 votes

---
Tags: 8
---


# Question
Title: Drush command from contrib module not recognized
I have installed a new module called S3fs using Composer. When I try to execute `/root/.composer/vendor/bin/drush drush_s3fs_copy_local`, it shows the following error.

> Command "drush\_s3fs\_copy\_local" is not defined

I found out that I could not run any command from third-party modules I installed and enabled.

Please help me.

# Answer
`drush_s3fs_copy_local` is the name of the PHP callback function for the command; the command itself is named `s3fs-copy-local`, with an alias of `s3fs-cl`.

So:

```
drush s3fs-cl

```

Is what you're looking for.
> 0 votes

---
Tags: drush
---


# Question
Title: Hiding menu item depending on specific access
I work on a D8 (8.6) I want to hide some item on my menu depending on route param onto this link.

When I try to access the route I get a 403 error and works as expected but the the link inside the menu is still displayed.

I create a custom Accessinterface which return an AccessResult::allowed() or denied() depending on my rules.

Is there a core solution to prevent the link to be displayed on the main menu or I have to handle it in JS ?

My CustomAccessCheck :

```
class CustomAccessCheck implements AccessInterface
{

  public function access(AccountInterface $account)
  {
    $isAuthenticated = $account->isAuthenticated();

    try {
      $currentGroup = TestEntity::getInstance()->currentGroup;
    } catch (InvalidPluginDefinitionException $e) {
      return AccessResult::forbidden();
    }
    if ( $isAuthenticated &&
      ( !empty($currentGroup["id"]) && isset($currentGroup["IsActive"]) && $currentGroup["IsActive"])
    ) {
      return AccessResult::allowed();
    }
    return AccessResult::forbidden();
  }
}

```

I configure services and routing.yml in order to run this AccessChecker. The custom menu contain some menu items which target the route configured.

My problem is even if the user don't have access to the route the menu item is displayed.

Thanks for help Nico

# Answer
> 0 votes
I found by myself my mistake.

The menu items are always shown for super user.

The menu items are hidden/shown correctly for others users.

---
Tags: 8, navigation
---


# Question
Title: How to filter Data on the basis of id or uuid by Rest API?
I am using `Drupal 8` I have installed the poll module. I created a view with `REST` export enabled. Now when I get the data by this `url`

```
http://localhost/poll/rest/polling

```

I am getting all the data of polls like this

```
[{"question":"which is best city","choice_target_id":"Delhi, Mumbai, Chennai","id":"1","choice_target_id_1":["1","2","3"],"uuid":"b0ef150c-bf05-4a25-8ae9-b6864539c080"},{"question":"Where do you work?","choice_target_id":"Flat, Hotel, Factory, Shop","id":"2","choice_target_id_1":["4","5","6","7"],"uuid":"b2145904-fe8b-4ef6-82fa-f069c2e29f3b"}]

```

But when I get the data on the basis of `id` or `uuid` by this `url`

```
http://localhost/poll/rest/polling?id=1

```

then I am still getting all the data without getting filtered as per the `id`

What am I doing wrong?

# Answer
> 1 votes
You haven’t set up any exposed filters or you’re using the wrong filter id on them. Views needs exposed filters on it by which to limit a query by.

---
Tags: services, polls
---


# Question
Title: How do I get the field definition of a paragraphs image field
I need to get the resolution of the image using `getFieldDefinitions()`. For normal fields I can get the field definitions with below.

```
$fieldDefinition = \Drupal::entityManager()->getFieldDefinitions('node', $type);
foreach ($fieldDefinition as $field_name => $field_definition) {
    $settings    = $field_definition->getSettings();
    $resolution  = $settings['min_resolution'];
}

```

How do I get the field definition of a image field inside of a paragraphs field.

# Answer
> 0 votes
As it mention in comment just use `paragraph` instead of `node`.

```
$fieldDefinition = \Drupal::entityManager()->getFieldDefinitions('paragraph', 'your_paragraph_type_name');
    foreach ($fieldDefinition as $field_name => $field_definition) {
      if ($field_definition->getType() == 'image'){
        $settings    = $field_definition->getSettings();
        $resolution  = $settings['min_resolution'];
      }
    }

```

---
Tags: 8, nodes, paragraphs
---


title: Access Node image within Page template

text:
# Question
Title: Access Node image within Page template
I need to access a Node's image field within the `page.twig.html` template in order to display it in relation to certain page-level elements such as primary/secondary menus and the page title.

In `node.html.twig`, I'm able to access it like so:

```
{{ content.field_responsive_hero_image.0 }}

```

but in `page.html.twig` if I try

```
{{ node.field_responsive_hero_image.0 }}

```

I get the following error:

```
Exception: Object of type Drupal\image\Plugin\Field\FieldType\ImageItem cannot be printed

```

I'm familiar with the workaround of loading the image with

```
<img src="{{file_url(node.field_responsive_hero_image.entity.fileuri)}}" />

```

However, I then lose the title and alt attributes (bad for 508 compliance) as well as the automatic resizing of the image served based on screen size (bad for SEO rankings).

How do I access the Node's image at a page-level?

# Answer
In a preprocess hook (preferred):

```
/**
 * Implements hook_preprocess_HOOK() for page.html.twig.
 */
function MYTHEME_preprocess_page(&$variables) {
  if (isset($variables['node'])) {
    $variables['image'] = $variables['node']->get('field_image')->first()->view('full');
  }
}

```

Or in Twig:

```
{{ node.field_image.0|view('full') }}

```

To use `|view` install the module https://www.drupal.org/project/twig\_tweak
> 5 votes

---
Tags: 8, theming
---


title: Making 'Check out' option appear

text:
# Question
Title: Making 'Check out' option appear
I am using the Commerce module and Paypal WPS on Drupal 7. When logged in as Admin to my website on a product page I can see the 'Check out' link next to 'View Cart'. However, if I log out and select the same product the 'Check out' option is not there. All I can see is the shopping cart.

What can I do about this?

# Answer
I have managed to solve this issue by changing the permissions for the Checkout module. I went to People/Permissions/Checkout and enabled 'access checkout' for both anonymous and authenticated users. Previously it was just enabled for Administrator. Hope this helps anyone else with the same issue.
> 0 votes

---
Tags: commerce
---


# Question
Title: Problem with Unorganized content on page
So I am not familiar with Drupal at all and need help. I am a graphic designer and trying to change the order of the layout on one of my pages. We had a developer design and organize our site but she screwed up the organization somehow.

How can I reorganize image on a page again? I tried going through Administrator \> content \> then I re-published the content in order but it did not work.

I've added an image so you can see my problem. Basically I'm having to manually drag the items in order but row weights but wanted to know if I can somehow organize them by title name and refresh the page to fix the problem. Any help is appreciated!

# Answer
> 1 votes
Since you tagged your question with "Views", I assume your screenprint is created via a *view*. And the view itself relates to some sort of *entities* like nodes, products, whatever.

If that's the case, decide about the "sort field" that you want to use in your view, and adapt it to fit your needs. If you cannot find any appropriate field that you want to use for such sorting, then just add an extra field (named something like *sequence nr*, and like an integer of say 4 digits). Then edit each of your entities to assign a relevant sequence nr, and use that as the sort field for your view.

BTW, this is true for pretty much any Drupal release.

PS: as per the "*drag the item*" in your question, it could well be that you're using the "DraggableViews" module to create such view.

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


title: Form alter overriding submitted values

text:
# Question
Title: Form alter overriding submitted values
I have a form\_form\_id\_alter function that sets some default values and a checkbox checked.

If I submit the form, with the checkbox unset and it fails validation, the re-rendered form re-sets the checkbox to a checked state (as per the form\_alter), not the submitted state.

Is this expected behaviour? I would expect the submitted values to remain persistant.

Do I need to re-assign the submitted values in the form\_validate function or am I doing something wrong?

I'm using this function to alter form:

```
// Form ID alter
function events_form_registration_event_node_form_alter(&$form, &$form_state, $form_id){
  global $user;

  $form['#validate'][] = 'events_form_registration_event_node_form_validate';

  // If node add.
  if(arg(1) == 'add'){

    // Check if the user is an event editor and perform the form_alter
    if(events_does_user_have_role($user)){

      // Show end date, checkbox value checked
      $form['field_show_end_date'][LANGUAGE_NONE]['#attributes']['checked'] = 'checked';

      // Event status, list value Open
      $form['field_event_status'][LANGUAGE_NONE]['#default_value'] = 'Open';

    }
  }
}

// Validate form.
function events_form_registration_event_node_form_validate(&$form, &$form_state){

  // Get the current end date value from submitted form.
  $current_end_date_value = ($form_state['values']['field_show_end_date'][LANGUAGE_NONE][0]['value']);

  // Set the show_end_date element to have the submitted value.
  $form['field_show_end_date'][LANGUAGE_NONE]['#attributes']['checked'] = $current_end_date_value ;

}

```

# Answer
You need to check values of checkbox field in *$form\_state* while setting it "checked" in line

```
$form['field_show_end_date'][LANGUAGE_NONE]['#attributes']['checked'] = 'checked';

```

This would be something like

```
$form['field_show_end_date'][LANGUAGE_NONE]['#attributes']['checked'] = isset($form_state['values']['field_show_end_date'][LANGUAGE_NONE][0]['value']) ? $form_state['values']['field_show_end_date'][LANGUAGE_NONE][0]['value'] : 'checked';

```

I haven't tested this code, but it should work just fine or it will give you idea about how to fix your problem. Hope it helps...cheers!
> 0 votes

---
Tags: 7, forms
---


# Question
Title: How to make Rules ignore case sensitivity when comparing strings
I have an issue where I want to use Text Comparison in the Drupal Rules module but sometimes the case doesn't match (one is provided by user input and the other is provided by user data). It's comparing 2 emails.

The rule fires as expected if the text matches exactly, but if the text doesn't match case (ie example@example.com != Example@example.com) it doesn't fire.

Is there a way to get rules to ignore case?

The data that I'm getting to compare is as follows in text comparison:
user-data:mail
person-email

The user-data:mail is the email of the user who is submitting the webform, the person-email is the provided data to a ruleset coming from the webform that the user entered.

# Answer
> 0 votes
I've solved this by going about it this way:
In my component - as the conditional for my rule I execute custom PHP code to check against instead of just doing a text comparison:

```
if(strtolower($user_data->mail) == strtolower($preceptor_email)){
    return TRUE;
}

```

This is using the $user\_data as one parameter which is a user object, and $preceptor\_email which is a text object being passed to the component.

Thanks to Pinueve for his answer as I hadn't thought about executing custom PHP code to evaluate the conditional!

# Answer
> 2 votes
Make a custom module called 'email\_lowercase' and place this code inside it, before runnin this new action, do on both emails 'convert a data type' to 'text', then run the new action this custom module provides with Example@example.com TEXT-token-value you have just converted. After running custom action it will return a TEXT in lowercase, then comapre your email1-text-converted with the TEXT returned from custom module.

Note: you will nedd rules conditional module to compare (add conditional, add an IF) your variables AFTER this custom action is triggered. Done.

```
<?php
/**
* Implement hook_rules_action_info()
* Declare any meta data about actions for Rules
*/

function email_lowercase_rules_action_info() {
 $actions = array(
  'email_lowercase_action' => array(
    'label' => t('Convert to lowercase a TEXT email'),
    'group' => t('custom'),

    'parameter' => array(

        'email' => array(
                'type' => 'text',
                'label' => t('$text-variable-token-Email to be lowercase'),
                ),
    ),

    'provides' => array(
      'email_lower_case' => array(
        'type' => 'text',
        'label' => t('email in lower case'),
      ),
    ),
  ),
);
  return $actions;
}

// rules function numero a texto
function email_lowercase_action($email) {
  $email_lower_case = array();
  $email_lower_case = strtolower($email);

  return array (
  'email_lower_case' => $email_lower_case,
 );
}

```

NOTE: there are no EMAIL data types for rules, thats way i suggested to firts convert an email field to text. It may work if you don't, i did not tryed that.

---
Tags: rules
---


# Question
Title: Module with block plugin not using custom template
I am struggling to get my custom module template to get use by by block plugin.

I have followed the solution given at: Twig Template for a Custom Block Plugin but continually get this error:

> The website encountered an unexpected error. Please try again later. Twig\_Error\_Loader: Template "modules/custom/lrg\_osm/templates/block--osmnhd.html.twig" is not defined in Twig\_Loader\_Chain-\>getCacheKey() (line 64 of themes/contrib/bootstrap/templates/block/block.html.twig). Drupal\Core\Template\TwigEnvironment--\>getTemplateClass("modules/custom/lrg\_osm/templates/block--osmnhd.html.twig") (Line: 424)

I have tried to also fiddle the name of the twig file in various ways to not avail.

My module file structure is shown below with relevant code if anyone is able to point out the error of my ways please:

**src/Plugin/Block/osmnhdblock.php**

```
<?php
declare(strict_types=1);

namespace Drupal\lrg_osm\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\BlockPluginInterface;

/**
 * Provides a 'OSM Block for Home development Landing page' block.
 *
 * @Block(
 *   id = "osmnhdblock",
 *   admin_label = @Translation("OSM New Homes Development (NHD) block"),
 *   category = @Translation("LRG")
 * )
 */
class OsmNhdBlock extends BlockBase implements BlockPluginInterface
{
    /**
     * {@inheritdoc}
     *
     */
    public function build()
    {
        return array(
            '#theme' => 'osmtheme',
            '#jsonDataLocations' => 'nhd some data',
            '#title' => 'nhd some title',
        );

        /*
         '#attach' => [
                'css' => '/css/openstreetmap.css',
                'js' => '/js/openstreetmap.js',
            ],
         */
    }
}

```

**lrg\_osm.module**

```
<?php
declare(strict_types=1);

function lrg_osm_theme($existing, $type, $theme, $path) {

    return array('osmtheme' =>
        array(
            'variables' => array(
                'title' => null,
                'jsonDataLocations' => null
            ),
            'template' => 'block--osmnhd'
        )
    );
}

```

**templates/block--osmnhd.html.twig**

```
{#
/**
 * @file
 * Some description
 */
#}
<div class="col-md-12 block--osmnhdmap">
    <h1>{{ title }}</h1>
    <h2>{{ jsonDataLocations }}</h2>
</div>

```

# Answer
> 0 votes
The `templates` directory must always be a direct descendent of the module or theme root directory, in your case `/modules/custom/lrg_osm/templates/` (not modules/custom/lrg\_osm/`src/`templates/).

---
Tags: 8, theming
---


title: How to pull out Twig variables?

text:
# Question
Title: How to pull out Twig variables?
Trying to use some Twig variables (simple strings) in a template that I created from a custom module. Using the Devel and Kint modules I can see the info under Iterator contents with:

```
{{kint(transaction[0])}}

```

>

I just can't get the template to print it out on the page.

I tried this:

```
<b>$ {{transaction.amount }}</b> total donation<br/><br/>

```

and

```
<b>$ {{transaction[0].amount }}</b> total donation<br/><br/>

```

Either way comes up empty. Not sure what I'm missing here. It works in other modules just fine. Maybe I'm too high on the Twig templates? I don't understand the tree structure very well. I created a template called `transaction.html.twig`.

This is what my controller looks like.

>

This is the .module file. It's passing over from the controller to this theme which then passes it to the twig file. At least this is how all the tutorials tell me to do it. I create this same thing on another module and it works fine.

```
function touchdownclub_theme($existing, $type, $theme, $path) {

 return array(
    'touchdownclubtransaction' => array(
      'variables' => array(
        'transaction' => NULL,
      ),
       'template' => 'touchdownclubtransaction',
    ),
  );
}

```

# Answer
> 0 votes
I looked at some other modules controllers and saw that in the controller they used

```
$result = db_query
$output = $result->fetchAll();

```

Before pushing the code to the return array. I tried it and it worked for me like it should. Problem solved.

---
Tags: theming
---


# Question
Title: What's the best infrastructure to set permissions to user roles that controls who can see which Nodes and which Views?
I'm building a bsite that needs pretty stringent permissions. I have already created the (4) user roles for the site, but not sure the best way to handle viewing permissions.

I see that when creating Views it is pretty simple to assign which roles have permission to view, but what about for my content that is straight up page/nodes?

# Answer
I was able to accomplish this using Permissions By Term (https://www.drupal.org/project/permissions\_by\_term). After I installed, I completed the following steps:

* define member/student/guest roles in People \> Roles
* define Taxonomy structure (I named the vocabulary 'Page View Permissions')
* In order to apply these permissions to Basic Pages, edit the Content Type of Basic Page to add section to set the permissions when creating a Basic Page. (Create new Entity Reference field.) Set default to Public.
> 0 votes

# Answer
Sorry to disagree with your own (accepted) answer, but just in case you want to consider your solution described in your answer: This seems like a perfect usecase for the Group module.

Check it out, do some homework (experiments) with it, browse some of the question. Or checkout some of these questions.

For sure you'll understand what I mean. After you agree, you may reconsider your own answer ...
> 0 votes

---
Tags: views, 8, nodes, users
---


# Question
Title: Views Contextual Filter by taxonomy in field collection
I have a Drupal 7 project I'm working on that's got me stumped.
I'm building a site where the node (Decals) are applicable to models and years (This decal is correct for this model of this year). Each product my be applicable multiple models and multiple years.

I created a content type that has a field collection of model and years that can have unlimited values. So far so good.

Where i'm stuck is i want to have a related decals block at the bottom, that would suggest additional decals based not the models and years that listed in the field collection.
I've creating a view of nodes that has a relationship to the field collection, but I can't figure out how to limit the results to only the **models & years** associated to the node.

Any suggestions would be greatly appreciated.

# Answer
To introduce the terms referenced from a field collection field (in your case Model and Year) you first have to add the Relationship to the Field collection field. After that you can add Relationships to the terms referenced from there.

The goal is to list all nodes that share the same terms as the current one. This is usually called "sibling" nodes and is a very common request in Views.

In your case, there is one extra level of structure that the data flows through: the Field collection.

Usually, to display sibling nodes you first add the Relationship to the taxonomy field, then you add the "reverse" Relationship to all the nodes using terms from that field, and you make the second Relationship use the first one. This is where the magic happens, the matching of the current node terms with all the other nodes to find the ones that share the same terms. After that a simple Contextual Content ID is added with `Content ID from URL` as default value, but it must use the second Relationship.

In your case you will have more Relationships chained because of the Field collection.

F.c.R \> Model (term) \> Reverse Model (node) \> F.c.R

and then add Content ID Contextual filter that uses the last Relationship and set its default value to `Content ID from URL`.

I haven't tried this myself (I haven't used Field collections with Views) but it seems logical.

If it doesn't work see if these modules help: Taxonomy Entity Index, Taxonomy Deep Index
> 0 votes

# Answer
Once you have the Relationship to the Field collection, you can add all the other information you need (Relationships to Models and Years if necessary, you'll probably need them too).

Then if you go to add Contextual filters, you will see that Contextual filters for Models and Years fields have become available.

Configure each one to Provide default values from the node you're on (you choose that from the Drop-down under that option).

It's good to test Contextual filters one by one and make sure they work on their own before combining them.

Or in the Views Preview you can test by entering `all/[year]` to test the second one, or `[model]/all` to test the first one.

Then place the Block and test that they work in real environment, because Preview only tests the "from URL" part.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Conditionally register a user based on fields
I have a Drupal 8 User registration form that has several text fields to gather information about the user.

I'd like to write a custom hook that examines the values in those fields and then either proceeds with the registration or 'cancels' it, like perhaps redirecting to a static page or displaying some static content.

What are the hooks I need to make this happen? Do I alter the form? Or do I hook an entity\_presave function?

What do I need to do to cancel the default form processing or default entity presave/save routines?

thanks,

# Answer
Forms have a validate and submit function(s). Submit never runs unless all validation passes.

So all you have to do is add a custom validation

```
/*
 * Implements hook_form_FORM_ID_alter
 */
function mymodule_form_user_register_form_alter(&$form, FormStateInterface $form_state) {

  $form['#validate'][] = 'mymodule_registration_validate';

}

/*
 * Custom Validation
 */
function mymodule_registration_validate(&$form, FormStateInterface $form_state) {

  $field_name = $form_state->getValue('field_name'); // Gets the value entered by the user
  // Note: depending on your field type & settings sometimes this value is an
  // array, so you may have to keep drilling down.
  if($field_name != 'Hello World') { // perform check
    $message = t('Only Hello World is allowed'); // message to display
    $form_state->setErrorByName('field_name', $message); // set error
  }

}

```

`$form_state->setErrorByName` will display an error message and highlight the offending field in red.

If you want to redirect use `$form_state->setRedirectUrl($url);`
> 1 votes

---
Tags: 8, users
---


# Question
Title: How to disable field on register form but keep show in edit profile?
I need to know how to disable field on register form but keep show in edit profile? because now if I can only enable in both section, edit profile / register.

I need only show username + email field on register, but custom a lot of custom field on edit profile. thanks

# Answer
## Drupal 7

In D7 you can edit each user field under `Configuration > People > Account Settings > Manage Fields` and untick the option **Display on user registration form**.

## Drupal 8

In D8 after you add your fields under `Configuration > People > Account Settings > Manage Fields` go to `Configuration > People > Account Settings > Manage form display`, scroll down and uncollapse **Custom display settings**, tick the **Register** option and Save.

Now you will see two sub-tabs on that page: `Default` and `Register`. Visit the **Register** sub-tab and rearrange the fields to disable the ones you don't want. This will apply to the Registration form only.

The `Default` settings will apply to the User Edit form, so you'll want to keep the field enabled there.
> 2 votes

---
Tags: users
---


title: A Rule to copy the user's picture

text:
# Question
Title: A Rule to copy the user's picture
In Drupal 7.. I'm trying to create a rule that copies the user's profile picture into an image field on another content type. How can I select the 'picture' from a user's account, as a source for copying? The event is after updating an existing account, which provides the source 'account'. The File Field Rules module provides the copy action, but it requires a source field, and the user-picture isn't a field.

Another approach I tried is with the file URL. The FileField Sources module allows the use of a remote URL in an image field, but if I try to set the value of the image field with the token \[account:picture:url\] Rules doesn't allow it.

There is a similar question here Rules: Copying field from user's account to field in content type but the solution is with an additional field attached to the user, not with the default 'picture' one.

thanks, d

# Answer
> 2 votes
Install views rules module, make a views-rule of users, if you need UID as a contextual filer add it as always, then in middle column set your UID as an integer in parameters settings, add user pictures as a field, now in middle column settings, set user-pictures as an file entity. then in your rule, fetch entity by id with your variable UID, now you have user picture avilable and can be copied to your content type file field. Done, cheers.

---
Tags: users, rules
---


# Question
Title: How to add a custom icon or symbol to a flag link?
I'm working on a 'sample request' implementation for a commerce site using Flag, Views, sessions and a little custom code.

I'd like to add an icon or a symbol to let people know that an item they are viewing has been flagged.

I'm not sure exactly how to approach this, I can imagine perhaps adding a conditional field that displays an image or check box that is then changed by Rules or ajax, or perhaps something more complicated in JavaScript?

It could really be as simple as adding a checkbox that is checked or unchecked as the flag link is clicked or maybe even changing the css/html on click to be identified as marked.

Anyway, grateful for any advice here.

# Answer
# Option 1: Show an image beside the Flag text

You can use CSS to add padding to the left of the text and in it show a background image, as shown also in the community documentation about How to show an image beside the text. Here is an excerpt from it (replace "bookmarks" with the machine-name of your flag):

```
.flag-bookmarks a {
  padding-left: 20px;
}
.flag-bookmarks a.flag-action {
  background: url(images/i-dont-like-it.png) no-repeat left center;
}

.flag-bookmarks a.unflag-action {
  background: url(images/i-like-it.png) no-repeat left center;
}

```

Refer to the Flag Theming guide for (way) more details, i.e.:

* Theming flag links using CSS, which provides a "map" of the HTML that makes a flag link.
* Theming flag links using Templates, which explains how to use the `flag.tpl.php` file in the 'theme' folder that is located inside Flag's own folder, and which is used to generate the HTML for the Flag links. It also explains how you can theme different flags differently, using a flag specific `flag--FLAGNAME.tpl.php` file (whereas `FLAGNAME` is the flag's machine-name).
* Theming examples, which contains solutions to some common theming tasks.

# Option 2: Transform Flag link into a button

You can transform the Flag link into a button, by adding this CSS (quote from that link):

```
.flag-wrapper.{flag-name} a.flag-action {
  background-image: url('path to the button image');
  display:block;
  text-indent:-9999em;
}
.flag-wrapper.{flag-name} a.unflag-action {
  background-image: url('path to the button image');
  display:block;
  text-indent:-9999em;
}

```

**Notes**:

* `text-indent:-9999em` hides the element (by placing it off the screen).
* Replace `.{flag-name}` with your flag's machine-name.
> 14 votes

# Answer
If you are using the Flag module for rendering the flag link, then you can use following code for showing images instead link text:

```
function theme_preprocess_flag(&$vars){
    $state = ($vars['action'] == 'flag' ? 'off' : 'on');
    $image_file = $vars['directory'] . '/images/flag-' . $vars['flag']->name . '-' . $state . '.png';
    if (file_exists($image_file)) {
        $vars['link_text'] = theme_image(array('path' => $image_file,   'attributes' =>
        array('class' => array('flag-' . $vars['flag']->name . '-' . $state))));
     }
}

```

After using this code in `template.php` place images in your theme directory named like `flag-flag_machine_name>-off|on.png`.
> 6 votes

# Answer
Paste this code in template.php

```
function Your_theme_preprocess_flag(&$vars) {
  $class = ($vars['action'] == 'flag') ? '<i class="fa fa-heart-o">   </i>' : '<i class="fa fa-heart"></i>';
  $vars['link_text'] = $class;
  $title_wishlist = ($vars['action'] == 'flag') ? 'Add to wishlist' : 'Remove from wishlist';
  $vars['link_title'] = $title_wishlist;
}

```
> 4 votes

# Answer
After you copy the tpl file at `sites/all/modules/your_flag_module_name/flag_tpl_file` to your `sites/all/themes/your_theme_name/templates/paste tpl file`, you can change your tpl design according to your choice.

All variables are available on this tpl like flag status, etc.
> 3 votes

# Answer
With a Bootstrap theme (glyphicons built in) you can add an icon directly in the flags' text field (where you normally enter the text of the flag link) as well. Instead of writing the text enter something like this:

```
<span class="glyphicon glyphicon-arrow-up" aria-hidden="true"></span>

```
> 1 votes

# Answer
I know this is older post, but I wanted to add a simple solution using Fontawesome module and Flags module.

When creating a flag it asked you what text you want to type for the flag both “flag link text” and “unflag link text”

You can paste a fontawesme code in these boxes and it will render the fontawesome icons in the pages. This even works with views too. So add something like

```
<i class="far fa-bookmark"></i>

```

in those setting boxes, and it will work.
> 0 votes

---
Tags: 7, rules, flags
---


title: Migrating input formats causes errors

text:
# Question
Title: Migrating input formats causes errors
I am trying to write custom migrations to migrate my Drupal 7 website to Drupal 8. I am currently using Drupal 8.6.7 and Drupal 7.61 for a copy of the production website.

So far I have set up the D8 website with composer (docroot is path/to/web) (https://www.drupal.org/docs/develop/using-composer/using-composer-to-manage-drupal-site-dependencies )

I have always used Drush for maintenance actions on the D7 site and I am using Drush 9 for most of the actions including the migrations on the D8 site.

I have installed the most relevant modules in the D8 site so that I can start the migration, most notably all the D8 equivalents of the modules I used in the text formats/filters as well as migrate\_plus, migrate\_tools and migrate\_upgrade.

The migration files are generated with the Drush command:

```
drush @dev migrate-upgrade "$LEGACYDB" "$LEGACYURL" --configure-only --migration-prefix=osn_custom_

```

So far I have successfully migrated the users and their roles so I have some knowledge on how migrations work.

The problem I am currently working on is the migration of a custom content type called 'classified'. This type has a default Drupal 7 body field and a field 'field\_image'. So quite ordinary.

When I use the default generated migration file, it looks like everything is migrated, but the text is not visible. After research I found this is caused by the fact that the input format is set to the D7 code (in my case 2 aka 'full html') while there is no filter code in D8 that is called '2'. (src: https://www.drupal.org/docs/8/upgrade/known-issues-when-upgrading-from-drupal-6-or-7-to-drupal-8#d7\_to\_d8 ).

I decided that I might as well convert 2 to 'basic html' and use the D8 configuration and not migrate the D7 text filters at all.

I created a migration lookup plugin with a static map that converts all D7 codes to the preferred D8 code. It might work well, but I am running into the problem that I can't get the migration plugin to work with the migration of the 'classified' migration configuration. So I decided to simplify it and set the format to a default value 'basic\_html'.

Here is what I tried in the `migrate_plus.migration.osn_custom_d7_node_classified.yml` The code snippets below only show the body configuration, because the other field configurations are generated with the drush command and not altered.

```
body: body

```

the default. Content is migrated, input format is set to '2'.

According to this: https://www.drupal.org/docs/8/api/migrate-api/migrate-process-plugins/migrate-process-overview#nested

and this: https://medium.com/drupal-stories-an-insiders-view/migrate-api-custom-drupal-to-drupal-migration-3bab05da4686

and this: https://www.phase2technology.com/blog/drupal-8-migrations

it should be done like this:

```
  'body/format':
    plugin: default_value
    default_value: basic_html

  'body/value': body

```

However, this results in the following error:

> \[error\] InvalidArgumentException: Placeholders must have a trailing \[\] if they are to be expanded with an array of values. in /path/to/dev/web/core/lib/Drupal/Core/Database/Connection.php).
>
> \[error\] Placeholders must have a trailing \[\] if they are to be expanded with an array of values. (/path/to/dev/web/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php:783)

I have no clue what is wrong and what I should do instead. I also don't know how to debug this to find out what it's expecting.

Can someone please give me some pointers?

# Answer
> 4 votes
Thanks to @Jdrupal I finally found the solution in this link.

```
  body:
    plugin: sub_process
    source: body
    process:
      value: value
      format:
        plugin: default_value
        default_value: basic_html

```

(sorry I can't seem to get the mention appropriately formatted)

---
Tags: 8, migrations, input-formats
---


# Question
Title: How to place after each 5th item in a view a different content type?
I want to create a view with news which outputs another content type after every 5th result, in my case a newsletter subscription.

How can I do this?

# Answer
Views paging isn't conditional, so you can't assign different filters and other settings to different sets of result items.

But you can achieve what you want by creating different Views displays, each with its own filter settings, then display them one below the other on a page, style the output so it looks like it's coming from the same source.

If you make the different displays to be Attachment types, you will be able to make them display before or after the display they're attached to, all through the Views interface. If your original display is of Page type it's the most convenient to make the other ones as Attachment types.

You could also create Blocks display types, but then you have to place each one individually in a region of your theme and order them the way you want.

## Use Views Displays

Here are steps how to do it:

1. Edit your original view display to only show 5 items of only the one Content type you want to show up first.
2. Duplicate that display as an Attachment, then override the filter to show a different content type and set it to attach after the first display
3. Duplicate the Attachement and repeat the edit: override the filter to show the third content type and set it to attach after the first display
4. Repeat again if you have more content types
5. Use CSS to style the attachments without gaps in between them so they look like they are one unit in your design
> 0 votes

---
Tags: views, 8
---


# Question
Title: Submit form load results instead of messages
I am testing out the new Drupal 8 custom modules and currently stuck with the submit form handler to load form submitted results in the same page and my current functions of last submit is this (inside the controller form) :

```
    <?php
/**
 * @file
 * Contains \Drupal\resume\Form\ResumeForm.
 */
namespace Drupal\resume\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class ResumeForm extends FormBase {
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'resume_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['candidate_name'] = array(
      '#type' => 'textfield',
      '#title' => t('Candidate Name:'),
      '#required' => TRUE,
    );

    $form['candidate_mail'] = array(
      '#type' => 'email',
      '#title' => t('Email ID:'),
      '#required' => TRUE,
    );

    $form['candidate_number'] = array (
      '#type' => 'tel',
      '#title' => t('Mobile no'),
    );

    $form['candidate_dob'] = array (
      '#type' => 'date',
      '#title' => t('DOB'),
      '#required' => TRUE,
    );

    $form['candidate_gender'] = array (
      '#type' => 'select',
      '#title' => ('Gender'),
      '#options' => array(
        'Female' => t('Female'),
        'male' => t('Male'),
      ),
    );

    $form['candidate_confirmation'] = array (
      '#type' => 'radios',
      '#title' => ('Are you above 18 years old?'),
      '#options' => array(
        'Yes' =>t('Yes'),
        'No' =>t('No')
      ),
    );

    $form['candidate_copy'] = array(
      '#type' => 'checkbox',
      '#title' => t('Send me a copy of the application.'),
    );

    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Save'),
      '#button_type' => 'primary',
    );
    return $form;
  }

  /**
   * {@inheritdoc}
   */
    public function validateForm(array &$form, FormStateInterface $form_state) {

      if (strlen($form_state->getValue('candidate_number')) < 10) {
        $form_state->setErrorByName('candidate_number', $this->t('Mobile number is too short.'));
      }

    }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

   // drupal_set_message($this->t('@can_name ,Your application is being submitted!', array('@can_name' => $form_state->getValue('candidate_name'))));

    foreach ($form_state->getValues() as $key => $value) {
      drupal_set_message($key . ': ' . $value);
    }

   }
}

```

I wanted to show results in a table in the same page form where user submit the form, rather than just throwing in messages

thank you

# Answer
> 1 votes
The example of @Ajay was not working for me. This one do. Hope this help.

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

    // Your $form fields here ...

    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Save'),
      '#button_type' => 'primary',
    );

    // Render this field bellow the submit button and above return $form.
    if (!empty($formValues = $form_state->getValues())){

      $header = ["Key","Value"];

      $output = [];
      foreach ($formValues as $key => $value) {
        if ($key=='submit'){
          break;
        }
        $output[$key]['key'] = $key;
        $output[$key]['value'] = $value;
      }

      $form['mytable'] = [
        '#type' => 'table',
        '#header' => $header,
        '#rows' => $output,
        '#empty' => t('No Data'),
      ];
    }

    return $form;
}

public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_state->setRebuild();
}

```

Soon I'll write a post about other ways to render form's data in a controller or even with a Private Temp Storage

# Answer
> 0 votes
After submit check for

```
     if(isset($form_state->getValues())){
        $header = array(
          array('key' => t('Key')),
          array('value' => t('Value')),
        );
        $output = array();
        foreach ($form_state->getValues() as $key => $value) {
           $output['key'] = $key;
           $output['value'] = $value;
        }
        $form['mytable'] = array(
          '#type' => 'table',
          '#header' => $header,
          '#rows' => $output,
          '#empty' => t('No Data'),
        )),
     }

```

in buildForm and try like this.

---
Tags: forms, 8
---


# Question
Title: Print commerce pricing attributes to email receipt
Users cannot see what size or color shirt they purchased in the email receipt because tokens won't print the attribute fields provided by Commerce Product Attributes / Commerce Pricing Attributes / Commerce Product Option combo.

1. User selects shirt size: XL and color: Green
2. Both fields can be previewed during checkout.
3. Email receipt received doesn't show any attributes, user cannot check what size/color they ordered. (All this can be achieved using default CCK fields under product type, but we're using the combination mentioned above for multiple reasons, many products got different option sets to chose from and certain attributes selected adds extra price to total, like eg size: XXXL costs extra $3+ and this cannot be achieved with default fields).

One of the tokens I found is like eg. `[commerce-order:commerce-line-items:0:commerce-pricing-attributes]` and email on checkout prints it like this:

```
Product: BK Test

a:1:{s:9:"coveralls";a:8:{s:25:"field_coverall_embroidery";N;s:25:"field_coverall_text_color";N;s:10:"field_font";N;s:16:"field_shirt_name";N;s:16:"field_patch_side";N;s:12:"field_length";s:1:"2";s:21:"field_coveralls_color";s:1:"4";s:19:"field_coverall_size";s:2:"16";}}

```

Also more tokens available at `admin/help/token` like eg.: `Attributes [commerce-line-item:commerce-product:field_attributes] Pricing Attributes field.` and combining them with `[commerce-order:commerce-line-items:0:commerce-product]` won't work, already tried dozens of variations.

E.g. in Order's view page I addded the view `Commerce Line Item: Product Attributes` and it displays correctly.

How to print this in the email receipt?

# Answer
> 1 votes
install views rules module, make a views-rules of orders, you will need OID as a contextual filter, add it as allways, then in middle column, in parameters settings set your OID as:integer, add all fields/attributes you wish, now in middle column settings, set your fields/attributes values as text, choose 'use rendered output'.

Then in your send-email-to-customer rule, add a views-rule with your new view, actions: fecth entity by id:ORDER with your variable OID, now you have all fields/attributes you added avilable as tokens, built your email body like: thanks \[user:name\], your order \[OID\] is in proccess, you bought : T-shirt \[tshirt:value\], T-shirt-size: \[tshirt-size:value\], ............. .

if you can not use HTML tags, here is an exported rules\_action\_info() rules code that i used in one site, adds a new action: build-email-body, it shows you how to built a row for a 'nice' html look alike. if you need this feature, you will need to make a custom module called: rulesbodyemail, change all $variables and code as needed, take a close look how is built variable: $text\_formatted\_body, and is how is returned.

```
<?php
/**
 * Implement hook_rules_action_info()
 * Declare any meta data about actions for Rules
 */

 function rulesbodyemail_rules_action_info() {

 $actions = array(
'buitl_email_body' => array(
    'label' => t('build-email-body'),
    'group' => t('cadena'),

    'parameter' => array(

      'node_id' => array(
              'type' => 'integer',
              'label' => t('node id'),
              ),

      'parcialidad_title' => array(
              'type' => 'text',
              'label' => t('parcialidad_title'),
              ),

      'parcialidad_monto' => array(
              'type' => 'decimal',
              'label' => t('parcialidad monto'),
              ),
      'parcialidad_cliente' => array(
              'type' => 'text',
              'label' => t('cliente'),
              ),

      'parcialidad_fecha' => array(
              'type' => 'date',
              'label' => t('parcialidad fecha'),
              ),
      'parcialidad_aseguradora' => array(
              'type' => 'text',
              'label' => t('cia aseguradora'),
              ),

      'parcialidad_ramo' => array(
              'type' => 'text',
              'label' => t('ramo'),
              ),

        'parcialidad_cobertura' => array(
                'type' => 'text',
                'label' => t('cobertura'),
                ),

        'parcialidad_fecha_formateada' => array(
                'type' => 'text',
                'label' => t('feha formateada'),
                ),

          ),

    'provides' => array(
        'text_formatted_body' => array(
                'type' => 'text',
                'label' => t('text_formatted body'),
                'wrap' => TRUE,
                //'format' => 'full_html'
                ),
              ),
  ),
);
  return $actions;

 } // fin de actions_info

// rules function procesar row
function buitl_email_body($node_id, $parcialidad_title, $parcialidad_monto,
$parcialidad_cliente, $parcialidad_fecha, $parcialidad_aseguradora,
$parcialidad_ramo, $parcialidad_cobertura, $parcialidad_fecha_formateada) {

// variable $hoy esta en UNIX
$hoy = time();
$formatted_hoy = date('j/M/y', $hoy);

  //drupal_set_message($parcialidad_fecha_int . ' $parcialidad_fecha ', 'status', FALSE);
  //drupal_set_message($formatted_fecha . ' $formatted_fecha ', 'status', FALSE);

  //prepara las variables y calcula dias vencidos
  $parcialidad_fecha_int = strip_tags($parcialidad_fecha);
  $hoy_int = (int)$hoy;
  $fecha_int = (int)$parcialidad_fecha_int;
  $diff = $hoy_int - $fecha_int;
  $diff = round($diff/86400);

  // formato fecha y $ pesos

  $monto_format = "$".number_format($parcialidad_monto, 2);
  $formatted_fecha = date('j/M/y', $parcialidad_fecha_int);

  //hace el render del row
  $text_formatted_body =
  "
  ▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁

  ▲ PARCIALIDAD ▲ $parcialidad_cliente

    Parcialidad: $parcialidad_title
    Monto:  $monto_format
    Venció: $formatted_fecha; Días vencidos: $diff

    Aseguradora : $parcialidad_aseguradora
    Ramo: $parcialidad_ramo; Cobertura: $parcialidad_cobertura

  " ;

  //return $text_formatted_body
  return array('text_formatted_body' => $text_formatted_body);

  } // fin de funcion rules procesar row

```

it returns this as the email body:

image of rule to send emails:

image of body email value

# Answer
> 1 votes
```
<?php

/**
 * Implements hook_token_info().
 */
function mymodule_token_info(){
    $info['tokens']['commerce-order']['line_item_detail'] = array(
        'name' => t('Line Item Product Detail List'),
        'description' => t('List all the Product Line Item Detail of the order')
    );
    return $info;
}

/**
 * Implements hook_tokens().
 */
function mymodule_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();

  if($type == 'commerce-order'){
    $order = $data['commerce-order'];
    $order_wrapper = entity_metadata_wrapper('commerce_order',$order);
    $lineItems = $order_wrapper->commerce_line_items->value();
    $lineItemArray = array();
    foreach($lineItems as $key => $value){
        $line_item_wrapper = entity_metadata_wrapper('commerce_line_item',$value);
        if($line_item_wrapper->type->value()=='product'){
            $product_title = $line_item_wrapper->commerce_product->title->value();
            $quantity = $line_item_wrapper->quantity->value();
            $lineItemArray[] =  $product_title.' x '.$quantity;
        }
    }

    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'line_item_detail':
            $variables = array(
                'items' => $lineItemArray,
                'type' => 'ul',
            );
            $replacements[$original] = theme('item_list', $variables);
            break;
      }
    }
  }
  return $replacements;
}

```

This is the sample code.

You can modify the result you want at hook\_tokens().

I hope this will help you.

---
Tags: 7, views, commerce, emails, tokens
---


title: Entity form submission sending email

text:
# Question
Title: Entity form submission sending email
I'm working on entity form using the module "eform" in D8.

I would like it to send email when the user submits a form. It was done using some other modules rules and entity rules, but since "entity rules" is not released yet in D8, I couldn't find a way to send submission email. Is there any module to make it possible or should I create a custom module to do that?

# Answer
I've asked the question multiple times. It appears that we need to wait for Rules. For the time-being, I'm using the built-in drupal contact form + contact\_storage module for form. It's not the best, but it works.
> 0 votes

# Answer
I can see 2 ways to achieve it programmatically.

1. Using Hooks.
2. Using the Events system.

1) You can use "hook\_ENTITY\_TYPE\_insert" in your module file. In this function/hook, you can trigger mail.

2) I believe using event system will be a better approach instead of using hooks. Currently, Drupal core doesn't provide any Events for entity(node) transactions like add/edit/delete. For this purpose, you can use "Entity Events" module. All steps are given module page. If you don't want to use the contributed module, you can create your own events to listen to entity-based transactions.
> 0 votes

---
Tags: 8, entities
---