# Question
Title: How do I check the value of a field if its empty?
Is there a way to check, in a preprocess function, if the value of a field is empty?

I'm getting the following error.

> Call to a member function isEmpty()

```
function iom_preprocess_block__twitterfeed(&$variables) {
  // Get the twitter_username field from node.
  $twitterUsername = \Drupal::routeMatch()
    ->getParameter('node')
    ->get('field_twitter_username')
    ->value;

  if ($twitterUsername->isEmpty()) {
    dump("Empty");
  }
  else {
    dump("Not Empty");
  }
}

```

# Answer
> 17 votes
@vinhd proposition is correct, by the way you can also use the `isEmpty()` method from the field list interface. It can be more adapted for complex field types.

```
if($node->hasField('field_your_field') && !$node->get('field_your_field')->isEmpty(){

}

```

# Answer
> 5 votes
None of the other answers is fully correct, each one will only work in some cases. Before calling an object method, you have to check
\- if the object exists,
\- if the object is of the right type
\- and if the object has that specific method/field.

The following code might look like a bit of an overkill, but it is the most bulletproof solution I've found so far. Everything I'm checking in there is based on a real word error I've had in my own projects:

```
function MYMODULE_preprocess_MYHOOK(&$variables) {

  $route = \Drupal::routeMatch();

  //special case node preview: has no node object, but a node_preview
  if ($route->getRouteName() == 'entity.node.preview') {
    $node = $route->getParameter('node_preview');
  }
  // this is the default case
  else {
    $node = $route->getParameter('node');
  }

  //$node can be either a node object (most of the times)
  //or an integer (on some admin routes)
  if (is_numeric($node)) {
    $node = \Drupal\node\Entity\Node::load($node);
  }

  // this if-statement is the important part that prevents the error messages
  if ($node instanceof \Drupal\node\NodeInterface && $node->hasField('field_MYFIELD')) {
    // no you can savely do whatever you want with field_MYFIELD
    $myVar = $node->get('field_MYFIELD')->value;
    $isEmpty = $node->get('field_MYFIELD')->isEmpty();
  }
}

```

# Answer
> 2 votes
You can try code:

check has field:

```
$node = \Drupal::routeMatch()->getParameter('node');
if($node->hasField('field_twitter_username')){
  //todo code
}

```

check empty value

```
$field_value = $node->field_twitter_username->getValue()
if(!empty($field_value)){
  //todo code
}

```

---
Tags: theming, hooks
---


# Question
Title: How can I see the clean query of a view?
I created a test view. It displays data of a content type 'Anagrafiche (name for internal use: contatti)'. The view has the following fields (sorry for the interface language):

* Contenuto: Immagine (Img) it's an image field
* Contenuto: Nome (Name) it's a text field
* Contenuto: Cognome (Surname) it's a text field

I used the proposed code for the following question, to get a 'clean' query: link

But the output was not what was expected:

```
SELECT
  node.nid AS nid,
  node.created AS node_created,
  node.changed AS node_changed,
  users_node.name AS users_node_name,
  users_node.uid AS users_node_uid,
  'node' AS field_data_field_immagine_node_entity_type,
  'node' AS field_data_field_nome_node_entity_type,
  'node' AS field_data_field_cognome_node_entity_type
FROM  node AS node
LEFT JOIN users AS users_node
  ON node.uid = users_node.uid
LEFT JOIN field_data_field_cognome AS field_data_field_cognome
  ON node.nid = field_data_field_cognome.entity_id
  AND (field_data_field_cognome.entity_type = 'node'
  AND field_data_field_cognome.deleted = 0)
WHERE (( (node.status = 1)
  AND (node.type IN  ('contatti')) ))
ORDER BY
  field_data_field_cognome.field_cognome_value ASC
LIMIT 20 OFFSET 0

```

I do not have very clear how the correct output should be, but by looking at the query, I gather that this piece is not correct

```
  'node' AS field_data_field_immagine_node_entity_type,
  'node' AS field_data_field_nome_node_entity_type,
  'node' AS field_data_field_cognome_node_entity_type

```

I also tried alternatives like the 'Devel' module and different types of hooks, but I never got what I wanted

**@mikeytown2** I ran the query inside phpmyadmin this is the result:

but the last three columns should not be `node | node | node`, but something like that`img | myName | mySurname`

# Answer
> 1 votes
> I gather that this piece is not correct

It’s absolutely correct - Views is just using the query results to pass through some meta data about the operation.

In this case your view joins three different fields, and the types of entity that the fields are related to are nodes. Views is just keeping track of the that fact for each field, so it can use a generic processor for the results.

If you don’t need to use those fields from the query, you can safely ignore them.

---
Tags: 7, views
---


# Question
Title: How to prevent Profile2 fields from loading on user registration?
I have a profile2 Profile that's named **Driver**. This profile has a **Term reference** to a vocabulary named **Cities** that contains over **30.000 terms**.

I made a **custom user-register.tpl.php** by declaring it in my template.php, and in here I display only the form keys that interests me for the account creation.
When I go to **driver/register** which is the custom page for registering to my profile type, **the loading is taking too much time**, and I suspect it to be caused by the loading of all the fields of my profile (even those non-rendered) and more especially that vast vocabulary.

I looked into profile2 folders and files trying to **comment parts related to the registration** but nothing would prevent the loading from happening.
I also tried to **unset($form\[profile\_driver\])** in my theme\_form\_user\_register\_alter, but it doesn't affect the fact that the profile fields are still loaded before being removed from $form, so I figured it has to be directly in profile2.

Been struggling for quite some days now so if anyone has clues on how to prevent the loading of the whole profile form or ideally specific fields I would be glad to read how to do the trick !
Thanks

***7.x-1.4***

---

**FINAL EDIT :**

I didn't manage to do it programmatically so I ended up setting up a Rule that assigns the Profile & the role to the newly saved user.

# Answer
> 0 votes
> Been struggling for quite some days now so if anyone has clues on how to prevent the loading of the whole profile form

Looks to me that the magic happens in **profile2.module** from line 436 to 460

> ```
> /**
>  * Implements hook_form_FORM_ID_alter() for the registration form.
>  */
> function profile2_form_user_register_form_alter(&$form, &$form_state) {
>   foreach (profile2_get_types() as $type_name => $profile_type) {
>     if (!empty($profile_type->data['registration'])) {
>       if (empty($form_state['profiles'][$type_name])) {
>         $form_state['profiles'][$type_name] = profile2_create(array('type' => $type_name));
>       }
>     }
>   }
>
>   // If we have profiles to attach to the registration form - then do it.
>   if (!empty($form_state['profiles'])) {
>     profile2_attach_form($form, $form_state);
>
>     // Wrap each profile form in a fieldset.
>     foreach ($form_state['profiles'] as $type_name => $profile_type) {
>       $form['profile_' . $type_name] += array(
>         '#type' => 'fieldset',
>         '#title' => check_plain($profile_type->getTranslation('label')),
>       );
>     }
>   }
> }
>
> ```

Usually I would never hack a contrib module directly, but unfortunately here there is no other option considering you have a profile field that loads 30,000 terms. So **comment this out and flush/clear cache**.

Just remember if there is ever an update to this module, it will override your changes, so you will have to comment it out again then.

# Answer
> 0 votes
Hello and thank you for your answer,

I also thought that this was happening in profile2's hook for the user\_register, which is quite logic after all. But sadly commenting this block was precisely what I meant by :

> I looked into profile2 folders and files trying to comment parts related to the registration

... it still renders the $form\[profile\_driver\] when I print\_r($form) (I did clear the caches several times to make sure).

I was going to write that I had no clue where it could be if not here, but I just found out that it is actually in the **profile2\_regpath** module that attached the fields to the user\_register\_form. For the record, line 424 of **profile2\_regpath.module** :

```
function profile2_regpath_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register_form') {
    // Get profile2 profile types from current path.
    $url = drupal_parse_url($form['#action']);
    $path = explode('/', str_replace('/inscription', '', $url['path']));
    $path_key = end($path);
    $profile_types = profile2_regpath_get_profiles($path_key);
    // profile2_regpath_attach_profile_fields($form, $form_state, $form_id, $profile_types);
  }
}

```

Commenting out the last line as I did prevents the \[profile\_driver\] key to load, but **every behavior is withdrawn**. I uncommented and tried modifying **profile2\_attach\_form** since it's the function responsible to the loading of the fields in the function that I commented above :

```
if($profile->type !== 'driver'){
        field_attach_form('profile2', $profile, $form['profile_' . $profile->type], $form_state);
    }

```

It attaches the profile to the user but none of its fields.

I'm trying for a few hours to figure out how to attach the fields after the submission or on user\_insert but no success so far.

I'll update here once I found.

***EDIT :*** I tried to **field\_attach\_form on the submit handlers**, but it doesn't work in the end; when I do so and dpm($form), I can see that **the fields are indeed part of $form\['profile\_driver'\]**, but after logging in with the new account the fields **don't appear in the edit form**, which leads me to think that I can't do such a thing on a handler.
Maybe I'm missing knowledge on the normal usage of handlers, but I don't see where to put the snippet to translate **"Load the fields of the Profile2 before submitting the form"** if not on the submit handler.
If anyone has a clue about that ...

---
Tags: 7, users
---


# Question
Title: Show different fields on node edit and node view depending on the sub-type of the node
I have a specific node type that I want to show/hide different fields in the page layout for both the node form and when viewing the node.

For various reasons I don't want to have to create a new/separate Node type for each. Not sure how best to achieve this in Drupal 7?

There are actually two content types involved here. 'Open Calls' and 'Projects'

I have an idea submission system built in D7. Users login and browse through available 'Open Calls' for projects.

Each call has a link to 'Apply Now'. This link takes users to the new node creation for a 'Project'.

Each 'Project' has an entity reference field that is required that links the Project to the Open Call. This field is auto populated when they click the Apply Now button.

Ideally, I would be able to specify in the Open Call (rather than the project) what kind of project page layout they see when clicking the Apply Now link.

I want to be able to post Open Calls for slightly different kinds of projects. For example an Open Call for artworks (paintings etc.), or alternatively an Open Call for performances.

Clicking apply now on each of these should take the user to the New Project node creation screen with different fields for artworks / performances. (Some fields will appear on both).

# Answer
Take a look at the Conditional Fields module. You could make some fields dependent on one checkbox selection and other fields dependent on a second checkbox selection.

