# Question
Title: Enable clean urls drupal 7.56 / nginx - check failed
I have an issue with the clean urls check. When I test there is an error in the Nginx log:

```
2017/10/06 09:49:01 [error] 468#468: *199 open()
"/usr/share/nginx/html/drupal-7/admin/config/search/clean-urls/check" failed
 (2: No such file or directory), client: 192.168.1.254, server: localhost,
 request: "GET /drupal-7/admin/config/search/clean-urls/check HTTP/1.0",
 host: "localhost".

```

I don't know if it is a nginx problem or a Drupal problem.

update : i change some things in the nginx.conf now i have an error in the log of nginx : 2017/10/14 21:55:08 \[error\] 4804#4804: \*1 directory index of "/usr/share/nginx/html/drupal-7/" is forbidden, client: 192.168.1.254, server: localhost, request: "GET /drupal-7/?q=admin/config/search/clean-urls HTTP/1.1", host: "localhost". Here is my nginx.conf :

```
http {
include       mime.types;
default_type  application/octet-stream;

#log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
#                  '$status $body_bytes_sent "$http_referer" '
#                  '"$http_user_agent" "$http_x_forwarded_for"';

#access_log  logs/access.log  main;

sendfile        on;
#tcp_nopush     on;

#keepalive_timeout  0;
keepalive_timeout  65;

#gzip  on;
# set client body size to 200M #
client_max_body_size 200M;

server {
    listen 443 ssl http2;
    server_name toniozz75.fr;
    root /usr/share/nginx/html;
    index index.html index.htm;

location = /favicon.ico {
            log_not_found off;
            access_log off;
    }

location = /robots.txt {
            allow all;
            log_not_found off;
            access_log off;
    }

location @rewrite {
    rewrite ^/(.*)$ /index.php?q=$1;
}

location ~ \.(php|html|htm)$ {
         root           /usr/share/nginx/html;
         fastcgi_pass   unix:/run/php-fpm/php-fpm.sock;
         fastcgi_index  index.php;
         try_files $uri $uri/ /index.php?$args;
         include        fastcgi.conf;
    }

```

# Answer
> 0 votes
You are missing some configuration for clean URLs. Try adding this snippet above the `location @rewrite` snippet.

```
 location / {
    try_files $uri /index.php?$query_string; # For Drupal >= 7
 }

```

---
Tags: uri
---


# Question
Title: Limit Migrate explode process plugin to 1 takes whole string
I have a csv places column with values like that:

```
Madrid|Spain
Barcelona|Spain

```

I want to migrate this places to a custom taxonomy and 3 terms (Madrid, Spain, Barcelona) get generated doing it like that:

```
  field_taxonomy_places:
    -
      plugin: explode
      source: places
      delimiter: '|'
    -
      plugin: entity_generate

```

But actually I only want to create cities (Madrid, Barcelona), but not countries. So I try to take the first value till the delimiter like that:

```
field_taxonomy_places:
    -
      plugin: explode
      source: places
      limit: 1
      delimiter: '|'
    -
      plugin: entity_generate

```

The problem is that now 2 terms get generated (Madrid|Spain, Barcelona|Spain).

# Answer
Just found the solution after rereading the PHP explode docs:

> If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string.

So setting the limit to 1 has the effect that the returned array element contains the rest of the string, which in my case is the whole string. So setting the limit to 2 fixes the problem and gives back the first part of the string:

```
field_taxonomy_places:
    -
      plugin: explode
      source: places
      limit: 2
      delimiter: '|'
    -
      plugin: entity_generate

```
> 1 votes

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


# Question
Title: Unable to save contents once a <img> tag is added
I try to add new contents and added a content with an image tag in it. It could be as simple as:

```
<img>
Hello

```

When I try to save, the page merely reloads and nothing is saved, no error messages and I am still at the same page.

Adding new contents without the tag saves with no problem. Adding new contents with just the tag also saves with no problem.

Only contents with an tag AND some other contents not save.

This problem came up suddenly. I have not updated Drupal nor any of my modules. And I have confirmed that I have allowed as a tag in my text format.

Would anyone know what problem this may be?

# Answer
Solved the problem. It has absolutely nothing to do with images. The web hosting company configured modsecurity and it broke the way Drupal does POST in some instances.
> 0 votes

---
Tags: nodes
---


# Question
Title: How to change the starting order number for Commerce 2?
I want to change the initial order number for my new Commerce store to 777 instead of 1.

For Drupal 7, there is an explanation here, but I know the Commerce architecture has changed a lot.

I'm using Drupal 8.4 and Commerce 2.1.

The basic approach described is to use a sql query to adjust `AUTO_INCREMENT` for the order table-- is that still the recommended approach in Commerce 2?

# Answer
> 1 votes
I used the command in the given explanation on my commerce 2 projects and it worked without any problems. So I am pretty sure you can't do anything wrong with this command.

---
Tags: 8, commerce
---


# Question
Title: Form submission with AJAX to override a block content
So, I have a block that I render with the following code.

```
public function build() {
  $filterForm = \Drupal::formBuilder()->getForm('Drupal\smeno\Form\FilterForm');

  $renderArray['filterform'] = $filterForm;
  $renderArray['McRefund_data'] = $this->getMcRefund();

  return [
    '#theme' => 'Remboursement-sur-compte',
    '#McRefund_build_data' => $renderArray,
  ];
}

```

>

As you can see within this block, I render a form and data (McRefund\_build\_data) which I put in a table(couple of Divs). The purpose of the form is to filter the data and put the response back in the block so that the block get rendered with the new filtered data. For this process I want to use AJAX to avoid the page from being reloaded.

I tried adding this on `buildForm()`.

```
$form['actions']['#type'] = 'actions';
$form['actions']['submit'] = array(
  '#type' => 'submit',
  '#value' => $this->t('OK'),
  '#button_type' => 'primary',
  '#prefix' => '<div class="tc btn_pay relative">',
  '#suffix' => '</div></div>',
  '#attributes' => array(
    'class' => array('proximabold', 'tc', 'transition', 'no-underline', 'ph3', 'pv2', 'mb2', 'dib', 'white'),
  ),
  '#ajax' => [
    // 'callback' => 'Drupal\smeno\Controller\RemboursementsController::filterRefunds',
    'url' => Url::fromUserInput('/filterremboursement'),
    'event' => 'click',
    // 'wrapper' => 'edit-output',
    'progress' => [
      'type' => 'throbber',
      'message' => t('Verifying entry...'),
    ],
  ],
);

```

I added a route and a controller to handle the request and the response.

### Route

```
filterRemboursement:
path: '/filterremboursement'
defaults:
  _controller: 'Drupal\smeno\Controller\RemboursementsController::filterRefunds'
  _title: 'filterRemboursement'
methods:  [POST]
requirements:
  _access: 'TRUE'

```

### Controller

```
function filterRefunds() {
  ddl('HELLO WORLD'); //devel module debug messages (usefull for ajax requests)
}

```

This isn't working, though.

# Answer
Remove the data table from the block

```
public function build() {
    $filterForm = \Drupal::formBuilder()->getForm('Drupal\smeno\Form\FilterForm');

    $renderArray['filterform'] = $filterForm;

    return [
       '#theme' => 'Remboursement-sur-compte',
       '#McRefund_build_data' => $renderArray,
    ];
}

```

and add it to the form (placed in a wrapper):

```
  $form['McRefund_data'] = [
    '#type' => 'container',
    '#attributes' => ['id' => 'table-wrapper'],
    'table' => $this->getMcRefund(),
  ];

```

Attach this ajax callback to a form element

```
          '#ajax' => [
            'event' => 'click',
            'callback' => '::updateTable',
            'wrapper' => 'table-wrapper',
            'progress' => [
              'type' => 'throbber',
              'message' => t('Verifying entry...'),
            ],
          ],

```

and replace the table in the ajax callback:

```
  public function updateTable(array $form, FormStateInterface $form_state) {
    return $form['McRefund_data'];
  }

```
> 1 votes

---
Tags: forms, blocks, ajax
---


# Question
Title: How to display items in Rules data selector in alphabetical order
Because of my sites having a lot of fields, it takes me a lot of time to select fields in the Rules data selector, because they are sorted by date created. What should I do to make them sorted alphabetically?

# Answer
> 0 votes
This is not an answer in any way, but

on around line 150 of rules.autocomplete.js, there is this code..

```
  Drupal.rules.autocomplete.prototype.success = function(data, request, response) {
    var list = new Array();
    jQuery.each(data, function(index, value) {
      list.push( {
        label: value,
        value: index
      });
    });

    this.cache[request.term] = list;
    response(list);
  };

```

That could possibly be where you need to add some code to rearrange the list. It might be there or it might be elsewhere.. It's a huge module.

If you manage it, create a patch for yourself that can be applied each time the module is updated.

---
Tags: 7, rules
---


# Question
Title: Permissions by taxonomy for taxonomy and nodes
# I have following setup:

* Taxonomy Departments (hierarchical in at least 3 levels)
    + Location A
        - Team A.1
            * Subteam A.1.I
            * Subteam A.1.II
            * Subteam A.1.III
        - Team A.2
    + Location B
        - Team B.1
        - Team B.2
* Taxonomy "Worker" (taxo ref to "Department")
* Content Type "performance review" (taxo ref to "Worker" and to "Department"), one user may have multiple of reviews (they can be done from time to time, like every 3 months)
* Users with a specific role ("Manager")

# What I need is:

* Managers should only see specific departments and all workers in that department
* If the manager can see Team A.1 (or Location A) he can see all (Teams and) Subteams also (and all workers belonging to those)
* Managers should only see the performance reviews of workers he has access to

# The question is:

* How do I best go forward to get there?

# Problems I found with existing modules and more problems:

