# Question
Title: Restrict creation of new taxonomy terms via node form through entity reference filed (autocomplete) for particular user role
I have Entity reference field (taxonomy terms ) in node form.

I have checked the option (***Create referenced entities if they don't already exist***) so that users can create new taxonomy terms in field of node form i.e.: on creation on node new terms creation is allowed.

Looks like below in Node Form:

But I want to alter this and make restricted to certain roles. So that user with particular role should not be able to create new terms and must select from existing node.

> My field is core/lib/Drupal/Core/Field/Plugin/Field/FieldWidget/EntityReferenceAutocompleteWidget.php

While going thorugh code it seems under :

```
[#selection_settings] => Array
                        (
                            [target_bundles] => Array
                                (
                                    [topic] => topic
                                )

                            [sort] => Array
                                (
                                    [field] => name
                                    [direction] => asc
                                )

                            [auto_create] => 1
                            [auto_create_bundle] =>
                            [match_operator] => CONTAINS
                        )

```

***\[auto\_create\] =\> 1*** I tried to alter this by adding contain of user role in node form alter, but not its not working the value get changed.

Please suggest !

**Update :** **Please see @ssibal**

```
    drupal config-list field.field.node.link.field_topic2
 field.field.node.link.field_topic2
 uuid: f3c818dd-b5cd-4a73-af88-c20c1d0e24c3
 langcode: en
 status: true
 dependencies:
   config:
     - field.storage.node.field_topic2
     - node.type.link
     - taxonomy.vocabulary.topic
 id: node.link.field_topic2
 field_name: field_topic2
 entity_type: node
 bundle: link
 label: Topic
 description: "Sätt flera olika ämnen, separera dem med kommatecken och inled med stor bokstav.\r\n<br>\r\nExempel: SEB, Fraktionella reserver, Svågerkapitalism"
 required: true
 translatable: false
 default_value: {  }
 default_value_callback: ''
 settings:
   handler: 'default:taxonomy_term'
   handler_settings:
     target_bundles:
       topic: topic
     sort:
       field: name
       direction: asc
     auto_create: true
     auto_create_bundle: ''
 field_type: entity_reference

```

# Answer
There are multiple ways to achieve this, but I think the most clean is: Config Override.

I suggest to read the whole to understand it, but only this part is needed for you: **Providing overrides from modules**

You need then only find the configuration you want to override in runtime, and do it based on the current user role.

The field config pattern you are looking for is the following: **field.field.entity\_type.bundle.field\_name**

The *auto\_create* is under '*settings/handler\_settings*'.

**HOW TO FIND AND EXAMINE THE CONFIGS YOU NEED**

Configs are also entities. They can be feetched with EntityTypeManager. To see what type of entities you have in the system you have the "getDefinitions()" method. Then all you have to do, is to find the right storage (`getStorage($config_entity_type)`), and then load it by ID. Printing it out with kint, will give you a nice overview how the entity looks like, and how the settings are stored.

You can also "drush cex" your configuration. In this case configuration files will be created. The same scheme can be also found here. It gives also a good overview.
> 1 votes

# Answer
I am able to solve it by 2 methods :

***First*** : http://www.drupalcontrib.org/api/drupal/drupal%21core%21modules%21field%21field.api.php/function/hook\_field\_widget\_WIDGET\_TYPE\_form\_alter/8

```
function my_module_field_widget_form_alter(&$element, &$form_state, $context) {

if ($element['target_id']['#type'] == 'entity_autocomplete' && $element['target_id']['#target_type'] == 'taxonomy_term' && !empty($element['target_id']['#selection_settings']['target_bundles']['topic'])) {

$current_user = \Drupal::currentUser();
$roles = $current_user->getRoles();

    if(!in_array(ROLE_ADMIN, $roles)){
      if (!in_array('my_role', $roles) || in_array('anonymous', $roles)) {
        unset($element['target_id']['#autocreate']);
      }
    }
  }
}

```

***Second***

By creating my own widget simialr to Autocomplete tag style and overriding formElement in that to remove auto\_create fields support based on user role.

***Third:***

```
As suggested by @ssibal [Config Override.][1] (but problem in this )

$current_user = \Drupal::currentUser();
    $roles = $current_user->getRoles();

    if (!in_array('my_role', $roles)) {
        $overrides = $overrides + [
            'field.field.node.link.field_topic2' => [
              'settings' => ['handler_settings' => ['auto_create' => 0 ]],
            ],
          ];
     }

        return $overrides;

```
> 0 votes

---
Tags: 8, entities
---


# Question
Title: How to create a test configuration that can called in a test class?
I am attempting to write a unit test by extending UnitTestCase. Below is how my code works, but I need a way to create a test (or mock) configuration that can be used to satisfy the testing.

How can I accomplish this?

To keep question short i am only adding pertinent code. Current issue is that my test cases are failing because the configuration is not valid.

Error message:

> Drupal\Core\DependencyInjection\ContainerNotInitializedException: \Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container.

mymodule/src/plugin/mymodule\_field/provider/MyClass.php

```
class MyClass extends ProviderPluginBase {
  /**
   * {@inheritdoc}
   */
  public static function someFunction($input) {
    // Get the config.
    $config = \Drupal::config('mymodule.settings');
    $test_value = $config->get('test');

    if (!empty($test_value)) {
      /* process $test value */
      return True;
    }
    elseif (empty($test_value)) {
      /* do something else */
      return false;
    }
  }
}

```

mymodule/test/src/Unit/MyModuleValueTest.php

```
class MyModuleValueTest extends UnitTestCase {
  public function testIsEmpty($value, $expected) {
    /* I am stuck here on how to get the config */
    $this->assertEquals($expected, MyClass::someFunction($value));
  }
}

```

# Answer
> 2 votes
You are missing a couple of basic ideas of unit testing. I try to show them to you:

**What is a unit?**

Unit is most cases (95%+) a single class. This unit has some dependencies, using them and adding some extra logic to the whole.

In a unit test you only want to test the logic you provide in your class, but you want to make the dependencies as black boxes. A change to the implementation of the dependencies should NEVER make any difference to your unit test. Only their interfaces what matters.

**Clear Dependencies**

One of the dependency injection main role is to make your class testable. By injecting all the dependencies through the constructor you not just giving a nice list what services you class is relying on, but also make it easy to test.

Static methods should not be harder to test than object methods but they have a big drawback: you can't handle calling another static method inside them. Here is a nice explanation:

> Unit-Testing needs seams, seams is where we prevent the execution of normal code path and is how we achieve isolation of the class under test. Seams work through polymorphism, we override/implement class/interface and then wire the class under test differently in order to take control of the execution flow. With static methods there is nothing to override. Yes, static methods are easy to call, but if the static method calls another static method there is no way to override the called method dependency.

**About your case**

Either you need to eliminate the dependency by providing the value you need via argument, or you will have to give up unit testing on this one. You still can write a kernel test tho. That will be of course slower, but you can also have a wider scope of functionality / integration to be tested.

---
Tags: 8, configuration, testing
---


title: How to list all available entity types?

text:
# Question
Title: How to list all available entity types?
How to list all available entity types in Drupal using drush?

Related:

# Answer
### Drupal 7

```
drush eval "print_r(array_keys(entity_get_info()));"

```

### Drupal 8

```
drush eval "print_r(array_keys(\Drupal::entityTypeManager()->getDefinitions()));"

```

as per Jason suggestion,

or:

```
drush eval "print_r(array_keys(\Drupal::entityManager()->getDefinitions()));"

```

as per @RaisinBranCrunch suggestion. Note `\Drupal::entityManager()` is being deprecated in 8.x.
> 49 votes

# Answer
### Drupal 8

Use the drupal console command:

```
drupal debug:entity

```

or (short hand):

```
drupal de

```

This will produce a concise list of entities available in *your* instance.
> 15 votes

# Answer
You can create a drush command named `entities-list`. Create a module, put inside a file named `drush_entity.drush.inc` and paste this code:

```
<?php
/**
 * @file
 * Drush commands related to Entities.
 */

/**
* Implements hook_drush_command().
*/
function drush_entity_drush_command() {
  $items['entities-list'] = array(
    'description' => dt("Show a list of available entities."),
    'aliases' => array('el'),
  );
  return $items;
}

/**
 * Callback for the content-type-list command.
 */
function drush_drush_entity_entities_list() {
  $entities = array_keys(entity_get_info());
  sort($entities);

  drush_print(dt("Machine name"));
  drush_print(implode("\r\n", $entities));
}

```

Install the module, run `drush cc drush` to clear the drush cache and use the command like this:

```
drush el

```

or

```
drush entities-list

```

If you want add another alias to the command add elements to the aliases array like this:

```
'aliases' => array('el', 'another'),

```

And you can use this commands:

```
drush el
drush entities-list
drush another

```

Always the output will be:

```
Machine name:
entity 1
entity 2
entity...
entity n

```

**EDIT:**

There is another solution using the Drush Entity module:

```
drush entity-type-read

```
> 5 votes

---
Tags: drush, entities
---


title: error message when installing drupal 8

text:
# Question
Title: error message when installing drupal 8
When I was installing Drupal 8 (Macos, nginx, php7.0, mysql5.6), the following error occurred, Can someone help me?

```
An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /core/install.php?langcode=zh-
hans&profile=standard&continue=1&id=1&op=do_nojs&op=do
StatusText: OK
ResponseText:
Warning:  Declaration of
Drupal\Core\DependencyInjection\ContainerBuilder::callMethod($service,
$call) should be compatible with Symfony\Component\DependencyInjection\ContainerBuilder::callMethod($service, $call, SplObjectStorage $inlinedDefinitions) in /Users/xile/code/drupal/core/lib/Drupal/Core/DependencyInjection/ContainerBuilder.php on line 22
Drupal\Core\Config\UnmetDependenciesException: Configuration objects (block.block.bartik_help, block.block.bartik_search,
block.block.seven_help, contact.form.feedback,
core.entity_form_display.node.article.default,
core.entity_form_display.node.page.default,
core.entity_form_display.user.user.default,
core.entity_view_display.node.article.default,
core.entity_view_display.node.article.teaser,
core.entity_view_display.user.user.compact,
core.entity_view_display.user.user.default,
field.field.node.article.field_image,
field.field.user.user.user_picture, field.storage.node.field_image,
field.storage.node.field_tags, field.storage.user.user_picture,
rdf.mapping.comment.comment, rdf.mapping.node.article,
rdf.mapping.node.page, rdf.mapping.taxonomy_term.tags,
taxonomy.vocabulary.tags) provided by standard have unmet dependencies in Drupal\Core\Config\UnmetDependenciesException::create()(line 89 of /Users/xile/code/drupal/core/lib/Drupal/Core/Config/UnmetDependenciesException.php).

```

# Answer
> 1 votes
Install drupal console and then try to install the site using drupal console

https://drupalconsole.com/articles/how-to-install-drupal-console

```
drupal si

```

---
Tags: debugging
---


# Question
Title: How do I identify the version of Bootstrap?
There is a general solution on How do I identify the Bootstrap version? but I found it's not useful for Drupal, as I couldn't find the `bootstrap.css` file.

I think I found a bug in it. I want to compare the Bootstrap version against the current one and see if it was already fixed.

How can I check the Bootstrap library version inside a Bootstrap theme?

# Answer
If you have installed **bootstrap** and enabled it in your themes, you can find the settings in **yoursite.com/admin/appearance/settings/bootstrap**.

If you are using CDN, in Bootstrap **Settings -\> advance -\>BootstrapCDN version** and the available version in the drop down; or you can go to http://bootstrapcdn.com/ and find the CDN url of the library available in that.

When you use CDN, you can view your CSS or JavaScript file from the CDN server directly.
> 0 votes

# Answer
If no CDN is used, it means the bootstrap.css file is served from your server.

So you can look in your theme's folder possible locations.

* THEMENAME/includes/bootstrap/css/bootstrap.css
* THEMENAME/bootstrap/css/bootstrap.css

If CSS compression is not enabled on *Configuration \> development \> performance \> Aggregate CSS files*, you can just right click on a page and view the page source to search for *bootstrap.css*, open the file (usually clicking on it). The first few lines will give you version number. You can probably inspect the *bootstrap.js* file included to get the used version.

If compression is enabled, you might be able to find the version from the corresponding *bootstrap.js* file. Right click and view the page source. At the bottom of the file, you will see the .js file that includes ALL the needed .js files.

```
<script src="/sites/default/files/js/js_bl7kzDdD0bZPEYqsSIW0zHWL86ZfVbExhnLkjlCOMUM.js"></script>

```

Open it (clicking on it) and search for *bootstrap*.
> 0 votes

---
Tags: bootstrap-theme
---


# Question
Title: Hide/Remove core simpleTests in Drupal 7
I would like to remove the core tests that show up when I activate the Testing (simpletest) module. I have created my own tests for custom modules and I would like those to be the only testing options available to the user. How can I do this?

# Answer
You can implement `hook_simpletest_alter`, e.g.

```
function hook_simpletest_alter(&$groups) {
  // An alternative session handler module would not want to run the original
  // Session HTTPS handling test because it checks the sessions table in the
  // database.
  unset($groups['Session']['testHttpsSession']);
}

```
> 1 votes

---
Tags: 7, testing
---


title: Search and replace text in Drupal nodes

text:
# Question
Title: Search and replace text in Drupal nodes
A client has recently been acquired by a new group and has requested that I do a search and replace for their name (for example *Foo Housing Trust Group* and *Foo Housing Trust*) and replace it with their new name (for example *New Group*).

Answers for How to fix millions of Alt Text are missing on body content? suggest to use the Search and Replace Scanner module.

Would using that module better than running a database query?

# Answer
A possible alternative to achieve what you're trying to do, is to use a combination of these (commonly used) modules: Rules, Views and VBO.

With these modules in place, you could implement (for each of the fields that your question is related to) a variation of the solution described in my answer to "How to bulk update select list fields?", i.e.:

* Create a Rules Component with a Rules Condition to checks if the field contains the string you're interested in (probably using a "text comparison" with a "regular expression" to find all variations).
* Create a VBO enabled view of all nodes to be checked, whereas you'll use the Rules Component as your custom VBO action.

Repeat the above for each field (simply by adapting your Rules Component for each of these fields).

PS: I'm assuming this question is above D7 ...

***Done ...***
> 0 votes

---
Tags: 8, nodes
---


# Question
Title: how to make a filter on a view be on the result of a select query
My content has a field called release year . I want to be able to make a searchable view which will show only the unique years in this release date as options as a select . I don't want to hard code the years or have the user have to type in the year. How can I do this in a view?

# Answer
I'm pretty sure Drupal 8 does this out of the box when you expose the field as a view filter. The drupal 8 documentation for Views and it's Filters is clear on how to set this up and I believe a Select list is possible with if your field is an integer or a date limited to a Year component.

https://www.drupal.org/docs/8/core/modules/views/expose-a-filter-to-site-visitors
> 0 votes

---
Tags: views, 8
---


# Question
Title: Use Tokens and/or Replacement Patterns in Shortcodes
Looking for a way to add a token/replacement pattern into shortcode.

For example, creating a button where different text and link is required depending on other factors - something like the following:

\[button link="mysite/\[url replacement pattern\]" text="\[label replacement pattern\]"\]\[/button\]

The main reason I need to do this is that I'm using view field views and want to replace an empty field with a custom button, contained in the 'sub view' when the view is empty, which needs to be different depending on what should be in the 'sub view' - I'm using shortcodes in with Global: Text Area in the No Results Behaviour (if that makes sense)

Unless, of course, anyone knows another way to achieve the same result.

# Answer
> 0 votes
Ok, seems there are some limited ways to do this, using available replacement patterns that are not contained within square brackets. i.e. **%1** and **!1**, but not **\[replacement pattern\]**

Luck would have it, the replacements I need are the %1 and !1 values.

Still - would be great if anyone had any ideas how to use square bracketed replacement patterns in shortcodes without closing the shortcode (which is what appears to happen).

# Answer
> 0 votes
You can use Token filter which will add a Text format filter for token replacement. They you simply need to make sure the Token filter will run **before** the Shortcode one. More specifically:

1. Install Token filter
2. Go to `admin/config/content/formats`
3. Click "Configure" for the text format you are using.
4. Enable the Token replacement and the Shortcodes filters under "Enabled Filters"
5. Under "Filter processing order" make sure that Token replacement precedes Shortcodes

This will ensure that the tokens will be replaced before the shortcodes are parsed and will therefore work as expected.

## Bonus:

In case you are using any sort of Visual Shortcodes, adding `[` or `]` as content will most likely confuse the editor (in my case they were replaced with `|LS|` and `|RS|` respectively).

In that case you can set up a pre-render hook where you can change back those specific strings (or any other you might use to wrap tokens with), e.g. for blocks it could be something like that (for Drupal 8)

```
/**
 * Implements hook_entity_view_alter().
 */
function my_module_entity_view_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) {
  $build['#pre_render'][] = 'my_module_replace_token_wrappers';
}

function my_module_replace_token_wrappers(array $build) {
  // Get the body
  $body = &$build['content']['body'][0]['#text'];
  // Replace the values of |LS|/|RS| with [\] respectively
  $body = str_replace('|LS|', '[', $body);
  $body = str_replace('|RS|', ']', $body);
}

```

---
Tags: tokens
---


# Question
Title: Unable to run database updates via Drush - Call to undefined function batch_get()
Having some difficulty running database updates via drush after updating modules in the codebase. This is the error that is being reported:

Error: Call to undefined function batch\_get() in /root/.config/composer/vendor/drush/drush/commands/core/drupal/batch.inc on line 92 #0 /root/.config/composer/vendor/drush/drush/includes/batch.inc(98): \_drush\_batch\_command('11459')

This is only happening on our production environment, our staging environment is identical and works without issue.

We are able to run the updates via update.php; but we are planning to migrate to the new core media module in the coming days, and those updates bring the site down until database updates are run so update.php will not be an option.

The database is located on another server, but we have no problem connecting to that server via tools such as drush sql-cli.

We have also tracked down the 'undefined' method in question and verified it to be in existence.

Many thanks in advance for any help.

# Answer
Run your drush statement with the --debug flag, you will see something along the lines of:

Checking DB credentials yielded error: Unable to find a matching SQL \[debug\] Class. Drush cannot find your database connection details.

Try navigating to the actual sites folder e.g. /var/www/vhosts/EXAMPLE/website/sites/default and run the drush command from the site specific directory.
> 1 votes

---
Tags: 8, database, drush, updating
---


# Question
Title: How can I build a "visitor history" using Flag/Rules?
I need to build a history for visitors so they can see which pages they've visited (ideally filtered by type). To do this, it seems that the correct combo is to use Flag module and then Rules.

I'd anticipate that I'd create a new rule config where I'd ensure the content was of a certain type, ensure a flag existed, then automatically mark the flag each time the content of that type was visited. I'd also have to update the time if an 'already-flagged' content was visited again (ie. so it appears at the top of a 'history' list).

I've messed around with Rules in Drupal 8 and I didn't get far at all. I could obviously add a rule for 'node is viewed', and then condition of it being the right type. But then I got stuck.

I need to be able to do things like see if there's a flag available, see the current value of the flag for that user, automatically set/update the flag, etc. I couldn't figure out how to do any of this.

Help? :)

