# Question
Title: How to add an SQL expression to the entity query? (D8)
Assume we have an entity query like the following:

```
$query = \Drupal::service('entity_type.manager')->getStorage('taxonomy_term')->getQuery();
$tids = $query->condition('vid', 'tags')->execute();

```

and we need to add some SQL expression and condition based on it, like the following:

```
Replace(name, ' ', '-') = 'some-tag'

```

How to do that?

The `Drupal\Core\Entity\Query\Sql\Query` class does not have methods for doing so (unlike `Drupal\Core\Database\Query\Select`).

# Answer
> 6 votes
Using query **tags** and **metadata** the underlying `Select` query can be altered easily.

```
$query = \Drupal::service('entity_type.manager')->getStorage('taxonomy_term')->getQuery();

// Add tag and any metadata to the entity query.
$query->addTag('my_category')
  ->addMetaData('my_category', $dynamic_category_name);

$tids = $query->condition('vid', 'tags')->execute();

```

And then in `my_module.module` file:

```
/**
 * Implements hook_query_TAG_alter() for my_category tag.
 */
function my_module_query_my_category_alter(\Drupal\Core\Database\Query\AlterableInterface $query) {
  $expression = "Replace(taxonomy_term_field_data.name, ' ', '-')";
  $args = [
    ':dynamic_category_name' => $query->getMetaData('my_category'),
  ];

  $query->addExpression($expression);
  $query->where($expression . ' = :dynamic_category_name', $args);
}

```

---
Tags: 8, database
---


# Question
Title: Login via REST fails (403 forbidden) if cookie set by Drupal is kept
I am trying to login via an Ajax request. I don't need any fancy REST features, I just want to login. According to the docs and other questions here it should be pretty straightforward for **Drupal 8.3.7**:

```
 $.ajax({
    method: "POST",
    url: "/user/login?_format=json",
    dataType: "json",
    contentType: "application/json",
    data: { user: "myname", pass: "mypass" }
})

```

However, this doesn't work at all for me, as I always get a 403 forbidden response. The funny thing is, I can get it to work in Postman (a third party tool for sending REST requests) but only under certain conditions. **It works great in Postman as long as I don't submit the domain's cookie** with the request. If I stick to the default settings and let it send the cookie I have the '403 forbidden' issues again. If I then manually delete the cookie all is well again for the next attempt (then it sets a new cookie and the next attempt will fail).

I assume I am having the same problem with the in-browser jQuery version of my request, but there I can not seem to get rid of the cookie so I can't get it to work. I have tried every answer provided in related questions (csrf token, jdrupal, basic auth, ...) but it's always the same issue if I make a request where cookie data is automatically attached by the browser.

Any ideas what is going wrong? Why is Drupal hating on the cookie data (which was set by Drupal itself!). Can authenticated users not use the login url anymore? Is it maybe because the /user/login page redirects to /user for authenticated users, so the request is sent to /user instead if you're already authenticated?

# Answer
> 2 votes
> Can authenticated users not use the login url anymore?

No they can't, it wouldn't make sense for them to be able to (you can't login if you're already logged in).

In practical terms, this is the routing entry for the login endpoint:

```
user.login:
  path: '/user/login'
  defaults:
    _form: '\Drupal\user\Form\UserLoginForm'
    _title: 'Log in'
  requirements:
    _user_is_logged_in: 'FALSE'
  options:
    _maintenance_access: TRUE

```

As you can see from the requirements, the user cannot already be logged in to access the resource.

---
Tags: 8, users, javascript, ajax, tokens
---


# Question
Title: How can I add a wrapper to a group by in Drupal 8 views?
I have a (drupal 8.3) view using group by that outputs html like:

```
<div class="view-content">
  <h3>Category 1</h3>
  <div class="view-row"></div>
  <div class="view-row"></div>
  <div class="view-row"></div>
  <h3>Category 2</h3>
  <div class="view-row"></div>
  <div class="view-row"></div>
  <div class="view-row"></div>
</div>

```

I would like to hook or template the group by to use a wrapper and achieve:

```
<div class="view-content">
  <div class="group-wrapper">
    <h3>Category 1</h3>
    <div class="view-row"></div>
    <div class="view-row"></div>
    <div class="view-row"></div>
  </div>
  <div class="group-wrapper">
    <h3>Category 2</h3>
    <div class="view-row"></div>
    <div class="view-row"></div>
    <div class="view-row"></div>
  </div>
</div>

```

Any ideas how I can accomplish this using Bootstrap theme?

# Answer
> 6 votes
You can accomplish this by customizing the views-view-unformatted.html.twig file:

* Use Twig debugging to determine which version of this template is currently being used. Most likely, it's `views-view-unformatted.html.twig` in /core/modules/views/templates
* Copy that file to your theme's templates folder.
* Rename the template to this: `views-view-unformatted--your-view--your-display.html.twig` where `your-view` is the machine name of your view and `your-display` is the machine name of your view display.
* Add this code to the template file you created:

```
<div class="group-wrapper">
  {% for row in rows %}
    {%
    set row_classes = [
    default_row_class ? 'views-row',
    ]
    %}
  <div{{ row.attributes.addClass(row_classes) }}>
    {% if loop.first and title  %}
      <h3>{{ title }}</h3>
        {% endif %}
        {{ row.content }}
   </div>
  {% endfor %}
</div>

```
* Flush your site's caches

Please note that spaces in your machine name are repalced with dashes in the name of the template file.

---
Tags: views, 8
---


title: hook_init called a second time on ajax

text:
# Question
Title: hook_init called a second time on ajax
I am using hook\_init to check if a variable is set, and then redirect if not...

```
function quickstart_init() {
  if (variable_get('quickstart_admin', 0) != 1 && $_SERVER['REQUEST_URI'] != '/welcome/admin') {
    drupal_goto('welcome/admin');
  }
}

```

This works for logged out users, but when you are logged in, it redirects - but the whole page displays twice!

I have traced this down to admin menu, as the second version of the page only appears once that JS runs. Does anyone know if admin\_menu bootstraps onload? In which case, probably run hook\_init again?

Anyway, main question....

What can i do to only run this once, is there something other than hook init that would work?

# Answer
You should really try to get to the bottom of why hook\_init is being called twice, but for a band-aid solution, you can use a static variable (using drupal\_static) to keep track of whether your implementation of hook\_init has already been called.
> 0 votes

---
Tags: 7, hooks
---


title: How to add a colspan in a table header?

text:
# Question
Title: How to add a colspan in a table header?
I need to create a table that will have a header with 4 columns and then all the rows will have 5 columns, so I need to add a colspan in the header.

This is an example of what I trying to do:

```
// The table header.
$header = [
  $this->t('Name'),
  $this->t('Description'),
  $this->t('Weight'),
  $this->t('Package'),
];

// The table.
$form['modules'] = [
  '#type' => 'table',
  '#header' => $header,
  '#rows' => [[1, 2, 3, 4, 5]],
  '#sticky' => TRUE,
];

```

This code just give something like this:

But I trying to obtain something like this:

I tried the last example in Add a class to a Drupal table cell containing \['data'\] but just give some errors.

If you go to see the class Table you will see an example using the `colspan` in the `'#wrapper_attributes'` but it seems not works for the `'#header'`

I can obtain a similar output just adding an empty header column like this:

```
// The table header.
$header = [
  $this->t('Name'),
  $this->t('Description'),
  $this->t('Weight'),
  '',
  $this->t('Package'),
];

```

This will give something like this:

But I think that the correct way is adding the colspan property to the header.

Maybe I'm missing something or we just need to wait for Multi level (multirow) header for table FAPI element to use the colspan in the table header?

# Answer
> 6 votes
I just found the solution looking a bit in the Multi level (multirow) header for table FAPI element and doing some test.

This is the way that I found:

```
// The table header.
$header = [
  $this->t('Name'),
  $this->t('Description'),
  [
    'data' => $this->t('Weight'),
    'colspan' => 2,
  ],
  $this->t('Package'),
];

// The table.
$form['modules'] = [
  '#type' => 'table',
  '#header' => $header,
  '#rows' => [[1, 2, 3, 4, 5]],
  '#sticky' => TRUE,
];

```

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


# Question
Title: How do I add multiple custom CSS classes to Views rows?
This is a kind of follow up to this question:

I have a view where I added taxonomy tags as custom CSS class for rows of a unformatted list:

```
<div class="views-row views-row-1 views-row-odd views-row-first tag1-tag2-tag3">

```

I did that using Replacement Pattern \[tags\] as row class.

The problem is that I need to filter by tags and so every taxonomy tag should be added as a separate class. I would need spaces instead of - so the output would be something like that:

```
<div class="views-row views-row-1 views-row-odd views-row-first tag1 tag2 tag3">

```

Is this possible with Views GUI or do I have to use Views preprocess function?

# Answer
> 1 votes
if you're using multivalue class token, this bug report may be of interest for you. There's also a patch as a workaround available.

> Currently if a views field token contains multiple space-separated class names, these classes will be combined into one class when the string is run through `drupal_html_class()`. Attached is a patch to split token classes before they are sanitized for HTML.

# Answer
> -2 votes
Under "Format" in the left column of the view, you click on "Settings" near the format you choosed, for example "Unformatted list".

In the popup you can edit the row classes.

---
Tags: 7, views
---


# Question
Title: Drupal 8 migrate language: switch all nodes to the default lang
Where testing the migration from drupal 7 to drupal 8 and everything almost works, except i'm running into a language problem.

I have two different languages enabled in Drupal 7, English(Default) and Dutch, but *only for the interface*, there is **no multi-language setup for nodes**.

Now, when i imported the content in drupal 8 with the same two languages enabled, i get to see the content, but it is dived between three types:

* Not specified
* Dutch
* English

I want to see all the content without selecting a language(via url, session, ..). So, how do change it so i can view my nodes without a language prefix in the url ?

I already tried messing with the database and changing the 'langcode' to 'und' and that works, but it breaks many other things. I just want to see site.tld/my-cool-url-alias without anything else.

# Answer
> 1 votes
You need to change your language selection criteria in this admin setting:

Admin -\> Configuration -\> Regional & Language -\> Language / Detection and Selection Tab

You can turn off or configure the URL settings as you want. With no standard detection, the default language should be shown.

You probably want to turn on the administration language detection option. This allows admin users to select their preferred admin language.

---
Tags: i18n-l10n
---


# Question
Title: How to make Views' sort criteria like this screenshot?
The built-in Drupal Views sort criteria separate sorting field and sort direction(ASC/DESC). But it's much more user-friendly under many situations like the screenshot. How to make that?