* You can give node acess based on taxonomy, but those modules don't give access to taxonomy based on taxonomy
* To me it would be logic to give the user accounts a new field with reference to the "Department" and build the permissions from there. "Acces by Reference" for example would need me to give the "Department" a reference to users (which you could argue for, but in this project I would prefer the other way (or a synced both-way-solution).
* Just in case you wonder about this: The review references the department (instead of always getting it from the referenced Worker taxo), because when workers switch to another department, the review should stay in the department in which it was created

# If the only way forward is programming my own module:

# Answer
I Think You need to take a look at Permissions By Term and you may need to get an extra step to implement some code to provide the required term and assign it for the required permission according to your required hierarchy.
> 0 votes

---
Tags: 7, users
---


# Question
Title: How can I bypass the login screen during checkout in Commerce 2?
I'm building a site where I want to allow guests to purchase without creating a user account. This appears to be default behaviour in Commerce 2.1 (the message stating that the user can create an account at the end of checkout is currently not implemented although I know work is being done on that in this issue https://www.drupal.org/node/2857157).

However, I also don't want to offer guests the option to log in, which is what currently happens.

So, I want to simply bypass the Login page and go straight to the checkout page.

# Answer
> 3 votes
I was able to solve this problem by editing the Default checkout flow at /admin/commerce/config/checkout-flows, where I could simply disable the **Login or continue as guest** step.

---
Tags: commerce
---


# Question
Title: How to add link to custom module configuration form in Drupal 8
I'm working on a custom module that has a couple configuration form for controlling it's settings. I want to add a link to this form to the admin configuration UI. The new link to my settings isn't appearing, but the form works fine if I navigate directly to it using the URL.

```
# stripedonation.links.menu.yml

stripedonation.admin:
  title: 'Stripe Donation'
  description: 'Manage settings for strip donations'
  parent: system.admin_config_system
  # menu_name: main
  route_name: stripedonation.settings
  weight: 1

```

NOTE: I cleared the cache after adding this.

```
# stripedonation.routing.yml

stripedonation.settings:
  path: '/admin/config/stripedonation'
  defaults:
    _form: '\Drupal\stripedonation\Form\SettingsForm'
    _title: 'Stipe Donation Settings'
  requirements:
    _permission: 'administer site config'

```

I also tried adding the key shown below to my \*.info.yml file and it didn't help

```
# stripedonation.info.yml

name: "Stripe Donation"
type: module
description: "Adds Stripe Donation form for ThinkShout vetting exercrise"
package: EmersonThis
core: 8.x
# configure: stripedonation.settings

```

In case it matters...

```
# stripedonation.settings.yml
stripe_pub_key: ''
stripe_secret_key: ''

```

I'm expecting my menu link to show up here (but obviously it is not):

I've studied the following documentation:

I've also studied every "how-to" I could find:

Still no menu in the admin UI. What am I doing wrong?

# Answer
Well it turned out to be a stupid mistake!

All of my filenames and syntax were correct, but my \*.links.menu.yml accidentally was saved into the src/ directory of my module instead of at the root of it. I moved it where it should be and cleared the cache and it works fine.
> 1 votes

---
Tags: 8, forms, navigation
---


# Question
Title: Hook to change display widget in facet api from template.php
In my site i have search api with one block facet option "Display widget" set to "Links with checkboxes"

but now i want to change the value to "Links"

because when the website is displayed on a mobile device i need to change to this option value.

Is there a way to change this option through any hook or another way to get this accomplished?

Maybe put a hook in template.php is my closes approach.

Thanks :)

# Answer
Create another index and configure facet display differently
> -1 votes

---
Tags: hooks, search
---


# Question
Title: Drupal\Component\Plugin\Exception\PluginNotFoundException: The "commerce_order_item" entity type does not exist
I installed the *Commerce core* module installed without using Composer.

I tried to update from Drupal 8.4.0 to Drupal 8.4.1 using Drush, but I am getting the following error.

> Drupal\Component\Plugin\Exception\PluginNotFoundException: The "commerce\_order\_item" entity type does not exist. in Drupal\Core\Entity\EntityTypeManager-\>getDefinition() (line 133 of core/lib/Drupal/Core/Entity/EntityTypeManager.php).

I cannot access update.php, run `drush cr` or `drush updb`.

How can I update Drupal without getting that exception?

# Answer
Hm, as I can see you try to update site directly on production version?

In next steps i can describe process that i use while perform site and plugins update, so after all they may be helpful for you:

> First rule, never perform updates directly on production site.
>
> Second, start practicing virtualization for projects (docker, vagrant) for local development.
>
> Third, start practicing Drush configuration management for synchronization between local, beta, production sites...
>
> And most important, always use GIT.

Because your site is already broken, I can suggest you to make local version with previously working configuration and database, so after this you can perform updates on your local site and debug problems if they still exists.

For example, on local version you can make clean install of Drupal 8.40, and import untouched database from state where site work and all site data with modules (same versions used on site before they going down). This will provide you site before update to Drupal 8.41, but for future updates I need to suggest you to start using composer, because lot of dependencies for site lying in the vendor directory.
> 0 votes

# Answer
Your error shows that you updated Commerce without updating Entity API.

Did you run *"composer update drupal/commerce --with-dependencies"*?

Install drupal commerce using composer with all its dependencies. You can use below command for that -

*composer require "drupal/commerce"*

and then run *composer update* .

If still any packages are missing in your setup, then you can search for the respective package at - https://packagist.org/ and then install that using composer.
> 0 votes

---
Tags: 8, commerce
---


title: Remove node edit form field validation

text:
# Question
Title: Remove node edit form field validation
I am working on the node edit form, and I want to remove all field validation when users click on *Save as unpublished*.

Is it possible?

I didn't write any code right now, so I don't have any code to show.

# Answer
> 1 votes
You could do this approach in HOOK\_form\_alter. Depending on validation that you want to remove... I provide you a simple example of required fields: Suppose you have an Image field that it's required, you could make it unrequired using the following:

```
$form['field_image']['widget']['0']['#required'] =  TRUE;

```

Also if you want to remove the "Alt field" for a image you could use:

```
$form['field_image']['widget']['0']['#alt_field'] =  FALSE;

```

---
Tags: 8, forms, hooks
---


# Question
Title: How to uninstall a module that has added a basefield that has data
My module adds a basefield 'myfield' to the core 'file' content entity.

I now need to uninstall my module for development purposes, but I can't because drush refuses to uninstall the module, saying "There is data for the field myfield on entity type File".

My understanding is that this is a known issue:

* Because my module adds this field to an entity it does not own, this uninstallation will not be taken care of automatically by the core uninnstall procedure,
* Therefore my module needs to have a hook\_uninstall that triggers field uninstallation using \Drupal::entityDefinitionUpdateManager()-\>uninstallFieldStorageDefinition
* However, a field can't be uninstalled if it still has data in it, so I first need to remove the data.
* But the system to purge field data currently only works for bundle fields not base fields.
* There may be other ways to delete field data, but they won't scale to large quantities of data.
* Therefore there is no robust way to uninstall my module and Drupal core is correct to refuse to uninstall it.

Given all that, how best can I uninstall it when I need to do so for development purposes (short of reinstalling Drupal)?

Here is how I am creating it:

In mymodule.module:

```
function mymodule_entity_base_field_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  if ($entity_type->id() == 'file') {
    $fields = array();
    $fields['myfield'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('My field'))
    return $fields;
  }
}

```

In mymodule.install:

```
  $entity_manager = \Drupal::entityManager();
  $definition = $entity_manager->getFieldStorageDefinitions('file')['myfield'];
  $entity_manager->onFieldStorageDefinitionCreate($definition);

```

# Answer
This is a known Drupal Core limitation that looks close to being ready so hopefully will be fixed in D8.5. In the meantime you could apply the patch linked to the issue.
> 1 votes

# Answer
Does `drush field-delete myfieldname` work for base fields? If so, you could look in drush's source code to see how it accomplishes this.

I don't see any information regarding this in the drush 8.x documentation.
> 0 votes

---
Tags: entities, 8, installation
---


# Question
Title: How to link contextual filters from user account reference to node via views
So I have a content type called 'band' that has a selection field for users as members of bands (band\_member) in band content type. I want to create a view that displays only the users profiles that are members of the band. I am using the 'profiles' module to create these though I have the profile type linked to display with the user account. I know it is done through contextual filters and relationships though I am not sure how. Any suggestions?

# Answer
Assuming this view will be on a band page, your contextual filter just needs to be the content NID.

Then, I guess you have to add the band\_members field. You might get lucky and be able to render all of the profile in the field settings.

If you can't get enough info or customisation for that, you could instead add the relationship for Entity ReferencED by band\_member. That should give you extra user fields to add.

**Additional question from comments.**

> Also if I wanted to show a block in the sidebar that shows all bands this user is listed in how would I do this. So how do I create the contextual filter or relationship with a user mentioned in the band\_members reference in band?

For this, you would create a new view showing `content: Band` and the contextual filter would be

```
Content: Band Member (field_band_member)
Appears in: node:band.

```

For that contextual filter, you into its settings and select

```
When the filter value is NOT available > Provide Default Value

```

and then select either `Current User` if you want the block to the show the bands of the logged in user all the time, or `User ID from URL` if you want it to show the bands of the currently viewed user profile.
> 0 votes

---
Tags: views
---


title: Autocomplete taxonomy with depth field

text:
# Question
Title: Autocomplete taxonomy with depth field
I am looking to achieve the next functionality:

I have a content type about fruits, I've added an autocomplete taxonomy field to the content type with the possibility to register new taxonomy.

I would like to achieve some taxonomy depth.

I am using the autocomplete deluxe module

For example, I input in the field *apple*, *fresh*, and *green*.

When I go to the *fruits* taxonomy vocabulary, I would like to have the taxonomy depth like this.

Instead, I get the following.

Is there a way to achieve this with taxonomy autocomplete field?

# Answer
I suggest implementing hook\_entity\_presave() getting values from taxonomy term reference field. If always the pre-term will be the parent of the current term then loop through the results of the term ids:

```
 if ($entity->getEntityTypeId() == 'node') {
    if ($entity->bundle() == 'Machine_Name_content_type') {
    // Get the values from taxonomy term:
    $terms = $entity->get('field_tags')->getValue();
    if (!empty($terms)) {
        foreach($terms as $key => $value) {
            // Exclude the first term because this will be the parent.
            if ($key != '0') {
                // Get the parent of the element.
                $parent = $terms[$key -1];
                // Load the current term.
                $term_loaded= \Drupal\taxonomy\Entity\Term::load($value['target_id']);
                // Set the parent: the term before.
                $term_loaded->parent = ['target_id' => $parent['target_id']];
                $term_loaded->save();
            }
        }

     }
  }
}

```

Hope to help you!
> 1 votes

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


# Question
Title: The website encountered an unexpected error due to installing custom module
I have created and installed custom module without additional code\[with mymodule.info and mymodule.module\].But after I created

> mymodule.links.menu.yml and mymodule.routing.yml i am grtting error like "The website encountered an unexpected error" code mymodule.links.menu.yml