# Answer
> 0 votes
Honestly I gave up pretty quickly since it seemed unnecessarily complicated. I created a very basic module that handles the marking/unmarking via the Flag API. It has a single hook that looks like this:

```
function mymodule_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {

  //UPON VIEWING 'mytype' NODES
  if($entity->getType() == 'mytype'){

    //CREATE HISTORY FLAGS
    $uid = \Drupal::currentUser()->id(); //current user
    $flag_id = 'history'; //flag type is named history
    $flag_service = \Drupal::service('flag');
    $flag = $flag_service->getFlagById($flag_id);

    if($flag->isFlagged($entity) == '1'){
        //unflag then reflag to update date
        $flag_service->unflag($flag, $entity);
        $flag_service->flag($flag, $entity);
    } else {
        //flag it for the first time
        $flag_service->flag($flag, $entity);
 }
 }
}

```

---
Tags: 8, rules, flags
---


# Question
Title: Flag module not joining flagging with EntityFieldQuery?
I'm using `EntityFieldQuery` to pull nodes based on a flag created with the Flag module (3.2):

```
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'article')
    ->propertyCondition('status', 1)
    ->range(0, 25)
    ->addTag('flagging_flag_names')
    ->addMetaData('flag_name_value', 'my_flag_name');

```

I'm not seeing the flagging table being joined to the query (from the error being thrown):

