# Question
Title: Implementing preprocess function for custom template
In Drupal 7, I'm creating thank you page for a custom form and have following in my `mymodule.module`:

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

  $items['mymodule/thank_you/%'] = array(
    'title' => 'My Module Thank You Page',
    'description' => 'my module thank you page',
    'page callback' => 'mymodule_thank_you_page',
    'access arguments' => array( 'access mymodule thank you page' ),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

function mymodule_theme() {
  return array(
    'mymodule_thank_you' => array(
      'variables' => array(
          'form_id' => NULL,
          'content' => NULL,
          'title' => NULL,
      ),
      'template' => 'thank-you',
      'file' => 'mymodule.theme.inc',
      'path' => drupal_get_path('module', 'mymodule') . '/templates',
    ),
  );
}

function mymodule_thank_you_page() {
  drupal_set_title( t( 'Thank You.' ) );

  $variables = array();

  return theme( 'mymodule_thank_you', $variables );
}

```

In `mymodule.theme.inc`, I have:

```
function template_preprocess_mymodule_thank_you( &$variables ) {
  $variables['title'] = 'test';
}

```

The problem I'm facing is that while I can access the thank-you template correctly, it doesn't read any of the variables I define in the preprocess function in the `theme.inc` file. Can anyone advice what I'm doing wrong for this?

# Answer
> 0 votes
I tried your thing on my local server. And its working fine. Just try in your template:

```
<?php
  // Print your defined variable here like this.
  print $title;
?>

```

---
Tags: 7, theming
---


title: Loop through taxonomy parents

text:
# Question
Title: Loop through taxonomy parents
How can i loop through taxonomy in drupal 8. I found this static function but TID is required, how can i loop through all taxonomy without using TID?

```
Drupal::entityManager()->getStorage('taxonomy_term')->loadAllParents($tid);

```

# Answer
> 1 votes
I figured out myself by looping through the table using the database api

```
public function getTaxonomy(){
  $query = db_query("SELECT * FROM taxonomy_term_field_data");

  $taxonomy = [];

  foreach($query as $val){
    $taxonomy[] = array(
        'tid' => $val->tid,
        'vid' => $val->vid,
        'name' => $val->name
      );
  }

  return $taxonomy;

}

```

EDIT : Yet better solution with api instead of using manual SQL query, as per Eyal suggestion.

```
public function getTaxonomy(){

  $terms = \Drupal::database()->select('taxonomy_term_field_data', 'td')->fields('td')->execute()->fetchAll();

  $taxonomy = [];

  foreach($terms as $val){
    $taxonomy[] = array(
        'tid' => $val->tid,
        'vid' => $val->vid,
        'name' => $val->name
      );
  }

  return $taxonomy;

}

```

# Answer
> 2 votes
I think you are using the word "parent" incorrectly.

The terms of a vocabulary can be sorted in a tree. And the parents of a specific term are the ones higher in that hierachy. So, if you want all parents of a term, of course you need so say, which term and give its id as $tid.

However, if you just want all terms of a taxonomy, you can use loadTree($vid) instead. $vid is the id of your vocabulary.

If you want to load all taxonomy terms, ignoring which vocabulary they belong to, then this is the best solution:

```
$terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadMultiple();

```

Then, to access the term data do

```
foreach ($terms as $term) {
    $tid = $term->id();
    $vid = $term->getVocabularyId();
    $name = $term->getName();
}

```

If all you need is the ids of all the terms, this is enough:

```
$tids = \Drupal::entityQuery('taxonomy_term')->execute();

```

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


# Question
Title: How do I add a specific class in a row of a table output depending on a field content?
I use the Views module to list the content of a custom entity, using the *Table* format.
I'd like to add the *myClass* CSS class to each row where a given field is equal to zero.

How can I achieve this?

`Edit` I found out that I could use 'Rewrite results' (Overriding the output of a field with custom text) with twig.
For example:

```
{% if nombreproduits == '0' %}
{{ '99/99/9999' }}
{% else %}
{{ datedistribution }}
{% endif %}

```

How could I use that to add a class to the corresponding row?

# Answer
> 1 votes
Finally, I made it work this way:

In Page\>Format\>Settings, I set 'Row class' to `"myClass"~{{ nombreproduits }}` where nombreproduits is the field to be checked equal to zero.
The result is something like `<tr class="myClass0">` in the corresponding rows (and, of course, myClass1, myClass2, etc. when nombreproduits = 1, 2 etc.).
Then, just have to add `tr.myClass0`to my custom CSS file...

# Answer
> 0 votes
Two options:

1. You alter your view with a View hook and you add to the row class value your own class based on one of the field value
2. You use this solution, and you can check with twig the actual row content and add a class based on that(use devel module and {{ kint(row) }} to understand how to reach the values you want)

---
Tags: views, 8
---


title: What's hook_node_view() alternative?

text:
# Question
Title: What's hook_node_view() alternative?
I am using Drupal 8 Beta 14 and I want to edit the node object in teaser view mode. As `hook_node_view` is removed in Drupal 8. What's the alternative hook or some other way that I can use to edit the node? Is it `hook_ENTITY_TYPE_view` or `hook_entity_view` or some other thing?

Thank you.

# Answer
`hook_node_view()` hasn't really been removed, the way it's invoked has just changed. As you mentioned, it's now handled by `hook_ENTITY_TYPE_view()`.

So you can either use:

```
hook_entity_view()

```

or

```
hook_node_view()

```

The latter would make more sense if you're targeting nodes specifically.
> 22 votes

# Answer
Here is the example for `hook_node_view` in D8 version 8.1.1

```
function mymodule_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {
   $build['body'][0]['#text'] = 'this is a new altered content body ';
}

```
> 10 votes

---
Tags: nodes, hooks, 8
---


# Question
Title: How can I export my translation changes?
I am using Core Module Locale in Drupal 7. What is the easiest way to export just my language changes? How do I find out which strings have been modified?

# Answer
> 1 votes
With locale module, you have an export tab here : admin/config/regional/translate/export. Or through the menu : Configuration \> Regional and language \> Export.

On a fresh installation, active the locale module and go to the import tab : admin/config/regional/translate/import. Or through the menu : Configuration \> Regional and language \> Import.

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


# Question
Title: Error before executing the submit handler
i've made a custom form by including into it a node creation form and the user profile form. But when i try to submit my form i get this error :

```
The website encountered an unexpected error. Please try again later.
TypeError: Argument 1 passed to Drupal\Core\Render\Element::children() must be of the type array, null given, called in /Applications/MAMP/htdocs/fritr/core/modules/file/src/Plugin/Field/FieldWidget/FileWidget.php on line 332 in Drupal\Core\Render\Element::children() (line 71 of core/lib/Drupal/Core/Render/Element.php).

```

I don't know what to do to fix that and it has been a week i work on fix this error... I need your help.

Here is my code :

```
<?php

namespace Drupal\fritr_register_friterie\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Class RegisterFriterieForm.
 *
 * @package Drupal\fritr_register_friterie\Form
 */
class RegisterFriterieForm extends FormBase {

    protected $sub_forms = [];

    /**
     * Le constructeur va initialiser nos deux objets innerForm qui sont :
     *  - User
     *  - Content type : Friterie
     */
    public function __construct() {
        $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
        $this->sub_forms['user'] = \Drupal::service('entity.form_builder')->getForm($user);
        $entity = \Drupal::entityManager()->getStorage('node')->create(array(
            'type' => node_type_load('friterie')->id(),
        ));
        $this->sub_forms['friterie'] = \Drupal::service('entity.form_builder')->getForm($entity);
    }

    /**
     * {@inheritdoc}
     */
    public function getFormId() {
        return 'register_friterie_form';
    }

    /**
     * {@inheritDoc}
     */
    public function buildForm(array $form, FormStateInterface $form_state) {
        // Champ vérification propriétaire
        $form['proprietaire'] = array(
            '#type' => 'radios',
            '#title' => t('Êtes-vous le propriétaire de cette friterie ?'),
            '#options' => array(
                t('Oui'),
                t('Non'),
            ),
            '#attributes' => array(
                'class' => array('clear-panel-field panel-field-inline container-inline'),
            ),
            '#default_value' => 1,
            '#required' => TRUE
        );

        $sub_forms_keys = array_keys($this->sub_forms);
        // INC ALL SUBFORM INTO THE MAIN FORM
        foreach ($this->sub_forms as $key => $sub_form) {
            // REMOVE THE PROCESS CALLBACK
            if (!empty($sub_form['#process'])) {
                unset($sub_form['#process']);
            }

            // ALTER THE SUBFORM
            if ($key == $sub_forms_keys[0]) { // user Alter
                foreach ($sub_form as $field_key => $sub_form_field) { // Pour tous les champs
                    if (substr($field_key, 0, 10) != 'field_user') { // Si ce n'est pas un champ personnalisé user
                        unset($sub_form[$field_key]); // Cacher le champ
                    } else { // Si c'est un champ user
                        // Cacher les label
                        $sub_form[$field_key]['#attributes'] = array(
                            'class' => array('no-label'),
                        );
                        if (array_key_exists('widget', $sub_form[$field_key])) { // Si c'est un champ user et qu'il dispose d'un widget
                            $sub_form_field_widget = $sub_form[$field_key]['widget'][0];
                            $sub_form_field_widget['value']['#states'] = array(
                                'visible' => array(':input[#edit-proprietaire-0]' => array('checked' => true))
                            );
                        }
                    }
                }
                // subform title
                $sub_form['title']['#markup'] = '<p class="form-info">Informations responsable <span>(Obligatoire)</span></p>';
            }
            if ($key == $sub_forms_keys[1]) { // Friterie Alter
                foreach ($sub_form as $field_key => $sub_form_field) { // Pour tous les champs
                    if (substr($field_key, 0, 14) != 'field_friterie') { // Si ce n'est pas un champ personnalisé friterie
                        unset($sub_form[$field_key]); // Cacher le champ
                    } else if (array_key_exists('widget', $sub_form[$field_key])) { // Si c'est un champ friterie et qu'il dispose d'un widget
                    }
                }
                // subform title
                $sub_form['title']['#markup'] = '<p class="form-info">Informations friterie <span>(Obligatoire)</span></p>';

                // Gestion préfix / suffix
                $sub_form['field_friterie_pays']['#prefix'] = '<div class="row">';
                $sub_form['field_friterie_ville']['#suffix'] = '</div>';
                $sub_form['field_friterie_nom']['#prefix'] = '<div>';
                $sub_form['field_friterie_telephone']['#suffix'] = '</div>';
                $sub_form['field_friterie_menu_frites']['#prefix'] = '<p class="form-info">Menus <span>(Facultatif)</span></p><div class="row">';
                $sub_form['field_friterie_menu_autre']['#suffix'] = '</div>';

                // Gestion class
                $sub_form['field_friterie_pays']['#attributes'] = array(
                    'class' => array('col-xs-12 col-sm-4 col-md-4 col-lg-4 no-label'),
                );
                $sub_form['field_friterie_code_postal']['#attributes'] = array(
                    'class' => array('col-xs-12 col-sm-4 col-md-4 col-lg-4 no-label'),
                );
                $sub_form['field_friterie_ville']['#attributes'] = array(
                    'class' => array('col-xs-12 col-sm-4 col-md-4 col-lg-4 no-label'),
                );
                $sub_form['field_friterie_adresse']['#attributes'] = array(
                    'class' => array('no-label'),
                );
                $sub_form['field_friterie_nom']['#attributes'] = array(
                    'class' => array('mid-display no-label'),
                );
                $sub_form['field_friterie_telephone']['#attributes'] = array(
                    'class' => array('mid-display no-label'),
                );
                $sub_form['field_friterie_menu_frites']['#attributes'] = array(
                    'class' => array('col-xs-12 col-sm-6 col-md-6 col-lg-6'),
                );
                $sub_form['field_friterie_menu_viande']['#attributes'] = array(
                    'class' => array('col-xs-12 col-sm-6 col-md-6 col-lg-6'),
                );
                $sub_form['field_friterie_menu_sandwich']['#attributes'] = array(
                    'class' => array('col-xs-12 col-sm-6 col-md-6 col-lg-6'),
                );
                $sub_form['field_friterie_menu_autre']['#attributes'] = array(
                    'class' => array('col-xs-12 col-sm-6 col-md-6 col-lg-6'),
                );
                $sub_form['field_friterie_paiement_type']['#attributes'] = array(
                    'class' => array('clear-panel-field third-display hide-required logo-checkboxes-container'),
                );
                $sub_form['field_friterie_budget']['#attributes'] = array(
                    'class' => array('clear-panel-field panel-field-inline'),
                );
                $sub_form['field_friterie_sur_place']['#attributes'] = array(
                    'class' => array('clear-panel-field panel-field-inline'),
                );
                $sub_form['field_friterie_photos_free']['#attributes'] = array(
                    'class' => array('clear-panel-field'),
                );
                $sub_form['field_friterie_photos_pay_conf']['#attributes'] = array(
                    'class' => array('clear-panel-field'),
                );
                $sub_form['field_friterie_photos_pay']['#attributes'] = array(
                    'class' => array('clear-panel-field'),
                );
                $sub_form['field_friterie_site_web']['#attributes'] = array(
                    'class' => array('inline-label'),
                );
                $sub_form['field_friterie_facebook']['#attributes'] = array(
                    'class' => array('inline-label'),
                );
            }

            // ADD THE SUBFORM INTO THE MAIN FORM
            $form[$key] = [
                '#type' => 'container',
                'form' => $sub_form
            ];
        }

        $form['actions']['#type'] = 'actions';
        $form['actions']['cancel'] = array(
            '#type' => 'submit',
            '#value' => t('Cancel'),
            '#button_type' => 'cancel',
            '#submit' => '::cancelForm',
        );
        $form['actions']['submit'] = array(
            '#type' => 'submit',
            '#value' => t('Submit'),
            '#button_type' => 'primary',
        );

        return $form;
    }

    public function cancelForm(array &$form, FormStateInterface $form_state) {
        drupal_set_message("cancel");
    }

    /**
     * {@inheritdoc}
     */
    public function validateForm(array &$form, FormStateInterface $form_state) {
        drupal_set_message("validate");
    }

    /**
     * {@inheritdoc}
     */
    public function submitForm(array &$form, FormStateInterface $form_state) {
        drupal_set_message("submitted");
    }
}

```

# Answer
I fix my bug by using a strong system of exclusion of non desired fields :

```
<?php

namespace Drupal\fritr_register_friterie\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Class RegisterFriterieForm.
 *
 * @package Drupal\fritr_register_friterie\Form
 */
class RegisterFriterieForm extends FormBase {

    protected $sub_forms = [];

    /**
     * Le constructeur va initialiser nos deux objets innerForm qui sont :
     *  - User
     *  - Content type : Friterie
     */
    public function __construct() {
        $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
        $this->sub_forms['user'] = \Drupal::service('entity.form_builder')->getForm($user);
        $entity = \Drupal::entityManager()->getStorage('node')->create(array(
            'type' => node_type_load('friterie')->id(),
        ));
        $this->sub_forms['friterie'] = \Drupal::service('entity.form_builder')->getForm($entity);
    }

    /**
     * {@inheritdoc}
     */
    public function getFormId() {
        return 'register_friterie_form';
    }

    /**
     * {@inheritDoc}
     */
    public function buildForm(array $form, FormStateInterface $form_state) {
        // Champ vérification propriétaire
        $form['proprietaire'] = array(
            '#type' => 'radios',
            '#title' => t('Êtes-vous le propriétaire de cette friterie ?'),
            '#options' => array(
                t('Oui'),
                t('Non'),
            ),
            '#attributes' => array(
                'class' => array('clear-panel-field panel-field-inline container-inline'),
            ),
            '#default_value' => 1,
            '#required' => TRUE
        );

        $sub_forms_keys = array_keys($this->sub_forms);
        // INC ALL SUBFORM INTO THE MAIN FORM
        foreach ($this->sub_forms as $key => $sub_form) {
            // REMOVE THE PROCESS CALLBACK
            if (!empty($sub_form['#process'])) {
                unset($sub_form['#process']);
            }

            // ALTER THE SUBFORM
            if ($key == $sub_forms_keys[0]) { // user Alter
                $form[$key]['title']['#markup'] = '<p class="form-info">Informations responsable <span>(Obligatoire)</span></p>';
                foreach ($sub_form as $field_key => $sub_form_field) { // Pour tous les champs
                    if (substr($field_key, 0, 10) != 'field_user') { // Si ce n'est pas un champ personnalisé user
                        unset($sub_form[$field_key]); // Cacher le champ
                    } else { // Si c'est un champ user
                        if (array_key_exists('widget', $sub_form[$field_key])) { // Si c'est un champ user et qu'il dispose d'un widget
                            // ON FILTRE LES WIDGETS POUR N'AJOUTER QUE LES CHAMPS DESIRES
                            $sub_form_field_widget = $sub_form[$field_key]['widget'];
                            if (array_key_exists('0', $sub_form_field_widget)) {
                                $sub_form_field_widget = $sub_form_field_widget[0];
                                if (array_key_exists('value', $sub_form_field_widget)) {
                                    // ON AJOUTE LE CHAMP AU FORMULAIRE
                                    $form[$key][$field_key] = $sub_form[$field_key];
                                }
                            }
                        }
                    }
                }
            }
            dsm('10');
            if ($key == $sub_forms_keys[1]) { // Friterie Alter
                foreach ($sub_form as $field_key => $sub_form_field) { // Pour tous les champs
                    if (substr($field_key, 0, 14) != 'field_friterie') { // Si ce n'est pas un champ personnalisé friterie
                        unset($sub_form[$field_key]); // Cacher le champ
                    } else if (array_key_exists('widget', $sub_form[$field_key])) { // Si c'est un champ friterie et qu'il dispose d'un widget
                        // ON FILTRE LES WIDGETS POUR N'AJOUTER QUE LES CHAMPS DESIRES
                        $sub_form_field_widget = $sub_form[$field_key]['widget'];
                        if (array_key_exists('0', $sub_form_field_widget)) {
                            $sub_form_field_widget = $sub_form_field_widget[0];
                            if (array_key_exists('value', $sub_form_field_widget)) {
                                // ON AJOUTE LE CHAMP AU FORMULAIRE
                                $form[$key][$field_key] = $sub_form[$field_key];
                            }
                        }
                    }
                }
//                // subform title
//                $sub_form['title']['#markup'] = '<p class="form-info">Informations friterie <span>(Obligatoire)</span></p>';
//
//                // Gestion préfix / suffix
//                $sub_form['field_friterie_pays']['#prefix'] = '<div class="row">';
//                $sub_form['field_friterie_ville']['#suffix'] = '</div>';
//                $sub_form['field_friterie_nom']['#prefix'] = '<div>';
//                $sub_form['field_friterie_telephone']['#suffix'] = '</div>';
//                $sub_form['field_friterie_menu_frites']['#prefix'] = '<p class="form-info">Menus <span>(Facultatif)</span></p><div class="row">';
//                $sub_form['field_friterie_menu_autre']['#suffix'] = '</div>';
//
//                // Gestion class
//                $sub_form['field_friterie_pays']['#attributes'] = array(
//                    'class' => array('col-xs-12 col-sm-4 col-md-4 col-lg-4 no-label'),
//                );
//                $sub_form['field_friterie_code_postal']['#attributes'] = array(
//                    'class' => array('col-xs-12 col-sm-4 col-md-4 col-lg-4 no-label'),
//                );
//                $sub_form['field_friterie_ville']['#attributes'] = array(
//                    'class' => array('col-xs-12 col-sm-4 col-md-4 col-lg-4 no-label'),
//                );
//                $sub_form['field_friterie_adresse']['#attributes'] = array(
//                    'class' => array('no-label'),
//                );
//                $sub_form['field_friterie_nom']['#attributes'] = array(
//                    'class' => array('mid-display no-label'),
//                );
//                $sub_form['field_friterie_telephone']['#attributes'] = array(
//                    'class' => array('mid-display no-label'),
//                );
//                $sub_form['field_friterie_menu_frites']['#attributes'] = array(
//                    'class' => array('col-xs-12 col-sm-6 col-md-6 col-lg-6'),
//                );
//                $sub_form['field_friterie_menu_viande']['#attributes'] = array(
//                    'class' => array('col-xs-12 col-sm-6 col-md-6 col-lg-6'),
//                );
//                $sub_form['field_friterie_menu_sandwich']['#attributes'] = array(
//                    'class' => array('col-xs-12 col-sm-6 col-md-6 col-lg-6'),
//                );
//                $sub_form['field_friterie_menu_autre']['#attributes'] = array(
//                    'class' => array('col-xs-12 col-sm-6 col-md-6 col-lg-6'),
//                );
//                $sub_form['field_friterie_paiement_type']['#attributes'] = array(
//                    'class' => array('clear-panel-field third-display hide-required logo-checkboxes-container'),
//                );
//                $sub_form['field_friterie_budget']['#attributes'] = array(
//                    'class' => array('clear-panel-field panel-field-inline'),
//                );
//                $sub_form['field_friterie_sur_place']['#attributes'] = array(
//                    'class' => array('clear-panel-field panel-field-inline'),
//                );
//                $sub_form['field_friterie_photos_free']['#attributes'] = array(
//                    'class' => array('clear-panel-field'),
//                );
//                $sub_form['field_friterie_photos_pay_conf']['#attributes'] = array(
//                    'class' => array('clear-panel-field'),
//                );
//                $sub_form['field_friterie_photos_pay']['#attributes'] = array(
//                    'class' => array('clear-panel-field'),
//                );
//                $sub_form['field_friterie_site_web']['#attributes'] = array(
//                    'class' => array('inline-label'),
//                );
//                $sub_form['field_friterie_facebook']['#attributes'] = array(
//                    'class' => array('inline-label'),
//                );
            }
        }

        $form['actions']['#type'] = 'actions';
        $form['actions']['submit'] = array(
            '#type' => 'submit',
            '#value' => t('Submit'),
            '#button_type' => 'primary',
        );

        return $form;
    }

    public function cancelForm(array &$form, FormStateInterface $form_state) {
        drupal_set_message("cancel");
    }

    /**
     * {@inheritdoc}
     */
    public function validateForm(array &$form, FormStateInterface $form_state) {
        drupal_set_message("validate");
    }

    /**
     * {@inheritdoc}
     */
    public function submitForm(array &$form, FormStateInterface $form_state) {
        drupal_set_message("submitted");
    }

}

```
> 0 votes

---
Tags: 8, forms
---


# Question
Title: How to delete children when main entity is deleted?
I am looking for the best way to delete children of my main entity when i delete it.

I have 2 entity type :

> commandes\_entity
>
> commandes\_ligne\_entity ( entity reference to commandes\_entity )

The only way i have found is to create a hook\_entity\_delete :

> Edit : This is how i delete children :

```
function boutique_commandes_entity_delete(Drupal\Core\Entity\EntityInterface $entity)
{
  $query = \Drupal::database()->delete('commandes_lignes_entity');
  $query->condition('commandes_id', $entity->get('id')->value);
  $query->execute();
}

```

Is there another way (maybe better) for delete children ?

# Answer
> 0 votes
You could use rules to react to an entity being deleted, then add a loop over the reference field and use entity delete for the current list item.

Currently on my phone so apoligies for the compact answer.

# Answer
> 0 votes
Alternativly you could overwrite the preDelete() or postDelete() method of your commandes\_entity.

For deleting you can also use the delete() methode provided by the EntityInterface:

```
$commandes_lignes_entity = $entity->commandes_id->entity;
$commandes_lignes_entity->delete();

```

---
Tags: 8, entities
---


# Question
Title: Drupal 7 Views 3.13 Filter groups returns nothing if one group is empty
I have a need to display a block with nodes from different content types. The content types contain different fields, and I would like to filter based on different criteria of each type. I had hoped to use the grouping function of Filter Criteria, but it's not operating as expected.

I am using two content types, Article and Career. Career has a Status field, which indicates if the career posting is open or closed. The filter criteria I have designed looks like:

Each part on it's own works as expected.. so if I remove "OR (Career AND Open)", I get a list of articles that meet the criteria. Conversely, if I remove "(Article AND Published AND Promoted) OR", I get open careers.

Together, I get the result of the 2nd group - I only get open Careers, and no Articles.

If it matters (not sure that it does .. ?), the fields I'm displaying are the node title, and two custom fields that are common to both content types.

Help please?

# Answer
> 0 votes
I think this is a bug/changed behavour in views introduced a long time ago.

A workaround might be to select the Reduce duplicates checkbox from one of the fields in OR group filter - which will transform your query to LEFT JOIN instead of INNER JOIN.

I found the solution here: https://www.drupal.org/node/1766338#comment-6973984

It worked for me in Views 7.x-3.13

---
Tags: 7, views
---


# Question
Title: Why is hook_forms form callback not reached?
In my custom\_apps.module file I'm trying to implement the same form multiple times with different ID's and for that in a loop I call for:

```
drupal_render(drupal_get_form('driver_route_'.$delivery_nid, $args));

```

I have a hook\_forms function:

```
function custom_apps_forms ($form_id, $args) {
    // If driver route form
    if (0 == strpos($form_id, 'driver_route_')) {
        // Call one of the multiple forms
        $forms = array();
        return $forms[$form_id] = array(
            'callback' => 'driver_route_form',
            'callback arguments' => array($form_id, $args),
        );
    }
    return array();
}

```

And the driver\_route\_form() function itself:

```
function driver_route_form(&$form_state, $form_id, $args) {...}

```

However for some reason the driver\_route\_form never gets called and instead I get this notices/warnings:

```
Notice: Undefined index: driver_route_55 in drupal_retrieve_form() (line 806 of /var/www/website/public_html/includes/form.inc).
Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'driver_route_55' not found or invalid function name in drupal_retrieve_form() (line 841 of /var/www/website/public_html/includes/form.inc).

```

It seems as if it's still trying to look for a function with the form\_id not the one defined in my callback. What could be the casue of this? I have made sure the inside of custom\_apps\_form where the form is returned is reached.

# Answer
> 1 votes
Instead of:

```
return $forms[$form_id] = array(
            'callback' => 'driver_route_form',
            'callback arguments' => array($form_id, $args),
        );

```

You should have:

```
$forms[$form_id] = array(
            'callback' => 'driver_route_form',
            'callback arguments' => array($form_id, $args),
        );
return $forms;

```

---
Tags: 7, forms
---


# Question
Title: How do I migrate to a existing taxonomy reference field?
Given a source that has a field with the corresponding ID which outputs the id in the field `special` like the field `nid` gives back a node id.

I want to map it to a taxonomy term that is already existing on the new site and not migrated.

This is the process part of my custom yml file:

```
process:
  nid: nid
  vid: vid
  # there were some more fields here that I left out.
  # hardcode destination node type as publication
  type:
    plugin: default_value
    default_value: publication
  # custom fields
  field_special:
    plugin: static_map
    source: special
    map:
      1: 1
      2: 2
      3: 3

```

I have a `field_special` as taxonomy term reference field in the node I want to migrate to.

How can I map the source field to be used in the destination field which is a taxonomy term reference field?

I'm using Drupal 8.1.2 with migrate\_plus migrate\_tools migrate\_drupal enabled.

# Answer
I've rewritten my yml to use:

```
field_special:
  plugin: iterator
  source: field_special
  process:
    target_id: tid

```

And written a preparerow function in my class to output an array as source property:

```
  /**
   * {@inheritdoc}
   */
  public function prepareRow(Row $row) {
    $nid = $row->getSourceProperty('nid');

    $result = $this->getDatabase()->query(
      'SELECT
        GROUP_CONCAT(field_special_tid) as tids
      FROM
        {field_data_field_special} fs
      WHERE
        fs.entity_id = :nid
      ',
      array(':nid' => $nid)
    );
    foreach ($result as $record) {
      if (!is_null($record->tids)) {
        $row->setSourceProperty('special', explode(',', $record->tids));
      }
    }
    return parent::prepareRow($row);
  }

```

This workaround will do for now, but if you have a better answer please post so I can accept your answer.
> 2 votes

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


# Question
Title: adding twig variable in html.html.twig from module
I'm looking to add a twig variable, which is set in a module, and render it in the html.html.twig template file for my theme.

In my module file I use the hook\_preprocess\_html() function where I render and set the twig variable like so:

```
function insusite_cta_bar_preprocess_html(&$variables) {
 $output = \Drupal::theme()->render('insusite_cta_bar_actions', array('items' => $itemsOutput, 'panels' => $panelOutput));

 $variables['cta_bar'] = $output;
}

```

Then in the html.html.twig template file in my themes folder I simply render the new cta\_bar variable like so:

```
<!DOCTYPE html>
<html{{ html_attributes }}>
 <head>
  <head-placeholder token="{{ placeholder_token|raw }}">
 <title>{{ head_title|safe_join(' | ') }}</title>
  <css-placeholder token="{{ placeholder_token|raw }}">
  <js-placeholder token="{{ placeholder_token|raw }}">
 </head>
 <body{{ attributes }}>
  {{ page_top }}
  {{ page }}
  {{ page_bottom }}
  {{ cta_bar }}
  <js-bottom-placeholder token="{{ placeholder_token|raw }}">
 </body>
</html>

```

This doesn't render anything at all.

However, if I add preprocess\_html() function to my .theme file then it DOES work, problem is we're using drupal as a multi-site system so I'd have to find a way to add this in to every theme's html, is there a way to do this?

# Answer
> 2 votes
Just tested what I can of your code, and this works from a custom module:

```
function examplemodule_preprocess_html(&$variables) {

 $variables['cta_bar'] = ['#markup' => '<h2>Test CTA Bar</h2>'];
}

```

It then can be output in the theme with this template:

/themes/custom/mycustomtheme/templates/layout/html.html.twig

like this:

```
{{ cta_bar }}

```

Of course, you need to register your preprocess function by clearing the cache.

Other than that, I think it must be a problem with your theme function insusite\_cta\_bar\_actions. Can you give us more info on that?

---
Tags: theming, 8
---


# Question
Title: Separate Comment Form DIV from Comments DIV
Is there a way to edit the output of a specific file/line of code that will remove the comment form div from the comments div? Currently, I cannot separate the two to place them next to each other, rather than stacked on one another. It doesn't really work with the theme I'm editing, but cannot find a way to remove it.

Here as a really basic example is how the code looks now:

```
<div id="comments">
    (comments go here)
<div id="comment-form">
    (comment form goes here)
</div></div>

```

But what I need is this:

```
<div id="comments">
    <div id="comment-display">
        (comments go here)</div>
    <div id="comment-form">
        (comment form goes here)</div>
    </div>

```

Thanks ahead of time!

# Answer
> 0 votes
Answered in comments of question, edit the html within the comments.tpl.php file of the theme's templates folder.

---
Tags: comments
---


# Question
Title: How to style and add more fields to the bubble in a gmap field?
I'm using gmap field, it displays only 1 bubble at the same time. If I click on bubble it displays title.

How can I customize it? I need to style it and add more fields to it.

I know how to do it using view (than I can do template for it), however in this case I have only gmap field that display itself.

I want to get this result:

# Answer
> 2 votes
Quote from the Comparison of mapping modules:

> GMap is considered a legacy module.

So maybe you want to have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

> Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
>
> The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (**Google**, **OpenLayers** or **Leaflet**) with any location storage module of your choice, e.g.:

> This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
>
> Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
>
> But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
>
> These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).

Head over to its (impressive) project page for even more information about it. That project page also includes various screenshots.

---
Tags: 7, theming, google-maps
---


# Question
Title: What is the alternative for user_check_password in drupal 8
What is the alternative for user\_check\_password(), How I can verify a plane password with a user account?

# Answer
> 1 votes
```
$uid = \Drupal::service('user.auth')->authenticate('testusername', 'testpassword');

if ($uid) {
// do stuff
 }

```

---
Tags: users, 8
---


title: Change size of the time textbox

text:
# Question
Title: Change size of the time textbox
I want to change the size of the time textbox but I can't find a way to do it.

```
    $form['feld']['start'] = array(
        '#type' => 'date_popup',
        '#title' => 'Start',
        '#size' => 10,
        '#date_formant' => 'd.m.Y',
        '#date_year_range' => '0:+1',
        '#default_value' => date('Y-m-d H:i'),
        '#date_timezone' => 'Europe/Rome',
        '#date_increment' => 15,
        '#required' => TRUE,
);

```

`'#size' => 10` only effects the date textbox.

This is an example.

>

How do I alter also the size of the textbox used for the time?

# Answer
Looking at the source code it appears that both date and time have a #size key. I don't have time to test this, but you might be able to access it from the 'time' element of the field.

```
$form['feld']['start']['time']['#size'] = 10;

```
> 0 votes

---
Tags: datetime
---


# Question
Title: How to add other types of dynamic attributes in the BODY tag?
i have this code to include node-ID attributes to the body tag on the page. My question is ... how can i modify this code to get additional dynamic attributes for the BODY class? **The most important for me are classes for the current vocabulary and taxonomy term**, possibly a panel page.. I has been searching for few days and found only solution for node-ID.

Thank you many times for help.

```
 /**
 * Implements hook_preprocess_html().
 */
function enar_preprocess_html(&$variables) {
  $node = \Drupal::request()->attributes->get('node');
  if ($node) {
    $variables['attributes']['class'][] = 'page-node-' . $node->id();
    if (empty($node->get('body')->value)) {
        $variables['attributes']['class'][] = 'no-padding-main-content';
    }
  }

   // Don't display the site name twice on the front page (and potentially others)
  if (isset($variables['head_title_array']['title']) && isset($variables['head_title_array']['name']) && ($variables['head_title_array']['title'] == $variables['head_title_array']['name'])) {
    $variables['head_title'] = $variables['head_title_array']['name'];
  }

  // Preloader configuration
  $preloader = theme_get_setting('preloader');
  $variables['attributes']['class'][] = $preloader;
  $variables['preloader'] = $preloader;
  // Go to top configuration
  $goto = theme_get_setting('gototop');
  $variables['goto'] = $goto;
}

```

# Answer
I think, i found the right solution below:

```
  if ($node) {
    $variables['attributes']['class'][] = 'page-node';
}

  if ($tid) {
    $variables['attributes']['class'][] = 'term-page';
}

  if ($tid) {
    $variables['attributes']['class'][] = 'term-page-' . $tid->id();
}

```
> 0 votes

---
Tags: theming
---


# Question
Title: Views slideshow won't show "slideshow" display format (commerce kickstart)
My Views slideshow won't give me the option to show my content as a slideshow (when creating block or page).

I have Libraries, Views 3.X, Views Slideshow, Ctools, ... all the requirements and both Views Slideshow and Views Slideshow Cycle is enabled. Still it isn't giving me the option.

Anyone who has any idea why?

# Answer
Fixed this myself.

I am working with commerce kickstart and instead of adding it to the regular modules, added it to the kickstart ones (contrib). Also added the jquery.cycle library there (in libraries though) and then cleared the cache just to be sure.
> 0 votes

---
Tags: 7, commerce, views
---


# Question
Title: Full website translate in multilingual website
we are developing a multilingual site. We have done all setting like installing Internationalizatio,Entity Translation and enabling local and content translation modules etc.

but there are some content which no get translate on choosing particular language, We want to translate my full website content on choosing particular language. How can I perform full transable website in multilingual site?

# Answer
> 1 votes
You need to enable the Content Translation module, and then, in the content type settings, set the content types to translatable. Then, you can translate content. You do that by creating translations though, in the ui, not in the interface translation ui. So, you translate content, not strings.

https://www.drupal.org/documentation/modules/translation

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


title: Execute substring

text:
# Question
Title: Execute substring
I want to execute a "SELECT " and the conditions use the " substring " postgres

e.g:" SELECT * from desembolso\_cnu WHERE substring(fecemi\_pub,1,4)='2016'"

How could I do with the use of **db\_select**

# Answer
> 0 votes
In Drupal 7 there is a `substring_index` method that gets created on install with PostgreSQL. This can be used when using the `where` method on a select query object.

```
$query = db_select('desembolso_cnu');
$query->fields('desembolso_cnu');
$query->where('substring_index(fecemi_pub,1,4) = :year', array(':year' => '2016'));

```

---
Tags: 7, database
---


# Question
Title: How to programmatically load a rendered view exposed filter block
I'm in Drupal 8 trying to load a Views Exposed Filter block based on its ID, similarly to how I would load a content block.

```
$bid = 'exposedformview_nameview_display_name'; // Found on mysite.test/admin/structure/block/manage/exposedformview_nameview_display_name/
$block = \Drupal\block_content\Entity\BlockContent::load($bid);
$render = \Drupal::entityManager()
        ->getViewBuilder('block_content')
        ->view($block);
return $render;

```

Nothing ends up printing out, and in the error log I see this message:

> Recoverable fatal error: Argument 1 passed to Drupal\block\_content\BlockContentViewBuilder::view() must implement interface Drupal\Core\Entity\EntityInterface, null given

Sure enough, when I `debug($block)`, it shows NULL.

I know this works for other blocks created in the content placement area, not sure why it wouldn't also work for views exposed filter blocks. They are both available for placement in the manage blocks page.

EDIT: It seems as though it will not be possible to load the block like this. This method depends on revisions being available for blocks. There is no revision for a views exposed filter block so there must be another way to accomplish this. Perhaps by loading the form directly.

# Answer
The block content entity is not the block entity that is required there.

The actual block entity is a configuration entity. Use the \Drupal\block\Entity\Block::load method to load it.

Try the following:

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

```
> 10 votes

---
Tags: 8, blocks, views
---


# Question
Title: How would I use the Field Validation module with Addressfield to make just city and province/state required?
I have set my addressfeild to be completely optional, however, I want to use the field validation module to ensure they at least fill out city and province/state.

Any thoughts?

# Answer
On your node type field administration page, click the **validate** for your address field. Click the **Required field** validator link. On the validator form you want to:

1. Add your arbitrary **Rule name** (e.g. Address State)
2. In Column, select *locality* or *administrative\_area* for City & State respectively.
3. Add your custom error message in the **Custom error message** field.
4. Click **Add rule** to add the validator.

Once added for both city/state this will force the address field's city/state to be entered.
> 2 votes

---
Tags: entities
---


title: AWS SDK installation problem

text:
# Question
Title: AWS SDK installation problem
I used Drush to install Amazon S3 module. AWS SDK was installed as part of the process. No error was thrown

```
[root@ip-10-128-146-179 zencoder]# drush dl amazons3
Project amazons3 (7.x-1.0-beta7) downloaded to                         [success]
/var/www/html/drupal/sites/all/modules/amazons3.
[root@ip-10-128-146-179 zencoder]# drush en amazons3
The following projects have unmet dependencies:
amazons3 requires awssdk
Would you like to download them? (y/n): y
Project awssdk (7.x-5.4) downloaded to                                 [success]
/var/www/html/drupal/sites/all/modules/awssdk.
Project awssdk contains 2 modules: awssdk_ui, awssdk.
The following extensions will be enabled: amazons3, awssdk
Do you really want to continue? (y/n): y
amazons3 was enabled successfully.                                     [ok]
awssdk was enabled successfully.                                       [ok]

```

Now I see an error in my Drupal admin dashboard:

```
Failed to load the AWSSDK
Please make sure the AWSSDK library is installed in the libraries directory. Use the drush make file for easy installation.

```

What shoud I do?

This is my drush status:

```
Drupal version                  :  7.22
 Site URI                        :  http://default
 Database driver                 :  mysql
 Database hostname               :  localhost
 Database username               :  drupal
 Database name                   :  drupal
 Database                        :  Connected
 Drupal bootstrap                :  Successful
 Drupal user                     :  Anonymous
 Default theme                   :  bartik
 Administration theme            :  seven
 PHP configuration               :  /etc/php.ini
 Drush version                   :  5.9
 Drush configuration             :
 Drupal root                     :  /var/www/html/drupal
 Site path                       :  sites/default
 File directory path             :  sites/default/files
 Temporary file directory path   :  /tmp

```

# Answer
Using the AWS PHP SDK version 1.6.2 instead of the latest solved the problem. `sites/all/libraries/awssdk/sdk.class.php` does not apply for at least version 2.1.1.
> 1 votes

# Answer
Simply download the AWSSDK library and extract it to your sites/all/libraries folder following the format **sites/all/libraries/awssdk/sdk.class.php.**
> 0 votes

# Answer
I ran this command from the Drupal root after installing the awssdk module and it worked:

drush make --no-core sites/all/modules/awssdk/awssdk.make

By worked, I mean it set up the library and fixed the "Failed to load the AWSSDK" error.

The command is referenced here: https://www.drupal.org/node/1353114#comment-5300564
> 0 votes

---
Tags: drush
---


# Question
Title: How to display node when view contains only 1 item?
I have a custom view which displays all nodes of a specific content-type off the main menu. You can click on any of the teaser headers and see the individual node data.

I have been asked to display this drill down-detailed view if there is only 1 item in the main view rather than forcing the user to click through another layer to get to the detail view.

Any thoughts on how to hook into this and which hook to call to override the defined view and jump directly to the node view?

# Answer
My approach is to count the views result first. If the result is only one I will get the node id and load it using `entity_load_single` and render according to whatever you want.

Pseudo code:

```
function hook_name_or_callback() {
  // Get the view.
  $view = views_get_view($view_name);
  // Based on $view you can get the views result.
  if (result_is_one) {
    $node = entity_load_single('node', NID);
    $node_view = node_view($node);
    return drupal_render($node_view);
  }
  else {
    // Just display the view.
  }
}

```

***P.S:*** *Haven't test this code and might not work for you.*

See these:

https://api.drupal.org/api/views/views.module/function/views\_get\_view/7.x-3.x http://www.drupalcontrib.org/api/drupal/contributions!entity!entity.module/function/entity\_load\_single/7
> 0 votes

---
Tags: views, nodes
---


# Question
Title: Edit a form retrieved using FormBuilder::getForm()
I found out how to get a node creation form, but I want to display and modify it (e.g. delete some fields I don't need).

This is my code.

```
public function buildForm(array $form, FormStateInterface $form_state) {
  $entity = \Drupal::entityManager()->getStorage('node')->create(array(
    'type' => node_type_load('friterie')->id(),
  ));
  // OPTIONAL - Set default values for node fields
  // $entity->set('field_machine_name', "value");
  $node_create_form = \Drupal::service('entity.form_builder')->getForm($entity);

  // I can display it with this method, but I don't know how to delete
  // some fields.
  $form['friterie'] = array(
    '#type' => 'markup',
    '#markup' => render($node_create_form),
    '#prefix' => '<div id="friterie-form">',
    '#suffix' => '</div>'
  );
  return $form;
}

```

# Answer
I see two approaches here:

1. You will have to use "hook\_form\_alter", or a more strict form alter (for example: hook\_form\_FORM\_ID\_alter()). You can remove any elements there (calling from you .module file).
2. When you get back your form object ($node\_create\_form) which will be rendered later on, you could make changes on that specific object witt it's public methods! Just dpm, or kint the object (with devel module enabled), and you will able the find the right method to alter the form elements you are about to render.

---

Side note: I **highly discourage** you from using **"\Drupal::..." static service calls**. FormBase classes are implementing the ContainerInjectionInterface, which means, in public static create function you can pass the services you need. Read more on this here!
> 1 votes

# Answer
You may just set the `#access` attribute of your fields in `$node_create_form` to false. I.e. if you have a field called title in your form, just set

```
$node_create_form['title']['#access'] = false;

```

This will hide the field (see From API Ref - access). Additionally, I'd suggest not to use the #markup. Instead of this, wrap your 'friterie' as a #type =\> 'container' and handover the result of getForm as sub-render array.

You don't need the alter-hooks if you're on that api-level. If you don't know what fields you have in your $node\_create\_form you may look at the rendered html (the field classes in there), or use the devel module and `dpm()`.

But `dpm()` (as `dpr()` and `kint()`) may be very chatty and load your browser with tons of data. So you may just `file_put_contents` the `array_keys` of $node\_create\_form to some tmp-file.

Regards, Rainer
> 0 votes

---
Tags: 8, nodes, entities
---


# Question
Title: Remove SKU label from product reference select list
Is there a way to remove/hide the SKU value in the product reference widget (select list)? Because we don't want to show the SKU value to the editors.

# Answer
```
function <mymodule>_field_widget_options_select_form_alter(&$element, &$form_state, $context) {
  if ($context['field']['field_name'] == 'field_<fieldname>') {
    foreach ($element['#options'] as $key => $values) {
      $value = explode(':', $values);
      $element['#options'][$key] = trim($value[1]);
    }
  }
}

```

I hope this helps some one.
> 1 votes

# Answer
In a custom module (or theme) you could implement hook\_field\_widget\_WIDGET\_TYPE\_form\_alter() and alter the labels of the options (i.e., stored in the `$element['#options']` variable). If I'm not mistaken your function would be `mymodule_field_widget_options_select_form_alter(&$element, &$form_state, $context)`, where `mymodule` is your custom module (theme) name. Don't forget to check for which field you're altering the options, you can find this in `$context['field']['field_name']`.

If you don't want to write custom code, you could as an alternative use the Entity reference module in combination with Views. Hereby you can use the output generated by a view as an option list for the (entity) reference field (pointing to your product).
> 1 votes

# Answer
I found Nagarjuna's code useful. I modified it to allow me to accommodate more than one field. In case someone can find it useful, I included the code below:

```
function <mymodule>_field_widget_options_select_form_alter(&$element, &$form_state, $context) {

  $affected_fields = array('field_<field_1>','field_<field_2>','field_<field_3>','field_<field_4>');

  if(in_array($context['field']['field_name'], $affected_fields)) {

    foreach ($element['#options'] as $key => $values) {
      $value = explode(':', $values);

      if(isset($element['#options'][$key])) {
        if(isset($value[1])) {
          $element['#options'][$key] = trim($value[1]);
}
}

```

} } }
> 0 votes