```
   mymodule.admin_form
     title: Upload IELTS Test Dates
     parent: cedar.admin_index
     weight: 100
     route_name : mymodule.admin_form

```

and code inside mymodule.routing.yml

```
 mymodule.settings:
   path: '/admin/config/services/migs'
   defaults:
     _controller: '\Drupal\quotesapi\Controller\MymoduleController::settings'
     _title: 'My module settings'
   requirements:
     _permission: 'administer site configuration'

```

I checked the watchdog and found a `RouteNotFoundException`. How do I fix this?

# Answer
It looks like a simple naming error. Your route name in the links file is:

```
route_name : mymodule.admin_form

```

But in your routing.yml you have:

```
 mymodule.settings:

```

Update one or the other so they both match, clear the cache, and it should work.
> 0 votes

# Answer
Change:

```
mymodule.admin_form

```

By

```
mymodule.admin_form:

```

Change:

```
route_name : mymodule.admin_form

```

By

```
route_name : mymodule.settings

```

**Note**: check the official documentation: on this page, there is an example of the use of the file: `links.menu.yml`. The file name must end in ":". and in the `route_name` parameter you must refer to the name of the route that is in the `routing.yml` file.
> 0 votes

---
Tags: navigation
---


# Question
Title: Rules component works different when fired by cron
I have a Rules Component that I want to run every week, using cron.

The component's elements:

* set a variable (emailbodytext)
* viewsloop 1 to fill the emailbodytext with titles of all recent nodes
* viewsloop 2 to send emails to selected users

When I (as admin) execute the component, it works fine: all selected users receive a mail with the recent node-titles. When I execute thru cron (after planning it) viewsloop 1 always gives zero results, which results in sending empty mails to all selected users in viewsloop 2.

**Question:**

Why does one view seem to give results and the other does not? Both views have the same access setting (role: adm) in the "Rules setting"-part.

I add the view from viewsloop 1 here:

```
$view = new view();
$view->name = 'nieuwigheden';
$view->description = 'nieuwe items van de laatste x dagen: blokken om in overzicht op te nemen';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Nieuwigheden';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Nieuwigheden';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['use_more_text'] = 'meer';
$handler->display->display_options['access']['type'] = 'role';
$handler->display->display_options['access']['role'] = array(
  2 => '2',
);
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['exposed_form']['options']['submit_button'] = 'Toepassen';
$handler->display->display_options['exposed_form']['options']['reset_button_label'] = 'Opnieuw instellen';
$handler->display->display_options['exposed_form']['options']['exposed_sorts_label'] = 'Sorteer op';
$handler->display->display_options['exposed_form']['options']['sort_asc_label'] = 'Oplopend';
$handler->display->display_options['exposed_form']['options']['sort_desc_label'] = 'Aflopend';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['pager']['options']['expose']['items_per_page_label'] = 'Items per pagina';
$handler->display->display_options['pager']['options']['expose']['items_per_page_options_all_label'] = '- Alle -';
$handler->display->display_options['pager']['options']['tags']['first'] = '« eerste';
$handler->display->display_options['pager']['options']['tags']['previous'] = '‹ vorige';
$handler->display->display_options['pager']['options']['tags']['next'] = 'volgende ›';
$handler->display->display_options['pager']['options']['tags']['last'] = 'laatste »';
$handler->display->display_options['style_plugin'] = 'table';
/* Relatie: Inhoud: Auteur */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'node';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
$handler->display->display_options['relationships']['uid']['required'] = TRUE;
/* Veld: Gebruiker: Naam */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'uid';
/* Veld: Inhoud: Titel */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Veld: Inhoud: Body */
$handler->display->display_options['fields']['body']['id'] = 'body';
$handler->display->display_options['fields']['body']['table'] = 'field_data_body';
$handler->display->display_options['fields']['body']['field'] = 'body';
$handler->display->display_options['fields']['body']['label'] = 'Berichttekst';
/* Veld: Inhoud: Datum van inzending */
$handler->display->display_options['fields']['created']['id'] = 'created';
$handler->display->display_options['fields']['created']['table'] = 'node';
$handler->display->display_options['fields']['created']['field'] = 'created';
$handler->display->display_options['fields']['created']['label'] = 'Datum';
$handler->display->display_options['fields']['created']['date_format'] = 'datum_zndr_tijd';
$handler->display->display_options['fields']['created']['second_date_format'] = 'long';
/* Veld: Gebruiker: E-mailadres */
$handler->display->display_options['fields']['mail']['id'] = 'mail';
$handler->display->display_options['fields']['mail']['table'] = 'users';
$handler->display->display_options['fields']['mail']['field'] = 'mail';
$handler->display->display_options['fields']['mail']['relationship'] = 'uid';
/* Sorteercriterium: Inhoud: Datum van inzending */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filtercriterium: Inhoud: Gepubliceerd */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filtercriterium: Inhoud: Datum van inzending */
$handler->display->display_options['filters']['created']['id'] = 'created';
$handler->display->display_options['filters']['created']['table'] = 'node';
$handler->display->display_options['filters']['created']['field'] = 'created';
$handler->display->display_options['filters']['created']['operator'] = '>=';
$handler->display->display_options['filters']['created']['value']['value'] = '2017-09-01';
$handler->display->display_options['filters']['created']['group'] = 1;

/* Display: Rules VAB last 7 days */
$handler = $view->new_display('views_rules', 'Rules VAB last 7 days', 'views_rules_1');
$handler->display->display_options['defaults']['access'] = FALSE;
$handler->display->display_options['access']['type'] = 'role';
$handler->display->display_options['access']['role'] = array(
  1 => '1',
);
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '50';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Veld: Inhoud: Nid */
$handler->display->display_options['fields']['nid']['id'] = 'nid';
$handler->display->display_options['fields']['nid']['table'] = 'node';
$handler->display->display_options['fields']['nid']['field'] = 'nid';
/* Veld: Inhoud: V/A/B */
$handler->display->display_options['fields']['field_v_a_b']['id'] = 'field_v_a_b';
$handler->display->display_options['fields']['field_v_a_b']['table'] = 'field_data_field_v_a_b';
$handler->display->display_options['fields']['field_v_a_b']['field'] = 'field_v_a_b';
$handler->display->display_options['fields']['field_v_a_b']['type'] = 'taxonomy_term_reference_plain';
/* Veld: Inhoud: Titel */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Veld: Inhoud: Body */
$handler->display->display_options['fields']['body']['id'] = 'body';
$handler->display->display_options['fields']['body']['table'] = 'field_data_body';
$handler->display->display_options['fields']['body']['field'] = 'body';
$handler->display->display_options['fields']['body']['label'] = 'Berichttekst';
/* Veld: Inhoud: Datum van inzending */
$handler->display->display_options['fields']['created']['id'] = 'created';
$handler->display->display_options['fields']['created']['table'] = 'node';
$handler->display->display_options['fields']['created']['field'] = 'created';
$handler->display->display_options['fields']['created']['label'] = 'Datum';
$handler->display->display_options['fields']['created']['date_format'] = 'datum_zndr_tijd';
$handler->display->display_options['fields']['created']['second_date_format'] = 'long';
/* Veld: Gebruiker: Naam */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'uid';
/* Veld: Gebruiker: E-mailadres */
$handler->display->display_options['fields']['mail']['id'] = 'mail';
$handler->display->display_options['fields']['mail']['table'] = 'users';
$handler->display->display_options['fields']['mail']['field'] = 'mail';
$handler->display->display_options['fields']['mail']['relationship'] = 'uid';
/* Veld: Gebruiker: Gemeente */
$handler->display->display_options['fields']['field_p_gemeente']['id'] = 'field_p_gemeente';
$handler->display->display_options['fields']['field_p_gemeente']['table'] = 'field_data_field_p_gemeente';
$handler->display->display_options['fields']['field_p_gemeente']['field'] = 'field_p_gemeente';
$handler->display->display_options['fields']['field_p_gemeente']['relationship'] = 'uid';
$handler->display->display_options['fields']['field_p_gemeente']['type'] = 'text_plain';
$handler->display->display_options['defaults']['filter_groups'] = FALSE;
$handler->display->display_options['defaults']['filters'] = FALSE;
/* Filtercriterium: Inhoud: Gepubliceerd */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filtercriterium: Inhoud: Datum van inzending */
$handler->display->display_options['filters']['created']['id'] = 'created';
$handler->display->display_options['filters']['created']['table'] = 'node';
$handler->display->display_options['filters']['created']['field'] = 'created';
$handler->display->display_options['filters']['created']['operator'] = '>=';
$handler->display->display_options['filters']['created']['value']['value'] = '-8 days';
$handler->display->display_options['filters']['created']['value']['type'] = 'offset';
$handler->display->display_options['filters']['created']['group'] = 1;
/* Filtercriterium: Inhoud: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'vraag_of_aanbod' => 'vraag_of_aanbod',
);
$handler->display->display_options['rules_variables'] = array(
  'nid' => array(
    'enabled' => 1,
    'rendered' => 0,
    'type' => 'integer',
    'label' => 'Nid',
    'name' => 'nid',
  ),
  'field_v_a_b' => array(
    'enabled' => 1,
    'rendered' => 1,
    'type' => 'text',
    'label' => 'V/A/B',
    'name' => 'field_v_a_b',
  ),
  'title' => array(
    'enabled' => 1,
    'rendered' => 0,
    'type' => 'text',
    'label' => 'Titel',
    'name' => 'title',
  ),
  'body' => array(
    'enabled' => 1,
    'rendered' => 1,
    'type' => 'text',
    'label' => 'Berichttekst',
    'name' => 'body',
  ),
  'created' => array(
    'enabled' => 1,
    'rendered' => 0,
    'type' => 'date',
    'label' => 'Datum',
    'name' => 'created',
  ),
  'name' => array(
    'enabled' => 1,
    'rendered' => 0,
    'type' => 'text',
    'label' => '(auteur) Naam',
    'name' => 'name',
  ),
  'mail' => array(
    'enabled' => 1,
    'rendered' => 0,
    'type' => 'text',
    'label' => '(auteur) E-mailadres',
    'name' => 'mail',
  ),
  'field_p_gemeente' => array(
    'enabled' => 1,
    'rendered' => 1,
    'type' => 'text',
    'label' => '(auteur) Gemeente',
    'name' => 'field_p_gemeente',
  ),
);
$translatables['nieuwigheden'] = array(
  t('Master'),
  t('Nieuwigheden'),
  t('meer'),
  t('Toepassen'),
  t('Opnieuw instellen'),
  t('Sorteer op'),
  t('Oplopend'),
  t('Aflopend'),
  t('Items per pagina'),
  t('- Alle -'),
  t('Offset'),
  t('« eerste'),
  t('‹ vorige'),
  t('volgende ›'),
  t('laatste »'),
  t('auteur'),
  t('Naam'),
  t('Titel'),
  t('Berichttekst'),
  t('Datum'),
  t('E-mailadres'),
  t('Rules VAB last 7 days'),
  t('Nid'),
  t('V/A/B'),
  t('Gemeente'),
);

```