> Define dependencies between fields based on their states and values.
>
> Conditional Fields for Drupal 7 is an user interface to the new States API, plus the ability to modify fields appearance and behavior on certain conditions when viewing content.
>
> ### Description
>
> Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition. When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API.
>
> A simple use case would be defining a custom “Article teaser" field that is shown only if a "Has teaser" checkbox is checked, but much more complex options are available.
> 3 votes

# Answer
Use Field Permissions module

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Deleting translate interface strings programmatically or using drush
I need to delete some translated strings added using t() function, I've about 17000 string to delete is there a way to delete it using a SQL query or drush command? in which table those strings are stored?

Thank you.

# Answer
Drupal 7 store translate interface strings in :

1. Table source `locales_source`
2. Table Target `locales_target`
> 1 votes

---
Tags: 7, drush, i18n-l10n
---


# Question
Title: How can I mass delete multilingual strings when I know only the page that added them?
Some inappropriately placed `t()` functions generated a large number of strings that I do not want to translate. Unfortunately, using the `Refresh strings` i18n page does not clear these strings.

On the `Translate interface` page, I can search for the strings one by one and delete them but there are about a hundred so I would prefer to do it another way. Thankfully, they were all created on two pages, so I can search by the path (`/ja/mypage`) and delete them that way. However, I still have to click each link.

Is there a faster way?

# Answer
```
drush sql-query "delete from locales_source where location = '/ja/mypage'"

```

Or delete by strings, for examples if all strings you want to delete contains "hoof" :

```
drush sql-query "delete from locales_source where source like '%hoof%'"

```
> 1 votes

---
Tags: i18n-l10n
---


# Question
Title: How to get Views field value in View twig template if the Views field is set to 'Exclude from display'?
I have a Views fields twig template where I want to print the Views fields values manually.

For example, using: {{ fields.body.content }}

But this only works if the Views field is not excluded from the display.

Is there a way for me to print Views fields values if they are hidden (excluded from display)?

# Answer
You shall do it like this:

{{ row.\_entity.field\_myfield.value }}
> 2 votes

---
Tags: views, 8
---


# Question
Title: How to Replace Value of CKEditor Field via Custom Module
Drupal 8.x

I have a custom module and I am trying to wrap any string beginning with a hash tag in an 'a' tag via RegEx.

**MYMODULE.module:**

```
function MYMODULE_preprocess_node(&$variables) {

    if ($variables['elements']['#node']->get('field_name')->value != '') {

        kpr($variables['elements']['#node']->get('field_name')->value);
        $variables['elements']['#node']->get('field_name')->value = $newValue;
        kpr($variables['elements']['#node']->get('field_name')->value);

    }

}

```

I've left the two *kpr()* statements which do show initial value, and the RegEx replaced value, correctly. However, the value of the CKEditor field is not being replaced. It appears my 'equals' operator has no effect.

How do I replace the value of the CKEditor with my updated value?

Referencing this Stackoverflow question: https://stackoverflow.com/questions/22040272/using-php-replace-regex-with-regex

# Answer
I have had some success.

**MYMODULE.module:**

```
use Drupal\Core\Entity\EntityInterface;

function MYMODULE_node_presave(EntityInterface $entity) {
  if ($entity->hasField('field_name')) {
    $entity->get('field_name')->value = $newValue;
  }
}

```
> 0 votes

---
Tags: 8, hooks
---


title: Not getting complete URL parameters

text:
# Question
Title: Not getting complete URL parameters
My url is `node/3?filter-value=67&filter-value=80` and when i try to do this code:

```
$param = \Drupal::request()->query->all();`

$param['filter-value']

```

It shows the value `80` only. I want to get both of them.

# Answer
> 2 votes
You’ll need to use array notation in the URL:

> node/3?filter-value\[\]=67&filter-value\[\]=80

Then `get(‘filter-value’)` will return an array with both values.

See https://stackoverflow.com/questions/6243051/how-to-pass-an-array-within-a-query-string for more information.

# Answer
> 3 votes
if you don't want to change the structure of your url.

you can use Explode function

I have made a helper function try it out:

```
function getParamsOfUrlWithSameKey(){
  $current_uri = \Drupal::request()->getRequestUri();
  $items = explode('?', $current_uri);
  $res_param = [];
  if (isset($items[1])) {
    $params = explode('&', $items[1]);
    foreach ($params as $param) {
      $param_value = explode('=', $param);
      $key = $param_value[0];
      $value = $param_value[1];
      $res_param[$key][] = $value;
    }
  }
  return $res_param;
}

```

The return of this function will be something like:

```
array:1 [▼
   "filter-value" => array:2 [▼
     0 => "67"
     1 => "80"
   ]
 ]

```

---
Tags: 8, uri
---


title: Search is not throwing any result

text:
# Question
Title: Search is not throwing any result
It is Drupal 7.

This is kind of strange behaviour of the website.

This is my website http://www.protecdental.com. If you visit this website, you will see the right-hand top search field. Please see the screenshot https://snag.gy/LfCDxs.jpg

If you type any junk keyword (That means the site will definitely throw 0 results) for example "werewe" then you will see the proper search result page with no result.

But if you type a keyword related to the website's content for example "dental" or "contact" or any related meaning full keyword then you will see the broken page with no content at all.

Not too sure the issues is: it seems like if there is a search result data, then it is somehow breaking the page:

I didn't find any error log for it even when I tried watchdog.

* I cleared the cache
* I re-indexed the search
* I manually ran the cron

But no luck. Can anyone please help to at least narrow down the cause of this issue.

# My default search result template:

```
<?php if ($search_results): ?>
    <h2><?php print t('Search results');?></h2>
    <ol class="search-results <?php print $module; ?>-results">
        <?php print $search_results; ?>
    </ol>
    <?php print $pager; ?>
<?php else : ?>
    <h2><?php print t('Your search yielded no results');?></h2>
    <?php print search_help('search#noresults', drupal_help_arg()); ?>
<?php endif; ?>

```

# Answer
> 0 votes
No problem, yeah when you see an error page like that, most of time the issue is in one of the template files.

---
Tags: search
---


# Question
Title: Webform field options missing Entity Reference?
We're using Webform 3.27 in Drupal 7 (not my call, don't yell at me) and it looks like one of the field type options should be Entity Reference, but we don't have that option. Not sure what's going on there.

Ultimately what I'm trying to do is add an Entity Reference select field that, when an option is selected, will populate up to four other existing fields (like Entity Reference Autofill works in a Content Type). Is that even possible using Webform?

# Answer
This module might do what you want, webform references.

From description,

> Provides a webform component that can reference a node/term/user in webform. It provides "Select List", "Autocomplete", "Checkbox" and "Radio" as widget. A view with entityreference display can also be used to get the list as options.
> 2 votes

---
Tags: 7, entities, webforms
---


# Question
Title: Using modules "not covered by Drupal’s security advisory policy"
I would like to use a Drupal 7 module that is "not covered by Drupal’s security advisory policy", specifically the Conditional Fields module.

It would allow me to do exactly what I need. It looks like this module is pretty actively used and maintained but I am not sure how worried I should be about using a module that I won't get updates about if any security issue should arise.

Any advice? Is coding something like this (using hook\_form\_alter and states) myself a safer approach?

# Answer
According to the Security advisory process and permissions policy, modules that have an alpha, beta, or rc (relase candidate) status are not covered by this policy, and security advisories will not be reported for these projects. At the time of writing, Conditional Fields has recommended releases for Drupal 7 and 8 that are both in "alpha" stage. Even without security advisories, you can still choose to be notified when the module is updated.

Since module releases and their status are arbitrarily assigned by project maintainers, only you can judge whether you should use a module marked as not being covered by Drupal’s security advisory policy. One maintainer's "alpha" module, would be a "1.0" version to another maintainer.

You should examine the maintainer's credibility, history on Drupal.org, the project's popularity, and the speed at which issues are resolved or responded to. Many popular and public sites *do* make use of "beta" or other modules.

Coding your own module to duplicate the functionality of a module that already exists seems more likely to introduce security vulnerabilities that can potentially only be diagnosed or fixed by one person: you. Using an "alpha" module with a competent maintainer and an active community of users seems far more advisable.
> 5 votes

# Answer
Be careful in "only" using the *security advisory*. Instead you may want to consider many more criteria to help you make decissions. As I documented in (what I call) maintenance scorecards. In that case they relate to charting modules, but you can apply them for any set of modules of course.

These are IMO the criteria you should also consider:

* Nr of open bugs
* No RTBC'd items
* Last commits
* Community docu
* Support 2 core releases
* DEV release for D8
* Nr of Committers
* SimpleTests or Unit Tests
* Automated testing enabled
* Downloads / installs ratio
* Contributing users in commits
> 2 votes

---
Tags: 7, security
---


# Question
Title: Link field sanitizes query string from foo.cgi?123456 to foo.cgi?0=
On my Drupal 8 site I have a custom content type that contains, among other fields, a link field. When I create a node and add the following external URL as one of the values of the link field:

```
http://www.isfdb.org/cgi-bin/title.cgi?1580

```

the rendered page contains this mangled query string:

```
http://www.isfdb.org/cgi-bin/title.cgi?0=

```

Is this the result of some misconfiguration on my part? How can I get the rendered page to use the correct URL?

I should probably mention that the D8 site is the result of a migration from a D7 site. On the old D7 site, the same URL was rendered correctly. The new Drupal 8 site uses Drupal version 8.6.1.

# Answer
> 2 votes
I have tracked down the problem deep into Drupal Core itself. The problem actually consists of two bugs, not just one!

**EDIT:** For the first bug I have submitted a new Drupal Core issue (issue 3007243). For the second bug I have contributed my analysis to the discussions of two existing Drupal Core issues (issue 2987114 and issue 1464244).

---

Let's start at the beginning. The Link module works with the Drupal Core class `Url`. At the appropriate time, the Link module gets the URI from the `Url` object by invoking its `toString()` method. For external links, this method makes use of the Drupal Core class `UnroutedUrlAssembler`, by invoking its `assemble()` method, which in turn invokes another method `buildExternalUrl`.

Bug #1 is in `buildExternalUrl`: The method contains this line:

```
$options['query'] = NestedArray::mergeDeep($parsed['query'], $options['query']);

```

This is wrong because it doesn't preserve integer keys! Remember that the query parameter in my URL is numeric (1580, see the OP)? The above line causes the 1580 to be discarded, instead the result is the 0 (zero) that we have seen in the mangled query string. The correct line would be this. The all-important thing is the `TRUE` parameter which tells `NestedArray::mergeDeepArray()` to preserve integer keys.

```
$options['query'] = NestedArray::mergeDeepArray(array($parsed['query'], $options['query']), TRUE);

