title: How to display a pseudo field in a view

text:
# Question
Title: How to display a pseudo field in a view
I have created a pseudo field with this code:

```
/**
 * Implements hook_entity_extra_field_info().
 */
function MYMODULE_entity_extra_field_info() {

  $extra['node']['my_bundle']['display']['my_pseudo_field'] = [
    'label'       => t('Pseudo Label'),
    'description' => t('Pseudo description'),
    'weight'      => 100,
    'visible'     => TRUE,
  ];

  return $extra;
}

/**
 * Implements hook_ENTITY_TYPE_view().
 */
function MYMODULE_node_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode, $langcode = 'fr') {

  if ($display->getComponent('my_pseudo_field')) {

    $build['my_pseudo_field'] = [
      '#markup' => 'This is my pseudo content',
    ];
  }
}

```

Everything is working fine, except that I couldn't add it in a view.

# Answer
> 7 votes
With the help of 4k4, I could solve my problem... I will start by explain my first try, which could be a good solution in some cases, then I will explain/show how I finally end up.

Firstly I created my computed field in `hook_entity_base_field_info_alter` \[Note that this is not a pseudo field this time\]

```
function my_module_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
    if ($entity_type->id() === "node") {
      ...field is created here... will show you how to after
    }
}

```

Secondly, we need to create a class (that will perform the calculation) for the computed field (will show you after)

Thirdly, we can display this field in a view simply by implementing `hook_views_data_alter`... This is the beauty of this solution: the view integration is made very quickly. Here is the how the hook is implemented

```
function my_module_views_data_alter(array &$data) {
  $data['node']['my_computed_field'] = [
    'title' => t('My computed field'),
    'field' => [
      'id' => 'field',
      'default_formatter' => 'string',
      'field_name' => 'my_computed_field',
    ],
  ];
}

```

What was not good in my case, is the fact that my computed field does appears in all bundles (even if I use `setTargetBundle('my_bundle')` like showed below).

Thus I changed a little bit my computed field process creation:

**1-Create the computed field** in `hook_entity_bundle_field_info_alter` ... not in `_entity_base_field_info_alter` (As you can see, it is a float field... youn could use a string)

```
function my_module_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle)
{
    if ($entity_type->id() == 'node' && $bundle == 'my_bundle' ) {
        $fields['my_computed_field'] = BaseFieldDefinition::create('float')
        ->setName('my_computed_field')
        ->setLabel(t('Nombre de litres total'))
        ->setComputed(TRUE)
        ->setTargetEntityTypeId('node')
        ->setTargetBundle('my_bundle')
        ->setClass('\Drupal\my_module\MyComputedFieldItemList')
        ->setDisplayOptions('view', [
            'type' => 'float',
            'weight' => 0,
        ])
        ->setDisplayConfigurable('view', TRUE);
    }

}

```

Note: if someone know the purpose of `->setTargetBundle('my_bundle')` I would be glad to read anything on it as I added it without knowing if it is mandatory/usefull.

**2-Extend `FieldItemList`** (MyComputedFieldItemList) \[use the same name as in `->setClass('\Drupal\my_module\MyComputedFieldItemList')`\]

The main point here is the protected function `computeValue` that will use $node to compute the value.

```
<?php
namespace Drupal\my_module;

use Drupal\Core\Field\FieldItemList;
use Drupal\Core\TypedData\ComputedItemListTrait;

/**
 * Item list for a computed field that displays the total liter for a soup.
 *
 */
class MyComputedFieldItemList extends FieldItemList
{

    /**
     *
     * {@inheritdoc}
     */
    use ComputedItemListTrait;

    protected function computeValue()
    {
        $node = $this->getEntity();
        if (! $node->isNew()) {
            $this->list[0] = $this->createItem(0, my_module_function_to_compute($node));
        }
    }
}

```

At this stage, you have a computed field that you can display in "my\_bundle"... Lets go to the view integration

3-Alter `hook_views_data_alter` to tell views that you have a new computed field linked to a node. The main point here is the id `my_computed_field`

```
function my_module_views_data_alter(&$data)
{
    $data['node']['my_computed_field'] = array(
        'title' => t('My computed result'),
        'group' => t('Content'),
        'field' => array(
            'title' => t('My computed result'),
            'help' => t('bla bla.'),
            'id' => 'my_computed_field',
        ),
    );
}

```

4-Thanks to 4k4, I understood that you need to **create a plugin class** that will have a `render` function to show the result in the view. The second important thing here is the `@ViewsField("my_computed_field")` annotation that needs to be the same as the id in step 3

```
<?php
/**
 * @file
 * Definition of Drupal\my_module\Plugin\views\field\ComputeField
 */

namespace Drupal\my_module\Plugin\views\field;

use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\ResultRow;

/**
 * Field handler to flag the node type.
 *
 * @ingroup views_field_handlers
 *
 * @ViewsField("my_computed_field")
 */
class ComputeField extends FieldPluginBase {

    /**
     * @{inheritdoc}
     */
    public function query() {
        // Leave empty to avoid a query on this field.
    }

    /**
     * @{inheritdoc}
     */
    public function render(ResultRow $values) {
        $node = $values->_entity;
        if ($node->bundle() == 'my_bundle') {
            return my_module_function_to_compute($node);
        }
    }
}

```

Now, everything runs fine:

* The field could be displayed (or not) in any display mode and you can change the settings in the UI as any regular field
* The field could be inserted in a node view
* There is a function `my_module_function_to_compute($node)` that you can put in your module. This function will compute the result of your field with the entity as argument (node here)

**One thing is missing**: the sort (in the view) doesn't work... I have to dig into it

---
Tags: views, 8
---


# Question
Title: Drupal 8 - what is application bootstrapper or auto-loader
I was working on a module in Drupal 8, and came across this thread answering a question on class auto-loading for Doctrine annotations: https://stackoverflow.com/questions/14629137/jmsserializer-stand-alone-annotation-does-not-exist-or-cannot-be-auto-loaded

At multiple places in the above referenced thread, the OP or answerers reference to something like an application bootstrapper. For example, OP updated the question with:

> EDIT: my final solution was to create a bootstrap file with the following content:

Another comment says:

> I put this in my application bootrapper (/app/boostrap/app.php), although it could go in the autoloader (/app/boostrap/autoload.php) as well as long as it follows the composer autoload

Although I think I understand how class auto-loading works in Drupal 8, its relation to composer, Drupal's own bootstrapping (which afaik usually refers to Drupal initialising itself for a page load) and ability to use composer to add dependency on packages for a Drupal installation, I have no idea what "application bootstrapper" means in Drupal 8, or special significance of these files (/app/boostrap/app.php, /app/boostrap/autoload.php).

Am I missing something or were people referring to composer packages (and not a Drupal 8 concept) when they used these terms.

# Answer
> 1 votes
Yep this is because of composer ... you will see one if you install anything using composer. here is an example of an autoloader that is automatically created by Composer.

```
?php

/**
 * @file
 * Includes the autoloader created by Composer.
 *
 * This file was generated by drupal-composer/drupal-scaffold.
 * https://github.com/drupal-composer/drupal-scaffold
 *
 * @see composer.json
 * @see index.php
 * @see core/install.php
 * @see core/rebuild.php
 * @see core/modules/statistics/statistics.php
 */

return require __DIR__ . '/../vendor/autoload.php';

```

---
Tags: 8, composer, bootstrapping
---


# Question
Title: Using a view result as allowed_options in a text(list) field
I have a set of values that are created in a different node, and I would like to use them as the allowed values for a field in another node. So, I have a view that collect the values and I have a `hook_allowed_values` function to create the `allowed_values` list. My function is:

```
function hnbuilder_fheq_allowed_values(FieldStorageConfig $definition, ContentEntityInterface $entity = NULL, $cacheable){
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface) {
        $nid = $node->id();
    }
    $view_id = 'default';
    $args = $nid;
    $result = views_get_view_result('outcomes',$view_id,$args);
    return $result;
}

```

My problem is that my `views_get_view_result` is not returning anything. I get the correct `$nid`, and pass this to the `views...result`. The view, on its own, works fine. But if `kint($result)`, I get nothing.

I've updated the config for the field, to make it call the `hook_allowed_values` function.

What am I doing wrong?

# Answer
Here's what I ended up with...

```
function hnbuilder_fheq_allowed_values(FieldStorageConfig $definition, ContentEntityInterface $entity = NULL, $cacheable){
    $node = \Drupal::routeMatch()->getParameter('node');
    //kint($node->bundle());
        if ($node instanceof \Drupal\node\NodeInterface) {
            $thisnid = $node->get('nid')->value;
            if($node->bundle() != 'qualification'){
                $nid = $node->get('field_qualification')->target_id;
                }
        }
        $args=[$nid];
        $values = [];
        $view = Views::getView('outcomes');

        if (is_object($view)){
            $view->setArguments($args);
            $view->setDisplay('default');
            $view->execute();
            foreach($view->result as $rid=>$row){
                foreach ($view->field as $fid => $field ) {
                    $values[$rid][$fid . '-value'] = $field->getValue($row);
                    $my_options[$values[$rid]['field_fheq_code-value']] = "[".$values[$rid]['field_fheq_code-value']."]- ".$values[$rid]['field_fheq_description-value'];
                }
            }
        return $my_options;
    }
}

```
> 0 votes

---
Tags: views, 8
---


# Question
Title: Related articles popup with Entity Reference View Widget
For the Articles, I have added below field.

```
Related Articles -> field_related_articles  -> Entity reference

```

So it's view like this

Now it's not very user friendly. So I want to create Popup where user can search & select articles.

https://www.drupal.org/project/entityreference\_view\_widget

I found above, but it's not supporting Drupal 8.

Anyone have idea how to implement this?

# Answer
> 1 votes
1) You can change the field widget for the form display at yoursite/admin/structure/types/manage/article/form-display.