# Answer
> 1 votes
Check here: drupal 7.10: View of Most viewed posts and follow the steps.

For better exposed filters use this: https://www.drupal.org/project/better\_exposed\_filters

Next time Google it :)

# Answer
> 0 votes
Two possible ways to do this:

1. Have a module that alters the views query to add the sort criteria you need.
2. Create different views with the sort criteria you want, then make a simple HTML / JS block that calls the appropriate page when an option is selected.

---
Tags: views
---


# Question
Title: Override the output of views with angular directives
I use Angular material in my Drupal 8 site (perforce!!!) and I have some problem with views. I want to override the output of views with custom text:

but as we all know views is strict with html tags and angular material uses custom directives for his purposes...

Question:

How to solve this problem?

How to make views to don't trim angular material directives?

Dose any one has solution for this?

UPDATE: The problem is that nothing is rendered correctly...

For example.

angular material card is this:

but the view shows this result:

This means that angular directives ware trimmed by Drupal, and that's why view shows incorrect result.

# Answer
> 0 votes
After a lot of research and debugging i came across to this solution...

The problem of restriction of custom text field of a view is that it uses Xss::filterAdmin function (core/modules/views/src/Plugin/views/PluginBase.php:398 line)...

So i created module, then in mymodule.views.inc file I alter "hook\_views\_plugins\_field\_alter", i changed class that uses the views custom text filed in my own class that i created in mymodule\>src\>plugin\>views\>field\>my\_Custom.php. This class is copy/paste of core/modules/views/src/Plugin/views/field/Custom.php and changed only the \Drupal\views\Plugin\views\PluginBase::viewsTokenReplace only this form:

```
$build = [
    '#type' => 'inline_template',
    '#template' => $text,
    '#context' => $twig_tokens,
    '#post_render' => [
      function ($children, $elements) {
        return Xss::filterAdmin($children);
      }
    ],
  ];

```

to:

```
 $build = [
    '#type' => 'inline_template',
    '#template' => $text,
    '#context' => $twig_tokens,
    '#post_render' => [
      function ($children, $elements) {
        return $children;
      }
    ],
  ];

```

and from now the custom text don't escapes html tags...

For more control i created also one checkbox in field setting to control f i want to escape the text or note for this field and accordingly to the value of checkbox i activate or deactivate the Xss::filterAdmin function

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


# Question
Title: How to get cache metadata from nested render array when returning response?
I have a controller action that renders a list nodes and returns them, and only them. It's invoked via AJAX and the JS code just takes the result and inserts it into the page somewhere.

My problem is getting the cache metadata from the render array of nodes and passing it to the response. Here's the simplified action:

```
public function myControllerAction() {
  $builder = \Drupal::entityTypeManager()->getViewBuilder('node');
  // Get render array containing a few nodes.
  $nodes = $builder->viewMultiple([1,2,3], 'teaser');

  $response = new CacheableResponse();
  $response->setCacheableMetadata(CacheableMetadata::createFromRenderArray($nodes));
  return $response;
}

```

The problem is `CacheableMetadata::createFromRenderArray()` expects you to not give it a nested render array, but that's what the view builder returns. It returns an array of render arrays.

How can I efficiently extract the metadata from each node in the list and apply it to the response?

# Answer
Render the nodes in a render context, so that the metadata can bubble up:

```
  $storage = \Drupal::entityTypeManager()->getStorage('node');
  $builder = \Drupal::entityTypeManager()->getViewBuilder('node');
  $nodes = $storage->loadMultiple([1,2,3]);
  $build = $builder->viewMultiple($nodes, 'teaser');

  $render_context = new \Drupal\Core\Render\RenderContext();
  \Drupal::service('renderer')->executeInRenderContext($render_context, function() use (&$build) {
    \Drupal::service('renderer')->render($build, TRUE);
  });

  $response = new CacheableResponse();
  if (!$render_context->isEmpty()) {
    $response->addCacheableDependency($render_context->pop());
  }

```

The rendering is not lost. The rendered nodes are in `$build['#markup']` and you can add the html to the response if that is what you want to do:

```
$response->setContent($build['#markup']);

```

---

Edit:

Just seen in the related question on the right a similar topic. While the above code is good for demonstration purpose, because it shows how to get cache metadata from a nested render array, the simpler code in the answer to How to handle cache metadata in an AJAX response? is actually working for this nested build array too, because the dependencies of the build array are added after rendering and at this point the metadata has bubbled up to the top level.
> 4 votes

---
Tags: 8, caching
---


# Question
Title: How to Reduce/Increase module's weight on the module install process?
I'm developing one custom module and I want to increase my module weight when the module is installed.

How can I achieve this? Otherwise, does anyone know in which table the module's weight is stored?

# Answer
Use `hook_module_implements_alter()` rather than changing the module weight.

Sample implementation from content\_translation.module:

```
function content_translation_module_implements_alter(&$implementations, $hook) {
  switch ($hook) {

    // Move our hook_entity_type_alter() implementation to the end of the list.
    case 'entity_type_alter':
      $group = $implementations['content_translation'];
      unset($implementations['content_translation']);
      $implementations['content_translation'] = $group;
      break;

    // Move our hook_entity_bundle_info_alter() implementation to the top of the
    // list, so that any other hook implementation can rely on bundles being
    // correctly marked as translatable.
    case 'entity_bundle_info_alter':
      $group = $implementations['content_translation'];
      $implementations = [
        'content_translation' => $group,
      ] + $implementations;
      break;
  }
}

```
> 9 votes

# Answer
There's an API for this now:

```
module_set_weight('your_module_name', 10);

```

You can also implement the hook as Ivan Jaros said, which allows for more fine-grained control (e.g. first for one hook, last for another, after a specific module for the third). But the module weight should work too.
> 10 votes

# Answer
If you use import/export configs, you can change module's weight in `core.extension.yml` file, number after module's name is weight.
> 5 votes

# Answer
You can use the Modules weight module:

> Sometimes we need to modify modules execution order, and some people could write a code that execute the query to modify the weight of a module in the system table, some one might go straight to his favorite SQL client and modify the record directly. This module provides an interface to reorder the modules weight.

Disclosure: I'm the maintainer of the module Modules Weight.
> 4 votes

---
Tags: 8
---


# Question
Title: Complicated module update error HTTP error 0
I'm recently getting the error below:

> HTTP error 0 occurred when trying to fetch https://ftp.drupal.org/files/projects/captcha-7.x-1.5.tar.gz. Downloading updates failed:
>
> Failed to download captcha from https://ftp.drupal.org/files/projects/captcha-7.x-1.5.tar.gz
>
> Blockquote

I'm running my website on a shared platform, so I can't change the parameters of PHP...

Based on this long thread drupal dot org/node/247009 I have already tried several many potential solution with no luck so far. This is what I tried and it did not work:

1. gave 777 recursive permissions to tmp and site/default/
2. tried on different browsers (Edge, Firefox, Chrome)
3. in jquery update module I changed the jquery default version to 1.10
4. I set the jquery source from google, and I set the jquery to non-minified
5. I checked and in settings.php I do not have any base url set
6. the file which failes to be downloaded is very small in size 103KB, so I guess it's not about uploading to large files
7. I checked my PHP version and it did not change recently it;s 5.3.29
8. I also checked the PHP memory limit and it's set to 256MB which to me it's not that low for uploading a 103KB file
9. I I tried the update of a different module, and I get the same error

What could be the problem? Where to look next?

# Answer
> 0 votes
I had the exact same problem and the solution given by Neograph734 was to manually add the module. If you have Filezilla, connect to your drupal site files. Go to Sites--\>all---\>modules---\> Locate the captcha folder, delete everything in that folder. Upload the updated captcha module files. (Download and upzip first).

Once this is done, you will also need to update the database. It will show you where to do that once you click on reports. Once the database is updated, your module should now be upgraded and working. :)

No more nasty notices about having to upgrade it!

---
Tags: updating
---


title: Add discount price on product page

text:
# Question
Title: Add discount price on product page
I use drupal commerce 2 I want to add some discount on my products, so I had enabled the promotion module and created a promotion whithout coupon. First of all is that the good way to create a discount on a product ?

Now I want to display the basic price and the discount one one the product page but I can't find a way to get this discount whithout having an order. What am I missing ?

Thank you

# Answer
> 0 votes
This is still in development and will be included by the full 2.0 release. Follow progress and / or contribute to the effort here: https://www.drupal.org/node/2805549

---
Tags: commerce
---


# Question
Title: Commerce: How to skip checkout cart and redirect to PayPal
How i have to set a rule to go direct to Paypal site? I use PayPal Express and i am not able to solve this. The only one rule i can set is to go to cart/checkout. But i´d like to go one step forward without to see the order and to have to click on the PayPal button. Thanks for helping

# Answer
It's not possible without custom code. The customer either initiates the Express Checkout payment by clicking the button form on the cart page, or the Commerce PayPal module does it on a form submission when the customer chooses PayPal as a payment option on the checkout form. That requires sending an API request to initiate the payment and get the tokens that must be passed with the customer to PayPal to submit payment. With custom code you could simulate the customer choosing PayPal as a payment option on the checkout form and initiate the redirect, but there's nothing that exists to do that that I've seen.
> 0 votes

---
Tags: 7, commerce, payment-gateways
---


# Question
Title: changing commerce product price but also components!
When I ask price info of a product, i have this:

```
Array (
    [amount] => 3020
    [currency_code] => EUR
    [data] => Array
        (
            [include_tax] => 21_btw
            [components] => Array
                (
                    [0] => Array
                        (
                            [name] => base_price
                            [price] => Array
                                (
                                    [amount] => 2496
                                    [currency_code] => EUR
                                    [data] => Array
                                        (

                                    )

                            )

                        [included] => 1
                    )

                [1] => Array
                    (
                        [name] => tax|21_btw
                        [price] => Array
                            (
                                [amount] => 524
                                [currency_code] => EUR
                                [data] => Array
                                    (
                                        [tax_rate] => Array
                                            (
                                                [name] => 21_btw
                                                [display_title] => 21% BTW
                                                [description] => 21% BTW
                                                [rate] => 0.21
                                                [type] => vat
                                                [rules_component] => commerce_tax_rate_21_btw
                                                [default_rules_component] => 1
                                                [price_component] => tax|21_btw
                                                [calculation_callback] => commerce_tax_rate_calculate
                                                [module] => commerce_tax_ui
                                                [title] => 21% BTW
                                                [admin_list] => 1
                                            )

                                    )

                            )

                        [included] => 1
                    )

            )

    )

```

so then i have price with components, then I have this snippet of code to update price, with new price:

```
            $product_wrapper = entity_metadata_wrapper('commerce_product', $product);
            $product_wrapper->commerce_price->amount=30200;
            $product_wrapper->save();

```

but this updates the price, and then I loose the components, I do not understand, isn't there a way to update the price and the components with just one method, or does someone know howto update price and components, what do I have to change in the code? thanks

# Answer
It appears you're entering your product prices with VAT included. This is a feature of the Tax module that works through the product add / edit form to manipulate the product price on form submission. There is no separate API function for it, though that would be a mighty fine feature request if you'd like to open it. Instead you just need to replicate what the module does.

The way it works is that it actually just stores the name of the tax rate in the price's data array via the "include\_tax" key. You can see this in the function commerce\_tax\_price\_field\_validate(). The tax price component then is actually calculated on load via hook\_field\_attach\_load(). This means you shouldn't need to create the tax price component, just ensure the data array contains the target tax rate and that the price is "reloaded" to recalculate that price component.
> 0 votes

---
Tags: commerce
---


# Question
Title: Post review for anonymous, save as draft or save unpublished
I have a form that allow anonymous user to send a job offer. Everything working fine but I don't want users to be able to publish node on the spot. I want it to publish as a draft/unpublished for reviewing before.

Can I alter my form in some way to prevent this? Like only use save unpublished button action.

# Answer
> 0 votes
Does your form after submission creates a node programmatically? If so you can just set the status of the node to 0.

---
Tags: nodes, forms
---


# Question
Title: appened custom text to content in template_preprocess_taxonomy_term drupal 8
I want to append some custom text to taxonomy term pages using template\_preprocess\_taxonomy\_term hook, But when I add my custom array key to it, the text don't show up on the term pages. PS I have cleared drupal cache many time.

Here is my code

`function cars_theme_preprocess_taxonomy_term(&$variables) {
 if($variables['view_mode'] == 'full'){
 $variables['content']['cars_view'] = "this is test";
 }
}`

# Answer
> 1 votes
Ok, so here is how I did it.

```
function cars_theme_preprocess_taxonomy_term(&$variables) {
      if($variables['view_mode'] == 'full'){
         $variables['cars_view'] = "this is test";
     }
}

```

And then in my twig file I output the cars\_view as {{ cars\_view }}

---
Tags: hooks
---


# Question
Title: How to display the entity ID next to the title of an ECK entity
I have an entity template that starts like this:

```
<div class="<?php print $classes; ?>">
<h1><?php print $title; ?></h1>
</div>

```

But now I want to display the entity ID and the UUID next to the title. `<?php print $entity_id; ?>` or `<?php print $entity_id; ?>` display nothing.

Do I need to preprocess something?

# Answer
> 0 votes
$title is an available variable in that entity template. So, yes if you need to pass entity ID and UUID then you will have to pass them via preprocess hook.

# Answer
> 0 votes
It wouldn't display like that, firstly you would need to get the entity id then only you can print it after title. Now if it is a template of node then you can either just get the argument from the url e.g $node\_id = arg(1); this will give you the node id and you can print this.

```
<?php print $node_id . ' ' . $title; ?>

```

If it is some other entity then definitely in the url you will be getting some id of the entity.

Another way is that you can write hook\_preprocess\_page(&$variables) function where in $variables array you can set the value of the entity id e.g $variable\['my\_entity\_id'\] = \______ and in your template you can just print $my\_entity\_id . ' ' . $title;

---
Tags: 7, theming, entities
---


# Question
Title: Configuration values in Kernel Test are null
I'm trying to write a kernel test for a service in my custom module.
This service depends on certain configuration values that are installed by default when the module is enabled. Values are stored in /config/install/mymodule.settings.yml
If I try to get these configuration values in my test setUp() function, I get the correct value.
However, when the test is running, the same value is null when called from inside the service.
Any idea why?

# Answer
Turned out to be a very silly mistake...
I instatiated the service before installing the config with $this-\>installConfig(\['mymodule'\])
> 2 votes

---
Tags: 8
---


title: How to suppress one specific warning?

text:
# Question
Title: How to suppress one specific warning?
I have one specific warning in Drupal 7 from the workbench module which I do not want to display. All other warnings should not be changed.

For now I edit the workbench module by comment the specific line which is not the way it should be solved for final.

I tried to use disables messages wit a specific regex but this is not working. I think because it is a warning and not a message.

I prefer to use hook\_page\_alter but cannot find the specific warning in the $vars array.

Any suggestion for this or what approach and possibility is there to solve this?

# Answer
> 0 votes
Solved it in Hook\_preprocess\_page(&$vars) {

```
  $all_warnings = $_SESSION['messages']['warning'];
  foreach ($all_warnings as $nr => $messageinfo) {
      if (strpos($messageinfo,"do not have permission to moderate") != false){
        unset ($_SESSION['messages']['warning']);
      }
  }

```

---
Tags: 7
---


# Question
Title: Insert JavaScripts into head of only one page
I want to an SVGMap product that requires that I insert the following javascript into head but I only want to use this on one page of my website in a block. If I insert it into the html.tpl.php page, it will load for every page. Is this a drain on resources or is there a better way to do it for just the block that I need it?

Thanks

```
<link href="/mapsvg/css/mapsvg.css" rel="stylesheet">
<script src="/mapsvg/js/jquery.js"></script>
<script src="/mapsvg/js/jquery.mousewheel.min.js"></script>
<script src="/mapsvg/js/mapsvg.min.js"></script>

```

# Answer
> 1 votes
Drupal provides theme suggestion for html.tpl.php

you can put html.tpl.php in templates folder inside you theme directory

**html--node--id.tpl.php**

***id*** will be your page id e.g. ID = 123, then file name will be **html--node--123.tpl.php**

Hope this will help.

===================================================================

For particular block you can use **hook\_block\_view\_MODULE\_DELTA\_alter**

@see https://api.drupal.org/api/drupal/modules!block!block.api.php/function/hook\_block\_view\_MODULE\_DELTA\_alter/7.x

like,

```
function module_name_hook_view_MODULE_DELTA_alter(&$data, $block) {
  drupal_add_js();
}

```

# Answer
> 0 votes
Use drupal\_add\_css and drupal\_add\_js to dynamically add the files only when they're needed.

If you look at the scope option for drupal\_add\_js you can make sure the script tags are added in the header like you need

# Answer
> 0 votes
Include your scripts using drupal\_add\_js() in theme\_preprocess\_page() of your theme's template.php file.

```
    function theme_preprocess_page(&$variables) {
      if('page' === arg(0)) {
        drupal_add_js(path_to_theme().'/js/your_script1.js');
        drupal_add_js(path_to_theme().'/js/your_script2.js');
        ..
      }

      $variables['scripts'] = drupal_get_js();
    }

```

---
Tags: 7, javascript
---


# Question
Title: Overload permissions for specifics users
On my website, I have users with classic roles, but I want to add the possibility to assign permissions to specifics users. For example, a user has a role that doesn't allow the user to create articles, but I want to have a checkbox (on the edit page of the user's account) to grant this permission (and not to all users that have this role). Of course I can't create a specific role for that because I'm talking of many permissions specifics to users.

How can I perform this ?