```

Unfortunately this is not the end of the road. Where does the "=" character in the mangled query string come from? The `assemble()` method of the `UnroutedUrlAssembler` class first breaks down the URI into its individual parts like this:

```
$parsed = UrlHelper::parse($uri);

```

Then it reassembles the URI, piece by piece. The query string gets reassembled with this line:

```
$uri .= '?' . UrlHelper::buildQuery($options['query']);

```

The `UrlHelper::buildQuery` function generates "key=value" pairs from the entries in the supplied array (`$options['query']`). It omits the "=value" part if - and only if - the value of an array entry is `NULL` (the check is made with the PHP function `isset()`). As I have found out, for my example URL the value of the array entry is **NOT** `NULL`, it's an empty string - and that's what causes the "=" character to be generated.

But where is the empty string coming from? The function `UrlHelper::parse()` uses the PHP built-in function parse\_str() to break down the query string into its parts, and that PHP function is the culprit! Here's the proof:

```
php -r '$query="1580"; $arr = array(); parse_str($query, $arr); echo "isset: " . isset($arr[1580]) . "\n"; echo "+" . $arr[1580] . "+\n"; echo "gettype: " . gettype($arr[1580]) . "\n";'
isset: 1
++
gettype: string

```

So to ultimately fix the problem, either `parse_str()` would have to change its buggy query string parsing, or the Drupal function `UrlHelper::parse()` would have to use some other function to parse query strings.

---
Tags: 8
---


title: How do I create a TEXT column?

text:
# Question
Title: How do I create a TEXT column?
I am trying to create a TEXT column.

```
function _mymodule_installed_fields() {
  return array(
    'mymodule_summary' => array(
      'field_name' => 'mymodule_summary',
      'label' => $t('Summary'),
      'type' => 'varchar',
      'not_null' => TRUE,
      'length' => '400',
    );
  );
}

```

I get a VARCHAR column. How do I get a TEXT column?

# Answer
Given the code you are showing, which is similar to the code shown in Fields API, create new content type I take you are adding a new field to a content type, not simply creating a new table field for a database table. This explains why the code is using properties like *field\_name* or *label* that implementations of hook\_schema() would not use.

The values you can use for the *type* property are the ones described from the `hook_field_info()` implementations. In particular, if you look at the code of `text_field_info()`, you will see the following descriptions.

* *text*: The field stores varchar text in the database
* *text\_long*: The field stores long text in the database

The confirm of what database field type is used for each entity field type comes from the implementations of `hook_field_schema()`, in particular from `text_field_schema()`.

```
case 'text':
  $columns = array(
    'value' => array(
      'type' => 'varchar',
      'length' => $field['settings']['max_length'],
      'not null' => FALSE,
    ),
  );
  break;
case 'text_long':
  $columns = array(
    'value' => array(
      'type' => 'text',
      'size' => 'big',
      'not null' => FALSE,
    ),
  );
  break;

```

So, if you effectively need to use a *TEXT* database column type, you need to use the following definition for the field.

```
array(
  'mymodule_summary' => array(
    'field_name' => 'mymodule_summary',
    'label' => $t('Summary'),
    'type' => 'text_long',
  );
);

```
> 0 votes

---
Tags: 7, database
---


# Question
Title: CKEditor oEmbed Plugin Shows up in config but not in actual Editor instance
The issue I'm having is very similar to this question, but the solutions here did not work for me.

The steps I took:

1. Downloaded the latest version of the oEmbed plugin from https://ckeditor.com/cke4/addon/oembed.
2. I extracted the `oembed` directory from the archive and placed that in a custom Drupal module that I already had. This module was used to create simple CKEditor button plugins and worked fine with them.
3. I went to the configuration page for `basic_html` and `full_html` editors and saw that the oEmbed button was one of the new options (`/admin/config/content/formats/manage/basic_html`).
4. I moved the oEmbed button to the "Active Toolbar" as well as some other custom plugins.
5. I went to edit some content where the WYSIWYG would show up
6. The other custom buttons showed up, but the oEmbed one did not, despite the fact that I could see it on the config page.

I've tried an older version of the oEmbed plugin from the download page, as well as clearing my cache many times with `drush cr`, but still no luck getting it to show up.

What's weird is that when I load the node edit page with the Chrome console open, I can see that *the Javascript/CSS for the oEmbed plugin is loading and executing*. The button icon though is never requested.

The Drupal Plugin looks like this

```
namespace Drupal\custom_ckeditor\Plugin\CKEditorPlugin;

/**
 * Defines the OEmbed plugin, with CKEditor.
 *
 * @CKEditorPlugin(
 *     id = "oembed",
 *     label = @Translation("OEmbed Plugin")
 * )
 */
class OEmbed extends extends PluginBase implements CKEditorPluginInterface, CKEditorPluginButtonsInterface
{
    protected $pluginName = 'oembed';

    public function getButtons()
    {
        $iconImage = $this->getIconPath();
        return [
            'OEmbed' => [
                'label' => t('Insert OEmbed'),
                'image' => $iconImage,
            ]
        ];
    }

    // Other required functions such as getLibraries() and getDependencies() all return an empty array or false and are omitted from this example.

}

```

I'm using Drupal 8, with CKEditor v4.7.2.

# Answer
I figured it out. On the Drupal side, everything was configured correctly. The error was in the Javascript. The original `plugin.js` file has the following:

```
editor.ui.addButton('oembed', {
                    label: editor.lang.oembed.button,
                    command: 'oembed',
                    toolbar: 'insert,10'
                });

```

I modified this to

```
editor.ui.addButton('OEmbed', {
                    label: editor.lang.oembed.button,
                    command: 'oembed',
                    toolbar: 'insert,10'
                });

```

Note the name passed to `addButton()` from `oembed` to `OEmbed`. I think there was some conflict in naming it `oembed`, possibly from some existing functionality. Not sure, but that was the fix for me.

In addition, I should note that for the *Basic Editor*, I had to modify the HTML filter to allow tags that the oEmbed plugin added to the source view. Hope this helps someone.
> 0 votes

---
Tags: wysiwyg, plugins
---


title: Cygwin Patch fails

text:
# Question
Title: Cygwin Patch fails
I have failed to get my first patch to implement. I loaded cygwin, maneuver to the directory, and enter patch -p0 \< `ThePatchName`.patch

Cygwin returns bash: patch: command not found

I searched the cygwin/bin directory and there is an executable for pathk.exe, but not patch.exe. I cannot find documentation on these commands at cygwin, so I do not know if they are the same. Does anyone know about this?

# Answer
This is not quite a Drupal question. That said, patch for Cygwin needs to be installed. Rerun your Cygwin "setup" program, and search for "patch". In my setup, it is under the "Utils" category. Once you find it, select it and then hit "Next" to finish the install. It should be available.
> 2 votes

# Answer
What I did:

Patch is not automatically installed. I went to cygwin.com/install.html, selected cygwin packages menu item, reloaded setup.exe and found patch buried in a long list of commands. after installing it, everything worked.

There are a couple of problems to watch out for using cygwin.

Moving to the directory in using this linux tool is different than DOS. Enter this: cd /cygdrive/c/theRestofthePath. Note that it does not recognize spaces unless they are preceded by a backslash.

The patch command is: patch -p0
> 1 votes

# Answer
Use: `apt-cyg install patch`. (It's in its own package.)
> 0 votes

---
Tags: 7, version-control
---


# Question
Title: Querying a custom table does not return latest results for anonymous user
I have a custom module and a simple custom table in the database. When I try to query the table to get the row, it seems Drupal 8, or maybe mysql, is caching the results.

```
$connection = \Drupal::database();

$result = $connection->query("SELECT SQL_NO_CACHE * FROM {mytable} WHERE id = (:id)", [':id' => $key]);

$result->fetch()

```

We get the latest data if a I am logged in to Drupal, but the data is cached if we are not logged in.

# Answer
> 1 votes
Try to user drupal select instead of normal query something like following:

```
  // Add this use at the top of the file
  use Drupal\Core\Database\Database;

  $connection = Database::getConnection();
  $query = $connection->select('mytable', 'my_table')
    ->condition('id', $key, '=');
  $result = $query->execute()->fetchAll(PDO::FETCH_ASSOC);

```

---
Tags: 8, database
---


# Question
Title: How to show entityQuery results as block
I use entityQuery to retrieve nodes related to actual content. Now I don't know how to add them to template and show them in my theme.

In Drupal 7 I used Bean module to create blocks as entities. The module states the following, which I don't fully understand:

> As Drupal 8 supports fields on its block entities, this module is not needed for new sites.

So how do I get the results of my entityQuery into blocks to afterwords use them twig templates?

# Answer
> 2 votes
Try the above suggestion:
Create Custom Block for example `MyBlock`.

In the your **src/Plugin/Block/MyBlock.php** File. implement `build method` and `getNodesBuild method` to get the nodes build:

```
  public function build() {
    return array(
      '#theme' => 'mymodule_my_block',
      '#nodes_build' => $this->getNodesBuild(),
    );
  }

```

**NB:** Change the `$nids` array by the result of your Query.

```
  /**
   * This function return view_builder of list of nodes.
   * @return array
   */
  protected  function  getNodesBuild(){
    //- Replace this by the result of your Query
    $nids = [38, 39];
    //- Get the current lang
    $language_manager = \Drupal::service('language_manager');
    $language = $language_manager->getCurrentLanguage()->getId();
    //- Get view_builder for node entity type
    $entity_type_manager = \Drupal::service('entity_type.manager');
    $view_builder = $entity_type_manager->getViewBuilder('node');
    //- Load nodes
    $nodes = Node::loadMultiple($nids);
    return $view_builder->viewMultiple($nodes, 'teaser', $language);
  }

```

Implement `hook_theme` in your **mymodule.module**

```
/**
 * Implements hook_theme().
 */
function mymodule_theme($existing, $type, $theme, $path) {
  return [
    'mymodule_my_block' => [
      'variables' => [
        'nodes_build' => [],
      ],
      'template'  => 'mymodule-my-block',
    ],
  ];
}

```

**templates/mymodule-my-block.html.twig**

```
  {{ nodes_build }}