```
Unknown column 'flagging.fid' in 'on clause':
SELECT node.nid AS entity_id, node.vid AS revision_id, node.type AS bundle, 'node' AS entity_type FROM node node INNER JOIN flag f ON flagging.fid = f.fid WHERE (node.status = 1) AND (node.type = 'article') AND (f.name = 'my_flag_name') LIMIT 25 OFFSET 0

```

Below is the `flag_query_flagging_flag_names_alter` from the flag module file:

```
function flag_query_flagging_flag_names_alter(QueryAlterableInterface $query) {
  // Get value and operator for bundle condition from meta data.
  $value = $query->getMetaData('flag_name_value');
  $operator = $query->getMetaData('flag_name_operator');
  // Join [flag] and [flagging] tables by [fid] and
  // apply bundle condition on [flag].[name] field.
  $query->join('flag', 'f', 'flagging.fid = f.fid');
  $query->condition('f.name', $value, $operator);
}

```

What am I missing in the query build to join the flagging table?

# Answer
> 4 votes
The `flagging` table is not available when querying for nodes using an EntityFieldQuery, that's why the `flagging.fid` column is missing in this query.

In order to get hold of flaged items, the flagging-entities need to be queried instead:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'flagging')
  ->entityCondition('bundle', 'name_of_some_flag');

```

Then use `entity_load('flagging', ...)` and obtain the `nid` from the `entity_id`-property of the flagging entities.

However keep in mind that it is impossible to sort / filter on properties of the target object (nodes in this case) because `EntityFieldQuery` does not support JOINs in Drupal 7.

I suggest to build a view instead of trying to battle the EFQ in this particular case.

# Answer
> 0 votes
To get all flagged entities on Drupal 8, plus a condition on the type (here on the type of Node) :

```
use Drupal\Core\Database\Database;

$connection = Database::getConnection();

$query = $connection->select('flagging', 'f');
$query->join('node_field_data', 'n', 'n.nid = f.entity_id');
$query->fields('f', ['entity_id', 'entity_type', 'flag_id', 'global'])
  ->fields('n', ['nid', 'type'])
  ->condition('f.flag_id', 'bookmark') // replace by flag machine name
  ->condition('n.type', 'article'); // replace by content type name

$data = $query->execute();
$results = $data->fetchAll(\PDO::FETCH_OBJ);

```

---
Tags: flags, database
---


# Question
Title: Call a custom module's function from template file
In the same context that this question, I want to add a link to a function in my custom module from a template file.

Something like this:

In my template file: `<a href="mymodule_my_function()" id="20">Action</a>`

In my custom module

`function my_function($id){
//update data base
}`

# Answer
a function doesn't have a url unless you set up a callback url for it first with hook\_menu. Then you can point your link to it and process the data. So in your case it'd look something roughly like that:

In your custom module:

```
function mymodule_menu() {
  $items['some_url/%'] = array(
    'page callback' => 'mymodule_myfunction',
    'page arguments' => array(
      1,
    ),
  );
  return $items;
}

function mymodule_myfunction($id) {
 // update database
}

```

Then in your template use l() as Kevin mentioned (you should adjust to fit your variables etc):

```
print l('Action', 'abc/20');

```

This is very simplified. You'd want to probably enable some access limitations on that new url (abc/%) etc and you can read more about that in the hook\_menu docs I linked to above.
> 2 votes

---
Tags: 7, theming, hooks
---


# Question
Title: View: Distinct list of all referenced entities
Basic setup: 3 content types

* **Festival**
* **Event**
* **Speaker**

**Event** has a entity 1-to-1 reference field containing a **Festival**.

**Event** also has a 1-to-many reference field containing **Speakers**.

How can I set up a View to list all of the Speakers taking part in a Festival? (A Speaker can take part in more than one Event).

# Answer
Create a view of **events** with relationship to the **speakers** and contextual filter to **festival**

For filtering duplicates you have to turn on aggregation as seen above and setup body `aggregation settings: group column: format`

The contexual settings for festival are

NOTE: To see preview for a festival put a festival node id in the `contextual filter` and press preview

Finally you can put the view block display on content region or any other region from `structure > block layout` and the block with relevant event/speakers will be present when you visit a festival page
> 3 votes

---
Tags: 8, views
---


# Question
Title: How do I get the translated title of a node?
I have a content type available in FR and in EN.

In `hook_node_presave()`, I would like to concatenate the French title and the English title in another field. (This is an "helper field" which contains concatenate strings to be used by a filter in a view.)

This is my code.

```
function mymodule_node_presave(Drupal\Core\Entity\EntityInterface $entity) {
  $entity_title1=$entity->getTitle(); //It is the French title if the saved node is the french node.
  $entity_title2= '?'; //HERE IS MY PROBLEM: how to get the title in the other language?
  $entity->my_helper_field->setValue("$entity_title1 $entity_title1");
}

```

How do I get the translated title of a node?

# Answer
> 19 votes
You should load the translated entity, and get the title from that.

```
$translated_entity = $entity->getTranslation('en');
$translated_title = $translated_entity->getTitle();

```

You can get the current entity language using `$entity->get('langcode')->value;`, and as @4k4 says, you should check that a translation exists using `$entity->hasTranslation($langcode);`.

# Answer
> 9 votes
The current language of the entity is not so important, because you can get the same language again. More important is to check if the entity has the translation so that you don't get an error:

```
 $title_en = $entity->hasTranslation('en') ? $entity->getTranslation('en')->getTitle() : '';
 $title_fr = $entity->hasTranslation('fr') ? $entity->getTranslation('fr')->getTitle() : '';

```

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


title: Subscriptions in Commerce Stripe

text:
# Question
Title: Subscriptions in Commerce Stripe
I use the Commerce Stripe module to make charges on my website, but I need to be able to subscribe through Stripe, and I have no idea how to do it. The charges I make and without problem but I would need someone to show me the way on how to change the charge to subscription through Commerce Stripe. Thank you.

# Answer
> 0 votes
You can not change existing charge to subscription. It is not a trivial task, but doable by using such modules as Commerce Recurring or Commerce License and Commerce License Billing.

---
Tags: commerce
---


# Question
Title: AJAX HTTP error 200 when using Views Bulk Operations on Files
I am attempting to use VBO's "Lock Files" operation to prevent some files without file usage records from being randomly deleted (it happens). I am open to alternate means of doing this as well as a solution to this specific problem.

VBO has never worked great. Particularly the options to "select all on this page" or "select all on all pages" almost never show up. Every once in a while it will but there seems to be no rhyme or reason there.

Whether I select multiple files or a single file from the view preview results, when I attempt to execute the "lock file" operation, on the "confirm" step, I get a js alert box pop up with this error:

> An AJAX HTTP error occurred HTTP Result Code: 200 Debugging information follows. Path: /admin/structure/views/ajax/preview/files\_check/default StatusText: ResponseText: window.NREUM||(NREUM={}),\__nr\_require=function(e,t,n){function r(n){if(!t\[n\]){var o=t\[n\]={exports:{}};e\[n\]\[0\].call(o.exports,function(t) {var o=e\[n\]\[1\]\[t\];return r(o||t)},0,0.exports)}return t\[n\].exports} if("function"==typeof\__nr\_require)return\__nr\_require;for(var o=0;o Performing Lock selected files on the selected items...

This does not appear to be the complete error, but since the error is in the alert box instead of the console there appears to be no way to access the full error.

After I clear the alert box I still have the confirm button and cancel link. When I click confirm I just get the error again. When I click cancel I return to my preview but now the "select all..." options are visible. All further attempts still generate the same error though.

This is the query output by my view

```
SELECT DISTINCT file_managed.fid AS fid, file_managed.timestamp AS file_managed_timestamp, file_managed.filename AS file_managed_filename, file_managed.uri AS file_managed_uri, file_usage.count AS file_usage_count
FROM
{file_managed} file_managed
LEFT JOIN {file_usage} file_usage ON file_managed.fid = file_usage.fid
ORDER BY file_usage_count ASC, file_managed_timestamp ASC
LIMIT 10 OFFSET 0

```

I have tried this by setting the advanced "Use Ajax" option to both yes and no with the same result.

Drupal (7) core and all modules are up to date.

I'd be happy to provide any additional information needed. Please advise.

# Answer
> 0 votes
200 means that a response was returned successfully, but the response is not something your code can work with, which is why you are getting the error. It looks like the response is returning a script, rather than whatever is expected (likely JSON).

---
Tags: 7, views
---


# Question
Title: How do I delete files attached with media entity?
**Background:**

drupal 8.4.2

custom media solution

**Issue**

I can not delete files permanently which created as media entity.

**Reproduce**

1. Created an image media entity.
2. `/admin/content/files` claims `status permanent` and `used in 2` places.
3. After deleting newly created media entity from UI `/admin/content/media`.
4. `/admin/content/files` says `status permanent` and `used in 1` places.

Even cron run after 6 hours (as described in file settings) file still exist on the server.

Is there any safest or best way to delete those unused file permanently?

# Answer
You have to delete old versions of entities (articles etc.) where you used the files for the files to get the "used in 0 places" under /admin/content/files. After that status should be changed to temporary with option make\_unused\_managed\_files\_temporary set to true.
> 1 votes

---
Tags: 8, media
---


# Question
Title: Connect to Salesforce using wsdl in Drupal 8
I am trying to connect to Salesforce (SF) with wsdl to pull data.

I can't use SF suite module or Salesforce rest client service.

In the D7 file, I have:

```
require_once ('soapclient/SforceEnterpriseClient.php');
require_once('soapclient/SforceHeaderOptions.php');
ini_set("soap.wsdl_cache_enabled", "0");

$sfdc = new SforceEnterpriseClient();
$SoapClient = $sfdc->createConnection($curPath.'/enterprise.wsdl');

```

It create the connections without any problems.

D7 References from here: https://developer.salesforce.com/page/PHP\_Toolkit\_11.0\_Getting\_Started and learned to how to use it from here: https://github.com/developerforce/Force.com-Toolkit-for-PHP/blob/master/soapclient/SforceEnterpriseClient.php

In the D8, I am trying to figure out how to connect to SF in the same way:

```
namespace Drupal\mymodule\Controller\Soapclient;
$sfdc = Soapclient::SforceEnterpriseClient();
$SoapClient = $sfdc->createConnection('../../includes/soapclient/enterprise.wsdl');