# Answer
> 1 votes
Just use the Group module, and create a content type like "Personal Groups". And then create a "group" for each user (using something like the user's name as its label), of group type "Personal Groups" (or whatever you want to label it).

Tune the permissions which come with the Group module (which are different from standard Drupal permissions!) to fit your needs.

Possibly you also want to use all sorts of integrations with modules such as the Rules module or the Views module (the Group module is entirely entity based, so those kind of integrations or virtually unlimited). As a sample: if a user enables the checkbox in their profile (as in your question), you could have the Rules module intercept such event, and then "Create a new entity (= i.e. a Group)", and / or trigger some kind of approval/notification process to make such creation of a requeted group happen.

For more details about the various roles and permissions, refer to my answer to "What are the various roles supported by the Group module?".

# Resources

PS: This answer applies for either Drupal 7, or Drupal 8.

# Answer
> 1 votes
I came across a similar situation and I think my is solution either the Group module or the og module. I didn't try them yet but both seems promising. I'm about to try them now.

---
Tags: 8, users
---


# Question
Title: error 500 when D8 site placed in maintenance
Unless connected to admin , putting site in maintenance generate a 500 error.

I have followed Drupal 8 maintenance page theming instructions, modifying the settings.php and adding the template to the theme but it is still not working .

How can i debug this ?

# Answer
**BEGINNER VERSION**

Maintenance mode is working in general. Use the following direction of debugging: FROM "untouched" Drupal TO your state.

1. Download a same core version of Drupal as you have. Turn on maintenance mode (without changing anything else), visit the page with a non-admin user.
2. Apply the settings in your link about (Drupal 8 maintenance page theming ) visit again the page with a non-admin user.

Whenever the site brakes you know where the problem resides.

**ADVANCED VERSION**

500 errors are always logged in Drupal. Check what says the "recent log messages" with admin. Also you can set in your settings.php

```
$config['system.logging']['error_level'] = 'verbose';

```

This won't just show 500 error, but also tell the reason.
> 1 votes

---
Tags: 8, maintenance-mode
---


# Question
Title: How to eliminate access to page based on the user ID?
I want to control the access of a page based on the user ID and the value of some other fields.

For example, if I am logged in as user #5, I have access to `user/5` but I don't have user to the page `user/6` and administrator users have access to both pages.

In my case, imagine I have a custom user page and I want to give access only to the owner and to the user selected in a custom field.

I don't think I can achieve that using permissions and in the future I might have more restrictions based on the value of other fields. So ideally, I would like to have a function where I will get the uid and the value of the fields, I will do my checks and I will restrict the access or not.

By the way my pages are panel pages not nodes.

Any idea/help/suggestion?

# Answer
> 0 votes
I managed to find the solution after long time!

What I really needed was the hook\_entity\_access.

As I'm working with panel pages it was pointless to use `hook_node_access` and I also wanted to have some checks to the url parameters.

# Answer
> 0 votes
You will probably need to add a custom hook\_node\_access code. In this you can use the view operation to check:

* Is the current user the owner (yes - done - allow access)
* Is the user an admin (yes - done - allow access)
* Does the node have your user access list field (No -done - allow access)
* Is the current user's uid in the field values? (Yes - allow access / No -deny access)

This should handle the basic access issues. You may need to look at how to hide / show links based on access as well.

---
Tags: 8, users
---


# Question
Title: Get list of webforms that can be created by the current user
Testing Webform in Drupal 8, I've found something strange when trying to get the list of the available webforms that a user can **create**.

My test environment: I've created a role, a user that belongs to that role and 3 webforms. In the "*Access*" tab of each of the webforms I've unchecked "*Anonymous user*" and "*Authenticated User*" and allowed access only to "*Administrator*" in 2 of the webforms. In the last one, I gave "create" access to my specific role.

Then, for testing purposes I created a rest service with the following code:

```
public function get()
{
    // Load all the available entities
    $entities = \Drupal::entityTypeManager()->getStorage('webform')->loadMultiple(NULL);

    // Check the access of the current user to each of the entities
    $forms = array();
    foreach( $entities as $entity_id => $entity )
    {
       $forms[] = array( "$entity_id" => $entity->access('create', NULL) );
    }

    return new ModifiedResourceResponse($forms);
}

```

I expected to get:

```
[{"webform1":false},{"webform2":false},{"webform3":true}]

```

But I get:

```
[{"webform1":false},{"webform2":false},{"webform3":false}]

```

In fact, I returned the `$entity` object as JSON and I found that the entity references the following permissions: "create", "view\_any", "update\_any", "delete\_any", "purge\_any", "view\_own", "update\_own", "delete\_own". If I expand the tree, then I can see that inside the "create" permission of my webform3 entity, the permissions are properly referenced (Object-\>access-\>create-\>Roles-\>My Role is present only in the last form).

But the `->access('create')` function is always returning false. The same goes for "view\_any" and the other permissions. The only permission that returns true for all the forms is "view".

Is there any way that I can do this? :

```
    $entities = \Drupal::entityTypeManager()->getStorage('webform')->loadMultiple(NULL);
    $forms = array();
    foreach( $entities as $entity_id => $entity )
    {
       if( $entity->access('create', NULL) )
       {
           $forms[] = $entityid;
       }
    }
    return new ModifiedResourceResponse($forms);

```

Thanks and best regards.

# Answer
I'll autoanswer my question :)

By grep-ing inside Webform source code I found that the permission name is not "create", but "submission\_create", even if `dpm($entity)` is referencing "create".

```
$ grep -r "access" * | grep submission_create
webform_node.routing.yml:    entity_access: 'webform.submission_create'
Webform.php:                 if (!$webform || !$webform->access('submission_create')) {
(...)

```

So, this works as expected:

```
$entities = \Drupal::entityTypeManager()->getStorage('webform')->loadMultiple(NULL);
$forms = array();
foreach( $entities as $entity_id => $entity )
{
    if( $entity->access('submission_create', NULL) ) {
        $forms[] = $entity_id;
    }
}

```

It returns only the webforms that you are entitled to send submissions to.
> 3 votes

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


# Question
Title: Placing result count below Views exposed filters?
I have a View, and I want to display result summary below the exposed filters. Currently I am modifying views-view--view\_name.tpl.php.

How I can render result summary header just below the exposed filters?

# Answer
Ad summary of the result in the head of the vieuw and reposition this div with css to the place where you want to put it.
> 0 votes

---
Tags: 7, views, theming
---


# Question
Title: How to save/map uploaded image in term field of type image with storage location equals s3://
I'm having 1 field in a taxonomy = 'features' of type image. Image storage location is set to s3.

I have written a `hook_form_alter` for form\_id = article (article is the content type) where I have created an image field like:

```
$form['image_dir'] = [
    '#type'                 => 'managed_file',
    '#upload_location'      => 's3://s3-bucket',
    '#multiple'             => FALSE,
    '#description'          => t('Allowed extensions: gif png jpg jpeg'),
    '#upload_validators'    => [
      'file_validate_is_image'      => array(),
      'file_validate_extensions'    => array('gif png jpg jpeg'),
      'file_validate_size'          => array(25600000)
    ],

     ];

```

Now in **my form submission**, I'm trying to **save/map** this **image** into my **term image field** (`field_vocab_image`) . For this, I'm trying something like:

```
$term = Term::create([
    'name' => $term_name,
    'vid' => 'my_vocab_name',
    'field_vocab_image' => $img,
  ]);
  $inserted = $term->save();

```

where `$img = $form_state->getvalues()['image_dir'];` this image is coming from the custom field created in `hook_form_alter`.

Above code is successfully saving term name but when I go to edit term , image field is empty. **Image is not getting mapped**.

# Answer
An `Image` type field should contain a file `fid` of an image file. The following should resolve your issue:

```
$img = $form_state->getValue('image_dir');

if (!empty($img['fids'])) {
  $img = reset($img['fids']);
}

```
> -1 votes

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


# Question
Title: How can I add asc and desc sort symbols?
I have a drupal 7 view, consists of table. I need to add sort symbol (both asc and desc) in view header by default if no sorting applied.

I tried with altering views-view-table.tpl.php file, and added asc, desc images for each header.

But I need proper solution, Is there any hook there to alter the table headers?

# Answer
Implement theme\_tablesort\_indicator(). Please replace your theme name with example

```
function example_tablesort_indicator($variables) {
  $style = $variables['style'];
  $theme_path = drupal_get_path('theme', 'example');
  if ($style == 'asc') {
    return theme('image', array('path' => $theme_path . '/images/arrow-asc.png', 'alt' => t('sort ascending'), 'width' => 13, 'height' => 13, 'title' => t('sort ascending')));
  }
  else {
    return theme('image', array('path' => $theme_path . '/images/arrow-desc.png', 'alt' => t('sort descending'), 'width' => 13, 'height' => 13, 'title' => t('sort descending')));
  }
}

```
> 0 votes

# Answer
I think your best bet without a lot of theming and template overrides, preprocessing and some JS is to use jquery TableSorter:

What you have linked to is actually an Angular based front end. TableSorter is the next closest thing without being Angular JS.
> 0 votes

---
Tags: views
---


# Question
Title: Change 'Log in', 'Log out', 'My account' menu text
Is there a way that the default text in the account menu can be changed within the theme?

# Answer
Since it's a menu normally you'd change the text in edit menu section but since the text is defined by the user module you'd have to do a work around. The template that's printing it is links.html.twig. Which looks like:

```
{#
/**
 * @file
 * Theme override for a set of links.
 *
 * Available variables:
 * - attributes: Attributes for the UL containing the list of links.
 * - links: Links to be output.
 *   Each link will have the following elements:
 *   - title: The link text.
 *   - href: The link URL. If omitted, the 'title' is shown as a plain text
 *     item in the links list. If 'href' is supplied, the entire link is passed
 *     to l() as its $options parameter.
 *   - attributes: (optional) HTML attributes for the anchor, or for the <span>
 *     tag if no 'href' is supplied.
 * - heading: (optional) A heading to precede the links.
 *   - text: The heading text.
 *   - level: The heading level (e.g. 'h2', 'h3').
 *   - attributes: (optional) A keyed list of attributes for the heading.
 *   If the heading is a string, it will be used as the text of the heading and
 *   the level will default to 'h2'.
 *
 *   Headings should be used on navigation menus and any list of links that
 *   consistently appears on multiple pages. To make the heading invisible use
 *   the 'visually-hidden' CSS class. Do not use 'display:none', which
 *   removes it from screen readers and assistive technology. Headings allow
 *   screen reader and keyboard only users to navigate to or skip the links.
 *   See http://juicystudio.com/article/screen-readers-display-none.php and
 *   http://www.w3.org/TR/WCAG-TECHS/H42.html for more information.
 *
 * @see template_preprocess_links()
 */
#}
{% if links -%}
  {%- if heading -%}
    {%- if heading.level -%}
      <{{ heading.level }}{{ heading.attributes }}>{{ heading.text }}</{{ heading.level }}>
    {%- else -%}
      <h2{{ heading.attributes }}>{{ heading.text }}</h2>
    {%- endif -%}
  {%- endif -%}
  <ul{{ attributes }}>
    {%- for item in links -%}
      <li{{ item.attributes }}>
        {%- if item.link -%}
          {{ item.link }}
        {%- elseif item.text_attributes -%}
          <span{{ item.text_attributes }}>{{ item.text }}</span>
        {%- else -%}
          {{ item.text }}
        {%- endif -%}
      </li>
    {%- endfor -%}
  </ul>
{%- endif %}

```

One way I think you could accomplish this is make a custom links template that refers to the account menu. You'd need to call it links--toolbar-user.html.twig. Then you could insert some logic like

```
{% if item.text == 'Log in' %}
New login text
{% endif %}

```

There may be other locations besides links.html.twig that bring up the account menu that would have to have custom templates as well, but that's the overall idea.
> 1 votes

# Answer
I needed to do the same but for a lot of items so working with the *menu--account.html.twig* was more confortable for me.

You can pick up string variable by using getUntranslatedString() method :

```
{% if item.title.getUntranslatedString() == 'Log in' %}
  <li{{ item.attributes.addClass(item_classes) }}>
  {{ link("new login text", item.url) }}

```

And if you want to do it for multiple strings :

```
{% if item.title.getUntranslatedString() == 'Log in' %}
 <li{{ item.attributes.addClass(item_classes) }}>
 {{ link('New login text', item.url) }}
{% elseif item.title.getUntranslatedString() == 'My account' %}
 <li{{ item.attributes.addClass(item_classes) }}>
 {{ link('new my account' text, item.url) }}
{% elseif item.title.getUntranslatedString() == 'Log out' %}
 <li{{ item.attributes.addClass(item_classes) }}>
 {{ link('new log out' text, item.url) }}
{% else %} {# when there is no match with the previous conditions #}
  <li{{ item.attributes.addClass(item_classes) }}>
  {{ link(item.title, item.url) }}
{% endif %}

```

Be sure to put your conditions before the trailing `</li>`
> 1 votes

---
Tags: 8
---


# Question
Title: How to resolve the Composer related error shown using the Drush DL command?
I am working on MAMP and I have already installed a Drupal 7 site in my local machine ( not using Drush or Composer ). Then I have installed Composer and Drush ( Installing Drush on MAMP ). Now my Drupal site is under `htdocs` folder and it's working. If I run "drush" from htdocs via the command line, then it's shown a bunch of help command list.

But if I am trying to install any module using `drush dl Module_Name` then it gives me an error like so:

> \[error\] dl has been deprecated. Please build your site using Composer. Add new projects with composer require drupal/\[project-name\]. Use https://www.drupal.org/project/composer\_generate to build a composer.json which represents the the enabled modules on your site.

Can anyone tell me what the problem is? Do I need to install a fresh Drupal 7 site via Composer?

# Answer
> 2 votes
using composer is rather for Drupal 8 than Drupal 7 You could remove your version:

```
composer global remove drush/drush

```

and install an older one

```
composer global require drush/drush:8.*

```

---
Tags: drush, composer
---


# Question
Title: Cache problem on entity view mode teaser
I'm using two slightly different versions of a teaser of a node on two different pages. It's the same fields used for both, but different HTML around each field.

In both cases, I get the renderable array of my node this way :

```
$view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
$vars['renderable_node'] = $view_builder->view($referenced_node, 'teaser');

```

What I would like to have :

* Page Node 1
* Node 3 teaser version 1
* Page Node 2
* Node 3 teaser version 2

The problem is when I flush caches, the cache is set for the first time rendering the teaser of my node, but on my other page it render the same version.

Here is what I have then :

* Page Node 1
* Node 3 teaser version 1
* Page Node 2
* Node 3 teaser **version 1**

I looked into `['#cache']['max-age']` but I don't really want to set it to 0 because it's not appropriate for obvious performance reasons.

I see that there is also `['#cache']['keys']`, `['#cache']['context']` and `['#cache']['tags']` but not sure what to do.

# Answer
I ran into the same problem recently. Adding a key to the `['#cache']['keys']` array as unique id solved my cache problem. For your case it should be like this :

```
$view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
$vars['renderable_node'] = $view_builder->view($referenced_node, 'teaser');
$vars['renderable_node']['#cache']['keys'][] = "page_1";

```

On your second call to the teaser node then it should be like this :

```
$view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
$vars['renderable_node'] = $view_builder->view($referenced_node, 'teaser');
$vars['renderable_node']['#cache']['keys'][] = "page_2";

```
> 1 votes

---
Tags: 8, entities, caching
---


# Question
Title: How to change autocomplete_route_parameters value on change of select option?
How to change autocomplete\_route\_parameters value on change of select option?

I have a form element and inside autocomplete\_route\_parameters, I want to change $langcode value when I select any language from select list.

```
$form['node_items'] = array(
            '#type' => 'textfield',
            '#autocomplete_route_name' => 'autocomplete_node_search.autocomplete',
            '#autocomplete_route_parameters' => array('skip_node_id_string' => $skip_node_id_string, 'langcode' => $langcode),

          );

```

So if I choose language french from select list, $langcode should become = 'fr' via ajax.

# Answer
I have used below example to do that.

https://api.drupal.org/api/examples/ajax\_example%21ajax\_example.module/function/ajax\_example\_dependent\_dropdown/7.x-1.x

Customized it as listed below.

```
$form_state_values = $form_state->getValues();
if (!empty($form_state_values['language'])) {
  // write your logic here to prepare $skip_node_id_string & $langcode
}
$form['first'] = [
 '#type' => 'textfield',
 '#title' => $this->t('first'),
 '#autocomplete_route_name' => 'autocomplete_node_search.autocomplete',
 '#autocomplete_route_parameters' =>
 array('skip_node_id_string' =>$skip_node_id_string,
 'langcode' => $langcode),
 '#prefix' => '<div id="change-lang-wrap">',
 '#suffix' => '</div>',
];
$form['language'] = [
 '#type' => 'select',
 '#title' => $this->t('language'),
 '#options' => ['someval'],
 '#ajax' => [
  'callback' => [$this, 'changeLanguage'],
  'event' => 'change',
  'wrapper' => 'change-lang-wrap',
 ],
];
// Ajax callback.
public function changeLanguage(array &$form, FormStateInterface $form_state) {
 return $form['first'];
}

```

Hope this will fix your issue.

Tried below links, but no luck.

https://www.drupal.org/node/1135288
> 0 votes

---
Tags: 8, routes
---


# Question
Title: Custom field widget form - Multiple values
I've create a custom field form widget for an entity reference field. When only one value is allowed it shows a (filtered) select list, but I want to allow user to assign multiple reference values to that field.

In my use case I want it to be shown as checkboxes when multiple values are allowed, but by default it shows my checkboxes in a 'add-another' fieldset.

How can this be accomplished?

Below some code, $type is now a field setting and is manually set.

```
// Construct element
$widget = $element;
$widget['#delta'] = $delta;
$type = $settings['option_limit_type'];

... extra logic ...

switch ($type) {
      case 'select':
        $widget += array(
          '#type' => 'select',
          '#prefix' => '<div id="' . $settings[$element['#field_name']]['ajax_wrapper'] . '">',
          '#suffix' => '</div>',
          '#options' => $options,
          '#delta' => $delta,
          '#element_validate' => array('_entityreference_hierachy_option_limit_validate'),
          '#default_value' =>  $saved_target_id,
        );
        break;
      case 'checkboxes':
        $widget += array(
          '#type' => 'checkboxes',
          '#prefix' => '<div id="' . $settings[$element['#field_name']]['ajax_wrapper'] . '">',
          '#suffix' => '</div>',
          '#options' => $options,
          '#delta' => $delta,
          '#element_validate' => array('_entityreference_hierachy_option_limit_validate'),
          '#default_value' =>  $saved_target_id,
        );
        break;
    }
return $widget;

```

# Answer
> 0 votes
You can use drupal form api attributes like

---

```
 case 'select':
        $widget += array(
          '#type' => 'select',
          '#prefix' => '<div id="' . $settings[$element['#field_name']]['ajax_wrapper'] . '">',
          '#suffix' => '</div>',
          '#options' => $options,
          '#delta' => $delta,
          '#element_validate' => array('_entityreference_hierachy_option_limit_validate'),
          '#default_value' =>  $saved_target_id,
          '#multiple' => $multiple,
          '#size' => $multiple ? min(12,count($options)) : 0,
        );
        break;

```

---

https://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7#multiple

# Answer
> 0 votes
In hook\_field\_widget\_info() use 'FIELD\_BEHAVIOR\_CUSTOM' like this:

```
 'field_my_checkboxes' => array(
  'label' => t('Let the user select from a set of checkboxes.'),
  'field types' => array('field_myfield'),
  'behaviors' => array(
    'multiple values' => FIELD_BEHAVIOR_CUSTOM,
  ),

```

In this case 'Add another' link and fieldset won't be shown but you need to handle user's input manually. Example: https://www.drupal.org/node/1464770

---
Tags: 7, entities
---


title: Execute complex SQL queries

text:
# Question
Title: Execute complex SQL queries
I need to execute these SQL instructions.

```
CREATE TABLE superstatistics_counter LIKE node_counter;
INSERT superstatistics_counter SELECT * FROM node_counter;

```

When I run the query, it runs. I expect the node\_counter table to get a big table with about 100000 rows. This is what I have tried:

1. With `hook_schema()` I have created the superstatistics\_counter table
2. With this code I tried to copy data from the node\_counter table

```
$sql = "SELECT * FROM `node_counter`";
$data = db_query($sql)->fetchAll();
foreach ($data as $dataObject) {
  $dataArray = array($dataObject->nid, $dataObject->totalcount, $dataObject->daycount, $dataObject->timestamp);
  $query = \Drupal::database()->insert('superstatistics_counter');
  $query->fields([
    'nid',
    'totalcount',
    'daycount',
    'timestamp'
  ]);
  $query->values($dataArray);
  $query->execute();
}

```

It caused the following error:

> Maximum execution time of 120 seconds exceeded

So it is very slow.

When I executed it in phpMyAdmin, it output the following.

> MySQL returned an empty result set (i.e. zero rows). (Query took 0.1401 seconds.)
> `CREATE TABLE superstatistics_counter LIKE node_counter`

> 100000 rows inserted. (Query took 0.9567 seconds.)
> INSERT superstatistics\_counter SELECT * FROM node\_counter

Is there a way to just execute this query in Drupal, without using `db_query()` and `\Drupal::database()->insert()`? Can it be done on MySQL side?

# Answer
> 0 votes
The `db_query` function isn't just for select queries, it will execute anything.

Just use that instead of the loop, the performance will be miles better:

```
db_query('INSERT INTO superstatistics_counter SELECT * FROM node_counter');

```

---
Tags: database
---


# Question
Title: How do I properly work with two or more buttons having the same name?
I have a form with custom design, tabs and buttons with the same name. That is, buttons placed in different tabs and have the name "More ..."

However, each button has different ajax-callback function.

```
   $form['btn_services_geo_add_more_wrapper']['btn_services_geo_add_more'] = [
        '#type' => 'button',
        '#value' =>  $this->t('More ...'),
        '#ajax' => [
            'callback' => [$this, 'servicesGeoAddMore'],
            'event' => 'mouseup',
            'progress' => [
                'type' => 'none',
            ]
        ]
    ];

    $form['btn_services_by_place_add_more_wrapper']['btn_services_by_place_add_more'] = [
        '#type' => 'button',
        '#value' =>  $this->t('More ...'),
        '#ajax' => [
            'callback' => [$this, 'servicesByPlaceAddMore'],
            'event' => 'mouseup',
            'progress' => [
                'type' => 'none',
            ]
        ]
    ];

```

When debugging I noticed that weird errors had been appeared. But when I changed the name of one of buttons to "More 1 ...", these errors ceased to occur.

Could you clarify me, how to work with several buttons having the same name ? I tried to set the id property, but it didn't help.

# Answer
You can't work with 2 buttons that have the same name and value, in submission it would be impossible to tell them apart.

You need to set a unique name for each button; that will allow Drupal to distinguish which one was clicked and should be actioned.

```
$form['btn_services_geo_add_more_wrapper']['btn_services_geo_add_more'] = [
  ...
  '#name' => 'more_1',
];

$form['btn_services_by_place_add_more_wrapper']['btn_services_by_place_add_more'] = [
  ...
  '#name' => 'more_2'
];

```
> 3 votes

# Answer
Try giving them unique name through #attribute instead of changing the #value.

```
    $form['btn_services_geo_add_more_wrapper']['btn_services_geo_add_more'] = [
        '#type' => 'button',
        '#value' =>  $this->t('More ...'),
        '#attributes' => array('name' => 'more1'),//
        '#ajax' => [
            'callback' => [$this, 'servicesGeoAddMore'],
            'event' => 'mouseup',
            'progress' => [
                'type' => 'none',
            ]
        ]
    ];

    $form['btn_services_by_place_add_more_wrapper']['btn_services_by_place_add_more'] = [
        '#type' => 'button',
        '#value' =>  $this->t('More ...'),
        '#attributes' => array('name' => 'more2'),
        '#ajax' => [
            'callback' => [$this, 'servicesByPlaceAddMore'],
            'event' => 'mouseup',
            'progress' => [
                'type' => 'none',
            ]
        ]
    ];

```
> 0 votes

---
Tags: forms, ajax
---


# Question
Title: How to add a image in your drupal.org bio?
Some www.drupal.org profiles like https://www.drupal.org/u/artofeclipse have a image in the Bio section like this:

So, I trying to achieve the same in my profile (https://www.drupal.org/u/adriancid) but with another image. The problem is that the site always says this:

But if you go to see the image it exists in drupal.org, but the site always says *Only local images are allowed*.

How can I add a picture in my drupal.org profile?

# Answer
I just did a similar experiment (followed by an undo ...), and tried adding this HTML code in the same "Bio" file:

```
<p><img src="/files/logo2104april_0.png" /><br />
<img src="/files/styles/grid-2/public/user-pictures/picture-1962106-1505315670.png" /><br />
Drupaler driven by Views/Flag/Rules/Message/Group.</p>

```

And guess what, it worked!

The bio you can currently see in my drupal.org profile is created using this HTML code:

```
<p><img src="/files/styles/grid-3/public/project-images/rules-140.png" /><br />
Drupaler driven by Views/Flag/Rules/Message/Group.</p>

```

So I *think* you should use an existing image that you know already exists on drupal.org (such as within `/files/` for both of my sample images).

Ps: note the special image I used from that pictures directory ... looks familiar?
> 2 votes

# Answer
Actually, the image you are trying to use doesn't exist. If you try to access it directly (https://www.drupal.org/files/issues/expert-back-end-development-Forcontu-badge.png), you will get a 404 error. The image used from the other account is https://www.drupal.org/files/logo2104april\_0.png, and it exists.
The markup used from that biography is the following one.

```
<img src="/files/logo2104april_0.png">
Web developer, Drupaler driven by passion, love to navigate new technologies and integrate them in Drupal.

```

In your biography, you should use the following markup, if you want to use the same image used from the other account.

```
<a href="https://www.forcontu.com/en/certificate?field_s_certificado_id_value=D8BD0341&field_s_certificado_codautentica_value=f2e44" title="See the Certification"><img src="/files/logo2104april_0.png" alt="Drupal Certification" title="Forcontu Expert Back-End Development" width="140" height="140"></a>

```

I take the image you see (https://www.drupal.org/misc/watchdog-error.png) is used as placeholder also in the case the referenced image is not found. The tooltip is clearly wrong in that case, but the input filter used from Drupal.org uses that tooltip even in the case the image cannot be found.

As side note, the images attached to a comment in an issue were once uploaded to the /files/issues directory, but nowadays they are uploaded to the /files directory.
> 2 votes

---
Tags: community-official-site
---


# Question
Title: How do I programmatically set up multiple default flags?
How do I programmatically set up multiple default flags?

The documentation shows how to create a single flag using `mymodule_flag_default_flags()`. If I need two or three default flags for my custom module, how could I achieve it?

# Answer
Figured it out. To have multiple default flags you simple do this:

```
function mymodule_flag_default_flags() {

$flags = array();

$flags[‘FLAG_NUMBER_1’] = array(
    'content_type' => 'node',
    'title' => '',
     // Rest of flag data
);

$flags[‘FLAG_NUMBER_2’] = array(
    'content_type' => 'node',
    'title' => '',
     // Rest of flag data
);

return $flags;

}

```

where `[‘FLAG_NUMBER’]` is the machine name for the flag.
> 0 votes

---
Tags: 7, flags
---


# Question
Title: How to specify Views page as parent for menu link?
I have a module with a menu link which I want to appear as a child of another link in the admin menu. The would-be-parent link is to a Views page if that matters.

This is the contents of mymodule.links.menu.yml:

```
mymodule.add_location:
  route_name: mymodule.add_form
  parent: views.branch_locations.page
  description: 'Add a foo.'
  title: Add new
  menu_name: admin

```

I got the `views.branch_locations.page` machine name for the desired parent link from `ViewsMenuLink::getDerivativeDefinitions()`, the class responsible for dynamically providing menu links for the Views module.

With the current setup the "Add new" item doesn't appear under "Branch Locations" in the admin menu. The `route_name` definitely exists, and no error is thrown when clearing cache or rebuilding menus, which suggests Drupal is accepting `views.branch_locations.page` as a valid parent link somewhere along the line.

But how do I get this item to show up in the menu, as a sub-item of the specified `parent`? I guess I could use the API to programatically create the link, although I haven't tried it so it might have the same problem, but I want this one in config.

Is the problem maybe that because the Views module declares its links dynamically, I need to do the same for that dynamically created parent to even be available?

# Answer
Views generates menu link id's with a prefix `views_view:` and the first page display normally has the id `page_1`, so the parent should be something like this:

```
  parent: views_view:views.branch_locations.page_1

```

There is no error thrown, if `parent:` doesn't match an existing menu link. It's ignored and the menu link appears in the top level of the menu.

It doesn't matter from which provider the menu links are from, all discovered menu links are treated equally in the menu tree table.
> 3 votes

---
Tags: views, 8, navigation
---


# Question
Title: How do I enable language without importing translations?
I need to enable many languages on a site. I don't want Drupal downloads translations, since only few forms and pages will be actually translated on the front-end so I'll handle that manually.

Is there a way to avoid translations are downloaded?

# Answer
`drush cset locale.settings translation.import_enabled 0` or any other method to disable that flag should do the trick.
> 4 votes

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


# Question
Title: Create duplicate registration form with extra fields
I have a site built using Drupal 7. The site has a registration form now. There is a new requirement to add a couple of new fields in the registration form and put it in a new page.

http://example.com/register is the existing registration form and user submitting this form will be registered. http://example.com/newpage is a new page with some content and registration form with two extra fields. When users submit this page, a new user account will be created along with saving the new fields to the user profile.

How can I implement this?

# Answer
Use the LoginToboggan module

> The LoginToboggan module offers several modifications of the Drupal login system in an external module by offering the following features and usability improvements:

1. Allow users to login using either their username OR their e-mail address.
2. Allow users to login immediately.
3. Provide a login form on Access Denied pages for non-logged-in (anonymous) users.
4. The module provides two login block options: One uses JavaScript to display the form within the block immediately upon clicking "log in". The other brings the user to a separate page, but returns the user to their original page upon login.
5. Customize the registration form with two e-mail fields to ensure accuracy.
6. Optionally redirect the user to a specific page when using the 'immediate login' feature.
7. Optionally redirect the user to a specific page upon validation of their e-mail address.
8. Optionally display a user message indicating a successful login.
9. Optionally combine both the login and registration form on one page.
10. Optionally have unvalidated users purged from the system at a pre-defined interval (please read the CAVEATS section of INSTALL.txt for important information on configuring this feature!).
11. Integrates with Rules module to do various tasks when a user validates via email validation process (see http://drupal.org/node/880904 for an example)

Demo is here http://doaproject.org/user/register
> 0 votes

# Answer
For this you can use either of the ways 1) You can create a new form in your **Custom module** as a block with all the mandatory and extra fields you required. Now assign this block to the page where you want to assign this.

2) Secondly alter the **register form block** in your theme's **template.php** or in **custom module**. You need to alter its submit function too so it will submit your extra values too.

Let me know for any more help.
> 0 votes

# Answer
for this you can use user-register.tpl.php. use hook\_theme function to register user-register tpl in template.php file of your theme. then using theme hook suggestions find the template of you new page. create that template and render user\_register form in that new tpl file ....
> 0 votes

# Answer
The base user form can be extended with fields. See admin/config/people/accounts/fields

```
Configuration > People > Account settings > Manage fields

```

Adding more complicated registration forms and mapping them to different pages is what the profile2 module does.

I've got a site with 'studios' and 'affiliates'. Install *profile2*. Then see admin/structure/profiles

```
Admin > Structure > Profile types

```

If I edit the profile type for 'studio' it has *Unique registration path* set and the path mapped to /studio/register. Affiliate has a different path and a different form.

A fully functional form builder is provided under 'manage fields'.

This site does also use 'login toboggan' to get people to fill out 'basic information' then redirect them to some content nodes once they are first registered.
> 0 votes

---
Tags: 7, forms, users
---


# Question
Title: Drupal 7 view to loop through store locations
I am needing to setup a view in Drupal 7 that loops through content entries with fields. The content listing page will display teasers of each entry item with only the store name, address, suburb and phone number displayed. When the store name is clicked, I want the resulting page to display all details about the store. Could someone provide me insight on how to get this setup. I have a single content item with multiple field collections that works in a similar way, but it does not provide the click through functionality. It can be viewed here: http://endlessfitness.co.nz/swim-spa-retailers.

# Answer
> 0 votes
For the view format instead of using teaser you can select fields. And then add those fields which you want to show. To make the titles clickable, when you will add the title field it will give an option to link it to the content. Here is the fields format option.

And here is the field which you will need to add. The screenshot will have different fields than yours because I don't know what fields are there in your content type.

And here is the option to link title. So when you will add title field you will get this popup

---
Tags: views, nodes, entities
---


# Question
Title: How do I use an HTML5 element for my field widget?
I have found lots of resources about using HTML5 elements in custom forms (via Form API or using elements module). What's the standard technique which implements HTML5 field widgets (e.g. for a node field)?

For example, I have an "integer" field on node type "article" for which i want to use an HTML5 "number" input type. The only widget available to Fields API for data type number\_integer is "textfield".

# Answer
Your question is not clear please explain what HTML5 element you want to add to the form field. If you want to add placeholder or any other element you can pass them in `#attributes`, like this:

`$form['name'] = array(
 '#type' => 'textfield',
 '#title' => t('First Name'),
 '#attributes' => array('placeholder' => 'First Name'),
);`
> 1 votes

---
Tags: 7, entities
---


# Question
Title: How to make Drupal Commerce send email notification to the author of products sold?
I use Drupal Commerce and the rules module to send email which works OK. But it doesn't send the email to author node of product.

Here is an export of my current rule:

```
{ "commerce_checkout_order_email" : {
    "LABEL" : "Send an order notification e-mail",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "4",
    "OWNER" : "rules",
    "TAGS" : [ "Commerce Checkout" ],
    "REQUIRES" : [ "rules", "mimemail", "commerce_checkout" ],
    "ON" : { "commerce_checkout_complete" : [] },
    "DO" : [
      { "mimemail" : {
          "USING" : {
            "key" : "emailrenzo",
            "to" : "[commerce-order:mail]",
            "from_name" : "Regalalo",
            "from_mail" : "info@regalalo.pe",
            "subject" : "Pedido # [commerce-order:order-number] en [site:name]",
            "body" : "\u003Cdiv\u003E\r\n\u003Cimg src=\u0022\/http:\/\/34.214.32.99\/sites\/default\/files\/logo-regalalo.png\u0022\u0022\u003E\r\n\u003C\/div\u003E\r\n\r\nHola [commerce-order:owner]!!\r\ngracias por realizar un pedido en [site:name], su n\u00famero de pedido es # [commerce-order:order-number].\r\n\r\nSi este es su primer pedido con nosotros, pronto recibir\u00e1 otro correo electr\u00f3nico con las instrucciones para acceder a nuestro sitio con su nombre de usuario y contrase\u00f1a. Puede ver su historial de pedidos en cualquier momento ingresando a nuestro sitio web:\r\n\r\n[site:login-url]\r\n\r\nPuede consultar el estado de su pedido en:\r\n\r\n\u003Ctable cellspacing=\u00220\u0022 cellpadding=\u002210\u0022 border=\u00221\u0022\u003E\u003Ctr\u003E\u003Ctd\u003E\u003Ctable cellspacing=\u00220\u0022 cellpadding=\u002210\u0022 border=\u00221\u0022\u003E\u003Ctr\u003E\u003Ctd\u003E[commerce-order:commerce_line_items]\u003C\/td\u003E\u003C\/tr\u003E\u003C\/table\u003E\u003C\/td\u003E\u003C\/tr\u003E\u003C\/table\u003E\r\n\r\n[commerce-order:customer-url]\r\n\r\nPor favor comun\u00edquese con nosotros si tiene alguna duda.\r\n\r\n\u00a1Gracias por comprar en nuestra plataforma! Vuelve a visitarnos aqu\u00ed: Regalalo.PE\r\nSi tienes alguna pregunta acerca de tu pedido, contacta la tienda del producto que tendr\u00e1 el agrado de atenderte. \r\nPara otra consulta de asistencia env\u00edanos un correo a \u003Ca href=\u0022mailto:info@regalalo.pe\u0022\u003E info@regalalo.pe\u003C\/a\u003E\r\n",
            "language" : [ "commerce-order:state" ]
          },
          "PROVIDE" : { "send_status" : { "send_status" : "Send status" } }
        }
      },
      { "mail" : {
          "to" : [ "commerce-order:owner:mail" ],
          "subject" : "Pedido # [commerce-order:order-number] en [site:name]",
          "message" : "Hola [commerce-order:owner]!!\r\nGracias por realizar un pedido en [site:name], su n\u00famero de pedido es # [commerce-order:order-number].\r\n\r\nSi este es su primer pedido con nosotros, pronto recibir\u00e1 otro correo electr\u00f3nico con las instrucciones para acceder a nuestro sitio con su nombre de usuario y contrase\u00f1a. Puede ver su historial de pedidos en cualquier momento ingresando a nuestro sitio web:\r\n\r\n[site:login-url]\r\n\r\nPuede consultar el estado de su pedido en:\r\n\r\n[commerce-order:commerce_line_items]\r\n\r\n[commerce-order:customer-url]\r\n\r\nPor favor comun\u00edquese con nosotros si tiene alguna duda.\r\n\r\n\u00a1Gracias por comprar en nuestra plataforma! Vuelve a visitarnos aqu\u00ed: Regalalo.PE\r\nSi tienes alguna pregunta acerca de tu pedido, contacta la tienda del producto que tendr\u00e1 el agrado de atenderte. \r\nPara otra consulta de asistencia env\u00edanos un correo a \u003Ca href=\u0022mailto:info@regalalo.pe\u0022\u003E info@regalalo.pe\u003C\/a\u003E",
          "language" : [ "commerce-order:state" ]
        }
      }
    ]
  }
}

```

This rule works with user customer but not sellerr or authors, what´s your recommendation?

# Answer
In short; you should loop over all commerce order line items, obtain the product owner and add it to a list. Then in a new loop, go through the created list to send all product owners a main.

First you need a rules component that checks if a provided line item contains a product field and pushes the author to a given list (enforcing uniqueness makes sure every product owner is only added once). You can import below code on the components tab:

```
{ "rules_product_on_line_item" : {
    "LABEL" : "get product owner from line item",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "line_item" : { "label" : "Line item", "type" : "commerce_line_item" },
      "owners" : { "label" : "Product owners", "type" : "list\u003Cuser\u003E" }
    },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "line-item" ], "field" : "commerce_product" } }
    ],
    "DO" : [
      { "list_add" : {
          "list" : [ "owners" ],
          "item" : [ "line-item:commerce-product:creator" ],
          "unique" : "1"
        }
      }
    ]
  }
}

```

Now for the main rule, create a new variable of type `list of users`. This is where we will store all product owners in.

Create a loop over `commerce-order:commerce-line-items`. In this loop, use the component that was created above. This will fill the list of product owners.

Finally, loop over the list of product owners, and send each of them a mail. The complete rule would look something like this:

```
{ "rules_mail_all_product_owners" : {
    "LABEL" : "Mail all product owners on an order",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "5",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "mimemail", "commerce_checkout" ],
    "ON" : { "commerce_checkout_complete" : [] },
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "list\u003Cuser\u003E" },
          "PROVIDE" : { "variable_added" : { "product_owner_list" : "Product owner list" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "component_rules_product_on_line_item" : { "line_item" : [ "list-item" ], "owners" : [ "product-owner-list" ] } }
          ]
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "product-owner-list" ] },
          "ITEM" : { "productowner" : "Current product owner" },
          "DO" : [
            { "mimemail" : {
                "key" : "mailkey",
                "to" : [ "productowner:mail" ],
                "from_mail" : [ "site:mail" ],
                "subject" : "",
                "body" : ""
              }
            }
          ]
        }
      }
    ]
  }
}

```
> 2 votes

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


# Question
Title: Is it possible to make a entity reference field translatable and keep content in existing translations?
In our current project we use entity reference fields widely. There is quite a lot of content that already has translations.

Now we would like to enable translations of some of these entity reference fields.

When I did so I noticed that only the original language version of the nodes keep the contents of the fields - the translations show up with an empty entity reference field.

Did I just stumble into yet another Drupal gotcha? I looked through Drupal 8's issue queue but could not find anything related.

# Answer
Normally you don't need to make the entity reference field translatable to translate the content. This is only necessary if you want to define for each language different target ids.

But this is a different issue. If you enable translation for a field the translated fields have not yet content. This is not specific to reference fields, it is the same for all field types. Only when you create new translations the field values are copied, so that the form is prefilled with the untranslated values. So if you change the field structure in this way and you want to start with all existing translations prefilled you may need an update script for the existing field data.
> 2 votes

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


title: General error when creating an account

text:
# Question
Title: General error when creating an account
I'm testing the creation of user accounts on the new website and I get a general database error after attempting to create an account. The error log shows:

> Sep 14 09:06:01 test drupal\_www\_example\_com: https://test.example.com|1505379961|php|97.120.1.69|https://test.example.com/user/register|https://test.example.com/user/register|0||PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry 'user-203409-0-0-und' for key 'PRIMARY': INSERT INTO {field\_data\_field\_name\_first} (entity\_type, entity\_id, revision\_id, bundle, delta, language, field\_name\_first\_value, field\_name\_first\_format) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4, :db\_insert\_placeholder\_5, :db\_insert\_placeholder\_6, :db\_insert\_placeholder\_7); Array#012(#012
> \[:db\_insert\_placeholder\_0\] =\> user#012
> \[:db\_insert\_placeholder\_1\] =\> 203409#012
> \[:db\_insert\_placeholder\_2\] =\> 203409#012
> \[:db\_insert\_placeholder\_3\] =\> user#012
> \[:db\_insert\_placeholder\_4\] =\> 0#012 \[:db\_insert\_placeholder\_5\] =\> und#012 \[:db\_insert\_placeholder\_6\] =\> betachristia556#012 \[:db\_insert\_placeholder\_7\] =\> #012)#012 in field\_sql\_storage\_field\_storage\_write() (line 514 of /var/www/html/example/docroot/modules/field/modules/field\_sql\_storage/field\_sql\_storage.module).

I looked in the user table and there is no user for the ID 203409.

# Answer
> 0 votes
The field\_data\_field\_name\_first field had some data stored in it for that user ID, apparently because it was migrated in at a later time than the user table or because I didn't drop the database before I imported new data. As a result, the system couldn't write to the database user table and field\_data\_field\_name\_first table. The solution was to do a fresh import of the user table and the first and last name custom fields.

This was on a test site.

---
Tags: 7, users
---


# Question
Title: Is it possible to alter the data passed into a Rule?
I have a bunch of Rules and some things require a bit more complex logic than usual. What I want to do is use a hook that runs when a particular rule fires, access the data that's passed in to it and manipulate it accordingly so when the rule executes it does it with the manipulated data. I looked through the Rules API and tried some of the function but none seem to have what I want. Is there such a function, or this there a better way?

A simple example: For a rule that sends an email, I want to hook in to it, check some stuff with code and then change the email address it sends to.

# Answer
> 0 votes
I think there are no hooks in rules by which you can achieve it. So you have 2 possible solutions. 1) In rules use the php code for action (Not recommended for security) 2) Use custom module to perform the action rather than using rules.