2)You could check this out for a combination of inline entity form and entity browser modules https://github.com/drupal-media/d8-guide/blob/master/modules/entity\_browser/inline\_entity\_form.md  3) If you choose 1) and you change the field widget to a dropdown select list, you can also use the "chosen" module https://www.drupal.org/project/chosen for a better user experience

---
Tags: 8
---


title: Override breadcrumbs is not present?

text:
# Question
Title: Override breadcrumbs is not present?
In Drupal 7, in the views with an argument, is easy to override both title and breadcrumbs.

Now in Drupal 8 I can't find the option.

Did I miss something? or isn't possible? In this case what is the workaround?

# Answer
Here is a few workarounds:

1) You may need to look in to creating a service in a custom module example: yourmodule.service.yml

```
services:
  someviews.breadcrumb:
    class: Drupal\yourmodule\HelpBreadcrumbBuilder
    arguments: ['@entity.manager']
    tags:
      - { name: breadcrumb_builder, priority: 701 }

```

Then in yourmodule/src/HelpBreadcrumbBuilder.php

```
namespace Drupal\yourmodule;

use Drupal\Core\Breadcrumb\Breadcrumb;
use Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface;
use Drupal\Core\Link;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;

/**
 * Provides a breadcrumb builder for whatever.
 */
class HelpBreadcrumbBuilder implements BreadcrumbBuilderInterface {

  use StringTranslationTrait;

  /**
   * {@inheritdoc}
   */
  public function applies(RouteMatchInterface $route_match) {
    return preg_match('/view\.your_view_name\./', $route_match->getRouteName());
  }

  /**
   * {@inheritdoc}
   */
  public function build(RouteMatchInterface $route_match) {
    $breadcrumb = new Breadcrumb();
    $breadcrumb->addLink(Link::createFromRoute($this->t('Home'), ''));
    $breadcrumb->addLink(Link::createFromRoute($this->t('something'), ''));
    $breadcrumb->addCacheTags(['config:views.view.youviewname']);
    $breadcrumb->addCacheContexts(['url.path']);
    $params = $route_match->getParameters();
    if ($params->has('arg_0') && !empty($params->get('arg_0'))) {
      $title = ucwords(str_replace('-', ' ', $params->get('arg_0')));
      $breadcrumb->addLink(Link::createFromRoute($title, ''));
    }
    return $breadcrumb;
  }
}

```

The above is not an exact example fit to your requirement but show you how to get in and change the breadcrumbs ect.

or look at examples for "hook\_system\_breadcrumb\_alter", https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Menu%21menu.api.php/function/hook\_system\_breadcrumb\_alter/8.2.x
> 0 votes

---
Tags: views, 8, breadcrumbs
---


# Question
Title: How to count the number of nodes with a certain taxonomy term, based on a list of nids?
The users on my website have an integer field *My medals*, which can contain an unlimited amount of values, representing nids from nodes of the type *Medal*. Every *Medal* node contains one term of the taxonomy *Colour* (either *Gold*, *Silver* and *Bronze*).

Given a certain uid, I would like to create a View that shows the total number of nodes per taxonomy term, based on the user's field *My medals*.

**Example.** Suppose the nodes with nids 1, 2 and 3 have a *Gold* term, the node with nid 4 has a *Silver* term, and the node with nid 5 has a *Bronze* term. Let user 1 have a *My medals* field with values 1, 2, 4, 5. Then the View should return "**Gold:** 2, **Silver:** 1, **Bronze:** 1" when the uid 1 is given.

# Answer
Mmm i dont think drupal 7 views is up to this perhaps this work around may help create a custom module and put

```
/**
 * Implements hook_block_info().
 */
function mymodule_block_info() {
  $blocks = [];
  $blocks['my_block'] = [
    'info' => t('My Medals'),
  ];
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function mymodule_block_view($delta = '') {
  $block = array();
  switch($delta) {
    case 'my_block' :
      $block['content'] = my_block_view();
      break;
  }
  return $block;
}

function my_block_view() {
  global $user;
  $uid = $user->uid;

  $result = db_query('SELECT * FROM {node} WHERE uid = :uid AND type = :type', [
   ':uid' => $uid,
   ':type' => 'post'
  ]);
  $node_ids = [];
  foreach ($result as $row) {
    $node_ids[] = $row->nid;
  }
  $output = '';
  $gold = [];
  $silver = [];
  $bron = [];
  if (count($node_ids) != 0) {
    foreach ($node_ids as $nid) {
      $node = node_load($nid);
      $tid = $node->field_term['und'][0]['tid'];
      switch($tid) {
        case 1;
          $gold[] = $nid;
        break;
        case 2;
          $silver[] = $nid;
        break;
        case 3;
          $bron[] = $nid;
        break;
        default;
        break;
      }
    }
  }
// bad practice but quick win.
  $output = 'GOLD ' . count($gold) . ' Silver ' . count($silver) . ' Bronze ' . count($bron);
  $block = [
    '#type' => 'markup',
    '#markup' => $output,
  ];
  return $block;
}

```

The above will create a custom block then you have to place the block on the user and change the "global $user; $uid" to fit your need.
> 0 votes

---
Tags: 7, views
---


title: Trying to create a block plugin module

text:
# Question
Title: Trying to create a block plugin module
I am trying to write a custom block module in Drupal 8 that will allow me to place this block into my pages using the block layout screen.

I'm very new to Drupal, so this is very much a "hello world" project (initially) to figure out how this works. To this end, I have been following Youtube video instructions as well as reading through whatever documentation I can find on Internet and also a couple of books, but to no avail \[yet\].

What I have done is creating a *walker* directory in the *modules* folder, where I have created the Walker.info.yml file, whose content is the following.

```
name: Walker
description: A filewalker
core: 8.x
package: Custom
type: module

```

In the same directory, I have created the Walker.module file.

```
/**
 * @file
 * Code for the walker module.
 */

```

I have then created the module/walker/src/Plugin/Block/ directory and the WalkerBlock.php file with the following content.

```
/**
 * @file
 * Code for the walker block.
 */

namespace Drupal\walker\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a walker block
 *
 * @Block(
 *   id = "walker",
 *   admin_label = @Translation("The walker block"),
 *   category = @Translation("Blocks")
 * )
 */

class WalkerBlock extends BlockBase {
  public function build() {
    return array('#markup' => 'Walker block');
  }
}

```

If I run the command "`find . -type f | grep Walker`" from my root Drupal directory, I get the following output.

```
./modules/Walker/Walker.module
./modules/Walker/src/Plugin/Block/WalkerBlock.php
./modules/Walker/Walker.info.yml

```

Yet, though the documentation and videos I have read suggest that this *should* be all I require, the Walker block does *not* appear in the block layout screen as an option that I can place in one of the block regions.

Can anyone see what I'm doing wrong?

I cleared the cache from /admin/config/development/performance.

# Answer
Ok can you go to drupal8/admin/modules

and see :

Your:

* walker.info.yml is correct
* your Walker.module id fine (however i would use (walker as the dir and walker.module aka non caps)
* your block looks fine

Thinking Rename all to ./modules/walker/walker.module ./modules/walker/src/Plugin/Block/WalkerBlock.php ./modules/walker/walker.info.yml

as could be Name space issue as "Drupal\walker\Plugin\Block" vs "Drupal\Walker\Plugin\Block" ?

but really every thing looks fine When you install the module you should be able to place the block in admin/structure/block
> 0 votes

# Answer
Ok lets review it all.

Your info file looks good.

walker.info.yml: (try to use only lowercasse for the name of your \*yml files)

```
name: Walker
description: A filewalker
core: 8.x
package: Custom
type: module

```

walker.module:

```
<?php
/**
 * @file
 * Code for the walker module.
 */

```

When you use the `@file` you are making a reference to drupal to a file, in this case you don't need that. In this moment your walker.module should look like:

```
<?php

```

Nothing else.

Next you need a controller, that it seems that you don't have it yet, it should be at `/modules/walker/src/Controller` and the name should be something like WalkerController.php (In this case you are allow to use uppercase), so the walker controller should be this way:

WalkerController.php

```
<?php
/**
 * @file
 * Contains \Drupal\walker\Controller\WalkerController.
 */
namespace Drupal\walker\Controller;

use Drupal\Core\Controller\ControllerBase;

class WalkerController extends ControllerBase {

  /**
   * Display the markup.
   *
   * @return array
   */

  public function content() {
    return array(
      '#type' => 'markup',
      '#markup' => t('Walker Sample Text Block!'),
    );
  }
}

```

As you can see here we are using the `public function content()` to generate the sample text and this is done on the WalkerController.php not in the plugin Block.

Now we'll take a look at the WalkerBlock.php this pluging it's mainly (not only) used to create a form for the administrator user to modify the content that this block will display and it normaly looks like:

WalkerBlock.php

```
<?php

namespace Drupal\walker\Plugin\Block;

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

/**
 * Provides a 'Walker Content Block Form' Block.
 *
 * @Block(
 *   id = "walker",
 *   admin_label = @Translation("Walker Content Block Form"),
 *   category = @Translation("Walker Content Block Form"),
 * )
 */

class WalkerBlock extends BlockBase implements BlockPluginInterface {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $name = $config['walker_name'];
   $block = array
    (
  'hello' => array
        (
   '#prefix' => '<p>',
   '#suffix' => '</p>',
         '#markup' => t('hello'),
        ),
  'name' => array
        (
   '#prefix' => '<p>',
   '#suffix' => '</p>',
         '#markup' => t('@name', array('@name' => $name,)),
        )
    );
return $block;
  }//End build

  /**
  * {@inheritdoc}
  */
  public function blockForm($form, FormStateInterface $form_state) {
    $form = parent::blockForm($form, $form_state);
    $config = $this->getConfiguration();
    $form['walker_name'] = array(
       '#type' => 'textfield',
       '#description' => 'Name to say Hello to',
    );

  }
  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
       $this->configuration['walker_name'] = $form_state->getValue('walker_name');
  }//End blockSubmit

}//End Class

```

So, in this case the WalkerBlock.php is creating a form to configure the block you set in the region. Don't forget to clean the cache, reload and you should be able to see your block at the layout structure. Go to you block layout click "configure" and you'll see a text field asking for a name, lets say you type "walker" then in the content page will show you "Hello walker".

Youtube tutorials are good but sometime they miss important thinks i recommend you take a look HERE
> 0 votes

---
Tags: 8, plugins
---


# Question
Title: How do I send a customized email to subscribed users?
I have a *post job* content type. When an employer posts a job, all the registered users, basing on the job category (taxonomy), should receive an email about the posted job.

How should I implement this?

# Answer
You'll have to write some code, essentially you need to hook in when Job node is created, find the users referencing to that taxonomy the Job has and then use the Mail service, something like (pseudo)

When a Job node is created

Get all user that has a reference to the created Node's taxonomy:

`$job_tax_tid = $node->get('job_taxonomy')->target_id`

Then find the users, perhaps by using a Entity Query:

```
$ids = \Drupal::entityQuery('user')
  ->condition('status', 1)
  ->condition('field_job_refs', $job_tax_tid)
  ->execute();
$users = User::loadMultiple($ids);

```

To send mail programmatically, you need to use the MailManager: http://valuebound.com/resources/blog/how-to-send-mail-programmatically-drupal-8

Since there can be many users that needs to receive an email, you maybe want to use the Queue or Batch operations.

https://api.drupal.org/api/drupal/core%21includes%21form.inc/group/batch/8.2.x

https://api.drupal.org/api/drupal/core!core.api.php/group/queue/8.2.x
> 1 votes

---
Tags: 8, emails
---


title: Email validation for user signup form

text:
# Question
Title: Email validation for user signup form
I am creating a website for submissions. I want the users to register only with "abc.def@mycompany.com". I want to avoid e-mail ids such as @gmail, @yahoo, @hotmail etc during registration.

True: email should be @mycompany

False: email with @gmail, @yahoo, @hotmail

What should I do to achieve the result?

Thanks in advance

# Answer
Can be managed by strpos easily. Below code will be in `validateForm` function

```
 $email = 'abc.def@mycompany.com';
 if (valid_email_address($email)) {
  if (strpos($email, '@mycompany.com') !== FALSE) {
       // Set form error message
   }
 }

```
> 0 votes

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


title: List of content type in a bloc view

text:
# Question
Title: List of content type in a bloc view
I created a block which displays several type of content. On the page of Country, I have a block which has a list such as:

* Anthem
* Flag

To be able to do this, I addd a filter in the Advanced column. I don't know if it's the best way, feel free to tell me if there is a better way to do it. Well, this is what I have after this modification:

* Anthem of XXX
* Flag of XXX

As you can see, this is the right list. There is one type of Anthem or Flag. This is the other half of the issue, I don't know how to not let the flag to be chosen on the formula of a Country if it has already been for an other one. So, in the list, how to display the type of the content and not the title such as on the first list.

Thanks :D !

UPDATE: this are the screenshots of what I did and the result I have:

I want to add other types of content but I didn't find how to do.

# Answer
> 1 votes
Assuming you are trying to add a personalized text that links to the anthem of the country.

To achieve this, you can add a global text field and rewrite the output.

Step by step:

1) Add the field "Link to content" and fill out your personalized text in the box that says "text that will show". Check the box "exclude from display."

2) Select your title field and check the box "exclude from display."

3) Add the field "custom text" (category global)

4) In the text field, add the token as seen in replacement patterns below called "{{ view\_node }}" for the link to the content.

5) Save it all and you now have a link to the content of the current country page, assuming you have set up the right contextual filter.

If you are trying to achieve something else, please clarify and let me know.

---
Tags: views, 8, entities, blocks
---


# Question
Title: How to grant User Points equal to the price of a Commerce Product?
I would like to grant User Point to product owner in amount of product price after a product is sold.

For this I defined a rule as below:

* Events: Completing the checkout process
* Actions: Loop (`commerce-order:commerce-line-items`)

And I defined a Rules Component as below:

* Conditions: Entity has field (Entity: `commerce-line-item`, Field: `commerce_product`)
* Actions: Grant points to a user: (User: `commerce-line-item:commerce-product:creator`, Points: `commerce-line-item:commerce-product:commerce-price:amount`)

But when I save component it generates this Error message:

> Data selector commerce-line-item:commerce-product:commerce-price:amount for parameter points is invalid.

How I can do that?

# Answer
> 5 votes
At first I tried to answer your question using rules and userpoints module, but I saw that while adding **Grant points to a user** as action there is no such data selector for selecting the user who has created the product. I found the data selector for selecting the user who is the owner of order, but that is not your requirement. (That is why I clarified this in comments).

I found a module solution to your question. The module uses hook\_commerce\_checkout\_complete(). From the hook page:

> Allows modules to perform business logic when an order completes checkout.
>
> This hook coincides with the "Customer completes checkout" event. Only business logic should be performed when this is invoked, such as updating the order status, assigning the order to a user account, or sending notification e-mails. Interaction with the user should instead occur through checkout panes on the checkout completion page.

This is the coding of the module I designed:

**YOURMODULE.info** file:

```
name = YOURMODULE
description = Module description
dependencies[] = commerce
dependencies[] = commerce_cart
dependencies[] = commerce_checkout
dependencies[] = userpoints
core = 7.x

```

**UPDATE** As suggested by Clive, I have changed the module file so that this custom module will also work with multilingual sites.

**YOURMODULE.module** file:

```
/**
 * Implements hook_commerce_checkout_complete().
 */
function YOURMODULE_commerce_checkout_complete($order) {
  // Iterate through every commerce line item added in product.
  foreach (field_get_items('commerce_order', $order, 'commerce_line_items') as $line_item_id) {

    // Load commerce line item by line item id.
    $line_item = commerce_line_item_load($line_item_id['line_item_id']);

    // We do not want to include shipping cost in userpoints.
    if ($line_item->type != 'shipping') {
      // Load commerce product by product id.
      $product = commerce_product_load(field_get_items('commerce_line_item', $line_item, 'commerce_product')[0]['product_id']);

      // Create parameters.
      $params = array(
        'uid' => $product->uid,
        'points' => commerce_currency_amount_to_decimal(field_get_items('commerce_line_item', $line_item, 'commerce_total')[0]['amount'], field_get_items('commerce_line_item', $line_item, 'commerce_total')[0]['currency_code']),
      );

      // Grant userpoints programmatically.
      userpoints_userpointsapi($params);
    }
  }
}

```

Reference links:

userpoints\_userpointsapi($params)

commerce\_checkout API

commerce\_line\_item\_load($line\_item\_id)

commerce\_product\_load($product\_id)

Userpoints: deduct points programmatically

commerce\_currency\_amount\_to\_decimal()

# Answer
> 0 votes
As an alternative to the previous answer, which requires custom code, you may want to try the alternative described below to get around that error message ...

Your question seems to be a variation (not a duplicate) of the question "How to grant user User Points equal to certain field's value / calculated value?". Similar to the accepted answer to that question, try to adapt your Rules Component like so:

1. Add these extra Rules Actions before the Rules Action in your Rules Component that causes the error:

* `Set a variable` that corresponds to "*amount of product price*" (as in your question), which appears to be `commerce-line-item:commerce-product:commerce-price:amount`. Let's assume you name that variable **`price_amount`**.
    * `Convert data type` of that **`price_amount`** variable to *integer*. Let's assume you name that conversion result **`amount_of_points`**.
2. Adapt your existing Rules Action (in that Rules Component) so that the number of user points to be granted uses this (calculated + converted) **`amount_of_points`**.

PS 1: Such "Convert data type" is simply a matter of how Rules works (by design), so it's not to be considered as a bug either ...

PS 2: I assume your question is about D7.

---
Tags: commerce, rules, userpoints
---


title: Get field types of a content type

text:
# Question
Title: Get field types of a content type
I am using Drupal 8.4. I am trying to dynamically create/update field data for a content type.

Is there a way to get the type of a field (e.g. text, image, file upload) for a content type?

# Answer
> 1 votes
You can obtain the field type using Entity field manager.

```
$definitions = \Drupal::service('entity_field.manager')
  ->getFieldStorageDefinitions('node');

$field_type = $definitions['field_image']->getType();

```

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


# Question
Title: How to check Commerce product type of current line item in Rules?
When building a Drupal Commerce rule, I would like to loop over all line items and determine the product type for each line item. I would like to use the product type in a Rules Component to check whether the product is a certain type.

How can I check the line item product type when looping over line items in a Drupal Commerce shopping cart?

# Answer
> 1 votes
If the data about a product ***are not*** available when processing a "line item", you can ***make*** them available. To do so, use a technique similar to what is explained in my answer to "How to access commerce\_product field of line-items using Rules to flag the Commerce Product?", which includes a Rules Component that looks like so:

```
{ "rules_perform_an_action_on_a_selected_line_item" : {
    "LABEL" : "Perform an action on a selected line item",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "selected_line_item" : { "label" : "Selected Line Item", "type" : "commerce_line_item" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "selected-line-item" ], "field" : "commerce_product" } }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : {
            "type" : "commerce_product",
            "id" : [ "selected-line-item:commerce-product:product-id" ]
          },
          "PROVIDE" : { "entity_fetched" : { "product_fetched" : "Fetched Product" } }
        }
      },
      { "drupal_message" : { "message" : "Some details about this product: Product ID = [product-fetched:product-id], Product SKU = [product-fetched:sku], Product Title = [product-fetched:title], Product Creator = [product-fetched:creator]" } }
    ]
  }
}

```

Here is a blueprint of what you need to do:

1. Create a Rules Component, similar to the above Rules Component. Just an import of that Rules Component should be enough (to get started and further improve it as detailed below).
2. Rework the Drupal Message shown via the last Rules Action in the Rules Component (Starting with "`Some details about this product`"), e.g. by also using either of these available tokens that seem to be what you're interested in:

* `[product-fetched:type]` \- The machine name of the product type.
    * `[product-fetched:type-name]` \- The human readable name of the product type.
3. Execute that Rules Component inside your Rules Loop of the rule in which you want to loop over all line items.
4. Improve the Rules Component from Step 1 by creating whatever additional Rules Action(s) you need. Make sure to place these Rules Action(s) AFTER that Rules Action (in the Rules Component) that performs "Fetch entity by ID".

PS: I assume this question is about D7.

---
Tags: commerce, rules
---


# Question
Title: The requested page "/user/password" could not be found. need to reset my password
I'm using Drupal 7.

For some reason my admin password on mysite wont work, when I click forgot pass word I a presented with The requested page "/user/password" could not be found.

I don't know what is causing the reset password page not to show, I thought it may be tabtamer but I disabled that by setting status to 0 in my database.

It might be a Facebook connect module as I only allow users except admin to login via Facebook but as I can't log in to my site I can't check.

How can I reset or log into my site if I do not know the password and the page to request a new one isn't working?

# Answer
> 0 votes
You could try the following drush command:

```
drush uli

```

---
Tags: users
---


# Question
Title: moving D8 from one sub-folder to another
If you move your Drupal 8 website from one sub-folder (example.com/oldsite) of your domain to another sub-folder (example.com/newsite), you will find that internal links to pages and references to images are not updated. Instead, these links and references will point to your old domain name. How to fix this issue?

For example, this is one of the pages after the move the site from one subfolder to another. If I click on any of this links it's taking me back to the old website.

Thanks

# Answer
> 1 votes
I had to update the content links manually. I learned that for to create any link for the internal content i need to use relative links instead of an absolute link.

Thank You

---
Tags: migrations
---


# Question
Title: Count the number of results of a free text field if they are similar
I'm using Drupal 8.

I want to count the number of results of a text field if they are similar.

I added a simple text field to my "Article" content type.

Users can enter the text (short) they want: textA, textB, textC ... I do not know this text and can not make a selection list.

I wish I could count the number of times a user entered textA, textB etc.

I tried with Views and Aggragation function, but it does not work. Indeed it works only for the results corresponding to selection lists where a reference to a term etc.

Any idea ?

# Answer
> 0 votes
I'd use taxonomy terms and the tagging feature built into drupal. There's an example of it on the Article content type that comes with drupal's standard install

So a user can start typing a term and the autocomplete will appear if that term already exists. The user can select it if it exists already. Otherwise when the node is saved the term will be created. You can select multiple terms by comma separating them exactly as you mentioned

Then getting a count of terms will be much more straight forward and should be do-able in views as each time a term is associated to a field it's stored in the database

---
Tags: views, 8
---


title: Twig theming boolean issue

text:
# Question
Title: Twig theming boolean issue
I have a boolean for the status of a page on whether it is new or not. If it's selected, I want the following code to take effect.

```
{% if fields.field_new.content %}
  <div class="info--details__new">
    {{ fields.field_new.content }}
  </div>
{% endif %}

```

This works fine for when it's selected. However, if I unselect it, it still displays the `div` with the `info--details__new` class only empty.

I'd like for this `div` to not be displayed when this boolean isn't selected but can't seem to figure out how to do this in my twig template.

What's the best way to go about doing this so that my empty `div` doesn't show up when the boolean is unselected?

This is in my views-view-fields--VIEW-NAME.html.twig file.

# Answer
> 2 votes
As discussed in the linked topic use database values to check for booleans in a condition. In a View template you'll find for each row the entity the row is based on in `row._entity`, from which you can get the raw field values:

```
{% if row._entity.field_new.value %}
  <div class="info--details__new">
    {{ fields.field_new.content }}
  </div>
{% endif %}

```

Even if it works with debugging turned off, you still depend on how you've configured the rendered output and this is not good practice, if a small change in UI can break the code.

# Answer
> 0 votes
Well, this ended up being a debug issue. Because I had twig debug on, it still ends up displaying the `div` because of the debug code being printed for the field. Once I turn debug off, my code in the original question works as intended.

---
Tags: 8, theming
---


title: Get nodes as options in a webform

text:
# Question
Title: Get nodes as options in a webform
Any pointers gratefully received!

For Drupal 8.

I'm looking to use the image select webform element - but instead of the options being added when the webform element is created/edited we need to get the options from a content type. This is partly because we need to have extra fields available to output from the content (so JS can show/hide) - but also the editors want to be able to control when various options are available - by using 'show after' dates etc.

So - we have a content type - called vehicle - with an image field and a car group field and a 'show after' date. Ideally I'd like them to display in the same way as the current 'image select' webform element. But any way of outputting the list of vehicles as options for a webform field would be great. And I'm happy to output all the vehicles as there are not very many and the list will be further cut back by Javascript.

Thanks again!

# Answer
> 0 votes
This question is essentially asking the same thing as this previously answered question: Programmatically change select field options in contact form

The accepted answer in the other thread describes how to set the select list from php code. You would alter the `$options` in the function provided to contain your vehicle list from SQL, a yaml file, or wherever.

---
Tags: webforms
---


title: Render image that is linked

text:
# Question
Title: Render image that is linked
I am loading an unmananged image file and would like to render it in a block, but it should be linked. I have an uri (public://...) and I am able to render the image using

$build\['my\_image'\] = \[ '#theme' =\> 'image\_style', '#style\_name' =\> 'large', '#uri' =\> $uri, \];

This works, but how can I render it beeing linked to some url?

# Answer
image\_formatter is to render an entity field, you can't use that without having that.

Try using a render array for the link, like this:

```
$type_link_nested_array = [
  '#type' => 'link',
  '#title' => ['#theme' => 'image_style', '#style_name' => 'large', '#uri' => $uri, ],
  '#url' => Url::fromUri('https://www.drupal.org'),
];

```
> 11 votes

# Answer
Without adding image styling (as original question never mentioned that), I found this to work:

```
use Drupal\Core\Link;
use Drupal\Core\Url;
use Drupal\Core\Render\Markup;
$img = '<img src="path_to_my_image" />';
$rendered_image = render($img);
$image_markup = Markup::create($rendered_image);
$link = Link::fromTextAndUrl($image_markup, Url::fromUri('internal:/my_link_path'))->toString();

```
> 2 votes

# Answer
You'd probably need to render the image yourself and then add the link around it. So something like:

```
$img_render_array =  [ '#theme' => 'image_style', '#style_name' => 'large', '#uri' => $uri, ];
$img = render($img_render_array)->__toString();
$build['my_image']['#markup'] = '<a href="/">'.$img.'</a>';

```
> 1 votes

---
Tags: 8, theming, media, navigation
---


# Question
Title: How to verify a token in the url of a drupal 7 site against an external web service and skip the login form all together?
# Context

We have this JSON web service `GET https://api.my-domain.com/accounts/me` (and a bunch of other endpoints). It takes a token in the header. When that token is valid it will return

```
{
  "email": "me@my-domain.com"
}

```

That JSON web service is used by a web application. That web application links their users to a Drupal forum. We don't want them to log in again.

The simplest solution we could think of is to link the users to:

https://drupal.my-domain.com?token=123456789

# The Challenge

Our challenge is for our Drupal instance to:

1. Read that token from the URL `https://drupal.my-domain.com?token=123456789`
2. Call our web service `GET https://api.my-domain.com/accounts/me` with header `Authorization: token 123456789`
3. If it responds with a status 200 response and `{"email": "me@my-domain.com"`}, have Drupal pick up the email value.
4. Drupal matches it against the drupal users.
5. When the user doesn't exist in Drupal, it has to be created.
6. And the user is logged (SSO) into the Drupal forum.
7. No login form was ever shown. The token was either correct (status 200 from the web service) or incorrect (status 403 or whatever) and some drupal node/page should show that an invalid token was used accessing the forum.

I have done some investigation but none of the solutions that I found quite matched this use case. Most show how to build a module and have the login form check against an external system. We don't need the form. Just a token in the url validated without a form. I don't want to build a fully fletched CAS-Server, OpenID or OAuth2 provider at the web service. We'd like to keep it simple and just verify one token in the URL against our web service.

Can we use a module for this? And how would the simplest version of this module look like?

# Answer
> 0 votes
So, I don't have a working solution for this (yet!) but I'm working on a similar use case. From what I've read, you can't really have an authenticated user do anything on a Drupal site without passing them through the user module, creating a user, and storing info about them in the database.

I believe you need to write a module that passes a user object based of the email in your json response to user\_external\_login\_register passing in some sort of programmatically populated dummy text for the extra fields you need, and then programmatically create the user and log them in in the background. In theory, all you need to do is pass the user object based off of your 200 response, and proceed to create and log the user in.

---
Tags: users, authentication-authorization
---


# Question
Title: Define node array id as parameter in routing
Is that possible to send somehow an array of nids and automatically convert it into and array of nodes? Something like:

```
custom.custom_nodes:
  path: '/custom/{nodes}'
  defaults:
    _form: '\Drupal\custom\Form\CustomForm'
    _title_callback: '\Drupal\custom\Form\CustomForm::titleCallback'
    nodes: []
  requirements:
    _access: 'TRUE'

```

Then I call this: /custom/1+2+3

And I will get at the backend an array of loaded nodes, which id's is 1, 2, 3.

If yes, how do I need to separate the nids from eachother? (And what else do I need to do?) Are there any best practice right now for this? What do I need if I need just an array of ids?

# Answer
> 3 votes
A custom parameter converter would probably be the best solution.

It's quite easy to implement; `+` symbols tend to be quirky in URLs so this example uses commas instead:

MODULE/src/ParamConverter/NodesConverter.php

