# Question
Title: Ajax not working inside hook_field_widget_form()
How to make ajax work inside hook\_field\_widget\_form()

```
    /**
      * Implements hook_field_widget_form().
     */
        function test_field_widget_form($form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
      $form_field['autocomplete'] = array(
        '#type' => 'textfield',
        '#title' => 'Tags',
        '#autocomplete_path' => 'taxonomy/autocomplete' . '/' . $field['field_name'],
        '#size' => $instance['widget']['settings']['size'],
        '#maxlength' => 1024,
        '#element_validate' => array('taxonomy_autocomplete_validate'),
        '#prefix' => '<div id ="subscribers-name">',
        '#suffix' => '</div>',
      );
      if (isset($form_state['values']['autocomplete'])) {
        $form_field['autocomplete']['#value'] = 'new value';
      }

      $form_field['search_tags'] = array(
        '#type' => 'button',
        '#value' => 'Recommend Tags',
        '#ajax' => array(
          'callback' => 'call_ajax_replace_value',
          'wrapper' => 'subscribers-name',
          'method' => 'replace',
        ),
      );
      $element += $form_field;
      return $element;
    }

    function call_ajax_replace_value($form, &$form_state) {
       return $form['field_tags'][LANGUAGE_NONE][0]['autocomplete'];
    }

```

How do i update autocomplete textfield value on AJAX callback?

# Answer
> 2 votes
Just assign the value in callback function.

```
/**
 * Implements hook_field_widget_form().
 */
function test_field_widget_form($form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $form_field['autocomplete'] = array(
    '#type' => 'textfield',
    '#title' => 'Tags',
    '#autocomplete_path' => 'taxonomy/autocomplete' . '/' . $field['field_name'],
    '#size' => $instance['widget']['settings']['size'],
    '#maxlength' => 1024,
    '#element_validate' => array('taxonomy_autocomplete_validate'),
    '#prefix' => '<div id ="subscribers-name">',
    '#suffix' => '</div>',
  );

  $form_field['search_tags'] = array(
    '#type' => 'button',
    '#value' => 'Recommend Tags',
    '#ajax' => array(
      'callback' => 'call_ajax_replace_value',
      'wrapper' => 'subscribers-name',
      'method' => 'replace',
    ),
  );
  $element += $form_field;
  return $element;
}

function call_ajax_replace_value($form, &$form_state) {
  if (isset($form_state['values']['autocomplete'])) {
    $form_field['autocomplete']['#value'] = 'new value';
  }
  return $form['field_tags'][LANGUAGE_NONE][0]['autocomplete'];
}

```

---
Tags: 7, entities, hooks, ajax
---


# Question
Title: How can I get the taxonomy tree by the vocabulary ID?
I want load all the taxonomy terms by their vocabulary ID in Drupal 8. In Drupal 7, I would use the following code.

```
$terms = taxonomy_get_tree($vid);

```

What code should I use in Drupal 8?

# Answer
This code snippet might help you.

```
$terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid,0,NULL,TRUE);
print_r($terms);

```
> 6 votes

# Answer
You can load terms using the entity query,

```
$terms =\Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid);
foreach ($terms as $term) {
     $term_data[] = array(
      "id" => $term->tid,
      "name" => $term->name
     );
    }

```
> 9 votes

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


# Question
Title: fieldset stays open regardless of checkbox
I've an application that fetches data off an Oracle database. Now, I'm adding fieldsets which will be visible based on the value. However, my fieldset stays open regardless of the value. I need to do this in a loop, as I need as many fieldsets as the number of children. So I've used a variable, based on this question. To debug, I set #default\_value to both 0 and 0 based on whether a field has a value. Fieldset stays open on both. What am I missing?

My code (I'm posing only the relevant parts)

```
for ($x=0;$x<count($child);$x++) {
    for ($y=0;$y<$form_state['num_names'];$y++) {
      $form['c'][$x][$y]['info'] =  [
        '#type' => 'fieldset',
        '#title' => ($lang == 'tr')?'Çocukları / Bakmakla Yükümlü Olduğu Kişilerin Durumu':'Status of Children Dependent On or Living With The Taxpayer',
        '#collapsed' => false,
        '#collapsible' => false,
        '#prefix' => '<div id="agi-fieldset-wrapper">',
        '#suffix' => '</div>',
        'info' => [
          '#type' => 'markup',
          '#markup' => ($lang == 'tr')?'Çocuğunuz 18 yaşından büyük ve eğitimine devam ediyorsa; eğitim durumu bilgilerini doldurunuz. Eğitimine devam etmiyor ise, Asgari Geçim İndirimi kapsamında değildir. Çocuğunuz 24 yaşından büyük ise Asgari Geçim İndirimi kapsamında değildir.':'If your other is older than 18 and continuing his/her education, fill out the education status information. If he/she is not continuing his/her education, he/she is not covered in the Minumum Living Allowance. If your other is older than 24, he/she is not covered in the Minumum Living Allowance.',
          '#prefix' => '<span class="agi-warning">',
          '#suffix' => '</span>'
        ],
      ];
      $form['c'][$x][$y]['info']['first_name'] = [
        '#type' => 'textfield',
        '#title' => ($lang == 'tr')?'Ad':'Name',
        '#default_value' => ($form_state['num_names']>1)?'':$child[$x]['CHILD_FIRST_NAME'],
        '#size' => 20,
        '#maxlength' => 20,
      ];
      $form['c'][$x][$y]['info']['middle_name'] = [
        '#type' => 'textfield',
        '#title' => ($lang == 'tr')?'Orta Ad':'Middle Name',
        '#default_value' => ($form_state['num_names']>1)?'':$child[$x]['CHILD_MIDDLE_NAME'],
        '#size' => 20,
        '#maxlength' => 20,
      ];
      $form['c'][$x][$y]['info']['last_name'] = [
        '#type' => 'textfield',
        '#title' => ($lang == 'tr')?'Soyad':'Last Name',
        '#default_value' => $person['LASTNAME'],
        '#size' => 20,
        '#maxlength' => 20,
      ];
      $form['c'][$x][$y]['info']['tckn'] = [
        '#type' => 'textfield',
        '#title' => ($lang == 'tr')?'T.C. Kimlik No':'T.C. Identity Number',
        '#default_value' => ($form_state['num_names']>1)?'':$child[$x]['TC_KIMLIK_NO'],
        '#size' => 20,
        '#maxlength' => 20,
      ];
      $form['c'][$x][$y]['info']['birth_date'] = [
        '#type' => 'date_popup',
        '#title' => ($lang == 'tr')?'Doğum Tarihi':'Date of Birth',
        '#default_value' => ($form_state['num_names']>1)?'':date('Y-m-d',strtotime($child[$x]['BIRTH_DATE'])),
        '#date_format' => 'd/m/Y',
        '#size' => 20,
        '#maxlength' => 20,
      ];
      $form['c'][$x][$y]['info']['father_name'] = [
        '#type' => 'textfield',
        '#title' => ($lang == 'tr')?'Baba Adı':'Father\'s Name',
        '#default_value' => $person['CINSIYET'] == 'M'?$person['FIRSTNAME']:$other['SPOUSE_FIRST_NAME'],
        '#size' => 20,
        '#maxlength' => 20,
      ];
      $form['c'][$x][$y]['info']['mother_name'] = [
        '#type' => 'textfield',
        '#title' => ($lang == 'tr')?'Anne Adı':'Mother\'s Name',
        '#default_value' => $person['CINSIYET'] == 'F'?$person['FIRSTNAME']:$other['SPOUSE_FIRST_NAME'],
        '#size' => 20,
        '#maxlength' => 20,
      ];
      $form['c'][$x][$y]['info']['gender'] = [
        '#type' => 'radios',
        '#title' => ($lang == 'tr')?'Cinsiyeti':'Gender',
        '#options' => ($lang == 'tr')?['F'=>'Kız','M'=>'Erkek']:['F' => 'Girl','M' => 'Boy'],
        '#default_value' => ($form_state['num_names']>1)?'':trim($child[$x]['GENDER']),
      ];
      $form['c'][$x][$y]['info']['x'] = [
        '#type' => 'textfield',
        '#title' => ($lang == 'tr')?'Okulun Adı':'School\'s Name',
        '#default_value' => $x,
      ];
      $form['c'][$x][$y]['info']['studying'] = [
        '#type' => 'checkbox',
        '#title' => ($lang == 'tr')?'Çalışıyor mu?':'Studying?',
        //'#default_value' => (isset($child[$x]['SCHOOL_NAME']))?1:0,
        '#default_value' => 0,
      ];
      $form['c'][$x][$y]['info']['education'] = [
        '#type' => 'fieldset',
        '#title' => ($lang == 'tr')?'Eğitim Bilgileri':'Education Details',
        '#collapsed' => false,
        '#collapsible' => false,
        '#states' => [
          'visible' => [
            ':input[name="c[info]['.$x.'][0][studying]"]' => ['value' => 1],
          ],
        ],
      ];
      $form['c'][$x][$y]['info']['education']['education_type'] = [
        '#type' => 'select',
        '#title' => ($lang == 'tr')?'Eğitim Tipi':'Education Type',
        '#options' => ($lang == 'tr')?['İlköğretim','Lise','Üniversite']:['Primary School'=>'İlköğretim','High School'=>'Lise','University'=>'Üniversite'],
        '#default_value' => ($form_state['num_names']>1)?'':$child[$x]['EDUCATION_TYPE'],
      ];
      $form['c'][$x][$y]['info']['education']['school_name'] = [
        '#type' => 'textfield',
        '#title' => ($lang == 'tr')?'Okulun Adı':'School\'s Name',
        '#default_value' => ($form_state['num_names']>1)?'':$child[$x]['SCHOOL_NAME'],
      ];
      $form['c'][$x][$y]['info']['education']['school_startdate'] = [
        '#type' => 'date_popup',
        '#title' => ($lang == 'tr')?'Okulun Başlangıç Tarihi':'School Start Date',
        '#default_value' => ($form_state['num_names']>1)?'':date('Y-m-d',strtotime($child[$x]['SCHOOL_STARTDATE'])),
        '#date_format' => 'd/m/Y',
        '#date_year_range' => '-50:+0'
      ];
      $form['c'][$x][$y]['info']['education']['school_enddate'] = [
        '#type' => 'date_popup',
        '#title' => ($lang == 'tr')?'Okulun Bitiş Tarihi':'School End Date',
        '#default_value' => ($form_state['num_names']>1)?'':date('Y-m-d',strtotime($child[$x]['SCHOOL_STARTDATE'])),
        '#date_format' => 'd/m/Y',
        '#date_year_range' => '-50:+0'
      ];
      $form['c'][$x][$y]['info']['remove_person'] = [
        '#type' => 'submit',
        '#value' => ($lang == 'tr')?'Kişi Sil':'Remove Person',
        '#submit' => ['suweb_agi_add_more_remove_one'],
        '#attributes' => ['style' => 'float:right', 'data-id' => $x],
        '#ajax' => [
          'callback' => 'suweb_agi_add_more_callback',
          'wrapper' => 'agi-fieldset-wrapper',
        ],
      ];
    }
  }

```

# Answer
> 0 votes
It seems I made a typo. I had to do '`:input[name="c['.$x.'][0][info][studying]"]' => ['checked' => TRUE],` instead.

---
Tags: 7, javascript
---


# Question
Title: Is it possible to apply Authcache caching to elements in page.tpl.php?
In applying Authcache settings to an existing site I have encountered a problem where certain items hard-coded into the theme's `page.tpl.php` need to be personalised for each user. I could do it by moving those components into blocks and/or panels, but they are quite complex and I was wondering if a better approach would be to do it via the Authcache API using the authcache\_usercookie.module example as a starting point.

Here is an example of the code I would like to personalise:

```
<?php if($page['topics_tab']): ?>
<div class="tabs-menu collapse hidden-print" id="topics-collapse-tab">
  <div class="container">
    <div class="row">
      <div class="col-md-8 col-md-push-2">
        <?php print render($page['topics_tab']); ?>
      </div>
    </div>
  </div>
</div>
<?php endif; ?>

```

Is it possible (easy? difficult?) to modify `page.tpl.php` to make Authcache cache this snippet for each user, or should I redo the page using blocks/panels?

# Answer
> 3 votes
I recommend to redo the page with blocks (or panels). The Authcache User Cookie example is rather basic and does not demonstrate how to *deliver* fragments from the custom front controller.

Regrettably there is still not enough documentation on how to roll your own custom fragment renderer. Look at the `api.php` files and read through the numerous submodules to get the picture.

Last but not least, there are some (closed) support requests in the ticket tracker covering this issue, e.g. #2780485.

---
Tags: 7, caching
---


# Question
Title: Couldn't get setErrorByName to apply error class
I have created a form following structure:

```
my_module
    |__
       src
         |__Form
                |__myform.php

```

**I want to get the form\_state** in `some()` function in controller located at:

```
my_module
    |__
       src
         |__Controller
                     |__mycontroller.php

```

So that I can set error on one of my form element (say) - `upload_container`. And I will call function `some()`:

```
static function some() {
$form_state->setErrorByName('upload_container', 'throw error while validating form');
}

```

here shown below as (in myform.php):

```
public function validateForm(array &$form, FormStateInterface $form_state) {
   mycontroller::some();
}

```

In D7, we do the same thing in a separate file example: common.inc

```
static function some() {
    form_set_error('upload_container', 'throw error while validating form');
    }

```

But in D8, How to set error on a form element via function located somewhere in controller file? I can't even get form\_state in any third function which is located at controller.

# Answer
> 5 votes
Setting errors outside of validation isn't supported any more. From a related change record:

> In Drupal 7, form validation functions could use either form\_set\_error() or form\_error() to set errors for an element, and form\_get\_errors() to retrieve the errors for a given form. These were global functions, which just set or retrieved errors from the current form being processed. This worked fine for form validation functions, but could produce unexpected results when called from non-form functions (like a theme function).
>
> In order to ensure that errors are associated with the correct form, you must now call the form error functions on $form\_state.

Even if you got a reference to the form state in your controller, setting errors on it wouldn't do anything as the form wouldn't be validating (see this change record)

The best alternative is probably to use `hook_form_alter` and a validation method to the form which contains your logic.

---
Tags: forms, 8
---


# Question
Title: Skipping form validation with a custom action button
Related to my previous question -- I've got the button added to the form properly (thanks googletorp!), but now I'm having separate validation issues beyond just adding the button.

I have added a "Cancel" button to my custom content entity add/edit form, using hook\_form\_id\_alter. When clicking this button I want it to leave the form completely and return to another admin-side page:

```
function mymodule_form_myform_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
    $form['actions']['cancel'] = array(
        '#type' => 'button',
        '#weight' => 10001,
        '#submit' => array('cancel_submit'),
        '#value' => t('Cancel'),
    );
}
function cancel_submit() {
    $response = new Symfony\Component\HttpFoundation\RedirectResponse(Url::fromUri('internal:/admin/mymodule/list', array('absolute' => true))->toString());
    $response->send();
}