```

But got the SforceEnterpriseClient class not found error.

Stuck on it for a while, any help will be so much appreciated. Anybody knows how to connect to SF in the same way like this:https://github.com/developerforce/Force.com-Toolkit-for-PHP/blob/master/soapclient/SforceEnterpriseClient.php

# Answer
It seems the problem you are facing is due to the way you are referring the library; please refer the following question; they have explained how you should be using external libraries in Drupal 8 custom modules.
> 0 votes

---
Tags: 8
---


# Question
Title: Remove duplicate values in a column after join in drupal 7
I am using this db\_select query.

```
$query = db_select('taxonomy_index', 't1');
    $query->distinct();
    $query->join('node', 't2', 't1.nid = t2.nid');
    $query->join('taxonomy_term_data', 't3', 't3.tid = t1.tid');
    $query->fields('t1', array('tid'));
    $query->fields('t3', array('name'));
    $query->fields('t1', array('nid'));
    $query->groupBy('t1.nid');
    $query->condition('t2.type', 'article', '=');
    $query->condition('t3.vid', '2', '=');
    $query->orderBy('t2.created', 'DESC');
    $query->range(0, 20);
    $result = $query->execute()->fetchAll();
    print_r($result);

```

After running this query my output is

```
tid  name   nid
1    apple   200
5    orange  165
9    grapes  130
5    orange  106

```

My expecting output is

```
 tid  name   nid
    1    apple   200
    5    orange  165
    9    grapes  130

```

No need to repeat duplicate rows like 5 orange 106 again. How this can be possible?

# Answer
> 1 votes
Can you try with the result you are getting and avoid the duplicates using below codes.

```
 $used_tids = array();
 foreach ($result as $row) {
        if (!in_array($row->tid, $used_tids)) {
          $new_result[] = $row;
          $used_tids[] = $row->tid;
        }
      }
      // new filtered results after avoiding duplicates
      $results = $new_result;

```

# Answer
> 0 votes
Here there is no use of joining with node table. If you are getting the taxonomy grouped by tag name and to get the node count, then it make sense to JOIN the node table. Otherwise directly query the taxonomy table.

Ref: https://www.drupal.org/node/494026#comment-4126908

```
$vid = 3; //vocabulary id
$num_term = 20; //limit maximum terms

$query = "SELECT tid, name, count
FROM (
SELECT td.tid AS tid, name, COUNT(*) AS count
FROM {term_data} AS td
JOIN {term_node }AS tn ON td.tid = tn.tid
JOIN {node} AS n ON n.nid = tn.nid AND n.vid = tn.vid
WHERE td.vid = ". $vid ." AND n.status = 1
GROUP BY td.tid
ORDER BY count DESC
LIMIT ". $num_term . "
) AS t
ORDER BY name ASC";

$result = db_query($query);
while ($term = db_fetch_object($result)) {
if ($term->count > 0) {
  $items[]= l($term->name, "taxonomy/term/$term->tid") . ' (' . $term->count . ')';
}
}

```

# Answer
> 0 votes
If you are using Drupal 8 then you can overwrite result with your desired result using hook\_views\_pre\_render

```
    function HOOK_views_pre_render(\Drupal\views\ViewExecutable $view) {

      if ($view->id() == 'view_machine_name' && $view->current_display == 'display_id') { // page_1

        foreach ($view->result as $key => $value) {

                  //do your business logic here
              }

      }

    }

```

---
Tags: 7, taxonomy-terms, database
---


# Question
Title: What is the right way of installing Drush?
The http://docs.drush.org/en/master/install page states:

> Drush 9 only supports one install method. It requires that your Drupal 8 site be built with Composer and Drush be listed as a dependency.

and if you go to https://github.com/drupal-composer/drupal-project and follow the given steps, in particular run the `composer create-project drupal-composer/drupal-project:8.x-dev some-dir --stability dev --no-interaction` command, then:

1. You will have to create an empty directory (otherwise it will complain the given directory is not empty);
2. It will create Composer structure with Drupal 8 located in `web` sub-directory;
3. It will also create `vendor` sub-directory with lot's of other sub-directories as:

alchemy composer doctrine fabpot league phar-io sebastian theseer asm89 consolidation drupal grasmash masterminds phpdocumentor squizlabs twig autoload.php container-interop drupal-composer guzzlehttp mikey179 phpspec stack vlucas behat cweagans drush instaclick myclabs phpunit stecman webflo bin dflydev easyrdf jakub-onderka nikic psr symfony webmozart chi-teck dnoegel egulias jcalderonzumba paragonie psy symfony-cmf zendframework

Now with regard the new way of isntalling Drupal 8 I have two questions:

1. Previously we would install Drupal 8 in document root set by control panel. Different control panel have different document roots, ours default them in `/home/username/public_html`.

Now, with the new way of installing Drupal 8 we end up with document root located in `/home/username/some-dir/web`, which does not play nice with our control panel's defaults. So I wonder what is the best recommended practice here?

Creating symbolic links between the old and new document roots also have its issues. For example, if you switch to `/home/username/public_html` (which is a symbolic link to `/home/username/some-dir/web`) and run the `composer update` command then it will give:

```
No composer.json in current directory, do you want to use the one at /home/username/some-dir? [Y,n]?

```

and we would really like to avoid this kind of extra steps, but at the same time respecting our control panel's default settings.

Changing the default setting for document roots in control panel is also not a good option as there could be lot's of old and non-Drupal websites on servers, so the old document root must be kept.

2. Do we have to have Composer structure with lot's of sub-directories like ones in `vendor` in every website's home directory? Please note that in my test setup Composer is installed globally. But when you run the `composer create-project drupal-composer/drupal-project:8.x-dev some-dir --stability dev --no-interaction` command it creates all those directories within a website's home directory.

# Answer
You do not necessarily have to run `composer create-project drupal-composer/drupal-project:8.x-dev some-dir --stability dev --no-interaction` to create a new Drupal 8 site using the `drupal-project` composer package.

You can also just download the `composer.json` of that project and place it into your future Drupal 8 base folder. Then you can alter the installer paths within that `composer.json` to your liking. So if you prefer `public` over `web` as your Drupal root, then rename that part of the installer paths. You may also wish to alter the project name or other details of the `composer.json` file.

After your customization, you can then run `composer update` to generate an according `composer.lock` file. Assuming you did so on a local development environment, you can then use `composer install --no-dev` on your production system after uploading your composer and custom files/checking them out if you use a code versioning system.

Coming to the folder structure: It is advisable to keep the folder above the Drupal 8 root as base folder of your root package (project), location for the composer dependencies (`vendor` folder), Drush site settings, and auxillary files that should not be directly accessible from your web URLs (e.g. exported configuration files, private files, temporary files, Node.js packages, ...).

Therefore you should consider pointing your virtual hosts' root directories for example to `/home/username/public_html/web` (or `/home/username/public_html/public`, if you customized your `composer.json` like that) while using the regular root directories of your hosting panel `/home/username/public_html` as composer root package folder.

Depending on your hosting panel, you may have the ability to alter the vhost root directory by overriding the web server settings (e.g. defining a `DocumentRoot` for Apache, or a `root` for Nginx). How to do this depends heavily on your used hosting solution and is therefore off-topic in Drupal Answers.

And yes, you will have this folder structure on every of your projects. As every project may require a different version of dependencies, different modules (which may add dependencies with certain version restrictions to the vendor folder as well), binary tools for the shell, probably applied patches and so on. These dependencies and their version requirements are project specific, even when you use a global Composer installation.
> 3 votes

# Answer
> with the new way of installing Drupal 8 we end up with document root located in /home/username/some-dir/web, which does not play nice with our control panel's defaults. So I wonder what is the best recommended practice here?

Navigate to the directory, then run the composer command. Composer will install Drupal at the directory from which you run the command.

> Do we have to have Composer structure with lot's of sub-directories like ones in vendor in every website's home directory?

Each Drupal 8 (and likely 9+) will have its own /vendor directory.
> 0 votes

---
Tags: 8, drush, composer
---


# Question
Title: How can I call 2 functions in the same custom module?
In my template file I have 2 links like

```
if(mytest){
  print l(t('Action 1'), 'my_first_link/'.$id);
}else{
  print l(t('Action 2'), 'my_second_link/'.$id);
}

```

In my custom module I have

```
function myModule_menu() {
  $items = array();
  $items['my_first_link'] = array(
    'title' => 'First function',
    'page callback' => array('myModule_first_function'),
    'page arguments' => array(1,),
  );
  $items['disableproject'] = array(
    'title' => 'Second function',
    'page callback' => array('myModule_second_function'),
    'page arguments' => array(1,),
  );
  return $items;
}
function myModule_first_function($url_argument){
  print('url_argument = '.$url_argument);
}
function myModule_second_function($url_argument){
 print('url_argument = '.$url_argument);
}

```

My first link works fine but my second doesn't!

It gives me a 404 error!

How can I solve it?

Thank you

# Answer
You need to add 'access arguments' to your call:

```
$items['disableproject'] = array(
  'title' => 'Second function',
  'page callback' => array('myModule_second_function'),
  'page arguments' => array(1),
  'access arguments' => array('some permission'),
);

```

Or you can add a custom access callback:

```
$items['disableproject'] = array(
  'title' => 'Second function',
  'page callback' => array('myModule_second_function'),
  'page arguments' => array(1),
  'access callback' => 'some_access_callback_function',
);

```
> 3 votes

# Answer
You can also define the access arguments true, use this if you want this link to be accessible by anyone else use what Jaypan has suggested. BTW I believe that you have flushed your drupal cache after making changes to hook\_menu

```
$items['disableproject'] = array(
  'title' => 'Second function',
  'page callback' => array('myModule_second_function'),
  'page arguments' => array(1),
  'access arguments' => TRUE,
);

```
> 1 votes

---
Tags: 7, hooks
---


# Question
Title: How can I flag content programmatically?
The Flag module is still in development for Drupal 8, but it's working nice. However, I didn't find how to add a flag programmatically; the API documentation seems to speak of the Drupal 7 version.

How do I programmatically add a flag?

# Answer
Here's how to flag or unflag an entity programmatically, using the Flag service.

```
$flag_id = 'bookmark';

$flag_service = \Drupal::service('flag');
$flag = $flag_service->getFlagById($flag_id);

// Flag an entity with a specific flag.
$flag_service->flag($flag, $entity);

// Unflag an entity with a specific flag.
$flag_service->unflag($flag, $entity);

$flag->save();