```
namespace Drupal\MODULE\ParamConverter;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\Routing\Route;
use Drupal\Core\ParamConverter\ParamConverterInterface;

class NodesConverter implements ParamConverterInterface {

  protected $entityTypeManager;

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

  public function convert($value, $definition, $name, array $defaults) {
    // Add whatever extra validation you feel is necessary here
    $nids = explode(',', $value);

    if (!empty($nids)) {
      return $this->entityTypeManager->getStorage('node')
        ->loadMultiple($nids);
    }
  }

  public function applies($definition, $name, Route $route) {
    return !empty($definition['type']) && $definition['type'] == 'nodes';
  }

}

```

MODULE/MODULE.services.yml:

```
services:
  module_nodes:
    class: Drupal\MODULE\ParamConverter\NodesConverter
    arguments: ['@entity_type.manager']
    tags:
      - { name: paramconverter }

```

MODULE/MODULE.routing.yml:

```
custom.custom_nodes:
  path: '/custom/{nodes}'
  defaults:
    _form: '\Drupal\custom\Form\CustomForm'
    _title_callback: '\Drupal\custom\Form\CustomForm::titleCallback'
    nodes: '[\d\,]+'
  requirements:
    _access: 'TRUE'
  options:
    parameters:
      nodes:
        type: 'nodes'

```

The regex for the route could probably be improved, the param could be made optional, etc; other than that it should work. The controller for the route at /custom/1,2,3 will receive an array of loaded nodes for the same IDs in the `$nodes` argument (or an empty/smaller array if none/only some were found).

---
Tags: 8, routes
---


# Question
Title: How to add custom fields and display settings to built-in content types via custom module install?
I'm pretty new to Drupal, I come from Wordpress development and I'm trying to "translate" some of my plugins to modules in Drupal 8.

I'm following the documentation trying to add a new field, say "price" to a node. All the documentation I found is related to add a field to a custom node, but in my case I want to add those fields to normal predefined nodes.

First question that comes to my mind is, I can create the custom field with YML configuration files or code right?

I created the field with YML and it is recognised by drupal; the problem is that they don't appear on the nodes (I have to manually activate it).

I created on my module /config/install/:

* core.entity\_form\_display.node.article.default
* core.entity\_view\_display.node.article.default

I add my field, but of course when I try to activate the module it does not like it since they are already defined by Drupal.

Is there a way to "extend" those core files? is that possible with YML or code?

I followed https://www.drupal.org/docs/8/api/entity-api/programming-custom-fields-into-your-content-type. I created the YML files on /config/install, and indeed the field is created, the problem is I don't know how to "extend" view and form display entities as they are not related to a custom node type, otherwise they should be linked to pre-built node types and I cannot redefine those files (core.entity\_form\_display.node.article.default core.entity\_view\_display.node.article.default) since they already exist on the core.

Following this comment I've created the following files:

### /config/install/field.field.node.article.field\_price.yml

```
langcode: en
status: true
dependencies:
  config:
    - field.storage.node.field_price
    - node.type.article
id: node.article.field_price
field_name: field_price
entity_type: node
bundle: article
label: Price
description: 'Premium Price'
required: false
translatable: false
default_value: {  }
default_value_callback: ''
settings:
  min: 1
  max: 9999
  prefix: ''
  suffix: ''
field_type: integer

```

### /config/install/field.storage.node.field\_price.yml

```
langcode: en
status: true
dependencies:
  module:
    - node
id: node.field_price
field_name: field_price
entity_type: node
type: integer
settings:
  unsigned: false
  size: normal
module: core
locked: false
cardinality: 1
translatable: true
indexes: {  }
persist_with_no_fields: false
custom_storage: false

```

Also I created FieldFormatter and FieldWidget. (I am not sure if properly.)

What I found out is the module is creating the field Price. If I go to /admin/structure/types/manage/article/display, I see my price there, but it is under *Disabled*.

>

I feel I'm so close, but at the same time so lost.

What am I missing in order to make that field go active?

# Answer
For a beginner I'ld recommend to use Drupal's convenient **user interface** in the back-end. Create an admin user, log in, start adding fields, change display, reorder – all done by clicking through the interface.

For example you can add custom fields to the existing Article content type at https://example.com/admin/structure/types/manage/article/fields. There's is a button `Add fields`. **Click it and explore**. There is no difference in adding fields to a built-in content type.

As others said before YML are for configuration export and import, when deploying a site. As you would do as an advanced developer: You'ld have that page locally on your computer, add some fields by clicking through the back-end, **export** their config, push that to a Git repo, and then on your live page, pull from your repository, **import** the config files and get the same fields there without the need to click anything again.

---

Adding fields from a custom module can be achieved by providing certain YML in your modules `/config/install` folder. There as well is no difference between built-in content types or custom content types. It is described pretty good on DO at https://www.drupal.org/docs/8/api/entity-api/programming-custom-fields-into-your-content-type. Except that you would have to change the naming and especially change the value of the `bundle: car_brand` (content type) you want your fields to get added to.

Apart from that, you may need to install and uninstall this module pretty often during development. Get used to `drush` commands, for example `drush dre module_name` to do that in Terminal/Console (you need to have installed the Devel module to use `drush dre`). For your own good, I hope you already work with a UNIX based OS (Linux or OSX). Maybe you always have a fresh database backup available you can re-import with `drush sql-cli < database.sql` when you want to start over during development.

---

Just for reference I paste the deleted answer code here OP originally had put in his question. To finally make the fields available in the content type OP came up with this. I strongly guess he had put this into the module's `*.install` file calling `hook_install()` or `hook_update_N()`. Possibly deprecated functions, but I think you'll get the idea.

```
$entity_type         = 'node';
$bundle              = 'article';
$field['field_name'] = 'field_price'; // your field id

entity_get_form_display($entity_type, $bundle, 'default')
  ->setComponent($field['field_name'], array())
  ->save();

entity_get_display($entity_type, $bundle, 'default')
  ->setComponent($field['field_name'], array())
  ->save();

```
> 7 votes

# Answer
Drupal's config YML files are primarily meant for import/export, to make the configuration portable between instances of the same site and to allow version control. They are not really intended as a development tool and I would never recommend writing them by hand, not even when you're an experienced Drupal developer.

Regardless of how a node type was defined, you should be able to add fields to them through the admin UI. I recommend that you do it that way, and use the config export system (either in the admin UI or using Drush on the command line) to generate config YML's that contain all the necessary data.
> 4 votes

# Answer
Got it working by using a `core.entity_form_display.node.<modulename>.default.yml` file with following content:

```
langcode: en
status: true
dependencies:
config:
  - field.field.node.modulename.body
  - node.type.modulename
module:
  - link
id: node.modulename.default
targetEntityType: node
bundle: modulename
mode: default
content:
  body:
    label: hidden
    type: string_textarea
    weight: 4
    settings:
      rows: 5
      placeholder: ''
    third_party_settings: {  }
    region: content
hidden:
  created: true
  path: true
  promote: true
  sticky: true
  uid: true
  body: true

```
> 3 votes

# Answer
What @leymannx answer is missing is explanation of what can (and should) be shipped with a custom module and what cannot.

Field storage can and should be shipped with your module.

Field instance may be shipped with your module, but only as `optional`, as it would depend on other modules providing content types (unless your module provides both content type and fields in which case you may just provide in `config/install`). Btw, you may store these files either in this or other module - when enabled, Drupal will scan all `config/optional` dirs for all modules to pickup any relevant configuration. https://www.drupal.org/node/2453919

Entity form display cannot be shipped with your module. Moreover, if your module provides just a field, shipping entity form display for the whole entity would override existing configuration. Instead, your module must include implementation of `hook_install()` where fields will be altered for form display for all supported content types.

Entity view display should be treated the same way as entity form display.
> 2 votes

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


# Question
Title: Contextual Filters > Default option: PHP Code input option is missing
I have two drupal 7 sites. I'm able to select the PHP Code option to input a default value for a contextual filter on a view on Site A....on Site B I'm unable to find this option. Is this a version issue or a settings issue? I'm at a loss to find out how to retrieve this option.

# Answer
Either the core 'PHP' module is disabled or you don't have the 'Use PHP for settings' permission.
> 1 votes

---
Tags: views
---


# Question
Title: Computed Twig solution not showing in preview?
I'm trying to understand Twig.

This is what I have got

{{ (data.number\_1) * (data.number\_2) }}

Why doesn't the preview page calculate the solution?

# Answer
I figured it out. You need to create a "Preview Page" as per Computed Twig example.

webform 5.x has an inbuilt preview page which does not recalculate when viewed.
> 0 votes

---
Tags: webforms
---


# Question
Title: Multipart Form Fields - Taxonomy Included
I'm starting out a new project and I think I've come across something like it before but I can't think of the right search terms or something along those lines...

What I'd like is a module to add multiple fields to one node field. So like a text field and a taxonomy field where I can add multiple of both the taxonomy value and the combined row of the text and taxonomy fields.

I'm near certain I once dealt with something like this once before but I cannot think of it for the life of me.

I have found this: https://www.drupal.org/project/multifield but the problem with this is that it only allows for only ONE value in each field (aka ruining my chances for using it with taxonomy).

So if anyone's run into something similar or can think of a solution to my predicament I would be incredibly grateful for some help. Thanks!

# Answer
You can use Field collection module

Tutorial: Using Field Collection In Drupal 7
> 1 votes

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


title: Currency block?

text:
# Question
Title: Currency block?
I need to be able to accept donations in different currencies. In Commerce 2 I see that currencies are tied to stores. Is there currently any solution that allows users to choose their currency from a block or similar?

# Answer
The module Commerce currency switcher does that. Unfortunately there is no country detection for now, by it may be handled with Rules.
> 0 votes

---
Tags: commerce
---


# Question
Title: Can a local Drush 8 be used to send commands to a remote site which uses Drush 9?
Let's say we have a dev-ops administrator who isn't a developer and doesn't want/need a local copy of the website. As of Drupal 8.4, Drush 9 is required, and Drush 9 doesn't have a way to install it globally, but Drush 8 still does.

Can Drush 8 be used locally with aliases for a remote Drupal 8.4 site which has Drush 9 as a dependency?
Is there another way to use Drush 9 locally without building the entire site?