And the rules itself: a duplicate where I replaced viewsloop2 with only 1 emailaddress:

```
{ "rules_weekoverzicht_per_mail_gedupliceerd_" : {
    "LABEL" : "Weekoverzicht per mail (gedupliceerd)",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "TAGS" : [ "mail" ],
    "REQUIRES" : [ "rules" ],
    "ACTION SET" : [
      { "variable_add" : {
          "USING" : {
            "type" : "text",
            "value" : "\u003Ch2\u003E[site:name] weekoverzicht op [site:current-date]\u003C\/h2\u003E\r\n"
          },
          "PROVIDE" : { "variable_added" : { "variable_samengesteld" : "Samengestelde inhoud" } }
        }
      },
      { "drupal_message" : { "message" : "[mail-from-view:value]" } },
      { "data_set" : {
          "data" : [ "variable-samengesteld" ],
          "value" : "\u003Cp\u003EDag\u003C\/p\u003E\r\n\u003Cp\u003ETer herinnering: Om de \u0022mail alle leden - nieuwe stijl\u0022 te ontvangen moet je in \u0022Mijn account: Adres etc bewerken\u0022 aanduiden tot welke interessegroep je behoort. Pas daarna ontvang je direct een email wanneer een nieuwe V\/A gepost wordt in jouw interesse. \u003C\/p\u003E\r\n\u003Cp\u003EHet volautomatische weekoverzicht woensdagnacht was niet echt een succes. Volgende keer beter.\r\n\u003C\/p\u003E\r\n\r\n[variable-samengesteld:value]"
        }
      },
      { "mail" : {
          "to" : "ingrid@letsleie.be",
          "subject" : "[[site:name]] Weekoverzicht test",
          "message" : [ "variable-samengesteld" ],
          "language" : [ "" ]
        }
      },
      { "VIEW LOOP" : {
          "VIEW" : "nieuwigheden",
          "DISPLAY" : "views_rules_1",
          "ROW VARIABLES" : {
            "nid" : { "fiche_nid" : "Nid van VAB fiche" },
            "field_v_a_b" : { "fiche_field_v_a_b" : "V\/A\/B uit view" },
            "title" : { "fiche_title" : "Titel uit view" },
            "body" : { "fiche_body" : "Body uit view" },
            "created" : { "fiche_created" : "Datum creatie" },
            "name" : { "fiche_van_name" : "(auteur) Naam" },
            "mail" : { "fiche_van_mail" : "(auteur) E-mailadres" },
            "field_p_gemeente" : { "fiche_field_p_gemeente" : "(auteur) Gemeente" }
          },
          "DO" : [
            { "data_set" : {
                "data" : [ "variable-samengesteld" ],
                "value" : "[variable-samengesteld:value]\r\n\u003Chr\u003E\r\n\u003Ch3\u003E\u003Ca href=\u0022[site:url]\/node\/[fiche-nid:value]\u0022\u003E [fiche-title:value]\u003C\/a\u003E\u003C\/h3\u003E\r\n\u003Cp\u003E\u003Cstrong\u003E[fiche-field-v-a-b:value] van [fiche-van-name:value] ([fiche-field-p-gemeente:value]) dd. [fiche-created:value]\u003C\/strong\u003E\u003C\/p\u003E\r\n\u003Cp\u003E[fiche-body:value]\u003C\/p\u003E\r\n\u003Cp\u003E Antwoorden via \u003Ca href=\u0022mailto:[fiche-van-mail:value]\u0022\u003E[fiche-van-mail:value]\u003C\/a\u003E\u003C\/p\u003E\r\n\r\n"
              }
            }
          ]
        }
      },
      { "data_set" : {
          "data" : [ "variable-samengesteld" ],
          "value" : "[variable-samengesteld:value]\r\n\u003Chr\u003E\r\n\u003Cp\u003EDe Letsleie Robot\u003C\/p\u003E\r\n\u003Cp\u003EJe krijgt deze mail omdat je lid bent van Letsleie. Via \u0022Mijn account: Adres etc. bewerken\u0022 kun je aanduiden of je wel of niet een wekelijks overzicht per email wenst.\u003C\/p\u003E "
        }
      },
      { "drupal_message" : { "message" : "[variable-samengesteld:value]" } },
      { "mail" : {
          "to" : "me@mysite.be",
          "subject" : "weekoverzicht test",
          "message" : [ "variable-samengesteld" ],
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

When executed from UI I receive a mail with the introduction text and the node-info. When exectuded thru cron the mail only has the introduction text.

# Answer
> 1 votes
Quote from Configuring cron jobs using the cron command:

> ... Note that as of Drupal 7, cron always runs as an anonymous user ...

So if your views have "access settings to limit them to role adm" (as in your question), then that explains why via cron you don't get any results (assuming your question is about D7 or above).

# Answer
> 0 votes
**conclusion: content\_access-permissions show different behaviour than core permissions**

**viewsloop 1:** content of a content type that has a setting “not to be displayed to anonymous” by module content\_access (because core permission “display published content” is not on a per content type basis).

Apparently the view evaluates this as an extra filter on the content: “may the user running the view see this node” . Anonymous cron executing the view receives no protected content.

**Viewsloop 2:** users, where user profiles are set “not to be displayed to anonymous”, by core role permissions (no content\_access involved here)

Apparently when the view is executed the view does not evaluate this permission, so anonymous cron receives all the email addresses needed.

I see no effect of the access setting `$handler->display->display_options['access']['type'] = 'role';` in the view when the view is called by a viewsloop-action in a Rules Component.

**Solution found!**

I solved my problem following the suggestions in the answer to a similar question: switch to and back to a specific user with just enough permissions to see what I want to have in the view.

---
Tags: views, rules, cron
---


# Question
Title: How can I print the customer name in the Orders view in Commerce 2?
I have a site where anonymous checkout is the default option. The problem with this is that the default order page simply shows "Anonymous" as the customer for every order in the list. I need to show the name of the actual customer.

# Answer
Since the order page is a View, you can modify the view to display what you want. However, it's not immediately obvious now to do this.

The steps I took were to add a relationship to the User entity, and then add another relationship to the User Profile (you need both relationships for this to work). From there, you can choose from three name fields for the Customer user profile type. I added the Given and Family name fields, hid them from display, and then rewrote the User column to output the first and last names followed by the user name, like this:

{{ address\_given\_name }} {{ address\_family\_name }} ({{ uid }})
> 1 votes

---
Tags: commerce
---


# Question
Title: How to enforce minimum height and width for image while resizing anything larger?
We have a requirement where the minimum and maximum image resolution 480x480 for an image on upload. The reason is that we want the image to be resized to be exactly 480x480.

However, whenever we upload an image that is larger than 480x480, we are constantly getting the following error message. Even when i modify the maximum to be 640x480 i still get the error message for an image that is 1200x968.

Need some help figuring out what could be the issue as i have tried to modify the maximum image resolution to be slightly larger than the minimum image resolution, but still get the error message.

# Answer
> 1 votes
Reformatting an image won't happen on upload, it will happen on display of the content. If you want to reject anything less than 480x480, set that as the minimum in the field's setting and don't set a maximum size.

To resize the image, be sure there is an image style set to resize an image to 480x480 (which is included by default in Drupal 8). Then under the "Manage Display" field of the content type, click the gear next to the image field and select the desired image style that you want displayed.

---
Tags: theming, 8, nodes, media
---


# Question
Title: How to display text field in webform block
Webform content type has two text fields. I added a webform node with one component. I can see the both text fields when I visit the webform node page. After I display the webform as a block, I can only see the webform component but block does not display the fields.

How can I display the text fields in webform block?

# Answer
> 0 votes
You need to create a view that will display the form. While creating the view, be sure that the "create a block" option is checked. You'll also want the view to display the full post and you'll need to set filters so only the single form is displayed.

---
Tags: webforms
---


title: Drush cannot rr or en a module

text:
# Question
Title: Drush cannot rr or en a module
I have a Drupal 7 dev-site hosted on pantheon. Using git bash and composer I installed drush on my windows 10 machine and I thought I did so globally. When I run composer --version and drush status I get what appear to be good responses. However, when I try to enable a module using drush or rebuild the registry I get ...

```
samha@LAPTOP-99SBTCQM /c/localworking/thecottagepress (master *=) $ drush
@pantheon.thecottagepress.dev rr
/bin/bash: -c: line 0: unexpected EOF while looking for matching `''
/bin/bash: -c: line 1: syntax error: unexpected end of file

```

Here is what I get when I run drush status...

```
samha@LAPTOP-99SBTCQM /c/localworking/thecottagepress (master *=) $ drush
status Drupal version         :  7.56
Site URI               :  http://default
PHP configuration      :  C:\PHP\php.ini
PHP OS                 :  WINNT
Drush script           :
C:/LocalWorking/thecottagepress/vendor/drush/drush/drush.php
Drush version          :  8.1.15
Drush temp directory   :  C:\Users\samha\AppData\Local\Temp
Drush configuration    :
Drush alias files      :  C:/Users/samha/.drush/pantheon.aliases.drushrc.php
Drupal root            :  C:\LocalWorking\thecottagepress
Drupal Settings File   :  sites/default/settings.php
Site path              :  sites/default

```

What do I need to do to make drush fully functional? I have researched for most of today whith no luck. Thank you. Sam

# Answer
> 0 votes
If you are running drush on you're local site, you do not need to include `@pantheon.thecottagepress.dev` to run the command. Just run drush from your site root as so: `drush rr`. Drush won't be able to run the command on a remote machine if it can't resolve the domain name.

---
Tags: drush, composer
---


title: Programmatically place blocks?

text:
# Question
Title: Programmatically place blocks?
I'm using Drupal 7. Right now, I have a main-menu navigation and Language switcher that exists in my website header. I placed them there by going to the CMS\>Structure\>Blocks and hten dragging the blocks into the header region.

How do I programmatically situate these block in the header?