# Answer
> 0 votes
Instead of using built in actions you can write your own action. Custom Actions here you can find a good tutorial.

---
Tags: 7, rules
---


title: XML Sitemap for Multi-site

text:
# Question
Title: XML Sitemap for Multi-site
I have generated a XML sitemap for multi-site using a free online tool - https://www.xml-sitemaps.com. I have downloaded XML file for each site and placed sitemap.xml at the root (\src\sitemap.xml) for main site and for sub-sites placed at \src\sites\sub-site-name\sitemap.xml.

When I access the main site at www.main-site.com/sitemap.xml, I get the correct sitemap.xml but for sub-sites (www.sub-site.com/sitemap.xml), I am getting the sitemap of the main site every time. How can I access the sitemap.xml file for sub-sites at www.sub-site.com/sitemap.xml. I can access the sitemap.xml for sub-sites if I go to the path: www.sub-site.com/sites/sub-site.com/sitemap.xml.

# Answer
> 0 votes
I got proper sitemaps for each sub-site by using the code below:

Syntax: RewriteRule /?sitemap.xml %{DOCUMENT\_ROOT}/sitemaps/%{HTTP\_HOST}.xml \[L\] My way: RewriteRule ^sitemap.xml$ sitemap/%{HTTP\_HOST}.xml \[L\]

