# Question
Title: PDF Module, PDF full pageheight or full scroll
I managed to get a PDF in a content type and to show the full PDF. I do this with the PDF module in drupal 7. But I want't the height of 1 page (A4 always) or just the full height of the document.

How can I manage this? 100%, auto doesn't work. I can only give a certain amount of pixels. But when it's resized, it's not perfect, the frame is higher then the document.

When I try to use the option PDF: Continuos scroll, it breaks. That should also be a solution for me, just the height of the document. But I have the following errors:

> Uncaught (in promise) TypeError: Cannot read property 'getDirection' of undefined at webViewerLocalized (viewer.js?opdors:7109) viewer.js?opdors:4958 Uncaught (in promise) TypeError: Cannot read property 'firstElementChild' of null at PDFViewer (viewer.js?opdors:4958) at viewer.js?opdors:5790 at Promise () at Object.\_initializeViewerComponents (viewer.js?opdors:5778) at viewer.js?opdors:5692 /sbsdebrug/sites/all/libraries/pdf.js/build/pdf.worker.js:50046 The provided value 'moz-chunked-arraybuffer' is not a valid enum value of type XMLHttpRequestResponseType. supportsMozChunkedClosure @ /sbsdebrug/sites/all/libraries/pdf.js/build/pdf.worker.js:50046 pdf.js:28 Uncaught (in promise) ReferenceError: getOutputScale is not defined at renderPage (pdf.js:28) pdf.js:28 Uncaught (in promise) ReferenceError: getOutputScale is not defined at renderPage (pdf.js:28) pdf.js:28 Uncaught (in promise) ReferenceError: getOutputScale is not defined at renderPage (pdf.js:28) pdf.js:28 Uncaught (in promise) ReferenceError: getOutputScale is not defined at renderPage (pdf.js:28)

# Answer
> 0 votes
The PDF module isn't compatible with pdf.js 1.8. I went down in versions, and from 1.3 and below. This works. There are still some errors in console, but that's fine for me (I didn't tried lower then version 1.1).

# Answer
> 0 votes
I did something similar with print module, it also may be posible with PDF module. Override print--pdf.tpl.php file to fit your needs, copy print.tlp.php file from print-module directory (or look for a similar file in pdf module), paste it in sites/all/themes/your-sub-theme/templates folder. in line 100 is print $content, there add a css class "myclass" with higth=100%; done!.

---
Tags: 7, files
---


# Question
Title: get last element in URL(menu item) generated by hook_menu
I have created a URL/menu item via hook\_menu, and in the proprocess\_html I'd like to get my item (last element in the URL) (/test) without using arg(0).

I can do it in PHP but I was wondering how it was possible to get this with drupal.

```
end(explode("/", request_uri()))

```

this code is actually bad, there could be URL such as ?test=ok

Cheers,

# Answer
> 1 votes
```
array_pop(arg());

```

will return the last component of the current Drupal path.

---
Tags: 7, uri, routes
---


# Question
Title: Remove the "Advanced search" form on the result page?
On Drupal 8, how can I remove the "Advanced search" form on the result page ?

I can hide it with css :

```
#edit-advanced,
#edit-help-link {
    display: none;
}

```

But I would prefer to do it with php or even better with a parameter in admin but I didn’t see any parameter related to Advanced search in

```
/ Administration / Configuration / Search and metadata

```

# Answer
> 6 votes
You need to go to:

```
admin/people/permissions

```

and uncheck the checkboxes for the users that don't need to use the Advanced Search.

---
Tags: 8, search
---


title: Hook into Group module

text:
# Question
Title: Hook into Group module
I'm creating a module for Drupal 8 that will auto fill some content in a add content page. Now I need to have a way to group different contents in one group. I found the Group module that does the job, but I cannot find a way to hook into it. Can someone help me with this?

I want to have a few check boxes, for every group, in my add content page. When the user select a group and create the content it will be added to that group. How can I create the checkboxes for the groups where the users has access for. Also how can I auto add the content to the selected groups?

# Answer
Sure it is possible but you'll have to write quite a bunch of custom code to accomplish this.

First let's take a look at how a node belongs to a group. This is done through the GroupContent entity.

Before we can actually relate a node to a group, we'd have to *install* the entity to the group type. This can be done by going to:

Groups -\> Group types -\> Set available content (can be found via the Operations action button).

First we want to add the possibility to choose one or many groups the node being created can belong to. So we'll have to determine if the node we are trying to add is first installed and then get the groups.

Here is a **very simplified example** on how to do that by using altering the node and then finding out which group types the current node type is installed to, finally getting the groups and exposing them as checkboxes.

It does not currently care about the user actually having access to that group yet.

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function custom_group_form_node_form_alter(&$form, FormStateInterface $form_state) {
  $node = $form_state->getFormObject()->getEntity();

  $groupPluginManager = \Drupal::service('plugin.manager.group_content_enabler');

  // Get the group types this node type is installed to.
  $plugin_id = 'group_node:' . $node->getType();
  $groupTypes = $groupPluginManager->getGroupContentTypeIds($plugin_id);

  // This node is not installed to any group types.
  if (empty($groupTypes)) {
    return;
  }

  // Normalize group type ids to just the type name
  $groupTypes = array_map(function($groupType) {
    return explode('-', $groupType)[0];
  }, $groupTypes);

  // Get groups...
  // @TODO: Sort, group the groups to its group type?
  $query = \Drupal::entityQuery('group');
  $query->condition('type', $groupTypes, 'IN');
  $groups_ids = $query->execute();

  // ugh... no groups though?
  if (empty($groups_ids)) {
    return;
  }

  // Create a checkboxes with all groups without any grouping of type
  $groups = \Drupal\group\Entity\Group::loadMultiple($groups_ids);
  $options = [];

  foreach ($groups as $group) {
    $options[$group->id()] = $group->label();
  }

  $form['groups'] = [
    '#type' => 'checkboxes',
    '#title' => 'Attach to group',
    '#options' => $options,
  ];

 foreach (array_keys($form['actions']) as $action) {
    if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
      $form['actions'][$action]['#submit'][] = 'custom_group_submit_handler';
    }
  }

}

```

So we have a list of groups on the node form, how do we actually relate them to the checked groups? We added a submit handler `custom_group_submit_handler` Let's write that to, again very simplified:

```
function custom_group_submit_handler(&$form, FormStateInterface $form_state) {

  $node = $form_state->getFormObject()->getEntity();
  $groups = $form_state->getValue('groups');

  // Iterate through each submitted group
  foreach ($groups as $group) {
    $groupEntity = Group::load($group);

    // Assemble the type.
    $type = $groupEntity->getGroupType()->id() . '-group_node-' . $node->getType();

    // Create the relation.
    $groupContent = GroupContent::create([
      'gid' => $group,
      'entity_id' => $node->id(),
      'type' => $type,
    ]);
    $groupContent->save();
  }
}

```

This took a bit longer to write than I expected, so therefore there are some details you will have to implement yourself, like:

* Take group access and permission under consideration
* You'd most likely want to clean up the code and move to a more object-oriented approach
* You want to handle both add/edit and deletion for the node relation to a group.
* You want to make sure the node is not already related to the group.

etc.

Hopefully this is an start to get you further on your objective!
> 5 votes

---
Tags: 8, group
---


title: How to get Drupal cache key?

text:
# Question
Title: How to get Drupal cache key?
If you have caching enabled in Drupal, instead of getting URLs like so:

```
image.png

```

You get:

```
image.png?itok=RANDOMNESS

```

What function would I need to call to get back the value = "RANDOMNESS"? I ask, because I want to cache other things using the same method Drupal does internally.

Any ideas?

# Answer
> 3 votes
The `itok` is defined in ImageStyle@getPathToken entity when building the URL (ImageStyle@buildUrl):

```
  /**
   * {@inheritdoc}
   */
  public function getPathToken($uri) {
    // Return the first 8 characters.
    return substr(Crypt::hmacBase64($this->id() . ':' . $this->addExtension($uri), $this->getPrivateKey() . $this->getHashSalt()), 0, 8);
  }

```

---
Tags: 8
---


title: Drush Installation

text:
# Question
Title: Drush Installation
I have a Drupal 8 site that was installed manually. I would like to install Drush to ease Core Updates/etc. Is there anything that I need be concerned about doing this, since the site wasn't installed originally via Drush?

# Answer
No, there isn't anything you should be concerned about :) Drush is simply an CLI tool to do some things quicker, like downloading a module.

In fact when installing with Drush you are simply automating the steps you would otherwise manually do. There are nothing that ties your Drupal installation to Drush when doing so.
> 0 votes

---
Tags: 8, drush
---


# Question
Title: After an Ajax request that modifies the form it will not pass in the submitForm method
I have a form with 3 dropdowns. When changing the first one, it updates the 2 other by an ajax call. Once the 2 selects are re-rendered, when the user submits the form, it no longer pass in the `submitForm()` method. I have tried many combinations to try to fix this but found no way. Here is the last state of my attempts.

In a module for geo location, I load a form in a block:

in src/Plugin/Block/GeoPopupBlock.php:

```
class GeoPopUpBlock extends BlockBase {