```

# Answer
> 0 votes
Depending on the complexity of your query, you probably rather want to use views to build the query. Can you please post your query?

If you could use views instead of an EntityQuery, creating a block display and adding that block to your theme will probably be quicker and less custom code to maintain compared to writing a custom query and block plugin.

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


title: Sale price not showing in cart page

text:
# Question
Title: Sale price not showing in cart page
I have added a product in commerce. Each products have a price and sale price. In product listing page the price is cutout and sale price is displayed. When a product is added to the cart, sale price is not calculated in checkout. Instead original price is calculated. Since i'm new in drupal, I have no idea to solve this problem.

# Answer
> 0 votes
Could you change the field labels and make the field used for the price calculation the actual sale price field? The other one you could possibly call something like "original price" or so.

If this isn't feasible and you're on Drupal 8, it sounds like you want to implement a custom price resolver.

# Answer
> 0 votes
You need to change one of your views:

`Shopping cart summary (Cart line item summary displayed during checkout.)` I think just that you need.

Or `Shopping cart block(Display a list of line items added to cart.)`

If above mentioned is not the answer to your question. You need to calculate new price for product item on checkout form page.

For that you need to implement `hook_form_FORM_ID_alter(&$form, &$form_state, $form_id)` function in your custom module, then grabbing price from `$form_state` array you need to change it for your needs then assign new price to a `$form_state` array.

---
Tags: commerce
---


# Question
Title: Getting an fatal error message when trying to render custom blocks on my node twig template
I'm trying to render or print my custom blocks on my node twig template and currently receiving a fatal error message.

`Argument 1 passed to Drupal\block\BlockViewBuilder::view()`

Here is the snippet of code I'm working on my `.theme` file

```
function iom_preprocess_node(&$variables) {

    $block = \Drupal\block\Entity\Block::load(917);
    $block_content = \Drupal::entityTypeManager()
      ->getViewBuilder('block')
      ->view($block);
}

```

---

`$block` returns `NULL` when I try to do a `dump($block)`

```
$block = \Drupal\block\Entity\Block::load(917);
dump($block);

```

---

Tried using `twig tweak` also to resolve the issue instead of having to pre-process it but no luck

`{{ drupal_block('twitterfeed') }}`

# Answer
> 2 votes
You can print blocks directly using Twig Tweak

> ```
>   {# No need to configure this block on "admin/structure/block" page. #}
>   <dt>Block:</dt>
>   <dd>{{ drupal_block('system_branding_block', {label: 'Branding', use_site_name: false}) }}</dd>
>
>   {# Bypass block.html.twig theming. #}
>   <dt>Block (without wrapper):</dt>
>   <dd>{{ drupal_block('system_branding_block', wrapper=false) }}</dd>
>
> ```

Source: Cheat sheet

Do not use the block's machine name, enable the devel and in block configuration click on Devel tab to get the Plugin ID.

For example, the Site Branding Block has machine name of `sitebranding`, but the plugin ID is `system_branding_block`

# Answer
> 1 votes
Can you try this:

```
$bid = ?;
$block = \Drupal\block_content\Entity\BlockContent::load($bid);
$render = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block);
return $render;

```

---
Tags: 8, theming
---


title: How to get methods from vendor classes

text:
# Question
Title: How to get methods from vendor classes
I use get\_class\_methods to get classes for Drupal classes, for example I go to devel/php and run:

```
$coupon = \Drupal::entityTypeManager()
  ->getStorage('commerce_promotion_coupon')->load(3);

ksm(get_class_methods($coupon));`

```

But If I want to get list of classes for some vendor library I don't know how to get them.

# Answer
> 1 votes
That's off-topic. But try this:

```
$ composer require ramsey/uuid

```

And then put the whole use statement without `use` into `get_class_methods()`:

```
ksm(get_class_methods('Ramsey\Uuid\Uuid'));

```

---

Putting that into a `new ReflectionClass()` would actually give you much more useful output:

```
$class = new ReflectionClass('Ramsey\Uuid\Uuid');
$methods = $class->getMethods(ReflectionMethod::IS_PUBLIC);
ksm($methods);

```

---
Tags: 8
---


title: Choose a destination after drush cex

text:
# Question
Title: Choose a destination after drush cex
1. In my `sites/default/settings.php` I changed:

```
$config_directories = array(
    CONFIG_SYNC_DIRECTORY => 'sites/default/config-sync',
);

```
2. I created the folder `config-sync` in `sites/default/`
3. When I do `drush cex` I get this message in my Terminal window:

> Choose a destination. \[0\] : Cancel
> \[1\] : sync
> \[2\] : staging

What do I have to do? Because I want **all** my configuration files in `sites/default/config-sync` because this directory is tracked by Git.

# Answer
> 3 votes
You just need to execute the command with the "destination" parameter:

```
$ drush cex sync

```

as *CONFIG\_SYNC\_DIRECTORY* is the same as *$config\_directories\['sync'\]*

# Answer
> 0 votes
You must define your config directories in `settings.php`, like this:

```
$config_directories['import'] = '../config/import';
$config_directories['export'] = '../config/export';

```

Now you can use these with drush:

```
drush cex export
drush cim import

```

---
Tags: 8, drush, configuration
---


# Question
Title: Is db_set_active a global or local setting?
I need to run a new query on another database.

I configured the **settings.php**

```
 $databases = array (
      'default' =>
      array (
        'default' =>
        array (
          'database' => 'db_name',
          'username' => 'db_usr',
          'password' => '',
          'host' => 'localhost',
          'port' => '',
          'driver' => 'mysql',
          'prefix' => '',
        ),
      ),
      'slave' =>
      array (
        'default' =>
        array (
          'database' => 'db_name',
          'username' => 'db_usr',
          'password' => '',
          'host' => 'localhost',
          'port' => '',
          'driver' => 'mysql',
          'prefix' => '',
        ),
      ),
    );

```

and this is my custom function:

```
    function myModule_test()
{

    db_set_active('slave');

    sleep(90);

    $view = views_get_view('test_view');
    $view->set_display('page');
    $view->pre_execute();
    $view->execute();

    print $view->render();
    db_set_active();

    }

```

the query is performed on the second database, what I do not understand is if the database change is **local or global**, because during the `sleep (90)` I tried to insert a new 'article' content and it has been inserted into the 'default' database.

# Answer
> 1 votes
It's a per-request global setting. `db_set_active` calls:

```
Database::setActiveConnection($key);

```

Which sets the static `$activeKey` property of the `Database` class.

`Database::getConnection()`, which is where the connection for all queries comes from, then uses that same static `$activeKey`.

So once you've used `db_set_active`, all queries in that request will use the new connection until changed again.

It doesn't persist across multiple requests.

---
Tags: 7, views, database
---


# Question
Title: View all Nodes & Comments by logged in user
Is it possible to show all comments and nodes created by a logged in user in one view?

Would like to display fields. Show title and time stamp when the node OR comment was created.

Another challenge is that I would like to sort by the newest Node / Comment. This is a little confusing for me since we are dealing with two different type of entities.

# Answer
> 0 votes
Yes, you can do it in one view. Follow below steps

1. Create page view
2. Add the title and comment field
3. Add author by field with choose the radio button *Provide default value* then \*Type - User ID from logged in user * in contextual filter
4. Add last update filed comment time field in sorting then add another one for node created time stamp.

It will resolve your problem.

---
Tags: views, 8
---


# Question
Title: How can I correctly include a (non-fragment) # in a URL?
I need to build an external URL that looks like this:

```
https://searchapp.foo.gov/search-org/#/collection-name?q=search%20terms%20here

```

First thought is that /#/ is entirely invalid according to RFC 3986, unless I'm reading it incorrectly, but that's what I've been given. So I'm building it like so:

```
$base_url = 'https://searchapp.foo.gov/search-org/#/collection-name';
$options = [
  'absolute' => TRUE,
  'https' => TRUE,
  'query' => [
    'q' => $form_state->getValue('search'),
  ],
];
$url = Url::fromUri($base_url, $options)->toString();

```

Instead of the expected output, I find that my querystring is appearing before the #:

```
https://searchapp.foo.gov/search-org/?q=search%20terms%20here#/collection-name

```

I've tried using /%23/ instead of /#/, and that fixes the problem with the querystring being out of place, but creates a new problem by url encoding the %, so that I wind up with /%2523/.

I'm guessing this is a problem with hash segment handling. Is there a right way to handle a URL like this?

# Answer
You are correct ... it is invalid to use the "#" for anything other than a fragment. That does not mean that someone doesn't have their web servers setup in such a way that "#" can be used in the URL itself.

> I'm guessing this is a problem with hash segment handling. Is there a right way to handle a URL like this?

To be clear, there is no problem with how Drupal is handling URLs ... Drupal is following the spec. I think your best bet in this case (short of yelling at whoever is giving you this URL for doing so) is to extend the Url class and replace the formUri method to handle your weird case.

Your other option is to do something really hacky like putting an easily replaced string in the URL and then doing a string replace at the last minute before displaying it.
> 1 votes

---
Tags: 8, uri
---


# Question
Title: How to add two extra buttons in a form to do extra actions with form data
I have a simple custom form with 3 submit buttons - one that calls the default hook\_form\_submit and generates a table. The submit as the rebuild as TRUE:

```
$form_state['rebuild'] = TRUE;

```

that shows the complete form with the 3 buttons and the tables.

I need the 2 extra buttons to call different functions but I need inputs from the form itself or the table array.

At the moment, with the code I have, I can't access the form data and also, the tables created by the main submit disappear when I click the 2 extra buttons.

My code:

```
function MYMOUDLE_form($form, &$form_state) {
    $form['container']['submit'] = array(
        '#type' => 'submit',
        '#value' => t("Submit Form"),
    );

    $form['container']['export_1'] = array(
        '#type' => 'submit',
        '#value' => t("Export - 1"),
        '#submit' => array('MYMOUDLE_export_1'),
    );

    $form['container']['export_2'] = array(
        '#type' => 'submit',
        '#value' => t("Export - 2"),
        '#submit' => array('MYMOUDLE_export_2'),
    );

    return $form;
}

function MYMOUDLE_form_submit($form, &$form_state) {
    # do my stuff - generate tables
}

function MYMOUDLE_export_1($form, $form_values) {
    dpm($form_values);
    $someData1 = MYMODULE_handleFormData1($formValue1, $formValue2, $formValue3);
    drupal_set_message('Action for export 1 was done successfully.');
}

function MYMOUDLE_export_2($form, $form_values) {
    dpm($form_values);
    $someData2 = MYMODULE_handleFormData2($formValue1, $formValue2, $formValue3);
    drupal_set_message('Action for export 2 was done successfully.');
}

```

# Answer
Rather than write submit function for each button use *$form\_state\['triggering\_element'\].* This will provide you the which button is clicked with form data in default hook\_form\_submit
> 1 votes

---
Tags: forms
---


# Question
Title: Alter existing form and add element with an ajax "add more" button
I am altering the field settigns form, in order to add custom settings. I used the example module as a guide and added my code in the following manner:

```
/**
 * Implements hook_form_FORM_ID_alter() for 'field_config_edit_form'.
 */
function fd_image_form_field_config_edit_form_alter(array &$form, FormStateInterface $form_state) {

  // Gather the number of names in the form already.
  $num_names = $form_state->get('num_names');
  // We have to ensure that there is at least one name field.
  if ($num_names === NULL) {
    $name_field = $form_state->set('num_names', 1);
    $num_names = 1;
  }

  $form['#tree'] = TRUE;
  $form['names_fieldset'] = [
    '#type' => 'fieldset',
    '#title' => t('People coming to picnic'),
    '#prefix' => '<div id="names-fieldset-wrapper">',
    '#suffix' => '</div>',
  ];

  for ($i = 0; $i < $num_names; $i++) {
    $form['names_fieldset']['name'][$i] = [
      '#type' => 'textfield',
      '#title' => t('Name'),
    ];
  }

  $form['names_fieldset']['actions'] = [
    '#type' => 'actions',
  ];
  $form['names_fieldset']['actions']['add_name'] = [
    '#type' => 'submit',
    '#value' => t('Add one more'),
    '#submit' => ['_fd_image_add_one'],
    '#ajax' => [
      'callback' => '_fd_image_add_more_callback',
      'wrapper' => 'names-fieldset-wrapper',
    ],
  ];
  // If there is more than one name, add the remove button.
  if ($num_names >= 1) {
    $form['names_fieldset']['actions']['remove_name'] = [
      '#type' => 'submit',
      '#value' => t('Remove one'),
      '#submit' => ['_fd_image_remove_callback'],
      '#ajax' => [
        'callback' => '_fd_image_add_more_callback',
        'wrapper' => 'names-fieldset-wrapper',
      ],
    ];

    $form_state->setCached(FALSE);
  }
}

```

I also added my ajax callbacks:

```
/**
 * Callback for both ajax-enabled buttons.
 *
 * Selects and returns the fieldset with the names in it.
 */
function _fd_image_add_more_callback(array &$form, FormStateInterface $form_state) {
  return $form['names_fieldset'];
}

/**
 * Submit handler for the "add-one-more" button.
 *
 * Increments the max counter and causes a rebuild.
 */
function _fd_image_add_one(array &$form, FormStateInterface $form_state) {
  $name_field = $form_state->get('num_names');
  $add_button = $name_field + 1;
  $form_state->set('num_names', $add_button);
  // Since our buildForm() method relies on the value of 'num_names' to
  // generate 'name' form elements, we have to tell the form to rebuild. If we
  // don't do this, the form builder will not call buildForm().
  $form_state->setRebuild();
}

/**
 * Submit handler for the "remove one" button.
 *
 * Decrements the max counter and causes a form rebuild.
 */
function _fd_image_remove_callback(array &$form, FormStateInterface $form_state) {
  $name_field = $form_state->get('num_names');
  if ($name_field > 1) {
    $remove_button = $name_field - 1;
    $form_state->set('num_names', $remove_button);
  }
  // Since our buildForm() method relies on the value of 'num_names' to
  // generate 'name' form elements, we have to tell the form to rebuild. If we
  // don't do this, the form builder will not call buildForm().
  $form_state->setRebuild();
}

```

Now when I go to the field settings form, I see my form elements and I do see the add more button. I can click the add more button 1 time and it adds an extra element, but the problem is, I cannot add more than 2. Once the page have 2 elements subsequents clicks on "add more" result in an ajax callback that does nothing.

After debugging it looks like the `$num_names` is not being correctly stored and increased. I am assuming that is because the Examples module has it's own `buildFrom` method while in my case I am only altering. What is the correct way of adding an ajax element to an existing form?

# Answer
> 0 votes
Answering my own question after resolving the issue. Removing `$form_state->setCached(FALSE);` fixed the issue.

However, I am not sure why it did or whether this have negative consequences. Hope this helps others.

---
Tags: 8, forms, ajax
---


title: Pantheon Site to Local Environment

text:
# Question
Title: Pantheon Site to Local Environment
I have recently inherited a Drupal 7 site running on Pantheon.io
I have set up a local Drupal 7 server for a dev/test environment that is working flawlessly as a fresh install.
However, once I put the code, files, and database backups in place, my content appears, but there is no theme or CSS present, none of my links work, etc.

I have a feeling there is a simple fix for this, but I have exhausted my limited knowledge of this platform.

# Answer
1. Clone the code
2. Import database
3. Configure your settings.php file
4. Get public files; copy them to sites/default/files
5. Compile CSS and JavaScript in the theme, if it is required
6. Clear the cache

Those step should works.

If Backup and Migrate module installed in Pantheon.io you can get the database and public files from https://pantheon.io/admin/config/system/backup\_migrate.
> 0 votes

---
Tags: 7, backups
---


# Question
Title: Custom form submit handler is called, but node is not saved
There are many questions about a custom form submit handler not being called, but in my case, the handler is being called; however, the entity is not being saved. Specifically, I have a custom submit handler on a content type; when I press the button to call the handler, nothing is saved in the database:

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

  $form['actions']['submit_publish'] = array(
    '#type' => 'submit',
    '#weight' => 999,
    '#button-type' => 'danger',
    '#value' => t('Submit for approval'),
    '#submit' => array('MYMODULE_draft2submit_callback'),
  );
}