```
> 14 votes

# Answer
Flag for a certain user you will have to do :

```
$account = \Drupal::currentUser(); // or load a specific user
$flag_service = \Drupal::service('flag');

$flag = $flag_service->getFlagById('bookmark'); // replace by flag machine name

// check if already flagged
$flagging = $flag_service->getFlagging($flag, $media, $account);
if (!$flagging) {
  $flag_service->flag($flag, $media, $account);
}
else {
  $flag_service->unflag($flag, $media, $account);
}

```
> 13 votes

---
Tags: 8, flags
---


title: Custom Checkout page

text:
# Question
Title: Custom Checkout page
I have made a form\_alter in template.php in my theme and I have created a custom page (page--checkout.tpl.php) to render my form. If I render the content as print render($page\['content'\]); everything is fine, but I want to print the cart content on the top of the page, and the customer\_profile\_billing and commerce\_payment below the cart contents in two seaprate columns. How can i call for these seperate panes in the page--checkout.tpl.php in order to show them the way I need?

I've searched everywhere but it seems that I cannot find something that works for my needs.

Thank you in advance everybody.

# Answer
> 0 votes
Well it might seem a little noobish mistake but nevertheless, for everyone that is interested out there.

After a lot of research I found out how to make it.

The problem that arises when you try to render a form in a .tpl file is the functionality of the form.

I was trying to render `$page['content']` and I couldn't do the above.

So I had to add to `MYTHEME\template.php` these lines:

```
function MYTHEME_theme($existing, $type, $theme, $path) {
  return array(
    'commerce_checkout_form_checkout' => array(
      'render element' => 'form',
      'template' => 'commerce-checkout-form-checkout',
      'path' => drupal_get_path('theme', 'MYTHEME') . '/template/forms',
    ),
  );
}

```

and then I created: `commerce-checkout-form-checkout.tpl.php` in MYTHEME/template/forms

and I just put this code inside:

```
<div class="row">
  <div class="col-sm-12"><?php print render($form['cart_contents']); ?></div>
</div>
<div class="row">
  <div class="col-sm-6"><?php print render($form['customer_profile_billing']); ?></div>
  <div class="col-sm-6"><?php print render($form['commerce_payment']); ?></div>
</div>
<?php print drupal_render_children($form); ?>

```

The key to render the form right was the last line:

```
<?php print drupal_render_children($form); ?>

```

which rendered all the missing funcionality (like ajax and submit buttons) from the form.

I hope this will help someone in the future to avoid all the time and hassle..

---
Tags: theming, forms
---


# Question
Title: Drush misidentifies my D7 site as drupal 8
I'm using Drush Commandline Tool 9.2.1 in a Drupal 7 webroot and I'm unable to run it.

```
$ drush -vvv cc all
 [preflight] Config paths: /home/user/.composer/vendor/drush/drush/drush.yml
 [preflight] Alias paths:
 [preflight] Commandfile search paths:
             /home/user/.composer/vendor/drush/drush/src
 [bootstrap] Bootstrap to max [0.14 sec, 11.2 MB]
 [debug] Trying to bootstrap as far as we can [0.14 sec, 11.21 MB]
 [error]  `cache-clear all` is deprecated for Drupal 8 and later.
          Please use the `cache-rebuild` command instead.

```

Seems to suggest that it thinks the site is D8 but it's a D7 site.

```
$ drush list
(...commands listed as normal...)
! [NOTE] Drupal root not found. Pass --root or a @siteAlias in order to
see Drupal-specific commands.

```

Says it can't identify the root. I'm in it! And my settings file is fine at the normal location of `sites/default/settings.php`

Even passing `--root` and `-l` options does not help - I still get the same errors.

Never had this before. Any ideas?

## EDIT

Here's why I didn't think this was a silly question:

Source: http://docs.drush.org/en/7.x/install/ at 23 Mar 2018.

# Answer
> 4 votes
> I'm using Drush Commandline Tool 9.2.1 in a Drupal 7

Drush 9 only works with Drupal 8.4+

<sub>As seen on: http://docs.drush.org/en/master/install/ </sub>

Uninstall Drush 9

```
composer global remove drush/drush

```

and install Drush 8

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

```

---
Tags: 7, drush
---


# Question
Title: Content Template no longer displaying new nodes. Works fine for older nodes
In my D7 site, I have a content type that's being displayed using Content Template (Contemplate). The Content Template code hasn't changed in over a year. It's been running like a champ… displaying new content and edited content on hundreds of nodes.

All of a sudden, no new node content will be displayed through Content Template. If I temporarily disable the Content Template, the node content will appear. When I turn it back on, nothing.

I wiped out my Content Template code thinking there might be some conflict in there. I replaced the whole thing with just one line:

```
<?php print $node->field_body[$node->language][0]['safe_value']; ?>

```

Nothing.

What's interesting is that any HTML or PHP in the Content Template code will still work… it's just the field variables that are not producing any values. And again, this is only for newly created nodes.

Some of the core node variables will still work (like NID and Title), but none of the custom fields. So, for example, this code works:

```
<p>node: <?php print $node->nid ?></p>
<p>title: <?php print $node->title ?></p>

```

This would produce the NID and the node title successfully on the page. But, the aforementioned `$node->field_body…` (which is a custom field), produces nothing.

In a further effort to troubleshoot, I've disable any recently activated modules (Entityforms and Rules). No change.

# Answer
The module's page explicitly states:

> NOTE: This module *may* be deprecated in Drupal 7! Here's your reason, basically the theming changes in D7 mean the field theming gets bound a lot lot later in the process, so it's not possible to generate the output into a Textarea for you to edit

In fact the module has been marked as deprecated and not updated since 20 September 2011.

Also there is a long discussion on https://www.drupal.org/node/1285558 about better ways of doing things without Contemplate module.

So it's just time for you to give up the deprecated module and re-code your template files as it simply won't work with later versions of Drupal 7.
> 0 votes

---
Tags: 7, theming, nodes
---


# Question
Title: How to get a 'result summary' of the rows effectively showed?
I have a view, and in the Header section I have activated the 'Global: Result Summary'. My problem is that the line count does not take into account the user's permissions: for example if the view has 10 results, but the user can only see 5 (let's say the other 5 are not published), I see a page with 5 lines, but with a result-summary that says: Result 1-10 of 10. While it should be Result 1-5 of 5. There is no need to tell the user that there are some results that he can't see. Is there a way to count the lines actually shown?

# Answer
> 0 votes
The `Global: Result Summary` should display only the total count of the actually output rows. You just need to set proper permissions and filter criteria for result summary to behave as you desire. For example, if you have `Content: Published (Yes)` filter in the `Filter criteria`, then the counter never will take unpublished nodes into account.

---
Tags: views
---


title: 4xx pages template override

text:
# Question
Title: 4xx pages template override
I am trying to implement the solution given in this question.

I want to have custom templates for 4xx pages.

I am using Drupal 8.3.1

I have tried the code as given in the above link to create the page suggestions in my theme's `.theme` file:

```
/**
 * Implements hook_theme_suggestions_page() to set 40x template suggestions
 */
function MY_THEME_NAME_theme_suggestions_page(array $variables) {
  $path_args = explode('/', trim(\Drupal::service('path.current')->getPath(), '/'));
  $suggestions = theme_get_suggestions($path_args, 'page');
  $http_error_suggestions = [
    'system.401' => 'page__401',
    'system.403' => 'page__403',
    'system.404' => 'page__404',
  ];
  $route_name = \Drupal::routeMatch()->getRouteName();
  if (isset($http_error_suggestions[$route_name])) {
    $suggestions[] = $http_error_suggestions[$route_name];
  }

  return $suggestions;
}

```

It does not appear to work.

`page--404.html.twig` or `page--system--404.html.twig` are not being used.

404 and 403 pages are not set inside the admin of the page.

What else am I suppose to do to get this working?

# Answer
I have pretty much the same code as you have with the exception that I have a `hook_theme_suggestions_page_alter()`. With the `_alter` attached to it.

Try putting the HOOK in a custom module instead of the `.theme` file.
> 0 votes

---
Tags: theming, 8
---


# Question
Title: Error when running database update: "DatabaseSchemaObjectExistsException: Cannot add field redirect.status: field already exists."
I'm getting the following error when attempting to run a database update:

```
Update #7101
Failed: DatabaseSchemaObjectExistsException: Cannot add field redirect.status:
field already exists. in DatabaseSchema_mysql->addField()
(line 336 of /var/www/sitename/drupal/web/includes/database/mysql/schema.inc).

```

It looks like the database update it do to some redirects I added. How do I go about solving this?

# Answer
Most probably you are on Redirect 7.x-1.0-rc3 which was released back on 8 July 2015. It has been fixed on https://www.drupal.org/project/redirect/issues/2541304, so just update your Redirect module to 7.x-1.x-dev.
> 1 votes

---
Tags: 7, database, redirection, updating, debugging
---


title: Trouble recreating my site locally

text:
# Question
Title: Trouble recreating my site locally
My online site gives "server encountered an unexpected error" and the shared hosting site (1and1) gives no log access. So I am trying to recreate my site at home. I started with a clean install of D8.5, and installed my theme, which works. Then I replaced the database with the SQL dump I made on the host when my site was working. I also copied the modules directory to my site, and carefully copied sites/default/files, but just my image files. But now my local version wants to reinstall from the start. How do I manage to recreate my site properly? I could never use backup/restore on my host site--it had an error and would not activate.

# Answer
> 0 votes
So, without knowing more about your production and dev environments, it's hard to say.

Most people would probably advocate moving your codebase with GIT, rather than manually as FTP programs will usually not move files prefixed like your .htaccess file (which maybe causing your whitescreen). If you're going the manual route, I would rsync a copy of your production sites folder, zip it, and the move it to your local computer, install drupal from scratch, then move your files over, set up the db and settings.php for your local environment, run update.php, and profit.

---
Tags: database, files
---


# Question
Title: Drupal 8 Webform - Loop the Result in Remote Post
I am a PHP and Drupal 8 newbie. I am working on a module based on Drupal 8 Webform and remote post.

I'd like to loop the request sent rather than doing a request-\>get('keyname') on each. I'm hoping to using the parameter name to search another string and then replace it with the parameter's value in that string.

Any small foreach example would be appreciated.

# Answer
> 0 votes
Assuming `$request` is a Symfony request object:

```
foreach ($request->request->all() as $key => $value) {
  // ...
}

```

---
Tags: 8, webforms
---