---
Tags: commerce
---


# Question
Title: Drupal 7 hook_form_alter and submitting the form
I added some custom field so that i can get more information when someone registers into the website but i want to alter one field on the form. I created a module which has a hook\_form\_alter function so that i can alter the field\_first\_name of the registration form. here is the code

```
function user_registration_form_alter(&$form, &$form_state, $form_id){
if ($form_id == 'user_register_form'){

    $form['field_first_name'] = array(
        '#type' => 'textfield',
        '#title' => t('First Name'),
        '#description' => t('Enter your first name.'),
        '#maxlength' => 255,
        '#required' => TRUE,
        );

}
if (isset($form['actions']['submit'])) {
 $form['actions']['submit']['#submit'][] ='user_registration_form_submit';
   }

}

```

I also created a the function which handles the form submission.

```
function user_registration_form_submit(&$form, &$form_state)
{

$fe_id = db_insert('field_revision_field_first_name')
    ->fields(array(
        'field_first_name_value' => $form_state['value']['field_first_name'],
        ))->execute();
    drupal_set_message(t('your form entry has been added'));
}

```

My problem is that when i submit the form and i check the user details. i find that the first name details does not exist in the database or when i login as the administrator and click on the 'people' link. i find that all information is are submitted except the first name field which i am trying to alter. I also tried to submit the form without the form submit function but it still doesn't work.