function MYMODULE_draft2submit_callback(array &$form, FormStateInterface &$form_state) {
  $form_state->setValue('moderation_state', 'submitted');
}

```

So I thought since the node is not being saved, maybe I have to do it manually. Following this article, I did this:

```
function MYMODULE_draft2submit_callback(array &$form, FormStateInterface &$form_state) {
  $form_state->setValue('moderation_state', 'submitted');
  $node = $form_state->getFormObject()->getEntity();
  $node->save();
}

```

However, in this case, the node is saved, but none of the submitted values (the node body, for example) are saved; everything added by the user is ignored, as is the `setValue()` in my callback.

**I only want to set the `moderation_state` in my custom form submit handler; in all other ways, I want my custom submit handler to be the same as the normal submit handler (i.e., I want it to save the node).** What am I doing wrong?

# Answer
Check that the action you are trying to submit is the correct one. In my case when I had to add a submit handler, I used `$form['actions']['submit']['#submit'][] = 'my_custom_submit_handler';` Also, try to add the an extra submit handler and not overwrite the existing one. Finally, try to save your entity in your submit handler and not in the callback. For me also worked the `$entity = $form_state->getBuildInfo()['callback_object']->getEntity();` in order to get the entity and alter it in my custom handler.
> 4 votes

# Answer
As pointed out by @Ismini, the entity has to be saved in the submit handler. The way to do this is, as pointed out by @4k4, to copy the submit handlers for the new button from the original submit handler. The corrected code is shown below.

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

  $form['actions']['submit_publish'] = array(
    '#type' => 'submit',
    '#weight' => 999,
    '#button-type' => 'danger',
    '#value' => t('Submit for approval'),
    '#submit' => array_merge($form['actions']['submit']['#submit'], array('MYMODULE_draft2submit_callback')),
  );
}

function MYMODULE_draft2submit_callback(array &$form, FormStateInterface &$form_state) {
  // Getting the entity.
  $entity = $form_state->getFormObject()->getEntity();
  // Changing the moderation state.
  $entity->set('moderation_state', 'submitted');
  // Saving the entity.
  $entity->save();
}

```
> 7 votes

# Answer
```
   function MODULE_form_alter(&$form,
      \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
      if($form_id == 'node_contentype_form') {
        array_unshift($form['actions']['submit']['#submit'],
                                         'MODULE_submit_handler');
       }
   }

   function MODULE_submit_handler(array &$form,
          \Drupal\Core\Form\FormStateInterface $form_state) {
       $form_state->setValue('title', [['value' => 'new title']]);
   }

```
> -1 votes

---
Tags: 8, forms
---


title: Do not want store credit card details

text:
# Question
Title: Do not want store credit card details
I am using Drupal 8 Commerce 2 Onsite payment gateway with USAepay payment gateway. I do not want to store credit card details in the database, even it should not save last 4 digit last of card number. Is there any way?

# Answer
> 3 votes
There is a reason that they have made it like that.

Take a look at this page, it describes why.

> **Onsite Payment Gateways always store credit card info**
>
> Payment gateways have different capabilities. Some support storing a user's card in the gateway. Others have an "offsite" flow, sending you to their site to collect card info and then returning you back to the commerce site when done.
>
> An "Onsite" payment gateway is one that keeps the visitor on the site, collects the card numbers and posts it from the site to the gateway. In Drupal Commerce 2, the payment flow for onsite gateways is completely different than in Commerce 1, Ubercart, or many other shopping carts: it now stores the credit card in the gateway first, and creates a "Payment Method" associated with the user that contains the token from the gateway. It can then use that token for any future charges (as long as the gateway continues to honor it).

---
Tags: 8, commerce
---


# Question
Title: Slashes in single route parameter or other ways to handle a menu tail with dynamic number of params
According to the Symfony documentation, a route defined as below should trigger the specified controller for both `/hello/bob` and `/hello/bob/bobby`:

```
_hello:
  path:     /hello/{names}
  defaults: { _controller: \Drupal\mymodule\Controller\Main::Controller }
  requirements:
    _access: 'TRUE'
    names: .+

```

In the case of a request to `/hello/bob/bobby` the `{names}` param would be "bob/bobby" (slash intact) and it would be up to the controller to break that down into multiple variables or to leave it as a single string. The trick to that is the altered regex (".+") used to filter that `{names}` param.

This stackoverflow post also implies that custom regex can be used to allow slashes in a route param (at least in Symfony 2).

If I try this against Drupal **8.0.0-beta15** it does **not** work and the specified controller is only triggered for a request to `/hello/bob`. However, I can confirm that this **used to** work in previous betas (I think up until ~beta13).

Has something changed in the way Drupal integrates with the Symfony routing component that would explain this? Perhaps there is an alternate way to accomplish the passing of slashes in routing params? I know there is a movement toward Symfony 3.0 in core, but I'm not sure if that could explain things.

