title: Little customization to gratis theme

text:
# Question
Title: Little customization to gratis theme
I am using the Gratis theme, but there is a little problem.

Here is the screen shot of the block region demonstration:

Yellow are the regions. I want to make the 1,2,3 marked area into one top nav where I have logo, main menu and other links. How to do that?

The main menu (third party system) is a different area. Say 4th area. Not concerned with that.

Here is the page.tpl code for these top 3 areas

\`

```
  <!-- top links-->
  <?php if ($page['top_links']): ?>
    <div id="top-bar" class="">
      <div class="l-top-wrapper l-setwidth" <?php if (!empty($set_width)) : print 'style="max-width:' . $set_width . ';"' ; endif; ?>>
        <div class="top-links s-grid">
          <?php print render($page['top_links']); ?>
        </div>
      </div>
    </div>
  <?php endif; ?>
  <!-- //top links-->

  <!-- header -->
  <div id="header-bar" class="l-header-wrapper" role="banner">
    <header class="l-header l-setwidth" <?php if (!empty($set_width)) : print 'style="max-width:' . $set_width . ';"' ; endif; ?>>

      <?php if ($logo): ?>
      <div class="l-logo">
          <a href="<?php print $front_page; ?>" title="<?php print $site_name; ?> » <?php print $site_slogan; ?>">
            <img id="logo-img" src="<?php print $logo; ?>" alt="<?php print $site_name; ?> » <?php print $site_slogan; ?>"/></a>
        </div><!--// l-logo-->
        <?php endif; ?>

      <?php if ($site_slogan || $site_name) : ?>
      <div class="l-branding">

            <?php if ($site_name) : ?>
              <h1 class="site-name">
                <a href="<?php print $front_page; ?>">
                  <?php print $site_name; ?></a>
              </h1>
          <?php endif; ?>

              <?php if ($site_slogan) : ?>
                <h3 class="site-slogan"><?php print $site_slogan; ?></h3>
            <?php endif; ?>

      </div><!--//branding-->
        <?php endif; ?>

    </header>
  </div><!-- // l-header -wrapper-->

  <div id="menu-wrapper" class="l-menu-wrapper main-menu" role="navigation">
    <div class="l-setwidth" <?php if (!empty($set_width)) : print 'style="max-width:' . $set_width . ';"' ; endif; ?>>

      <?php if ($main_menu): ?>
        <a id="off-canvas-left-show" href="#off-canvas" class="l-off-canvas-show l-off-canvas-show--left"><?php print t('Show Navigation'); ?></a>
        <div id="off-canvas-left" class="l-off-canvas l-off-canvas--left">
          <a id="off-canvas-left-hide" href="#" class="l-off-canvas-hide l-off-canvas-hide--left"><?php print t('Hide Navigation'); ?></a>

          <div class="main-menu-wrapper">

            <?php print render($primary_nav); ?>
          </div>
        </div><!-- // off-canvas-left -->
      <?php endif; ?>`

```