    public function build() {

    if(!$cookie = Util::getCookie()){
      $message = 'Cookie was not set.';
      \Drupal::logger($message);
      die($message);
    }

      $buildForm = \Drupal::formBuilder()->getForm('\Drupal\my_module\Form\GeoForm');
//      $buildForm = \Drupal::formBuilder()->getForm(new GeoForm());
      $build['#form'] = $buildForm;

[...]
    return $build;

```

In src/Form/GeoForm.php

```
<?php

[...]

class GeoForm extends FormBase{

  public function getFormId(){
    return 'geo_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state){
    if (!$cookie = Util::getCookie()){
      $message = 'Cookie was not set.';
      \Drupal::logger(__CLASS__)->critical($message);
      die($message);
    }

    $form['country'] = array(
      '#type' => 'select',
      '#options' => $this->getCountries(),
      '#default_value' => $cookie['countryId'],
      '#attributes' => array('class' => array('edit-country')),
      '#ajax' => array(
        'callback' => '::ajaxFillProvider',
        'wrapper' => 'provider-language',
        'method' => 'replaceWith',
        'progress' => array(
          'type' => 'throbber',
          'message' => NULL,
        ),
      ),
    );
    $form['provider'] = array(
      '#prefix' => '<div id="provider-language">',
      '#type' => 'select',
      '#options' => $this->getProviders($cookie['countryId']),
      '#default_value' => $cookie['providerId'],
      '#attributes' => array('class' => array('edit-provider')),
    );
    $form['language'] = array(
      '#type' => 'select',
      '#options' => $this->getLanguages($cookie['countryId']),
      '#default_value' => $cookie['languageId'],
      '#suffix' => '</div>',
      '#attributes' => array('class' => array('edit-language')),
    );
    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = array(
      '#prefix' => '<div class="flex"><div class="submit-button">',
      '#type' => 'submit',
      '#value' => $this->t('Access my content'),
      '#suffix' => '</div>',
    );
    $form['actions']['decline'] = array(
      '#prefix' => '<div class="decline-button" id="decline-button">',
      '#markup' => t('Decline'),
      '#suffix' => '</div></div>',
    );
    return $form;
  }

  public function ajaxFillProvider(array &$form, FormStateInterface $form_state){

    $ajaxForm['provider'] = array(
      '#prefix' => '<div id="provider-language">',
      '#type' => 'select',
      '#name' => 'provider', // have to add this otherwise the select would have no name!
      '#options' => $this->getProviders($form_state->getValue('country')),
      '#attributes' => array('class' => array('edit-provider')),
    );
    $ajaxForm['language'] = array(
      '#type' => 'select',
      '#name' => 'language', // have to add this otherwise the select would have no name!
      '#options' => $this->getLanguages($form_state->getValue('country')),
      '#suffix' => '</div>',
      '#attributes' => array('class' => array('edit-language')),
    );
    return $ajaxForm;

  }

  /**
   * @param array $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   */
  public function submitForm(array &$form, FormStateInterface $form_state){

    if (!$cookie = Util::getCookie()){
      $message = 'Cookie was not set.';
      \Drupal::logger(__CLASS__)->critical($message);
      die($message);
    }

    $commConfig = \Drupal::config('communication.settings');

    $cookie['countryId'] = $form_state->getValue('country');
    $cookie['providerId'] = $form_state->getValue('provider');
    $cookie['languageId'] = $form_state->getValue('language');

    Util::setCookie($cookie);
  }

[... more private methods]

}

```

At this point the ajax is working and filling the 2 selects with new values. Submitting the form will send all values to the server. But for an unknown reason, it will not pass in the `submitForm()`.

Note that if I remove the extra `'#name' => 'provider',` and `'#name' => 'language',` it will pass in the `submitForm()` but since the new select tags have no name attribute, the form in unable the use those form elements.

# Answer
Pretty sure I answered this before but can't find a matching answer right now.

This is the golden rule when doing ajax with Drupal. Ajax callbacks must not alter $form, they only "logic" they should contain is what to return and possible additional ajax commands.

Instead, buildForm() must contain the logic to update the form according to what's in form user input or e.g. by setting something with $form\_state-\>set('foo', 'bar') in a submit callback (if you want to have a submit callback on a select element, you need #execute\_submit\_callback and possibly #limit\_validation\_errors so that the element can be changed when other fields are not filled out). Then you just return the part of the form you want to return in your ajax callback.

This also helps to ensure that the form works without JS (with a select that's obviously a bit tricky, but you can for example also add a submit button that you hide by adding a js-hide class).
> 3 votes

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


# Question
Title: Unset terms that show in taxonomy autocomplete
I would like to unset terms that show up in taxonomy autocomplete.

For example if TID 1 2 3 4, are in the taxonomy I would only like 1 2 and 3 to show in the dropdown for autocomplete.

# Answer
You could try to alter the query but according to a comment there is no alter tag set on the query

\- https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_query\_alter/7.x \- https://api.drupal.org/api/drupal/modules%21taxonomy%21taxonomy.pages.inc/function/taxonomy\_autocomplete/7.x

Another solution would be to alter the form with the autocomplete field to alter the path

iirc as a last resort you could use javascript to drop the unwanted item from the list using css display:none
> 1 votes

# Answer
Your best bet would be to create your own autocomplete path. Here are the steps to implement this:

Create a custom module

In hook menu create a custom autocomplete path:

```
$items['my-module-taxonomy/autocomplete'] = array(
  'title' => 'Custom Autocomplete taxonomy',
  'page callback' => 'my_module_taxonomy_autocomplete',
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK,
);

```

Create my\_module\_taxonomy\_autocomplete function. The easy way would be to copy everything from the taxonomy\_autocomplete() function and add conditions in your query. For example:

```
->condition('t.tid', array(1,2,3), 'IN')

```

In hook\_form\_alter() set the autocomplete field from using the default one to the custom one you just made:

```
/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'my_node') {
    $form['field_term'][LANGUAGE_NONE]['#autocomplete_path'] = 'my-module-taxonomy/autocomplete';
  }
}

```
> 2 votes

# Answer
**Overview**

Use an Entity Reference field to reference taxonomy terms filtered by an entity reference view.

**Method**

1. Create a View showing "Taxonomy terms" of type "vocabulary name"
2. Add a Views display of type "Entity Reference"
3. Under "Format" next to "Entity Reference list" click "Settings" and select relevant "Search fields"
4. Add any filters under "Filter criteria", such as "Taxonomy term: Term ID"
5. For "Operator" in step 4, select "Is not equal to" or "Is less than" for example. See below.
6. Save the view.
7. Add an "Entity reference" field to your entity with "Target type" of "Taxonomy term" and select your "Target bundles"
8. For "Mode" under "Entity selection", select "Views: filter by an entity reference view"
9. Select the "View used to select the entities"
10. Provide any arguments if required and review other field options.
11. Save the field settings.

**Example**

In your example, for step 5 you could add a single filter for "Taxonomy term: Term ID":

**Operator:** Is less than

**Value:** 4

You can add as many filters as you like and even perform calculations if required.

More filter options are available via custom code or contributed modules such as Code Filter which allows the use of PHP. See also Views PHP and Global Filter.
> 1 votes

---
Tags: 7
---


title: How do I print the node title and body?

text:
# Question
Title: How do I print the node title and body?
This is the code which I have put in node.html.twig. It doesn't print the body and title of the node, whose bundle is *Basic page*.

How do I print node title and body of a node?

```
{%
  set classes = [
'node',
'node--type-' ~ node.bundle|clean_class,
node.isPromoted() ? 'node--promoted',
node.isSticky() ? 'node--sticky',
not node.isPublished() ? 'node--unpublished',
view_mode ? 'node--view-mode-' ~ view_mode|clean_class,
'clearfix',
  ]
%}
{{ attach_library('classy/node') }}
<article{{ attributes.addClass(classes) }}>
  <header>
{{ title_prefix }}
{% if not page %}
  <h2{{ title_attributes.addClass('node__title') }}>
    <a href="{{ url }}" rel="bookmark">{{ label }}</a>
  </h2>
{% endif %}
{{ title_suffix }}
{% if display_submitted %}
  <div class="node__meta">
    {{ author_picture }}
    <span{{ author_attributes }}>
      {% trans %}Submitted by {{ author_name }} on {{ date }}{% endtrans %}
    </span>
    {{ metadata }}
  </div>
{% endif %}
  </header>
  <div{{ content_attributes.addClass('node__content', 'clearfix') }}>
     {{ content }}
  </div>
</article>

```

# Answer
You can print the node

Title as

> {{ label }}

Body

> {{ content.body }}

Try this,

> {{ content.body| raw }}

It will be used to remove the markup in the content.
> 1 votes

---
Tags: theming
---


title: video embed field module folder path

text:
# Question
Title: video embed field module folder path
I have placed the video embed field module in the location sites/all/modules/contrib/video embed field. Now I have problem with generating youtube thumbnail.Is that path I uploadwed the module is correct or need to change the module to some where

# Answer
Yes, you've uploaded the module to the correct location (otherwise you wouldn't have been able to install it).

Failure to generate thumbnails could theoretically be caused by a number of different configuration problems, but the most common would probably be either:

* incorrect permissions on sites/default/files (or a subfolder)
* something blocking the outgoing request to download the thumbnail from YouTube's servers.

Check your server logs and Drupal's watchdog for errors, if there are none you'll probably need to step through the code to find out exactly where and why it's failing.
> 1 votes

---
Tags: 7, views
---


# Question
Title: How can I add a currency field to a content type?
I would like to have a field that accepts U.S. dollar amount. I installed the module: https://www.drupal.org/project/currency. Structure \> content type \> I do not see a field type "Currency". I am not sure how I can add a field to accept USD amount.

How can I add the price field to the content type?

# Answer
> -1 votes
So to add a decimal field.

* edit your content type.
* manage fields
* add new field
* select Decimal from the Field Type dropdown.
* Click the 'Save' button
* Change 'Scale' to 2. These are the cents.
* Click the 'Save field settings' button.
* In the Prefix field add '$'.
* Click the 'Save settings' button

---
Tags: 7, entities
---


title: variables table in D8?

text:
# Question
Title: variables table in D8?
What database table in Drupal 8 replaces `variables` table in Drupal 7?

Where are the values of Configuration stored?

example : `$config->set('message', 'Hi')->save();` Where can I find value of `message` variable in database?

# Answer
In Drupal 8, you can find the equivalent in the `config` table.

```
mysql> desc config;
+------------+--------------+------+-----+---------+-------+
| Field      | Type         | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| collection | varchar(255) | NO   | PRI |         |       |
| name       | varchar(255) | NO   | PRI |         |       |
| data       | longblob     | YES  |     | NULL    |       |
+------------+--------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> select * from config where name = 'system.theme';
+------------+--------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
| collection | name         | data                                                                                |
+------------+--------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
|            | system.theme | a:3:{s:5:"admin";s:5:"seven";s:7:"default";s:6:"bartik";s:5:"_core";a:1:{s:19:"default_config_hash";s:43:"gOjer9hADYYnbCJVZMFZIIM1azTFWyg84ZkFDHfAbTz";}} |
+------------+--------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql>