I also know that route subscribers are available to manage dynamic route structures. However the case I am working on requires an almost infinite combination/number of dynamic parameters at the end of a base path (but which are trivial to parse in my controller). I'm also trying to avoid query strings (e.g. `/hello?names[]=bob&names[]=bobby`) for this case.

Mainly I'm just confused as to the disconnect with the Symfony documentation, which seems to state that this should be possible.

---

### Additional Notes

After posting this question I discovered this discussion in the D8 core queues: \[Discussion\] Drop automated passing of extra argument: Y/N. It seems to conclude that "menu tail" support (which is essentially what I am after) will officially be dropped in D8. That discussion ended 3 years ago and so I can only guess that some of the more generalized implementation specifics were not fully realized until recently (~beta13). This may explain why I've only now noticed this change.

I'm guessing that Drupal (not Symfony) is now generating a 404 response based on the raw slash-delimited request *before* any of the Symfony-specific routing logic further dissects the route (and it's param-specific regex, etc.). If this is the case it could explain why technique above stopped working. I am still wondering however if there are alternative ways to deal with this need that avoid using query params and custom route subscribers.

# Answer
You can alter the path by adding a class that implements the InboundPathProcessorInterface

```
namespace Drupal\mymodule\PathProcessor;

use Drupal\Core\PathProcessor\InboundPathProcessorInterface;
use Symfony\Component\HttpFoundation\Request;

class HelloPathProcessor implements InboundPathProcessorInterface {

  public function processInbound($path, Request $request) {
    if (strpos($path, '/hello/') === 0) {
      $names = preg_replace('|^\/hello\/|', '', $path);
      $names = str_replace('/',':', $names);
      return "/hello/$names";
    }
    return $path;
  }

}

```

This way the router will interpret the path `/hello/bob/bobby` as `/hello/bob:bobby` and you will get the parameters separated by `:` (or any other character that won't conflict with the parameters) in your controller.

You will also need to register the class as a service in mymodule.services.yml (make sure the priority is set higher than 200)

```
services:
  mymodule.path_processor:
    class: Drupal\mymodule\PathProcessor\HelloPathProcessor
    tags:
      - { name: path_processor_inbound, priority: 250 }

```
> 12 votes

# Answer
You can do the following to retrieve path params: In this case, I want to retrieve everything that comes after /rest/ as an array of strings.

Your yourmodule.routing.yml file should look something like this.

```
yourmodule.rest:
  path: /rest/{path_parms}
  defaults:
    _controller: 'Drupal\yourmodule\Controller\YourController::response'
    _title: 'Rest API Title'
  requirements:
    path_params: '^[^\?]*$'
    _permission: 'access content'

```

or in path\to\yourmodule\src\Routing\RouteProvider.php

```
/**
 * @file
 * Contains \Drupal\yourmodule\Routing\RouteProvider.
 */

namespace Drupal\yourmodule\Routing;

use Symfony\Component\Routing\Route;

/**
 * Defines dynamic routes.
 */
class RouteProvider
{
    /**
     * Returns all your module routes.
     *
     * @return RouteCollection
     */
    public function routes()
    {
        $routes = [];

        // This route leads to the JS REST controller
        $routes['yourmodule.rest'] = new Route(
            '/rest/{path_params}',
            [
              '_controller' => '\Drupal\yourmodule\Controller\YourController::response',
              '_title' => 'REST API Title',
            ],
            [
              'path_params' => '^[^\?]*$',
              '_permission' => 'access content',
            ]
        );

        \Drupal::service('router.builder')->setRebuildNeeded();

        return $routes;
    }
}

```

Next, add a Path processor to your module as follows. path\to\yourmodule\src\PathProcessor\YourModulePathProcessor.php

```
namespace Drupal\yourmodule\PathProcessor;

use Drupal\Core\PathProcessor\InboundPathProcessorInterface;
use Symfony\Component\HttpFoundation\Request;

class YourModulePathProcessor implements InboundPathProcessorInterface {

    public function processInbound($path, Request $request) {
        // If a path begins with `/rest`
        if (strpos($path, '/rest/') === 0) {
            // Transform the rest of the path after `/rest`
            $names = preg_replace('|^\/rest\/|', '', $path);
            $names = str_replace('/',':', $names);

            return "/rest/$names";
        }

        return $path;
    }
}

```

Finally, in your controller, do this: path\to\yourmodule\src\Controller\YourController.php

```
namespace Drupal\yourmodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;

/**
 * Controller routines for test_api routes.
 */
class YourController extends ControllerBase {

    /**
     * Callback for `rest/{path_params}` API method.
     */
    public function response(Request $request) {
        $params = explode(':', $request->attributes->get('path_params'));

        // The rest of your logic goes here ...
    }

}

```
> 1 votes

# Answer
## Alternative solution:

Create a route parameter that receives a json array.

---

## mymodule.routing.yml

```
_hello:
  path:     /hello/{names}
  defaults: { _controller: \Drupal\mymodule\Controller\Main::index }
  requirements:
    _access: 'TRUE'

```

## \Drupal\mymodule\Controller\Main

```
public function index($names_json) {
  $names = Json::decode($names_json);
  // Do something with $names
}

```
> 0 votes

---
Tags: 8, routes
---


title: Patching .htaccess file

text:
# Question
Title: Patching .htaccess file
I need to patch `.htaccess` file which is located in project's root (`docroot` in this case), my project is written using composer and I created a patch using git, added it to the /patches directory and wrote a composer.json entry:

```
"drupal/drupal": [
          {
            "title": "htaccess patch",
            "url": "docroot/profiles/laeg/patches/redirects.patch"
          }
        ]

```

Sadly after running `composer update` my patch doesn't appear in the patches list therefore it is not applied. I was told that I should patch `drupal/drupal` but it seems to not be a case, has some done anything like this and could suggest me something? Project is running Drupal 7.

# Answer
> 4 votes
For drupal 8, use the following. In the 'scripts' section of your composer.json, add

```
"post-drupal-scaffold-cmd": [
  "patch -p0 < patches/htaccess.patch"
]

```

# Answer
> -1 votes
A little late, but check out https://github.com/drupal-composer/drupal-scaffold/issues/45. They give a few solutions for handling the issue.

---
Tags: 7, composer, version-control
---


title: ON/OFF toggle as a custom view field

text:
# Question
Title: ON/OFF toggle as a custom view field
I have a table view output of node data. The node type has a list field called status. Status is set to accept a single value. It has the following option to select from:

```
Inactive
Active
Submitted
Approved

```

They work in pairs. When a node is created it's Inactive by default. Someone reviews it and sets it to Active. Upon further work it is set to Submitted and eventually someone else will set it to Approved.

What I am tasked with is creating a toggle button against each row of the table output containing **\[Inactive|Active\]** or **\[Submitted|Approved\]** which a user can simply click on and change it's status rather than go to the actual nodes' edit page.

I'm interested in ideas on how I can accomplish this or perhaps if there is a module that fully or partially does this.

# Answer
> 0 votes
Try using the Editable Fields module. It let you edit any CCK field on node/view display page, and it changes field values on the fly using AJAX.

# Answer
> 1 votes
For Drupal 8 You have to use Toogle Editable Fields https://www.drupal.org/project/toggle\_editable\_fields

# Answer
> 0 votes
You can achieve that using the flag and rules modules.
Set a role named "moderator". Moderator users can flag the content as active. Then other role ("super moderator" for example) can flag the content as approved/ submitted. Configure a rule to publish the content when it's flagged as approved.
You can also create views accessible only to specific roles where they can view the nodes flagged as inactive/ active/ submitted/ or approved.
In order to create a toggle button - try this tutorial - http://www.wdtutorials.com/2011/10/18/drupal-7-how-create-do-list-flag-module.
You can also try the Workflow module.

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


# Question
Title: View result alter title link based on content type
I have view which it has content type filter with more than 1 content type(Eg: A,B). For one specific content type(B) i want to alter the title link to external url(This external url is a custom field in that content type(B) ).

If I alter through Rewrite results using token(custom url),it work fine for the title which comes from B content type, but the title which comes from A content type is going to home page since this custom field is not available in that content type(A).

Please some one suggest on this.

# Answer
You can do it via views itself with the little tweaking.

Since you said the custom URL will not be available in other content types,

* Add the required fields including custom field and the content path to your views fields.
* Open the custom URL field and go to No Results Behaviour. Add the Replacement pattern of default content path.
* Created a custom text and assembled results. Make sure u refer to custom URL field to link and not the default content URL.

It should automatically work now. Whenever there is no third party URL link not available, it will fetch the default URL. This should have your issue resolved.

But in case if the third-party URL field was available in all content type with some data, Then you need to do this in preprocess function. This approach will have issues.
> 1 votes

---
Tags: views
---


title: Webform File Upload field

text:
# Question
Title: Webform File Upload field
I'm using Drupal 8 with Webform module.

I want to allow users to upload one or several files when filling the form. Is it possible with Drupal 8? May be some additional module required for this?

# Answer
> 22 votes
You need to enable **webform UI**, then set in your **sites/default/settings.php** file the privates files directory path: `$settings['file_private_path'] = 'sites/default/files/private';` where 'sites/default/files/private' is your privates files directory path. You can choose another directory. And give to this directory the write permission. Then clear all caches. Now you can add files fied in your webform while adding new element. In the popup that appears, typing file, you will see all files type like image, audio, etc.

# Answer
> 2 votes
Yes, you can allow users to upload files to the webform by adding a new "managed\_file" form element into the "Elements (YAML)":

This is provided that you have your public and private file paths set, which will otherwise throw a notice telling you to set those up.

# Answer
> 2 votes
Another solution of yaml configuration for images in order to upload a file:

```
picture:
  '#type': image_file
  '#title': Photo
  '#file_extensions': 'gif jpg png svg jpeg'
  '#multiple': True

```

You can install the module Webform UI to do this in the interface...

---
Tags: webforms, files, 8
---


# Question
Title: Programmatically create a Custom Content type on saving a form
We have explored it and found - how to create a content type by adding the YML files in the config/install directory of a custom module. The new content type will be created when we enable the module.

But we have a use case where we need to generate content types on saving a form. For eg: We have a custom form with a field called "Content-Type Name". On submitting the form, we need to create a new content type with that name.

We are not able to find any proper documentation for this in Drupal 8.

# Answer
> 5 votes
A content type is a config entity, you can create one like any other config entity (\*):

```
$content_type = \Drupal\node\Entity\NodeType::create([
  'type' => $machine_name,
  'label' => $label,
]);
$content_type->save();

```

---
Tags: 8
---


# Question
Title: Generate menu links for a view with contextual filter and parameters in the path
I have a view with a contextual filter, and a few tabs corresponding to a taxonomy. In my `module.links.menu.yml` I have something like this:

```
mymodule.apple_view:
  title: 'List of apples'
  route_name: view.fruit_view.page_1
  route_parameters: { fruittype: 'apple' }
  menu_name: main

```

So I have my tab "List of apples", but the URL has the form http://localhost/it/fruit\_view?fruittype=apple (which works), but I'd rather have it as http://localhost/it/fruit\_view/apple (which also works). I suppose there may be a parameter for `.link.menu.yml` to achieve this, but I cannot find the full documentation. I checked the documentation and the source, but that didn't help. Any suggestion?

# Answer
> 1 votes
Never mind - solved it. In the view definition, I changed the path from `/fruit_view` to `/fruit_view/%fruittype`, and I got the URLs as I wanted them. I also had to remove the menu voice defined in the view, but that's not a problem, since I have to redefine the filtered ones anyway.

---
Tags: 8, navigation
---


# Question
Title: Moving a website from Drupal to Wordpress
i want to move a website from drupal to wordpress, keeping the hosting provider the same (siteground). please bear in mind my knowledge in these matters is very rudimentary (i have published a blog on wordpress before but never attempted a migration and have zero knowledge of drupal!).

this plugin FG Drupal to Wordpress comes highly rated. in the installation process it includes a step:

Configure the plugin settings. You can find the Drupal database parameters in the Drupal file sites/default/settings.php

But i am at a loss where to find this, i am logged into the dashboard of the website as administrator. any help would be much appreciated!

# Answer
> 1 votes
Since you are migrating away from Drupal to WordPress, it would seem that this is a more appropriate question for a WordPress forum.

Echoing Kevin's advice in the comment above, the best place for you to start would be by learning a little bit about databases and the Structured Query Language (SQL) used to get data into and out of them:

https://www.codecademy.com/learn/learn-sql

Once you understand some basic stuff about database administration, you'll have a much easier time migrating content from one database to another, no matter what Content Management System (CMS) you are using.

In particular, you seem to be stuck configuring your plugin because you cannot find the Drupal database parameters. You won't find this information anywhere in the Drupal admin user interface.

> You can find the Drupal database parameters in the Drupal file `sites/default/settings.php`

That is a plain text file on the server. To read it, you'll need to access the server via SSH, FTP, or some other method, depending on your hosting. (You'll want to do some research about these things, too.)