# Question
Title: Exposed filters and taxonomy. How to make a redirect to a term page when exposed form submit?
Let's say there are 2 vocabularies:

* Sizes (S, M, L, XL)
* Colors (Red, Green, Yellow)

pathauto sizes: /size/s, /size/m, ... pathauto colors: /color/red, /color/green, ...

There is a catalog - taxonomy/term/% view with the following filters:

* Size
* Color

If we use a filter, then the url will be like this - ?field\_size\_tid=2&field\_color\_tid=3 It's normal, when several fields are selected in the filter

But when one field is selected in the filter, the url will be like - ?field\_color\_tid=2 But in fact the ?field\_color\_tid=2 = /color/green

How to make an redirect to /color/green instead of ?field\_color\_tid=2 in this case after exposed form submit?

# Answer
Here is the code that should work for your use case. Create a custom module and replace YOUR\_CUSTOM\_MODULE part:

```
function YOUR_CUSTOM_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    // Exclude cases when query contains 'field_color_tid'.
    if (strpos($_SERVER['QUERY_STRING'],'field_color_tid') === FALSE) {
      // Act only if query string contains 'field_size_tid'
      if (strpos($_SERVER['QUERY_STRING'],'field_size_tid') !== FALSE) {
        $selected_tid = $form_state['view']->exposed_input['field_size_tid'];
        // Check if such taxonomy term exists.
        $term = taxonomy_term_load($selected_tid);
        if (!empty($term)) {
          // Redirect to taxonomy page.
          $path_alias = drupal_get_path_alias('taxonomy/term/'.$selected_tid);
          drupal_goto($path_alias);
        }
      }
    }
  }
}

```
> 0 votes

# Answer
I have a slightly different solution. Hope this helps too...

* You can have as many taxonomy categories as you need as exposed filters.
* Each vocabulary may have different pathauto patterns.
* Other exposed filters should still work without any conflict.

Place this code in your custom module (CUSTOMMODULE.module):

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function CUSTOMMODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  // Replace `Size` filter.
  CUSTOMMODULE_jumpmenu($form, 'field_size_tid');

  // Replace `Color` filter.
  CUSTOMMODULE_jumpmenu($form, 'field_color_tid');
}

/**
 * Transform select filters into a simple jump menu.
 *
 * @param $form
 *   Nested array of form elements that comprise the form.
 * @param $field_name
 *   String representing the name of the field to be replaced.
 */
function CUSTOMMODULE_jumpmenu(&$form, $field_name) {
  if (
    isset($form[$field_name])
    && ($form[$field_name]['#type'] === 'select')
    && !empty($form[$field_name]['#options'])
  ) {
    $options = &$form[$field_name]['#options'];
    foreach ($options as $tid => $value) {
      if (is_int($tid)) {
        $path = drupal_get_path_alias('taxonomy/term/' . $tid);
        $options[url($path)] = $value;
        unset($options[$tid]);
      }
    }

    $form[$field_name]['#attributes']['onChange'] = 'javascript:if (this.value !== "All") { location.href = this.value; return false; }';

    return $form;
  }

  return [];
}

```

You can test this solution with this simple view:

```
$view = new view();
$view->name = 'example_view';
$view->description = '';
$view->tag = 'drupal_stackexchange';
$view->base_table = 'node';
$view->human_name = 'Example view';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE;

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Example view';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '50';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
  'field_color' => 'field_color',
  'field_size' => 'field_size',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'field_color' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'field_size' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: Color */
$handler->display->display_options['fields']['field_color']['id'] = 'field_color';
$handler->display->display_options['fields']['field_color']['table'] = 'field_data_field_color';
$handler->display->display_options['fields']['field_color']['field'] = 'field_color';
/* Field: Content: Size */
$handler->display->display_options['fields']['field_size']['id'] = 'field_size';
$handler->display->display_options['fields']['field_size']['table'] = 'field_data_field_size';
$handler->display->display_options['fields']['field_size']['field'] = 'field_size';
/* Sort criterion: Content: Title */
$handler->display->display_options['sorts']['title']['id'] = 'title';
$handler->display->display_options['sorts']['title']['table'] = 'node';
$handler->display->display_options['sorts']['title']['field'] = 'title';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'tshirt' => 'tshirt',
);
/* Filter criterion: Content: Size (field_size) */
$handler->display->display_options['filters']['field_size_tid']['id'] = 'field_size_tid';
$handler->display->display_options['filters']['field_size_tid']['table'] = 'field_data_field_size';
$handler->display->display_options['filters']['field_size_tid']['field'] = 'field_size_tid';
$handler->display->display_options['filters']['field_size_tid']['exposed'] = TRUE;
$handler->display->display_options['filters']['field_size_tid']['expose']['operator_id'] = 'field_size_tid_op';
$handler->display->display_options['filters']['field_size_tid']['expose']['label'] = 'Size';
$handler->display->display_options['filters']['field_size_tid']['expose']['operator'] = 'field_size_tid_op';
$handler->display->display_options['filters']['field_size_tid']['expose']['identifier'] = 'field_size_tid';
$handler->display->display_options['filters']['field_size_tid']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
);
$handler->display->display_options['filters']['field_size_tid']['type'] = 'select';
$handler->display->display_options['filters']['field_size_tid']['vocabulary'] = 'size';
/* Filter criterion: Content: Color (field_color) */
$handler->display->display_options['filters']['field_color_tid']['id'] = 'field_color_tid';
$handler->display->display_options['filters']['field_color_tid']['table'] = 'field_data_field_color';
$handler->display->display_options['filters']['field_color_tid']['field'] = 'field_color_tid';
$handler->display->display_options['filters']['field_color_tid']['exposed'] = TRUE;
$handler->display->display_options['filters']['field_color_tid']['expose']['operator_id'] = 'field_color_tid_op';
$handler->display->display_options['filters']['field_color_tid']['expose']['label'] = 'Color';
$handler->display->display_options['filters']['field_color_tid']['expose']['operator'] = 'field_color_tid_op';
$handler->display->display_options['filters']['field_color_tid']['expose']['identifier'] = 'field_color_tid';
$handler->display->display_options['filters']['field_color_tid']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
);
$handler->display->display_options['filters']['field_color_tid']['type'] = 'select';
$handler->display->display_options['filters']['field_color_tid']['vocabulary'] = 'color';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'example-view';
$handler->display->display_options['menu']['type'] = 'normal';
$handler->display->display_options['menu']['title'] = 'Example view';
$handler->display->display_options['menu']['name'] = 'main-menu';

```
> 0 votes

# Answer
In the end, I did this way:

```
    $params = drupal_get_query_parameters();
    $redirected_fields = array('field_size_tid','field_class_tid','field_color_tid', field_brand_tid);
    $checked_fields = array();

    foreach ($params as $key => $val) {
      if ($val == '' || $val == 'All') {} else { $checked_fields[] = $key; }
    }

    if ((count($checked_fields) == 1) && (in_array($checked_fields[0],$redirected_fields)) && (count($params[$checked_fields[0]]) == 1)) {
      $selected_tid = $form_state['view']->exposed_input[$checked_fields[0]];
      if (is_array($selected_tid)) {$selected_tid = implode('',$selected_tid);}
      // Check if such taxonomy term exists.
      $term = taxonomy_term_load($selected_tid);
      //dpm($term);
      if (!empty($term)) {
        // Redirect to taxonomy page.
        $path_alias = drupal_get_path_alias('taxonomy/term/'.$selected_tid);
        drupal_goto($path_alias);
      }
    }

```
> 0 votes

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


# Question
Title: Create a Node with Fields and turn them into tabs in a display?
I am a Drupal 7 newbie, I am only proficient in CSS and HTML and I am looking for someone to point me in the right direction(to documentation/modules/advice) on how to execute what I am trying to do or even telling me if it is possible or not.

I tried making tabs already, I was using quick tabs and multiple blocks but I found that would be inefficient because I need 12 pages with tabs and each has at least 2-3 tabs with content each that need to be eventually edited by heads of departments.

**What I am trying to do:**

* Create a page with multiple tabs and content inside of it.
* When editing the node there should be multiple tabs at the top corresponding with the tabs on the page and an option to add more tabs up to a limit
* Tabs should have a title and body field.

Some examples of the content of the tabs: welcome, about, programme. They would just have 1 or two paragraphs of content.

**How I was thinking it could be done:**

* Creating a New Field type called Tab, that groups a title & body
* Creating a New Structure type that has max of 6 Tabs
* Create a new display to have the fields organized into tabs.
* Download Module for displaying tabs in editing mode?

I just don't know how to make that possible or if it is. Can someone point me in the right direction or help me to come up with a better alternative?

# Answer
The easiest approach to create tabs to nest your content for visitors to see on your pages without much hassle is to try to use the Field Group module in D7.

Another solution is to use the Paragraphs module with 2 fields: title and body. And try to setup Field Groups possibly to treat each paragraph entry as a Tab on the page ...
> 0 votes

---
Tags: 7, nodes, entities
---


# Question
Title: Cannot get articles or custom content types to load on front page
I am new to drupal. I have Drupal ver 8.5 installed on my local MAMP.

Unfortunately, though I am following a tutorial that is using version 7.28 (perhaps this is the issue). I cannot get my recently made articles OR custom content types to show on my front page.

a.) I have ensured that my URL under Front page \> "Basic Site Settings" is blank. b.) I have ensured that all my articles have "Promoted to front page" checked under the Promotion Options Tab. c.) I have ensured that all my custom content types have "Promoted to front page" under the Promotion Options Tab.

What am I doing wrong?

# Answer
> 0 votes
By default, in a fresh Drupal 8 installation, your homepage is populated by the *frontpage* view. Make sure that your homepage URL under admin/config/system/site-information is /node. That is the default URI of the *frontpage* view.

You can find the definition of that view under admin/structure/views/view/frontpage.

If you need a guide about the Views module, you can find it on Chapter 9. Creating Listings with Views.

---
Tags: 8, nodes
---


# Question
Title: is there a way to customize url alias by content type?
I have several contentypes, url alias are working fine, by default if there is a space in node title (or another token) is replaced with a dash "-", is it posible to change that beheavior by contentype and only on this special contentype replace spaces with nothing? example: my special contentype node title is= "word1 word2", this is replaced by "word1-word2", and i need to be "word1word2".

EDIT: i have allready pathauto module installed and working, path aliases are working fine, i need to change de default separator settings from a dash to "nothing" in one contentype only. Both answers bellow do not help me.

# Answer
Yes. You can use the pathauto module.

http://dgo.to/pathauto
> 2 votes

# Answer
To have a unique replacement pattern for every content type follow these instructions:

Like Jaypan said use the pathauto module https://www.drupal.org/project/pathauto then

1. Click on configuration in the admin menu
2. Click URL aliases
3. Click the Patterns tab at the top
4. Click 'Add Pathauto Pattern'
5. For pattern type choose 'content', and give it a name
6. After saving click edit to the right of the pattern you just created
7. You should have a list of content types you can choose to have this pattern applied to.
8. Enter in the pattern using whatever tokens you need
9. Repeat these steps for each content type you want to have a custom path pattern
> 0 votes

---
Tags: path-aliases
---


# Question
Title: aborted prematurely while running update #7204
I get this message but nothing is logged (that I can see)

The update process was aborted prematurely while running update #7204 in wysiwyg.module. All errors have been logged. You may need to check the watchdog database table manually.

# Answer
> 1 votes
I did more digging and found it is because the wysiwyg module was disabled. I enabled it and the update worked.

---
Tags: updating
---


# Question
Title: Starting new 8.5 site is it safe to delete and reuse field_image field
I am starting a new 8.5 website and using the core media module. I want to know if it is safe to delete the field\_image field from the Article content type and replace it with a field with the same name but instead make it a media reference field. I have searched high and low and it is not clear as to if this will cause me issues with future versions of Drupal.

Thanks in advance

# Answer
> 2 votes
Any field could be deleted and re-created per your preferences and it won't cause any problems in the future as Drupal 8 does not require fields of certain machine names to be of certain types only.

---
Tags: 8, media
---


# Question
Title: Configuring drupal in a virtual directory
I am running drupal using apache on redhat linux. Currently drupal is running at the root of the apache site. However, I want to put drupal in a sub-directory/virtual folder, because it's possible other sites will be on this server in the future.

The sub-folder I want to use is /fr. I can easily setup apache to use this alias, but how do I configure drupal to know that it's running in a subfolder? I currently have URLs like /agent/dashboard. If I configure apache for the /fr subfolder, drupal loads but it doesn't recognize /fr/agent/dashboard.

Do I just make a subfolder in the drupal install folder? I'm not too familiar with apache so I really don't know. Do I have to redefine all my routes (i'm using Drupal 8). I really hope not. I'm looking just for a setting in drupal or apache where I can set this.

# Answer
> 1 votes
Running Drupal in a subdomain and changing the document root of Apache virtual server are two different things.

To change document root you would set new paths in two Apache configuration lines for the given website:

```
DocumentRoot /home/username/public_html
<Directory /home/username/public_html>