```

> By default, the "active" configuration is stored in the database ("config" table). This is for performance and security reasons. This is the complete configuration for the entire site at that moment. Configuration can be exported and imported as YAML files, either in it's entirety, or a single piece of configuration, using Drush config commands or the Configuration Manager.

More info: https://www.drupal.org/docs/8/configuration-management/managing-your-sites-configuration
> 6 votes

---
Tags: 8, configuration
---


# Question
Title: Why doesn't watchdog() run when I execute my custom module from Drush?
I have a custom module that performs an import from an XML file. It can be invoked in two different ways: from a menu callback or a custom Drush command.

The import works fine and all of its `watchdog()` calls work fine when I execute it from the menu callback, but when it's executed from Drush, the import works, but no `watchdog()` entries are logged.

Why is this? How can I get `watchdog()` to work in this module when it's triggered from Drush?

# Answer
This is working for me, using the latest Drush dev-master:

`drush @dev ev 'watchdog("system", "test watchdog message.");'`

What I am doing here is just calling the 'watchdog' function directly with the php-eval command, after bootstrapping a dev site. This should produce the same results as a watchdog function called from a module, and in fact I see the message logged in the Drupal admin/reports/dblog page.

Drush does install a watchdog handler, so that it can log the watchdog messages to the console in addition to the dblog page; however, many of these messages are ignored by Drush as uninteresting. To see the full range of watchdog messages that Drush sees, set the --watchdog flag to 'print':

`drush @dev --watchdog=print ev 'watchdog("system", "another watchdog message.");'`

You should see this message printed in the console, and it should also appear in the dblog page.

I'm not sure why you are not seeing anything in your dblog page, but you might try upgrading Drush (if you're running an old version), and try some of these commands and see what results you get. This should give you some indication of where the problem is, at least.

**UPDATE:**

It seems impossible that the Drush hook should be called, but that nothing should be added to the dblog. The watchdog function in core does nothing but call hooks:

https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/watchdog/7

The actual database write happens in function dblog\_watchdog(), which is in dblog.module. It invariantly writes the entry to the database.

The only guess I have at this point in time is that perhaps you have multisite set up, and Drush is targeting the wrong site or database when you call your menu hook via a drush command. `drush status` might help determine if this is the case. Next step would be to put a breakpoint on dblog\_watchdog(), or add some sort of print statement there and see what happens when you run your function from Drush.
> 1 votes

# Answer
You could just pass the stdout from Drush as the stdin to grep.

Example:

```
drush wd-show | grep 'Undefined offset'
```

As a bonus - If you want the errors in a file, try the following:

```
drush wd-show | grep 'Undefined offset' > ~/Undefined-errors.txt
```

This'll put the errors into a text file in your home directory.
> 0 votes

---
Tags: drush, log-messages
---


title: theme_table override not working

text:
# Question
Title: theme_table override not working
I am trying to override / hook `theme_table` from `theme.inc`.
My theme name is `stat`.
I have added following function to my theme `template.php`.

```
function stat_table($variables) {
  //table logic here
  return $output;
}

```

I have dev env configured with xdebug and while function is 'loaded'/processed when displaying page with table, it is never called.
Original `theme_table` is called instead. I already tried clearing cache via `drupal_theme_rebuild();`
Using Drupal 7.

Is there anything I am doing wrong?
How can I debug why is the function not called?

# Answer
use hook\_theme\_registry\_alter.

Example:

```
function MYMODULE_theme_registry_alter(&$theme_registry) {
  $theme_registry['table']['function'] = '_MYMODULE_my_table_theme';
}

function _MYMODULE_my_table_theme($variables) {
...
...
}

```
> 0 votes

---
Tags: theming, hooks
---


# Question
Title: How do I display a view content for a specific user?
There are several views to show the content that is restricted by the page\_access module. For now, the view shows all the content. Ideally, it must show the content that the specific user is allowed to see.

How can I achieve this?

# Answer
You can set permission for the specific role in view. Check the access in page/block settings

Change the access permission to role, then check the access for the specific roles for view content.

For example, Restrict View for the authenticated user. So, the users who are belonging to the authenticated user roles can able to access the content, other roles cant access it.
> 0 votes

---
Tags: views
---


# Question
Title: How to test if current page is an admin page?
At some point I started using the following code to test if current page is an admin page:

```
  $route = \Drupal::routeMatch()->getRouteObject();

  $is_admin = \Drupal::service('router.admin_context')->isAdminRoute($route);

```

But I found that this fails on node edit pages in hook\_entity\_load().

How do we test if we are on an admin page in Drupal 8? Something like path\_is\_admin() in Drupal 7?

I found that if I test the same node edit page path from outside hook\_entity\_load, using the code on this page (https://api.drupal.org/api/drupal/includes%21path.inc/function/path\_is\_admin/7.x) it works.

```
use Symfony\Component\HttpFoundation\Request;
use Symfony\Cmf\Component\Routing\RouteObjectInterface;

$path = '/node/75/edit';
$request = Request::create($path);

$route_match = \Drupal::service('router.no_access_checks')->matchRequest($request);
$route = $route_match[RouteObjectInterface::ROUTE_OBJECT];
$is_admin = \Drupal::service('router.admin_context')->isAdminRoute($route);

```

But if I try to add this code in hook\_entity\_load using the current path, I get a fatal loop.

I think where I'm stuck is loading the current route in hook\_entity\_load.

# Answer
> 39 votes
*** Updated ***

When I first answered this question, node edit and taxonomy edit pages weren't set as admin routes. So I added separate checks for those. Such separate checks aren't necessary any more. The following seems to cover it pretty well:

```
if (\Drupal::service('router.admin_context')->isAdminRoute()) {
 // do stuff
}

```

If you want to check a route other than the current route, you can pass it into isAdminRoute().

Note, the above way won't work for node edit pages or taxonomy term edit pages if you uncheck "Use the administration theme when editing or creating content" on the theme admin page at /admin/appearance. Then you'd need a separate check.

*** Original Answer: ***

To test if a page is an admin page, you can use a two step process. Since regex for the node edit may not be using the admin theme.

**First I use the isAdminRoute method:**

```
  $route = \Drupal::routeMatch()->getRouteObject();

  $is_admin = \Drupal::service('router.admin_context')->isAdminRoute($route);

```

**Then you can use an additional check for the path to see if it's a node edit page:**

```
  $current_path = \Drupal::service('path.current')->getPath();
  if(preg_match('/node\/(\d+)\/edit/', $current_path, $matches)) {
    $is_admin = TRUE;
  }

```

Here's a pretty elaborate, but pretty complete way to test for node and taxonomy term edit pages as well as other admin routes:

```
  $route = \Drupal::routeMatch()->getRouteObject();

  $is_admin = FALSE;
  if (!empty($route)) {
    $is_admin_route = \Drupal::service('router.admin_context')->isAdminRoute($route);
    $has_node_operation_option = $route->getOption('_node_operation_route');
    $is_admin = ($is_admin_route || $has_node_operation_option);
  }
  else {
    $current_path = \Drupal::service('path.current')->getPath();
    if(preg_match('/node\/(\d+)\/edit/', $current_path, $matches)) {
      $is_admin = TRUE;
    }
    elseif(preg_match('/taxonomy\/term\/(\d+)\/edit/', $current_path, $matches)) {
      $is_admin = TRUE;
    }
  }

```

# Answer
> 14 votes
The following is a bit more concise, and also captures node edit pages when they're configured to use the admin theme. The `isAdminRoute` method uses the current Route if none is specified:

```
  /** @var \Drupal\Core\Routing\AdminContext $admin_context */
  $admin_context = \Drupal::service('router.admin_context');
  if (!$admin_context->isAdminRoute()) {
    // perform tasks.
  }

```

---
Tags: 8, routes
---


# Question
Title: How to use conditions on a REPLACE expression?
For an autocomplete, I'm searching a table of address (full address in one column).

Example: `123 Example building, Somestreet, Town, QW1E 2RT`

To improve the search I want to remove the space, so you can search `QW1E2RT` or `QW1E 2RT`, however, I obviously don't want that to be displayed to the user.

I think I'm most of the way there:

```
$query = \Drupal::database()->select('mctable', 'mc');
$query->addField('mc', 'a_address');
$query->where('REPLACE(mc.a_address, \' \', \'\') LIKE \':value\'', [':value' => '%' . $string . '%']);
$query->distinct();
$rows = $query->execute();

```

The problem is that the `:value` placeholder doesn't appear to be passed through… If I hardcode a value in the "snippet" it works.

I originally tried with:

```
$query->addExpression('REPLACE(mc.a_address, \' \', \'\')', 'a_address');
$query->condition('a_address','%' . $query->escapeLike($string) . '%', 'LIKE');

```

But couldn't figure out how to use the expression in the condition.

Many Thanks for reading and helping.

# Answer
> 0 votes
The problem with the code above is the apostrophes around the placeholder.

`LIKE \':value\'',` should be `LIKE :value',`.

I would still like to know how to do this with `addExpression` though :-/

---
Tags: database
---


# Question
Title: Add field to display in views using a custom table
I joined a custom table in an existing Views (using hook\_views\_query\_alter) and now I'd like to display fields from this table.

Any idea how to do it ?

Thank you

# Answer
For your custom table you need to add custom field handler for views. Check out below link for example code.

https://gist.github.com/juampynr/5816530

Hope this will help.
> 1 votes

---
Tags: views, 8
---


title: Delete node without Confirm

text:
# Question
Title: Delete node without Confirm
How to Delete nodes for specific Content type without redirect to a confirm delete page ?

```
function _node_delete_function($node) {
  if ($node->type == 'bills') {
    node_delete($node->nid);
    drupal_goto();
 }
  else {

   return drupal_get_form('node_delete_confirm', $node);
  }
}

```

Any help?

# Answer
You can use hook\_menu\_alter().

Example :

```
/**
 * Implements hook_menu_alter().
 */
function Module_menu_alter(&$items) {
  $items['node/%node/delete']['page arguments'] = array('_custom_node_delete', 1);
}

/*
 * Custom delete.
 */
function _custom_node_delete($form, &$form_state, $node) {
  node_delete($node->nid);
  cache_clear_all();
  watchdog('content', '@type: deleted %title.', array('@type' => $node->type, '%title' => $node->title));
  drupal_set_message(
    t('@type %title has been deleted.', array('@type' => node_type_get_name($node), '%title' => $node->title))
  );
  $form_state['redirect'] = '<front>';
}

```
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: How to allow users to attribute accumulating points to nodes?
I would want to make a thing in priori simple: allow users to attribute (grant) a selectable amount of accumulating *points* to nodes.

I tried various modules (Fivestar, etc.), but these modules are about a note (or a score like '4/5') and not of a number of accumulative points.

It would be necessary from a field (for example list of selection), make increase or decrease the value of another field.

Anybody has an idea?

**Notes**:

* Fivestar allows to give a note (for example: 4 on 5), while I wish to give points which accumulate. Points: simple value. Give X points to this node. For example: I give 5 points to this node because I find this a good node.
* Multiple users could give a different number of points. The functioning would be close to Fivestar, except that instead of having an overall average there would be a total number of points.
* There would be a field of a node which stores the accumulation of points, and possibly one other to give points.

# Answer
> 1 votes
### Step 1 - Use the Flag module

I'd definitely use the Flag module for what you're trying to achieve. To allow authorized users (to use such flag) to flag relevant nodes. Maybe you want to limit them to only selected content types also.

### Step 2 - Add a field to a Flag to specify the points

However, to also implement those *points* to nodes that get flagged, you should configure the flag (you only need 1 flag!) by attaching a **field** to such flag. Such field can then be used to enter, or select, any of the allowed values of points you want to be granted (appointed) to a node that gets flagged by such flag.