---
Tags: 8, xml-sitemap
---


title: Change page content

text:
# Question
Title: Change page content
I'm working on a website not made by me that is build with drupal 7. I have to change the content of 4 pages that contains some blocks. How can remove some block from only 4 pages?

# Answer
Log in with administrator credential and go to `admin/structure/block`. Here you can find all blocks which are available on your site. You can find configure button at the right-hand side of each block like below image.  Click on Configure, it will open a new page with visibility settings for the blocks. At the bottom of the page, you can find settings where you can define the visibility of the block.

If your block is visible on all pages then check the first radio button and in textarea enter the URL of those pages where you don't want to display the block.
> 1 votes

# Answer
You can use Visibility settings showing below screenshot. If your condition more complicated please enable php filter module . Then you can also see a php condition option there.
> 0 votes

# Answer
1. Go to **/admin/structure/block**
2. Hit the **configure** link for which the block you want to remove.
3. In the **visibility settings** choose "All pages except those listed" and enter URL's you don't want to this block.
4. Hit Save block
> 0 votes

---
Tags: 7, blocks
---


# Question
Title: What does "apachesolr_access_node_ignore = 1" mean?
What does `apachesolr_access_node_ignore => 1` mean?

Does it affect the search, when `apachesolr_access_node_ignore` is set to 1?