# Answer
> 4 votes
To alter the region where blocks defined by other modules are placed, you can implement hook\_block\_info\_alter(), which receives the following arguments:

* `$blocks` (passed by reference): the array containing the block definitions, keyed by module, and delta
* `$theme`: the theme for which the blocks are being defined
* `$code_blocks`: the blocks as defined from the `hook_block_info()` implementations, before their values are overridden by the values obtained from the database

# Answer
> 3 votes
It is legitimate to add a renderable array to any page region in hook\_page\_build(). Drupal 7 example to add a minipanel to the footer region.

```
<?php
/**
 * Implements hook_page_build().
 */
function MODULE_page_build(&$page) {
  $block = module_invoke('panels_mini', 'block_view', 'blah');
  $blocks['blah'] = array('#markup' => $block['content']);

  $region = 'footer';
  if (isset($page[$region])) {
    $page[$region] = array_merge($page[$region], $blocks);
  }
  else {
    $page[$region] = $blocks;
  }
}

```

This is the very same technique that uses context module.

Note: you don't need block.module enable for this to work.

# Answer
> 2 votes
In D6 it would essentially be

```
$block = module_invoke("the_module_name", "block", "view", the_block_delta);
drupal_set_content("the_region_name", theme("block", $block));

```

In D7 I think it is

```
$block = module_invoke("the_module_name", "block_view", the_block_delta);
drupal_add_region_content("the_region_name", theme("block", $block));

```

but I am still getting up to speed on D7.

# Answer
> 2 votes
If you are adding a custom block you do this using hook\_block\_info, setting the status option to 1 and the region option to the region you want the block to be placed into.

Example:

```
MODULE_block_info() {
  $blocks = array();
  $blocks['my_block'] = array(
    'info' => t('My Block Name'),
    'status' => 1,
    'region' => 'THE_REGION_I_WANT',
   );
   return $blocks;
}

```

If you are wanting to change an already existing block, you would use hook\_block\_info\_alter() instead, updating the same options has shown below.

Example:

```
MODULE_hook_block_info_alter(&$blocks, $theme, $code_blocks) {
  $blocks['my_block']['status'] = 1;
  $blocks['my_block']['region'] = 'THE_REGION_I_WANT';
}

```

For more information see https://api.drupal.org/api/drupal/modules%21block%21block.api.php/function/hook\_block\_info/7

# Answer
> 0 votes
This code is based on @jonhattan's, but his doesn't render the block container HTML or contextual links. I also provided a simple way to specify all blocks and regions in one place.

```
<?php
/**
 * Implements hook_page_build().
 */
function MODULE_page_build(&$page) {
  global $theme;

  // A list of blocks you wish to display, keyed by region.
  // These are in the format of: 'module_name' => 'delta'.
  $blocks_to_render = array(
    'header' => array(
      'block' => 1,
    ),
  );

  // Add the blocks to each region.
  foreach ($blocks_to_render as $region => $block_list) {
    $block_objects = array();
    foreach ($block_list as $module_name => $delta) {
      $block = block_load($module_name, $delta);
      // Alter some of the defaults to match the current context.
      $block->theme = $theme;
      $block->region = $region;
      $block->weight = 0;
      $block_objects[] = $block;
    }
    $blocks_build = _block_get_renderable_array(_block_render_blocks($block_objects));

    if (isset($page[$region])) {
      $page[$region] = array_merge($page[$region], $blocks_build);
    }
    else {
      $page[$region] = $blocks_build;
    }
  }
}

```

Note: Unlike his code, you DO need the block.module installed.

# Answer
> -1 votes
This isn't the best form, but you **can** manually place content into the page array like this...

```
function mymodule_page_alter(&$page) {
  $my_content = _mymodule_render_mycontent();
  $page['my_region']['my_special_insert']['content']['#markup'] = $my_content;
}

```

Though you should stick to using Context or just core blocks. Making new plugins isn't as bad as it seems. Just name files correctly, setup a trigger and a test. example.

# Answer
> -1 votes
you also can adjust blocks in your theme like:

```
/**
 * Implements hook_preprocess_page().
 */
function your_theme_preprocess_page(&$variables) {

  if (drupal_is_front_page()) {
    $variables['page']['region_one'] = $variables['page']['region_two'];
    unset($variables['page']['region_two']);
  }
}

```

---
Tags: 7, blocks
---


# Question
Title: How to display selectable variations without attributes?
With Drupal Commerce 2, each of my products have multiple variations which are unique and can be adequately described by their variation title.

I can not figure out how to display a dropdown for the add to cart form based the variation title alone. All that is shown is the title of first variation, the price and the add to cart button. No dropdown with the other variations.

The only way I can get it to work is by first creating a series of matching attributes which is both a repetitive exercise and seems like it should not be necessary.

What am I missing?

Similar question: What's the best the approach to add an extra attribute field in Drupal Commerce?

# Answer
if i understand you question correctly, you accomplish this by going to your order item type, choose manager form display then you have the field available called Purchased entity ... you want to change the default widget from product variation attributes to Product variation title.
> 0 votes

---
Tags: commerce
---


# Question
Title: href link assigning callback action - ajax
I have a situation where I would like to define a href link and when it is clicked, for it to trigger an ajax response such as sending back some information which can then be shown on the page...

Part 1. Creating the link... So I've created the link via:

```
    $url = Url::fromUserInput('#');

    $nxt_button=Link::fromTextAndUrl('Submit Application',$url);
    $nxt_button=$nxt_button->toRenderable();

    $nxt_button['#attributes'] = [

    ];

    $output['link1']=array(
        "the_link"=>$nxt_button,
    );

```

Now in the '#attributes' I assume i could put something like 'callback' =\> 'name of function to be run' ... but, if the function to be run resides in another object say 'ajax\_test\_script.php' how would I do that?

Part 2. Say the server side responding code, was in a different class called 'ajax\_test\_scirpt' and the function to call is 'start' ... If I was sending back information via:

```
$response=new AjaxResponse();
$response->addCommand(<<what goes here>>);
return $response;

```

And these lines of code were inside the function 'start'... What would I put as the input parameter for addCommand, if I wanted the response to behave such that it could call the javascript function outlined below, which would be attached to the page (e.g call readMessage passing in the parameters needed by the readMessage function):

```
(function($, Drupal) {
/**
 * Add new command for reading a message.
 */
Drupal.AjaxCommands.prototype.readMessage = function(ajax, response, status){
    // Place content in current-msg div.
    $('#current-msg h2').html(response.subject);
    $('#current-msg p').html(response.content);
    // Remove from unread list.
    $('#msg-' + response.mid).remove();
    // Add message to read list.
    $('#read-msgs').append('<li>' + response.subject + '</li>');
}

})(jQuery, Drupal);

```

Any help is appreciated.

# Answer
For anyone needing help on this, as the information out there seems to be either related to forms only or seems rather over convoluted... ajax callback can be added to normal links, by defining the link as outlined above (in the question) - but adding the '/nojs/' prefix to the Url defining portion of the code and adding the class 'use-ajax' in the attributes section of the code e.g. :

```
// Define the link.
$url = Url::fromUserInput('/nojs/ajax_call_url');
$the_link = Link::fromTextAndUrl('Submit Application',$url);
$the_link = $the_link->toRenderable();

$the_link['#attributes'] = [
  'class'=>'use-ajax',
];

// Add the link to your render array.
$output['link1'] = array(
    "the_link"=>$the_link,
);

```

Now in the '*name of your module*'.routing.yml file add the route to where your ajax callback function is... as '/nojs/' is used (as it has to be by the looks of things) it means your path must be defined with the prefix '/ajax/' followed by the path of your choice e.g.:

```
path: '/ajax/call_ajax_url'

```

the \_controller attribute in the routing.yml file, will be defined to point to where your ajax callback command is defined... e.g. will point to whatever object and function holds the

```
    $message="hello";
    $response=new AjaxResponse();
    $response->addCommand( new HtmlCommand("#current-msg",$message);
    return $response;

```

Hope this helps someone - as it took a while for me to find the info necessary to resolve this issue.
> 1 votes

---
Tags: 8, ajax
---


# Question
Title: How to programatically add a pseudo field to views and display the field value based on value of other field?
I need to add a field to view and display the value of that field depending on the value of other fields already present.

The pseudo field i need to add is not connected with any database table.

# Answer
> 0 votes
In addition to the preprocess hook approach noted in the comments, you may want to use:

---
Tags: 7, views, entities
---


# Question
Title: How to get Drupal 7 to search attached PDF and Word documents
From what I have read it seems like you have to use Solr to have PDF and Word attachments indexed and returned in a search. I have Solr working with Drupal but I think I need Tika working on Solr in order to do the document indexing. There is very little documentation I can find for Tika. Does anybody know where a good source for this is? Is there a better/easier way to have search in Drupal index attached documents?

# Answer
To help you, you've this nice module Apache Solr Attachments. If you download the module you'll have a README.txt that give you some clues how to help you install and configure Tika.
> 5 votes

# Answer
We have used Search Files before with success, but I think the last time we used it was two years ago. Note that there are server side requirements for executables to do the searching, and that there isn't a Drupal 7 version available.
> 1 votes

# Answer
I discovered Search File Attachments, which has support for both Drupal 7/8 and a variety of file types.
> 0 votes

---
Tags: 7, search
---


# Question
Title: How to get nodes created on current using Views and Drupal 8
How can I display records that were created on the current date using views. I have used the now value on the created date filter but the records are not showing. I think its because now also includes the the current time. Please Help?

# Answer
You can use Content: Authored on in views filter criteria and specify offset today. I was able to achieve event date filter using below code. I was able to achieve this using custom coding may be it will help you.

```
function common_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
if ($view->id() == 'new_page' && $view->getDisplay()->display['id'] == 'news_present_year') {
       // print_r($query->where[1]['conditions'][2]);
        $current_yr_start = strtotime(date('Y-01-01'));
        $current_yr_end = strtotime(date('Y-12-31'));
        $current_yr = 'node_field_data.created BETWEEN ' .$current_yr_start.' AND '.$current_yr_end;
        //$current_yr= 'node_field_data.created = '.strtotime(date('Y-01-01'));
        $query->where[1]['conditions'][2]['field']= $current_yr;

        /*print_r($query->where[1]['conditions'][2]);
       kint($query->where[1][3]);
        dpm($query);*/
        }
        if ($view->id() == 'new_page' && $view->getDisplay()->display['id'] == 'news_block') {
        //print_r($query->where[1]['conditions'][2]);
        $current_yr= 'node_field_data.created < '.strtotime(date('Y-01-01'));
        $query->where[1]['conditions'][2]['field']= $current_yr;

        //print_r($query->where[1]['conditions'][2]);
        }
    }

```
> 0 votes