However when doing so, make sure to also be aware about (and do) what is described in Attaching fields to flags, i.e.:

> By default, Flags use the "JavaScript toggle" link-type. While this allows entities to be flagged without reloading the page, users cannot set any field values with the Flag. In order for users to set a Flag's field values, you must use the "Form" link type.
>
> Navigate to `Administration > Structure > Flags` page. Click the Edit link for the Flag. Scroll down to the Display Options box and select the Confirmation Form radio button.

### Step 3 - Add some 'Total points' field to your nodes

Define some other field in the content types for the nodes you want to use these points for, which will contain the total number of points. And which will get updated each time a node gets flagged with '+X' (or '-Y') points, as explained in the next step.

### Step 4 - Use the Rules module to maintain the value of the 'Total points'

The Rules module integrates extremely well with the Flag module. So it should be fairly simple to create a rule to maintain the value of the 'Total points'. Here is a blueprint (to avoid writing an entire manual ...) of this rule:

* Rules Event: when a node is flagged (with the flag you created in step 1)
* Rules Conditions: whatever you might need (if anything), on top of what is not yet covered by the way you configured the flag.
* Rules Action(s): Perform some Rules Actions that use the value of the points as specified by the user who flagged the node, and then adds that to the current value of the 'Total points' field. For an example of such calculation, refer to this answer to the question about "How to add up all items of a field collection field using Rules?". In your case here, you don't need the 'loop' (you're not processing a field collection, only 2 fields for which you want to calculate the sum of it).

### Summary

Using Flag (with 1 extra field) and Rules, and by adding a field (for 'Total points') to relevant content types, the above is how you can create something similar to what User Points can do, though with a summary like so:

> provides `a technique` an API for `nodes` users to gain or lose points `for selected nodes` performing certain actions on your site.

And btw ... zero custom code involved ...

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


# Question
Title: How to create a template for a Views row style?
I want to create a template file for a Views row style. I have created a template file for a field as `views-view-fields--menu.tpl.php` and output style file as `views-view--menu.tpl.php`.

How to create a template for a view row style?

# Answer
In Advanced section in your view, there is a theme option in the last row. On clicking it you can get suggestions for possible template files in row style output sub heading. In this the last option is the most specific one.

Also on clicking the row style output heading you can get the code of default row style tpl which is getting called currently, which you can add in your tpl file and override it as per your requirement.
> 3 votes

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


# Question
Title: How to migrate a value into a field attached to a taxonomy_term (from CSV using YML)
I'm trying to migrate a CSV file of taxonomies (cities) into Drupal 8. The CSV has a code and the city name, for example:

```
City_Code,"Name"
1234,"CITY A"
5678,"CITY B"

```

I have the following as my current migration, which is working, and importing the city names. My problem is I also added a field with the machine name `field_legacy_id` to my term (Drupal 8), which I would like to populate with the OLD `City_Code` for reference later.

```
langcode: en
status: true
dependencies: {  }
id: cities
class: null
field_plugin_method: null
cck_plugin_method: null
migration_tags: null
migration_group: null
label: 'My Import'
source:
  plugin: csv
  path: /path/to/data.csv
  delimiter: ','
  enclosure: '"'
  header_row_count: 1
  keys:
    - City_Code
  column_names:
    0:
      City_Cd: City_Code
    1:
      Name: Name
process:
  vid:
    plugin: default_value
    default_value: city
  name: Name
  field_leagcy_id: City_Code
destination:
  plugin: 'entity:taxonomy_term'
migration_dependencies: null

```

The `field_legacy_id` seems to be ignored and I can't figure out how to get the migration to populate the field value. Thanks.

Edit: This is the field attached to the `taxonomy.vocabulary.city`:

```
langcode: en
status: true
dependencies:
  config:
    - field.storage.taxonomy_term.field_legacy_id
    - taxonomy.vocabulary.city
id: taxonomy_term.city.field_legacy_id
field_name: field_legacy_id
entity_type: taxonomy_term
bundle: city
label: legacy_id
description: ''
required: false
translatable: false
default_value: {  }
default_value_callback: ''
settings:
  min: null
  max: null
  prefix: ''
  suffix: ''
field_type: integer

```

# Answer
Looks like the field name is misspelled?

```
  field_leagcy_id: City_Code

```
> 0 votes

---
Tags: entities, taxonomy-terms, migrations
---


# Question
Title: Is it possible to use the Forena module in conjunction with the Flot module?
I need to plot based on some data that will be fetched from an external (non-drupal) database. I have found the Forena module, but in the part I do not like about the graph utility it uses by default.

Is it possible to use the Flot module in conjunction with Forena?

The Forena module says: "Virtually any JavaScript library may be used with Forena to produce amazing displays".

How is it implemented?

# Answer
> 0 votes
I'm not aware of a way to use the Flot module in conjunction with the Forena (disclosure: I'm a co-maintainer) module.

About "Virtually any JavaScript library may be used with Forena ...": have a look at the feature request # 2364427, especially these comments in it:

Another approach is to write your own "renderer", as a variation of the FrxSVGGraph renderer (which extends FrxRenderer), and which is how the current support for the PHP SVGGraph library is implemented.

---
Tags: charts, forena
---


# Question
Title: Insert data into entity programmatically
I've installed contact storage module, it's provide storage for Contact messages which are fully-fledged entities in Drupal 8. What I want to do, is to insert data programmatically from my custom module into the entity of the contact storage

# Answer
Yep. Just use any of the methods available to create the entity and save it.

```
use Drupal\contact\Entity\Message;

$message = Message::create([
    // And other fields required...
    'subject' => 'Subject',
    'message' => 'Message...',
    'recipient' => 1,
]);
$message->save();

```
> 4 votes

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


# Question
Title: Hide webform after the user's first submission
How would I hide the webform in drupal7 after user's(authenticated user) first submission.Later the user should not be able to view the webform again. Please help me on this.

# Answer
After creating your webform, go to the "Form Settings" under "Webform". In case you don't find it, here's the URL: node/Nid/webform/configure (I choose not to remind you of the Nid that you should change :)).

Here, you should see an option for "Per User Submission Limit"- In your scenario, Limit each user to "1" submission(s) "ever".
> 0 votes

---
Tags: webforms
---


# Question
Title: Is it possible to display a Mailchimp campaign (the newsletter, not a link) from my Drupal 7 website?
I've tried using views, but when I choose the rendered entity display of the MailChimp campaign field, the result is empty even though I've created 3 campaigns from within my Drupal site. I don't think views is the answer anyhow as creating a campaign from a Drupal site still requires logging in to MailChimp to send. So I need to be able to display newsletters created in MailChimp.

I've resorted to displaying the archive of the latest newsletter in an iframe. Besides being unattractive, it requires my client perform extra steps which is counterproductive. Not to mention, it is not responsive.

# Answer
> 2 votes
Outside of linking or iframe embedding, there isn't a way of simply displaying the content as, say, a Drupal page. There is actually a reason for this.

First, the content of the email is already an entire webpage: it (should) have an `<html>` tag and it will likely have `<head>`, `<style>`, and `<body>` sections. So it actually makes plenty of sense to just include it as an iframe directly on a page since it will need it's own space to format the content properly.

But let's say you decide to use the /campaigns/content.format API call to grab the actual content of the campaign. You'd likely still need to strip away the CSS and other HTML from within the content to make it display within your page nicely.

And with regards to synchronization, it only syncs from Drupal to Mailchimp. You'd need some other way of grabbing those campaigns if you wanted to see them in Drupal. This is especially useful because Mailchimp is used by many who have a single account + multiple clients.

# Answer
> 0 votes
I use Kompozer to edit my site, it's WYSIWYG software and easy to use. Just open the Mailchimp campaign URL in Kompozer and copy and paste what you need from there into your page. You may have to tweak it a little but it works for me :-)

Look here www.brycebrownart.com/arts-news

---
Tags: emails
---


# Question
Title: Javascript errors caused by <script> elements being wrapped inside a <strong> tag
I noticed that my site footer and a lot of `<script>` elements are wrapped inside a `<strong>` tag.

This is causing a lot of JS errors of the type:

> Uncaught TypeError: Cannot read property 'permissionsHash' of undefined
>
> Uncaught TypeError: Cannot set property 'StateModel' of undefined
>
> Uncaught TypeError: Cannot set property 'AuralView' of undefined

How can I fix that?

# Answer
I found out that the checkbox 'Trim this field to a maximum number of characters' was checked in one of my views which was trimming some HTML from the field content (closing tags) and causing the issue.

checking the option 'Field can contain HTML' fixed the issue for me.
> 0 votes

---
Tags: theming, 8
---


# Question
Title: After installing any module I get "The website encountered an unexpected error. Please try again later."
I'm a Drupal beginner and after setting up my site and installing some modules I now have this annoying bug.

After installing any module, doesn't matter what one, I get this white page: https://i.stack.imgur.com/VL6UO.jpg

Even though it says it has encountered an error, the module actually just gets enabled without any other error logs.

https://i.stack.imgur.com/3falV.jpg