Then, inside the Drupal document root on the server, you will find a directory called `sites`, which contains a directory called `default`, inside which you will find the `settings.php` file.

When you read this file, you will find the super secret database authentication tokens that your plugin needs to help automate the migration.

Depending on your Drupal version and hosting, it may look something like this:

```
  // Database.
  $databases['default']['default'] = array(
    'database' => 'DATABASE',
    'username' => 'USERNAME',
    'password' => 'PASSWORD',
    'host' => 'localhost',
    'driver' => 'mysql',
    'port' => 3306,
    'prefix' => '',
  );

```

Never share this info online, by the way.

There's more to website administration than just using the admin user interface of a CMS. You'll need to understand some basic concepts about the PHP code that you are running on the server -- not necessarily how to edit it, but at least how to view it.

Until you know some basic things like that, you'll have an easier time migrating your content by cutting and pasting articles manually between the old site and the new site.

---
Tags: migrations
---


title: How to show price range

text:
# Question
Title: How to show price range
I got Drupal 8 / Commerce 2 installation, and trying to create product category pages, showing product image, title and price range (min & max price)

I've created product category page with Views. Category is defined as Taxonomy reference field in product. Views has "Contextual filter", where category name is taken from url e.g. /product/\[category\].

Product catalog page works fine, showing fields defined in (custom) Summary view mode. It shows title and the first product variation image and price.

Only thing missing is the price range info

I've tried to do some experiments by

* overwriting commerce-product.html.twig in custom theme
* writing hook\__preprocess\_commerce\_product in custom module

..but with no luck. Debugging is hard because, for some reason kint() / dpm() calls fail or just take tooo long and give execution time out...

So the question is: how and where to check product variations lowest & highest prices plus pass them to product template?

Any hints or ideas are greatly appreciated.

EDIT:

I got it done by adding the following preprocess hook to my custom module

```
function CUSTOMMODULE_preprocess_commerce_product(&$variables) {

  $product = $variables['elements']['#commerce_product'];

  foreach( $product->variations as $variation) {
    $prices[] = $variation->entity->getPrice()->getNumber();
  }

  $min_price = min($prices);
  $max_price = max($prices);

  if ($min_price != $max_price) {
    $variables['min_price'] = $min_price;
    $variables['max_price'] = $max_price;
  }

  $variables['currency'] = $variation->entity->getPrice()->getCurrencyCode();
}

```

... And then in commerce-product--teaser.html.twig

```
{% if min_price is defined and max_price is defined %}
  {{ min_price |number_format(2, '.', ',') }} -
  {{ max_price |number_format(2, '.', ',') }} {{ currency }}
{% else %}
  {{ product.price }}
{% endif %}

```

# Answer
> 3 votes
I don't think the min max would be readily available in the template and you'll have to add it in.

You could use hook\_preprocess\_commerce\_product($variables) and within $variables it will contain the product entity and also all of its variations. You would just need to loop through the variations to work out the min and max price and then add the new value into $variables e.g.

```
$variables['min_max_price'] = $myvalue;

```

Then in your template commerce-product.html.twig do:

```
{{ min_max_price }}

```

and that should come out with your $myvalue value

---
Tags: 8, commerce
---


title: Adding composer to update core

text:
# Question
Title: Adding composer to update core
I'm using a site created on Pantheon and now I'm not using pantheon.

So the core is not installed with composer. Now I want to upgrade core with composer but I don't understand how.

I've some modules installed with composer, so I try to add drupal/core :

```
compose require "drupal/core"

```

It's ok, but if I try to this, the aren't upgrades:

```
composer update drupal/core --with-dependencies

```

I've core 8.6.1 and I wanto to update to 8.6.2.

Thanks

# Answer
> 2 votes
It is probably due to how the drupal/core line in your composer.json file is defined. It probably has the version locked to 8.6.1. So the update is saying: You are already at the version you requested. There are no updates.

I would try doing the following:

```
composer require drupal/core:8.6.2 --update-with-dependencies

```

This will tell composer to use that version and ignore the version info in the composer.json file.

---
Tags: composer, upgrading
---


title: Why aren't my pages caching?

text:
# Question
Title: Why aren't my pages caching?
My Cache-Control header is always set to `must-revalidate, no-cache, post-check=0, pre-check=0, private` on the front page as well as every other page.

I've gone to configuration\>performance and set Page cache maximum age to 5 mins, and I've gone to every view and set time-based caching to 5 mins as well.

There are a lot of articles about what to grep for in modules that might disable caching on a page, but these are all for Drupal 7, and I'm on Drupal 8.

What should I be looking for in my D8 modules that might be killing my caches? If I don't fix this header, CloudFront won't like my pages very much.

EDIT: The poll module was invalidating my caches on pages that were showing poll results, but that didn't turn out to be my main issue. After disabling the poll module, I was still getting `must-revalidate, no-cache, post-check=0, pre-check=0, private`, but only on my Firefox Developer Edition (with browser caching disabled, though that probably doesn't matter) while all other browsers (including regular Firefox, with or without caching disabled) are returning `max-age=300, public` as they should. I'm concerned, does this mean users can bypass caching under the right circumstances?

# Answer
> 12 votes
In general, this is pretty hard to answer without going into details and knowing what you did with your site. But to give you a few starting points...

* To ask the obvious, you *are* testing this as an anonymous user without a session, right?
* If you *do* have a session, check what values you have in there and who sets them
* One thing to grep for is \Drupal::service('page\_cache\_kill\_switch')-\>trigger();, although it could also be injected, so just look for -\>trigger(). That's the equivalent of drupal\_page\_is\_cacheable(FALSE) although are other ways to plug into that too.
* Typical modules that set this are captcha or poll
* If all else fails, look at FinishResponseSubscriber, that's the one that adds those headers, specifically look at the request policies that return if a page is cacheable or not (the kill switch is one of those, as is the check for a session)

# Answer
> 0 votes
to solve I used this module http\_response\_headers. Can solution my bug whith headers http.

Steps:

1. Install Module
2. Configuration Response header configuration
3. Go path: /admin/config/system/response-headers
4. Add Response header configuration
5. Configuration the fields.
6. Save

For example, my case:

My Headers is change:

Before:

After:

I hope it helps in something!

---
Tags: 8, caching
---


title: Theme Suggestions for User Page

text:
# Question
Title: Theme Suggestions for User Page
I want to create a separate `html.tpl.php` for user pages and user edit pages like `html--user.tpl.php` and `html--user--edit.tpl.php`.

For nodes I have added:

```
if (isset($node) && $node->nid) {
  $vars['theme_hook_suggestions'][] = 'html__' . $node->type;
}

```

in `template.php`.

Is there a way to do this for user pages as well?

# Answer
You can use this template for the user page: `user-profile.tpl.php`

For the user edit page you can take a look at this page: Customize the User Edit page in Drupal 7 - an example.

UPDATE: To add CSS and JS to specific page you can do it like outlined below in a custom module.

```
/**
 * Implements hook_page_build().
 */
function MYMODULE_page_build(&$page) {

  if (request_uri() == 'path') {

    drupal_add_js( // arguments );
    drupal_add_css( // arguments );
  }
}

```
> 1 votes

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


# Question
Title: Module name and name of the directory the containing it
Google and stack has come up dry so far, so I'll ask you: In Drupal 8, does my module folder *need* to match the name of my module? Some basic testing indicates that they can differ with no harm done, but Drupal 8 is still a bit of a black-box to me and I don't want to find myself painted into a corner because of this.

# Answer
> 4 votes
Good conventions mentioned by Kevin aside, there's no technical reason for the names to match, no. What's important is the name of the .info.yml file, that's what defines the module machine name.

Drupal just interrogates the known module folder locations recursively looking for .info.yml files, so anything will get picked up regardless of folder name.

---
Tags: 8
---


title: How do I set multiple attributes?

text:
# Question
Title: How do I set multiple attributes?
If I have multiple attributes that I want to set to an element in a twig template it can get quite long since each attribute requires setAttribute(attribute name, attribute value).