---
Tags: views
---


title: How do I update a module schema?

text:
# Question
Title: How do I update a module schema?
I have already created a module (test\_auth), which I installed on a Drupal site.

I added `test_auth_schema()` & `test_auth_update_8101()` to test\_auth.install. When I run `drupal cache:rebuild`, it doesn't create my table in the database.

I put `echo 1; exit;` in both functions, but they don't seem invoked.

What am I missing?

# Answer
Simply clearing the cache doesn't make Drupal do anything on updated modules. `hook_update_N()` implementations are invoked from update.php, similarly to what happens with previous Drupal versions. This means, for example, that once Drupal runs `mymodule_update_8001()`, it will not run the same update hook again; for new updates, `mymodule_update_8002()` is required.

Differently from `hook_update_N()`, `hook_schema()` is not invoked when a module is updated, but when a module is installed. So, it is expected that `test_auth_schema()` is not invoked, when the module is not installed.

The alternative to run update.php is using Drush (i.e. `drush updatedb`).
> 2 votes

---
Tags: updating
---


# Question
Title: Cannot seem to get hook_preprocess_page to work in 8.4.2
Why do I get to the breakpoint in `MYMODULE_preprocess_page_title` but not in `MYMODULE_preprocess_page`?

What I am tying to achieve is to update page title both on the top of the page and in the browser title bar/tab name.

The following code only affects the title on the top of the page.

```
function MYMODULE_preprocess_page_title(&$variables) {
  $variables['title] = 'Something Different!';
}

```

I've read some people are saying hook `hook_preprocess_page` instead to update both.

I tried to find what are the available hooks like `hook_preprocess_blabla` starting here, but couldn't find my way in the documents to the list of available hooks.

# Answer
> 0 votes
both should work on custom MODULE or THEME

```
function MODULENAME_preprocess_page(&$vars) {
  //do stuff
}

function MODULENAME_preprocess(&$vars, $hook) {
  if($hook == 'page') {
    //do stuff
  }
}

```

You need to rebuild cache and at least when using netbeans be careful not all lines will trigger the breakpoint ... for example I have noticed that multiline array definitions will not trigger it. Post your code for more details

---
Tags: 8, hooks
---


# Question
Title: Fast way to test (manually) commerce checkout process
For a Drupal 7 Commerce site, I am working on the behavior of a payment and invoicing service during checkout. Among other things, there is one implementation of `hook_commerce_checkout_complete()`, the behavior of which I want to improve.

So far, for testing this, I always do a complete shopping and checkout process:

1. Visit a product page.
2. Add the product to the cart.
3. Enter a (new) address. (For a realistic experience, I think I need to type in a new address, because most buyers on this site are one-time anonymous customers.)
4. Choose a payment method, confirm.

After this, I will look at the logs, the order that was created, and the emails I received. Then I will start over with the next iteration.

My browser does a half-decent job of prefilling the form with the address. Just one field (city) is left empty consistently.

But even if this would work, there are still some steps too many for my taste, for rapid iteration of manual tests.

Is there a way to automate some of this?

Note: I am not talking about automated tests here. I am talking about manual testing during development.

# EDIT: Automated vs manual testing

The comments indicate that my question might be confusing. Maybe I chose the terms poorly, so I will explain how I want them to be understood for this question.

"Automated testing": I have a machine that bakes a cake according to a codified recipe. And another machine that determines if the cake is according to expectations, e.g. by testing chemical properties or the color. The expectations are also codified, and do not change. The result is either "passes" or "does not pass".

What I want instead: A machine that bakes a cake according to a codified recipe. But then I want to taste the cake myself, and determine how I want to change the recipe. This means in this case, the expectations are not known beforehand, and they are not codified.

Without any automation, I would have to bake the cake manually, then taste it, then bake another cake, taste it again, etc.

According to the answer by @PatrickKenny, Selenium can do both things for me.

If someone can suggest a better way to say this, I will be grateful.

# Answer
This is not specific to Drupal, but you can use Selenium IDE.

Selenium is a framework for automated testing, but the IDE allows you to do lazy manual testing too.

You need to install Firefox and the Selenium IDE addon.

**Basic explanation of how to get started**

1. Open the IDE (addon) and press the red "record" button.
2. Go to your site and carry out all the steps manually. Selenium IDE will automatically record the steps as you go along.
3. You can also add steps manually or edit the steps in the displayed editor. This supports cut and paste so you can edit it pretty quickly.
4. When you're done, save the file. You can then open this file again in the IDE and press the play button to automatically carry out all the steps.
> 2 votes

---
Tags: 7, commerce
---


# Question
Title: Not able to alter field value/s using hook_views_pre_render or views api hook functions
I have a search result page created using search api and views. My search result page is based on this tutorial and it seems to work properly,however I need to tweak some field's output value and I used `hook_views_pre_render` to try to alter the field values however I cant see my fields that I added from the views UI interface on the `$view->result` array but they are rendered on the page. All I see when I `krumo($view->result)` is (see attached image).

I seem to only get entity and entity\_properties array but not the fields in the array. I need to access the field to make the necessary tweaks like we have in the normal `$view->result`.

# Answer
> 1 votes
This is not a specific answer for your situation but I would like to advise you a better way of managing it.

Instead of rendering the views using `Fields` you can render each row by rendering as `Content` where you can choose a dedicated `View mode` which can be easily overridden using the standard `template_preprocess_node`.

This will bring a lot more flexibility in your Web application.

---
Tags: 7, views, search
---


# Question
Title: Multiple form submissions sorted by user
Here's my case:

I have site with 5 forms. These can be filled in by user assigned with the a 'client' role. They can view and edit their own submissions and fill in forms multiple times, this works all as expected.

Now I'm looking for a way to display *all submissions* of *all forms* filtered by user. So when the site admin clicks on a client he can see a list with all submissions that this particular user has made.

I've been trying to tweak the default webform submissions view, create new views based on user, create a new view based on webform submissions with different relationships and contextual filters,.. unfortunately all without any luck.

I've been looking around but haven't found a good answer yet, I do apologize if I overlooked and this question has already been asked and properly answered.

Thanks a lot in advance.

# Answer
> 0 votes
It sounds like you are doing two different searches:

A. Get all webforms for which a user is the author

B. Get all users

Basically, Views has trouble with this kind of thing, because Views generally deals with one type of entity at a time, and users and webforms are different types of entities.

You can use Views Field View module to put one view inside the other.

Rough outline:

1. Create a view showing all the forms for a given user (filter for the user using a *Contextual filter* on the UID)
2. Create another view showing all users. Use Views Field View to embed the view created in 1 and supply the UID as the argument.

This view will probably be very slow/performance intensive but since this is mainly for admin purposes hopefully that's ok.

See more details in this answer.

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


# Question
Title: node aliased path as views contextual filter
I want to have a view which would output a node title and use a contextual filter the aliased path of a node

```
/nodefilter?url=/category/path-to-article

```

I see there no php contextual filters in drupal 8 anymore do I have to write a custom contextual filter or is there another solution ? Any help will be greatly appreciated

# Answer
First I have created a view that uses contextual filter `content ID` to filter the results by "node id" and can be called like this

```
/nodefilter/[NID]

```

After I made sure the view was working I modified the `content ID` contextual filter adding default query paramenter named `url` under `WHEN THE FILTER VALUE IS NOT AVAILABLE > Provide default value`

then in a custom module used the views api `hook_views_pre_view` as follows

```
use Drupal\views\ViewExecutable;
function MODULENAME_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  if($view->id() == 'view_machine_name'){
    $url = \Drupal::request()->query->get('url');
    $path = \Drupal::service('path.alias_manager')->getPathByAlias($url);
    if(preg_match('/node\/(\d+)/', $path, $matches)) {
      //$node = \Drupal\node\Entity\Node::load($matches[1]);
      //$nid = $matches[1];
      $args[0] = $matches[1];
    }
  }
}

```

Now the view works with `NID` or the `url` parameter

```
/nodefilter/[NID]
/nodefilter/?url=/category/path-to-article

```
> 1 votes

---
Tags: views
---


# Question
Title: View the original price, the discounted price and the discount percentage
I am currently working on a newsletter and I want to display the prices of my products there. How to recover the original price, discounted prices and the discount percentage. I wish to put three different value to place my letter and apply a different style.

With this line **`print render($content['product:commerce_price']);`** it displays the three values. But I would separate them.

So what line of code do I type to get the original price, then to get the discounted price and then to get the discount percentage? here is a product page of my site enter link description here

thank you

# Answer
> 0 votes
If this is Drupal 7, you can use the Commerce Price Savings Formatter. This extends the price field to show the "list price" and "sale price" and automatically calculates the percentage.

The module page links to a video explaining how to use the module.

---
Tags: commerce
---


# Question
Title: Hide the number of products on the shopping cart when it is empty
I copy the file "commerce-cart-block.html.twig" in my sub-theme. Currently it displays my shopping cart with the number of products inside.

I want that when there is no product in it, the shopping cart remains displayed and the number disappears.

How to do this ?

```
<div{{ attributes}}>
  <div class="cart-block--summary">
    <a class="cart-block--link__expand" href="{{ url }}">
      <span class="fa fa-shopping-basket"></span>
      <span class="badge">{{ count }}</span>
    </a>
  </div>
  {% if content %}
  <div class="cart-block--contents">
    <div class="cart-block--contents__inner">
      <div class="cart-block--contents__items">
        {{ content }}
      </div>
      <div class="cart-block--contents__links">
        {{ links }}
      </div>
    </div>
  </div>
  {% endif %}
</div>

```

# Answer
Could you not add an if around the tag containing the {{ count }}?

since you are using Drupal 8, you can use Twig filters. One way could be like below.

```
{% if count > 0 %}
    <span class="badge">{{ count }}</span>
{% endif %}

```
> 0 votes

---
Tags: theming, 8, commerce
---


# Question
Title: How to get list of installed/enabled modules ready for repopulating new site with drush module installation?
When doing `drush pm-list` I get a whole list of modules but too much info also, like this:

Mail Privatemsg filter (privatemsg\_filter) 7.x-1.4
Mail Privatemsg Limits (privatemsg\_limits) 7.x-1.4
Mail Privatemsg roles (privatemsg\_roles) 7.x-1.4\`

I have to edit in notepad++ and run macros...

I want the module list, but ONLY drush module names X\_Y

Is there a way to get a clean list like:

module\_a
module\_b
module\_c

ONLY

And then can use it as:

```
drush en module_a module_b module_c

```

# Answer
Ok, got it working, commands to use are:

```
drush pm-list --type=module --status=enabled --no-core --format=list

```

and then you can use the:

```
edit>>mark>>copy

```

from drush console.
> 3 votes

# Answer
```
drush pm-list --status="enabled" --pipe

```

> * `--status="enabled"` Filter by extension status. Choices: `enabled`, `disabled` and/or '`not installed`'. You can use multiple comma separated values. (i.e. `--status="disabled,not installed"`).
> * `--pipe` Equivalent to `--format=list`.
> * `--format="list"` Select output format. Available: `table`, `csv`, `json`, `list`, `var_export`, `yaml`. Default is `table`.
> 15 votes

# Answer
If the purpose of your question is to repopulate a new site (as in your question title), then you may want to look at the drush make-generate command.

No need for things like editing and/or running macros (though you could edit the result if for whatever reason you still have to do so).

Refer to How to use Drush Make in your daily routine for an interesting article about it also.
> 2 votes

# Answer
You can obtain the list using the module\_list() function

> Returns a list of currently active modules.
>
> Usually, this returns a list of all enabled modules. When called early on in the bootstrap, it will return a list of vital modules only (those needed to generate cached pages).
>
> All parameters to this function are optional and should generally not be changed from their defaults. Parameters
>
> $refresh: (optional) Whether to force the module list to be regenerated (such as after the administrator has changed the system settings). Defaults to FALSE.
>
> $bootstrap\_refresh: (optional) When $refresh is TRUE, setting $bootstrap\_refresh to TRUE forces the module list to be regenerated using the reduced set of modules loaded in "bootstrap mode" for cached pages. Otherwise, setting $refresh to TRUE generates the complete list of enabled modules.
>
> $sort: (optional) By default, modules are ordered by weight and module name. Set this option to TRUE to return a module list ordered only by module name.
>
> $fixed\_list: (optional) If an array of module names is provided, this will override the module list with the given set of modules. This will persist until the next call with $refresh set to TRUE or with a new $fixed\_list passed in. This parameter is primarily intended for internal use (e.g., in install.php and update.php).
> 1 votes

---
Tags: 7, drush
---


# Question
Title: Full urls to internal pages logging users out
I have a website with a private area for authenticated users only.

I have some custom routing to control user access and it generally all works fine, however, I have run in to a problem I am not sure how to fix.

My users can create content. When they create a link to another page on the site - say `/apage` with its internal alias it all works fine. If they insert the entire url however, say `https://www.fakesite.com/apage` they get redirected to the login page and asked for their credentials.

Obviously it would be ideal if users only entered the internal alias but there are 200 of them and they don't always listen to me...

Is this a simple fix or have I made some error in my routing?

---

It's happening on links created within the site. I have watched users do it. User are definitely getting booted to log in, once they log in again they can visit the page from that same link and everything is ok for that page, but it is happening for every single page with an full url link.

# Answer
> 2 votes
This is probably due to a change in the base URL. For example, you are using `www.example.com` sometimes and `example.com` others (without a redirection from one to the other).

The reason you get logged out is that the browser tracks the session with a cookie that is linked to a specific domain. By default Drupal includes the subdomain (www/bare).

## D7 Solution

You can fix this by adding this to your settings.php file.

`ini_set('session.cookie_domain', '*example.com');`

This will tell your browser to allow both `www.example.com` and `example.com`.

Alternatively, you can redirect all traffic to one or the other. Drupal's .htaccess file has examples of both of these. You just need to uncomment one.

## D8 Solution

The Drupal 8 solution can be found here: https://drupal.stackexchange.com/a/233753/49434

# Answer
> 2 votes
The easiest solution to this would be to always process the users input as an internal URL. The module LinkIt may provide that. Additionally, you can try using the custom code from an answer to this question which will convert whatever the user enters to an internal URL.

---
Tags: users, routes
---


# Question
Title: Using twig|without for a commerce product
I have a twig template for my commerce product, `commerc-product--contenttype.html.twig`:

```
<article{{ attributes }}>
  <div class="row">
    <div class="col-xs-6">
      {{ product.field_price_original }}
      {{ product.variation_price }}
    </div>
    <div class="col-xs-6">
      {{ product.field_discount_percentage }}
    </div>
  </div>
  {{ product|without('variation_attributes', 'product.field_price_original', 'product.variation_price', 'product.field_discount_percentage') }}
</article>

```

I want to print three fields separately first and then print the rest of the content except for the first three fields (which have already been printed).

However, even though this note implies that without can take multiple values, everything is being printed; the `without` is ignored.

If I try a single value like this:

```
  {{ product|without('product.field_price_original') }}

```

The `without` is still ignored. What might be the cause of this?

Drupal 8.4 and Commerce 2.1

# Answer
> 1 votes
You remove the sub-keys below `product`:

```
article{{ attributes }}>
  <div class="row">
    <div class="col-xs-6">
      {{ product.field_price_original }}
      {{ product.variation_price }}
    </div>
    <div class="col-xs-6">
      {{ product.field_discount_percentage }}
    </div>
  </div>
  {{ product|without('field_price_original', 'variation_price', 'field_discount_percentage') }}
</article>

```

---
Tags: 8, commerce
---


# Question
Title: How can I create a custom module that allows multiple image upload fields?
To be a little more specific, I am trying to create a custom field which will contain 4 images and 4 corresponding paragraphs. The part that I am having issues with is allowing 4 image upload fields.

# Answer
No need for custom module, the Paragraphs contrib module will allow you to do that. See Tutorial.
> 1 votes

---
Tags: files
---


# Question
Title: How to get content with their taxonomy term name and id?
Hello I have created content type product. I also add Taxonomy with name "category". I add field in with term reference in product content type. Now I want to get all content with taxonomy name and id which have content type named "product" using query in Drupal 8 .

# Answer
> 0 votes
Make a dynamic query like this:

```
$query = \Drupal::database()->select('node_field_data', 'nfd');
$query->condition('nfd.type', 'product');
$query->leftJoin('node__field_category', 'ft', 'ft.entity_id = nfd.nid');
$query->leftJoin('taxonomy_term_field_data', 'fd', 'fd.tid = ft.field_category_target_id');
$query->fields('fd', ['tid', 'name']);
$query->fields('nfd', ['nid']);
$results = $query->execute()->fetchAll();

```

Suppose the reference field taxonomy machine name is "node\__field\_category". The result of the query will be node id , term name and term id.

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


title: Twig templates not inheriting

text:
# Question
Title: Twig templates not inheriting
I have a parent theme with templates defined in a directory called templates. Within that folder, I have directories like base (page, html, block etc twig templates), views, and menu folder.

My subtheme, which is based on the parent, will not load these templates even though base\_theme is set in the .info.yml file.

What am I missing? If I copy the templates into the subtheme, they begin to work.

# Answer
Annnnd after asking I read my question and realized my answer. The key base\_theme is not one word, it's two.
> 0 votes

# Answer
Make sure you have the correct indentation in THEME.info.yml file, I had some problems before with this aspect. And also clear the cache after changes.
> 0 votes

---
Tags: 8, theming
---


# Question
Title: Why is accessing paragraphs slow? Is there a better approach?
I'm trying to get the target\_revision\_id of a paragraph within a paragraph within a node. I can do this, but it is slow.

```
$all_nodes = db_select('node','e')->fields('e',array('nid'));
$all_nodes->condition('type','author');
$data = $all_nodes->execute();
$the_result = $data->fetchAll(\PDO::FETCH_ASSOC);
foreach ($the_result as $node){
    $node_load =  \Drupal\node\Entity\Node::load($node['nid']);
    foreach ($node_load->field_paragraphs as $item) {
      $para_id = $item->entity->field_affiliation_details->target_revision_id;
      //then, store the para_ids in some array
      $para_ids[] = $para_id;
    }
}

```

Performing the reference "$item-\>entity" makes my app slow down by a lot. It is really just Kilobytes of data. Is there maybe a better approach to this?

Thanks for any help.

# Answer
> 2 votes
Well after fiddling around with it some more, I suppose the best answer here is to just cache the variable `$para_ids` using `\Drupal::cache()` and then update it whenever there is a node/entity update or insert. I could look into database optimization to see what is actually happening with the `$item->entity` reference, and put an index on the joins/where statements but I am not very confident that is the best way.

---
Tags: 8, entities, paragraphs
---


# Question
Title: How to validate all elements in Custom Widget
I can validate a single textfield usig the fllowing code.

```
/**
 * @file
 * Contains \Drupal\field_example\Plugin\Field\FieldWidget\TextWidget.
 */

namespace Drupal\field_example\Plugin\Field\FieldWidget;

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

/**
 * Plugin implementation of the 'field_example_text' widget.
 *
 * @FieldWidget(
 *   id = "field_example_text",
 *   module = "field_example",
 *   label = @Translation("RGB value as #ffffff"),
 *   field_types = {
 *     "field_example_rgb"
 *   }
 * )
 */
class TextWidget extends WidgetBase {

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $value = isset($items[$delta]->value) ? $items[$delta]->value : '';
    $element += array(
      '#type' => 'textfield',
      '#default_value' => $value,
      '#size' => 7,
      '#maxlength' => 7,
      '#element_validate' => array(
        array($this, 'validate'),
      ),
    );
    return array('value' => $element);
  }

  /**
   * Validate the color text field.
   */
  public function validate($element, FormStateInterface $form_state) {
    $value = $element['#value'];
    if (strlen($value) == 0) {
      $form_state->setValueForElement($element, '');
      return;
    }
    if (!preg_match('/^#([a-f0-9]{6})$/iD', strtolower($value))) {
      $form_state->setError($element, t("Color must be a 6-digit hexadecimal value, suitable for CSS."));
    }
  }

}
```

But I have more elements in the widgets as follows