# Answer
> 1 votes
Drupal 8 doesn't require Drush 9. Users who are updating Drupal to Drupal 8.4 need to first update Drush to Drush 8.1.12 or higher. (See Drupal 8.4.0 release notes).

I use Drush 8.1.15 with Acquia aliases to do a lot of things, for example clearing the cache, updating the database, synchronizing the local database with the production server.

You may need to figure out the connection requirements (like SSH keys and the like), but there is no reason a dev-op can't use Drush 8.

# Answer
> 1 votes
My answer is along the lines of tenken, but I'll add some more details.

To answer your actual question first: Yes, you can probably use a local Drush 8 to control a remote site using Drush 9 for quite some time, until they differ too much. I wouldn't recommend it.

Having Drush 9 on a local computer doesn't require to have a local Drupal site. Installing it "globally" for the current user is as easy as running `composer global require drush/drush`.

Then you can the */vendor/bin* directory that contains Drush to PATH for convenience. This should be perfectly suitable for dev-ops administrators.

PS: Installing Drush 9 as part of a Drupal site saves some package downloads, 24 versus 35 when I tested it, but that's it.

# Answer
> 0 votes
I would assume install drush 9 locally to a project, but still use alias files for all your remote systems. eg, treat the local installation as a globally installed service conceptually.

if you dont like a random project on your system hosting drush this way stick it on a VM or Container and interact with drush there.

---
Tags: drush
---


# Question
Title: Remove query strings from static resources in template.php
I've read several articles throughout the web about removing query strings from static resources, in the template.php file, after I saw a recommendation to do so in a forum, for better page-loading time in Drupal.

All of the articles I've seen lacked some didcatance in the following points:

1. Why should one remove Query strings for better loading times? I've never seen them in any URL of any my site's pages, and, I don't understand why would their appearance in a URL effect in any shape or form the loading time of a site's page (that deals more to image-optimization, bandwidth, etc).
2. What is a **static resource** in Drupal? Cache is something dynamic so I'm guessing it's not the cache itself. So what is it?
3. Where should I put the following code of this JavaScript function, at the start of the file, at the end, or between any special segments? It wasn't clear from none of the articles.

```
/**
 * Implements template_process_html().
 */
function MYTHEME_process_html(&$variables) {
  $variables['styles'] = preg_replace('/\.css\?.*"/','.css"', $variables['styles']);
}

```

# Answer
> 3 votes
The only reason you'd want do this is to remove any cache busting query parameter. These are query parameters that are appended to a URL (e.g. **www.example.com/js/some\_file.js?b= 1433781670** & **www.example.com/css/some\_file.css?b= 1433781671** ) to prevent browser caching.

---

As the tutorial probably explained, you'd only want to do this for static resources (i.e. any web resource like a CSS/JS/Image file that will never change) so that the browser **will cache** the static resource.