# Answer
> 2 votes
It doesn't affect search. Basically, `$node->apachesolr_access_node_ignore` is set to 1 in `hook_node_insert()` or `hook_node_update()` by the *Apache SOLR Access* module for ignoring node that is already index.

---
Tags: 7, search
---


# Question
Title: Changing generated html of a module. (Search API)
I need to change the generated html (twig) of the search API module ( https://www.drupal.org/project/search\_api ). The Module generates a form having 2 divs with input tag in each of them. I need it to be a form with one div having an input tag and an anchor tag!

---

**What the module generates (in short)**

```
<form>
 <div>
  <input>
 </div>
 <div>
  <input "submit-btn">
 </div>
</form>

```

---

**What I want it to be**

```
<form>
 <div>
  <input>
  <a "submit-btn"><img></a>
 </div>
</form>

```

---

So basically, I need to be able to change the submit button to an image so I can place by "position:absolute" at the end of the first input field.

The search API module doesn't have the templates folder or any .twig files than I can overwrite. AND if I do overwrite the base theme form twig files that are used by the module, I cannot do it so that it changes only for this module and it doesn't change all other forms.

I am using drupal 8 btw.

# Answer
> 0 votes
I finally got around to do this using the MYTHEME.THEME file, I used this function:

```
function nestle_theme_suggestions_input_alter(&$suggestions, array $variables) {
  $element = $variables['element'];
  if ($element['#id'] == 'edit-submit-search-content') {
    $suggestions[] = 'input__' . $element['#type'] . '__' . 'mainsearch';
  }
}

```

---

Basically, it gets the element by its ID then changes its twig suggestion to kinda force twig to ditch the normal method of choosing the twig template based on naming conventions, Instead, it gives it a twig template to use!

---
Tags: theming, 8
---


title: Sorting comments from newest to oldest

text:
# Question
Title: Sorting comments from newest to oldest
How should I configure Drupal 8 to sort comments from newest to oldest, similarly to what the *Comment Goodness* module does in Drupal 7?

# Answer
> 5 votes
As `CommentStorage::loadThread` adds `comment_filter` tag to its query, you may use `hook_query_TAG_alter` hook to change comments order:

```
/**
 * Implements hook_query_TAG_alter() for comment_filter tag.
 *
 * @see CommentStorage::loadThread().
 */
function mymodule_query_comment_filter_alter(Drupal\Core\Database\Query\AlterableInterface $query) {
  // Change comment order to DESC for 'comment' field.
  if ($query->getMetaData('field_name') == 'comment') {
    /** @var \Drupal\Core\Database\Query\SelectInterface $query */
    $order_by = &$query->getOrderBy();
    // 'c.cid' is for flat comment lists.
    if (isset($order_by['c.cid']) && $order_by['c.cid'] == 'ASC') {
      $order_by['c.cid'] = 'DESC';
    }
    // 'torder' is for threated comment lists.
    if (isset($order_by['torder']) && $order_by['torder'] == 'ASC') {
      $order_by['torder'] = 'DESC';
    }
  }
}

```

# Answer
> 4 votes
Assuming your comment field's machine name is **field\_comments**, put this code into a module to get descending comments. I was having trouble with threaded comments, but this works since it alters the query by the c.thread database column instead of just 'torder'

```
/**
 * Implements hook_query_TAG_alter() for comment_filter tag.
 *
 * @see CommentStorage::loadThread().
 */
function MYMODULE_query_comment_filter_alter(Drupal\Core\Database\Query\AlterableInterface $query) {

  // Change comment order to DESC for 'comment' field.
  if ($query->getMetaData('field_name') == 'field_comments') {

    $order_by = &$query->getOrderBy();
    $expressions = &$query->getExpressions();
    // Sorting for threaded comments.
    if (isset($order_by['torder']) && $order_by['torder'] == 'ASC') {
      // Get rid of the expressions that prepare the threads for ASC ordering.
      unset($expressions['torder']);
      unset($order_by['torder']);
      // Simply order by the thread field.
      $order_by['c.thread'] = 'DESC';
    }

  }

}

```

# Answer
> 2 votes
You could create a comments view and sort them there.

# Answer
> 1 votes
For Drupal 8 you can use the next module: Comments order.

Link: https://www.drupal.org/project/comments\_order

> This module provides to change comments order (sorting functionality) in Drupal 8. You can pick comment order (newest first or oldest first) per node type, editing your comment type field on the "Manage fields" tab (node type administration page).
>
> Not only in flat, but also in threaded display! If you use threaded display, you can pick how will able to sort children comments. Examples below.

# Answer
> 0 votes
core/modules/comment/src/CommentStorage.php line 302. I think the only way is hack the core! & only for FLAT module.

```
    if ($mode == CommentManagerInterface::COMMENT_MODE_FLAT) {
  $query->orderBy('c.cid', 'DESC');
}
else {
  // See comment above. Analysis reveals that this doesn't cost too
  // much. It scales much much better than having the whole comment
  // structure.
  $query->addExpression('SUBSTRING(c.thread, 1, (LENGTH(c.thread) - 1))', 'torder');
  $query->orderBy('torder', 'ASC');
}

```

---
Tags: 8, comments
---


# Question
Title: How to prevent granting Userpoints again after a user already passed a Quiz?
I'm using the Quiz and the User Points module.

After a user takes a quiz, the points are granted. But if the quiz is taken multiple times, the points are granted multiple times also. For example;

* points balance: 0
* after quiz (1st time), point balance: 10
* take the same quiz again, point balance becomes: 10+10=20

I don't want it to be cumulative. How can I prevent this?

# Answer
You might use the Rules module to take away the role which has the permission to take the quiz once the quiz has been completed.
> 0 votes

# Answer
Using the Rules module, as suggested in the prior answer, is indeed a way to answer this question. Especially now that there is the 7.x-5.x release of the Quiz module, which enables all sorts of Rules logic to be implemented for quizes. However, if you have many quizes, you'd also end up with *many* roles if you'd use the approach suggested in the prior answer.

Therefor, I suggest you rather use a combination of the Rules module with the Flag module. Here is a summary of how to do so:

* Use the Flag module to create a flag for tracking Passed Quizes.
* Use the Rules module to implement this logic: ***if*** the quiz node (to which this quiz result relates) is not yet flagged (by the flag that was created for it), and the quiz result is that it is at least equal to the *pass rate of that quiz*, ***then*** it is the very first time this user passed the quiz. At which time the quiz node gets flagged. From then on use a Rules Condition to check if the quiz node was flagged or not by the current user. And based on that Rules Condition, you decide to yes or no perform some Rules Action(s), e.g to grant points (but only 1 time).

For more details, refer to my answer to "How to check if user has passed the quiz already before granting user points?", which also includes an export of the configuration of the flag and the rule to get this to work.

PS: I'm assuming this question is about D7.
> 0 votes

---
Tags: userpoints, quiz
---


title: Wrong date field format in Chrome

text:
# Question
Title: Wrong date field format in Chrome
I am working on a form.

I have this date field:

```
$form['date'] = [
  '#type' => 'date',
  '#title' => $this->t('Date:'),
  '#attributes' => [
    'type' => 'date',
    'placeholder' => 'dd/mm/aaaa',
    'data-drupal-date-format' => ['d/m/Y'],
  ],
  '#date_date_format' => 'd/m/Y'
];

```

When I set the date to August 30, 2017 I get

**Firefox** (Excellent!):

**Chrome** (Wrong!):

How can I set the 'd/m/Y' format in Chrome?

# Answer
> 1 votes
In Drupal 8, the `date` form element uses the HTML5 date input format by default. Chrome is one of the browsers that support this. So, it looks like your browser is using US style dates.

Changing to

```
$form['date'] = [
  '#type' => 'date',
  '#title' => $this->t('Date:'),
  '#attributes' => [
    'type' => 'text', // <=== CHANGE THIS
    'placeholder' => 'dd/mm/aaaa',
    'data-drupal-date-format' => ['d/m/Y'],
  ],
  '#date_date_format' => 'd/m/Y'
];

```

should work, but I would recommend using a `datetime` element and configuring it for date-only inputs. You can also configure that to not use the HTML5 inputs.

# Answer
> 0 votes
I think there is a type error  `'#date_date_format' => 'd/m/Y'`  which should be  `'#date_format' => 'd/m/Y'`

---
Tags: 8, entities, datetime
---


# Question
Title: Multiple sites using the same domain with each site in a subfolder
I am looking to migrate our multisite Drupal install to AEGIR but what I can not find clarity on is setting up domains for each site. Our current multi-site structure sets up independent Drupal sites under a sub folder of the same domain. We would like to replicate this under AEGIR however it seems each site is unique & requires it's own personal domain and can not share the same domain the way we currently have it.

TL;DR Is it possible to use the same domain and setup multiple AEGIR sites up as a sub folder under the same domain?

# Answer
For that you need the 'Site subdirectories' module which is included in the main Aegir distribution.

You can find it on `admin/hosting` under the Experimental category.
> 1 votes

---
Tags: aegir
---


title: Calculating a shipping cost

text:
# Question
Title: Calculating a shipping cost
I am using the Commerce Shipping Rate Field to set a unique shipping rate per product.

However, I would like to use this value in calculating another shipping value/service (commerce\_shipping\_price x 0.5). I can't seam to work out how to pull this value/field into a Calculation Rule.

How do I create a calculation Rule of 50% of the Commerce Shipping Price?

# Answer
> 0 votes
The problem you're facing is that shipping rates are calculated at the order level while your field exists at the product level. You can loop over the line items on an order to inspect this field value and then make calculations to the price based on what you find, but what do you do when the field value is different for different products on an order?

In my opinion, this logic is going to get confusing quickly to try and reproduce in Rules. I would favor writing a custom Rules action that inspects and sorts the product data in code, adjusting the price directly via the API instead of through the Rules UI.

---
Tags: commerce
---