```

Change the above two records to whatever you like, for example to:

```
DocumentRoot /home/username/public_html/sub-directory/sub-sub-directory
<Directory /home/username/public_html/sub-directory/sub-sub-directory>

```

and it wouldn't matter for Drupal as long as the following directive stays same:

```
ServerName example.com

```

In other words, whatever document root you set for a website, it will be still accessible through its domain name typed in the browser's address bar, set as ServerName in Apache configuration file, and Drupal will behave accordingly.

However, if you want to just place Drupal in a sub-directory, then you do not have to meddle with Apache configuration at all.

---
Tags: installation
---


# Question
Title: How do I avoid behaviors are invoked after an AJAX call?
I have a search result page, with the first set of data being fetched during the page load, and we add a *Load More* button. Clicking on this button fires an AJAX call, using the *ajax\_links\_api* module. After the AJAX call is completed, we append more search results to the current set. I have a behavior where I read the URL parameter; if it exists, I open a Colorbox.

If the colorbox opens on page load, we close it, and then click on *Load More* (which fires AJAX); then the Colorbox JavaScript is fired again, and we see the popup in action again.

I don't want to fire the Colorbox JavaScript after AJAX is completed/fired.

I tried jQuery Once, but it didn't work.

How can I achieve this? Can I detect when an AJAX call happens?

The following is the code I am using.

```
Drupal.behaviors.openColorbox = {
  attach: function (context, settings) {
    if ($('body', context).hasClass('page-search-site')) {
      var nid = url('?node');
      if (nid != undefined) {
        if (nid.trim()) {
          $('div.search-result')
            .find('.node-' + nid)
            .once('colorbox-clicked')
            .click();
        }
      }
    }
  }
};

```

# Answer
> 0 votes
You are using .once in the wrong spot

```
(function($, Drupal) {

  "use strict";

  function openColorbox(context) {
    $(context).find("div.search-result").once("openColorbox").each(function () {
      if ($('body', context).hasClass('page-search-site')) {
        var nid = url('?node');
        if (nid != undefined) {
          if (nid.trim()) {
            $('div.search-result')
              .find('.node-' + nid)
              .click();
          }
        }
      }
    }
  }

  Drupal.behaviors.openColorbox = {
    attach: function (context) {
      openColorbox(context);
    }
  };

}(jQuery, Drupal));

```

Note that this is D8 style. If you are using D7, the above will not work as it is done differently, and you didn't tell us which Drupal version you are using.

---
Tags: javascript, ajax, search
---


# Question
Title: How do I add a class to the search block form?
I want to add a class to the `<form>` element on the form\_id 'search\_block\_form'

this is my current code

```
function THEME_form_search_block_form_alter(&$form, &$form_state, $form_id) {
  $form['#attributes']['class'][] = 'form-inline ';

}

```

# Answer
You can use the `template_preprocess_form`

```
function THEMENAME_preprocess_form(&$vars) {
  // Add class to your specific form
  if ($vars['attributes']['id'] == 'search-block-form') {
    $vars['attributes']['class'][] = 'form-inline ';
  }
}

```

NOTE: the preprocessor you are using adds class to the block element
> 1 votes

# Answer
Try this code..

```
/*
* Implement hook_form_alter()
*/
function custom_form_search_block_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
    $form['#attributes']['class'][] = 'test';
}

```
> -1 votes

---
Tags: 8, theming
---


title: Override webform module submit

text:
# Question
Title: Override webform module submit
I want to save webform submissions in node table..

I want to use the solution from "How to create a node out of a webform submission?".

How can I implement it? I used **hook\_form\_alter** but it doesn't work.

# Answer
The question about "How to create a node out of a webform submission?" that you linked to, is about D8, while yours is about D7 ...

In D7, for sure,, you can use the Rules module for this. As an example, consider this rule (in Rules export format), which does what you're asking for:

```
{ "rules_create_a_node_from_webform_data" : {
    "LABEL" : "Create a node from webform data",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "webform_rules", "rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "webform_has_id" : {
          "form_id" : [ "form_id" ],
          "selected_webform" : { "value" : { "webform-client-form-191" : "webform-client-form-191" } }
        }
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "The webform submitted contains these fields:\r\n\u003C\/ul\u003E\r\n\u003Cli\u003Ethe field labeled \u0022[data:demoform_title-title]\u0022 which has value \u0022[data:demoform_title-value-raw]\u0022.\u003C\/li\u003E\r\n\u003Cli\u003E the field labeled \u0022[data:demoform_text-title]\u0022 which has value \u0022[data:demoform_text-value-raw]\u0022.\u003C\/li\u003E\r\n\u003Cli\u003E the field labeled \u0022[data:demoform_number-title]\u0022 which has value \u0022[data:demoform_number-value-raw]\u0022.\u003C\/li\u003E\r\n\u003Cli\u003E the field labeled \u0022[data:demoform_option-title]\u0022 which has value \u0022[data:demoform_option-value-raw]\u0022.\u003C\/li\u003E\r\n\u003C\/ul\u003E" } },
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "[data:demoform_text-value-raw]" },
          "PROVIDE" : { "variable_added" : { "var_demoform_text" : "Form variable text" } }
        }
      },
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "[data:demoform_number-value-raw]" },
          "PROVIDE" : { "variable_added" : { "var_demoform_number_text" : "Form variable number text" } }
        }
      },
      { "data_convert" : {
          "USING" : { "type" : "integer", "value" : [ "var-demoform-number-text" ] },
          "PROVIDE" : { "conversion_result" : { "var_demoformvar_number" : "Form variable number" } }
        }
      },
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "[data:demoform_option-value-raw]" },
          "PROVIDE" : { "variable_added" : { "var_demoform_option" : " Form variable option" } }
        }
      },
      { "entity_create" : {
          "USING" : {
            "type" : "node",
            "param_type" : "article",
            "param_title" : "[data:demoform_title-value-raw]",
            "param_author" : [ "user" ]
          },
          "PROVIDE" : { "entity_created" : { "article_created" : "Created article" } }
        }
      },
      { "data_set" : {
          "data" : [ "article-created:body:value" ],
          "value" : [ "var-demoform-text" ]
        }
      },
      { "data_set" : {
          "data" : [ "article-created:field-free-format-nr" ],
          "value" : [ "var-demoformvar-number" ]
        }
      },
      { "data_set" : {
          "data" : [ "article-created:field-optionlist" ],
          "value" : [ "var-demoform-option" ]
        }
      },
      { "data_set" : { "data" : [ "article-created:comment" ], "value" : "0" } },
      { "entity_save" : { "data" : [ "article-created" ], "immediate" : "1" } },
      { "drupal_message" : { "message" : "A new article got created, with nid=[article-created:nid] and url=[article-created:url]" } }
    ]
  }
}

```

Anybody a bit familiar with Rules and Webform, while know that it's often a struggle to get access to the data contained in a submitted Webform. Mostly because they are not available to select them when building Rules Actions.

However by introducing those `var-demoform-...` variables (as in the above rule), you can make the typical Rules magic happen. Refer to my answer to "How to create a node from a Webform using rules?" for more details about all this.
> 2 votes

# Answer
Try hook\_form\_alter into your custom module file.

```
/*
* Implement hook_form_alter()
*/
function mymodule_form_alter( &$form, &$form_state,$form_id ){
  // this is for your developer information and shows you the
  // structure of the form array
  dpm($form);
  // this will give you the details for my_form_component
  $a_component = $form['submitted']['my_form_component'];
  dpm($a_component);

  // you'll want to limit your altering to specific forms
  if ($form_id == 'my_webform_client_form_id') {
    // edit component values like this:
    $form['submitted']['my_form_component']['#title'] = 'A spurious text title';
    $from['#submit'] = 'custom_form_submit';
  }
}