```

I can't get this to work because it's still trying to validate the form.

In my form code, my validation code will only execute if `if ($form_state->getValue('op') == 'Save')` is `true`, and this evaluates to `false` for the Cancel button. However, while this is stopping my custom validation code from running, it isn't stopping built-in validation for fields that I defined as required in the Drupal interface. The `cancel_submit` function doesn't seem to be doing anything, and clicking the Cancel button just loads the form again with a validation error on a required field.

I also tried adding `'#limit_validation_errors' => array(),` to `$form['actions']['cancel']` as recommended here, but this just refreshed the form without showing validation errors instead of redirecting where I want it to go, so I have no idea what this code is actually doing or if this is even applicable for Drupal 8.

I am not sure where to go from here.

# Answer
> 1 votes
To send a redirect response from a form use `setRedirect()` or `setRedirectUrl()`:

```
  function cancel_submit(array &$form, FormStateInterface $form_state) {
    $form_state->setRedirectUrl($url);
  }

```

And add `'#limit_validation_errors' => array()` to the cancel button as already mentioned in the question to prevent validation errors.

---
Tags: forms, 8
---


# Question
Title: Editing the navigation menu template in Drupal 8
I'm getting into Drupal with version 8, and trying to wrap my head around the template system.

I've created a theme with classy as a base theme. I would like to edit the markup for the navigation menu, adding two div's before the `<ul>`. I've copied the `menu.html.twig` file over from `/core/themes/classy/templates/navigation` into `my-theme/templates/navigation`.

I've added to div's right before the ul but they don't appear on the front-end. Is perhaps my template not being loaded? Or what would be the way to do this?

# Answer
Simply needed to clear the cache... case closed!
> 0 votes

---
Tags: theming, navigation
---


title: 7 - Can't update page titles

text:
# Question
Title: 7 - Can't update page titles
I'm currently working on a project on which I'm trying to dynamically shorten the pages titles as following:

`"This is very long text blahblahblah | Site Name"` becomes `"This is very ... | Site Name"` but the rendered page doesn't take this into account.

Here's my problem: I tried several hooks to implement this behaviour, using `hook_menu_alter()`, `hook_preprocess_html()`, `hook_node_preprocess()`, etc. and I followed the indications given to update the pages titles when using these hooks, but it always falls back to using the original long title.

Actually, when I set the arrays accurate keys/values, would it be `$vars['head_title']`, `$vars['title']`, etc. I can var\_dump the array and verify the needed variable is updated, but the title is untouched. Using `drupal_set_title($new_title)` didn't help either.

I'm quite puzzled; would this be because I'm using Custom Field, Metatag, or a specific module? Or would this be because I'm not updating the page at the correct moment during its generation? Drupal is somehow new to me!

Thanks a lot :)

~Steph

# Answer
OK! After going back and forth between var\_dump's, installed modules list and hooks, I discovered that the ONLY hook that will update the page's tags is `hook_metatag_metatags_view_alter(&$output)`, in which something like this needs to be done:

```
$output['title']['#attached']['metatag_set_preprocess_variable'][0][2] = "Custom title";

```

My n00b diagnosis is that this hook is called right after the last Metatag module's function that rebuilds the metatags from scratch, and therefore it's the only one that matters.

Hope this will help others! :)

~Steph
> 0 votes

# Answer
Did you try template\_preprocess\_page? You can modify the $variables\['title'\] value there. Inside your theme's template.php file,

```
function YOUR-THEME_preprocess_page(&$variables) {
  $variables['title'] = YOUR-TRUNCATE-FUNCTION($variables['title']) . ' | ' . $variables['site_name'];
}

```
> 0 votes

---
Tags: theming, hooks
---


# Question
Title: Views exposed Filter by date: month OR year
If i make an exposed filter with a date-field, i can only select date and month together. Not on year or month. How can i make it by year OR month?

# Answer
You should be able to add the same filter twice and set one to a Month granularity and the other to a Year granularity. Then you can rearrange the filters and setup an OR grouping and place the year in that one
> -1 votes

---
Tags: views
---


title: Change From on Admin Order Emails

text:
# Question
Title: Change From on Admin Order Emails
In the Drupal Commerce module is there a way to change the ADMIN ORDER EMAIL sender to the customers email instead of it being from the administrators email?

Thanks!

# Answer
> 0 votes
You can just edit the Rule that controls that admin email and there is a From field for you to enter in the token or data selector for the customers billing email.

---
Tags: commerce, emails
---


# Question
Title: How to Add product type donation into cart programmatically with custom amount(100 or 200 or something)?
I am using commerce\_donate module and I want to add a product (type=donation) into cart programmatically with the amount set as per the user has already selected on some other page. On some custom form submit, I want to add this donation type product into cart in order to process the usual commerce order / checkout.

How can I achieve this ?

Thanks.

# Answer
> 1 votes
No code needed, just watch the video about "Donations with Custom Line Item Types in Drupal Commerce". Some more details about it (= quote from that link):

> This screencast shows how to use a custom line item type to allow your customer to specify a user-defined amount to donate. The line item has a Donation Amount field on it, and we then create a product display node that uses that custom line item. Finally, we use a custom rule to update the "price" of the donation product to the amount the customer has chosen.

# Answer
> 0 votes
In the form submit

```
function custom_form_submit($form,$form_state) {
  $line_item = commerce_product_line_item_new(commerce_product_load($pid));
  commerce_cart_product_add($account->uid, $line_item);
  drupal_goto('cart');
}

```

---
Tags: 7, commerce
---


# Question
Title: Login form on restricted page doesn't accept login credentials
I took over a d7 page from another dev to whom I currently don't have contact. Now I'm digging through the different configurations and settings etc. trying to fix various minor issues. One of the issues is a strange behavior that prevents users from logging in in case they access a restricted node. In detail:

The website I'm working on has a restricted area "intranet" which is only accessible for logged in users. Users that are not logged in trying to access the "intranet pages" see only the login form with the message "You have to be logged in to access this page". So far so good.

But when I (not logged in) then actually enter the correct login credentials on the form that appears on those restricted nodes, I'm just getting the error message "You have to be logged in…" again, together with the login form. Logging in through the regular login page "/login" works perfectly fine.

I hope somebody knows a way around this problem? Any pointers appreciated…

# Answer
A possible explanation for what is happening is that this is implemented via some custom rule, created with the Rules module (at least that's how it "could" have been implemented with a rather basic custom rule).

So if you have the Rules module enabled in your site, you may want to do some Rules **debugging**, as explained in my answer to "How can I display the value of a variable inside a condition?".
> 1 votes

---
Tags: 7, users
---


title: Views Slideshow missing JS files

text:
# Question
Title: Views Slideshow missing JS files
Views Slideshow on Drupal 8 gives me all kinds of 404 errors loading the js files. Missing files:

```
/libraries/jquery.cycle/jquery.cycle.all.js?v=3.0.3
/libraries/jquery.hoverIntent/jquery.hoverIntent.js?v=1.9
/libraries/json2/json2.js?v=2