(In the screenshot I tested it by enabling ban and telephone module, each time after enabling it in the module list I got an error page. But the modules actually work and there aren't any errors to be found on the logging page.

It's quite annoying to get a white error page instead of the blue loading bar.

Anyone have an idea what the issue here is?

# Answer
Enable error reporting in Drupal. This way, Drupal can print the errors and stack traces on the page when the errors occur. Also, consider enabling the module using Drush particularly with `--verbose` and `--debug` options. This prints logging info while enabling the module.

The source of this could be anything. It could be a bad module install script, bad configuration, bad module hook code, or a malformed template (for that page). I usually get these pages when code tries to access non-existent properties or indexes or have modules that don't play nice with each other. This usually look harmless. But if the error cuts into execution and there was data that was still to be saved, it might result in a bad system.
> 0 votes

---
Tags: 8
---


# Question
Title: Create a postcard for each item in a view
I have a view of user data. I want to print a postcard for each one with name and address from the view on the front and other data from the view on the back. Ideally, there will four postcards per printable page, so matching up front-side data and back-side data is a challenge.

# Answer
> 0 votes
I solved this problem with a custom module. Total php, html, and css is 250 lines. Cards can be printed double-sided or fronts and backs separately for non-duplex printers. I prepare the view with the following code:

```
$view = views_get_view('postcard');
$view->set_display('page');
$view->preview = true;
$view->is_cacheable = false;
$view->pre_execute();
$view->display_handler->preview();
$view->post_execute();

```

To access view data after the above processing, I wrote a simple `getViewData()` function that uses Drupal's `field_get_items()`.

---
Tags: views
---


# Question
Title: Dynamic pricing of products/line items with a "pricing entity"
I'm trying to achieve a pricing functionality in which product/line item's price is configured in an external entity. So that I can have one product which can be priced by multiple entities depending on which is being viewed.

This external entity is a "host" entity or a product display which has two fields: product reference and a price field (float).

Now, when customer visits this host entity page and adds a line item to cart it should change the price according to host entity price field.

At first I tried this with Rules but it was just so inconsistent that I decided to look other options. So here's a piece code that I think could solve this:

```
    // Alter the price in list and single product page.
function commerce_dynamic_pricing_commerce_product_calculate_sell_price_line_item_alter($line_item){

    if ($node_wrapper = entity_metadata_wrapper('node',_commerce_dynamic_pricing_menu_get_any_object()) ) {

        if ($node_wrapper->type->value() == "price_list") {

            $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);

            dsm($line_item_wrapper->commerce_unit_price->amount->value(). 'Old price');

            foreach ($node_wrapper->field_collection_licenses as $key => $license) {
                if ($line_item_wrapper->commerce_product->product_id->value() === $license->field_license->product_id->value()) {
                                            $line_item_wrapper->commerce_unit_price->amount->set($license->field_license_price->value());
                }

                $line_item_wrapper->save();
            }

            dsm($line_item_wrapper->commerce_unit_price->amount->value(),'New price');
            }
        }
}

```

The problem with this code is that the price isn't changed/updated. I'm not sure that how the price should be modified.

# Answer
So this first alter hook handles price on product display.

But price needs to be handled again with another hook: commerce\_dynamic\_pricing\_commerce\_cart\_line\_item\_refresh. This handles prices regarding current line items in cart.

I also needed to avoid combining same type of line items into "quantity groups".This works well in:

```
    $line_item->data['context']['add_to_cart_combine'] = FALSE;

```
> 0 votes

---
Tags: commerce
---


title: Ajax filter in exposed view not working

text:
# Question
Title: Ajax filter in exposed view not working
I am embedding a view as such:

```
function theme_module_name_element($element) {
  $view = views_get_view('view_name');
  $view->set_use_ajax(TRUE);
  $output = $view->render();
  return $output;
}

```

The view is displayed then by the filefield sources module but when you try to search it won't use ajax. I'm assuming this has something to do with the js not being loaded but I just can't figure out how to get this going!

Any ideas?

Edit: This might be related to this: http://drupal.org/node/386388

Edit 2: The pager works and when it has been used the search works...

Edit 3: When the pager is pressed (and everything works fine) there is html added to the form so it goes from:

(Edit 3 update: If I had to guess I would say "Drupal.behaviors.ViewsAjaxView" from ajaxViews.js isn't being executed when the filefield\_sources source is being chosen.)

```
<div class="view-filters">
    <div><div class="views-exposed-form">
        <div class="views-exposed-widgets clear-block">
            <div class="views-exposed-widget views-widget-filter-title">
                <label for="edit-image-title">Search</label>
                    <div class="views-widget">
                        <div class="form-item" id="edit-image-title-wrapper">
                            <input type="text" maxlength="128" name="image-title" id="edit-image-title" size="30" value="" class="form-text">
                        </div>
                    </div>
                </div>
                <div class="views-exposed-widget views-submit-button">
                    <input type="submit" id="edit-submit-Filefield-Sources-Imagebrowser" value="Apply" class="form-submit">
                </div>
            </div>
        </div>
    </div>
</div>

```

to:

```
<div class="view-filters">
    <form action="/" accept-charset="UTF-8" method="get" id="views-exposed-form-Filefield-Sources-Imagebrowser-default" class="views-processed">
        <div><div class="views-exposed-form">
            <div class="views-exposed-widgets clear-block">
                <div class="views-exposed-widget views-widget-filter-title">
                    <label for="edit-image-title">Search</label>
                        <div class="views-widget">
                            <div class="form-item" id="edit-image-title-wrapper">
                                <input type="text" maxlength="128" name="image-title" id="edit-image-title" size="30" value="arnar" class="form-text">
                            </div>
                        </div>
                    </div>
                    <div class="views-exposed-widget views-submit-button">
                        <input type="submit" id="edit-submit-Filefield-Sources-Imagebrowser" value="Apply" class="form-submit">
                    </div>
                </div>
            </div>
        </div>
        <input type="hidden" name="view_name" value="Filefield_Sources_Imagebrowser">
        <input type="hidden" name="view_display_id" value="default">
        <input type="hidden" name="view_args" value="">
        <input type="hidden" name="view_path" value="node/add/dagskrafaerslur">
        <input type="hidden" name="view_base_path" value="null">
        <input type="hidden" name="view_dom_id" value="655136b3027e2ef4608dfbaa7605db4c">
        <input type="hidden" name="pager_element" value="0">
    </form>
</div>

```

(Notice the addition of the form tag and input elements.)

# Answer
Enable the `Ajax` in `Views Basic Setting` and remove `$view->set_use_ajax(TRUE);` and check.
> 2 votes

# Answer
Not sure what you mean by: "the js isn't applied"

So the shotgun approach...

---

Check the HTML source for .js files:

misc/ajax.js
sites/all/modules/views/js/ajax\_view.js

---

views\_add\_js() is the command that loads the javascript.

http://api.drupal.org/api/views/views.module/function/views\_add\_js/7

---

If the js files aren't there maybe the scripts section in the header doesn't get updated:

$vars\['scripts'\] = drupal\_get\_js();

From: http://drupal.org/node/386388#comment-3176034
> 2 votes

# Answer
I just fixed a similar issue in my page. From your listing:

```
<input class="form-submit" type="submit" id="edit-submit-Filefield-Sources-Imagebrowser" value="Apply">

```

What is missing here (and was also missing in my case) are the classes which make autosubmitting code work. From my code (after fixes):

```
<input class="ctools-use-ajax ctools-auto-submit-click js-hide form-submit" type="submit" id="edit-submit-view-path" name="" value="Apply" />

```

In order to get the classes ctools-use-ajax ctools-auto-submit-click js-hide applied on input I had to fix theming. Check where your buttons are themed and if the classes aren't removed. I suspect this might be the reason because the attributes of your input are rendered in different order as in original Drupal theme. As for quick fix you can use a standard template coming with standard Drupal installation. Hope that helps.
> 0 votes

# Answer
I had the exact same problem down the same experience where using the pager caused the exposed filters to start using Ajax. In my case it was because the code was making the view get rendered inside of another form. If the views code was moved to render above the other form the JS was properly applied and the exposed form used Ajax submission. This makes sense since forms are not allowed inside of other forms.
> 0 votes

---
Tags: 6, views, ajax, files
---


# Question
Title: Multisite: Only Drupal Root recognized for subpath
I am having a Drupal 8 multisite installation:

* Hostname: example.com
* 1st Drupal site: in example.com
* 2nd Drupal site: in example.com/sub/path

I have configured this in sites.php:

```
$sites['example.com.sub.path'] = 'subpath.example.com';
$sites['example.com'] = 'example.com';

```

The directories example.com and subpath.example.com contain the corresponding settings.php, setting.local.php, etc files.

Additionally, I have added this to the apache configuration (apache 2.4):

```
DocumentRoot /var/drupal
Alias /sub/path /var/drupal
Alias / /var/drupal
  <Directory /var/drupal/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Include /var/drupal/.htaccess
  </Directory>

```

The site example.com works as expected. I could install the site example.com/sub/path, but I now can just go to the home page. Every sub-page goes instead to the example.com configuration and gives an appropriate 404 error.

What did I do wrong/overlook?

Any help greatly appreciated!

# Answer
Adding a rewrite rule into the .htaccess file fixes the problem. Without the rewrite rule for this path, the default rewrite rule goes into effect, pointing to the `example.com/index.php` instead of `example.com/sub/path/index.php`.

Disadvantage: I will have to patch .htaccess every time I upgrade Drupal core.

```
RewriteCond %{REQUEST_URI} ^/sub/path/(.*)$
RewriteRule ^(.*)$ /sub/path/index.php [L,QSA]

```
> 0 votes

---
Tags: 8, multi-sites
---


# Question
Title: Can one domain be hosted on two drupal instances?
I have a huge Drupal 6 site, and a small, newer partial version of the site on Drupal 8. Instead of migrating, we decided to build a brand new site from scratch.

Is it possible to host the site such that:

http://www.sitename.com takes user to --\> new D8 site

http://www.sitename.com/topic1 /topic2 takes user to new site.

http://www.sitename.com/topic3 /topic4 (everything else) takes user to old D6 site?

Thanks!

# Answer
> 2 votes
You can use a reverse proxy for this, both Apache and Nginx support this. What you do is that you make the Drupal 6 site available on a different URL. This might be even a local url, like sitename2.local. Add this to the hosts file on your server (/etc/hosts on Linux) and point it to 127.0.0.1. Make sure you set up a virtual host in your webserver to point sitename2.local to the root directory of your Drupal 6 site.

By using a reverse proxy you tell your webservice to forward calls to /topic/4 to sitename2.local/topic/4 and return it to the user, just like a proxy. In Nginx it should look something like:

```
location /topic/4 {
    proxy_pass http://sitename2.local/topic/4;
}

```

For Apache you need to enable the proxy modules:

```
> a2enmod
> proxy proxy_ajp proxy_http rewrite deflate headers proxy_balancer proxy_connect proxy_html

```

Your virtual host file should look something like this:

```
<VirtualHost *:*>
    ProxyPreserveHost On

    ProxyPass /topic/4 http://sitename2.local/topic/4
    ProxyPassReverse /topic/4 http://sitename2.local/topic/4
    (...)
</VirtualHost>

```

If you Google around for reverse proxy you will find tons of information on how to exactly configure them.

---
Tags: 8
---


title: Styling the layout of a content type

text:
# Question
Title: Styling the layout of a content type
I am using drupal 8 and I am trying to get the layout of my content type "jacuzzi" to go from this:

To this

As you can see, I am using bootstrap. What do I have to change (css or tpl or something else?) to group the text fields and add the right classes?

Thanks in advance

# Answer
You can use node--(machine name of contenttype).html.twig to achieve this thing.

```
<div class = "col-md-6 someclass">{{ content.field_machinenameofimage }}</div>
<div class = "col-md-6 someclass">{{ content.field_machinenameofotherfields }}</div>

```

Replace the {{ content }} by the above code. And change the above code how you want to achieve.
> 0 votes

---
Tags: theming, nodes
---


# Question
Title: How to unpublish or disable webform components without code for d7?
**How to unpublish or disable webform components without code for d7?**

I've seen answers to do this programmatically, but I'm looking for a simple "unpublish" or "disable" field from back end GUI, is that possible?

# Answer
> 0 votes
Webform itself offers no UI-based method for disabling/un-publishing components.

Unless you can find something in contrib that can help (or perhaps convince the developer of webform to add it as a feature), you'll need custom code to achieve it.

As an example you may be able to configure Webform Conditional to disable fields unconditionally, or based on a contrived condition, to simulate the effect. But it wasn't necessarily built for the purpose you need.

---
Tags: webforms
---


# Question
Title: Any risks associated with habitually updating/reverting ALL features in drush?
I want to start using drush commands to simply update all or revert all features (depending on which environment I'm in) instead of doing them one by one. What are the risks involved or questions I should ask myself before habitually just updating all or reverting all features?

`drush fra` (to revert all on production and test servers)

`drush fua` (to update all on dev environment)

Thanks!

# Answer
> 1 votes
Personally, I do "**revert-all**" **all the time** (to test / roll out changes on Test and Production). Because no feature update should be overlooked before / during release.

Personally, I would find **"update-all" way too risky**. Because Dev potentially contains many small tests, changes, trials, and failed attempts. Those should never slip into a (bloated) commit. Let alone reach a "revert-all" on Production.

An "update-all" would also conflict with my understanding of **"atomic commits"**. Where commits are always (many) small changes, exclusively.

Those are easily read. Easily understood. Easily undone. (And all features contain only small components (are not bloated).)

Changing a content-type? Do "drush fu this-content-type-feature". Commit.

Updating a view? If happy, then do "drush fu that-view-feature". Commit. Next.

Makes for very **readable** "git diff"s, without including any accidental or experimental changes from a Dev.

# Answer
> 1 votes
In my opinion, first and foremost thing which should be taken into consideration is that your feature should not have any changes different from your development environment.

secondly, make sure that all of the fields of a content type have same type and widget as that are in your production environment.

You can also take backup of the db before reverting the features in case you are making any major changes.

---
Tags: 7, drush, features
---


# Question
Title: How to add custom checkout pane to drupal-commerce in drupal 8
I installed drupal-commerce on drupal 8, straightforward and easy using composer. Now I need to collect some extra information from customer at checkout, and I understood, I need to install a custom checkout pane.

Unfortunately there is no module for that, so I guess, I have to write a custom module. I know how to generate it with drupal-console, but than I'm lost...

It should be possible to copy some of the code from commerce checkout module, but I have no idea where to start. Can someone help me with that? Thanks!

# Answer
Here is an excerpt from our step-by-step guide "Creating a custom checkout pane for Drupal Commerce in Drupal 8". The rest can be found here: https://ws.agency/blog/creating-custom-checkout-pane-drupal-commerce-drupal-8

"In this article, I'll show how you can create a custom checkout pane for Drupal Commerce in Drupal 8. For this purpose, we'll create a checkout pane with a configuration form and the ability for users to add coupons to their order.

Checkout pane needs to be created with the correct annotation and in the correct namespace. We'll create *CommerceCoupons* class in *module\_name/src/Plugin/Commerce/CheckoutPane* directory with annotation like in code below.

```
namespace Drupal\module_name\Plugin\Commerce\CheckoutPane;

use Drupal\commerce_checkout\Plugin\Commerce\CheckoutFlow\CheckoutFlowInterface;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneBase;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides the coupons pane.
 *
 * @CommerceCheckoutPane(
 *   id = "coupons",
 *   label = @Translation("Redeem Coupon"),
 *   default_step = "order_information",
 * )
 */
class CommerceCoupons extends CheckoutPaneBase implements CheckoutPaneInterface {

/**
 * {@inheritdoc}
 */
public function __construct(array $configuration, $plugin_id, $plugin_definition,     CheckoutFlowInterface $checkout_flow, EntityTypeManagerInterface $entity_type_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $checkout_flow, $entity_type_manager);
}

```

This means that our custom checkout pane will have an id *'coupons'* and will be labelled as *Redeem Coupon* and will be set on order information step by default.

First, we'll create the settings (configuration) form for our pane. For this purpose, we'll have settings if we, for example, want to set up that user has the ability to redeem only one coupon on order. For this, we'll have to implement four functions.

First, we'll setup our default configuration.

```
/**
 * {@inheritdoc}
 */
public function defaultConfiguration() {
  return [
      'single_coupon' => FALSE,
    ] + parent::defaultConfiguration();
}

```

Then we'll implement summary for our configuration form.

```
/**
 * {@inheritdoc}
 */
public function buildConfigurationSummary() {
  $summary = !empty($this->configuration['single_coupon']) ? $this->t('Single Coupon Usage on Order: Yes') : $this->t('Single Coupon Usage on  Order: No');
  return $summary;
}

```

Next, we'll build our configuration form..." Continue reading...
> 4 votes

# Answer
You can add a plugin in your custom module for implementing the custom checkout pane. a plugin similar to BillingInformation.php in 'commerce/modules/checkout/src/Plugin/Commerce/CheckoutPane'. I hope this gives you a kickstart.
> 3 votes

---
Tags: 8, commerce
---


# Question
Title: How do I get parameters from form redirect?
I've made a form and I'm trying to get the submit result into a redirect page with URL api:

```
 public function submitForm(array &$form, FormStateInterface $form_state)
    {

    $metier=$form_state->getValue('metier');
    $position=$form_state->getValue('position');

    //$form_state->setRedirect('recherche.resultat',array('param'=>'test');

    $url = new Url('recherche.resultat');
    $url->setOptions(array('param'=>'test2'));
    $url->setRouteParameters(array('param'=>'test2'));

    $form_state->setRedirectUrl($url);

    drupal_set_message("envoyer");

}

```

I set two options :

```
$url->setOptions(array('param'=>'test2'));

```

and

```
$url->setRouteParameters(array('param'=>'test2'));

```

The form redirect me and this is my controller :

```
public function resultat()
{
    $request = \Drupal::request();
    $url = Url::createFromRequest($request);
    kint($url);
    kint($url->getOptions());
    kint($url->getRouteParameters());
    return array('#markup'=>t('test'));

}

```

The two methods :

```
    kint($url->getOptions());
    kint($url->getRouteParameters());

```

are empty

This is my routing :

```
 recherche.resultat:
  path: '/resultat'
  defaults:
    _title: 'resultat'
    _controller: '\Drupal\recherche\Controller\ResultatRechercheController::resultat'
  requirements:
     _permission: 'access content'

```

The parameters are in the URL and I can get them with $\_GET but how can I get with the URL API?

# Answer
> 7 votes
Ok i got it by this way :

So i have 2 parameters from my form to pass to my controller :

```
public function submitForm(array &$form, FormStateInterface $form_state)
{

    $metier=$form_state->getValue('metier');
    $position=$form_state->getValue('position');

    $url = \Drupal\Core\Url::fromRoute('recherche.resultat')
          ->setRouteParameters(array('metier'=>$metier,'position'=>$position));

    $form_state->setRedirectUrl($url);

}

```

The key is in the YAML routing, you need to build your path like that for get parameters ( name of parameters need to be same as your route, see previous function (submitForm)) :

```
recherche.resultat:
  path: '/resultat/{metier}/{position}'
  defaults:
    _title: 'resultat'
    _controller: '\Drupal\recherche\Controller\ResultatRechercheController::resultat'
    metier: ''
    position: ''
  requirements:
     _permission: 'access content'

```

And in my controller for get my parameters :

Class: ResultatRechercheController

```
 public function resultat($metier, $position)
    {

        kint($metier);
        kint($position);

        return array('#markup'=>t('la premiere spécialite est @specialite',array('@specialite'=>'test')));

    }

```

And the URL is clean :

> localhost:8888//monsite.com/resultat/{metier}/{position}

# Answer
> 3 votes
You can get the get attributes directly from the request object `\Drupal::request()->attributes->get('param');` or `\Drupal::request()->query`

Source: https://api.drupal.org/api/drupal/core%21lib%21Drupal.php/function/Drupal%3A%3Arequest/8

# Answer
> 0 votes
In a block form, you can simply add your parameters in your form redirect url, without routing :

```
public function submitForm(array &$form, FormStateInterface $form_state) {
  # get form data
    $form_var = $form_state->getValue('input_name')
    ...

  # set form data in url redirect
  $option = [
    'query' => ['testvar' => $form_var],
  ];
  $url = Url::fromUri('internal:/my_url/redirect', $option);

  $form_state->setRedirectUrl($url);
}

```

Then retrieve it and clean it :

```
# retrieve query param
$my_var = \Drupal::request()->query->get('testvar');

# clean for a textfield
$my_var_escaped = Html::escape($my_var);

```

---
Tags: forms, 8, redirection
---


title: Manage programmatically added fields

text:
# Question
Title: Manage programmatically added fields
I'm working on a custom module that allow anonymous users who add a new content, to register himself in the same form providing a simple email field (user name is the same as email).

In my module I hook the node\_form\_alter to add the email field from the user registration form:

```
function mymodule_form_node_form_alter(&$form, FormStateInterface $form_state) {
  if (\Drupal::currentUser()->isAnonymous()) {

    // Add drupal registration form
    $entity = \Drupal::entityTypeManager()->getStorage('user')->create(array());
    $formObject = \Drupal::entityTypeManager()
      ->getFormObject('user', 'register')
      ->setEntity($entity);
    $user_register_form = \Drupal::formBuilder()->getForm($formObject);

    //kint($user_register_form['account']);
    $form['user_registration'] = $user_register_form['account'];
    unset($form['user_registration']['name']);
  }
}

```

And this works good. In node\_presave I'm expecting the field to register, but i get an error "Field user\_registration is unknown."

```
function mymodule_node_presave(NodeInterface $node) {
  kint($node);

  $email = $node->get('user_registration')->value; // This throws the error

  if ($email) {
    $email_user = user_load_by_mail($email);

    if (!$email_user) {
      /* Create user */
      $email_user = _create_user($email);
    }

    /* Set user as author */
    if ($email_user) $node->setOwnerId($email_user);
  }
}

```

What am I missing?

# Answer
You have to add a custom submit handler to handle these fields. The form fields you add are custom, so they won't be attached to the node.

```
$form['user_registration']['#submit'] = 'custom_user_registration_handler';

```

In the submit handler you'll be able create the user like you're doing no in your presave function. The presave function should load the user and attach it to the node.

Edit \

**Problem**: The node\_presave hook does not contain the email adres so it's not able to lookup the right user.

**Solution**: The default node form has an author form field. You probably hid that field but I think your still able to fill the value. What if you fill the 'author' field with the email value, this will be the user name.

So in your custom submit handler:

* Create the user;
* Fill the (hidden) author form field with the right value (fill the right value in the form\_state object/array?).

The the default form submit handler will do all the hard work for you.
> 1 votes

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


title: How to add dynamic class in li element?

text:
# Question
Title: How to add dynamic class in li element?
**Need to add dynamic class in li element of below code like dymanic democlass1,democlass2...... so-on in loop.**

```
 <div class="rrssb">
 {% if prefix_text %}
 <div class="rrssb-prefix">{{ prefix_text }}</div>
 {% endif %}
 <ul class="rrssb-buttons">
{% for button in buttons %}
  <li class="rrssb-{{ button.name }}">
    <a href="{{ button.link }}" {{ button.class | raw }}>
      <span class="rrssb-icon">{{ button.svg | raw }}</span>
      <span class="rrssb-text">{{ button.text }}</span>
    </a>
  </li>
{% endfor %}

```

# Answer
> 1 votes
You can use

```
{{ loop.index }}

```

this will count up each time it goes through the loop

---
Tags: 8
---


# Question
Title: Url query - using a key with multiple values
I am trying to build a url with a query using the url() function.

```
    $options = array(
        'query' => array(
                'parameter1' => 'value1',
                'parameter2' => 'value1,value2',
        ),
        'absolute' => TRUE,
        'external' => TRUE,
    );
    url ('https://somesite.com/', $options);

```

The URL becomes: `https://somesite.com/?parameter1=value1&parameter2=value1%2Cvalue2`

So commas become encoded as %2C.

How can I build a query that has parameters with multiple values separated by comma?

EDIT: I have to deal with an old API that does not recognize %2C as comma characters, so actual commas have to be present in the end url.

# Answer
> 1 votes
> How can I build a query that has parameters with multiple values separated by comma?

You already have, the commas are just encoded so they can be transported safely as part of the URL.

If you mean how can you stop the `url()` function from encoding special characters: you can't, without editing it. More specifically, you would need to replace its use of `drupal_http_build_query` with something that only selectively encodes special characters, much like `drupal_http_build_query` does itself for the `/` character.

The other options you have are

* Do a string replace on the return value from `url` (or parse it and build it up again to your own spec)
* Roll your own `url` function to your own spec
* Contact the maintainers of the API and ask them to fix their decoding bug. Obviously YMMV on that.

---
Tags: 7
---


# Question
Title: translate the page title in search template file
What is the best way to translate the title in search template file

I use a commercial theme. In :

```
page--search.html.twig

```

I can modify the tytle by replacing :

```
 <h1>{{ title }}</h1>

```

by

```
<h1>Recherche</h1>

```

It works but it is obviously not the best way.

Since search result page is not a node, where is this title ?

I’ve searched in blocks, content, module and I can't find this title.

# Answer
> 1 votes
Drupal 8 has extensive multi-lingual support and French is one of the supported languages.

As administrator, turn on the language module at Administration -\> Extend

Then go to Administration -\> Configuration -\> Regional and Language -\> Languages, click on Add Language and select French. If you want it to be the default language set it as the default and Save Configuration. (This can cause issues if the site is already live!)

The User Interface Translation module (also in core) can be used to import additional translations and to allow you to translate strings manually as needed.

---
Tags: 8
---


# Question
Title: How can I maintain redirects from a non-existing path to an existing one?
With Drupal 7, the Global redirect module provided end users with a great interface to input redirects from a non-existing path to an existing one. I have installed and enabled the Redirect module for Drupal 8, but I do not see where end users can maintain a list of redirects. We are migrating an old site to Drupal 8 and we will need a method to redirect old URLs to new ones.

How can I maintain these redirects using the Redirect module?

# Answer
After you've installed and enabled the "Redirect" module (https://www.drupal.org/project/redirect), you can manage your redirects by going to the redirect list page at `/admin/config/search/redirect`:

You can find this route and all the other routes provided by the "Redirect" module in `redirect.routing.yml`:

```
redirect.list:
  path: '/admin/config/search/redirect'
  defaults:
    _entity_list: 'redirect'
    _title: 'URL redirects'
  requirements:
    _permission: 'administer redirects'

```
> 2 votes

---
Tags: 8, redirection
---


# Question
Title: Using a Third-Party API to dynamically create pages
I have a Drupal website that I'm working on where for section of it, I want to pull data in from an external API and dynamically create pages with this data. Do I need to create a custom module for this? I'm not too sure where to start with this, so any advice would be appreciated!

# Answer
> 0 votes
You have a few options here, though without knowing the API your using, it's hard to nail down exactly what one you would need.

If it's a commonly used service, there might already be a module that exists for it. As a general rule, if there is a module already created to handle it, that should be the way to go.

You might be able to go slightly out of the box if your API spits out some form of feed and use a module to import that feed (it's a bit older, but as an example, feeds does this.) There's a few other ingestion modules out there that might work for you.

Creating your own custom module is, of course, always an option. I know I've written a few import modules, but I normally only do that when the other options are not viable.

---
Tags: services
---


# Question
Title: How to reference a image field and get it's file URI?
I have a paragraph type rn-accordion (rn-acc.html.twig), that has a entity reference revision to rn-accordion-section which houses a bunch of different fields. One of which is an image field (bp\_image\_field); however I am unsure how to reference this field in my twig file. So far I have tried:

```
      <img src="{{ file_url(paragraph.field_bp_image_field.fileuri) }}" class="img-responsive">

      <img src="{{ file_url(element['#object'].field_bp_image_field.0.entity.uri.value) }}" class="img-responsive">

      <img src="{{ file_url(content.field_bp_image_field['#items'].entity.uri.value) }}" class="img-responsive">

```

but the output is always

```
       <img src="/" class="img-responsive">

```

Can someone help steer me in the right direction?

# Answer
> 1 votes
I would suggest not doing this, as you lose the benefits of image styles (the built-in image manipulation feature).

Suggesting you make a hook for this template, pick out the url from the source field, render an image with Drupal APIs, and make the result available as a variable on the template.

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


# Question
Title: How to render a paragraph 'Text (formatted, long)' as full HTML, not escaped
I'm trying to create a custom paragraph template that displays as an accordion. I am able to correctly reference most of the other variables, except for the Text (formatted, long) field types as whenever I do .value for the field, it returns the escaped value so it looks like `<ul><li>text</li><li>text2</li></ul>` instead of the actual bulleted list.

I am able to get the value using .value|raw, but I read that I should be avoided and I'd like to get this perform correctly.

Please let me know if any further information is required.

The following code is under paragraph--rn-accordion.html.twig. I have two paragraph types, rn\_accordion and rn\_accordion\_section(which houses all the different fields). I tried to mirror this from the bootstrap module to get this working.

The troublesome fields are: {{ item\['#paragraph'\].field\_rn\_acc\_1.value }} and {{ item\['#paragraph'\].field\_rn\_acc\_2.value }}

```
            {# Prints Accordion template. #}
            <div{{ attributes.addClass(classes).setAttribute('id', paragraph_id) }} role="tablist" aria-multiselectable="true">
                <div class="panel panel-default consortia">
                  {# Loop through all of the accordion sections. #}
                  {% for key, item in content.field_rn_accordion if key|first != '#' %}
                    <div class="panel-heading" role="tab" id="heading-{{ item['#paragraph'].field_rn_acc_abbr.value }}">
                      <div class="row panel-title">
                          <div class="col-sm-1 col-xs-2">
                            <img src="{{ base_path }}Images/Icons/{{ item['#paragraph'].field_rn_acc_abbr.value }}_Icon.png" alt="{{ item['#paragraph'].field_rn_acc_abbr.value }}" class="img-responsive"/>
                          </div>
                          <div class="col-sm-11 col-xs-10">
                            {# Print the accordion section title. #}
                            <h5>{{ item['#paragraph'].field_rn_acc_title.value }}</h5>
                            <p>
                              <small>
                                <a href="http://{{ item['#paragraph'].field_rn_acc_link.value }}" target="_blank">
                                {{ item['#paragraph'].field_rn_acc_link.value }}
                                </a>
                              </small>
                            </p>
                            <a class="button collapsed" data-toggle="collapse" data-parent="{{ paragraph_id }}" href="#{{ item['#paragraph'].field_rn_acc_abbr.value }}-1" aria-expanded="false" aria-controls="{{ item['#paragraph'].field_rn_acc_abbr.value }}-1">{{ item['#paragraph'].field_rn_acc_1_btn.value }}
                            </a>
                            <a class="button collapsed" data-toggle="collapse" data-parent="{{ paragraph_id }}" href="#{{ item['#paragraph'].field_rn_acc_abbr.value }}-2" aria-expanded="false" aria-controls="{{ item['#paragraph'].field_rn_acc_abbr.value }}-2">{{ item['#paragraph'].field_rn_acc_2_btn.value }}
                            </a>
                          </div>
                      </div>
                    </div>
                    <div id="{{ item['#paragraph'].field_rn_acc_abbr.value }}-1" class="panel-collapse collapse" role="tabpanel" aria-labelledby="heading-{{ item['#paragraph'].field_rn_acc_abbr.value }}">
                    {{ item['#paragraph'].field_rn_acc_1.value }}
                    </div>
                    <div id="{{ item['#paragraph'].field_rn_acc_abbr.value }}-2" class="panel-collapse collapse" role="tabpanel" aria-labelledby="heading-{{ item['#paragraph'].field_rn_acc_abbr.value }}">
                    {{ item['#paragraph'].field_rn_acc_2.value }}
                    </div>
                  {% endfor %}
                </div>
            </div>

```

# Answer
> 3 votes
If you want to render a formatted text field you have to use the render element `processed_text`:

```
  {% set paragraph =  item['#paragraph'] %}

  {% set body = {
    '#type':   'processed_text',
    '#text':    paragraph.field_rn_acc_1.value,
    '#format':  paragraph.field_rn_acc_1.format,
  } %}

  <div id="{{ paragraph.field_rn_acc_abbr.value }}-1" class="panel-collapse collapse">
  {{ body }}
  </div>

```

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


# Question
Title: Translation of BlockBase (ConfigurablePluginInterface)
```
  public function blockForm($form, FormStateInterface $form_state) {
    $form = parent::blockForm($form, $form_state);

    // Retrieve existing configuration for this block.
    $config = $this->getConfiguration();

    // Add a form field to the existing block configuration form.
    $form['Heading'] = array(
      '#type' => 'textfield',
      '#title' => t('Heading'),
      '#default_value' => isset($config['heading']) ? $config['heading'] : '',
    );

```

'#default\_value' =\> isset($config\['heading'\]) ? $config\['heading'\] : '',

can this thing be translated? And how? I use it to display a text to site users

# Answer
> 0 votes
The key was in creating mymodule.schema.yml in mymodule/config/schema/mymodule.schema.yml

with content of a kind

```
block.settings.myblock:
  type: block_settings
  mapping:
    Heading:
      type: text
      label: 'Heading'
      translatable: true

```

also

```
$config = $this->getConfiguration();

```

is not needed using

```
$this->configuration['heading']

```

insted

\core\modules\system\src\Plugin\Block\SystemBrandingBlock.php -- is a good example

---
Tags: blocks, i18n-l10n
---


# Question
Title: How to auto-yes "drush features-revert-all" ... via terminus
On a local machine

```
drush features-revert-all

```

will convert all features to codebase definition. On a local machine ...

```
drush -y

```

will auto-yes any command. On a local machine

```
terminus -y command

```

will auto-yes as well.

But when combined, even

```
terminus -y drush -y yoursite.dev -y features-revert-all -y

```

... will still ask for a key-press.

How can it be forced to run non-interactively?

# Answer
You need to add a `--` separator to your command. The options for Terminus come before this marker, and the options for Drush come after.

In other words:

```
terminus -y drush site.dev -- features-revert-all -y

```

**Explanation:**

In programs that support it, `--` means "all of the options that come after should be treated as arguements". The command `terminus drush` passes all of its arguments through to Drush.
> 3 votes

---
Tags: drush, features
---


# Question
Title: How can I get an entityform attached to an order in drupal commerce?
I'm trying to append an entityform to an order in Drupal commerce. I included the several attempts in my code snippet. Version 1 just throws the following error:

```
Fatal error: Cannot use object of type EntityValueWrapper as array in /sites/all/modules/kalamuna/tb_commerce_panes/tb_commerce_panes.module on line 374

```

I tried two other attempts. Version 2 and 3 show up in $order, but when I get to the checkout page and var\_dump $order it isn't there. Any ideas why?

```
function commerce_panes_custom_submit($form, &$form_state, $checkout_pane, $order) {
  // Strip out the entityform type.
  $values = $form_state['values'];
  $entityform_type_name = $values['entityform_bundle'];

  // Create a new entityform from the remaining fields.
  global $user;
  $form = new Entityform(
    array(
      'type'     => $entityform_type_name,
      'created'  => time(),
      'changed'  => time(),
      'language' => LANGUAGE_NONE,
      'uid'      => 2
    )
  );

  // The process the rest entityform fields.
  foreach ($values as $k => $v) {
    if (strstr($k, 'field_')) {
      $form->$k = $v;
    }
  }

  //Version 1 - Original
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  $order_wrapper->field_tb_registration_forms[] = $form;
  $order_wrapper->save();

  //Version 2 - Modified Original
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  $node = $order_wrapper->values();
  $node->field_tb_registration_forms[] = $form;
  $order_wrapper->save();

  //Version 3 - modify $order and save it
  $order->field_tb_registration_forms = $form;
  commerce_order_save($order);

}

```

# Answer
Have you tried first checking to make sure $order is set? If not then load cart from $user-\>id first and then wrap it.
> 0 votes

---
Tags: commerce
---


# Question
Title: Moving file structure and documents from Static site to Drupal
I have a static site that we have created content types for and moved most of the content over. There are links leading back to the old static site documents. I am looking for a good way to bring these docs into the drupal fold. I understand i'll need to update the path to the doc, but if we can keep the majority of the structure and just update to /default/files/directory/subdirectory/file.ext that would be great.

How does one most successfully import large amounts of documents?

# Answer
What you could have done is use the Migrate module. It allows you to read from various sources (db, files, csv, etc.) and feed them to Drupal (db, files, csv, etc). It's essentially just a pipeline of read-\>process-\>save.

What I would do is create 2 migrations, one for the files and one for the pages. You migrate files first which essentially just tells Drupal they exist by creating records of them in the DB and where they are. During migration, Migrate creates a mapping table which tracks the source id (module-generated, you decide, usually by filename or hash) and destination id (entity id) of the content.

Then you migrate the pages. Migrate allows you to do processing on content before it gets saved to Drupal. Using the data from the mapping done in the file migration earlier (the entity ids), you simply need to look for the urls in the page content, use it to find the id Drupal assigned to it when it was migrated (there are APIs for this), generate a url from that ID, and replace the url in the content.

Migration is easier done than said actually. This section extensively explains how to use Migrate. In addition, check out Migrate Extras and Migrate D2D as additional tools. Also, the Migrate module itself has examples in the source code which you can check out. And... a lot of trial and error.
> 1 votes

---
Tags: 7, files, media
---


title: A Report of Logins on the Site

text:
# Question
Title: A Report of Logins on the Site
Is there a way to see a report of the users on a site that shows who is logging in and who isn't logging in? (other than just looking at 'People' tab I mean...we have thousands of users on the site).

# Answer
The DB log should log user logins. It usually appears as "Session created for \[user name\]".

Alternatively, you can create an admin-only view of users and the time they last login and/or the last time they accessed. iirc, users have `access` and `login` fields in the DB which are timestamps that represent last page access while logged in and login time, respectively. I believe they are exposed to Views.

For reports, there is Views Data Export which adds a display to a View, exposing itself as an endpoint from which you can download the data. Exports in various formats, most especially CSV.

However, for the views approach mentioned, it will only display the latest data. This doesn't do historical record-keeping.
> 2 votes

---
Tags: 8, users
---


# Question
Title: Structure for Headless Drupal 8 and Angular
I have been looking and can't find an answer to this relatively simple thing. In doing headless Drupal 8 with angular front-end, I was able to build an app in angular but it won't reach the Drupal endpoint as they are running on different ports (local development, :9000 and :80). I don't want to use CORS as that seems that it will introduce a host of security issues in production that I am not looking to deal with.

If I create the angular app with Drupal inside angular, will Drupal have access to LAMP - if its in the same location that has access to LAMP stack?

# Answer
> -1 votes
There are third-party JS modules that allow proxying of a subpath on your app domain to an entirely different domain. One such example is grunt-connect-proxy. This way, the browser will think it's hitting the same domain, when the proxy is actually forwarding it to the other domain. However, this will depend on your JS setup, which you didn't mention.

Alternatively, just enable CORS and work with it. It's as simple as adding the following to the remote domain's `.htaccess` (which in your case, Drupal's).

```
Header Set Access-Control-Allow-Origin "*"

```

---
Tags: javascript, 8
---


# Question
Title: Dynamic menu item based on Views argument
Is it possible to have a dynamic title on the menu item based on the argument that Views is receiving? I'm using the title on the menu item on the breadcrumb and my breadcrumb changes based on the argument.

# Answer
I never used breadcrumbs and i am quite new to Drupal but i think breadcrumbs get their copy from the URL arguments ( which is also where view is getting its arguments, well in most cases). Though the menu items get their copy from the taxo (if you use a taxonomy menu block) or whatever name you gave them in the menu section of the site admin.

Therefor the only solution i would see, is to create you owns menu template in which you can use function such as drupal\_get\_path\_alias() to populate your menu.
> 0 votes

# Answer
Use a module such as Menu Token to allow the use of Tokens in menu items. For an example see Dynamic menu elements with tokens.

Create the view as normal, install Menu Token and tokens will be available to use in the path or title of the menu. You can then select a token based on the contextual filter. Alternatively, you could add a hidden Custom Text field populated with the required value based on the contextual filter and use the token which represents the Custom Text field in the menu title.
> 0 votes

---
Tags: 7, views, breadcrumbs
---


# Question
Title: How to define profile types per group type in the Group module?
I am working on a site where I am just starting to work with the Drupal 7 version of the Group module. The groups and roles stuff is fine but can I define a profile type per group type?

eg. Group Type "School" might have profiles Principal, Teacher, Student, Volunteer and Group Type "Church" might have profiles Pastor, Youth Worker, Member etc

So when someone signs up I want them to find their group (eg St John's Baptist) and then enter their profile type (eg Pastor).

Then I want to show specific content depending on their profile type. eg All Pastor's will have access to certain nodes.

Group profile types seems to be global so looking for a way to do this neatly.

# Answer
> ... can I define a profile type per group type?

*Sure (yes?) you can*, it's what in the Group module is called "**Group Specific Roles**".

> Group profile types seems to be global ...

Here you're talking about what in the Group module is called "**Special Global Role**" or "**Configured Global Roles**".

For more details on this, refer to the answer to "What are the various roles supported by the Group module?".

Be aware: this answer applies to D7, as in the question (for D8 it would be different ...).
> 0 votes

---
Tags: users, group
---


# Question
Title: How to add Google recaptcha to a custom form?
I have a form I'm creating programmatically with a custom module, and I need to add the Google recaptcha to it. In the Google reCaptcha module's settings page (/admin/config/spam\_protection/google\_recaptcha/forms) I only see the login, register and comments forms and no way to add a custom form (like in the captcha module).

I googled as well as looked in the Google Captcha module's files and API file and can't find any hooks or info on how I can add the captcha element to a custom form. Any pointers would be appreciated!

# Answer
You can use **recaptcha** module (https://www.drupal.org/project/recaptcha) and in captcha settings(admin/config/people/captcha) you can add your custom form's form\_id and select the challenge type reCAPTCHA(from module recaptcha). This should work.
> 1 votes

---
Tags: 7, forms, captcha
---


title: JPEG Quality configuration

text:
# Question
Title: JPEG Quality configuration
I'm wandering how and when the JPEG quality ratio (75% by default in admin/config/media/image-toolkit) is applied to the images. 1/ I suppose it is used a first time when the image is upload and scaled to feat the max width/height set up in the content type field. So, in case the original uploaded image already feats the max width/height, is it processed and compressed anyway or not? 2/ Then, I suppose this ratio is applied a second time when generating image styles at page load. So this means that the resulting displayed image has been compressed two times with 75% quality loss (resulting ±56%). Is that it? Thanks for your help.

# Answer
I tested it on a local server. Now I can say that: 1/ Image is processed at upload ONLY if it is larger than maximum authorized width/height (if it fits in this max size, it is not processed). In this process, the JPEG quality ratio set up in configuration (admin/config/media/image-toolkit) will be applied. This first step generates the "drupal original image" with will be used to generate image styles. 2/ In this new process of generating the image styles, the JPEG quality ratio will be applied AGAIN when resizing the thumbnails.

This means that it seems better to keep the JPEG quality ration roughly around 60-80% to have lights pages, but in order to avoid it to be applied twice on the images styles thumbnails displayed in the pages, upload "original" images that are 100% quality JPEG and fit to the max allowed size (so that are not processed at upload).
> 1 votes

---
Tags: media
---