and i get the following error message if i add the form\_submit function

> Notice: Undefined index: value in user\_registration\_form\_submit() (line 37 of /var/www/html/lite/sites/all/modules/user\_regestration/user\_registration.module).
>
> PDOException: SQLSTATE\[HY000\]: General error: 1364 Field 'entity\_id' doesn't have a default value: INSERT INTO {field\_revision\_field\_first\_name} (field\_first\_name\_value) VALUES (:db\_insert\_placeholder\_0); Array ( \[:db\_insert\_placeholder\_0\] =\> ) in user\_registration\_form\_submit() (line 38 of /var/www/html/lite/sites/all/modules/user\_regestration/user\_registration.module).

THIS IS LINE 37 AND 38 OF MY CODE

```
'field_first_name_value' => $form_state['value']['field_first_name'],
))->execute();

```

I am creating the module on localhost first before i push it to the live website

# Answer
There's a typo, change value to **values**

To get the user id use:

```
<?php
global $user;
print $user->uid;
?>

```
> 2 votes

---
Tags: forms
---


# Question
Title: Can you restrict core search to the current language?
I can't figure out how to restrict results to current language other than crude theme preprocess hacks to inspect the language of individual results. I haven't had luck getting contrib search modules that might allow filtering to work.

Can I override the results page with a view and filter there?