```

Isn't the module supposed to take care of these dependencies?

Any tips on how to solve it?

# Answer
Only downloading this module does not work. It has **dependencies**. You have not installed the required JS filed which required by module. Those all are dependencies and required by module to work properly. Here is the step wise procedure for installing Views slideshow properly for D8.

In the procedure steps, if you read 4th step it states that,

> 4. Download the latest version of the jQuery Cycle plugin place it inside the jquery.cycle directory. The filename should be: jquery.cycle.all.js

This is just example, follow all the steps properly then only this module will work properly.
> 6 votes

# Answer
The dependencies are listed here with links: https://www.drupal.org/node/2563071. Hoverintent caused difficulties for me if memory serves me right - there is no library folder - I avoided using the setting.

The flexslider module is also a very good module to use for images. Both used here, for example: https://www.aucklandhotel.co.uk/rooms The testimonials use views slideshow.
> 2 votes

---
Tags: 8, views
---


# Question
Title: How can get access to field's data of plugin block in twig template?
how can I get access to fields data (Variables) of custom plugin block in twig template?
this block has been created by a module (Not a custom block type) and has its own twig template.
in below is shown structure of my module directory:

```
my_module
  ├ src
  | └ Plugin
  |    └ Block
  |       └ MyBlock.php
  ├ templates
  |  └ block--my-module.html.twig
  ├ my_module.info.yml
  └ my_module.module

```

MyBlock.php:

```
<?php

namespace Drupal\my_modules\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;

/**
 * @Block(
 *   id = "my_block",
 *   admin_label = @Translation("My Block"),
 *   category = @Translation("My Block")
 * )
 */
class MyBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    // Add a form field to the existing block configuration form.

  $form['block_LinkA_url'] = array(
    '#type' => 'url',
    '#title' => t('Link A:'),
    '#size' => 60,
  );
  $form['block_LinkB_url'] = array(
    '#type' => 'url',
    '#title' => t('Link B:'),
    '#size' => 60,
  );
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    // Save our custom settings when the form is submitted.
    $this->configuration['LinkA_url'] = $form_state->getValue('block_LinkA_url');
    $this->configuration['LinkB_url'] = $form_state->getValue('block_LinkB_url');
  }

}

```

I'm trying to get access to for eg `LinkA_url` Variable in `block--my-module.html.twig` with something like below code:

```
<div>
    {% block content %}
      {{ content.LinkA_url.value }}
    {% endblock %}
</div>

```

But whatsoever I try nothing could not be displayed , I would be happy to hear what the problem is.
Thanks for any help.

# Answer
> 1 votes
you can use markup render arrays like this:

```
 public function build() {
    $build = [];

    $build['LinkA_url'] = ['#markup' => $this->configuration['LinkA_url']];
    $build['LinkB_url'] = ['#markup' => $this->configuration['LinkB_url']];

    return $build;
  }

```

Then in your twig:

```
  <p><a href="{{ content.LinkA_url }}">link 1</a></p>
  <p><a href="{{ content.LinkB_url }}">link 2</a></p>

```

then add hook\_theme in your .module file:

```
/**
 * Implements hook_theme().
 */
function my_module_theme() {
  return array(
    'block__my_module' => array(
      'base hook' => 'block'
    ),
  );
}

```

Otherwise, it won't look in your module's templates folder.

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


# Question
Title: Change node configuration dashboard UI settings
While creating a node content Drupal 8 provides the following settings.

I want the *URL path setting* tab to be open by default.

I want to achieve it through the Drupal 8 backend customization settings (more preferable) or even Javascript/jQuery.

# Answer
You can't do this in the UI, you need code.

You could attach some JS to open it, but it's much easier to create a module with a form\_alter and then you can make the element expanded by default.

https://api.drupal.org/api/drupal/core%21modules%21path%21path.module/function/path\_form\_node\_form\_alter/8.2.x defines the element, you can see that it defaults to open when there is an alias already.
> 1 votes

---
Tags: nodes, 8
---


title: Is hook_node_view() invoked every time?

text:
# Question
Title: Is hook_node_view() invoked every time?
I wrote a custom module that records page views. So each time a user views a node, it creates an entry in a database table. Essentially I wanted my own custom statistics module.

The problem is, it's only called once. I would assume some kind of caching is applied to this function. I have this:

```
function hook_node_view( $node,  $display, $view_mode, $langcode)
{
    $nodeObject = $node['#node'];

    $insert = array(
        'created'    => REQUEST_TIME,
        'nid'        => $nodeObject->id(),
        'uid'        => \Drupal::currentUser()->id(),
        'ip'         => \Drupal::request()->getClientIp(),
        'session_id' => session_id(),
    );

    db_insert('node_view_log')
    ->fields($insert)
    ->execute();

}

```

But it is only called once per node, and not each time the node is viewed. Any idea as to why this is happening? Is there a way to turn of caching for this function only? Or is there perhaps a better place to log page views?

# Answer
Drupal core provides the statistics module which does basically this. It just maintains a counter and not a record per visit, but that's the basic idea.

And it does that with JS that triggers a callback. The reason it does it like that is that *nothing* on the server side can reliably do this in many situations. You might have something like varnish in front of your site, then most requests will not even reach your webserver.
> 1 votes

# Answer
Usually you do this outside of drupal in access.log. Or use the statistics module, which does the logging in javascript with ajax.

If you need to do this in drupal, the only way to catch all requests is with symfony middlewares, before the drupal kernel is loaded:

```
namespace Igorw\Middleware;

use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;

class Logger implements HttpKernelInterface
{
    private $app;
    private $logger;

    public function __construct(HttpKernelInterface $app, LoggerInterface $logger)
    {
        $this->app = $app;
        $this->logger = $logger;
    }

    public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
    {
        $response = $this->app->handle($request, $type, $catch);

        $this->logger->info(sprintf('%s "%s %s %s" %d',
            $request->getHost(),
            $request->getMethod(),
            $request->getRequestUri(),
            $request->server->get('SERVER_PROTOCOL'),
            $response->getStatusCode()));

        return $response;
    }
}

```

Source: https://igor.io/2013/02/02/http-kernel-middlewares.html

You would need to adapt the example for drupal. But I wouldn't do this. See this warning from the same source:

> **A word of warning**
>
> Middlewares are neat, but they are not suited for everything.
>
> For one, infrastructure tasks like logging and caching really belong into your webserver. Re-implementing that in PHP is just going to slow things down. Use Varnish.
>
> The more important point however is that middlewares are coupled to HTTP. They should only be considered an integration point. The specific pieces of functionality they provide should still be moved to separate classes so that they can be properly unit tested and perhaps re-used.
> 0 votes

---
Tags: 8, hooks
---


# Question
Title: How can I change the file system from public to private?
I have been using public file system has the upload destination for file field. I want to change public file system into private file system. I cannot change it it showing below error.

> There is data for this field in the database. The field settings can no longer be changed.

I cannot select the upload destination. How to change the file system for file field in drupal 8

# Answer
I have no idea why the UI prevents from doing that. It's not actually anything in the storage, it's just the default for new files.

What you need to do is edit the config file directly, which is named `field.field.$entity_type_id.$bundle.$field_name`, for example `field.field.node.article.field_image`.

You can do that using drush cedit, or single export and then import it again from the UI, or do a full config export and import it again after changing that file.
> 6 votes

---
Tags: 8, files
---


# Question
Title: How to update the search title and page title depending on facet options
I am using Search Api Views module to list some publications. User can filter them using facets. For example he can look for publications only in Kenya.

I want to update the title of my page (view) depending on this user selection.

Here is a screenshot of my application:

I tried to use Facet API Bonus module, unfortunately I cannot figure out how to use it, I looked everywhere, but cannot find where the configuration interface is located..

# Answer
> 0 votes
The solution is on the Facet API Bonus module's project page:

Integration with Page Title module Now you can set search (views) page titles using Page Title module. Module provides possibility to set tokens 'facetapi\_results' and 'facetapi\_active' groups. So in title we can display number of results on the page or values of active facets. As there can be multiple active facet values please use following pattern to use facetapi\_active tokens: list\<\[facetapi\_active:facet-label\]: \[facetapi\_active:active-value\]\>

This will make coma separated list of active facet labels and their values.

---
Tags: 7, search
---


# Question
Title: An error which appears in Autocomplete taxonomy fields
Did someone ever note this annoying D7 taxonomy error? It jumps out when I seem to "pass" a certain amount of terms or characters. The error is as follows:

> An AJAX HTTP request terminated abnormally. Debugging information follows. Path: http://pancherim.co.il/taxonomy/autocomplete/field\_engines StatusText: ResponseText: ReadyState: 4

# Answer
In my case I get this exact error when using Views. It happens when I try to save changes in a given view and I click too quickly to start another action, while the ajax loader of the previous action hasn't gone away. Basically it's moaning that I should wait for one action to finish before starting another.

In your case, maybe the ajax request isn't fast enough to go and grab an existing match for the taxonomy term(s) you're adding in order to autocomplete it. Do you have enough memory allocated to Drupal in your machine/server?

If you're using the admin overlay, another trail to follow is comment #10 in this issue
> 2 votes

# Answer
This problem started occurring after switching my site to https.

Setting `$base_url` appropriately in `settings.php` fixed it for me. (See also this comment on d.o.)
> 1 votes

---
Tags: 7, taxonomy-terms, entities, ajax
---


title: Taxonomy vocabulary templates

text:
# Question
Title: Taxonomy vocabulary templates
I have three taxonomy vocabularies in my site and one of them using custom template files.. Parent and child term pages and that's ok.. But I don't want to use these template files for two other vocabularies.

I was trying to use TVI module and I get nice views for these vocabulary terms, but I have one huge problem. It messed up my third category page.. It's override template files.

3 vocabularies: Articles, Blogs and Notes..

Articles uses parent-term.tpl files and it's ok, but blogs and notes uses views with TVI module. When I enable TVI module my article category pages messed up..

So what I can do? I love this module, but I don't want automatic override article term pages or nothing.. Only use this module for blog and notes category pages.

# Answer
> 1 votes
To use TVI with individual vocabularies instead of all vocabularies, first make sure it is not globally overriding your vocabulary term pages. Go to Admin \> Configuration \> User Interface \> TVI Settings (admin/config/user-interface/tvi) and uncheck the **Use view override** checkbox.

Then edit each vocabulary to apply the TVI view override individually. Admin \> Structure \> Taxonomy \> edit vocabulary. In your case, you would edit your Article vocabulary and make sure the **Use view override** checkbox is unchecked.

Then edit the two vocabularies you do wish to override with the appropriate view. The fields for selecting the view appear once you check the **Use view override** box:

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


# Question
Title: Identical permission set for panels and panelizer with different results
I have a brand new site install profile I'm working on and with a clean site install, I'm seeing different results of the same permission setting. We have roles "Site Editor" and "Site Admin" and for panels and panelizer, all permissions are set identically. However, Site Admin is seeing all Settings, Context, Layout, Content, and Breadcrumbs. Site Editor is seeing what should be seen: Layout and Content. I'm not sure if there is some other hidden permission that a Site Admin has that the Site Editor does not have that is causing this override.

# Answer
It appears that this is a documented bug in panelizer where a role having "Administer Organic groups permissions" can see all options for panelizer even when those panelizer permissions are not set for that role.
> 0 votes

---
Tags: users, panels
---


# Question
Title: How to let a user switch between blocks that need to be shown?
I have pre-defined blocks A,B and C that are meant to be placed in the sidebar\_first region. What I would like to achieve is: a visitor could select the block that needs to be displayed for the sidebar\_first region when click on a dropdown button containing option A, B and C. This dropdown button should exist somewhere on the same page of these blocks (means the visitor will not do it in the admin pages).

For example, if Option A is selected by default, then only Block A should be shown. If the visitor clicks on Option B, then Block A will be hidden (or removed) and Block B will show up.

The way I could think of is to disable and enable blocks programmatically on clicking the dropdown button, and then refresh the region via ajax, but I have no clue how this can be acheived. I am also open to other approaches.

# Answer
For Drupal 8, there is the Block Tabs module:

> This module provides basic tabs function for Drupal. Deep integration with Drupal8's API, Plugin, Block, Entity and Config API. Provide simple tabs functions, you can control the CSS by your self. Based on jquery.ui.tabs...Tab type using Plugin system, it is very easy to extend.

---

For Drupal 7:

The Quicktabs module might work for you.

> The Quicktabs module allows you to create blocks of tabbed content, specifically views, blocks, nodes and other quicktabs. You can create a block on your site containing multiple tabs with corresponding content.

You would create a Quicktabs instance (Admin \> Structure \> Quicktabs) with the blocks you want to display. You can select a default block, and load the blocks with or without AJAX. With certain render options, you can choose to maintain a history of the user's selection.

The Quicktabs Styles sub-module provides various tab styles (enable the Quicktabs Styles module to use them and visit Admin \> Structure \> Quicktabs \> Styles to preview them). Or you can style the tabs with your own CSS. Examples of some of the included styles:

Once your Quicktabs instance is created, you would add the block to the sidebar region (Admin \> Structure \> Blocks). Example:

If you need the selection element to be a dropdown menu instead of tabs, you might be able to use a custom renderer plugin. From the Quicktabs README.txt:

> Another way to extend Quicktabs is to add a renderer plugin. Quicktabs comes with 3 renderer plugins: jQuery UI Tabs, jQuery UI Accordion, and classic Quicktabs. A renderer plugin is a class that extends the QuickRenderer class and implements the `render()` method, returning a render array that can be passed to renderer service (`\Drupal::service('renderer')`). See any of the existing renderer plugins for examples. Also see Quicktabs' implementation of `hook_quicktabs_renderers()`.
> 0 votes

# Answer
I found Block Accordions to be my solution. It shows blocks at your choice in accordion style. With some simple modification to the JavaScript and CSS file (maybe the twig as well), you can also get blocks to show in tabs or dropdown menu.
> 0 votes

---
Tags: 8, blocks, ajax, theming
---


title: Custom User Login Template Error

text:
# Question
Title: Custom User Login Template Error
I am using Drupal 7 and I have added some code to my template.php file in my theme (which I found on a Drupal tutorial) so I can use a custom template for the user login form. The form works and it is using the custom template but it is generating these errors:

```
Notice: Undefined index: classes_array in template_process() (line 2527 of /includes/theme.inc).
Warning: implode(): Invalid arguments passed in template_process() (line 2527 of /includes/theme.inc).
Notice: Undefined index: attributes_array in template_process() (line 2533 of /includes/theme.inc).
Notice: Undefined index: title_attributes_array in template_process() (line 2534 of /includes/theme.inc).
Notice: Undefined index: content_attributes_array in template_process() (line 2535 of /includes/theme.inc).