```
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {

     $element['cert_fqdn'] = [
      '#type' => 'textfield',
      '#title' => t('Fully qualified Domain Name'),
      '#value' => $items[$delta]->value ?: NULL,
      '#empty_value' => '',
      '#placeholder' => t('Fully qualified Domain Name'),

    ];
    $element['privatekey'] = [
      '#type' => 'textfield',
      '#title' => t('Private Key'),
      '#default_value' => isset($items[$delta]->cert_key) ?
          $items[$delta]->cert_key : null,
      '#empty_value' => '',
      '#placeholder' => t('PrivateKey'),
    ];

    // City

    $element['csr'] = [
      '#type' => 'textfield',
      '#title' => t('Certificate Signing Request'),
      '#default_value' => isset($items[$delta]->cert_csr) ?
          $items[$delta]->cert_csr : null,
      '#empty_value' => '',
      '#placeholder' => t('Certificate Signing Request'),
    ];
    $element['cert_crt'] = [
      '#type' => 'textfield',
      '#title' => t('Server Certificate'),
      '#placeholder' => t('Server Certificate'),
    ];

$element['create_cert_btn'] = array(
    //'#name' => implode('_', $element['#parents']) .'_create_cert_btn',
    '#type' => 'submit',
    '#value' => t('Create/Renew Cert'),
        '#element_validate' => array(
        array($this, 'validate'),
            ),

    );

    return $element;

  }
```

I need to get the values of all the elements in validate function. How can I change the code to meet this . Please help.

# Answer
> 1 votes
A GOOD example of this approach is Field\_example module from Example module for developers.(link here https://www.drupal.org/project/examples/releases/8.x-1.x-dev).

The widget with the "field\_example\_3text" id has also 3 elements: "r", "g, "b", and the values are accessed in validation function:

```
  foreach (['r', 'g', 'b'] as $colorfield) {

      $values[$colorfield] = $element[$colorfield]['#value'];
  }

```

So create an array containing your keys elements and loop into it, accessing the values by writing $element\['your key'\]\['#value'\];

Have a look at this module. The dpm of the $element variable looks like this:

---
Tags: 8
---


# Question
Title: How to check if field value has changed on a node?
I have a node type that holds a field of users, when this node is saved I am emailing all the users in this field.

This node might be updated from time to time and I don't want to re-email these users, but I want to check for any new users added to this field.

What would be a good way to check this? Could I simply check `$form_state` against `$form` for that field when it is submitted, or is there a better way to achieve this?

# Answer
You could use the Rules module for this. Similar to what is shown in my answer to "How to check with Rules if a new element has been added to a list in a node?".

By using the rule included in that answer, you can discover scenarios such as these:

```
Value user3@example.com was removed from the multi value field.
Value user2@example.com was added to the multi value field.

```

Here is a simplified version of the rule that should be pretty close to your case (to only show the inserted values):

```
{ "rules_verify_updates_to_selected_email_ids" : {
    "LABEL" : "Verify updates to selected eMail IDs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules_conditional", "rules" ],
    "ON" : { "node_update--article" : { "bundle" : "article" } },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-email-addresses" ] },
          "ITEM" : { "current_email_id" : "Current eMail ID" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "NOT list_contains" : {
                      "list" : [ "node-unchanged:field-email-addresses" ],
                      "item" : [ "current-email-id" ]
                    }
                  },
                  "DO" : [
                    { "drupal_message" : { "message" : "Value [current-email-id:value] was added to the multi value field." } }
                  ]
                }
              ]
            }
          ]
        }
      }
    ]
  }
}

```

If you just replace the machine name "`field-email-addresses`" by the machine name of your field that contains the eMail id of the user (prior to import), you should be able to experiment with this rule in your own site to see it at work (for nodes of content type "Article", adapt this type to fit your needs).

All that's left to do is to transform the message that is displayed by sending an appropriate eMail (which is like a Rules-getting-started exercise).
> 0 votes

---
Tags: 7, forms
---


# Question
Title: View's path prevents 404 page from showing
D7, Views 3. I'm kinda puzzled with how Views path work. I have these paths at my site:

`mysite.com/people` \- a view displaying a list of all people

`mysite.com/people/alice` \- an article about Alice

`mysite.com/people/bob` \- there is no such article at mysite.com

When I go to `/people/alice` I get my article. And when I go to `/people/bob` I naturally expect to get a 404 page. But `/people` view is shown instead, probably seeing the "people" part of the path and thinking I've called `/people` view with some parameter. As I do not expect `/people` view to have any parameters and always want it to display a list of all people, how do I tell it not to get into Drupal's process of resolving its paths?

# Answer
> 4 votes
This is not a problem with the Views module; it's how Drupal behaves.

If you look at menu\_get\_item(), you will notice the following code.

```
$original_map = arg(NULL, $path);

$parts = array_slice($original_map, 0, MENU_MAX_PARTS);
$ancestors = menu_get_ancestors($parts);
$router_item = db_query_range('SELECT * FROM {menu_router} WHERE path IN (:ancestors) ORDER BY fit DESC', 0, 1, array(':ancestors' => $ancestors))->fetchAssoc();

```

I tried the following code, in a test site.

```
$original_map = arg(NULL, 'people/bob');

$parts = array_slice($original_map, 0, MENU_MAX_PARTS);
$ancestors = menu_get_ancestors($parts);

```

What I got is an array containing the following items:

* people/bob
* people/%
* people

In your case, as there isn't a menu callback for people/bob, and people/%, the query executed from `menu_get_item()` will find the menu callback for people, the view you have defined.

To avoid people/bob returns the view page, I would create a custom module with the following code.

```
function mymodule_menu() {
  $items['people/%'] = array(
    'page callback' => 'mymodule_people_view',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
}

function mymodule_people_view($username) {
  $alias = "people/$username";
  $path = drupal_get_normal_path($alias);

  if ($alias == $path) {
    // $alias is not a defined alias; in this case, drupal_get_normal_path()
    // returns the string it gets as argument.
    drupal_not_found();
  }
  else {
    drupal_goto($path);
  }
}

```

There is a module to resolve this issue (Views 404), which has now a version for Drupal 7.

> Are your views returning a 200 when it should return a 404? Views404 is the answer! This is very helpful for any caching layer and it will help SEO. \[...\] Standard Drupal behavior is to pass all arguments through, whether or not they requested. Sometimes this behavior is desired. The views 404 module assumes that by default you do not want arguments passed through. 404s for views can also be accomplished by setting the Global: Null under Arguments.

# Answer
> 0 votes
I found creating a module (or installing a beta module) a bit of a hassle. So I set the `empty text` of my view to this

```
<?php
if (arg(1)){
  drupal_set_header($_SERVER ['SERVER_PROTOCOL'] . ' 404 Not Found');
  watchdog('page not found', check_plain($_GET ['q']), NULL, WATCHDOG_WARNING);
  drupal_set_title(t('Page not found'));
  echo t('The requested page could not be found.');
}
?>

```

And set the `input format` to `PHP code`.

It works, but IMHO this should be the default behaviour of a view that doesn't use arguments.

# Answer
> 0 votes
Views can do this natively, but it is very well hidden and non-intuitive:

* Add a contextual filter to your view, and set it as *Global: Null*.
* In the settings for *Global: Null* under WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED check *Specify validation criteria* and set Validator to *Basic Validation* and Action to *Show "Page not found"*. Under the collapsed MORE section check Fail basic validation if any argument is given.

---
Tags: 7, views, path-aliases
---


# Question
Title: Passing values from text field to a javascript function in Drupal 8
i am new to Drupal and i am building a form (Drupal 8)that needs to calculate an amount based on the input in two text fields. What i want to achieve is for the "calculate" button to be hidden until the two text fields have been filled but i'm not sure how to achieve this with behaviors. Code example:

```
    $form['weight'] = array(
        '#type'  => 'number',
        '#title' => t('Weight:'),
        '#required' => TRUE,
        '#attributes' => array(
            'id' => 'weight',
            ),
    );
    $form['number'] = array(
        '#type'  => 'number',
        '#title' => t('Number:'),
        '#required' => TRUE,
        '#attributes' => array(
            'id' => 'number',
            ),

    );
   // Here if weight and number are not empty, show button

```

Thanks

# Answer
You do not need to use Drupal Behaviours for this, this can be done with States API which ultimately uses javascript.

e.g.

```
$form['calculate'] = array(
  '#type' => 'submit',
  '#states' => array(
    // Only show this field when the 'toggle_me' checkbox is enabled.
    'visible' => array(
      ':input[name="weight"]' => array(
        'filled' => TRUE,
      ':input[name="number"]' => array(
        'filled' => TRUE,
      ),
    ),
  ),
);

```

You can change the fields name as per your requirement. Hope this will help.

Thanks
> 2 votes

# Answer
Using jQuery you can achieve this

For example if you have input class for weight is input1 and for number it is input2 first hide both the classes using css then using jquery u can show it based on below condition.

```
if($('.input1,.input2').length && $('.input1,.input2').val().length)){
//your code here showing calculate button
$('.calculate').show();
}

```

length evaluates to false in a condition, when the value is 0
> -1 votes

---
Tags: forms, javascript
---


title: There is no homepage URL

text:
# Question
Title: There is no homepage URL
I have just started learning/working with Drupal and I am trying to build a theme for a website (something that has nothing to do with a blog other than the fact that the content is dynamically generated).

I have just installed Drupal 8.4 with the *Minimal* profile and created the bare structure of my theme. However, when I go to visit `http://mysite` I get redirected to `http://mysite/users/1`.

I want to create a frontpage containing a large search bar and the thumbnails of some content (if that matters in any way). I created a `page--front.html.twig` but I still can't get rid of the redirect from `/` to `/users/1`.

Could you please give me some advice regarding this redirect and the more general idea of implementing a custom landing page?

# Answer
> 2 votes
This is the site default configuration:

*/core/modules/system/config/install/system.site.yml*

```
uuid: ''
name: 'Drupal'
mail: ''
slogan: ''
page:
  403: ''
  404: ''
  front: /user/login
admin_compact_mode: false
weight_select_max: 100
langcode: en
default_langcode: en

```

So if you have a *Minimal* install, you have to go to */admin/config/system/site-information* and change the default front page.

The *Standard* profile overwrites this config to point it to the pre-installed front page view.

# Answer
> 0 votes
For redirection, You need to check if anything is written in .htaccess. By default after login if drupal is redirecting you to user/{uid} page and you want it on front page, then you can write below code in your custom module:

```
function hook_user_login($account) {
  // We want to redirect user on login.
  $response = new RedirectResponse("<front>");
  $response->send();
  return;
}

```

For Custom design of Front page, you are going in write direction. You can write the twig code in `page--front.html.twig`.

thanks

---
Tags: theming, 8
---