As for the template question you can place the `MYTHEME_processs_html()` function anywhere in **template.php** (if you don't have one, create it). On top of that, the only thing you'd need is to replace MYTHEME with the short name of your theme and flush your theme cache.

If you're new to Drupal I'd recommend avoiding this for now; unless you're sure ***there's only static CSS stylesheets that can safely have its cache-busting query string removed***, you can end up with a scenario where modules/themes aren't displaying correctly because the cache busting query parameter was needed.

# Answer
> 1 votes
The query parameters on the CSS and JS resources in Drupal are used to clear browser cache when the file changes on the server-side. But in normal circumstances, the query parameters will remain the same for all requests, thereby allowing the browser to cache the resources.

Removing these parameters might create problems if you ever decide to edit the CSS file in the future and someone already has the file cached on their browser. Such a user will continue to see the old CSS file (which you changed) until the cache lifetime expires.

What you can set caching rules for static resources in your `.htaccess`, which, in my opinion would be a better thing to do (cause there is a reason why Drupal devs did additional work to add those query parameters in the first place).

```
# Set expiry for static files
<FilesMatch "\.(?i:gif|jpe?g|png|ico|css|js|swf|ttf|otf|woff|svg)$">

  <IfModule mod_expires.c>
    ExpiresActive On
    ExpiresDefault "access plus 1 seconds"
    ExpiresByType text/html "access plus 1 seconds"
    ExpiresByType image/x-icon "access plus 6 hours"
    ExpiresByType image/gif "access plus 6 hours"
    ExpiresByType image/jpeg "access plus 6 hours"
    ExpiresByType image/png "access plus 6 hours"
    ExpiresByType text/css "access plus 6 hours"
    ExpiresByType text/javascript "access plus 6 hours"
    ExpiresByType application/x-javascript "access plus 6 hours"

    ExpiresByType application/vnd.ms-fontobject "access plus 1 month"
    ExpiresByType application/x-font-ttf "access plus 1 month"
    ExpiresByType application/x-font-opentype "access plus 1 month"
    ExpiresByType application/x-font-woff "access plus 1 month"
    ExpiresByType image/svg+xml "access plus 1 month"
  </IfModule>

  <IfModule mod_headers.c>
    Header set Cache-Control "public, max-age=21600"
  </IfModule>

</FilesMatch>

```

Of course, you can remove the lines you do not need or add new ones as per your requirements. Hope it helps!

# Answer
> 1 votes
I solved it with this code:

```

use Drupal\Core\Asset\AttachedAssetsInterface;

/**
* Implements hook_css_alter().
*/

function YOURTHEMENAME_css_alter(&$css, AttachedAssetsInterface $assets){

     foreach ($css as &$file) {
    if ($file['type'] != 'external') {
      $file['type'] = 'external';
      $file['data'] = '/' . $file['data'];
    }
  }

 }

/**
* Implements hook_js_alter().
*/

function YOURTHEMENAME_js_alter(&$javascript, AttachedAssetsInterface $assets){

     foreach ($javascript as &$file) {
    if ($file['type'] != 'external') {
      $file['type'] = 'external';
      $file['data'] = '/' . $file['data'];
    }
  }

 }

```

Put the code into YOURTHEMENAME.theme file.

It works perfect on Drupal 8.

---
Tags: javascript, performance
---


# Question
Title: Webform 8.x-5.0-RC3 can't set custom settings
Here is my problem. I have a drupal website I'm working on where I've got webform with custom settings (such as checklist with custom elements and some others). I was on 5.0-beta24 and everything was fine. I saw that an update to the RC3 was available so I tried to see if there was any breaking change. And it seems that my custom settings are no longer saved.

What is the breaking change, and is there a solution so I can still define my custom settings / another way to do it ?

You can find below my current function to alter the settings form and add my custom's one.

```
<?php
function mymodule__form_webform_settings_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  $settings = $form_state->getFormObject()->getEntity()->getSettings();

  $form['general_settings']['description']['#title'] = t("Subtitle");
  $form['general_settings']['description']['#type'] = 'textfield';

  $form['form_settings_categories'] = [
    '#type' => 'details',
    '#title' => 'Catégories',
    '#open' => TRUE,
    '#input' => FALSE,
  ];

  $form['form_settings_categories']['categories'] = [
    '#type' => 'checkboxes',
    '#options' => \Drupal\avantages\Services\PopulationsService::getPopulationList(),
    '#title' => t('Catégories'),
    '#default_value' => $settings['categories'] ?? ['test'],
    '#required' => FALSE,
  ];

}

```

Edit :

After some research, it seems (but I can be wrong) that the line that cause trouble is this one

```
  /**
   * {@inheritdoc}
   */
  public function setSettings(array $settings) {
    // Always apply the default settings.
    $this->settings += static::getDefaultSettings();
    // Now apply new settings.
    foreach ($settings as $name => $value) {
    if (array_key_exists($name, $this->settings)) {
      $this->settings[$name] = $value;
    }
  }

  return $this;
}

```

As my custom setting is not is getDefaultSettings, I can't save it.

Is there any new way to save custom settings ?

Thanks

# Answer
> 0 votes
Finally, I found the answer. Webform implement ThirdPartySettingsInterface so I can edit my form\_alter function to do the following :

```
// Because hidden by default.
$form["third_party_settings"]["#access"] = true;
$form['third_party_settings']['quizzes']['details_categories'] = [
    '#type' => 'details',
    '#title' => 'Catégories',
    '#open' => true,
    '#input' => false,
  ];

  $form['third_party_settings']['quizzes']['details_categories']['categories'] = [
    '#type' => 'checkboxes',
    '#options' => \Drupal\avantages\Services\PopulationsService::getPopulationList(),
    '#title' => t('Catégories'),
    '#default_value' => "",
    '#required' => false,
  ];

```

And to access my data, within the Webform entity :

```
$webform->getThirdPartySetting("quizzes", "categories");

```

---
Tags: 8, webforms
---


# Question
Title: Fixed time per questions in quiz modules
I'm new to Drupal, and I'm developing a site in Drupal 6. It's an online exam related site. I want to add quiz questions that have their own time; each question will have its individual time, and the total time of the quiz will be the total sum of the single question's times.

Is this possible in Drupal 6 with one of the quiz modules?

# Answer
> 0 votes
The quiz module allows you to have a time for the whole quiz: http://drupal.org/project/quiz

To do time it per question you might have to make your own solution or you might be able to use hook\_nodeapi() and update the 'time limit' field in the 'quiz\_node\_properties' table with the total of each question: http://drupalcode.org/project/quiz.git/blob/refs/heads/6.x-4.x:/quiz.module but it would be far from an out of the box solution.

# Answer
> 2 votes
Made a similar functionality for their tasks.

https://www.drupal.org/project/quiz/issues/2940636

---
Tags: 7
---


# Question
Title: Parent node does not update when updating referenced entity child node
I have a node type called page which references a node type called slider. I am using the Drupal 8 rest module to make updates to content.

I make a PATCH request to update the slider content and it says the content had been updated. When I view the slider content I can see the updated version all good but when I view the page (which renders the reference entity) it is still showing the older revision of the slider.

When I update the page by saving it to sending a PATCH to update the page then it shows the most recent version.

Is there a way to update a entity reference field (slider in this case) and also have the parent (page) also auto update with the changes?

# Answer
> 2 votes
When the referenced child node is updated in the database this triggers automatically a cache invalidation.

In this case there are three theming levels, page, parent node and child node. They all need to be invalidated when an entity involved gets updated.

But this only works when they are tagged properly. You only need to have the children tagged, because tags bubble up to the parent.

For debugging check the response header `X-Drupal-Cache-Tags`. To enable this header copy `sites/default/default.services.yml` to `services.yml`and set:

```
  # Cacheability debugging:
  #
  # Responses with cacheability metadata (CacheableResponseInterface instances)
  # get X-Drupal-Cache-Tags and X-Drupal-Cache-Contexts headers.
  #
  # For more information about debugging cacheable responses, see
  # https://www.drupal.org/developing/api/8/response/cacheable-response-interface
  #
  # Not recommended in production environments
  # @default false
  http.response.debug_cacheability_headers: true

```

Now you can check the response headers in the browser debugging tools and see which cache tags are missing in the page.

---
Tags: entities, 8
---


# Question
Title: How to grant user points to the product creator after the product is sold?
I would like to grant user points to a product owner in amount of 70% of product price after product is sold. I have a rule and part of component

**Rule**

```
Events:
Completing the checkout process

Actions:
Loop (commerce-order:commerce-line-items)

```

**Rules Component**

```
Conditions:
Entity has field (Entity: commerce-line-item, Field: commerce_product)

```

In action I can not put the value for field POINTS and I'm not sure about the user. Now I have: commerce-line-item:commerce-product:creator

```
Actions:
Grant points to a user:

```

What should I do more for my purpose? I have Drupal 7 installed.

# Answer
> 0 votes
It is complicated rule.

I can say that you need in rule or maybe in Rule component (I'm not sure) U need also add:

1. "Calculate a value" action to calculate the points which should be added to user balance. commerce-price:amount * 0.7 (here will be created some new value. EX.: point\_to\_plus
2. After use "Calculate a value" action one more time to sum current points and new. current points + point\_to\_plus = final result.

If you use the user points module first load user points. Some thing like that. Af course you need to loop over each line item of the order. I do know how to do it correct. Maybe some one will help you! Good luck!

# Answer
> 0 votes
First creat a field balance in user account

Rule

```
{ "rules_add_points" : {
    "LABEL" : "Add points",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Commerce Checkout" ],
    "REQUIRES" : [ "rules", "commerce_checkout" ],
    "ON" : { "commerce_checkout_complete" : [] },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "component_rules_calc_points" : { "line_item" : [ "list-item" ], "point" : "0.9" } }
          ]
        }
      }
    ]
  }
}

```

Component

```
{ "rules_calc_points" : {
    "LABEL" : "Calculation of point",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "line_item" : { "label" : "lin item", "type" : "commerce_line_item" },
      "point" : { "label" : "Points", "type" : "decimal" }
    },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "line-item" ], "field" : "commerce_product" } }
    ],
    "DO" : [
      { "data_calc" : {
          "USING" : {
            "input_1" : [ "line-item:commerce-unit-price:amount-decimal" ],
            "op" : "*",
            "input_2" : [ "point" ]
          },
          "PROVIDE" : { "result" : { "points2add" : "Points 2 add" } }
        }
      },
      { "data_calc" : {
          "USING" : {
            "input_1" : [ "line-item:commerce-product:creator:field-balance" ],
            "op" : "+",
            "input_2" : [ "points2add" ]
          },
          "PROVIDE" : { "result" : { "result2" : "Calculation result" } }
        }
      },
      { "data_set" : {
          "data" : [ "line-item:commerce-product:creator:field-balance" ],
          "value" : [ "result2" ]
        }
      }
    ]
  }
}

```

# Answer
> 0 votes
Even though this previous answer is a good start, it does not take into account that this question is about granting points using the User Points module (eg: the Rules Component included only REQUIRES `rules` (and not `userpoints_rules`). This answer provides a solution that actually grants such points using User Points.

### 1. Rules Component

Create a Rules Component, which looks like so (in Rules export format):

```
{ "rules_perform_an_action_on_a_selected_line_item" : {
    "LABEL" : "Perform an action on a selected line item",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "userpoints_rules" ],
    "USES VARIABLES" : {
      "selected_line_item" : { "label" : "Selected Line Item", "type" : "commerce_line_item" },
      "multiplication_factor" : { "label" : "Multiplication factor", "type" : "decimal" }
    },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "selected-line-item" ], "field" : "commerce_product" } }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : {
            "type" : "commerce_product",
            "id" : [ "selected-line-item:commerce-product:product-id" ]
          },
          "PROVIDE" : { "entity_fetched" : { "product_fetched" : "Fetched Product" } }
        }
      },
      { "drupal_message" : { "message" : "Some details about this product: Product ID = [product-fetched:product-id], Product SKU = [product-fetched:sku], Product Title = [product-fetched:title], Product Creator = [product-fetched:creator], Decimal Product Price = [product-fetched:commerce-price:amount-decimal]" } },
      { "data_calc" : {
          "USING" : {
            "input_1" : [ "product-fetched:commerce-price:amount-decimal" ],
            "op" : "*",
            "input_2" : [ "multiplication-factor" ]
          },
          "PROVIDE" : { "result" : { "points_calculated" : "Points calculated" } }
        }
      },
      { "data_convert" : {
          "USING" : { "type" : "integer", "value" : [ "points-calculated" ] },
          "PROVIDE" : { "conversion_result" : { "points_converted" : "Points Converted" } }
        }
      },
      { "userpoints_action_grant_points" : {
          "user" : [ "product-fetched:creator" ],
          "points" : [ "points-converted" ],
          "tid" : "0",
          "entity" : [ "selected-line-item:order" ],
          "operation" : "Grant points to product creator",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}

```

If you have the User Points module enabled, you should be able to just import this Rules Component in your own site.

Some more details about it:

* Rules Condition: entity `selected-line-item` has field `commerce_product`.
* Rules Actions:
    + `Fetch entity by ID`, to make all data about the Commerce product available for further processing (e.g: the Product creator who will receive the user points ...).
    + `Show a message` (just for demo / testing purposes, feel free to delete this Rules Action if you don't need/want it anymore).
    + `Calculate a value`, i.e. to multiply the (decimal) product price of the line item, with some `multiplication_factor` (like the "\* amount of 70% of product\*" in the question, provided as a parameter for the Rules Component, with data type `decimal`), and store the result in `points_calculated`.
    + `Convert data type`, to convert (decimal) `points_calculated` to (integer) `points_converted` (note the default rounding behavior being used, feel free to adapt to "down" or "up" if you prefer). The reason why this conversion is needed, is because only integers can be selected as tokens in the subsequent "Grant points to a user" Rules Action (i.e it's not possible to select (decimal) `points_calculated` for that).
    + `Grant points to a user`, i.e. to grant `points-converted` to `product-fetched:creator` (the creator of the Commerce product). Feel free to adapt the various options (e.g: Category, reason, etc) for this Rules Action to fit your needs.

### 2. Rule that invokes the Rules Component

Create a rule which invokes the Rules Component from the previous step, and which looks like so (in Rules export format):

```
{ "rules_process_product_fields_at_checkout" : {
    "LABEL" : "Process product fields at checkout",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_checkout" ],
    "ON" : { "commerce_checkout_complete" : [] },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
          "ITEM" : { "line_item" : "Current line item" },
          "DO" : [
            { "drupal_message" : { "message" : "Current line item has label \u0027[line-item:line-item-label]\u0027 and id \u0027[line-item:line-item-id]\u0027" } },
            { "component_rules_perform_an_action_on_a_selected_line_item" : {
                "selected_line_item" : [ "line-item" ],
                "multiplication_factor" : "0.7"
              }
            }
          ]
        }
      }
    ]
  }
}

```

You should be able to just import this Rules Component in your own site. The Rules Event is obvious (at checkout time), while there is no need for any Rules Conditions. About the rules Actions:

* Perform a Rules Loop, to iterate over each line item in the cart.
* Within that Rules Loop, show a message (just for demo / testing purposes also) and invoke the Rules Component from Step 1, using these values for the 2 parameters:
    + the "selected\_line\_item" being processed within the Rules Loop.
    + the "multiplication\_factor" which in this case is (hardcoded) "`0.7`" (the `70%` as in the question), feel free to change to whatever you want (or just use "`1.0`" to not take that parameter into consideration.

### 3. Quantity of each line item

The above Rules Component does not take into account the *quantity of each line item*. However to also cover that, all that's needed is to add another Rules Action in the Rules Component to perform a similar "Calculate a value" (to multiply `points_calculated` also by the available `selected-line-item:quantity` token).

### 4. Demo

Consider a shopping cart which looks like so at checkout time:

```
Product                 Price       Quantity    Total

Black Bowler - Small    125,00 €    2           250,00 €
Red T-Shirt - Small     11,00 €     3           33,00 €

                                    Subtotal    233,89 €
                                    VAT (21%)   49,11 €
                                    Order total 283,00 €

```

After completing the checkout, these are the relevant messages shown (for demo/testing purposes only):

```
Current line item has label 'HAT05' and id '12'
Some details about this product: Product ID = 5, Product SKU = HAT05, Product Title = Black Bowler - Small, Product Creator = Dries.Buytaert, Decimal Product Price = 125.00

Current line item has label 'SHRT01' and id '13'
Some details about this product: Product ID = 6, Product SKU = SHRT01, Product Title = Red T-Shirt - Small, Product Creator = Dries.Buytaert, Decimal Product Price = 11.00

```

And for the product creator, who had not earned any User Points yet, this is how the User Points report looks like afterwards (sort = most recent first):

```
Points for Dries.Buytaert

Points  Date                        Reason                          Status

8       Tue, 02/06/2018 - 13:19     Grant points to product creator Approved
88      Tue, 02/06/2018 - 13:19     Grant points to product creator Approved

Total points
Approved points 96
Pending points  0

```

Do the math: 88 (= 125.00 * 0.7, rounded) User Points for the Black Bowler, and 8 (= 11.00 * 0.7, rounded) User Points for the Red T-Shirt.

### 5. Homework (= open question)

If a user (= "`current user`") "buys" products from a product creator that equals "`current user`", then I don't think that user should be granted any User Points for doing so. But *that* was not part of the question here (*solution to the problem, changes the problem ...*).

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


# Question
Title: How to run module code on a specific page/path?
So, I'm working on an implementation where users will be redirected to a specific path on a Drupal 7 site with query parameters appended to the URL in an Oauth2 scenario (e.g. www.mysite.com/mypath&code&scope) which the D7 should process and respond to. How does one specify within a custom module to run the code a particular path? Would this be achieved through a code block?

# Answer
> 1 votes
You can use OAuth2 Authentication. Some details about it, from its project page:

> ... allows users to log into your Drupal site authenticating against a remote identity provider (IDP) via OAuth2.
>
> That is, if a user's credentials can be used to retrieve a valid access token, he/she will be logged into the site with those credentials and the token will be added to his/her session. If the user doesn't exist yet, it will be created.

---
Tags: 7
---


# Question
Title: what security measures should be taken when creating/updating/retrieving entities with data from users' form submissions?
We have webforms for authenticated users (anyone can create an account without admin approval) to fill out. With their submission data I'm using the `civicrm_api` to create contacts and relationships.

For example:

```
// in hook_webform_submission_insert I do this:
$newcontact= civicrm_api3('Contact', 'create', array(
  'sequential' => 1,
  'contact_type' => 'Organization',
  'contact_sub_type' => 'Sub_Type',
  'organization_name' => $submission->data[20][0],
));

```

Is there any filtering I should be doing or are Drupal's security measures sufficient?

There are various hooks I could use. Currently I'm using a combination of `hook_form_alter` with submit callbacks and `hook_webform_submission_insert`. Would one of these or some other hook have significantly greater security measures?

# Answer
Designers need to worry about two things, making sure that user-supplied data can go into the database successfully, and also that data pulled from the database can be written to the page successfully.

When adding data to the database, Drupal will use prepared statements to ensure the SQL injection does not occur. What this means is, Drupal will tell the database, "Expect to see an INSERT command that looks like {statement}." and then sends all the data. If the resulting statements does not match, there will be an error.

Drupal Fields are defined such that the system knows how the data in that field should be displayed. The database schema guarantees that only a certain data format is available. For example, if the field is a number, we know we won't get a string because the database is designed to only record numbers. Drupal can just worry about formatting it properly. Same if it's text, it will make sure that it is not displaying a URL by passing the text through check\_plain() after retrieving the data from the database.

In your case, you are going to be inserting this user-supplied data into the database. The Drupal Field API should be ensuring that the data is of the correct type for the database, and that it is not too long, or improperly formatted before inserting the record. It will insert it using the prepared statement to prevent SQL injection. So, you should be fine.

Make sure you read the CiviCRM secure coding guide: https://docs.civicrm.org/dev/en/latest/security/
> 0 votes

---
Tags: hooks, security, civicrm
---


# Question
Title: Commerce 2 | Quantity Dropdown with Default Values -> Error
I need to allow the costumers to choose specific quantities for specific type of products but I would like to avoid adding 2 extra modules to my website ( Commerce Extended Quantity & Extended Number Field). So I used a form alter function like here Set default "Quantity" dropdown select in product. Commerce Kickstart.

The issue is that the input is transformed to a dropdown but when the form is submitted, a blank page appears with the message "The website encountered an unexpected error" and the error in admin/reports/dblog is `Cannot unset string offsets in Drupal\Core\Field\WidgetBase->extractFormValues()...` Here is the code I use:

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

  if (strpos($form_id, "commerce_order_item_add_to_cart_form") !== false) {

  // Change widget type of quantity to select list
 $form['quantity'] = array(
'#title' => t('Quantity'),
'#type' => 'select',
'#datatype' => 'integer', // <-- I added this one to fix Notice: Undefined index: #datatype in commerce_cart_add_to_cart_form_validate() when you click add to cart button
'#options' => array(
  1 => '1',
  2 => '2',
  3 => '3'
)
);

 }}

```

Does anybody know if there is a way to fix this error? Thanks!

# Answer
> 0 votes
I found the solution to my issue:

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

 if (strpos($form_id, "commerce_order_item_add_to_cart_form") !== false) {
$form['quantity']['widget'][0]['value']['#default_value'] = 1;
 $form['quantity']['widget'][0]['value']['#step'] = 0.5;
   $form['quantity']['widget'][0]['value']['#min'] = 1;
    $form['quantity']['widget'][0]['value']['#max'] = 3;
    $form['quantity']['widget'][0]['value']['#type'] = 'select';
 $form['quantity']['widget'][0]['value']['#options'] = array(
 '1' => t('1 hour'),
'1.5' => t('1,5 hour'),
  '2' => t('2 hours'),
   '2.5' => t('2,5 hours'),
   '3' => t('3 hours') );
    }}

```

---
Tags: 8, forms, commerce
---


# Question
Title: Can a site be put in maintenance mode without a database?
I'm trying to handle a planned database outage and want Drupal to show the maintenance page during that time.

* `$conf['maintenance_theme'] = 'exampletheme'` and a suitable `$conf['_message']` are set in my `sites/sitename.com/settings.php`
* I have a `maintenace-page--offline.tpl.php` and `maintenance-page.tpl.php` in `sites/all/themes/exampletheme/templates/`
* I set `$conf['maintenance_mode'] = TRUE` in `sites/sitename.com/settings.php`

I hope that Drupal that does not have a database can still bootstrap and display the contents of `maintenance-page--offline-tpl.php` in this configuration, but in my testing it seems that's not the case. Should this work? Anything I should look into?

# Answer
What you're describing should work: the `maintenance-page--offline.tpl.php` template should be called when the database is unavailable.

Drupal does not bootstrap completely when there is no database, but does so partially. When the bootstrap process fails to contact the database, it calls `_drupal_log_error()` in `include/errors.inc`, which (indirectly) calls `_drupal_maintenance_theme()` in `includes/theme.maintenance.inc.` This is enough to allow hook invocations to work, and to load the theme specified in your `$conf['maintenance_theme']` setting.

First, I would verify that `_drupal_maintenance_theme()` is being called and that it's finding your theme. If you're using a debugger, set a breakpoint there. If not, add this line at the end of the function:

```
  echo "<p>Custom theme: $custom_theme</p>";

```

If all is ok up to this point, try starting off with the simplest possible maintenance page in `maintenance-page--offline.tpl.php`, e.g.

```
<h1>Hello world</h1>

```

If that works, and your maintenance page does not, perhaps your maintenance page contains something that attempts to access the database, or invokes a hook that attempts to access the database? Can you post your template and any errors you are seeing?

If the simple maintenance page doesn't work, more debugging would be needed.
> 2 votes

---
Tags: 7, maintenance-mode
---


title: How do I turn off notices and warnings?

text:
# Question
Title: How do I turn off notices and warnings?
I am developing a site and am getting a few warning messages that cover the page. I want to deal with them later and turn them off for now so I can concentrate on theming.

I've tried going to Config\>\>Development\>\>Logging and turning them off from there, but although it says the save was successful refreshing the pages shows the 'All Messages' option is still selected and the messages still appear on the front end.

I searched how to do this in Drush and tried `drush vset -y error_level 0` and `drush vset error_level 0` and got the response "error\_level was set to 0." but this too had no affect.

I've tried clearning my cache after each attempt as well.

Would anyone know how to achieve this?

# Answer
> 2 votes
If you don't want to add CSS you can comment out the $messages variable in your page.tpl.php file while you are developing.

# Answer
> 1 votes
To followup on @longboardnode's comment, If you really want to remove them, you can always download an app for your browser where you can style with css.

Such as Stylish for Chrome or Stylish for Firefox, which remembers your styling even after page refresh.

Then you simply hide it with css.

```
.messages.status {

   display: none;

}

```

**Note:** This will only turn it off for you / your browser.

**Side Note**: For theming I like to use a Live Editor such as Live CSS Editor for Chrome unlike Stylish, this one is not global, it will only remember your code on a per page basis.

# Answer
> 1 votes
Turn them off here: `admin/config/development/logging`

Or to show up all errors you could also set these in your `local.setting.php`

```
//Spew out all the errors!
$conf['error_level'] = 2;
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

```

# Answer
> 0 votes
Learn how to set your error reporting level either within your php.ini file or by using the

```
error_reporting()

```

function.

The approporiate docs are here :-

http://php.net/manual/en/function.error-reporting.php

You can also set :-

```
display_errors = stderr

```

In your php.ini file to force errors to only go to the log file. http://php.net/manual/en/errorfunc.configuration.php#ini.display-errors

---
Tags: 7, debugging
---


title: Add Last changed date to search results

text:
# Question
Title: Add Last changed date to search results
I'm trying to override the search--results.html.twig file.

And it says i can use info\_split.date to render the dates.

But when I try

{% if info\_split.date %} {{ info\_split.date }} {% endif %}

It does nothing, and kint says it's an empty array.

# Answer
If someone is facing exactly same issue, Here is what i did.

In my .theme file I've preprocessed search results like this

`function YOURTHEME_preprocess_search_result(&$variables){
 $result = $variables['result'];
 $info = array();
 if($result['node']){
 $info['date'] = format_date($result['node']->getChangedTime(),'short');
 }`

`$variables['info_split'] = $info;
 $variables['info']['#context'] = array(
 'info' => $info,
 );
}`

After this the date will be available in info\_split.date variable and it will be automatically rendered as in the twig file all the info is rendered you can optionally render o hide some parts of the search listing.
> 2 votes

---
Tags: 8, theming, search
---