```

The code I have in my template.php file is:

```
function cr_theme() {
  $items = array();

  $items['user_login'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'cr') . '/templates',
    'template' => 'user-login',
    'preprocess functions' => array(
       'cr_preprocess_user_login'
    ),
  );
  return $items;
}

function cr_preprocess_user_login(&$vars) {
  $vars['forgot_link'] = l(t('Forgot password?'),'user/password');
}

```

and my user-login.tpl.php file contains:

```
<div class="cr-user-login-form-wrapper">
  <?php print drupal_render_children($form) ?>
<p style="margin-top:12px;"><?php print render($forgot_link); ?></p>
</div>

```

I have been trying to find the cause of the errors which I think is probably something I have not added to my cr\_theme() function but now need some help.

# Answer
> 1 votes
By playing around with the preprocess function I seem to have fixed the errors. I changed the preprocess function to:

```
function cr_preprocess_user_login(&$vars) {
  $vars['content_attributes_array']['class'][] = 'content';
  $vars['title_attributes_array']['class'][] = 'content';
  $vars['attributes_array']['class'][] = 'content';
  $vars['classes_array'] = array('content');
  $vars['forgot_link'] = l(t('Forgot password?'),'user/password');
}

```

I just added in the undefined indexes that were coming up in the errors. I'm really not completely sure what I am doing but it does seem to be removing the errors so far.

It would be great if someone could comment how this is working.

# Answer
> 0 votes
I would try add back in all the default preprocess functions to the array, given that the system is whining about getting undefined indexes.

> preprocess functions: A list of functions used to preprocess this data. Ordinarily this won't be used; it's automatically filled in. By default, for a module this will be filled in as template\_preprocess\_HOOK. For a theme this will be filled in as phptemplate\_preprocess and phptemplate\_preprocess\_HOOK as well as themename\_preprocess and themename\_preprocess\_HOOK.

# Answer
> 0 votes
I had exactly the same issue (guessing I found & used the same tutorial referenced in the question... :)

Based on the info provided by cchen, I simply removed the preprocess array info:

```
   'preprocess functions' => array(
   'cr_preprocess_user_login'
),

```

Cleared cache, and that was it.

Also like you, I don't know enough about this stuff to understand why this worked. All I can do is confirm it did.

---
Tags: 7, theming
---


# Question
Title: What's wrong with my code to overwrite a block template?
I want to render a template from a custom block.

When I check the source with Twig debug enabled, I see the following output.

```
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'block' -->
<!-- FILE NAME SUGGESTIONS:
   * block--mozgraph.html.twig
   * block--moz-graph.html.twig
   * block--wk-elastic.html.twig
   x block.html.twig
-->
<!-- BEGIN OUTPUT from 'themes/custom/wundertheme/templates/block/block.html.twig' -->
<div id="block-mozgraph" class="contextual-region block-wk-elastic block-moz-graph">

      <h2>Moz: Graph</h2>
    <div data-contextual-id="block:block=mozgraph:langcode=en"></div>

```

My module structure is the following.

```
wk_elastic
  Plugin
    Block
     MozGraphBlock.php
  templates
    block--wk-elastic.html.twig
  wk_elastic.info.yml
  wk_elastic.services.yml

```

The code I use to build the block is the following.

```
/**
 * @file
 * Contains \Drupal\wk_elastic\Plugin\Block\MozGraphBlock.
 */

/**
 * Provides a 'MOZ: Graph' block.
 *
 * @Block(
 *   id = "moz_graph",
 *   admin_label = @Translation("Moz: Graph")
 * )
 */
namespace Drupal\wk_elastic\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Elasticsearch;

class MozGraphBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
    $hosts = array(
      '192.168.10.10',
    );

    $client_builder = Elasticsearch\ClientBuilder::create();
    $client_builder->setHosts($hosts);
    $client = $client_builder->build();

    $query = array(
      'query' => array(
        'match_all' => array(),
      ),
    );

    $params = array(
      'index' => 'moz',
      'size' => 10000,
      'body' => $query,
    );

    $response = $client->search($params);

    return array(
      '#markup' => $this->t('Hello, World!'),
      '#theme' => 'block--wk-elastic',
    );
  }
}

```

What is wrong in my code?

# Answer
> 3 votes
You can create a directory called `templates/` in your modules root. Place your template here.

Now let Drupal know you store the template in your module. in `your_module.module` add this function:

```
function YOUR_MODULE_theme($existing, $type, $theme, $path) {
  return array(
    'block__my_module' => array(
      'render element' => 'elements',
      'template' => 'block--my-module',
      'base hook' => 'block'
    )
  );
}

```

Finally be careful about where you place your twig file and what you name it. Create a templates directory in your module directory, and replace the `_` in the theme function name with `-`:
`mymodule-block.html.twig`

Don´t forget to clear the cache.

---

According to answer written by `Nicensin` in this post:
Drupal 8 custom block (module) create twig template file

# Answer
> 1 votes
If you want to override the block template you have to put `block--wk-elastic.html.twig` in your theme. This doesn't work in the module.

Overriding a block template is usually done to add additional containers around the block. Not to theme what is inside the block.

What you are trying to do is to theme your own output. Here is the documentation for this:

Create custom twig templates from custom module

# Answer
> 0 votes
block--wk-elastic is the wrong value for #theme. What you can use is a value that is acceptable as function name.
PHP function names cannot contain hyphens, but they can contain underscores. So, you can use `'#theme' => 'block__wk_elastic'`. It's the template filename that needs to replace the underscores with hyphens. It's correct for the template filename to be block--wk-elastic.html.twig.

---
Tags: 8, blocks
---


# Question
Title: Use custom module template for content type page?
I'm finding lots of examples for theming the node template of a content type, but I can't figure out how to use a template from my module as the page template for a custom node type.

# Answer
> 1 votes
**page.tpl.php** doesn't know, by itself, anything about node types so you'll have to make your module preprocess the page with `hook_preprocess_HOOK()` to add an alternative theme hook suggestion.

```
function MYMODULE_preprocess_page(&$variables) {
   if (isset($variables['node']->type)) {
     $variables['theme_hook_suggestions'][] = 'page__' . $variables['node']->type;
    }
}

```

Once done, you can have your module evoke `hook_theme()` to advertise processing for your custom page node type template and its location. For example:

```
/**
 * Implements hook_theme().
 */
function MYMODULE_theme($existing, $type, $theme, $path) {
  $theme = array();
  $theme['page__mynodetype'] = array(
    'path' => drupal_get_path('module', 'MYMODULE') . '/templates',
    'template' => 'page--mynodetype',
  );
  return $theme;
}