```

https://www.drupal.org/node/1558246
> 1 votes

---
Tags: 7, webforms
---


title: Get field values in Twig with #markup

text:
# Question
Title: Get field values in Twig with #markup
I want the content to be customized by the user, so I created a simple theme and added some fields like background image, color, size etc.

```
{%
    set background_image = content.field_image.0['#markup']
%}
{%
    set size  = content.field_size.0['#markup']
%}
{%
    set background_color  = content.field_background_color.0['#markup']
%}

```

Is this the right way to do it? Is it a safe way to get content with #markup?

```
{%
  set section = {
    'section_attributes': create_attribute().addClass([
      'section',
      size|clean_class,
      background_color|clean_class,
    ])
    .setAttribute('style', 'background-image: url(' ~ background_image ~ ');' )
  }
%}

```

Is there any other safe way to do this?

# Answer
I think that it would be better to use

```
{{ content.field_size.value }}

```

Then twig will automatically get the value from the field.

If you just want to render the field then `{{ content.field_size}}` should be fine.

Hope it helps.
> 2 votes

---
Tags: 8, theming
---


# Question
Title: How to print add to cart form for drupal 8 commerce on my custom page programatically
I have a site where I created a custom page to list products (can't use views module due to custom requirements for printing that list). On the list page for each product I have variation sku available. I want to show add to cart form with qty field on this custom list page. I have searched for a solution but couldn't find one for drupal 8. I know how to do it in drupal 7 but can someone help me with how we can have this in D8?

# Answer
> 1 votes
I got solution to the above problem. I used a drupal commerce service to load the form. Below is the code which I used, please let me know if it is an acceptable solution.

```
$commerceProduct = \Drupal::service('commerce_product.lazy_builders');
$cart_array = $commerceProduct->addToCartForm($product_id, 'teaser', true, $language);

```

This gave me a renderable array which I rendered using render service. Add to cart form is working fine.

---
Tags: 8, commerce
---


# Question
Title: How can I create comment on node insert?
I try to create comment on node insert using `insert()` hook but it collides with `INSERT INTO {comment_entity_statistics}` sql.

```
Integrity constraint violation: 1062 Duplicate entry '53-node-field_support' for key 'PRIMARY': INSERT INTO {comment_entity_statistics}

```

The code:

```
/**
 * Implements hook_ENTITY_TYPE_insert().
 */
function notifications_node_insert(Drupal\Core\Entity\EntityInterface $entity)
{
    $timestamp = mt_rand($entity->getCreatedTime(), REQUEST_TIME);
    $stub = array(
        'entity_type' => $entity->getEntityTypeId(),
        'entity_id' => $entity->id(),
        'field_name' => 'field_support',
        'name' => 'devel generate',
        'mail' => 'devel_generate@example.com',
        'timestamp' => $timestamp,
        'subject' => $_POST['field_support_message'],
        'uid' => \Drupal::currentUser()->id(),
        'langcode' => $entity->language()->getId(),
    );
    $comment = \Drupal\comment\Entity\Comment::create($stub);
    $comment->save();
}

```

# Answer
I guess you're hitting some edge case in \Drupal\comment\CommentStatistics::create(), which is called in comment\_entity\_insert(). The code assumes that there is no comment yet when that is called. Which is an assumption that you are breaking, probably because your module gets called first.

That's arguably a core bug, you could open a bug report and try to fix it there to do a merge query. That said, as a workaround, make sure that your hook is called later than comment. You will have to implement hook\_entity\_insert() instead of node as that is apparently called later (by default, hooks are stored by modules by weight, name, so C should be before N).

PS: You should enable verbose error logging and check the full backtrace of that error. That can often help with understanding what's going on.
> 4 votes

# Answer
Works for me using hook\_entity\_insert instead of hook\_node\_insert.
> 0 votes

---
Tags: 8
---


# Question
Title: Concatenating translatable strings is not allowed, use placeholders instead and only one string literal
The following code:

```
$report .= '<p>' . t('<strong>%percentage</strong> of <strong><em>'.$node_type_get_types[$type]->name.'</em></strong> completed.', array('%percentage' => $percentage)) . ' ' . $count . '</p>';

```

is inside of iteration, because I need to make the same calculations and collect all the results and output all in one string.

Drupal.org's automated testing complains about the above part:

`Concatenating translatable strings is not allowed, use placeholders instead and only one string literal`

I don't have any idea how to make this correct.

# Answer
> 3 votes
It means you have to use a placeholder, in the same way you used the *%percentage* placeholder.

```
$report .= '<p>' . t('<strong>%percentage</strong> of <strong><em>@content-type</em></strong> completed. %count', array('%percentage' => $percentage, '@content-type' => $node_type_get_types[$type]->name, '%count' => $count)) . '</p>';

```

I used a @-placeholder for the content type, in the same way done from `node_add()`.

For a list of the placeholder types used from Drupal, see `format_string()`. The documentation for t() explain in details why concatenating is not possible in translatable strings.

---
Tags: testing
---


title: Taxonomy page view template override

text:
# Question
Title: Taxonomy page view template override
I have a view showing content and a view showing taxonomy terms.

For the first one, one of the suggested template files is *views-view--{viewname}.html.twig*. I don't get the same template file suggested for the second view.

Am I missing something, or is it just the way it is?

# Answer
I noticed the template suggestions for views are sometimes not complete. As Views template files says, though, the *views-view--\[view\_name\].html.twig* template file, where *\[view\_name\]* is the view machine name, can be used for every view, independently from what the view shows.

> All views templates can be overridden with a variety of names, using the view, the display ID of the view, the display type of the view, or some combination thereof.
>
> For each view, there will be a minimum of two templates used. The first is used for all views: views-view.html.twig.
>
> The second template is determined by the style selected for the view. Note that certain aspects of the view can also change which style is used; for example, arguments which provide a summary view might change the style to one of the special summary styles.
>
> The default style for all views is views-view-unformatted.html.twig.
> 0 votes

# Answer
You can enable twig debug - this will output, as html comments (you'll have to inspect the dom), all twig override options above all twig rendered output. Check out this page for more info: https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates

One note I'll make is that I would use the development.services.yml file to make this override if you're using a settings.local.php. You can find that file and information about how to use it at sites/development.services.yml. You'll have to copy that file to your site's directory for your current site, e.g. sites/default/development.services.yml and then add the configuration for enabling twig debug there.
> 0 votes

---
Tags: 8, views
---


# Question
Title: How do I render an image from a Twig template?
I cannot get this to render out. This is what I get with `{{ kint(paragraph.field_image.value) }}`.

>

If this makes any difference, the image is uploaded through a media entity browser widget.

How do I render an image from a Twig template?

# Answer
> 2 votes
you could just use `{{ content.field_image }}`

Here is an example of a template file from a paragraph

```
{%
  set classes = [
  'paragraph',
  'paragraph--type--' ~ paragraph.bundle|clean_class,
  view_mode ? 'paragraph--view-mode--' ~ view_mode|clean_class,
]
%}
{% block paragraph %}
<div{{ attributes.addClass(classes) }}>
  {% block content %}
      <div class="row collapse expanded mainsection">
        <div class="large-12 columns">
          <div class="row collapse">
            <div class="large-12 columns">
              {{ content.image }}
            </div>
          </div>
        </div>
      </div>
  {% endblock %}
  </div>
{% endblock paragraph %}

```

Notice that I only need to write `{{ content.FIELDNAME }}`, if I wrap everything in a `{% block content %}`

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


title: Make all Quicktabs closed by default

text:
# Question
Title: Make all Quicktabs closed by default
Is there any way to set all of the tabs on Quicktabs to **closed** or **inactive** by default?

I would like, that if I visit the page then the first Quicktab isn't open by default. In this inherited site there are images and content underneath this open tab that I would like visible instead of an opened tab.

Would I have to implement something using JavaScript or is there a better option beside Quicktabs?

---

Quicktabs Version: 7.x-3.8 | Drupal Version: 7.57

# Answer
> 0 votes
I think that you might need to add some jQuery to your theme.

Here is a way to do it.

```
jQuery(document).ready(function(){
    jQuery("#id-of-my-custom-block h3:first").trigger('click');
});

```

---
Tags: 7, blocks, nodes
---


# Question
Title: Display Suite Extra Fields not showing in content page
Display suite extra fields are shown in the manage display. Fields such as author, user, AND submitted by, are enabled in the custom regions I have defined using a custom ds layout. When I go to the full content page it does not show any of the extra ds fields that i enabled. Does anybody know what the issue can be?

I'm using a custom ds layout

```
custom_article:
  label: article
  category: My Layouts
  template: templates/custom_article
  css: css/custom-article.css
  regions:
    header:
      label: header
    author:
      label: author
    body:
      label: body

```

# Answer
> 0 votes
I would try adding a class key, for example:

```
class: '\Drupal\ds\Plugin\DsLayout'

```

Also, I think you should update the template line, replace the underscore with a hyphen (and do the same for the actual twig file), for example:

```
template: templates/custom-article

```

---
Tags: 8, display-suite
---


# Question
Title: Can't get url from internal uri in twig template file
I have tried every suggestion I could find and nothing is working. I need to get the actual path or url since I am adding some specific classes to the link. The array is below

I got to this from the following

```
{% set link = paragraph.field_link.value.0 %}
{{ kint(link) }}

```

I understand that I need to use the url() or path() function but these require 2 parameters and I am unsure where to get these from.

# Answer
> -1 votes
You can try to do like this

```
{{ content.field_link.0['#url'] }}

```

That should do it.

This is another possible way of diong it

```
{{paragraph.field_link.uri }}

```

---
Tags: theming
---


title: How can I delete the "Drupal" text?

text:
# Question
Title: How can I delete the "Drupal" text?
I have tried to go in to the inspector mode and I find the string and delete it, but when I refresh, it is still there. I have tried to empty the cache as well. I don't know how to save my changes and I do not find a way to delete the text through any options in the more graphic interface. I am not good at coding.

>

>

# Answer
> 2 votes
You have a few options to adjust your *site branding name* or the whole block.

## Modify

Change the value in *Configuration \> System \> Basic site settings: Site name* and save.

## Hide/delete

If you actually want to take it out, you can remove the *Site branding* block from the active theme region (*structure \> block layout*).

## Modify/delete on theme level

Move core/modules/system/templates/block--system-branding-block.html.twig to your custom theme and modify/delete specifically `{{ site_name }}` which hold the site name.

---
Tags: blocks
---