# Answer
> 1 votes
I installed the theme on my computer and those elements are not printed using regions (as you said), are printed using the template file (and that's because there are no blocks with them, they are printed directly in the template file - except the menu that is printed using $primary\_nav variable).

So, if you want something like you said, you need to add that content in blocks. Or, if you only want to add them in the same area or div in the page, just move them in the template file (for example, move "#menu-wrapper" in the "#header-bar" div, and you will have them together).

---
Tags: 7, theming
---


# Question
Title: Can't override module css for Mega Menu in Zen theme
I am a fresh convert to Drupal and still a novice overall. My problem seems simple, but I just can't figure it out.

I installed a Zen theme, then a Mega Menu module. I am in the process of styling the collapsing menu, so I wanted to copy the CSS from the module to my theme CSS file.

**First:** I copied the tb-megamenu.tpl.php to my theme in order to add the correct glyphicon. That worked just fine.

**Second:** I copied the default.css from the module to my css folder. It didn't override.

**Third:** I changed the name of that file to custom-megamenu-default.css (in case there was some conflict with the file being named "default", and tried to register it in the .info file. It still didn't override the css.

What am I missing?

*Note:* I have cleared the cache at each step, and I (in the very beginning) created a custom.css file that overrides just fine, without registering in the .info file. I believe Zen aggregates all the css files in the css folder automatically.

Edit: If it helps here is the address of the site I am using to learn Drupal: www.sandbox.thefinanceplanner.com

# Answer
> 0 votes
For something like this, I would suggest you first to unset the css file in the module with hook\_css\_alter. After that, you can use the css you added in the theme, you don't need two css files with the same info loaded.

---
Tags: 7, theming, navigation
---


# Question
Title: View Rewrite results Inline CSS for Newletter
I am trying to send a HTML newsletter with the simplenews plugin using views. The mailing of HTML via the plugin works flawlessly (after tinkering). I included a View via the Twig Tweak plugin inside the corresponding twig template. My main problem is very similar to this but for Drupal 8. HTML mails require (as far as I know) inline CSS to be displayed correctly in the majority of mail clients. As I use a View, inline CSS get stripped away ("sanititzed" for security I guess).

Is there any possibility for me to use Views with inline CSS as in Drupal 8 I couldn't find the correct line of code to disable this "sanitisation"?

# Answer
I've been looking into this problem myself for several days, and my conclusion after going through the views code is that views is absolutely dead-set on sanitizing certain data (specifically twig template fields for custom field rewriting) not even writing your own templates can fix that.

Ultimately, my work around for this was to use Display Suite to build a custom display for my node type (which lets me use tokens in custom display suite fields) and then telling views setting up views to output Display Suite content instead of Fields.
> 2 votes

---
Tags: views, 8, emails
---


# Question
Title: How to add margin between columns with Drupal Bootstrap View Grid
I need help I'm trying to add some margin between columns using drupal Views Bootstrap module the grid view but the columns are closed together. How can I add margin between columns. I have tried through the module settings but there isn't any option to. How can I achieve this?

# Answer
You can use only CSS for this, look for the columns classes and then add it in a CSS file that is loaded on your page.
> 0 votes

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


title: BBcodes module not working

text:
# Question
Title: BBcodes module not working
I have installed and enabled BBcode, BUEditor, Extensible BBcode and Advanced Forum modules on my site. I would like use BBcodes to post the topics in forum. When I post the topic with any value \[for e.g \[b\]this is a test data\[/b\]\] and submit the posting I see the raw data displayed without BBcode formatting.

Not sure what is going wrong. I see the errors in the drupal logs.

> Warning: preg\_match\_all(): Compilation failed: unrecognized character after (?\< at offset 5 in XBBCodeFilter-\>process() (line 42 of /var/web/sites/all/modules/xbbcode/xbbcode.filter.inc).

Appreciate your help.

Thanks

# Answer
> 0 votes
xbbcode maintainer here.

It seems that the module uses a Regex syntax that was introduced in PHP 5.2.2: http://php.net/manual/de/regexp.reference.subpatterns.php

I'll release a fix when I can; it's a pretty small code change: For each occurrence of `(?<...>` in the pattern, insert a P to make it `(?P<...>`.

Alternatively, you can fix it by upgrading to PHP 5.2.2 or later.

Edit: In fact, Drupal 7's minimum requirements mention PHP 5.2.5 (https://www.drupal.org/docs/7/system-requirements/overview).

---
Tags: nodes
---


title: Display node with specific revision

text:
# Question
Title: Display node with specific revision
I am trying to load a node using the revisioning module to display an unpublished piece of content, by passing a version ID to `node_load()`. We also use the i18n module which may or may not have an affect on what I am trying to achieve. We are looking to implement a "preview" of a page which may be sent out to departments that do not have a user account of any sort (We do not want to create a login for this). The preview page is requested with the version `&vid=12345` and a `&preview` URL parameter.

At the moment, if the specific revision is not published, the preview page will load the currently published content instead of the version we are passing to node\_load().

I have tried to create a preview user with view unpublished permissions, but this does not work (still loads the published content).

Is it possible to prevent the fallback and load the specific revision?

UPDATE: Thank you for the renewed interest. So we are using the "entity\_translation module" and have extended this to include the preview functionality. This allows a page URL to be called with the node id and version id. These are both passed to node\_load. The node is then displayed via calls to `$output = _revisioning_view($node);` and finally `drupal_deliver_page($output);`

# Answer
If you are doing this by custom method try below code to get published revision id.

```
$query = db_select('node_revision','nr');
$query->join('node','n','n.nid=nr.nid');
$query->fields('nr',array('vid','status','nid'));
$query->condition('nr.status',1,'=');
$query->condition('nr.nid',$nid,'=');
$result = $query->orderby('vid','DESC')->range(0,1)->execute()->fetchAll();

```

Pass $nid in condition, here you will get the latest published revision ID.

Then load node as

> entity\_revision\_load('node', $result-\>vid)

This will load particular revision id with content type.

Here you will get all node data related to that revision id.

Hope this helps.
> 3 votes

---
Tags: 7, nodes
---


# Question
Title: Custom module - find out the name of the field
I have written a custom field module and I would like to know how I can programmatically find out what the name of the field in the database.

E.g. someone installs my module, that installs a new fieldtype and widget. The user adds a new field to a content type and calls the field "test\_field". How can the module provide the database name of the field ("test\_field") to some function within the module?

Currently I am hard-coding the name of the field which works fine until a user decides to use another name. Then I am not able to do some database operations anymore.

# Answer
> 0 votes
OK. I ended up doing it a little differently:

In my `field_widget_form` function I added a hidden field. In this function it is possible to access the $field and therefore the name of the field using

`$field['field_name'];`

So I saved that value to the hidden form. Then when I trigger a function within that form it is able to access that value. So in my different function that relies on the *machine\_name* of the field I actually access the value of the form that is set when the widget form is built.

---
Tags: entities
---


# Question
Title: How do I add a JavaScript file to a form?
I'm trying to add a JavaScript file to a form that I have in a modal. Although I followed the information found here, here, and here, the file doesn't appear in the Network tab of the inspector and nothing is logged to the browser console when the modal is launched.

The form modal is triggered in themes/custom/my\_theme/templates/controllers/my-controller-theme.html.twig.

```
<a class="use-ajax" data-dialog-type="modal" href="/help/{{ var1 }}/{{ var2 }}/add">Click here to add</a>

```

The library is defined in my custom theme in themes/custom/my\_theme/my\_theme.libraries.yml.

```
my_modals:
  version: 1.x
  js:
    js/my_modals.js: {}
  dependencies:
    - core/jquery

```

The JavaScript file is themes/custom/my\_theme/js/my\_modals.js.

```
(function ($) {
    Drupal.behaviors.my_modals = {
        attach: function (context, settings) {
            console.log('test');
        }
    };
}(jQuery));

```

The form itself is defined in my custom profile in profiles/my\_profile/src/Form/MyModalAddForm.php.

```
public function buildForm(array $form, FormStateInterface $form_state) {
  // ...
  $form['#attached']['library'][] = 'my_theme/my_modals';
}

```

# Answer
The issue ended up being related to namespaces. My profile and theme had the same name so Drupal didn't know where to load the JS from.
> 0 votes

# Answer
There is no use to attach libraries to a form that is displayed in a modal window because the window has no place for assets (JS and CSS files). Instead I would suggest using hook\_page\_attachements or attaching the library to page element that is responsible for triggering that modal window.
> 0 votes

---
Tags: 8, forms, javascript
---


# Question
Title: Explanation of pear's include path, and why Drush cr clears it?
I got an error message when trying to import Drupal configuration with drush cim, saying the following:

include\_once(/var/www/d8site/modules/custom/somemodule/somemodule.module):\[warning\] failed to open stream: No such file or directory Extension.php:140 include\_once(): Failed opening \[warning\] '/var/www/d8site/modules/custom/somemodule/somemodule.module' for inclusion (include\_path='.:/usr/share/php:/usr/share/pear') Extension.php:140

The somemodule.module file was deleted between versions, but it's still expecting it. Restarting and/or reloading Apache didn't get rid of this message, but drush cr did. I don't want to have to clear the entire Drupal cache on production, so how could I update this include list without clearing all cache with drush? If I didn't have pear installed, would this be any different?

# Answer
Pear has no connection to this. The error message displays the include path value in brackets for debugging purpose. You can check the value as follows:

```
drush ev 'print get_include_path();'

```

In your case the PHP is trying to include the file from this location and emits the error as it fails. */var/www/d8site/modules/custom/somemodule/somemodule.module*

My guess the file still presents in Drupal registry because the module wasn't uninstalled properly. Check out this guide to fix it. https://www.drupal.org/node/2487215
> 3 votes

---
Tags: 8
---


# Question
Title: Allow html tags in Form submit button in block plugin
I'm using a block plugin to render a user specified form. I'm retrieving the form like so:

```
public function blockSubmit($form, FormStateInterface $form_state) {

    $this->configuration['template'] = $form_state->getValue('template');
    $selected_entity_type_bundle     = $form_state->getValue('entity_type');
    $values                          = explode('.', $selected_entity_type_bundle);

    $this->configuration['entity_type']             = $values[0];
    $this->configuration['bundle']                  = $values[1];
    $this->configuration['entity_type_submit_text'] = $form_state->getValue('entity_type_submit_text');

}

private function buildEntityForm() {
    $values = array();
    // Specify selected bundle if the entity has bundles.
    if (\Drupal::entityManager()->getDefinition($this->configuration['entity_type'])->hasKey('bundle')) {
        $bundle_key = \Drupal::entityManager()->getDefinition($this->configuration['entity_type'])->getKey('bundle');
        $values     = array($bundle_key => $this->configuration['bundle']);
    }
    $entity = \Drupal::entityManager()
        ->getStorage($this->configuration['entity_type'])
        ->create($values);

    if ($entity instanceof EntityOwnerInterface) {
        $entity->setOwnerId(\Drupal::currentUser()->id());
    }

    $form = \Drupal::entityManager()
        ->getFormObject($this->configuration['entity_type'], 'default')
        ->setEntity($entity);

    return \Drupal::formBuilder()->getForm($form);
}

```

This grabs the form just fine, and I render it using

```
public function build() {

    if ($this->configuration['entity_type'] != '') {
        $entityForm                                = $this->buildEntityForm();
        $entityForm['actions']['submit']['#value'] = t($this->configuration['entity_type_submit_text']);// Editable submit button value.
        if ($this->configuration['template'] == 'learnmore') {
            $entityForm['actions']['submit']['#value'] = '<i class="fa fa-mail"></i>'.$entityForm['actions']['submit']['#value'];
        }
    } else {
        $entityForm = '';
    }
    $entityForm['actions']['preview'] = '';

    $content = [
        'template'     => [
            '#type'       => 'container',
            '#attributes' => [
                'class'      => [$this->configuration['template']],
            ],
            'header'  => [
                '#type'  => 'html_tag',
                '#tag'   => 'h5',
                '#value' => $this->configuration['label'],
            ],
            'form' => $entityForm,
        ],
    ];

    return $content;
}

```

Which renders the form. But I'm setting the submit button text as specified by the user like so

```
$entityForm['actions']['submit']['#value'] = t($this->configuration['entity_type_submit_text']);

```

And I want to add an icon inside the button before the text like so

```
$entityForm['actions']['submit']['#value'] = '<i class="fa fa-mail"></i>'.$entityForm['actions']['submit']['#value'];

```

The issue is when it renders the button it includes the html tags so the actual submit button text is

> `<i class="fa fa-mail"></i>`Submit Button Text

It displays the html tags instead of rendering the actual icon. Is there a way to allow html tags inside of a submit button on a form?

# Answer
Use a formattable markup:

```
use Drupal\Component\Render\FormattableMarkup;

  $value = new FormattableMarkup('<i class="fa fa-mail"></i>@text', [
    '@text' => $value,
  ]);

```

The formattable string will not be escaped. The variable in the placeholder `@text` will be escaped and that is important, because it contains user input.
> 4 votes

# Answer
I don't believe this is possible since it's inserting the html into the value attributes of a submit type input tag rather than in the content within a button tag. To resolve this I appended a button element like so.

```
    $content = [
        'template'     => [
            '#type'       => 'container',
            '#attributes' => [
                'class'      => [$this->configuration['template']],
            ],
            'header'  => [
                '#type'  => 'html_tag',
                '#tag'   => 'h5',
                '#value' => $this->configuration['label'],
            ],
            'form' => $entityForm,
        ],
    ];
    if ($this->configuration['template'] == 'learnmore') {
        $content['template'][] = [
            'test'           => [
                '#type'         => 'html_tag',
                '#tag'          => 'button',
                '#value'        => '<i class="fa fa-envelope-o"></i> '.$entityForm['actions']['submit']['#value'],
                '#allowed_tags' => 'i',
                '#attributes'   => [
                    'type'         => 'submit',
                    'form'         => 'contact-message-learn-more-form',
                ],
            ],
        ];

    }

    return $content;

```
> -1 votes

---
Tags: forms, 8, blocks, plugins
---


title: Submit form after custom submit handler

text:
# Question
Title: Submit form after custom submit handler
I'm trying to create my first module which essentially is a visitor sign-in system where each visitor is stored as a custom content type.

The user will be a visitor to our building who's able to input their name and who they are here to see (autocomplete field based on taxonomy terms). My custom module will then add a timestamp to the node, as well as email the person they are here to see.

Code is below:

```
function visitor_email_staff_form_alter(&$form, &$form_state, $form_id){
    if ($form_id == 'visitor_sign_in_node_form'){
        $form['actions']['submit']['#submit'][0] = 'visitor_email_staff_my_custom_submit_handler';
    }
}

function visitor_email_staff_my_custom_submit_handler($form, &$form_state){

    $guestName = $form['field_visitors_name']['und'][0]['value']['#value'];
    $staffName = $form['field_tags']['und']['#value'];
    $visitorTitle = $guestName.' - '.time();

    $staffTaxonomy = taxonomy_get_term_by_name($staffName);

    foreach ($staffTaxonomy as $email) {
        $staffEmail =  $email->description; // email address
    }

    $form_state = array();
    $form_state['values']['title'] = $visitorTitle;
    $form_state['values']['field_visitors_name'] = $guestName;
    $form_state['values']['field_tags'] = $staffName;
    $form_state['values']['field_timestamp_in'] = time(); // timestamp
    $form_state['values']['field_timestamp_out'] = '';
    $form_state['values']['op'] = t('Save');

    drupal_form_submit('visitor_sign_in_node_form',$form_state);

}

```

The major issue I'm having at the moment is getting the data to save and submit... I keep getting the below errors:

```
Warning: Missing argument 3 for node_form() in node_form() (line 107 of C:\www\xxx\modules\node\node.pages.inc).
Warning: Creating default object from empty value in node_form() (line 115 of C:\www\xxx\modules\node\node.pages.inc).
Notice: Undefined property: stdClass::$type in node_object_prepare() (line 981 of C:\www\xxx\modules\node\node.module).
Notice: Undefined property: stdClass::$type in _node_extract_type() (line 379 of C:\www\xxx\modules\node\node.module).
Notice: Undefined property: stdClass::$type in comment_node_prepare() (line 1298 of C:\www\xxx\modules\comment\comment.module).
Notice: Undefined property: stdClass::$type in menu_node_prepare() (line 568 of C:\www\xxx\modules\menu\menu.module).
Notice: Undefined property: stdClass::$type in _node_extract_type() (line 379 of C:\www\xxx\modules\node\node.module).
Notice: Undefined property: stdClass::$type in node_form() (line 294 of C:\www\xxx\modules\node\node.pages.inc).
Notice: Undefined property: stdClass::$type in node_form() (line 300 of C:\www\xxx\modules\node\node.pages.inc).
Notice: Undefined property: stdClass::$type in node_form() (line 321 of C:\www\xxx\modules\node\node.pages.inc).
EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids() (line 7922 of C:\www\xxx\includes\common.inc).

```

Am I going about this the wrong way? Should I be using something else instead of `drupal_form_submit()`?

# Answer
Your close, however, I think there are two changes you'll need to make.

1. You'll need to add $form\_state\['bundle'\] = "visitor\_sign\_in" to your $form\_state array()
2. You'll need to pass an (object) $node as the third parameter to drupal\_form\_submit.

The changes might look something like this:

```
function visitor_email_staff_form_alter(&$form, &$form_state, $form_id){
  if ($form_id == 'visitor_sign_in_node_form'){
    $form['actions']['submit']['#submit'][0] = 'visitor_email_staff_my_custom_submit_handler';
  }
}

function visitor_email_staff_my_custom_submit_handler($form, &$form_state){

  $guestName = $form['field_visitors_name']['und'][0]['value']['#value'];
  $staffName = $form['field_tags']['und']['#value'];
  $visitorTitle = $guestName.' - '.time();

  $staffTaxonomy = taxonomy_get_term_by_name($staffName);

  foreach ($staffTaxonomy as $email) {
    $staffEmail =  $email->description; // email address
  }

  $form_state = array();
  $form_state['values']['bundle'] = "visitor_sign_in";
  $form_state['values']['title'] = $visitorTitle;
  $form_state['values']['field_visitors_name'] = $guestName;
  $form_state['values']['field_tags'] = $staffName;
  $form_state['values']['field_timestamp_in'] = time(); // timestamp
  $form_state['values']['field_timestamp_out'] = '';
  $form_state['values']['op'] = t('Save');

  drupal_form_submit('visitor_sign_in_node_form', $form_state, (object)$node);

```

}
> 0 votes

---
Tags: 7, forms
---


title: hook form submit being called twice

text:
# Question
Title: hook form submit being called twice
In the following code custom call back function is being printed twice. How to prevent submit call back function being called twice.

```
function my_module_form_alter(&$form, &$form_state, $form_id){
 if ($form['#id'] == "views-exposed-form-test-page"){
    $form['#submit'][] = 'custom_callback';
  }
}

function custom_callback($form,&$form_state){
    $form_state['redirect'] = false;
    dpm("insert record");
}

```

# Answer
> 1 votes
`hook_form_alter()` will fire once for every time there is a form on the current page.

You can try the hook `hook_form_FORM_ID_alter()`. This will only run once when the form with the specific ID pops up.

Unfortunately I had this issue happen before, the `hook_form_alter()` ran multiple times. I stopped the code from running multiple times by encapsulating the code inside an IF statement inside the `hook_form_alter()` example: `if($form_id == my_id)`. So the hook ran multiple times but the code only ran once.

---
Tags: forms
---


# Question
Title: How to find the right token to use in a rule for sending an email to the node author?
I am having the toughest time figuring out how to send an email to the node author. I created my rule and everything works if I hard code the email but I can't seem to get the right token to use and it seems the tokens available only allow:**\[node:author**\] nothing for the node authors email?

# Answer
Sometimes, the Rules module user interface doesn't show all the allowed tokens. Manually enter *\[node:author:mail\]*. If it's not an allowed token, an error message would be shown.
> 11 votes

# Answer
The Rules module is great, but it also has its hidden features ... ***Yes*** the "*token for the eMail Id of the node author*" is available to use it in the Rules Action. However you won't find it by simply expanding the typical "**`REPLACEMENT PATTERNS`**"-link that show up by default.

Moreover, there is no need for *guessing* or *trial-and-error* (similar to the "*So try just manually inputting \[node:author:mail\]\` and see if it validates in Rules*" in the accepted answer). Instead, whenever you're looking for some token that at first doesn't seem to be available, you should try to use the `Switch to data selection` button as in this screenprint:

Then select "`node...(Created content)`" from the **Data selector** selection list (or if you know part of what you're looking for just start typing "`node:`"). Here is another screenprint that should look pretty similar:

After completing such selection, the list of possible values (= tokens starting with "`node:`") will change and start to show (dozens of) other values such as:

* `node:nid (Node ID)`
* `node:type (Content Type)`
* `node:author... (Node Author)`
* `node:comment (Comments allowed)`
* `node:comments... (Comments)`

In the above list, note the ones that have a "`...`": those are the ones that, after you select any of them, will bring up yet another list of tokens that start with what you selected. So if you select "`node:author... (Node Author)`", it'll show (many) other values (some with yet another "`...`"), such as:

* `node:author:uid (User ID)`
* `node:author:name (Name)`
* `node:author:mail (Email)`
* `node:author:roles... (User roles)`

So there you are: using the drill-down approach as shown above, `node:author:mail (Email)` is what you're looking for. All that's needed now, is to select it from this list. Though in this case there is no more *Label* and *Description* for the token, you only have what's shown between "`(`" and "`)`" to decide about which token to select.

PS: If you don't find what you're looking for (after using the `Switch to data selection` button), you can always return to the previous display by using the `Switch to the direct input mode` button.
> 1 votes

# Answer
Also, the user is logged in when creating the node so:

```
<?
global $user;
echo $user->mail;
?>

```

Should work too.
> 0 votes

---
Tags: 7, rules
---


# Question
Title: How to add a result count in exposed filters?
For theming purposes, I need to display the views results in the exposed form. Right now, through the UI, it's easy to add "Global: Result summary" to the views header, section. But how would one display it within the exposed form?

# Answer
There's no use trying to use hook\_form\_alter, as you need to wait until the view is rendered. You can do this in hook\_preprocess\_views\_view\__VIEWNAME like this:

```
function examplemodule_preprocess_views_view__exampleview(&$variables) {
  $result = $variables['header']['result'];
  unset($variables['header']['result']);
  $variables['exposed']['result'] = $result;
}

```
> 3 votes

---
Tags: 8, views
---


# Question
Title: Generate unique form ID based on context
When you try to build the same form twice on a page, the submit handler of the first form gets executed.

In order to overcome this issue you need to generate a unique form ID. How do you generate a unique ID based on some pass context.

# Answer
> 6 votes
As with Drupal 7, forms need to have a unique form ID. What's different is that in Drupal 8, the connection between the form (code) and the form ID is reversed.

In Drupal 7, as pointed out by @Ivan Jaros in the comment, you start with the form\_id, so we had hook\_forms() that allowed to map form ID's to a function that then built the form.

In Drupal 8, you first need to create a form object so that its `getFormId()` method can return a unique ID. The challenge there is that `getFormId()` is called very early, specifically *before* `buildForm()`, so the usual way of passing arguments to forms does not work.

What you need to do is create the form object yourself instead of just passing the class name to the form builder, then you can set any data on it that you want before passing it the form builder.

To get the form class, you can either instantiate it yourself, but then you can't use the ::create() method to inject dependencies, for that, you need to use the class resolver, from FormBuilder::getFormId(), this is what it does by default if you pass in a class name:

```
if (is_string($form_arg) && class_exists($form_arg)) {
  $form_arg = $this->classResolver->getInstanceFromDefinition($form_arg);
}

```

You could even use the current object or any other existing object as a form, as long as it implements `\Drupal\Core\Form\FormInterface`. One example in core that does that is the DraggableListBuilder and BlockListBuilder, see its render() method:

```
public function render() {
  if (!empty($this->weightKey)) {
    return $this->formBuilder()->getForm($this);
  }
  return parent::render();
}

```

That has the advantage that you do not need another class, you could make a block plugin that displays a form do it in the same class, for example. On the other side, that prevents you from re-using that form elsewhere and could also result in conflicts if the same method names are used for something else.

---
Tags: 8
---


# Question
Title: How can I set a default node owner for anonymous nodes on the node edit form?
This question is refining the poorly asked Is there any easy way to set the default author for a node being edited to the current author if it is currently anonymous?

The site I'm working on has a lot of Anonymous nodes because it is a migration from a system that didn't have a proper user system. Users can claim their articles (they have permission via the override node options module) by going in and editing the node and changing the system author.

I'd like the default value on the edit form for node owner to be the current user for non-admin users who are editing a node that was not owned by anyone previously. I'm sure it must be imminently doable through some form alter or form preprocess hook, but I don't quite get the drupal form system yet. Solutions and pointers to good sources of information both welcome. My ulterior motive in this question is to learn more about how to use hook\_form\_alter to change the values of fields on the form, and particularly the owner field, so answers related to that are preferred.

# Answer
You can do this pretty quickly in a custom module by implementing a hook\_form\_alter().

In this example, I created a module called "anon" (you might want to use something more specific) and in my anon.module, I have the following:

```
<?php

/**
 * Implements hook_form_alter()
 */
function anon_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($form_id == "article_node_form" && isset($form['author']['name']['#default_value']) && $form['author']['name']['#default_value'] == "") {
    $form['author']['name']['#default_value'] = $user->name;
  }
}

```

The above code checks to see if you are on a article\_node\_form (change this to the content type you are using), if the author of the form is blank (which is representative of an anonymous user) and then sets the author name to the currently logged in user name.

Note that by default a new form will always set the author value to the logged in user, so this would only apply for existing nodes.
> 1 votes

---
Tags: 7, forms
---


# Question
Title: How to insert JavaScript code on a specific page using a module?
I'm trying to insert a JavaScript code on a specific page using Tracking Code Snippets module, but it does not seem to work (there's a bug in it). Specifically, I want the code to be inserted only on a specific page (URL path .html) inside the tag. Anyone knows of a module / easy solution (without changing the code of my .tpl files) to do that? Thanks!

# Answer
You can place it in a block that only displays on that page.

If you want it in the head, there's a module that does it for you: Add To Head
> 2 votes

# Answer
in your themes template.php you can add this to node preprocess:

```
function MY_THEME_preprocess_node(&$vars) {
    if($vars['nid'] == 'XX'){
      drupal_add_js('path/to/js/file.js');
    }
}

```

this checks for only node pages that match the node ID. you can also change drupal\_add\_js to have the javascript placed at the footer instead of header.
> 2 votes

---
Tags: 7, javascript
---


# Question
Title: Is there any way to number Paragraphs rendered so as to have a numbered list rendered?
I’m putting together a project that requires a content type that has a numbered “How To” list in Drupal 7.5.x.

I am using the Paragraphs module and so far the basic concept of having paragraph blocks of how to “steps” is working as expected. Users are able to “Add another Paragraph” to add each additional step and the steps render correctly on the front-end display as expected.

But while that’s all fine, I’m having a heck of a time understanding how I can have Drupal/Paragraphs automatically number each paragraph so it would look like—for all intents and purposes—something like this; literally I just need that number to the left of each **Step …:** item and that’s it:

1. **Step One:** Do this.
2. **Step Two:** Do that.
3. **Step Three:** Do something else.

I have been playing around with the Custom Formatters module and it *almost* seems like that might be my solution: I could use a custom formatter that uses PHP to do something like this. Let’s assume this is what outputs the title for each paragraph `field_title` value with a PHP custom formatter:

```
return $variables['#object']->field_title['und']['0']['value'];

```

So I should be able to do something like this to get a number/order prepended:

```
return $count . ': ' . $variables['#object']->field_title['und']['0']['value'];

```

Of course `$count` is just some arbitrary pseudo-code I am placing for example’s sake, but is this the right approach? Or am I barking up the wrong tree. FWIW, I am poking around the values of the output via the Devel module and don’t see anything useful that would related to count/order.

# Answer
> 2 votes
I’d take a look at overriding the paragraph template file in your theme and doing the work there. Paragraph’s uses the following template names:

* `paragraphs-item--[VIEW-MODE].tpl.php`
* `paragraphs-item--[BUNDLE-NAME].tpl.php`
* `paragraphs-item--[BUNDLE-NAME]--[VIEW-MODE].tpl.php`

The source code of the `paragraphs-items.tpl.php` is as follows:

```
<?php

/**
 * @file
 * Default theme implementation for a single paragraph item.
 *
 * Available variables:
 * - $content: An array of content items. Use render($content) to print them
 *   all, or print a subset such as render($content['field_example']). Use
 *   hide($content['field_example']) to temporarily suppress the printing of a
 *   given element.
 * - $classes: String of classes that can be used to style contextually through
 *   CSS. It can be manipulated through the variable $classes_array from
 *   preprocess functions. By default the following classes are available, where
 *   the parts enclosed by {} are replaced by the appropriate values:
 *   - entity
 *   - entity-paragraphs-item
 *   - paragraphs-item-{bundle}
 *
 * Other variables:
 * - $classes_array: Array of html class attribute values. It is flattened   into
 *   a string within the variable $classes.
 *
 * @see template_preprocess()
 * @see template_preprocess_entity()
 * @see template_process()
 */
?>
<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <div class="content"<?php print $content_attributes; ?>>
    <?php print render($content); ?>
  </div>
</div>

```

You could use a preprocess hook to set an `$attribute` or other variable that would provide the Step identifier for the paragraph being rendered, although, I’d be suprised if you couldn’t figure that logic out at this level with data available on either `$content` or `$attributes`.

---
Tags: 7, entities
---


title: How to 'Entity Reference' using Rules

text:
# Question
Title: How to 'Entity Reference' using Rules
I am simply trying to autopopulate a Taxonomy Term from Content Type A into Content Type B.

An example, I'm creating a review site for Cars:

Content Type A = Car Model field: field\_car\_model\_tag

Content Type B = Car Review field: field\_car\_review\_tag

Assuming, Content Type A|CAR MODEL has already been created, titled "FORD MODEL".... My users will find and click a "Review Ford" link that routes them to Content Type B|CAR REVIEW, and auto-populates the Node Reference field (Node Reference URL Widget, for example, even though I'm attempting to only use Entity Reference fields).

After saving this same Content Type B|CAR REVIEW node, I would like this field, 'field\_car\_review\_tag' to automatically populate with it's sister term from Content Type A|CAR MODEL.

In Drupal 6 Rules, I found this to be very straightforward.
I would simply "Load a referenced node, and then set a CCK field without validation", applying the token from the referenced content type. In Drupal 7, the settings are seemingly endless.

Thank you for your help!

# Answer
> 1 votes
I believe I've resolved this issue; least it looks good so far. Super thanks to Alauddin's response to "how to create rules to send email notification for node reference content?"

EVENT After saving new content of Car Review

CONDITION

* Entity has field
* data selector: node:field-car-review-node-reference
* value: field\_car\_model\_tag

ACTION

* Fetch Entity by ID, with value: `node` and data selector: `node:field-car-review-node-reference:nid`
* Set a data value, with selected data (that I want to change): `node:field-car-review-node-reference:field-car-model-tag`

I think I have this right, here is an export of my Rule:

```
{ "rules_term_ref_4" : {
"LABEL" : "TERM REF 4",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : {
  "node_insert--car_review" : { "bundle" : "car_review" },
  "node_update--car_review" : { "bundle" : "car_review" }
},
"IF" : [
  { "entity_has_field" : {
      "entity" : [ "node:field-car-review-node-reference" ],
      "field" : "field_car_model_tag"
    }
  }
],
"DO" : [
  { "entity_fetch" : {
      "USING" : { "type" : "node", "id" : [ "node:field-car-review-node-reference:nid" ] },
      "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
    }
  },
  { "data_set" : {
      "data" : [ "node:field-car-review-tag" ],
      "value" : [ "node:field-car-review-node-reference:field-car-model-tag" ]
    }
  }
]
}
}

```

---
Tags: 7, rules
---


# Question
Title: How to protect thumbnail and library images from media browser from being deleted?
I have a Drupal 7 site where authenticated users can create a webpage to raise money for a charity. They can add a picture from the media library using the media browser. However, if they delete their page, this deletes the thumbnail and the library image from the db and site.

I've tried the File Lock module, but that doesn't work. I've set the user permissions to where the images cannot be deleted; that doesn't work. The images are used in other places as well as the need to keep them library for future users.

Any suggestions?

# Answer
You could try this module:

Soft delete

> This module allows selected users, based on a permission, to soft delete nodes. To users the operation looks like delete but the node is unpublished. It's useful if you want to prevent accidental deletes or bring back content that wasn't supposed to be deleted.
>
> Note that this is a very simple module, adding just a tab called Delete next to View and Edit on nodes that the user can unpublish. A more advanced and customizable alternative is the Content unpublish module.
> 1 votes

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


title: Cube portfolio pop up image went wrong

text:
# Question
Title: Cube portfolio pop up image went wrong
I am using Cube Portfolio to display portfolios.

The "View Larger" button link shows the correct link.

But when I click on the button,

the pop up image went wrong.

How do I find out the problem?

I look into the code, there is a weird link.

The portfolio section was created in Views. Drupal version is 7.

# Answer
> 1 votes
The image path changes to absoulute path.

---
Tags: media
---


title: Incorporating external jquery library

text:
# Question
Title: Incorporating external jquery library
I am trying to use with Javascript in Drupal 8. I took an example from official drupal website, which I got it from https://www.drupal.org/project/examples and modified the code of ***js\_example*** to incorporate **sDashboard** library.

The **js\_example.libraries.yml** includes:

```
# A simple script using jquery ui accordion.
js_example.accordion:
  js:
    js/js_example_accordion.js: {}
  # Build up our dependencies for this page as a library. Our accordion script
  # needs jquery.ui.accordion. You can find the core scripts under core/assets/.
  dependencies:
    - core/jquery.ui.accordion
    - core/jquery

js_example.sdashboard:
  js:
    js/jquery-sDashboard.js : {}
  css:
    component:
      css/sDashboard.css: {}
  dependencies:
    - core/jquery
    - core/jquery.ui
    - core/jquery.datatables

```

The example module includes a Controller which I modified as:

```
public function getJsAccordionImplementation() {
    $title = t('Click sections to expand or collapse:');
    // Build using our theme. This gives us content, which is not a good
    // practice, but which allows us to demonstrate adding JavaScript here.
    $build['myelement'] = array(
      '#theme' => 'js_example_accordion',
      '#title' => $title,
    );
    // Add our script. It is tiny, but this demonstrates how to add it. We pass
    // our module name followed by the internal library name declared in
    // libraries yml file.
    $build['myelement']['#attached']['library'][] = 'js_example/js_example.accordion';
    $build['myelement']['#attached']['library'][] = 'js_example/js_example.sdashboard';
    // Return the renderable array.
    return $build;
  }

```

and there is an accordion.html.twig where I added the code for displaying the sdashboard widget. It is given as:

```
<div class="demo">
<h2>{{  title }}</h2>
<div id="accordion">
  .... accordion here ...
</div>
<ul id="myDashboard"></ul>
<script type="text/javascript" >
  var tdata = [],i;

  for(i=0;i<4*Math.PI;i++){
  tdata.push([i,Math.sin(i)]);
  }

  var widgetDefinitions = [
  {   widgetTitle:"Plot Example",
      widgetId : "first" ,
      widgetType : "chart" ,
      widgetContent : {
      data : [tdata],
      options : {points:{show:true}}
      }

  }
  ]
  $("#myDashboard").sDashboard({
  dashboardData : widgetDefinitions
  });
</script>

</div>

```

Now when I am trying to run the example, I get the error:

```
ReferenceError: $ is not defined
$("#myDashboard").sDashboard({
accordion (line 299, col 3)
ReferenceError: Flotr is not defined
factory($, Flotr);

```

Isn't this the usual way of using any external library in drupal. How do I use other libraries that I may need like sDashboard, etc?

# Answer
> 2 votes
If you are trying to add a js library from an external cdn in drupal 8 then, in your theme/module mycustom.libraries.yml file add do like this:

**NOTE:** Make sure you indent each spaces with two *spacebar press* button and not a tab press.

**NOTE:** *version* is optional here. You may not need add in.

```
mycustom.flexslider:
  version: 2.6.3
  css:
    theme:
      //cdnjs.cloudflare.com/ajax/libs/flexslider/2.6.3/flexslider.css: {type: external}
  js:
    //cdnjs.cloudflare.com/ajax/libs/flexslider/2.6.3/flexslider.min.css: {type: external}
  dependencies:
    - core/jquery

```

If you are hosting it within your module or theme then:

**NOTE:** Here I placed flexslider within my theme or module vendor directory. So it would be inside mycustom/vendor/flexslider

```
mycustom.flexslider:
  version: 2.6.3
  css:
    theme:
      vendor/flexslider/flexslider.css: {}
  js:
    vendor/flexslider/jquery.flexslider-min.js: {}
  dependencies:
    - core/jquery

```

If you are just trying to host your custom js or css file then:

```
mycustom.myscript:
  js:
    js/script.js: {}

```

If its dependent on other library like core jquery or custom library then:

```
mycustom.myscript:
  js:
    js/script.js: {}
  dependencies:
   - core/jquery
   - mycustom.myscript2

```

Then like in example module If I had to add flexslider library:

```
public function getFlexSliderImplementation() {

    $build['myelement'] = array(
      '#theme' => 'js_flexslider',
    );
    // Add our script. It is tiny, but this demonstrates how to add it. We pass
    // our module name followed by the internal library name declared in
    // libraries yml file.
    $build['myelement']['#attached']['library'][] = 'mycustom/mycustom.flexslider';
    // Return the renderable array.
    return $build;
  }

```

**Update:** Download and extract Flotr2 to your module or theme vendor directory. Modify libraries.yml file to include flotr2

```
js_example.flotr2:
 js:
   vendor/flotr2/flotr2.min.js : {}

js_example.sdashboard:
  css:
    component:
      vendor/sDashboard/sDashboard.css: {}
  js:
    vendor/sDashboard/jquery-sDashboard.js : {}
  dependencies:
    - core/jquery
    - core/jquery.ui
    - core/jquery.datatables
    - js_example/js_example.flotr2

```

---
Tags: theming, 8, javascript
---


# Question
Title: Does field_revision_field_xxx table store the same values as field_data_field_xxx does?
I use drupal7.

According to the answer here,

* {field\_data\_\[field\_name\]} Standard data storage for a field.
* {field\_revision\_\[field\_name\]} Standard revision storage for a field.

I understand it, but, finally, they store the same values, right? This is because, I found that field\_revision\_field\_xxx actually stores the updated values after I update a field-xxx.

\[The reason why I ask this\]
I try to transfer field values from one profile type to another which have the same uid. For it, I create field\_data\_field\_xxx\_transfered and field\_revision\_field\_xxx\_transfered and rewrite the pid in them.

I succeeded to transfer values from field\_data\_field\_xxx to field\_data\_field\_xxx\_transfered. And, if field\_revision\_field\_xxx stores the same values as field\_data\_field\_xxx does, all I need to do is to copy field\_data\_field\_xxx\_transfered to field\_revision\_field\_xxx\_transfered. And, this is much easier than to do from field\_revision\_field\_xxx to field\_revision\_field\_xxx\_transfered.

Thank you.

# Answer
Yes, field\_revision\_\[FIELD\_NAME\] contains the same value as field\_data\_\[FIELD\_NAME\]. The only difference in both these table is, if you've enabled revision for entity having this field (\[FIELD\_NAME\]), the field\_data\_\[FIELD\_NAME\] will contain the latest revision value of the field and field\_revision\_\[FIELD\_NAME\] will contain all revision value.

For example, Suppose I've a content type `article` with revision enabled, and has a field `field_tags`. I've then created a content of type `article`, so now `field_data_field_tags` and `field_revision_field_tags` contain data for the content I've just created. After this when ever I'll be updating this content, the `field_data_field_tags` will hold the latest revision data for `field_tags` field and `field_revision_field_tags` will hold all revision data for `field_tags` field i.e. revision id 1, 2, 3 and so on.
> 2 votes

---
Tags: 7, entities, database
---


title: How can I edit a mini-panels output?

text:
# Question
Title: How can I edit a mini-panels output?
I have a minipanel that out puts a price, based on the node, but without a currency symbol. I wanted to add a dollar sign so created a new .tpl file and added it as such:

```
<div class="<?php print $classes; ?>" <?php print $id; ?> <?php print $attributes; ?>>
  $<?php print render($content); ?>
</div>

```

However, the content renders a div as well, so on the front end I get:

```
$
<div class="entity-property entity-property-price">
49.99
</div>

```

Would anyone know where I can access this 'entity-property' div so I can drop in my '$' sign?

# Answer
> 0 votes
Turns out there was yet another .tpl file, just for this element, I could copy from the moduel and place in my themes directory - component.tpl.php

---
Tags: 7, panels
---


title: How to show only updated nodes in VIEWS

text:
# Question
Title: How to show only updated nodes in VIEWS
I am creating a **View** in **Drupal 7** for a particular content type. I want to **add filter to show nodes which are updated**. When I am adding Node Update Date field, it is asking for operator and Value to compare with. But I can not provide Updated date of each node.

Then I also tried **hook\_views\_query\_alter** to alter the query. When I am adding Query Value to node.created field it take it as a string or you can say Value.

Can someone help me to achieve this?

# Answer
> 0 votes
You may be able to use hook\_views\_query\_alter to load only nodes which have node.updated value equal to NULL or ''.

# Answer
> 0 votes
There's actually a filter available called `Content: Has New Content` specifically for this use case.

```
Content: Has new content
Show only content that is new or updated.

```

# Answer
> 0 votes
You can use the sort option and Sort by Content: Updated date in the views.

---
Tags: 7, views
---


# Question
Title: How do I create a .tpl file for a panel pane?
So, I want to add some HTML to surround the output of a Panel pane. I know the existing pane is rendered with:

`panels-pane--entity-field-extra.tpl.php`

If I edit this file, of course, every pane using it will show the changes.

If I create a new .tpl, say `panels-pane--entity-field-top.tpl.php` how do I apply it to a particular pane?

# Answer
You can refer Documentation on Panels Pane template, which provides details on how to define a template for Panels Pane. If you want to add your own template name you can also do that by implementing `template_preprocess_panels_pane` in your theme or module file. Example for same is also available on documentation page.
> 1 votes

---
Tags: 7, panels
---


# Question
Title: Field image in attachment affect block settings
I created a block in views with field image and title.

Then I created an attachent after the block with title only.

The field image in block is gone after I removed the field image in attachment.

How do I make it override? I can't find the settings.

# Answer
View module provides ability to override changes based on display. Please check steps below:

1. Go to Attachment display.
2. Click on Down arrow, next to Fields, and click on Rearrange. As per shown in screenshot.
3. Click on **For** drop down and select "This attachment (override)" and click on **Apply** button. check screenshot below:
> 1 votes

# Answer
Before removing the field image in attachment Please select "This attachment (override)" on the top select box.Then you can retain field image in block only
> 0 votes

---
Tags: views
---


title: How to add a login to a tab

text:
# Question
Title: How to add a login to a tab
I have a website, but I want to figure out how to create a tab or link within the website that users would have to log in to view. There would most likely be one set of log in information that everyone in my organization would use. For example, maybe the username is org27 and password is 222orgs and everyone would use that to access the tab or link. How would I do that or is that even possible? Thank you.

# Answer
> 1 votes
You might take a look at the module, Protected Pages. https://www.drupal.org/project/protected\_pages
It seems your tab would direct users to a particular page with sensitive or unique information pertaining to only those users. In that case a simple module protecting those pages might do the trick.

---
Tags: users
---


# Question
Title: hook_tokens() implementation no longer being called
We have a custom module in development, the purpose of which is to fetch the email addresses of the users who review content. Upon revisiting this module (after updating from Drupal-7.41 to Drupal-7.51) its `hook_tokens()` implementation is no longer being called in the same way it was before.

I cannot understand why this functionality no longer works. I thought this was a proper implementation of these functions. It now no longer fires on nodes, but when an entity is on a node.

Why would `hook_tokens()` not be called on a node? (The module is enabled, depends on tokens and workbench\_access, both of which are enabled.)

Please forgive me if my question is framed inappropriately, I may have an inaccurate understanding of the hook function(s), but I've checked the API and haven't gained clarity. I know for a *fact* that this module worked earlier this year with Drupal-7.41, but I couldn't find any changes in the related API since that release.

```
function mymodule_token_info() {
   $info = array();
   $info['tokens']['node']['publisher_one'] = array(
     'name' => t('Section Publisher One'),
     'description' => t('Email address of sections primary publisher.'),
   );
   $info['tokens']['node']['publisher_two'] = array(
     'name' => t('Section Publisher Two'),
     'description' => t('Email address of sections secondary publisher.'),
   );
   return $info;
}

function mymodule_tokens($type, $tokens, array $data = array(), array $options = array()) {
   $replacements = array();
   if ($type == 'node' && !empty($data['node'])) {
      print_r('inside if conditional');
      $section_users = array();
      $users = entity_load('user');
      // Get the current Page's section ID (sID).
      $sID = key(_workbench_access_get_node_section_names($data['node']));
      $user_count = 0;
      // Is a given user 1) assigned to the same section as the node and also
      //  of the role identified as the one to be notified.
      // If so, their email address are acquired.
      foreach($users as $user) {
          $user_sections = _workbench_access_get_user_section_names($user);
          if(array_key_exists($sID, $user_sections) && $user_count < 2){
              $role_type = user_roles(TRUE)[variable_get('waemail_role', '0')];
              if(in_array($role_type, $user->roles)){
                  if($user_count == 0){
                      $section_users['publisher_one'] = $user->mail;
                      $user_count++;
                  }
                  else if($user_count == 1){
                      $section_users['publisher_two'] = $user->mail;
                      $user_count++;
                      break;
                  }
              }
          }
      }

      // Assign the values aquired above to the tokens.
      foreach ($tokens as $name => $original) {
          switch ($name) {
              case 'publisher_one':
                  if(!empty($section_users[$name]))
                      $replacements[$original] = $section_users[$name];
                  break;
              case 'publisher_two':
                  if(!empty($section_users[$name]))
                      $replacements[$original] = $section_users[$name];
                  break;
          }
      }
    } //end if($type == 'node'...
 return $replacements;
}

```

# Answer
> 1 votes
`hook_tokens()` is invoked only when `token_generate()` is called. Since that doesn't necessarily happens when a node is viewed (or similar events), but it happens when a module calls `token_replace()`, `hook_tokens()` not being invoked could not mean your code is wrong.

Assuming that the code you show is not causing any PHP error, that means that a module that was before calling `token_replace()` is not calling that function anymore, or it is calling it in very specific occasions.
For PHP error I mean:

* The code is calling a function that doesn't exist anymore (e.g. `_workbench_access_get_user_section_names()`)
* It is calling a function that is returning a value of a different type from what it previously returned (e.g. `_workbench_access_get_user_section_names()` returns a value that is not an array)

There isn't any change in the token subsystem from Drupal 7.41 to Drupal 7.51 that could cause your code not to work anymore. The only reason for your `hook_tokens()` implementation not to be invoked in a change in the code of the module your hook implementation is using, or a change in the code of a module that was generating token when viewing a node (or a similar event).

To test your implementation of `hook_tokens()`, you should directly call `token_replace()` passing a string containing a token your module defines and a node object. If the token is not replaced, then you can check for errors in your code; if the token is replaced, then your code is working perfectly, and your `hook_tokens()` implementation is not invoked simply because no module is replacing tokens in a string when you are expecting it to happen.

I would use the following code, to put in a file in the same directory containing the index.php file that comes with Drupal.

```
/**
 * @file
 * Test page to check the hook implementation of a custom module work.
 */

/**
 * Root directory of Drupal installation.
 */
define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// Load a node to use as context for the tokens.
// Change the argument for node_load() to match the node ID of
// an existing node.
$node = node_load(1);

// Change the string to the token name for the token that needs to
// be tested.
$token = 'publisher_one';

$result = token_replace("[$token]", array('node' => $node), array('clear' => FALSE));

if ($result == "[$token]") {
  // The token has not been replaced.
}

```

---
Tags: 7, hooks, tokens, workbench
---


# Question
Title: how to create node for ecommerce display page?
I am new to drupal ecommerce.

I created one product type as service for that I have to create a service display content type using node, how can I create this node ? and how to enable that node ?

Thanks,

Vinudha

# Answer
> 0 votes
There is a module Auto Product Display

This module will do automatically create product display for you.

> This module is created in order to solve that problem. This module can simplify the Product Display creation process by providing option the create it at the same time with Product creation.
>
> **Features**
>
> 1. Provide the Product Display creation form along with the Product creation form. User can fill that form to create Product Display at the same time with Product creation.
> 2. That form, which used to create Product Display, will be the same as the form when user try to create Product Display manually. So, If you have additional fields in your Product Display node type, those fields will also appear in the form.
> 3. If the product is referenced by only one Product Display, the Product Display content is displayed directly to the form, so it will be automatically updated when you save the product.
> 4. If the product is referenced by more than one Product Display, the referencing Product Displays will be displayed in list, so you can also update the Product Display by clicking the link from that list first.

If you want to create manually, this will guide you

"Product Display" is the default content type that Commerce Kickstart 1.x creates and it has a product reference field. Technically, any entity that has a product reference field could be considered a product display. Nodes are the obvious product display entity type, and they're privileged because they're the default and standard entity type to use for the front-end display of content. But you could use taxonomy vocabularies, or even users as product displays.

Taken reference from here

Basically you need to add product reference field field for your node.

---
Tags: nodes
---


# Question
Title: Custom Search Page Filtered by Content Type
Is it possible to have custom search pages that filter based on content type? I attempted adding a hidden input to the search form like so:

```
<form class="search-block-form" data-drupal-selector="search-block-form-7" action="/search/node" method="get" id="search-block-form--7" accept-charset="UTF-8" data-drupal-form-fields="edit-keys--7">

<input title="Enter the terms you wish to search for." data-drupal-selector="edit-keys" type="search" id="edit-keys--7" name="keys" value="" size="15" maxlength="128" class="form-search">

<input data-drupal-selector="edit-submit" type="submit" id="edit-submit--8" value="Search" class="button js-form-submit form-submit">

<input type="hidden" name="type" value="blogpost">

</form>

```

But the search results page ignores the 'type' variable in the GET request and displays all results instead of just the results of the content type I want. I also noticed that you can create multiple custom search pages in the configuration page, but there doesn't seem to be any options for filtering by content type. Is there anyway to have a search page that filters based on content type? Preferably without creating a view page.

# Answer
> 1 votes
A few things to note:

1. The **Advanced Search** portion of Drupal core search (that filters by type) works by POSTing to the **/search/node** route so altering the form wouldn't help here.
2. For custom search pages, the **Advanced Search** \> **Content** types option is for controlling *the display only* so it won't help here.

The core search block doesn't have the ability to customize for filtering on types, but a contrib module called Custom Search will. Under its **Content** configuration section there exist options to control what can be selected as content types to filter on.

# Answer
> 1 votes
You can use "custom search" module for filter search by a particular content type

---
Tags: 8, search
---


# Question
Title: What is the use of node--product_display.tpl.php?
I am new to Drupal Commerce, what is the use of `node--product_display.tpl.php`?

# Answer
> 0 votes
`node.tpl.php` is the default theme for all content types in a drupal installation. If you want a specific content type to have different layout/theme you can override by creating a tpl.php file like this `node--[CONTENTTYPENAME].tpl.php` so for example for ARTICLE content type your would copy `node.tpl.php` and rename to `node--article.tpl.php` and adjust the new file to as you desire.

Now Commerce displays a product using a CONTENT type called product display thus to change the look of this content type you will create `node--product_dispaly.tpl.php`

here is some more explanation of things that you can do inside a node.tpl.php file and (all overrides) https://api.drupal.org/api/drupal/modules%21node%21node.tpl.php/7.x

# Answer
> 0 votes
File ending with `.tpl.php` extension are template files used for defining the HTML output of anything like Page, Node, Region, Block, Comment, etc.

When working (overriding) with node.tpl.php (used to override HTML of content) 2nd part after `--` consist of Content Type name or Content ID. i.e. node--\[content\_type|nodeid\].tpl.php. File `node--product_display.tpl.php` is used to override/re-write HTML of Content of Content (Node) Type **Product Display**.

Read more details about Template (theme hook) suggestions.

---
Tags: theming, commerce
---


# Question
Title: How can i customize the display of private message module?
I am new to drupal, present i am using Private message module 7.x-1.4 version.

After installing this module it look like this (screenshots attached) current look and feel is not pretty. how can I customize this ? suggest me the changes.

# Answer
If as you say you only want to change the look/theme then you should create a custom theme and override it using custom css rules.

Doing this requires knowledge of css/html and creating a drupal subtheme as modifying an existing theme/module/core is not advisable

Here is tutorial of how to create a custom subtheme https://www.drupal.org/docs/7/theming/howto/create-a-new-custom-theme-with-css-alone

NOT RECOMMENDED If you still want to HACK core/module/theme then in your Chrome/Firefox/Opera/Safari browser just right click on the element that you want to change and use inspect/inspect element or something similar. There you can see which css rules and in which file influence the display of each element. You can even adjust the visual properties (css rules) of each element and when you are satisfied with the result you should go and change the appropriate files.

Here is a tutorial of how to use the chrome inspector https://developer.chrome.com/devtools but inspectors of other browser should be very similar
> 0 votes

---
Tags: views, theming, privatemsg
---


title: User band management

text:
# Question
Title: User band management
I have a content type of band. I have a view filtering by user id to see my bands.

What I'm trying to accomplish is allowing users to create a band and have a management dashboard. This dashboard would be separate from their public facing page.

I would like the dashboard to have the ability to add shows, members, photos etc all on the same screen.

My guess would be to create a page with multiple views filtered based on some type of criteria either a reference field to members or the single node author.

Is there a better approach to handling this type of functionality?

# Answer
Your question is about relationships between the different entities or content types like users, bands, shows and so on. You build this relationships with reference fields.

For the dashboard you don't need necessarily views.

When you use a reference field to another entity you can configure in the display mode to render the referenced entities. Then you can configure the display mode of the referenced entity, which can contain itself other reference fields which you then configure in the same way and so on.

So you can build and theme the complete dashboard without views by only showing the parent entity.

Though at some point you probably need views, as view block in a header, footer or sidebar or from the start as view page, if you need more options for filtering. The entities displayed in these views can contain again rendered reference fields. This is how you combine these tools to build the layout you want.
> 1 votes

---
Tags: views, nodes, 8, dashboard
---


# Question
Title: How to create multiple nodes using Rules once?
I have a content type named Run that have two entity reference

1. entity reference field named participants which reference user.
2. entity reference field named examinations which reference content type Examination.

I want to use Rules to create multiple nodes of content type "Results" for each user "participant" referenced in "Run". the number of Results nodes equals the number of examination.

So I created a rule that fires when the user views the node of type run and I made a loop through examination and I created results node. This runs OK for the first time. But when the user views the node again the nodes are duplicated n times as per number of node views.

Any suggestions how I can make the rule run once per user? Or any other work around.

# Answer
> 0 votes
You could use the Flag module and define a none global flag used to flag nodes of type "Run" (name the flag whatever you want).

Then extend your existing Rule like so:

* Add an extra **Rules Action** to flag that node of type "Run" (to indicate that the rule was executed a first time for that user).
* Add an extra **Rules Condition** to check that the node was NOT yet flagged by the user viewing the node.

Using this approach, you have a mechanisme in place that allows you to keep track of the users for which your rule was yes or no executed exactly 1 time.

---
Tags: rules
---


# Question
Title: How do I call an object in a prepressor only once
In drupal8 is there a way to call a function only once in the theme layer. Can I call this function only once and not on other preprocessor hooks or am I using the wrong hook?

```
function template_preprocess(&$vars){
    //-- can I call this function only once and not on other preprocessor hooks
    _updateFieldOnNode('field_metatag_title');
}

```

# Answer
If you want to call the preprocess hook on nodes only you can use template\_preprocess\_node().
> 0 votes

---
Tags: theming, hooks
---


# Question
Title: Are there any easier ways to update a site than following the official instructions?
For tech people (like sys admins) the are the official instructions about How to update Drupal Core for how to update a site. But what if the user is inexperienced and just wants to maintain the site by installing security updates?

I can follow these steps myself but if I'm not available it's important that anyone (in the organization I'm volunteering for) can do it.

So, are there any easier ways to update a Drupal 7 site than following the official instructions?

# Answer
> 0 votes
If you have access to ssh in your server install drush (drupal shell) http://docs.drush.org/en/master/install/

This will only need to be done once and and then it will be easy to apply drupal core updates from the command line

```
drush up drupal

```

or any other module updates

```
drush up views

```

But I would recommend applying ALL security patches at once (core and modules security updates) using

```
drush upc --security-only

```

all the above commands will do all the necessary actions as described in the instructions that you linked above and in case of a bad update the updates are reversed with error messages displayed.

To learn drush read https://www.ostraining.com/blog/drupal/drush/ but the installation instructions might be a little outdated. You can also learn more drush commands at drushcommands.com

---
Tags: 7, updating
---


title: problem with JOIN query

text:
# Question
Title: problem with JOIN query
I have tow custom fields field\_city and field\_priority for a user profile. Now I want to fetch the priority for a city like chicago. ( all I want is max priority for a city but first trying to fetch all )

I am trying with following queries but they are not giving me any result, I am getting a blank array. it works when I remove WHERE clause but not with WHERE for a city.

```
$query = "SELECT p.field_priority_value, p.entity_id, b.field_city_value FROM field_data_field_priority p LEFT JOIN field_data_field_city b on p.entity_id = b.entity_id WHERE b.field_city_value='chicago'";
    $result = db_query($query);
    $res = $result->fetchAll();

```

Tried following code with drupal query function.

```
$query = db_select('field_data_field_priority', 'p');
    $query->join('field_data_field_city', 'd', 'p.entity_id = d.entity_id');
    $query->fields('p');
    $query->condition('d.field_city_value','chicago','=');
    $result = $query->execute();
    $res = $result->fetchAll();

```

# Answer
> 0 votes
In the original query, you're using LEFT JOIN, so that will return results for the priority table, even if there is no successful join to the city table.

To match that query, use -\>leftJoin instead of -\>join

https://api.drupal.org/api/drupal/includes%21database%21select.inc/function/SelectQuery%3A%3AleftJoin/7.x

Otherwise, your query should be correct and you don't have a priority for chicago.

---
Tags: 7, database
---


# Question
Title: Image path all 404 after move my remote site to localhost
I just moved everything from my remote Drupal site to localhost (C:\xampp\htdocs\folder). All links (content images, menu links) are shown like `http://localhost/sites/default/files/inline-images/magento.png` when it should be `http://localhost/foldername/sites/default/files/inline-images/magento.png`.

Is there any quick method I can use to fix this problem like using mod\_rewrite?

# Answer
If the RewriteBase Method is not working and every other page works, try to set the $base\_url variable in your settings.php file to your folder.
> 0 votes

# Answer
You can try with pathologic module for solving image url issue
> 0 votes

---
Tags: 8, migrations
---


title: Group repeating dates in Views

text:
# Question
Title: Group repeating dates in Views
**I have this scenario:** The contenttype "event" has a date-field (with repeat-options). All repeating events are repeated for a certain timespan once a week.

**I want to achieve this views-block:**

* Show me all repeating events (got this to work with condition eventdate:rrule not empty).
* Group by Event-Id and don't show me every repeating event (because the description text of the event contains the human-readable repeat-logic ... e.g. every tuesday at 12.00)

**My Problem is:** I activated "Use aggregation" in the view and wanted to group the events by node-id, but the date field (field\_data\_field\_event\_date\_field\_event\_date\_value) is automatically added to the "GROUP BY"-SQL part when i do this (and i can't remove it)

Am I using the wrong approach?

# Answer
> 1 votes
I ran into similar problems and managed to fix it by enabling Aggregation on the view plus enabling 'Distinct'.

---
Tags: 7, views, datetime
---


# Question
Title: entity_reference field widget as select instead of autocomplete
Is there a select widget I can use instead of autocomplete for referencing entities? Right now I am using this in my `baseFieldDefinitions` function:

```
->setDisplayOptions('form', array(
    'type' => 'entity_reference_autocomplete',
    'settings' => array(
      'match_operator' => 'CONTAINS',
      'size' => 60,
      'placeholder' => '',
    ),
  ))

```

but I need to have a select widget instead. Any ideas?

# Answer
I was able to change the widget from the field config page. The key used by drupal was `options_select`, so I updated the type to:

```
'type' => 'options_select'

```
> 3 votes

---
Tags: 8, entities
---


title: How do I correctly use states?

text:
# Question
Title: How do I correctly use states?
I have a form that has a field with conditional validation. I mean if a certain radio button is checked, then the field need to be required. Please find below a code snippet of how I tried to solve it. Unfortunately, when I run this code, the field disappears, and when I comment out this logic, the field appears again.

I implemented the code from https://api.drupal.org/api/drupal/core!includes!common.inc/function/drupal\_process\_states/8.2.x.

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYTHEME_form_user_register_form_alter(&$form, FormStateInterface $form_state) {

  $form['the_field'] = [
    '#states' => [
      // Only make the field 'the_field' as required when the 'field_of_type_radio' value is equal to '1'.
      'required' => [
        ':input[name="field_of_type_radio"]' => ['value' => '1'],
      ],
    ],
  ];

}

```

# Answer
> 0 votes
```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYTHEME_form_user_register_form_alter(&$form, FormStateInterface $form_state) {
  // If your field is link field
  $form['the_field']['widget'][0]['uri']['#states'] = [
    // Only make the field 'the_field' as required when the 'field_of_type_radio' value is equal to '1'.
    'required' => [
      ':input[name="field_of_type_radio"]' => ['value' => '1'],
    ],
  ];
  // If your field is text field
  $form['the_field']['#states'] = [
    // Only make the field 'the_field' as required when the 'field_of_type_radio' value is equal to '1'.
    'required' => [
      ':input[name="field_of_type_radio"]' => ['value' => '1'],
    ],
  ];
}

```

---
Tags: 8, forms
---


# Question
Title: Blank screen with no error messages on new server
I have a working Drupal 7 site, built with git, running on 2 different servers, one test server and one server used for staging and production sites. So I know that the site is working.

So after deciding to move the production and staging sites to a new Apache server I cloned my git repo with the whole codebase, to the webroot and created the database and imported a copy of the mysql database.

I then edited the settings.php file to match the new database name, user and password. Using SSH and Cygwin I can login and run mysql commands, like 'show databases' etc. So I know that the mysql connection works too.

But when I try to test the site from a browser I just get a white screen, that times out after a couple of minutes.

I have read this artcile How to see the error messages when I get the white screen of death?, and I have added the suggested lines in order to show error messages in both index.php and settings.php with no change whatsoever. Just a white screen and the busy icon turning.

So maybe there is something in .htaccess that needs to be changed? I tried to uncomment the rewritebase line and adding the site name, with no luck.

```
  RewriteBase /

```

The phpinfo.php file in the webroot opens without problems. So I guess it must be somehting odd with the site all the same.

The file structure on the web server does not include any public\_html folder. This is how it looks and I have cloned my site directly into this folder:

```
/home/httpd/example/www.example.com

```

Is that the problem here? That Drupal 7 needs a another folder structure?

This is what the server error log looks like, after the timeout:

```
PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 130968 bytes) in /home/httpd/example/www.example.se/includes/bootstrap.inc on line 966

```

After increasing the memory\_limit from 128 MB to 512 MB, the apache server's error message stops complaining about the memory and instead shows this message:

```
Script timed out before returning headers: index.php

```

I now tried to do a fresh install of a Drupal 7 site with a new database, which actually worked. I then changed the database settings in settings.php to call my original site database. And that worked to.

So now my code is on speaking terms with the right database. But I have no git branches and all my images an so forth in the default/files folder is missing. But why did this work? Is there a step when deploying a Drupal site to a brand new server with git, that I missed? The git repo contains everything that is needed, but still it didn't work. Please help, if anyone recognizes this behavior.

# Answer
> 1 votes
In case anyone else is struggling with the same problem, here is how I could partially solve it and open the site without the white screen.

In the settings.php file I commented out this line:

```
// $conf['memcache_servers'] = array('localhost:11211' => 'default');

```

So if you are using Memcache and are moving to a new environment, try the above if you encounter a white screen problem.

---
Tags: 7, installation, .htaccess
---


# Question
Title: How to create and hide user login link in drupal 7?
Hello everyone I am new to drupal, I want to know the steps to create user-login link in menu bar and after user-login this link should be convert into logout link. Can any one help me ?

# Answer
> 0 votes
Goto

```
Admin -> Structure -> Block -> User login [Region : None]

```

# Answer
> 0 votes
You can add two links to needed menu manually. First - user/login, second - user/logout, the system control link permissions, so when you are not logged, you can see login link and vice versa, when you logged in - you can see logout link and cannot see login link.

---
Tags: users
---


# Question
Title: Get taxonomy name in cycle (performance)
I have a subset of data ($query-\>execute) where 1 column is an ID of taxonomy.

I need to replace 'term id' on 'term name'. Right now I just make 'lookup' for each id and replace it with name:

```
foreach ($entries as $entry) {
  $row = array_map('check_plain', (array) $entry);

  // --> HERE I WANT TO AVOID LOOKUP FOR SAME ID
  $location = taxonomy_term_load($row['term']);
  $row['term']=$location->name;
}

```

However I'm not sure if it is a proper way to do that, since I have many similar ID and I want to avoid useless lookups (so I do lookup only for 'unknown' ID)

Should I build my own cache variable-list for every new ID or there is already an efficient way to do it?

# Answer
You can use custom query like next:

```
$result = db_select('taxonomy_term_data', 't')
  ->fields('t', array('tid', 'name'))
  ->condition('t.tid', $tids, 'IN')
  ->execute()->fetchAllKeyed();

```

Or you can do join with entity table for single query.
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: how to propose when editing content 2 possible media style for an image field?
My content type has an image field. I'd like to propose to the editor two possible displays for that uploaded image, either 100% width or 50% width How can i achieve that?

EDIT: i found out this module : https://www.drupal.org/project/field\_image\_style Is this module stable enough?

How can I make this behavior compatible with the field formatter from colorbox module?

# Answer
> 1 votes
You could add a separate select dropdown textfield with two options, which are the image styles you'd like, and if they select the alternate one, update the field in hook\_entity\_view.

```
 function mymodule_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
   if ($entity->getEntityType()->id() == 'node' && $entity->bundle() == 'article' && !$entity->field_image_style->isEmpty()) {
     $style = $entity->field_image_style->getValue()[0]['value'];
     $build['field_image'][0]['#image_style'] = $style;
   }
 }

```

---
Tags: 8, media
---


title: Search API path make SEO friendly

text:
# Question
Title: Search API path make SEO friendly
I am using **Search API**. I make a view of all the indexed entities and uses **Taxonomy term** as **Contextual Filter**. But the path of view is not SEO friendly. The path is like **http://www.example.com/en/Real%20Estate**.

I want to make this path SEO friendly and convert this **space(%20) to dash**. In views I am getting configuration "**Convert dashes into spaces**" for contextual filter.

I tried to alter the views and implement **hook\_views\_pre\_render, hook\_views\_post\_render, hook\_views\_post\_build and hook\_views\_post\_execute**. This time it is not showing the results.

Can anyone help me regarding this?

# Answer
> 0 votes
Facet Pretty Paths module to the rescue https://www.drupal.org/project/facetapi\_pretty\_paths

# Answer
> 0 votes
I managed to do that with the following code:

```
/**
  * Implements hook_views_pre_view().
  */
 function hook_views_pre_view(&$view, &$display_id, &$args) {
   /* Search page view */
   if ($display_id == 'search_page' && !empty($args[0])) {
     $args[0] = strtr($args[0], '-', ' ');
   }
}

```

You should also adjust the search form ofcourse..

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


title: Refreshless doesn't work

text:
# Question
Title: Refreshless doesn't work
I just tried to setup the RefreshLess module for my Drupal 8 site; after enabling it, I just see that some meta information is added to the DOM, but switching pages using links seems not to be effected in any way.

As written in the README file, I applied the patch to core.

How can I debug this?

**PS**: The refreshless.js file is not even loaded.

# Answer
I was wondering the same and maybe this code is related:

```
function refreshless_page_attachments(array &$page) {
  $request = \Drupal::request();

  // Refreshless is only sensible when there is an actual session (otherwise the
  // entire page can be cached by the page_cache module, and be sent more
  // quickly than Refreshless could).
  // @see \Drupal\big_pipe\Render\Placeholder\BigPipeStrategy.
  $session_exists = \Drupal::service('session_configuration')->hasSession($request);

  $page['#cache']['contexts'][] = 'session.exists';
  if ($session_exists) {
    $page['#attached']['library'][] = 'refreshless/refreshless';
  }
}

```

It could be that for anonymous user the library is not loaded at all(check the comments in the function).

However I am not 100% sure.

Update: if you log in, you can see that refreshless.js is loaded.
> 2 votes

---
Tags: 8, caching
---


title: Tokens for multi-valued fields?

text:
# Question
Title: Tokens for multi-valued fields?
In D7, it seems the token for fields (e.g., `[node:field_date]`) just returns the rendering of the field. So if the field is multi-valued, this token returns all the values rendered together. However, I'd like to be able to access specific delta values of the field separately using tokens, e.g. using `[node:field_date:0]` or similar syntax. I also want to be able to chain the token, e.g. `[node:field_date:0:long]`.

Has this been done before? My solution would be to use `hook_token_info_alter` to mark the field's token as `dynamic`, then do my own parsing in `hook_tokens_alter`. But if I do this, will I lose the ability to chain the token?

# Answer
> 1 votes
Have you tried Entity Tokens? It's part of Entity API module.

There are long discussions about date tokens: Date issue about date tokens and Entity Token issue about multi-value field tokens.

# Answer
> 0 votes
For Date fields there are 3 available values to use...

```
[node:field-date:value]    = Start date
[node:field-date:value2]   = End date
[node:field-date:duration] = Well... Duration. :-)

```

/marcus

# Answer
> 0 votes
I found I needed to use the Compound Token module for this.

Works with vanilla Token:

```
[node:field_my_field]

```

Throws errors with vanilla Token; Works after installing Compound Token:

```
[node:field_my_field:und:0:value]

```

---
Tags: 7, tokens
---


# Question
Title: How can I change a theme for a specific module?
I am new to Drupal, I want to change a theme for a particular module (private message module) current look and feel is not pretty.

I am planning to put a "Garland" theme for Private message module. I have two development environments dev1 & dev2. I have installed private message module in both Environments with different themes Dev1 have "Seven" and Dev2 have "Garland" theme.

Is it possible to set in dev1 with private message module theme as "Garland" and remaining all can use "Seven" theme?

# Answer
There's no such concept as "a theme for a particular module": modules generate and manipulate content, working together to build the different parts of a page. Then a single theme renders that content to produce the HTML you see in the browser.

Your best bet would be to identify the paths of pages which you want to use a different theme for, and use something like the Theme Key module to manage the switching for you.
> 1 votes

---
Tags: 7, theme-negotiation
---


# Question
Title: Title tag not overriding after using meta tag module
I have created a content type for uploading user details. I have changed the title as **UPLOAD PAGE** using `drupal_set_title`. I have installed Meta Tag module, now page title remains same but title tag i.e. (title displayed in browser tab) are different. Please guide me. Thanks

# Answer
Try theme\_preprocess\_html and modify the title using variable `header_title`

Sample code:

```
function mytheme_preprocess_html(&$vars) {
  $vars['head_title'] = 'TITLE';
}

```

It works for me.
> 2 votes

# Answer
Thanks @Vamsi - $vars\['head\_title'\] did the trick for me after lots of frustrating experiences trying different module/UI and code based methods. Here's how I ended up using this to override a particular view one page at a time:

```
function mytheme_preprocess_html(&$vars) {

  // customize <title> tag for a complex view with url structure /people/%
  if (arg(0)=='people'):
    switch (arg(1)) {
      case 'faculty':
        $vars['head_title'] = 'People - Faculty - My School';
        break;
      case 'graduate-students':
        $vars['head_title'] = 'People - Graduate Students - My School';
        break;
      case 'alumni':
        $vars['head_title'] = 'People - Alumni - My School';
        break;
    }
  endif;

}

```
> 0 votes

---
Tags: 7, meta-tags
---


# Question
Title: How do I install Flysystem and Flysystem S3?
I'm using the Flysystem module, but I am not able to install the module. I am getting this error:

> Dependencies missing: Flysystem, replicate adapter, stream wrapper.

I followed the steps given on https://www.drupal.org/node/2541116, but I am still not able to install the module.

I have installed the Replicate and Stream wrapper modules.

Is there any other method to integrate S3 with Drupal 8?

# Answer
That documentation you referenced is outdated and wrong. You should read the official documentation on https://www.drupal.org/node/2404989.

The easiest way to do this is to install the drupal modules with composer, as documented on https://www.drupal.org/node/2718229. Once you've configured the drupal.org repository, installing a module is as simple as `composer require drupal/flysystem`. That will download that module, including alll dependencies that it needs for you.

You can manage your whole installation, including core, with composer if you use `composer create-project drupal-composer/drupal-project:8.x-dev`. You can also add contrib modules if you installed drupal core by hand, but when updating core, you need to be careful to not lose your composer.json changes and run composer update again.
> 3 votes

# Answer
There is a module called S3 File System

> S3 File System (s3fs) provides an additional file system to your drupal site, which stores files in Amazon's Simple Storage Service (S3) or any other S3-compatible storage service. You can set your site to use S3 File System as the default, or use it only for individual fields. This functionality is designed for sites which are load-balanced across multiple servers, as the mechanism used by Drupal's default file systems is not viable under such a configuration

Hope this helps you.
> 1 votes

---
Tags: files, 8
---


title: How to find and remove a cached image?

text:
# Question
Title: How to find and remove a cached image?
I have an image with url like:

```
http://example.com/index.php?q=sites/default/files/imagecache/node-gallery-display/123.JPG

```

I want to remove this image but don't know where it stored in database.

Whenever I remove `123.JPG` from the path, it is re-generated on the next GET request. I removed all nodes with that title from the node table but it had no effect. So I'm have no idea how to find and remove all trace of it from the database. Appreciate your help about it.

# Answer
> 0 votes
Try this:

```
find -name   "123.JPG" -exec rm {} \;

```

---
Tags: 6, database, media
---


# Question
Title: Bakery: Why do I get the "Logging out the user with the bad cookie"?
I am attempting a Single Sign On solution using the Bakery module.

My problem is each attempt to login results in the following error:

> Logging out the user with the bad cookie.

Those failing login attempts are to the master site which also means I can't login to the sub-sites.

All the necessary configurations are in place.

1. The master site is **http://www.example.com/**
2. The master site checkbox is enabled
3. http://sub.example.com/ is input as the slave site
4. Cookie age is set to 3600
5. Private key is **examplesite**
6. Cookie domain is **.examplesite.com**
7. Username and email are my enabled profile fields

I don't get why it's not responding with successful logins. Please help if you can.

# Answer
> 0 votes
As an alternative to Bakery, if your sites are all co-hosted and you're using MySQL, you can get your sites to share user tables as described by Lullabot.

The important parts are the Master site setup:

```
$db_url = 'mysql://user:pass@localhost/master_database';
$db_prefix = '';

```

The shared cookie domain (which you already have):

```
$cookie_domain = '.example.com';

```

And the slave site setup:

```
$db_url = 'mysql://user:pass@localhost/slave_database';
$db_prefix = array(
   'default'   => 'name_of_slave_database.',
   'users'     => 'name_of_master_database.',
   'sessions'  => 'name_of_master_database.',
   'role'      => 'name_of_master_database.',
   'authmap'   => 'name_of_master_database.',
);

```

I have succeeded with this method in the past, though I think I used the normal database array instead of `$db_url`.

---
Tags: 7, authentication-authorization
---


# Question
Title: How to set DataDefinition::create('integer') to allow bigint numbers
I'm trying to create a FieldType in Drupal 8 which needs to be stored as bigint. I set the field in the schema:

```
public static function schema(FieldStorageDefinitionInterface $field_definition) {
return array(
  'columns' => array(
    'value' => array(
      'type' => 'int',
      'size' => 'big',
      'not null' => FALSE,
      'unsigned' => TRUE,
    ),
  ),
);

```

}

I then added the propertyDefinitions:

```
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$properties['value'] = DataDefinition::create('integer')
  ->setLabel(t('Field value'));

return $properties;

```

}

When trying to add an integer of more than 9 digits I get following validation error:

> This value should be of the correct primitive type.

How can I get this correct?

Thanks!

# Answer
I do not believe there is a solution for this.

Typed Data Manager will always add the `PrimitiveType` validation constraint plugin for any primitive data type (data type implementing `PrimitiveInterface`). This plugin does not provide any options for the `filter_var` native PHP function, which is required to set `max_range`. This option itself must be less than the `PHP_INT_MAX` constant. Furthermore PHP\_INT\_MAX is signed and BIGINT is unsigned. 10 digits should be supported by PHP\_INT\_MAX for even 32-bit systems as long as it is below 2147483647, which is probably the case for your PHP build. You could try using a 64-bit version of PHP.

There are three alternatives given the signed/unsigned caveat above:

1. Create a Data Type plugin (that does not extend on PrimitiveInterface) to handle bigger integers.
2. Alter the constraint plugins and replace PrimitiveType with your own constraint plugin that allows for this or does its own logic. Hope that no other module will do this for the same plugin.
3. File a core issue and patch Drupal core so that Typed Data Manager allows to pass options and PrimitiveType plugin uses those options. This is trickier than it seems because those options would need to be a part of the DataDefinition (in a backwards-compatible API change), and then extracted out as options into the constraint.
    * My preferred way would be to get rid of PrimitiveType constraint altogether in Drupal 9 and use specific Symfony constraints.
> 2 votes

---
Tags: 8, entities
---


# Question
Title: what are the different ways to use the variable in many functions within a module?
I want to access a variable changed in one function in another. I tried this with Session and global variables. I need the variable to be persisted across multiple page requests. are there any other ways to do this?

# Answer
variable\_set

> sets a persistent variable.
>
> Case-sensitivity of the variable\_\* functions depends on the database collation used. To avoid problems, always use lower case for persistent variable names.

variable\_get

> Returns a persistent variable.
>
> Case-sensitivity of the variable\_\* functions depends on the database collation used. To avoid problems, always use lower case for persistent variable names.

variable\_del

> Unsets a persistent variable.
>
> Case-sensitivity of the variable\_\* functions depends on the database collation used. To avoid problems, always use lower case for persistent variable names.
> 1 votes

# Answer
Use below functions:

1. variable\_set() : Sets a persistent variable.
2. variable\_get() : Returns a persistent variable.
> 1 votes

---
Tags: 7, forms, sessions
---


# Question
Title: What can break quickedit, and how do I fix it?
We hired someone else to make our theme, and they gave us something with the quickedit not working. What can cause this to break, and how do I fix it?

Here's what my contextual-links ul looks like right now:

`

Quick edit

`

The entitynodeedit-form `li` is empty, as well as the delete `li`. What is supposed to fill them in, and how do I fix it?

# Answer
If there is not an obvious error in php or javascript, see the comment from @mradcliffe, then there are probably some attributes missing, because they were removed in twig templates.

The quickedit links are not delivered in html, they are build in javascript. For this the attributes to identify the involved entities and fields need to be present.

Look especially for the attributes `data-quickedit-entity-id` in node templates and `data-quickedit-field-id` in field templates.

This is the correct way to add attributes in twig:

```
{%
  set classes = [
    'red',
    'green',
  ]
%}
<div{{ attributes.addClass(classes) }}></div>

```

Source: https://www.drupal.org/docs/8/theming-drupal-8/using-attributes-in-templates
> 1 votes

---
Tags: 8, entities
---


# Question
Title: How to change field value from a Views block?
I have a content type named "Tasks" and it has a boolean field simple on/off checkbox. It controls tasks for done or not done.

I have a views block to list all task assigned to me. I want to control this checkbox field from this block like this:

When I click the checkbox beside Task 1 it's value should change. How can I do that?

# Answer
You can use Editable Views Module. The module provides a field to be editable when displaying using views.
> 2 votes

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