# Answer
With a View you will need to do the following:

* Make sure, you have also a second language and content translation is enabled (else you won't able to see the filter we need)
* Add Filter Criteria: "Translation language"
* And then check the following checkbox: "Interface text language selected for page"

Now this view is only going to list elements, which are available on the current language (and their translated version is going to be listed).
> 0 votes

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


# Question
Title: Menu items disable and weight resets on save
Under Admin =\> Structures =\> Menus (select any menu item), I am able to create menus with no problem. However if I click save two things happen, 1. any drag/drop positioning I do is not saved and 2. all the menu items get disabled.

In order to keep them enabled I can edit each individual menu item and check the "enabled" box and manually edit the weight in that area and it works. Otherwise it doesn't work.

Also when ever I clear the drupal cache the "show as expanded" ends up disabling and all my drop down menus disappear.

I stepped through drupal and confirmed those fields are passing blank on save. I'm at a loss what to do and not sure how to fix this.

**Update:** Just to update I discovered one of the issues is my 1st level menu item "Products" was generated from a view. I then manually created drop down items in the menus area and placed them underneath the "Products" link. When ever I would clear the cache the menu would no longer show as expanded and all weights reset to 0 so my menu orders would tank.

Still trying to figure out why the enable/disable check boxes and weights are getting reset on save.

**Final Update:** O.k. I've traced it down to the fact that my server is ignoring the those specific form fields. For example the "enable/disable" check box form name was: name="links\[menu\_plugin\_id:menu\_link\_content:2e7779b8-6668-4b9f-8a04-049cca46c13b\]\[enabled\]

My server would simply ignore this form field name and not pass it to the global \_POST variable. I changed the form name too: name="links\[menu\_plugin\_id:menu\_link\_content:1\]\[enabled\]

and it worked. I thought maybe it was mod\_security so I turned that off but had no effect. At this point I'm not sure what it is in my server settings CENTOS 7.2 x86\_64 standard that's causing these fields to be ignored. I'm not entirely sure what to do right now to work this out.

Hopefully somebody will come across this post someday and it will be of help.

# Answer
> 0 votes
I think I have discovered this issue with Drupal 8 too.

I have the default Menu navigation from the Bootstrap theme, which I am trying to add a menu item for an "About me" page. When I edit the menu item link and save with correct weight and Enabled set, the menu item is ticked. However, when I click the Save button on the main Menu page, the About Me item is disabled. Two items remain ticked - the Home menu and a View.

There seems to be a bug in the global Save button for the Menu. I guess the workaround is to modify menu items by clicking Edit, rather than directly on the menu page.

# Answer
> 0 votes
I had the same problem with Drupal 8.1.2. When I cleared the caches, the order of the main menu links got messed up. I had to edit each link, set the proper weight, and save the link. This way, it worked.

---
Tags: 8
---


# Question
Title: How to give access to the files of node for individual users?
In my website I have these modules enabled: File Entity (fieldable files), Media, Rules, Entity reference.

The default download method is: Private local files served by Drupal.

So when **userA** upload file to node. **userB** can't see it.

Q: How to give access to view file by entityreference(user) for **userB**?

---

**UPD:**

I create subdomain http://filesaccess.onenglar.com/

So you can login:

user: root

pass: root

---

**UPD2:**

Sharing access i think by entity reference field (user)

**But how share access to the files of node for individual users?))**