```

When the module is enabled (and theme registry cache cleared), the theme engine will look for **page--mynodetype.tpl.php** within the templates directory of your module.

---
Tags: 7, theming
---


# Question
Title: How to display Block content on menu click?
I want to display a block below a menu item (like a dropdown) when I click on the menu item. Specifically I want to use this way to display the search block when I click on the my search menu item.

Any suggestions about how to do this?

# Answer
Install the Menu Attach Block module

> Menu Attach Block allows you to embed blocks in menu items. You may choose to replace a menu item entirely with a block, or keep the menu link and embed the block after it in the wrapper element.
> 1 votes

---
Tags: 7, navigation, blocks
---


# Question
Title: What is the correct way to pass values from PHP code to javascript in Drupal 8?
I'm not talking about the library. That part is covered fairly extensive. What I want to do is generate the javascript based on PHP. But I can't, for example, do this:

```
$o = '<script> $data = [';
for ($i = 0 ; $i < 10; $i++) {
    $o .= $i.', ';
}
$o .= ']; </script>';

$form['mainText'] = array (
        '#type' => 'markup',
        '#markup' => $o,
    );

return $form;

```

How am I supposed to do this correctly?

And if you are wondering, the reason I am doing this is because I want to generate javascript that is to be used to plot points on a graph.

# Answer
There are a number of ways you could do this. I will you tell you one.

Create a controller class that has a method that is responsible for printing an array of numbers. Hit that endpoint via a javascript get request and do something with the returned data.

So you would create a routing file:

**your\_module.routing.yml**

```
your_module.create_numbers:
 path: '/your_module/{numbers}'
 defaults:
   _controller: '\your_module\Controller\YourCustomControllerClass::createNumberArray'
 requirements:
   _permission: 'access content'

```

**YourCustomControllerClass.php**

```
<?php

namespace 'your_module\Controller';

class YourCustomControllerClass extends ControllerBase {

 /**
 * Return a JSON response based on the number param
 * @param $number integer The number passed into the route.
 * @returns JsonResponse
 */
 public function createNumberArray($number) {
   $numbers = [];
   for ($i = 0 ; $i < $number; $i++) {
     $numbers[] = $i;
   }
   return new JsonResponse($numbers);
 }

}

```

Now you can hit your route from Javascript. The cool thing about this is that your route can create dynamic arrays. If you notice in the routing file the numbers is in {}. That means it is dynamic and is passed in as an argument to the createNumbersArray method. It can then use it to create an array of any length.

**your\_module\_graph.js**

```
var numbers = 10;

// Note numbers can be set to whatever you want.
var jqxhr = $.get( "/your_module/" + numbers, function(data) {
  // data will be a JSON object containing an array of numbers.
  var parsedJson = JSON.parse(data);
  // Now do what you want with parsedJson. Build your graphs etc.
});

```

I haven't tested that but have done similar things a lot lately and I'm quite confident that if not that exact code, the approach in general will suit your needs. As mentioned earlier there is no one way to do this but with Symfony now a core part of Drupal 8 it really is built for doing stuff like this. That is, taking HTTP requests and returning data.

Hope that helps.
> 2 votes

# Answer
You should place the data into any one of php variables and then you could easily pass the php variables to javascript file if you follow this link

After the you can access the data in your javascript library.
> 1 votes

---
Tags: 8, javascript
---


title: Finding correct twig file for page

text:
# Question
Title: Finding correct twig file for page
Consider, I have created two pages using Views for content types Activites and Articles viz. Latest Activities and Latest Articles. I have made a view to display the grid structure for these contents. However, if I modify the `views-view-grid.html.twig`, it affects the both views. What twig file I should create so that I work on separate view for each pages? eg. `something_view1.html.twig` for Activities and `something_view2.html.twig`. Thanks.

# Answer
Views uses a different mechanism to provide variations of twig templates that doesn't work yet with the debug feature from twig.

The logic that builds those suggestions is in `\Drupal\views\ViewExecutable::buildThemeFunctions()`, you can debug that or ad some php statements to dump the $themes variable for a certain hook to get what you need.
> 2 votes

# Answer
if you modify this file *views-view-grid.html.twig* it is not affecting only the both views page it would affect all the views with grid format, Your twig file name should be in proper format,

**Format :** views-view-{format-type}--{view-name}--{id}.html.twig

* format-type = grid, table, unformatted etc..,
* view-name = machine name of the view,
* id = Unique id for the particular views page or block.

**Samples :**

```
views-view-unformatted--portfolio--page.html.twig
views-view-unformatted--portfolio--page1.html.twig
views-view-unformatted--portfolio--block.html.twig
views-view-unformatted--portfolio--block1.html.twig

```
> 1 votes

# Answer
For this the best approach would be to use the template suggestions added by the devel module. Here is a tutorial for that: https://www.drupal.org/docs/8/theming/twig/working-with-twig-templates

Also see the Twig Template naming conventions: https://www.drupal.org/node/2354645
> 0 votes

# Answer
You can edit the services.yml file in sites/default and set debug to true. Doing so will add twig template suggestions in the page source of every page. It will also tell you what template is being used where. Here's an example of what some of the output will look like when you enable debug mode.

```
<!-- END OUTPUT from 'core/themes/stable/templates/misc/status-messages.html.twig' -->
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'block' -->
<!-- FILE NAME SUGGESTIONS:
   * block--custom_theme-content.html.twig
   * block--system-main-block.html.twig
   * block--system.html.twig
   x block.html.twig
-->
<!-- BEGIN OUTPUT from 'core/themes/stable/templates/block/block.html.twig' -->
<div id="block-custom_theme-content">
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'node' -->
<!-- FILE NAME SUGGESTIONS:
   * node--41--full.html.twig
   * node--41.html.twig
   * node--page--full.html.twig
   x node--page.html.twig
   * node--full.html.twig
   * node.html.twig
-->
<!-- BEGIN OUTPUT from 'themes/custom/custom_theme/templates/node--page.html.twig' -->

```

```
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'field' -->
<!-- FILE NAME SUGGESTIONS:
   * field--node--title--page.html.twig
   x field--node--title.html.twig
   * field--node--page.html.twig
   * field--title.html.twig
   * field--string.html.twig
   * field.html.twig
-->
<!-- BEGIN OUTPUT from 'core/themes/stable/templates/field/field--node--title.html.twig' -->
<span property="schema:name" data-quickedit-field-id="node/41/title/en/full">Navigator Newsletter</span>

<!-- END OUTPUT from 'core/themes/stable/templates/field/field--node--title.html.twig' -->
</h2>

```
> 0 votes

# Answer
You can create new view template with some naming conventions. You can check this link. It have useful information.

https://api.drupal.org/api/drupal/core!modules!views!views.theme.inc/group/views\_templates/8.2.x
> 0 votes

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


# Question
Title: How do I add column to existing table on module installation?
I want to add an extra field to the `users` table from a custom module. I am not sure how exactly can it be done. I'm sure it is done in `mymodule.install` file.
Should I use `db_add_field`, or is there any other way? And where should I implement it? `hook_schema` (but the schema is already defined), or `hook_install`?

# Answer
For the sake of giving a (hopefully) complete answer:

* You will need to alter the schema of an existing module, signalling the change to the system. So implement `hook_schema_alter()`.
* You will need to implement `hook_install()` to actually add the field to the database.
* You will need to implement `hook_uninstall()` as well, to remove the extra field when the module is uninstalled. You might need to do extra cleanup at this stage.

An example which alters the Webform module's webform\_submitted\_data table:

```
function MYMODULE_schema_alter(&$schema) {
  $schema['webform_submitted_data']['fields']['extra'] = array(
    'description' => 'Some random extra info.',
    'type' => 'text',
    'size' => 'big',
  );
}

function MYMODULE_install() {
  db_add_field('webform_submitted_data', 'extra', array(
    'description' => 'Some random extra info.',
    'type' => 'text',
    'size' => 'big',
  ));
}

function MYMODULE_uninstall() {
  db_drop_field('webform_submitted_data', 'extra');
}

```
> 5 votes

# Answer
Maybe, I went too early to put this as question, but I've figured it out on my local drupal installation. Just added the following code to `MYMODULE.install` file. Used `hook_install()` and `db_add_field()`.

```
function MYMODULE_install() {
  db_add_field('users', 'encuid', array(
    'type' => 'varchar',
    'length' => 60,
    'not null' => TRUE,
    'default' => 0,
  ));
}

```
> 3 votes

# Answer
I think that best method for not loose data is create a hook\_update in your custom module and make a drush updb.

```

/**
 * Implements hook_update_7084().
 * Add new field in custom table.
 */
function my_module_update_7084() {
  db_add_field('mytable', 'my_new_field', array(
    'type' => 'varchar',
    'length' => 24,
    'not null' => TRUE,
    'default' => 'favorite',
  ));
}

```

Regards... ;) Miguel
> 3 votes

---
Tags: hooks
---


title: Block disable but show in front page

text:
# Question
Title: Block disable but show in front page
I installed a theme that come with different homepage style (homepage-2, homepage-3, etc..)

I configured a new homepage name as homepage-abc, then I set my Default front page to homepage-abc. (Configuration\>Site Information)

When I checked the frontpage, it displays homepage-abc with frontpage layout.

I check these frontpage blocks, the blocks show in frontpage is disable.

Is there other place the theme author wrote a script that configure the combination blocks to define the frontpage?

# Answer
> 0 votes
It's using **context** to make the combination of blocks.

Admin\>Structure\>Context

Under Reactions, choose block and make combination.

---
Tags: 7, blocks
---


title: Fixing Multi-site files path

text:
# Question
Title: Fixing Multi-site files path
I have two separate **fully developed** Drupal 7 sites, which I now want to make as Multi-site.

I did it like in the above pic, and it worked, except all the images on both sites are broken.

Upon inspecting element, the paths are still trying to read from `/sites/default/files` folder instead of `/sites/site1.com/files` and `/sites/site2.com/files` respectively.

How can I fix the paths so it reads from `/sites/site1.com/files` and `/sites/site2.com/files`?

# Answer
> 3 votes
You may be aware of this. Change file path for individual sites at `Configuration/Media/File system`. By default it is set to `sites/default/files`. So your both sites are addressing same path.

So just change the path there accordingly for both sites.

---
Tags: 7, multi-sites
---


# Question
Title: How do I update the documentation on someone elses module?
I want to update the documentation on the Agenda module on Drupal to provide a bit more clarity on how to get it set up.

I have contacted the author and he said great!

How do I do this on drupal.org? I see the code can be changed via git, is the documentation part of the git repo?

# Answer
> 3 votes
Documentation pages on drupal.org are normal Drupal nodes. You need special permissions in order to edit these nodes. There is documentation on drupal.org about how to contribute to documentation.

If the module in question includes a README.txt file, then you can submit a patch to the module maintainers that includes the updates. If the module doesn't have a README.txt file, then submit a patch that adds one.

# Answer
> 1 votes
# Module docu that gets installed with a module

For documentation that gets installed with a module, you need to get something "included" in a module as it is downloaded from drupal.org (such as the .zip or .tar files).

That is why you need something like a patch file, and then you have to wait/hope for it to get committed by a module (co-)maintainer (if you are not one of them).

Examples of this type of docu are the `readme.txt` file, or docu that uses the format provided by the Advanced help module.

# Module docu published as community documentation

The ***community documentation*** pages is something that anybody (logged in to drupal.org) can contribute to without the need for a module (co-)maintainer to "accept" the patch (as is the case for the Advanced help module approach). Obviously, creating such docu is just a matter of create/update of relevant nodes on drupal.org (there are no patches involved).

The only (minor I think) challenge is to locate the best spot for the top (parent level) of the "community pages to be created". Once you figured that out (or you found some already existing docu for the module you want to contribute to), just create a child page of the parent page you want it to be a child of.

For community docu there is 1 (optional, but important) task that needs to be completed by the module (co-)maintainers: add a "link" to the top of the community docu of that module within the "resources" of the project page. That will create the "Read documentation" link on the project page. Only module maintainers have that autorisation. So if you created community docu, or find existing docu which is not mentioned on the project page, then create an issue for getting that fixed.

# Pros and cons

The advantage of community docu, as compared to module docu installed with a module, is that it can be accessed by potential users of the module (compare to "promotion material"?), who have not yet installed the module. As compared to Advanced help which is only accessible for users that already installed the module (compare to admin/user guides for the module). Obvious, both types of docu serve different purposes. So any time docu is created, one should decided about "where it should be included in".

---
Tags: 7, community-official-site
---


# Question
Title: Drupal 8, override template menu in custom module doesn't work, theme template is called instead
I Want create a custom module with custom template for override a menu created from the back office administration. I don't want put my custom template in the theme, I want put this file in my custom module (in custommodule/templates/..)

1) I activated twig debug, I can see what is the suggested template menu name : (menu--main.html.twig)

2) I added in my custom .module file the hook theme :

```
function custommodule_menu_theme($existing, $type, $theme, $path)
{
  return array(
    'menu__main' => array(
      'base hook' => 'menu',
      // 'render element' => 'menu', // I tried this, nothing change
      // 'template' => 'menu--main', // I tried this, nothing change
    ),
  );
}