Based on my IRC conversation (I don't remember who it was), it looks like it is not possible to set multiple attributes at once, like it is possible with CSS classes.

So I would like to know what would be a "pretty" way of setting multiple attributes in a twig template. I presume a loop of some kind.

# Answer
If you are adding the attributes in Twig you can set multiple attributes by chaining the setAttribute calls like this:

```
{{ attributes.setAttribute('id', 'value').setAttribute('data-info', 'value'); }}

```
> 4 votes

# Answer
Are you limited to using twig to do this?

If you are open, you can try a template\_preprocess\_field hook to add the attributes.

Maybe you can inspire from this.

```
// template_preprocess_field().
{% for item in items %}
  <div {{ attributes }}>
    {{ item.content }}
  </div>
{% endfor %}

function mytheme_preprocess_field(&$variables) {
  // If you need to use values from another field, you can build an array and use that to populate the necessary attributes.

  $variables['attributes']['id'] = 'some-id';
  $variables['attributes']['class'] = 'some-class';
  $variables['attributes']['custom_attribute'] = 'custom attribute value';
}

```
> 0 votes

---
Tags: 8, theming
---


# Question
Title: What is the process to upload custom drupal themes to Drupal.org? What is relevance of "PayWithPaytm"?
I am new to this community, so apologies in advance for some ignorance.

I know there are forums, chat channels, ect, so I also apologize if this is the wrong medium for such questions.

**Basically, I want join the community by building my own Drupal Theme and eventually upload it to Drupal.org for other users to download and use if they wish.**

I went to my dashboard on Drupal.org where there are tabs for "Your Projects" and "Your Commits" and such, but commits is just a blank page, and projects is empty but with a message "*To learn about projects, see Contributing code on Drupal.org.*".

Clicking this hyperlink goes to this page: https://www.drupal.org/contribute-projects .

So my confusion starts here. **What does this e-commerce payment gateway plugin have to do with contributing code?** I downloaded it, the readme mentions nothing. Under the download option, there begins the info I need (like how to create a sandbox project and eventually

**So what does that PayWithPaytm plugin have to do with anything?** Do users need to pay Drupal to create a project or something? Why does the "learn about contributing" link go to an e-commerce plugin?

Below is a screenshot of my dashboard and the link to PayWithPaytm.

# Answer
> 2 votes
The Drupal community pages are basically a Wiki done in Drupal. As such, anyone can get authorized to make changes. However, like a Wiki, people can add spam like this. This page was spammed today.

I've reverted the page back to the last revision so it should now be helpful.

Welcome to Drupal.

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


# Question
Title: How to go from View to Webform, submit Return to View
User is working a list of names with Views... select a link on the view to open webform, submit the webform. Then I would like to return the user to the view.. Where he can continue working the list of names.

Hopefully save url to a hidden token in the view (which token is current url?) then send token in the link to webform pre-populating hidden object in webform? Back button is a bad idea because I don't want to go back to the webform. I want to return to the View.

# Answer
Does your views page had a direct url? E.g. www.mysite.com/my-views-url? If so you can just redirect the webform on submit

* Edit the webform, select settings tab
* Select confirmation tab
* Chose either
    + URL (redirects to a custom path or URL)
    + URL with message (redirects to a custom path or URL and displays the confirmation message at the top of the page)
* Set the url in Confirmation URL to redirect back to your view
> 1 votes

---
Tags: views, 8, webforms
---


# Question
Title: Assign programmatically created order to anonymous user
I want to create a pre-made order in Drupal Commerce for an anonymous user, and redirect the user to the checkout.

My use-case is that I have two sites: One big Drupal Commerce site (up and running since 2011), and another site that sells a few very specific products. The second site is not a Drupal site.

Ideally I want users on the second site to be able to select a few products, click "checkout" and be redirected to the checkout page on the Drupal site, with an order that contains the products that he/she selected on site two.

Now, selecting products etc. won't be an issue (second site has access to all product data via Services API), *but* I have no idea how to create the order for the anonymous user in Drupal and make it belong to him/her.

I read this blog entry which could've been of use (send user to page that creates the order and then redirects user to checkout) but apparently that doesn't work for anonymous users.

Any help would be greatly appreciated!

# Answer
I think you may be thinking about this incorrectly. If I were you, I'd write a custom module that created a new path designed to create a shopping cart for whoever lands on it with the requested products. You can include a token or something in the URL to ensure each one only gets processed once, and you can redirect to /cart or some other route after the order is created to try to reduce duplicate carts.

This means on the secondary site you're just storing in a cookie or the session the product IDs that you'll then use to construct the cart when you pass them to the Drupal site via query parameters or something like that. It isn't really possible to create a remote session for someone and then force assign the session ID to them when they land on your site afaik.
> 0 votes

---
Tags: commerce
---


# Question
Title: Does Drupal 8 entities have any events I can listen to?
I know we can use `hook_entity_update()` hook to do something when an entity is updated. But is there an event to listen for node updates/deletes, or other entities such for that matter?

# Answer
> 19 votes
You can't listen to an event. You can either use a hook or implement a method like postSave() in your custom entity.

Here is the order of hooks and other events that happen during an entity save:

# Answer
> 7 votes
Ideally you would listen for entity related events but these aren't ready yet. See "Add events for matching entity hooks".

For now, if you're wanting to stay away from hooks, you can use a contrib module: Hook Event Dispatcher

# Answer
> 3 votes
A `node` is an entity type, so `hook_ENTITY_TYPE_update(..` is the same as `hook_node_update(..`,

```
function hook_node_update(Drupal\Core\Entity\EntityInterface $entity) {
    //$entity->bundle()  - 'article' 'page'
}

```

or

```
function hook_customentity_update(Drupal\Core\Entity\EntityInterface $entity{
    //$entity->bundle()  - 'awesome_entity_bundle'
}

```

https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Entity!entity.api.php/function/hook\_ENTITY\_TYPE\_update/8.2.x

---
Tags: 8, entities, event-subscribers
---


title: Webform submission values with PHP

text:
# Question
Title: Webform submission values with PHP
I am using webform 2 pdf module, where I am trying to set up a custom content to the pdf file.

I would like to acces the webform submission data, but I have no idea how to do it. Basically I would like to access them and use them as tokens.

I am on a basic level with both drupal and php, which means I have limits.

```
//simple first section
<h1 align="center" style="font-family:verdana;" style="font-size:14;"><b>Registration<b></h1><br>

<p style="text-align:left; font-family:verdana; font-size:12;" ><b>1. Registered Data:</b></p>
<p style="text-align:left; font-family:verdana; font-weight: normal; font-size:12;" >[submission:values:personal_info:key]</p>

<p style="text-align:left; font-family:verdana; font-size:12;" ><b>2.  Declaration:</b></p>
// there comes the non-working php part
<p><?php
    $var=($fields["institutuonal info"]);
    if ($var == "spec_inst") {
      echo "some juristic stuff";
    }
    ?></p>

```

So I am trying to export webform submission results to PDF, but the result depends on the submission content.

# Answer
So I partly was able to access webform values. I still have a problem, that I cannot access to one single submission, altough I tried `$sid = GET[sid]` method. So here is my partly good code:

```
    //simple first section
<h1 align="center" style="font-family:verdana;" style="font-size:14;"><b>Registration<b></h1><br>

<p style="text-align:left; font-family:verdana; font-size:12;" ><b>1. Registered Data:</b></p>
<p style="text-align:left; font-family:verdana; font-weight: normal; font-size:12;" >[submission:values:personal_info:key]</p>

<p style="text-align:left; font-family:verdana; font-size:12;" ><b>2.  Declaration:</b></p>

<?php
$submissions = webform_get_submissions(array('nid'=>1));
foreach ($submissions as $submission){
foreach ($submission->data as $row=>$data){
        if ($row == 4){
              if (in_array("0", $data)) {
                    print("long boring text content");
}}}}
?>

```

So still not what I wanted but that is another question.
> 0 votes

---
Tags: 7, webforms
---


# Question
Title: Disabling module with config sync and removing with composer
I have an issue disabling modules, I've searched but cannot find something useful:
\- Developer A disable module and via composer remove it
\- I pull his changes so i run composer install that remove the code, then drush cim to update configuration, but it complains that the module is missing while it's trying to delete its configurations.

What's the right way to do this? I can't import config before running composer install because along the uninstalled module there could be also new modules needed for the configuration import.

# Answer
You need *two consecutive releases* for stuff like that.

**First release:**

Your colleague uninstalls the module and commits the updated config.

If you don't manage your site via config use `hook_update_N` instead.

```
/**
 * Uninstall SOME_MODULE module.
 */
function MYMODULE_update_8001(&$sandbox) {

  \Drupal::service('module_installer')->uninstall(['SOME_MODULE']);
}

```

**Second release:**

The module can be removed via Composer.

---

Related:

Order of drush commands for automated deployment?
> 8 votes

# Answer
Adding an alternative solution to @leymannx - you will still need two releases. This is taking into consideration your mention of `drush cim`

**First release:**

1. Uninstall the module `drush pmu module_name`
2. Export the configuration.
3. Commit, push, and release.
4. Deploy and execute `drush cim`. That should uninstall the module.

A hacky way to uninstall is directly editing the `core.extension.yml`, remove the complete entry of the module from under the `module:` key, and executing `drush cim`. **NOTE:** Use this hacky way only when you are sure that the module doesn't export any configuration. Else, there would be an exception thrown.

**Second release:**

Removing module from composer.
> 5 votes

---
Tags: 8, configuration, composer, installation
---


title: Composer update

text:
# Question
Title: Composer update
I had an existing Drupal 7 website already running. I downloaded a template composer.json file https://github.com/drupal-composer/drupal-project/blob/7.x/composer.json , to be able to run composer update. It updates modules perfectly, however when it came to drupal core it does not update (drupal 7.59 -\> 7.6). The path it currently has is

```
"installer-paths": {
        "web/core": ["type:drupal-core"],

```

but (the website I got composer.json file from) definition of web directory was for their instance:

"Drupal will be installed in the web-directory."

So my installer path is core/ and it still does not get updated. My question is how can i find out which directory drupal-core should be updating? If it is root, I have tried "./:\[type..\]", "core:\[type..\]", "web:\[type..\]" to no avail. Any pointers would help, thank you.

# Answer
> 0 votes
> So my installer path is core/

Assuming by that you mean the Drupal installation is in ./core/, as relative to your Composer project root (i.e. /path/to/core/index.php etc. exist), then your installed path should simply be "core":

```
"installer-paths": {
    "core": ["type:drupal-core"],

```

---
Tags: updating, composer
---