# Answer
To do the access checking yourself you'll need to write a `hook_file_download()`.

In broad strokes you'll need to get the actual file object (see this question for help with that), find the references with `file_get_file_references()`, and finally load them to check each reference (probably just one but it would be unwise to assume that's true) to see if the current user is given access to the file.
> 4 votes

# Answer
> It appears to me that he just wants to show/print the picture only if the logged in user is the same as the entity reference user or is the node author.

Sorry I don't have time to write an explicit answer. Consider this an implicit or bare bones answer.

All you gotta do is create a template file for your content type.

Then in your template file with PHP use `Global User` to grab the current logged in User ID. Also, you will need to grab the User ID of the entity reference field, perhaps the raw value will have it? Use Devel to check that.

Almost forgot, you will also need the node author uid.

Once you have these 3 values, you do a simple check

```
if ($global_uid == $entity_reference_uid || $global_uid == $author_uid) {

print render($content['field_image']);

}

```

If anyone wants to write a more explicit version of my answer, feel free.
> 1 votes

# Answer
Here is some pseudocode (inasmuch as you'll need to do the work to get the CURRENT\_USER\_ID and ENTITY\_REFERENCE\_ID) that should work in a custom module:

```
function MYMODULE_file_download($uri) {
  # get CURRENT_USER_UID and ENTITY_REFERENCE_UID here
  if (!$CURRENT_USER_UID === $ENTITY_REFERENCE_UID) {
      return -1;
  }
  else {
      $info = image_get_info($uri);
      return array('Content-Type' => $info['mime_type']);
  }
}

```
> 0 votes

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


# Question
Title: Content enity type: edit form not working
I have created a content entity form. Below is the code attached:

```
/**
 * Defines the mymodule entity.
 *
 * @ingroup mymodule
 *
 * @ContentEntityType(
 *   id = "mymodule",
 *   label = @Translation("mymodule"),
 *   handlers = {
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
 *     "list_builder" = "Drupal\mymodule\Entity\Controller\mymoduleListBuilder",
 *     "views_data" = "Drupal\views\EntityViewsData",
 *     "form" = {
 *       "default" = "Drupal\mymodule\Form\mymoduleForm",
 *       "edit" = "Drupal\mymodule\Form\mymoduleForm",
 *       "delete" = "Drupal\mymodule\Form\mymoduleDeleteForm",
 *       },
 *      "access" = "Drupal\mymodule\RssFeedsAccessControlHandler",
 *
 *   },
 *   links = {
 *     "canonical" = "/admin/config/search/mymodule/edit/{mymodule}",
 *     "edit-form" = "/admin/config/search/mymodule/edit/{mymodule}",
 *     "delete-form" = "/admin/config/search/mymodule/delete/{mymodule}",
 *
 *   },
 *   base_table = "mymodule",
 *   admin_permission = "administer mymodule entity",
 *   fieldable = TRUE,
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "name",
 *     "uuid" = "uuid",
 *   },
 * )
 */

```

Here is my class with database table and form fields:

```
class Myclass extends ContentEntityBase  implements  ContentEntityInterface  {
    public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
        $options_first = node_type_get_names();
        $fields['id'] = BaseFieldDefinition::create('integer')
                ->setLabel(t('ID'))
                ->setDescription(t('The ID of the contact entity'))
                ->setReadOnly(TRUE);
        $fields['uuid'] = BaseFieldDefinition::create('uuid')
                ->setLabel(t('UUID'))
                ->setDescription(t('The UUID of the contact entity'))
                ->setReadOnly(TRUE);
        $fields['name'] = BaseFieldDefinition::create('string')
                ->setLabel(t('Configuration Name'))
                ->setDescription(t('The Configuration Name of the rss entity.'))
                ->setSettings(array(
                  'default_value' => '',
                  'max_length' => 255,
                  'text_processing' => 0,
                ))
                ->setDisplayOptions('view', array(
                  'label' => 'above',
                  'type' => 'string',
                  'weight' => -5,
                ))
                ->setDisplayOptions('form', array(
                  'type' => 'string',
                  'weight' => -5,
                ))
                ->setDisplayConfigurable('form', TRUE)
                ->setDisplayConfigurable('view', TRUE);
        $fields['content_type'] = BaseFieldDefinition::create('list_string')
                ->setLabel(t('Content Type'))
                ->setDescription(t('The Content Type of the Rss entity.'))
                ->setSettings(array(
                  'allowed_values' => $options_first,
                ))
                ->setDisplayOptions('view', array(
                  'label' => 'above',
                  'type' => 'string',
                  'weight' => -4,
                ))
                ->setDisplayOptions('form', array(
                  'type' => 'options_select',
                  'weight' => -4,
                ))
                ->setDisplayConfigurable('form', TRUE)
                ->setDisplayConfigurable('view', TRUE);
        $fields['langcode'] = BaseFieldDefinition::create('language')
                ->setLabel(t('Language code'))
                ->setDescription(t('The language code of Rss entity.'));
        $fields['created'] = BaseFieldDefinition::create('created')
                ->setLabel(t('Created'))
                ->setDescription(t('The time that the entity was created.'));
        $fields['changed'] = BaseFieldDefinition::create('changed')
                ->setLabel(t('Changed'))
                ->setDescription(t('The time that the entity was last edited.'));

        return $fields;

    }
}

```

**My Routing.yml links are:**

```
mymodule.add:
  path: '/admin/config/search/mymodule/add'
  defaults:
    _entity_form: 'mymodule.default'
    _title: 'Add form'
  requirements:
    _entity_create_access: 'mymodule'

entity.mymodule.edit_form:
  path: '/admin/config/search/mymodule/edit/{mymodule}'
  defaults:
    _entity_form: 'mymodule.edit'
    _title: 'Edit form'
  requirements:
    _entity_access: 'mymodule.edit'

```

**Form gets created and values are submitted in database, which is fine. But when I click on edit link, form doesn't get open, instead only content type selected value get shown. Why I'm not able to edit/update form? Any suggestion where and what is being missed in creating content type entity form?**

# Answer
> -1 votes
The links should be different for canonical and edit:

```
 *     "canonical" = "/admin/config/search/mymodule/edit/{mymodule}",
 *     "edit-form" = "/admin/config/search/mymodule/edit/{mymodule}",

```

eg

```
 *     "canonical" = "/admin/config/search/mymodule/{mymodule}",
 *     "edit-form" = "/admin/config/search/mymodule/edit/{mymodule}",

```

---
Tags: 8, entities
---


# Question
Title: Display solr result by specific field order
I am implemented the Apache Solr with Search API module. Everything working fine but now requirement is to show solr result by specific field order.

I have total 4 fields in content type

1. Field 1
2. Field 2
3. Field 3
4. Field 4

Now solr show result random order from this field i.e any field coming on top.

**I need to show result by field order.<br>i.e display all result on top by matching "field 1" then "field 2" and so on.. Anyone can help me to achieve this result...**

# Answer
I am resolve my problem by using edismax of solr.

Ref Link: https://cwiki.apache.org/confluence/display/solr/The+DisMax+Query+Parser

http://localhost:8983/solr/collection1/select?q=search\_word&wt=json&indent=true **&defType=edismax&qf=field\_1^20+field\_2^19+field\_3^18+field\_4^17&pf=field\_1+field\_2+field\_3+field\_4**
> 0 votes

---
Tags: search
---


title: HTML displayed in product title

text:
# Question
Title: HTML displayed in product title
I have a Drupal commerce webshop with two main products having multiple variations.

Those variations have labels containing HTML tags.

My problem is when I add to cart HTML tags are displayed in text... Does someone know how to solve this ?

Thank you

# Answer
> 0 votes
For this you have to select text format to full html check in `admin/commerce/products/types/product/display` or in `admin/commerce/products/types/product/` your field name and check for format option.

---
Tags: commerce
---


# Question
Title: Session Timeout after certain period of inactivity
How can I logout users after a certain period of inactivity (say 20 minutes)?

# Answer
> 3 votes
You are looking for Automated Logout module.

> This module provides a site administrator the ability to log users out after a specified time of inactivity. It is highly customizable and includes "site policies" by role to enforce logout.

Features

* Different timeouts based on role
* Disabling of timeouts based on role
* Permission for users to set their own timeout
* Includes some JS mechanisms to keep uses logged in even if multiple tabs are open or if the user is working on a form for a long period of time.
* Includes developer hooks to allow users to remain logged in depending on your own project specific requirements
* Optional integration with Javascript Timer

(or) take a look at Session Limit

(or)

**Ejector Seat**

> A Drupal module to immediately log out (eject) a user whose session has ended

# Answer
> 1 votes
You can change the `session.cookie_lifetime` time (in seconds) from the session is created to the cookie expires (when the browser is expected to discard the cookie).

There is a module Session expire which enhances that functionality.

Related:

---
Tags: 7, users, sessions
---


# Question
Title: How to add separator field to user profile
I'm creating new fields for the user profile.

I have this:

* Company Name
* City
* Logo
* etc

**I need to add a new field or some kind of header/separator with this "CONTACT INFORMATION"**

and then a bunch of other fields

* Name
* Email
* Address

Basically I need to divide the fields by sections, I just need it to be visible, no programming purposes.

# Answer
Option 1: Add *one* contact field that has cardinality 3 and stores the name, email and address.

Option 2: Alter the form and put name, email and address in one *fieldset*.
> 0 votes

---
Tags: users
---


# Question
Title: How do I customize the date-submit part in comment section?
I am formatting the Date/Submit part of the comment. By default when we post any comment, it comes in the format of, `Submitted by author-name on Sun, 06/12/2016 - 20:34`. I am using Adaptive theme.

I would like to change (1) date part in the `ago` format, like

`1 minute ago`

`24 minutes ago`

`an hour ago`

`2 hours ago`

`1 day ago`

`20 days ago`

`1 month ago`

`1 year ago`

`etc...`

AND the (2) Sentence part as described below,

**From** `Submitted by author-name on Sun, 06/12/2016 - 20:34` **To** `author-name ------- ago`

**Now, Sentence part I did achieve as described below**,

1. I did some change in `comment.tpl.php` as shown below

**From-\>**

```
<?php if ($picture || $submitted): ?>
<footer<?php print $footer_attributes; ?>>
  <?php print $picture; ?>
  <p class="author-datetime"><?php print $submitted; ?></p>
</footer>

```

**To-\>**

```
<?php if ($picture || $submitted): ?>
<footer<?php print $footer_attributes; ?>>
  <?php print $picture; ?>
  <span class="auth"><?php print $author; ?></span>
  <div class="cret"><p><?php print $created; ?></p></div>
  <!--<p class="author-datetime"><?php print $submitted; ?></p>--> <!--I did remove this part, so it can not take the whole submitted by sentence by default-->
</footer>

```

So, by doing this, I can add `author-name` separately and `date` separately, so this will allow me to format the sentence the way I want

Hence now, I am getting,

`author-name Sun, 06/12/2016 - 20:34`

Now, how can I change the `date` part. Thanks

# Answer
> 2 votes
You can use `format_interval()` to do this.

```
function MYTHEME_preprocess_comment(&$variables) {
  $comment = $variables['elements']['#comment'];
  $variables['created'] = t('@created ago', array(
    '@created' => format_interval(REQUEST_TIME - $comment->created),
  ));
}

```

If you look at the source for `template_preprocess_comment()`, you are essentially just using `format_interval()` instead of `format_date()` to create the timestamps. In the above, we run everything through `t()` so that the string "ago" gets translated properly.

# Answer
> 0 votes
```
<?php
function mytheme_preprocess_node(&$variables) {
  $node = $variables['node'];
  $variables['date'] = format_date($node->created, 'custom', 'l, d/m/Y');

  if (variable_get('node_submitted_' . $node->type, TRUE)) {
    $variables['display_submitted'] = TRUE;
    $variables['submitted'] = t('Submitted by !username on !datetime', array('!username' => $variables['name'], '!datetime' => $variables['date']));
    $variables['user_picture'] = theme_get_setting('toggle_node_user_picture') ? theme('user_picture', array('account' => $node)) : '';
  }
  else {
    $variables['display_submitted'] = FALSE;
    $variables['submitted'] = '';
    $variables['user_picture'] = '';
  }
}

function mytheme_preprocess_comment(&$variables) {
  $comment = $variables['elements']['#comment'];
  $node = $variables['elements']['#node'];
  $variables['created']   = format_date($comment->created, 'custom', 'l, d/m/Y');
  $variables['changed']   = format_date($comment->changed, 'custom', 'l, d/m/Y');

  $variables['submitted'] = t('Submitted by !username on !datetime', array('!username' => $variables['author'], '!datetime' => $variables['created']));
}
?>

```

for more information check this link https://www.drupal.org/node/1075692

---
Tags: 7, datetime
---


# Question
Title: How to change new theme for a content type
Requirements: Create content type based theme.

I have a requirement to create content based theme, I mean if the content type is **article** then node view call theme-1 and if type is **basic page** then node view call theme-2

# Answer
ThemeKey module can do this:

> ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules. In combination with Drupal's theme inheritance you can easily achieve features like:

* individually-styled channels
* a front-page / "splash" screen
* a date/time-selected Christmas theme
* mobile themes for different auto-detected mobile devices
* special themes for "limited" or "old" browsers
* **content, user, or role -specific themes**
* indicating your environment (production, staging, testing, sandbox, … )
* testing your redesign safely on a live server ...
> 1 votes

# Answer
Use the theme layer to add your logic and create separate template files (**or** theme hook suggestions) to structure the markup for each of your content types. In case you only want to apply different style per node type instead of structure use drupal\_add\_css accordingly.
> 0 votes

---
Tags: theming, hooks
---


# Question
Title: modified value in form_state but it is not being saved
in the validation of my form i pass the form\_state by reference and I modified the form state value of one of the fields with `$form_state['values']['field_total_payment']['und'][0]['value'] = $total_payment;`

I also tried `form_set_value($form['field_total_payment'], array('und' => array(0 => array('value' => $total_payment))), $form_state);`

and I add a second submit to check if the value is there and I can see that with both pieces of code it is in the form\_state\['value'\] , but it is not getting saved to the node.

What is missing for this information to be stored into the database?

# Answer
> -1 votes
update, i took off the submit handler that i had added to look at the data and it works now.

# Answer
> -1 votes
Use

```
$form_state->setValue($key, $value);

```

In your case, that should be

```
$form_state->setValue(['field_total_payment'], $total_payment);

```

---
Tags: forms
---


title: Install without Bootstrap CDN

text:
# Question
Title: Install without Bootstrap CDN
I have the theme Bootstrap CDN 3.3.6 installed on my site and I use the appearance "Journal". How not to use the CDN maintaining the appearance "Journal" ? Thank you

* I download on Bootstrap http://getbootstrap.com/getting-started/#download and I copy the folder in my sub-theme, as you can see on the screenshot.
* I copy the file overrides-journal.min.css to bootstrap theme of css file my subtheme.
* I added a few lines in my file bootstrap\_subtheme\_front\_office.info, see the catch.
* I disabled CDN in subtheme /admin/appearance/settings/bootstrap\_subtheme\_front\_office
* I deleted the cache.

If I erases the line stylesheets\[all\]\[\] = css/overrides-journal.min.css the theme works correctly but I want to show the appearance of the theme "Journal".

If I add the line stylesheets\[all\]\[\] = css/overrides-journal.min.css the theme "Journal" is not applied.

# Answer
Get the css files , or compile the less ones , and copy them to your theme css folder , then modify your theme .info file so drupal can see the new css files
> 0 votes

# Answer
Could the order of the css files be causing the problem. If journal overrides bootstrap, it should come after it in the .info file.
> 0 votes

---
Tags: bootstrap-theme
---


# Question
Title: How to display 12 grid for development purpose in bootstrap?
I am using bootstrap theme and create child theme. i want to display 12 grid for development purpose.

Can any body tell me how to enable this?

Thanks

# Answer
> 1 votes
You could try adding a image of the grid as a css background image to the container class. This might fail if you are overriding it for any reason.

A more difficult way of achieving this would to try having a grid fixed position over your site that you can maybe toggle with JavaScript.

---
Tags: theming
---


title: Cannot redeclare class Drush error

text:
# Question
Title: Cannot redeclare class Drush error
When I go to my site on command line and run a drush command I get the following error:

```
PHP Fatal error:  Cannot redeclare class Drush in /var/www/xmd8/www/vendor/drush/drush/lib/Drush.php on line 36

```

If I run `which drush` I get:

```
/usr/local/bin/drush

```

I have the Lightning Distribution installed via composer and they are adding Drush.

Any ideas on how to fix this?

# Answer
I had Drush version 9.0-dev installed which was causing issues. I downgraded to 8.0.5 and this problem went away. Thanks @greg\_1\_anderson for giving me the idea.
> 0 votes

# Answer
What version of Drush are you using? Recent versions of Drush will notice that there is a copy of Drush included in your Drupal site, and will redispatch (exec) to use it instead. If you are using an old, unsupported version of Drush (e.g. Drush 6 or earlier), then it will not do this, and the error you see above would be the likely result.
> 1 votes

---
Tags: 8, drush
---


# Question
Title: Redirect to PayPal site without payments pane in checkout
On the checkout forms review pane when i select to pay with Paypal WPS and submit the form it get's redirected to an intermediary pane which is the payments pane. And only after 10 seconds it redirects to the PayPal site, there's a button as well..

Could this step be left out? If so, what is the right configuration.

So when selecting PayPal WPS payment and submitting the form it should automatically redirect to the PayPal site.

# Answer
Commerce Paypal WS already redirects automatically by using the "offsite\_autoredirect" flag in hook\_commerce\_payment\_method\_info:

```
  $payment_methods['paypal_wps'] = array(
    'base' => 'commerce_paypal_wps',
    'title' => t('PayPal WPS'),
    'short_title' => t('PayPal'),
    'display_title' => $display_title,
    'description' => t('PayPal Website Payments Standard'),
    'terminal' => FALSE,
    'offsite' => TRUE,
    'offsite_autoredirect' => TRUE,
  );

```

The behaviour of this flag is to redirect automatically:

```
if (!empty($payment_method['offsite_autoredirect'])) {
  $form['#attached']['js'][] = drupal_get_path('module', 'commerce_payment') . '/commerce_payment.js';

```

And the js is the simplest it can be:

```
  Drupal.behaviors.commercePayment = {
    attach: function (context, settings) {
      $('div.payment-redirect-form form', context).submit();
    }
  }

```

So if you're experiencing a 10s delay on this operation, you need to debug what's happening in your payment page to cause this slowness. Check things like other panes you've put there (there should be just the payment one), cache, js compression and so on.
> 1 votes

# Answer
You can clean up the auto redirect experience for the user by hiding the page content of the redirect form. Something simple like this will work in commerce\_payment.js to hide the form from the user and still allow the redirect code to run.

```
  Drupal.behaviors.commercePayment = {
     attach: function (context, settings) {
       $(document.body).hide();
       $('div.payment-redirect-form form', context).submit();
    }
  }

```
> 0 votes

---
Tags: commerce, payment-gateways
---


# Question
Title: How to Move Tooltip Away from Checkbox in Bootstrap Theme?
I am using the Bootstrap theme as the administration theme. The tooltips get in the way of the checkboxes. How to move?

# Answer
> 1 votes
If you open up the settings for your theme under the appearance tab there should be a javascript tab. If you click that the tooltips and popover settings are displayed. You can either turn them off or make them appear below the field.

---
Tags: theming
---


title: What module name do I use for drush dl?

text:
# Question
Title: What module name do I use for drush dl?
I'm trying to install the Delete All module on Drupal 7 via Drush, but whenever I type `drush dl delete-all` I get the following error:

> No release history was found for the requested project (delete-all). \[warning\]

I thought it might have been related to case sensitivity, but trying other names like `Delete-All` and `DeleteAll` gave me the same error. Is there anything I'm doing wrong here, or is something wrong with my installation of Drush/Drupal?

# Answer
> 8 votes
Try:

```
drush dl delete_all

```

You have to check the project URL:

> https://www.drupal.org/project/**delete\_all**

And use the last part, the project machine name.

The *delete-all* string is the drush command provided by this module.

---
Tags: 7, drush, files
---


# Question
Title: How to get path of an element of a kint printed array?
In D7, when you used DPM to print out an array / object, you could double click each line to get the "path" of the element (like: \['#target'\]\['tid'\]). In D8 am totally missing this feature. I also saw on a site where I can see this feature. But my "stable" devel module just doesn't seems to have this feature. Am I missing a config issue?

# Answer
> 4 votes
you need to install and enable Search kint module

---
Tags: 8, debugging
---


# Question
Title: Why aren't CSS files served? There is nothing in sites/default/files/css
In my Drupal 8 installation profile, I install a theme and a lot of configuration for it. I'm using Features to install blocks/settings/views for it, but when I enable the feature Drupal stops serving ANY CSS files on page loads.

I don't think it's an issue with features, because if I wait long enough, those files will be generated by Drupal and CSS files will load as normal, it's just that Drupal assumes those files already exist.

I have tried:
\- drush cr
\- clearing the cache manually in the UI
\- all of the individual drush cc options
\- deleting the contents of all cache\_\* tables and clearing the cache or drush cr
\- turning aggregated css off, clearing caches, turning it back on, clearing caches
\- running cron
\- running /update.php

...Is there any way I can tell Drupal to generate these files instead of waiting hours for it?

# Answer
A few more things to check when you have issues like this:

* **Any noteworthy issues on the Status page?** *(admin/reports/status)*
* **Does saving the File system page generate any errors?** *(admin/config/media/file-system)* This sometimes indicates permission or ownership issues in the file structure, which could keep the aggregate CSS and JS files from being generated?
* **Have you checked the error log for any noteworthy messages?** *(admin/reports/dblog)*

Clearing the cache is a good place to start, but I see that you already did that. Try checking the error log immediately after clearing the cache to see if anything pops up.
> 2 votes

---
Tags: 8, theming
---


# Question
Title: How do you get field groups to render for a block_content entity loaded programmatically?
I added some field groups to my display, but they don't render on my custom block\_content entity.

```
$blocks = \Drupal::entityManager()->getStorage('block_content')->loadByProperties(['type' => 'footer_bottom']);
if (!empty($blocks)) {
  $block = array_shift($blocks);
  $render_controller = \Drupal::entityManager()->getViewBuilder('block_content');
  $footer_bottom = $render_controller->view($block);

  return $footer_bottom; // won't render field groups.

}

```

I see the field groups in the render array when I dump the $footer\_bottom array:

```
  "#fieldgroups" => array:2 [▼
    "group_tricolumn" => {#5505 ▶}
    "group_subfooter" => {#5465 ▶}
  ]

```

Is there another step to process the field groups?

# Answer
The field\_group module does not currently support the block entities, see Does not work with blocks \[2689501\]
> 1 votes

# Answer
After digging around in the field\_group module, I came up with a solution that is rather klunky. I'm sharing it, but I hope one of you can still give me a better solution.

```
$render_controller = \Drupal::entityManager()->getViewBuilder('block_content');
$footer_bottom = $render_controller->view($block);
field_group_fields_nest($footer_bottom);

$build['footer_bottom']['group_tricolumn'] = $footer_bottom['group_tricolumn'];
$build['footer_bottom']['group_subfooter'] = $footer_bottom['group_subfooter'];

```

I can't just output the entity once I do this, I have to grab the field groups themselves. So it adds an extra step. I'd like to know how to render a block\_content entity without having to manually create an array from the elements as I'm doing here.
> 0 votes

---
Tags: 8
---


# Question
Title: How do I programmatically insert the entity ID?
I have added extra fields on the drupal 7 user registration form and created a module with a hook\_form\_alter function so that i can alter one field in the registration form. in the same file i also added the hook\_form\_submit function to handle the submission of that input box.

```
function user_registration_form_alter(&$form, &$form_state, $form_id){
if ($form_id == 'user_register_form'){

    $form['field_first_name'] = array(
        '#type' => 'textfield',
        '#title' => t('First Name'),
        '#description' => t('Enter your first name.'),
        '#maxlength' => 255,
        '#required' => TRUE,
        );

}

if (isset($form['actions']['submit'])) {
        $form['actions']['submit']['#submit'][] = 'user_registration_form_submit';
       }
}

function user_registration_form_submit(&$form, &$form_state)
    {
        $fe_id = db_insert('field_revision_field_first_name')
        ->fields(array(
            'field_first_name_value' => $form_state['values']['field_first_name'],
            ))->execute();
        drupal_set_message(t('your form entry has been added'));
    }

```

When i click on the submit button i get the following error message

> PDOException: SQLSTATE\[HY000\]: General error: 1364 Field 'entity\_id' doesn't have a default value: INSERT INTO {field\_revision\_field\_first\_name} (field\_first\_name\_value) VALUES (:db\_insert\_placeholder\_0); Array ( \[:db\_insert\_placeholder\_0\] =\> john ) in user\_registration\_form\_submit() (line 38 of /var/www/html/lite/sites/all/modules/user\_regestration/user\_registration.module)

I noticed the error is generated because the"entity\_id doesn't have a default value" when the insert query is executed. My question is how do i include the entity\_id default value.

# Answer
Why don't you use a module providing this functionality, like profile2 ?

The user is not created in your submithandler, so either you save it:

```
function foo_user_register_form_submit($form, &$form_state){
    $edit = array(
          'name' => $form_state['values']['name'],
          'pass' => user_password(),
          'mail' => $form_state['values']['mail'],
          'init' => $form_state['values']['mail'],
          'status' => 1,
          'access' => REQUEST_TIME,
          'field_first_name' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_first_name']))),
    );
    user_save(drupal_anonymous_user(), $edit);
}

```

For more details see the docs.

Or you could try to add a custom submit handler, which would be fired after the user is created, in form\_alter:

```
$form['#submit'][] = 'your_custom_submit_handler_function';

```

In there the user should already be created. so:

```
function your_custom_submit_handler_function(&$form, &$form_state)
    {
        $fe_id = db_insert('field_revision_field_first_name')
        ->fields(array(
            'field_first_name_value' => $form_state['values']['field_first_name'],
            ))->execute();
        drupal_set_message(t('your form entry has been added'));
    }

```

> But keep in mind, that this custom inserting maybe needs some more code, here you only add the revision entry ..
> 1 votes

---
Tags: 7, database, forms
---


title: How do you alter the value of a field?

text:
# Question
Title: How do you alter the value of a field?
I would like to perform a string replace function on a field in views. What is the best way to access and change the value? A template will not work as the view is being output as JSON.

Is the best way hook\_field\_views\_data\_alter? If so I am having trouble implementing it in a module.

Or can I do this with a preprocess function? I tried the following. I can change the value but when I assign it back it is not output in the view.

```
function mytheme_preprocess_views_view_fields(&$variables) {
  $view = $variables['view'];
  $row = $variables['row'];
  $new_value = str_replace ( '.' , ',' , $row -> node__field_product_price_field_product_price_value );
  $row -> node__field_product_price_field_product_price_value = $new_value;
}

```

# Answer
I don't know if this is the best way for you, but it works for me.

If view is being output as JSON, and you are using fields, then you can just edit field settings and use twig for this.

So in your field configuration, under **Rewrite Results** check *Override the output of this field with custom text*. Under Text you can put something like

```
{{ your_field_name|replace({".": ","}) }}

```

your field name can be found lower under Replacement patterns.

Of course, you are limited to twig with this method, but if it's just about string replacement I think it's fine.
> 4 votes

# Answer
You can implement your own `FieldFormatter` class (extending for example `FormatterBase`) and configure your view to use it.

Edit: although this approach works, it is not the Drupal way to do it. Thanks to @Eyal for pointing that out.
> 0 votes

---
Tags: views, 8
---


title: Get information about a menu item

text:
# Question
Title: Get information about a menu item
In Drupal 8, you can use system blocks to show menus starting from different levels. For example:

```
Menu item 1 (level1)
--- Menu Item 2 (level2)
--- Menu Item 3 (level2)

Menu item 4 (level1)
--- Menu Item 5 (level2)
--- Menu Item 6 (level2)

```

When user is on a page linked by menu item 2 I want to have a block showing the following:

```
Menu item 1
    --- Menu Item 2
    --- Menu Item 3

```

What the main system block offers is the following result:

```
    --- Menu Item 2
    --- Menu Item 3

```

You see? I need the parent menu item of these menu items as well.

What I did so far is to define a custom block in my module:

```
class MainMenuBlockSecondLevel extends BlockBase {

  public function build() {
    $menu_name = 'main';
    $menu_tree = \Drupal::menuTree();
    $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
    $parameters->setMinDepth(2);

    $tree = $menu_tree->load($menu_name, $parameters);
    $manipulators = array(
      array('callable' => 'menu.default_tree_manipulators:checkAccess'),
      array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
    );
    $tree = $menu_tree->transform($tree, $manipulators);

    $parents = $parameters->expandedParents;  // menu_link_content:dd7b39a6-c4c8-48dd-a1cf-92a755087c29

    $build['parent']['#markup'] = '<div class="parent-menuitem">Parent</div>';
    $build['menu'] = $menu_tree->build($tree);
    return $build;
  }
}

```

With the $parents variable I get an array like that:

```
Array
(
    [0] =>
    [1] => menu_link_content:dd7b39a6-c4c8-48dd-a1cf-92a755087c29
)

```

Here it stops for me now. What is menu\_link\_content:dd7b39a6-c4c8-48dd-a1cf-92a755087c29 and how can I get the needed information like menu item title and path out of it?

# Answer
`MenuTreeParameters::$expandedParents` are a list of menu tree ids (a composite key of the menu bundle and the menu content UUID). You can see its data in the `menu_tree`, `menu_link_content`, `menu_link_content_data`, database tables.

If you need to programmatically invoke the menu item for reference, you can load it via Drupal's entity manager:

```
// Load each menu content item per UUID
foreach ($parents as $menu_uuid) {
  $menu_content = current(\Drupal::entityManager()->getStorage('menu_link_content')->loadByProperties(array('uuid' => $menu_uuid)));
  // @TODO: Reference menu content properties for data
  // (e.g. $menu_content->get('title')->value / $menu_content->get('link')
}

```
> 3 votes

---
Tags: 8, routes
---