```

3) From my custommodule, I created a directory 'templates'. In this directory, I add the twig file menu--main.html.twig :

```
<h1> Hello ! <h1>

```

4) I cleared caches (drush cr)

5) I reloaded the page from my browser. I noticed my custom template isn't called. And if I look in the html structure page, I see :

Why this is the template from the global theme called ? and not my templates/main--menu.html.twig ? I don't understand..

**UP**

My new code :

```
function custommodule_theme($existing, $type, $theme, $path) {
  $theme=array();
  $theme['menu__main'] = array(
    'base hook' => 'menu',
    'render element' => 'menu',
      );
  return $theme;
}

```

But my custommodule/templates/menu--main.html.twig is still not called (I cleared caches). My page always uses the themes/boostrap/templates/menu/menu--main.html.twig in the

# Answer
Your module function `custommodule_menu_theme()` is incorrectly named so `hook_theme()` isn't evoked and returning incomplete output; it needs, at least, the `base hook` & `render element` elements entered so that it knows what hook to target and the render array to supply to the template.

```
/**
 * Implements hook_theme().
 */
function custommodule_theme($existing, $type, $theme, $path) {
  $theme = array();
  $theme['menu__main'] = array(
    'base hook' => 'menu',
    'render element' => 'menu',
  );
  return $theme;
}

```
> 4 votes

# Answer
A theme will always win over a module when it comes to theming. So you need to either

* remove template from theme (so your module's template will be used.
* create a custom template suggestion for the main menu that only your module has using `hook_theme_suggestions_HOOK_alter`
* Modify the theme registry to let your module win using `hook_theme_registry_alter`

Of the 3 I would suggest going for option 2, as it is the most flexible one (themes could overwrite the module defined template if needed).

Also remember that the template suggestion can be anything, but your module needs to implement `hook_theme` to register the template.
> 3 votes

---
Tags: theming, 8, navigation
---


title: Prevent drupal_messages in drush

text:
# Question
Title: Prevent drupal_messages in drush
I am creating a bash script to automate some stuff including drush commands. When using drush vget I always get Drupal messages, but I only want the value of the variable. This prevents me from correctly using the drush vget output. I already tried with output formats etc. but I always get the messages. How to prevent the Drupal messages to use the output of drush vget in my shell script?

# Answer
> 0 votes
I just realized they are just printed to the command line and are not contained in the return value itself. So it is actually working. Since I was printing my variable directly for debugging it looked like it contained the messages as well.

---
Tags: drush, status-messages
---


title: How can I print a field on my template?

text:
# Question
Title: How can I print a field on my template?
How can I print a field on my template, not only in node page but in every page.

I use this in my page.tpl but it's wrong:

```
echo $node->field_custom['und'][0]['value'];

```

---

Update

I solved using this code on template.php:

```
function MyTheme_preprocess_page(&$vars) {
  $mynode = node_load(1);
  $vars['field_custom'] = field_get_items('node', $mynode, 'field_custom');
}

```

And this in page.tpl:

```
<?php if (isset($field_custom)) : print $field_custom[0]['value']; endif; ?>

```

# Answer
Try the following code:

```
 <?php
    function THEME_preprocess_page(&$vars) {
      $vars['field_custom'] = '';
      // Get the object and do some other checks based on what you need.
      if (($node = menu_get_object()) && $node->type) {
        // Generate a render array for the node.
        $view = node_view($node);
        // "Create" a new variable for the page.tpl.php.
        // This will expose $VAR_NAME in the page template.
        $vars['field_custom'] = drupal_render($view['field_custom']);
      }
    }
    ?>

```

or you can also use:

```
$vars['field_custom'] = field_get_items('node', $mynode, 'field_custom');

```

Then add this to your page.tpl.php:

```
<?php if (isset($field_custom)) : print $field_custom; endif; ?>

```
> 2 votes

---
Tags: 7, theming
---


# Question
Title: How get empty record on date field with entityQuery?
I am on a custom entity with custom fields and i try to get all empty record on date field :

Field was create with CCK, so the field storage has a table.

```
  $query = \Drupal::entityQuery('test_entity');
        $query->condition('field_date',NULL,'=');
        $ids=$query->execute();

```

This doesn't work for date field.

# Answer
> 27 votes
Since the field is stored in a single table, this is how i get all empty record from my entity where my custom field is empty :

```
 $query = \Drupal::entityQuery('test_entity');
        $query->notExists('field_date');
        $ids=$query->execute();

```

---
Tags: 8, database, entities
---


# Question
Title: Translate hard-coded strings with source language other than english
I building a custom module for a multi-language Drupal 7 site where the default language is not english. Now I want to translate the module. Since my source strings are not in english I cannot use `t()`.

The `i18n` module provides a i18n\_string() function which would seem to do the job but I can't find my strings under `admin/config/regional/translate/translate`? I even implemented `hook_i18n_string_info()` to define my own textgroup, which shows up, but the strings don't!

What am I missing? Or is there a better way to translate strings that are in an other language than english?

# Answer
> 2 votes
We also have a lot of sites with a primary language which is not english.

After several different approaches we opted to write all user exposed string in our modules in english and translate them with the t() function.

We then use a crawler like wget to crawl the whole site (to get all strings into the translation database).

We enable the module Translation template extractor (https://www.drupal.org/project/potx) and export all strings from our module with this module in our languages.

The resulting language-files are edited and translations are added.

This file is then put in a "translations" subfolder in our module file with a \*.po extension.

Uninstall and reinstall the module to activate the translations for your languages.

It may sound like a lot of work, because it is, but this is the only method that actually worked for us.

# Answer
> 0 votes
Go to admin/config/regional/i18n/strings and mark the default language as English, then everything would be working fine with you and you could also add different translation for different language other than English.

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


title: jQuery error in a theme

text:
# Question
Title: jQuery error in a theme
I'm trying to run a jquery script for my Drupal 8 site, but in the error console, I get a `TypeError: $ is not a function`. I know this usually happens when jQuery isn't loaded, but the `jquery.min.js` is loaded fine. Is it loaded too late? Do I perhaps need a wrapper?

In my theme.libraries.yml, I have the following:

```
global-styling:
  version: 1.x
  css:
    theme:
      css/style.css: {}
  js:
    js/script.js: {}
  dependencies:
    - core/jquery

```

My script is simply

```
$('#some-element').on('click', function() {
  // Do something
}

```

I would think this is all I need, or am I overlooking something?

Edit:

I don't think this is a duplicate question since:

1. This is Drupal 8
2. The dependency is defined in the libraries file. I would think this would take care of exactly the problem described in the other question.

# Answer
> 5 votes
In Drupal 8 jQuery is added in the non intrusive way, this means that `$` is not defined in the global space.

What you should do is to use closures (this is a very good idea, as it makes it easy for you to fix potential issues with colliding variables names. `$` is used by other frameworks as well.

This is done by wrapping your code in a anonymous function so you don't need to get variables from the window object but can get them from the function definition. This means that you can easily change the source one place and it will effect all of the script you have written.

```
(function ($, Drupal) {

  // It's best practice to use strict mode, can help avoid some browser issues.
  'use strict';

  // Generally you always want to use behaviors, remember to depend on Drupal js.
  Drupal.behaviors.name = {
    // Called on document ready and when no elements is added to the page.
    attach: function (context, settings) {
      $(".selector", context)...
    }
  }

  // Sometimes you just want to do something when DOM is ready.
  $(document).ready(function() {
    // Stuff to do as soon as the DOM is ready;
  });

})(window.jQuery, window.Drupal);

```

---
Tags: theming, javascript
---


# Question
Title: How to Render a field collection item in a Twig template in tabular view
I have a field collection field having four fields.

I want to display the record in tabular format.

**What I have done.**

Created a field `twig template` file.

Added the code like

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

```

Twig file is working properly. But i need to display the content in tabular form.

Coming like

Required

Available Variables

# Answer
> 1 votes
There is not only one twig template, there are three levels of twig templates in a field collection field:

1) The field template for the field-collection field: `field--field-collection.html.twig`

2) The field-collection template itself: `field-collection-item.html.twig`

3) The field templates for the fields inside of the field collection: `field--field-collection-item--field-field1.html.twig`

When you are in the top level, the fields of the field collection are not built yet and you have no access to the rendered fields.

The best approach is probably to put the table structure in all three levels, in 1) the header and footer, in 2) the row and in 3) the cells.

There is one problem with this approach. In 1) you don't have the labels for the header. If you don't want to hardcode them, you can try to get them from the configuration of the field collection in a preprocess hook.

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


# Question
Title: How would I create conditional fields on install?
I am creating a content type in a module so that it gets created on install.

I got the fields and field instances in separate files and include those files in the .install file. I then call **field\_create\_field()** and **field\_create\_instance()** in the install file.

However, I also have conditional\_fields for this content type. I have the code to create the conditions, what I need to know is what function do I now call from the .install file like I did with the other two field functions?

# Answer
> 0 votes
I ended up getting this to work by creating a feature for the node and copying the array to the module.

To get the 'ID' of the **dependee** and **dependent**, I used *field\_info\_instance*. After I had that I could pass that info to *conditional\_fields\_dependency\_insert*.

I did all this in *hook\_install*.

---
Tags: entities, installation
---


# Question
Title: Taxonomy i18n does not translate term name in a term page
I set option Localized in my Vocabulary "Categories" and translated all the terms in english French and german some of them. The default language is russian. Term page title has russian name: http://tlito.ru/en/categories/debugging in all the languages. I've made html-document title in need language using Page Title module. But the page title rest russian. Please what is this bug?

# Answer
> 2 votes
Some tokens are not provided in the token list, but do the job, for instance:

```
[node:field-myvocabulary:0:i18n-name]/[node:title]

```

`[node:field-myvocabulary:1:i18n-name]/[node:title]` (with the `:1`) is provided by the token list (but doesn't work), `[node:field-myvocabulary:0:i18n-name]/[node:title]` (with the `:0`) is not provided, but doés work.

# Answer
> 1 votes
This is a known issue: Vocabulary Name value doesn't get translated. It dates from 2005 (!), related to D6, status "won't fix". However comment # 2 in that issue states:

> I have used the locale module to translate the name of the vocabulary, and display it with t($vocabulary-\>name). If all modules would display the name this way (e.g. taxonomy\_menu does it), then there is no need for a new database table i18n\_vocabulary.

The **t($vocabulary-\>name)** seems like a possible/partial work around to consider, i.e. from within a (custom) module.

There is a more recent similar issue, i.e. Vocabulary names are not translated. That one is for D7, with status "needs work".

Another potential work around could be to have a separate taxonomy for each language (and with a "name" corresponding to that language). Of course, you'd have to think how to best use these separated taxonomies for each content type (a kind of "solution to the problem, changes the problem) ...

That's probably the best you can get these days. Does this somehow "answer the question"?

---
Tags: i18n-l10n
---


# Question
Title: How to get the taxonomy translated in URLs?
I have a bilingual site with localized taxonomy terms used as categories.

I would like to achieve this:

`http://www.mysite.com/about/pageinenglish`

`http://www.mysite.com/apropos/pageinfrench`

(A propos means about in French)

But I only have:

`http://www.mysite.com/about/pageinfrench`

How can I translate the taxonomy in urls?

**EDIT**

I have pathauto configured with i18n terms (which are only available in TAXONOMY TERM PATHS)

# Answer
> 4 votes
Check this post on drupal.org. I am in the same position as you, but it seems that there aren't any solutions for D7.

---

**Edit**

I'm editing this so it can be visible that this is already possible. As of writing this there wasn't any way of achieving this. As of drupal 8 comming soon there were new modules developed to help translation processes. They are in the core of drupal 8 and available as modules for drupal 7. So the right answer is what @Pere answered in the bellow answer.

# Answer
> 5 votes
I've been able to do that, using Entity Translation instead of Taxonomy translation (part of i18n) for translating taxonomy terms, and using the Title module to replace the **name field** of the taxonomy term and making it translatable.

It works so far.

# Answer
> 3 votes
I'm using this, which supports token. You just need to modify the pathauto rule with the provided token.

https://drupal.org/project/pathauto\_i18n\_taxonomy

# Answer
> 0 votes
If you use the i18n suite of modules, do you have i18n taxonomy enabled?

You can also use the pathauto module to translate your URLs using tokens.

# Answer
> 0 votes
Some tokens are not provided by the token list, but do work. Tokens that have `:1:` in them for instance. Replace the `:1:` with `:0:`, and there you go…

(Source)

---
Tags: taxonomy-terms, i18n-l10n
---


# Question
Title: How to get the field collection field value in twig file?
I have field collection field. I need the field value in field in twig file.

How to print the field value.

Image of the below code.

```
{% for item in items %}
    {{ kint(item.content) }}
{% endfor %}

```

Need the "field\_project\_from" date field value.

# Answer
> 10 votes
Say you have a field collection `field_test` and the field collection has fields say `field_name` and `field_age`, you can access them using the below snippet.

```
{% for details in node.field_test %}
    Name: {{ details.getFieldCollectionItem().field_name.value }}
    Age: {{ details.getFieldCollectionItem().field_age.value }}
{% endfor %}

```

See reference and another reference

I assume `getFieldCollectionItem().field_name.value` is what you are looking for.

# Answer
> 1 votes
You have a good answer to the question, how to get the field collection field values, from @AkiShankar. But you only get the values as they are stored in the database and you have to format the content yourself.

If you want to print the formatted fields use the template of the field collection item.

The theming for field collection items is the same as for nodes. Both are entities. And only if have a template of the entity or of a field inside of the entity you are able to handle the rendering of the field output.

# Answer
> 1 votes
@AkiShankar's answer works, but creates a lot of work for the developer in the twig template. If you work directly off of the entity and do getFieldCollectionItem(), you are forced to validate the data within your twig, and you can't use field formatters, so for something like a google map, pulling the data directly out without a formatter doesn't work so well. If you want to be able to use view modes in your field collection (this works for paragraphs and entity references as well), you can create a custom field formatter for your entity that renders the fields. You can then access the child fields easily in the parent twig:

At /modules/custom/mymodule/src/Plugin/Field/FieldFormatter/EntityComponentFormatter.php

```
namespace Drupal\mymodule\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceEntityFormatter;

/**
 * Plugin implementation of the 'entity reference rendered entity' formatter.
 *
 * @FieldFormatter(
 *   id = "entity_component_formatter",
 *   label = @Translation("Rendered entity variables (available to parent template)"),
 *   description = @Translation("Entity with fields available in parent template."),
 *   field_types = {
 *     "entity_reference"
 *   }
 * )
 */
class EntityComponentFormatter extends EntityReferenceEntityFormatter {

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = parent::viewElements($items, $langcode);

    foreach ($this->getEntitiesToView($items, $langcode) as $delta => $entity) {
      $view_builder = $this->entityTypeManager->getViewBuilder($entity->getEntityTypeId());
      $elements[$delta] = $view_builder->build($elements[$delta]);
    }

    return $elements;
  }

}

```

You can iterate through in your twig like this:

```
{% for key, item in content.field_my_field_collection %}
  {{ item.field_1 }}
  {{ item.field_2 }}
{% endfor %}

```

If you don't want to create a custom formatter, you can do the same thing in hook\_entity\_view:

```
/**
 * Implements hook_entity_view().
 *
 * Gets the output for extra fields.
 */
function mymodule_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {

  if ($entity->getEntityType()->id() == 'node' && $entity->bundle() == 'article' && $view_mode == 'myviewmode' && !empty($build['field_my_field_collection'])) {
    $view_builder = \Drupal::entityTypeManager()
  ->getViewBuilder('field_collection_item');

    $build['field_my_field_collection'] = $view_builder->build($build['field_my_field_collection']);
  }

}

```

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


title: What do I do with the "files"?

text:
# Question
Title: What do I do with the "files"?
I have a pantheon account and a Drupal site installed on it. I wanted to work on my project via localhost, so I have the WAMP server setup, with the Drupal code and downloaded & imported the Drupal Database. However, I also have pantheon "files". What do I do with these files if I already have the code & database? I downloaded them to my computer in a zip file, but not sure what to do with them or where to put them?

# Answer
That should be the contents of your public file system, which will usually be placed at PATH\_TO\_DRUPAL\_ROOT/sites/default/files
> 0 votes

---
Tags: 7
---


# Question
Title: PDO exception error [database].semaphore doesnot exist
I created a website in drupal 7, tested it in my localhost and works good. Now, I want to host the site in our Main server. So, I uploaded the site directory to the server and created a corresponding database for that. Updated the settings.php file with the database name, user and password.

I do hope that the site install process is done. The site is deployed within the server, database created. When I give the address of the site, it shows some PDO exception error.

```
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table '[database].semaphore' doesn't exist: SELECT expire, value FROM {semaphore} WHERE name = :name; Array ( [:name] => variable_init ) in lock_may_be_available() (line 167 of /home/cpath/D-6.12/apache2/htdocs/[htdocs]/includes/lock.inc).

```

I tried re-installing the drupal site, it didn't work.

I even reviewed and tried all the solutions shown in drupal.org, but no way I couldn't resolve the issue.

I appreciate your valuable suggestions.

# Answer
Changing the database engine wont help. What you should understand is what is drupal semaphores. follow this link: https://www.drupal.org/project/flood\_sem if you want to understand what semaphores are. In you case it means this table of semaphores which drupal depends on does not exist due to your misconfiguration during migrate or install. You will have to run drupal install script.

However, semaphores tables dont run on innoDB but myISAM since its a PHP process that calls a third party service for data like drupal theme forms, theme tables ect.

I hope u understand.
> 1 votes

# Answer
I ran into this same error message in moving Drupal 7 from one development site to another development site on my laptop. Upon checking the tables in the Drupal database I found that the full sql dump was not being imported (using Adminer and the "From server" option, adminer.sql).

Look for Drupal 7 database tables that come near the end of the dump alphabetically like: **user\***, **views\***, **webform\***, **workbench\***, **xmlsitemap\*** to see if it all imported.

I then used `drush sql-cli < database.sql` to import the sql dump into the Drupal database after dropping all tables with `drush sql-drop`.
> 1 votes

---
Tags: users, database, configuration
---


# Question
Title: PDOException when creating the table: Base table or view not found
I have Drupal running on MariaDB 5.5.33. When I run update.php (after upgrade to Drupal 7.28 from Drupal 6) I get an error:

> Failed: PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table 'webdb.location\_country' doesn't exist: CREATE TABLE {location\_country} ( `code` CHAR(2) NOT NULL COMMENT 'Primary Key: Two letter ISO Country Code', `name` VARCHAR(255) NOT NULL DEFAULT '' COMMENT 'Full Country Name ', PRIMARY KEY (`code`) ) ENGINE = InnoDB DEFAULT CHARACTER SET utf8 COMMENT 'Country data managed by location.module.'; Array ( ) indb\_create\_table() (line 2720 of /home/web/public\_html/includes/database/database.inc).

When I try to run command

> CREATE TABLE {location\_country} ( `code` CHAR(2) NOT NULL COMMENT 'Primary Key: Two letter ISO Country Code', `name` VARCHAR(255) NOT NULL DEFAULT '' COMMENT 'Full Country Name ', PRIMARY KEY (`code`) ) ENGINE = InnoDB DEFAULT CHARACTER SET utf8 COMMENT 'Country data managed by location.module.';

in phpMyAdmin I get an error

> #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '{location\_country} ( `code` CHAR(2) NOT NULL COMMENT 'Primary Key: Two letter IS' at line 1

But I wasn't able to find out where is the problem.

# Answer
I had the same problem, and in my case the issue was the database tables engine: By default it is InnoDB and (for some reasons I still don't have to understand) Drupal reports this error.

You must change the database engine to MyISAM. First off, you must be sure the tables that are going to be created by Drupal have MyISAM as engine: In `/includes/database/mysql/schema.inc`, look for `createTableSql($name, $table)`, and change InnoDB to MyISAM; then, save it.
Since you have a few tables in your database they must be changed to `MyISAM` as well, so simply export the database as .sql file open it in a text editor and replace `Engine=InnoDB` with `Engine=MyISAM`. Now in the server `phpmyadmin` delete all the tables of the DB and import the new `.sql` file in there. In this way, all your tables and the tables that will be created by Drupal are MyISAM.
> 6 votes

# Answer
Since others answers (including those in no way related to the InnoDB engine) to questions about this PDOException are marked as duplicates and redirects to this one, I guess this is the canonical place for answers about this problem.

I have encountered this several time when uninstalling a module, and the table looked for does not exist on the site (because it has been deleted by accident, because there is a typo in the schema definition in `.install`, or for some other reason).

The simplest way to fix it is to run the database update script (`update.php`) manually.

After your site is brought back to life, you should try to figure out the root cause of the problem and fix it.
> 3 votes

# Answer
You'll need to remove the curly braces around the table name when using as raw SQL.

e.g:

```
CREATE TABLE location_country ( `code` CHAR(2) NOT NULL COMMENT 'Primary Key: Two letter ISO Country Code', `name` VARCHAR(255) NOT NULL DEFAULT '' COMMENT 'Full Country Name ', PRIMARY KEY (`code`) ) ENGINE = InnoDB DEFAULT CHARACTER SET utf8 COMMENT 'Country data managed by location.module.';

```
> 2 votes

# Answer
This is the same error message in ran into moving Drupal 7 from one development site to another development site on my laptop. After checking the tables in the Drupal database I found that the full sql dump was not being imported (using Adminer and the "From server" option, adminer.sql).

Look for Drupal 7 database tables that come near the end of the SQL dump alphabetically like: **user\***, **views\***, **webform\***, **workbench\***, **xmlsitemap\*** to see if it all imported.

I used `drush sql-cli < database.sql` to import the sql dump into the Drupal database after dropping all the database tables with `drush sql-drop`.
> 1 votes

---
Tags: 7, database
---


# Question
Title: View using views content pane not updating on node save
On the home page, I have a view content pane to display the latest 3 blog items. When I save a new blog node I don't see my new item on the home page. The only way to get it to show up is to flush all cache.

Any way to force the cache on the home page alone to clear when the node is saved?

# Answer
> 1 votes
Take a look at the Views content cache module. It allows you to expire the views cache on add/edit/delete of nodes in your view.

Also, be sure to look at the Panels caching on your home page, whether that be in Page Manager, or Panelizer, you can set caching on items in Panels using the Panels Content Cache module.

---
Tags: panels, chaos-tool-suite
---


# Question
Title: Allow module to overwrite multiple templates from module
I have a couple paragraphs set up in my content type. I would like to overwrite the templates from my module (long story - we want to reuse this same set up across multiple sites if I get this to work).

I used the following hook in my module:

```
/**
 * Implements hook_theme_registry_alter().
 */
function my_module_theme_registry_alter(&$theme_registry) {
  $theme_registry['paragraph']['path'] = drupal_get_path('module', 'my_module') . '/templates/paragraph';
  $theme_registry['paragraph']['template'] = 'paragraph';
}

```

In my module's templates/paragraph folder I have the following files:

```
paragraph.html.twig
paragraph--accordion.html.twig
paragraph--carousel.html.twig

```

Here is theme debug:

```
<!-- THEME HOOK: 'paragraph' -->
<!-- FILE NAME SUGGESTIONS:
   * paragraph--accordion--default.html.twig
   * paragraph--accordion.html.twig
   x paragraph--default.html.twig
   * paragraph.html.twig
-->
<!-- BEGIN OUTPUT from 'modules/contrib/bootstrap_paragraphs/templates/paragraph/paragraph.html.twig' -->

```

It seems to work but the problem is that paragraph--accordion and paragraph--carousel always use paragraph.html.twig. How can I have paragraph--accordion and paragraph--carousel use the templates that are in my module. If I place them in my theme's template folder they do render.

# Answer
> 1 votes
If you want to place the twig files in the module's templates folder you have to use `hook_theme()`:

```
function mymodule_theme($existing, $type, $theme, $path) {
  return [
    'paragraph__accordion' => [
      'base hook' => 'paragraph',
    ],
    'paragraph__carousel' => [
      'base hook' => 'paragraph',
    ],
  ];
}

```

# Answer
> 2 votes
I was able to figure it out. I only used hook\_theme\_registry\_alter(). You have the copy $theme\_registry\['paragraphs'\] to all items you want to use paragraphs.

```
/**
 * Implements hook_theme_registry_alter().
 */
function my_module_theme_registry_alter(&$theme_registry) {
  $module_path = drupal_get_path('module', 'my_module');

  // Use the templates in my module's template folder.
  $theme_registry['paragraph__accordion'] = $theme_registry['paragraph'];
  $theme_registry['paragraph__accordion']['path'] = $module_path . '/templates/paragraph';
  $theme_registry['paragraph__accordion']['template'] = 'paragraph--accordion';
  $theme_registry['paragraph__carousel'] = $theme_registry['paragraph__accordion'];
  $theme_registry['paragraph__carousel']['template'] = 'paragraph--carousel';
}

```

---
Tags: theming, 8
---


# Question
Title: How can I automatically add a comment to a node with rules
Can someone help me with this?

I have created a view that gives me a table of certain fields. Now I would like to add a "bulk operation" that lets users add an automatic comment to that specific node.

I have tried to ad a rule (component) and this was the result.

I have activated PHP-filter mode and tried with a component with "Execute custom PHP code".

The code in the component

```
<?php
$comment = new stdClass();
$comment->nid = $node->nid; // nid of a node you want to attach a comment to  (er stond 1)
$comment->cid = 0; // leave it as is
$comment->pid = 0; // parent comment id, 0 if none
$comment->uid = $user->uid; // user's id, who left the comment
//$comment->mail = 'email@example.com'; // user's email
//$comment->name = 'User name'; // If user is authenticated you can omit this field, it will be auto-populated, if the user is anonymous and you want to name him somehow, input his name here
//$comment->thread = '01/'; // OPTIONAL. If you need comments to be threaded you can fill this value. Otherwise omit it.
//$comment->hostname = '127.0.01' // OPTIONAL. You can log poster's ip here
$comment->created = time(); // OPTIONAL. You can set any time you want here. Useful for backdated comments creation.
$comment->is_anonymous = 0; // leave it as is
//$comment->homepage = ''; // you can add homepage URL here
$comment->status = COMMENT_PUBLISHED; // We auto-publish this comment
$comment->language = LANGUAGE_NONE; // The same as for a node
$comment->subject = 'Comment subject';
$comment->comment_body[$comment->language][0]['value'] = 'Afgehaald'; // Everything here is pretty much like with a node
$comment->comment_body[$comment->language][0]['format'] = 'filtered_html';
//$comment->field_custom_field_name[LANGUAGE_NONE][0]['value'] = ‘Some value’; // OPTIONAL. If your comment has a custom field attached it can added as simple as this // preparing a comment for a save
comment_submit($comment); // saving a comment
comment_save($comment);
?>

```

But when I go to the view and execute the operation, he asks for an identifier. But I want him to directly add the comment.

What I mean with the identifier

Can someone help me with this? Or is there another way?

# Answer
If I'm going right with your requirement that you want an add comment link with every node in view result listing of nodes.

You should add a relation first to that node with comment by using node reference/entity reference by using referece from url widget type. Your requirement is same like posting answers node on the specific question node.
> 1 votes

---
Tags: views, rules
---


# Question
Title: Unable to index field in Search API settings in a commerce site
In my product display content type, I created a new image field and am aiming to show that in a view among other things. I after long research found out that I have to enable indexing of a field before I can use it in a view. However, this new field is nowhere to be found on Search API settings. Where else can I look?

Best, mto

# Answer
Do you have "Search Index " display settings enabled (#overlay=admin/structure/types/manage/product\_display/display) If so, then I guess you may have to enable this field in the Manage display of Search Index display.
> 0 votes

# Answer
If you go to admin/config/search/search\_api, then I guess you could see a server of type "Index". Click on the Edit link against that and go to the "fields" tab(admin/config/search/search\_api/index/product\_display/fields). Enable the checkbox against your new field and save. You will have to index the whole content, which you can do by click the view tab and clicking the "Index Now" button. I guess this would do.
> 0 votes

# Answer
In case others are looking for the answer, check out `hook_entity_property_info` Clear cache and then your entity fields should appear.
> 0 votes

---
Tags: commerce, search
---


title: limit information in menu_tree_all_data

text:
# Question
Title: limit information in menu_tree_all_data
If I am using the menu\_tree\_all\_data command, how can that be modified to just get some data, not all? in other words I want to get all of the menu items, but not all of the information, eg updated: "0", load\_functions: null, to\_arg\_functions: null, access\_callback: null, access\_arguments: null, page\_callback: null,

which I don't need. Thanks

# Answer
I wrote a function to get rid of unwanted elements

```
function removeUnwanted($j)
{
    unset($j['link']['load_functions']);
    unset($j['link']['tab_parent']);
    unset($j['link']['router_path']);
    unset($j['link']['page_callback']);
    unset($j['link']['page_arguments']);
    unset($j['link']['title_callback']);
    unset($j['link']['title_arguments']);
    unset($j['link']['theme_callback']);
    unset($j['link']['theme_arguments']);
    unset($j['link']['access_callback']);
    unset($j['link']['access_arguments']);
    unset($j['link']['tab_root']);
    unset($j['link']['to_arg_functions']);
    unset($j['link']['in_active_trail']);
    unset($j['link']['delivery_callback']);
    unset($j['link']['description']);
    unset($j['link']['localized_options']);
    $j['link']['href'] = drupal_get_path_alias($j['link']['href']);

    foreach ($j['below'] as $key => $r) {

       $j['below'][$key]= removeUnwanted($r);

    }
    return $j;
}

```
> 0 votes

---
Tags: 7
---


title: remove second admin menu

text:
# Question
Title: remove second admin menu
This is a pretty basic problem I think but i can't seem to find the solution. I've install the adminimal menu and I would like to remove the second menu on the bottom of this image. I've disable toolbar.

# Answer
> 0 votes
navbar was enable. I disable it and the hambuger menu was gone.
Thanks for your help.

# Answer
> -1 votes
Disable Toolbar module from core section in module list, hope it helps

---
Tags: 7, navigation
---