# Question
Title: How do I render form fields in my custom.tpl.php template?
Here's my dilemma, I built a custom form-based module that allows a user to vote on a future conference location but I'm having a issue printing or rendering my form fields to have them display in my custom block template.

## ****eventvoting.module****

```
<?php
/**
 * @file
 * Title        : Drupal 7 Event Voting form in a block pattern with template file
 * Author       : Kenyon M. Johnston
 *
 * Web application form that allows site visitors to vote on what city they
 * would like to see host their favorite event next year.
 */

 /**
 * Implmentation of hook_permission()
 */
function eventvoting_permission(){
  return array (
    'Administer event voting form' => array(
      'title' => t('Administer event voting form'),
      'description' => t('Allows users to implement custom css class for the Event Voting Form module'),
    )
  );
}

 /**
 * Implements hook_block_info().
 */
function eventvoting_block_info() {
  $block['eventvoting_block'] = array(
    'info' => t('Event Voting Form Block'),
    'cache' => DRUPAL_CACHE_PER_ROLE,
  );
  return $block;
}

/**
 * Implementation of hook_block_view()
 */
function eventvoting_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'eventvoting':
      $block['subject'] = t('');
      $block['content'] = array(
        '#theme' => 'eventvoting',
        '#vote_event_name' => variable_get('event_name'),
        '#vote_city' => variable_get('city'),
        '#vote_name' => variable_get('name'),
        '#vote_email' => variable_get('email'),
        '#vote_submit' => variable_get('submit'),
      );
    break;
  }
  return $block;
}

/*
 * Implements hook_theme
 */
function eventvoting_theme(){
  return array (
    'eventvoting' => array (
      'arguments' => array(
        'vote_event_name' => NULL,
        'vote_city' => NULL,
        'vote_name' => NULL,
        'vote_email' => NULL,
        'vote_submit' => NULL,
      ),
      // Use a template file called eventtheme.tpl.php
      'template' => 'theme/eventtheme',
    ),
  );
}

/**
 * Implements hook_menu().
*/
function eventvoting_menu() {
  $items['event-voting-form'] = array(
    'title' => 'Event Voting Form',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('eventvoting_form'),
    // Use the default/standard site configuration permission.
    'access arguments' => array('administer site configuration'),
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

/**
 * Creates/returns a form to configure the block's variables.
 *
 * @param array $form
 * @param array $form_state
 * @return array
 */
function eventvoting_form($form, &$form_state) {

  $form['event_name'] = array(
        '#title' => t('Select an event:'),
        '#type' => 'textfield',
        '#default_value' => variable_get('event_name'),
        '#required' => TRUE,
        '#weight' => 0,
    );

    $form['city'] = array(
        '#title' => t('Vote for a city:'),
        '#type' => 'textfield',
        '#default_value' => variable_get('city'),
        '#required' => TRUE,
        '#weight' => 0,
    );

    $form['name'] = array(
        '#title' => t('Your name:'),
        '#type' => 'textfield',
        '#default_value' => variable_get('name'),
        '#required' => TRUE,
        '#weight' => 0,
    );

    $form['email'] = array(
        '#title' => t('Your email:'),
        '#type' => 'textfield',
        '#default_value' => variable_get('email'),
        '#required' => TRUE,
        '#weight' => 0,
    );

    $form['save'] = array(
        '#type' => 'submit',
        '#value' => t('Vote'),
      );

    return $form;
}

**<h2><strong>eventheme.tpl.php (inside the "theme" directory)</strong></h2>**

<?php

/*
 * File         : eventtheme.tpl.php
 * Title        : Drupal 7 Event Voting Location form in a block pattern with template file
 * Author       : Kenyon M. Johnston
 *
 */

?>

<div class="event-voting-form">
    <form>
        <h2>Vote for Next Year's Event</h2>

        <div id="vote_event_name">
            <?php print $vote_event_name; ?>
        </div>

        <div id="data-fieldset">
            <div id="vote_city">
                <?php print $vote_city ?>
            </div>
            <div id="vote_name">
                <?php print $name ?>
            </div>
            <div id="vote_email">
                <?php print $email ?>
            </div>
            <div id="vote_submit">
                <?php print $submit ?>
            </div>
        </div>

    <?php print drupal_render_children($form); ?>
    </form>
</div>

```

My goal is to render my fields of choice. The theme renders in the block but not the fields,

This has been racking my brain for a few hours now, any help and assistance would be GREATLY appreciated.

# Answer
> 0 votes
```

function hook_myform_form ($form, &$form_state,$user_id) {

}

function hook_BLOCK_myform_CONTENT() {
  return drupal_get_form('hook_myform_form');
}

function hook_block_info() {
  $blocks = array();

  $blocks['custom_myform_for_homepage'] = array(
    'info' => t('Details'),
  );
  return $blocks;
}

function hook_block_view($delta='') {
  $block = array();
  switch($delta) {
    case 'custom_myform_for_homepage':
      $block['subject'] = t("Details");
      $block['content'] = hook_BLOCK_myform_CONTENT();
      break;
  }
  return $block;
}

```

Then in your theme template.php add

```
function yourthemename_theme($existing, $type, $theme, $path) {
    $items['hook_myform_form'] = array(
        'render element' => 'form',
        'template' => 'filename_withoutextension',
        'path' => drupal_get_path('theme', 'yourthemename') . '/nameoffolder',
    );
  return $items;
}

```
Now in filename\_withoutextension tpl file render fields like this.
```
print render($form['checkboxes']);

```

# Answer
> 0 votes
You can try the code:

```
/**
 * Implements hook_block_info().
 */
function mymodule_block_info() {
  $block['eventvoting_block'] = array(
    'info' => t('Event Voting Form Block'),
    'cache' => DRUPAL_CACHE_PER_ROLE,
  );
  return $block;
}

/**
 * Implementation of hook_block_view()
 */
function mymodule_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'eventvoting_block':
      $block['subject'] = t("Details");
      $block['content'] = mymodule_block_form();
      break;
  }
  return $block;
}

function mymodule_block_form() {
  return drupal_get_form('mymodule_build_block_form');
}

function mymodule_build_block_form($form, &$form_submit) {
  $form['name'] = array(
    '#title' => t('Your name:'),
    '#type' => 'textfield',
    '#default_value' => variable_get('name'),
    '#required' => TRUE,
    '#weight' => 0,
  );

  $form['email'] = array(
    '#title' => t('Your email:'),
    '#type' => 'textfield',
    '#default_value' => variable_get('email'),
    '#required' => TRUE,
    '#weight' => 0,
  );

  $form['save'] = array(
    '#type' => 'submit',
    '#value' => t('Vote'),
  );
  $form['#theme']='eventvoting';
  return $form;
}

function mymodule_theme($existing, $type, $theme, $path) {
  return [
    'eventvoting' => [
      'render element' => 'form',
      'path' => $path . '/templates',
      'template' => 'eventvoting_form',
    ]
  ];
}

```

create file `eventvoting_form.tpl.php` in the module `mymodule/templates/eventvoting_form.tpl.php` print form field:

```
<?php print render($form['form_id'])?>
<?php print render($form['form_token'])?>
<?php print render($form['name'])?>
<?php print render($form['email'])?>
<?php print render($form['save'])?>

```

---
Tags: 7, entities
---


# Question
Title: Is there a way to input the data of multiple content types all on the same page?
I have three content types: `student`, `course`, and `student_takes_course` (`student_takes_course` have two reference fields that points to the `student` and `course` content types).

To input a new `student_takes_course` record, I would first have to go to the `student` content type and input a new `student` record, and then go to the `course` content type and input a new `course` record, and only then I can go to the `student_takes_course` content type and input a new record that have references to the newly inputted `student` and `course` records).

But is there a way to input the `student` and `course` and `student_takes_course` records all on the same page?

# Answer
> 5 votes
You can use the module Inline Entity Form as widget for student and course in your student-course content type.

This widget loads the node form for student and course in student-course content creation form, so you can fill all the data in the same place.

---
Tags: 8
---


# Question
Title: How to load a node title of different language?
In my case the noads are stored in three different languages. How can add a condition, where I specify the language for the title that need to be loaded?

```
foreach($references as $reference){
    if($node = Node::load($reference->nid)){
      $url = Url::fromRoute('entity.node.canonical', array('node' => $node->id()))->toString();
      $link = '<a href="'.$url.'">'.$this->t($node->getTitle()).'</a>';
      $render .= '<li>'.$link.'</li>';
    }

```

Where $references is an array of nids.

# Answer
You can load the translation separately with `ContentEntityBase::getTranslation`, e.g.:

```
if ($node->hasTranslation('es')) {
  $translation = $node->getTranslation('es');
  $translated_title = $translation->label();
}

```
> 12 votes

---
Tags: 8
---


# Question
Title: Should I create a reference field or a third content type to represent a many-to-many relationship?
I have a student table and a course table that have a many-to-many relationship (a student can take many courses, and a course can be taken by many students).

If I am implementing the above data model as a database, I would create a third table to represent the many-to-many relationship.

But I want to implement the above data model in Drupal 8. I think that in Drupal 8 there are two ways to implement the above data model:

* I can create a reference field in one of the two content types (student or course) that points to the other content type.
* I can create a third content type that have two reference fields that points to the student and course content types.

Am I correct that these two ways are valid? And if I am correct, which one should I choose?

# Answer
> 1 votes
I know you won't like this answer but in general **it depends**:

What are your use cases when adding a new relationship? Is it more likely to add classes via students or the other way around? Or is it a migration process?

If **UI** is heavily used by both of the entites, I would give reference fields to both content types, and always update the other type reference field upon saving one type.

If this is more like for **listing** stuff (without editing on the UI these properties) and the information is coming from a big relationship list, then I would store it in a key-value table or a custom table.

---
Tags: 8
---


# Question
Title: How to disable 'promote to front page' and 'sticky' options?
Two possible methods that I have explored:

Use hook\_form\_alter to unset both options on node edit forms. But on the main admin content page, the options still appear under 'Update options' dropdown.

Use Override Node Options module. This provides granular control, but it means disabling the 'Administer content' permission. Users then can't see the 'Update options' at all, which they still need in order to bulk publish, delete, etc.

# Answer
> 16 votes
There are 3 places, where those options can be seen:

* on admin/structure/types/manage/article, for the "Article" content type
* on node/2/edit, for the node with ID equal to 2
* on admin/content, between the "Update options"

If you need to remove the options from those setting/administrative pages, then you need to alter the following form builders:

`node_admin_nodes()` is the form builder for the node administration overview in admin/content, which includes the "Update options" field that allows the users with the right permission to promote/demote a node from the front page, and to make a node sticky. The field lists all the node operations implemented by modules; in the list of the operations obtained with `$operations = module_invoke_all('node_operations')`, those operations are represented from `$operations['promote']`, `$operations['demote']`, `$operations['sticky']`, and `$operations['unsticky']`.

# Answer
> 13 votes
Here is a custom module I wrote for Drupal 7 that removes "promote to front page" and "sticky at top of lists" on node add/edit forms, content type add/edit forms and the admin/content dropdown. This module does not alter any database settings so it won't change existing content, you can always disable it and get your options back and everything will work just like it did before.

Paste this code into a hide\_sticky\_promote.module and make a corresponding hide\_sticky\_promote.info file, enable module and wallah, no more sticky and promote checkboxes or dropdown selections.

```
/**
 * Remove sticky/promote entirely from add and edit content type forms.
 *
 * Implements hook_form_FORM_ID_alter().
 */
function hide_sticky_promote_form_node_type_form_alter(&$form, &$form_state, $form_id) {
  // Remove sticky/promote entirely from add and edit content type forms.
  $options = array('promote', 'sticky');
  foreach ($options as $key) {
    unset($form['workflow']['node_options']['#options'][$key]);
  }
}

/**
 * Remove sticky/promote entirely from node/X/edit & node/X/add forms.
 *
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function hide_sticky_promote_form_node_form_alter(&$form, &$form_state, $form_id) {
  $options = array('promote', 'sticky');
  foreach ($options as $key) {
    $form['options'][$key]['#access'] = FALSE;
  }
}

/**
 * Remove some sticky/promote update options on admin/content.
 *
 * Implements hook_form_FORM_ID_alter().
 */
function hide_sticky_promote_form_node_admin_content_alter(&$form, &$form_state, $form_id) {
  $options = array('demote', 'promote', 'sticky', 'unsticky', );
  foreach ($options as $key) {
    unset($form['admin']['options']['operation']['#options'][$key]);
  }
}

```

Or grab it from here in module form: https://github.com/StudioZut/hide-sticky-promote

# Answer
> 3 votes
Use the following:

```
/**
 * Implements hook_form_alter().
 * This is remove the promote to frontpage, and make sticky options from node edit pages
 */
function alter_drupal_form_alter(&$form, &$form_state, $form_id) {
  if (strpos($form_id, '_node_form') !== FALSE) {
    unset($form['options']['sticky']);
    unset($form['options']['promote']);
  }

  if (strpos($form_id, 'node_admin_content') !== FALSE) {
    //$opt[''] = '- Select -';
    $opt['publish'] = 'Publish selected content';
    $opt['unpublish'] = 'Unpublish selected content';
    $opt['delete'] = 'Delete selected content';
    $opt['pathauto_update_alias'] = 'Update URL alias';
    $form['admin']['options']['operation']['#options'] = $opt;

    // print_r($form['admin']['options']['operation']['#options']);
  }
}

```

# Answer
> 2 votes
In Drupal 8, the option can be disabled per content type:

```
/admin/structure/types/manage/page/form-display

```

The "node operation bulk form" field must also be modified in the admin content view to remove the corresponding action from /admin/content

```
/admin/structure/views/view/admin_content

```

If wanting to keep the content type promoting options, for usage with custom views for example, the view "frontpage" that generate the frontpage page can also be modified in

```
/admin/structure/views/view/frontpage

```

Adding for example an extra filter 'is not equal to promoted' and removing the "no result behaviour" " makes that view returning no results.

# Answer
> 1 votes
You can disable the 'promote to front page' by editing the content type. To hide it and/or the 'sticky' options, revisions and more, check out the Jammer module for Drupal 7.

# Answer
> 0 votes
Why don't make a different template region that only appears on the front page and remove the \['content'\] region on that page ?

Elements on forms can be hidden using css or with hook\_preprocess\_form()

# Answer
> 0 votes
I use the "Promote Disable" module for this.

It creates a control at Configuration -\> Content authoring -\> Promote disable that gives a select list of all your content types. Ctrl/multi-select items in the list to remove the promote option entirely.

# Answer
> 0 votes
```
function HOOK_form_node_form_alter(&$form, FormStateInterface $form_state) {
  if (isset($form['promote'])) {
    unset($form['promote']);
  }

  if (isset($form['sticky'])) {
    unset($form['sticky']);
  }
}

```

It only needs above

# Answer
> -1 votes
I suspect you could implement a hook\_node\_presave and set those to 0. This should override any possible way to set these.

You could also try to `hook_form_alter` the form used on that admin page and remove those options.

---
Tags: nodes
---


# Question
Title: Programatically create user that needs admin aproval
When creating a new user with user\_save, it seems to get the "approved" role automatically, even though I pass an empty array to `$user->roles`.

How can I force the programatically created user to need admin approval before being activated?

# Answer
**Step1**
**Not need to follow it compulsary**
You don't need any third-party modules. Drupal core has the option to verify the email the user enters, and the option for the administrator user to approve the accounts users create. In Drupal 7, those settings are on /admin/config/people/accounts.
**Step2**

* Once you prepare your $user object and use it on user\_save function you have to follow below steps to send the mail.

```
$userData = user_save($user);
$account = user_load($userData->uid);
$op = 'register_pending_approval';
$status = _user_mail_notify($op, $account);

```
> 0 votes

---
Tags: users
---


# Question
Title: Views > Exposed Filter > How to disable output of options that aren't attached/used by a node
I have a exposed filter setup to filter content within a view.

The view is displaying a list of house designs. These designs need to be able to be filtered by number of beds, bathrooms etc.

"House Design" content type/node has a field (List (integer)) for bedrooms:

http://theexhale.com/screenshot\_1.png

The allowed values for this field are 1,2,3,4,5 (bedrooms)

http://theexhale.com/screenshot\_2.png

The issue I'm having is that the exposed filter is outputting all of these fields for sorting the view even though currently only values "2" and "4" are being used by the "House Design" content type.

http://theexhale.com/screenshot\_5.png

**QUESTION: Can the exposed filter be smart enough to check to see if values of a field/taxonomy vocab are actually being used by the displayed content type/node and then dynamically only display those values in the filter?**

I want to do this to remove/lesson the possibility of no results when a user uses the filter.

Thank you :)

# Answer
The concept's the same in Drupal 8 but the access of properties and handling is a little different from what's done on D7. Here's a working example of 3 exposed filters dependent on each other to allow only values available based on prior selections.

Tips: \- View is built with page that has exposed form in block checked to yes. \- Enable master display, make sure filter identify of exposed filter is same \- Use BEF (better exposed filters) for menu select and autosubmit \- See code comments

This is for D8:

```
/**

* @file
 * Provides functionality for handling exposed filters
 */

use Drupal\Core\Form\FormStateInterface;
use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\query\QueryPluginBase;
use Drupal\views\Plugin\views\query\Sql;
use Drupal\views\ResultRow;
use Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem;
use Drupal\views\Entity\View;
use Drupal\Core\Form\FormState;
use Drupal\Core\Form;
use Drupal\taxonomy\Entity\Term;
use Drupal\Core\Entity;

/**
   * Implements hook_views_exposed_form_alter().
   *
   * alters exposed filter for equipment selector to limit filtered results in a new view
   */
function ahern_equipment_selector_form_views_exposed_form_alter(&$form,  &$form_state){
    if ($form['#id'] == 'views-exposed-form-ahern-exposed-filters-page-1') {
        // Get whatever values selected by user in all menus
        $input = &$form_state->getUserInput();

        // Form fields have given/arbitrary name from Filter identifier in Exposed filter settings
        $selected_what_moving = $input['moving'];
        $selected_where_working = $input['where'];
        $selected_height = $input['height'];

        // Again, form fields have given/arbitrary name from Filter identifier in Exposed filter settings
        // NOTE: make sure also match Filter identifier in Master display
        // Also keep in mind that any view duplicated/cloned from main view should be disabled as
        // it can/will affect results
        $form['moving']['#options'] = _get_associative_array_from_view(
         'ahern_exposed_filters', // viewi id
          'default', // view dsplay id
          $selected_what_moving,
          'moving_chosen'
        );

        $form['where']['#options'] = _get_associative_array_from_view(
         'ahern_exposed_filters', // viewi id
          'default', // view dsplay id
          $selected_where_working,
          'where_chosen'
        );

        $form['height']['#options'] = _get_associative_array_from_view(
         'ahern_exposed_filters', // viewi id
          'default', // view dsplay id
          $selected_height,
          'height_chosen'
        );
    }
}

function _get_associative_array_from_view($viewID, $viewDisplayID, $contextualFilter, $menu_chosen){
//ksm($contextualFilter,'context filter');

  $associativeArray = array();
  $associativeArray['All'] = t('- Any -');
  $viewResults = views_get_view_result($viewID, $viewDisplayID, $contextualFilter);

  foreach($viewResults as $viewRow) {

    switch ($menu_chosen) {
    // views_get_view_result returns rows with original field name so don't use filter identifier name to acceess, use field name
        case 'moving_chosen':
            //ksm($menu_chosen, 'target menu to filter to');
            $term_name = $viewRow->_relationship_entities['field_what_are_you_moving']->getName();
            $term_id = $viewRow->_relationship_entities['field_what_are_you_moving']->id();
            if (!in_array($term_name,$associativeArray)) {
                $associativeArray[] = $associativeArray[$term_id] = $term_name;
            }
            break;

        case 'where_chosen':
            $term_name = $viewRow->_relationship_entities['field_attr_where_are_you_working']->getName();
             $term_id = $viewRow->_relationship_entities['field_attr_where_are_you_working']->id();
             if (!in_array($term_name,$associativeArray)) {
                $associativeArray[] = $associativeArray[$term_id] = $term_name;
            }
            break;

        case 'height_chosen':
            //ksm($menu_chosen, 'target menu to filter to');
            $term_name = $viewRow->_relationship_entities['field_what_is_the_working_height']->getName();
            $term_id = $viewRow->_relationship_entities['field_what_is_the_working_height']->id();
            if (!in_array($term_name,$associativeArray)) {
                $associativeArray[] = $associativeArray[$term_id] = $term_name;
            }
            asort($associativeArray);
            break;

        default:
            break;
    }

  }

    $associativeArray = array_unique($associativeArray);
    return $associativeArray;
}

```
> 2 votes

# Answer
Sure see these examples. My google search terms were `drupal exposed filters limit dynamic`.

I like the 2nd example a tad better than the 1st. Using it as a template and making your own View that outputs allowed number of rooms used within the content type so far on the website, the code in a custom module could look like:

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

  if ($form['#id'] == 'views-exposed-form-MYVIEW-page') {

    $form['bedrooms']['#options'] = _get_associative_array_from_view(
      'mycustom_view_limit_bedroom_count', // view id
      'default', // view display id,
      // Look in the field_data_field_design_bedrooms table and get its
      // primary key for the key field, as its data value for the value field.
      // I forget the exact naming convention in Drupal for an integer
      // list field type offhand ...
      'field_data_field_design_bedrooms_id', // key field id
      'field_data_field_design_bedrooms_value_id' // value field id
    );
  }
}
?>
<?php
function _get_associative_array_from_view($viewID, $viewDisplayID, $keyFieldID, $valueFieldID){

  $associativeArray = array();
  $associativeArray['All'] = t('- Any -');
  // Your view will use Aggregation to show the unique list of room counts
  // by "id" -> "displayed count value" pairs.
  $viewResults = views_get_view_result($viewID, $viewDisplayID);

  foreach($viewResults as $viewRow) {
    $associativeArray[$viewRow->$keyFieldID] = $viewRow->$valueFieldID;
  }

  return $associativeArray;
}

```

My example code is not a guarenteed exact solution, but its not allowed to provide merely links to tutorials here -- so I'm providing some example code for you exemplifying the pieces of code that would go into a custom module.
> 1 votes

# Answer
I have just done this as well and based my solution on @vrwired's solution

(Drupal 8 Dynamic Dependent Dropdown Views Exposed Filters)

My view is a view of content teaser with 3 referenced vocabs on the content type.

Firstly I duplicated the entire view and called it the same as the first on with "Count" on the end and changed it to have no limit to the number of results returned and also to just return fields and only the title field.

This was because without it I wasn't getting the full list of terms I could filter by

All the things in CAPS are as descriptive as I could make them in 5 mins, you'll need to change them as required for your solution

```
<?php

/**
 * Implements hook_views_exposed_form_alter().
 *
 * Alters exposed filter for equipment selector to limit filtered results in a
 * new view
 */
function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state) {
  if ($form['#id'] == 'views-exposed-form-VIEWID-page-1') {
    // Get whatever values selected by user in all menus
    $input = &$form_state->getUserInput();

    $args = [];
    foreach ($input as $arg) {
      if (!empty($arg)) {
        $args[] = $arg;
      }
    }

    $filters = ['FILTER_1', 'FILTER_2', 'FILTER_2'];
    foreach ($filters as $filter) {
      $form[$filter]['#options'] = MYMODULE_get_associative_array_from_view(
        'VIEWID_count', // viewi id
        'page_1', // view dsplay id
        $args, $filter
      );
    }
  }
}

/**
 * Filters out the unavailable options from the drop downs
 */
function MYMODULE_get_associative_array_from_view($view_id, $display_id, $args, $menu_chosen) {

  $options_array = array();
  $options_array['All'] = t('- Any -');
  $result = MYMODULE_get_view_result($view_id, $display_id, $args);

  foreach ($result as $row) {
    switch ($menu_chosen) {

      // views_get_view_result returns rows with original field name so don't
      // use filter identifier name to acceess, use field name
      case 'FILTER_1':
        $field = $row->_entity->get('FIELD_1')->getValue();
        break;

      case 'FILTER_2':
        $field = $row->_entity->get('FIELD_2')->getValue();
        break;

      case 'FILTER_2':
        $field = $row->_entity->get('FIELD_3')->getValue();
        break;

      default:
        break;
    }

    $target_id = $field[0]['target_id'];
    $term = MYMODULE_get_referenced_term($target_id);
    if (!empty($term)) {
      $term_name = $term->getName();
      $term_id = $term->id();
      if (!in_array($term_name, $options_array)) {
        $options_array[$term_id] = $term_name;
      }
    }
  }

  asort($options_array);

  return $options_array;
}

/**
 * Returns a term if in scope
 *
 * @param int $tid
 *
 * @return object
 */
function MYMODULE_get_referenced_term($tid = 0) {
  if (empty($tid)) {
    return;
  }

  $term = taxonomy_term_load($tid);

  if (empty($term)) {
    return;
  }

  return $term;
}

/**
 * Get the view result filtered by the arguments passed
 *
 * @param string $viewname
 * @param string $display
 * @param array $args
 *
 * @return boolean|array
 */
function MYMODULE_get_view_result($viewname, $display, $args) {
  // Get the view
  $view = \Drupal\views\Views::getView($viewname);

  if (!$view) {
    // The view could not be loaded. Add a watchdog message and leave the function
    \Drupal::logger('MYMODULE')->error('View @view not found', array('@view' => $viewname));
    return false;
  }

  // set the display machine name
  $view->setDisplay($display);

  // Set arguments for exposed filters
  // Note that you always need to use an array.
  // The arguments are passed in the order as they appear on the view
  $view->setArguments($args);

  // Execute the view
  // This function does not do any access checks on the view. It is the
  // responsibility of the caller to check $view->access()
  $view->preview();

  if (!empty($view->result)) {
    return $view->result;
  }
}

```
> 1 votes

---
Tags: views
---


title: TB Megamenu 3rd level does not expand

text:
# Question
Title: TB Megamenu 3rd level does not expand
I'm using TB Megamenu on a D8 site. With a bit of tweaking all working fine.. However, when I try to have a third level of links I can't get this to show expanded. In the menu itself the level 2 item and all level 3 items have 'show as expanded' ticked on, to no avail.

In the TB toolbox it shows correct, I can have the level2 item function as header (group set to 'yes') and have the feel 3 links in one or more columns under level 2. But on the site I get a toggle arrow, and no leave three links. And clicking level 2 does not show the level 3 items underneath (I think they're rendered on the right, outside my 100% width submenu).

Structure wanted: level 1 link | level 1 link | etc
level 2 nolink (group yes) | normal level 2 items
level 3 items always expanded as group | level 3 items

(when looking at mobile the level 3 does appear under there level 2, but again not expanded, only unfolding when clicking the level 2 item..)

I have a suspicion I could change the one of the twigs (tb-megamenu-submenu.html.twig? tb-megamenu-subnav.html.twig?) but don't know how..

All help massively appreciated!

# Answer
> 0 votes
TB Mega Menu is a pretty awesome module, but we've been using it for a few years and occasionally run into issues where the rendered menu doesn't appear to reflect the menu's structure. It gets "stuck." Here are a few things that have worked for us, in various combinations:

* Clear your site's cache.
* Rebuild your site's menus (use devel for this).
* For the items that aren't showing, create a new parent menu item and move the child items to under the new parent and delete the old parent menu item.

From our troubleshooting, we've determined that TB sometimes seems to "lose track" of the menu and basically all of these efforts are intended to get TB to re-sync.

Hope it helps!

---
Tags: navigation
---


# Question
Title: How to define event listener in the service?
In Drupal 8 is possible to use event subscriber that is the separate class that defines the callback that should be called on the defined event. See Event Systems Overview & How To Subscribe To and Dispatch Events

But I'm wondering how to define event listener that will trigger the method of the service on the desired event?

here Symfony references:

Events and Event Listeners

Built-in Symfony Events

# Answer
> 2 votes
If I understood correctly, I think you are asking about implementing minimalistic single responsibility event listeners declared in the YML config file, like in this Java example:

```
class MyListener implements ActionListener {
  public void actionPerformed(ActionEvent e) {
    myTextArea.append('Hello from MyListener');
  }
}

```

That is not possible since this is this what the `EventDispatcher` actually does:

```
    public function addSubscriber(EventSubscriberInterface $subscriber)
    {
        foreach ($subscriber->getSubscribedEvents() as $eventName => $params) {
            if (is_string($params)) {
                $this->addListener($eventName, array($subscriber, $params));
            } elseif (is_string($params[0])) {
                $this->addListener($eventName, array($subscriber, $params[0]), isset($params[1]) ? $params[1] : 0);
            } else {
                foreach ($params as $listener) {
                    $this->addListener($eventName, array($subscriber, $listener[0]), isset($listener[1]) ? $listener[1] : 0);
                }
            }
        }
    }

```

You can still have your separate `ActionListener`'s, but you would have to write some code to call them from your implementation of `EventSubscriberInterface`.

---
Tags: 8, symfony-services
---


# Question
Title: How to get the field template for view modes to work
Content type - article , view modes - teaser, vma, vmb. There are 3 views , 2 on the left sidebar called vma view mode and vmb view mode, the one on the right is called teaser view mode. All the views show unformatted list of content using view modes vma, vmb and teaser respectively. How to check for view mode in twig template?

# Answer
Don't put too much logic into your templates. Simply add the field template suggestion by implementing `hook_theme_suggestions_HOOK_alter` to respect view modes from within your theme or custom module:

```
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME/MYMODULE_theme_suggestions_field_alter(array &$suggestions, array $variables) {

  $element = $variables['element'];
  $suggestions[] = 'field__' . $element['#entity_type'] . '__' . $element['#field_name'] . '__' . $element['#bundle'] . '__' . $element['#view_mode'];
}

```

Now you can add templates following this pattern: `field--node--field-myfield--article--teaser.html.twig`.

---

When using Layout Builder or Display Suite you might need to check what else you find inside `$variables['element']` by printing its values with Kint (sub-module of Devel) via `ksm($variables['element'])` and then build the template suggestion from what you find there.
> 5 votes

---
Tags: 8, theming
---


title: Jsonapi query to return specific field

text:
# Question
Title: Jsonapi query to return specific field
In a simple article content type, is there a way we can have a jsonapi query to return specific field only? The same as how REST export view is doing, we can select what field to be displayed in the output.

E.g. `http://localhost:8080/jsonapi/node/article/<return body field value>`

If not, is there a method I can create a list of string then I would want to call a jsonapi to get that list. Thanks in advance!

# Answer
Yes, with the caveat it still contains the JSONAPI document payload around your requested field. This is mandated by the spec so you can't just have an arbitrary JSON structure that contains **only** the field data you want.

This is called a sparse fields query. When you add a `?fields[$RESOURCE_ENTITY]=field1,field2...` to a:

* index endpoint (`/jsonapi/node/article`)
* resource endpoint (`/jsonapi/node/article/$UUID`) endpoint

It will trim down the list of fields to the comma-delimited list you've specified.

To use your example, `http://localhost:8080/jsonapi/node/article?fields[node--article]=body` will return a JSONAPI document with all `article` nodes with only the `body` property in the `attributes` object.

See the JSONAPI docs about fetching resources for more info.
> 3 votes

---
Tags: 8
---


# Question
Title: How to hook_form_alter() inside paragraph item
I would like to edit a field in the node\_form of a paragraph item. For normal fields i would use something like the code below to tweak a field called field\_p\_custom\_id (d7)

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
    switch ($form_id) {
        // tweak CONTENTTYPE_node_form
        case 'CONTENTTYPE_node_form':
            // hide custom ID field for all users, even admin (this field should never be changed)
            $form['field_p_custom_id']['#access'] = FALSE;

        break;
    }
}

```

... but, in the case of a paragraph item, the field\_p\_custom\_id is placed inside a paragraph bundle. I searched inside $form and $form\_state, but can't find where to alter this field. (the paragraph item is default not present on the form since it is not required and can be added unlimited times)

# Answer
For Drupal 8 you can implement hook\_field\_widget\_WIDGET\_TYPE\_form\_alter.

```
/**
 * Implements hook_field_widget_WIDGET_TYPE_form_alter().
 */
function paragraphs_test_field_widget_entity_reference_paragraphs_form_alter(&$element, &$form_state, $context) {
  if ($element['#paragraph_type'] == 'altered_paragraph') {
    $element['subform']['field_text']['widget'][0]['#title'] = 'Altered title';
  }
}

```

see my answer here: How do I alter the behavior of the form fields contained within the paragraph field?
> 3 votes

# Answer
I have been struggling with this for the last two days. I was looking to add a button that would allow users to enter an ASIN and click the button, which would get a bunch of information from the Amazon API. I wanted to use some sort of hook to place the button and some additional containers for the info from the API call directly into the paragraph. However, I could not find a way to do that. I ended up building a solution that works, but is not quite the Drupal way.

I used hook\_form\_FORM\_ID\_alter() to insert a jQuery ajaxComplete command in the page that fired after someone clicked on the "add new paragraph" button. In the callback function, I inserted my button with a click handler in the new paragraph form (with some checks so that my button only got built once each time the user clicked the "add new paragraph" button).

The click handler then made its own ajax call, and I used a hook\_menu to catch that and take care of the Amazon API call. Finally, I put together a bunch of hacky-feeling jQuery calls to create divs and insert the Amazon information in them.

It is not very elegant, but my code is below if it will help anyone.

I did find that someone built/patched the hooks we are looking for to paragraphs in Drupal 8. Too bad we don't have them for Drupal 7. Hopefully someone can point out a better solution and/or create the hooks in the future.

```
<?php

function amazon_fill_form_amazon_list_node_form_alter(&$form, &$form_state, $form_id) {

$form['from'] = array(

    '#type' => 'item',

    '#markup' => '
        <script>
            var beer = function() {
                event.preventDefault();
                var ASIN = jQuery(this).parent().parent().find("input").val();
                var preThis = this;
                jQuery.get("/bestpresentsfor.com/getamazoninfo/?asin=" + ASIN, function(info) {
                    console.log(info);
                    var paragraphContainer = jQuery(preThis).closest(".ajax-new-content");
                    jQuery(paragraphContainer).find(".field-name-field-title").find(".description").after("<div class=\"asin-title-container\">This is the title that Amazon provides:<br>" + info[ASIN].title + "</div>");
                    jQuery(paragraphContainer).find(".field-type-link-field").find("input").val(info[ASIN].detailpageurl);
                    jQuery(paragraphContainer).find(".field-name-field-product-image").find(".description").after("<div class=\"asin-image-container\">This is the image that Amazon provides:<br><img src=\" " + info[ASIN].imagesets.largeimage.url + " \" alt=\"There is no Amazon image for this product!\"></div>");
                    jQuery(paragraphContainer).find(".field-name-field-product-description-amazon").find(".description").after("<div class=\"asin-description-container\">This is the description that Amazon provides:<br>" + info[ASIN].editorialreviews[0].content + "</div>");
                });
                return false;
            }

            var megaIndex = 0;
            var newButton = "<div class=\"asin-button-container\"><button class=\"asin-button\" onclick=\"beer.call(this)\">Enter ASIN</button></div>";
            jQuery( document ).ajaxComplete(function() {
                addASINS = jQuery(".field-type-asin");
                for (var i = 0; i < addASINS.length; i++) {
                    if (jQuery(addASINS[i]).find(".asin-button").length == 0) {
                        jQuery(addASINS[i]).append(newButton);
                    }
                }
            })
        </script>
    ',
);
}

function amazon_fill_menu() {
     $items['getamazoninfo'] = array(
         'page callback' => 'page_callback',
         'type' => MENU_CALLBACK,
         'access arguments' => array('access content'),
     );
     return $items;
}

function page_callback() {
     $asin = $_GET['asin'];
     $info = amazon_item_lookup_from_web($item_ids = array( $asin ));
     drupal_json_output(
         $info
     );
     drupal_exit();
}

```
> 1 votes

# Answer
When create a new node the paragraph field always will be empty, you can try creating a node and add some paragraph, then edit the node and search inside $form. Maybe you can add a default paragraphs first https://www.drupal.org/project/paragraphs\_defaults
> 0 votes

---
Tags: 7, forms, hooks, paragraphs
---


# Question
Title: Unable to perform update when adding new menu field
I'm attempting to add a custom image field to my menu from a custom module like so

```
function my_module_entity_base_field_info(EntityTypeInterface $entity_type) {
  $fields = array();
      if ($entity_type->id() === 'menu_link_content') {
          $fields['menu_link_secondary_image'] = BaseFieldDefinition::create('image')
              ->setLabel(t('Menu link secondary image'))
              ->setDescription(t('Upload a secondary image related to this menu item'))
              ->setDisplayOptions('form',array('type' => 'image','weight' => 1))
              ->setDisplayConfigurable('form',TRUE)
          ->setSettings([
              'file_directory' => 'public://',
              'alt_field_required' => 'FALSE',
              'file_extensions' => 'png jpg jpeg',
          ]);

      return $fields;
    }
}

```

Then in my update function I have

```
function my_module_update_8001(){
    $entity_manager = \Drupal::entityManager();
    $definitions = $entity_manager->getLastInstallFieldStorageDefinitions('menu_link_content');
    if(!isset($definitions['menu_link_secondary_image']) || empty($definitions['menu_link_secondary_image'])){
        $definition = $entity_manager->getFieldStorageDefinitions('menu_link_content')['menu_link_secondary_image'];
        $entity_manager->onFieldStorageDefinitionCreate($definition);
    }
}

```

But when I attempt to run update.php it hangs and I get errors like

> Notice: Undefined index: menu\_link\_secondary\_image\__alt in Drupal\Core\Entity\Sql\SqlContentEntityStorage-\>loadFromSharedTables()

Strangely enough I added a menu link afterwards and my field was actually there. I couldn't tell if my update actually worked and just didn't act as if it did, or if it already worked before hand and the update was unnecessary. Did I do something wrong?

UPDATE: I see that although my field appeared I'm unable to save it due to this error

> Column not found: 1054 Unknown column 'menu\_link\_secondary\_image\__target\_id' i

# Answer
Just update entities it will work: run the command `drush entity-updates`.
**No need** for `hook_update_N`.
You can add `hook_install` to update entities automatically when you install your module don't need to do it by command each time or get the error on every installation .

```

/**
 * Implements hook_install().
 */
function my_module_install() {
  \Drupal::service('entity.definition_update_manager')->applyUpdates();
}

```
> 1 votes

---
Tags: 8, entities
---


# Question
Title: Upgrading from 8.3.7 to 8.4 conflicts with acquia/blt-project
In the composer.json file I added `"drupal/core": "~8.4"` to the *required* section. When I run `composer update drupal/core --with-all-dependencies`, I get the following output.

> Loading composer repositories with package information
> Updating dependencies (including require-dev)
> Your requirements could not be resolved to an installable set of packages.
>
> Problem 1
>
> * drupal/core 8.4.0 conflicts with acquia/blt-project

Why does Drupal 8.4 conflict with acquia/blt-project?

# Answer
> 0 votes
The problem was a line in my composer.json file which is prevent the upgrade from happening.

In the "conflict" section, there's a line `"drupal/core": ">=8.4.0-alpha1"` I have to remove that line and also run the following commands to complete the upgrade.

```
composer update --lock
composer require acquia/lightning:^3.0 acquia/blt:^8.9 --no-update
composer update acquia/lightning --with-all-dependencies

```

---
Tags: 8, composer
---


title: add css if url contains

text:
# Question
Title: add css if url contains
I have one node type and two page types for this node.

```
http://site.com/themes/*

```

and

```
http://site.com/years/*

```

And i want to hide one of the "view-filed" in all "years" pages using the css.

Found this but it doesn't work

```
function mythemename_preprocess_page(&$variables,$hook) {
  $alias = explode('/',drupal_get_path_alias(request_uri()));
  if($alias[1]== "years") {
   $vars['theme_hook_suggestions'][] = 'years';
  }
}

```

https://groups.drupal.org/node/130944#comment-762483

I would be very grateful for any help.

# Answer
> 1 votes
Here's how I would do it (but I'm rather new to this, so maybe your approach is better)...

```
function mythemename_preprocess_page(&$vars, $hook) {
  if (arg(0) == 'years') {
    drupal_add_css(path_to_theme().'/css/years.css');
  }
}

```

# Answer
> -1 votes
I would suggest doing this with pure CSS selectors.

I'm pretty sure you can do something like this:

`/* Hides the link text. */`

`a[href*="find_this_part_of_URL"] {

display: none;

}`

I suggest you do NOT hide page content with this CSS, as it is bad for search engine optimization, but if you honestly can't get the theme to cover up a link, so you can focus on fixing the theme hook, use the above code.

---
Tags: views, theming, forms
---


# Question
Title: drupal/drupal package versus drupal/core package: deciding the one to use
Installing Drupal via Composer, I can choose between two packages: *drupal/drupal* and *drupal/core*. What are the differences between them?

(As a side note, why was the package named *drupal/drupal* instead of simply *drupal*?)

# Answer
*drupal/core* is used for a completely Composer-driven Drupal project where your canonical code repository isn't storing Drupal's codebase but pulling it down as you assemble the project where needed (e.g. local dev, CI build, etc.) Per the README in the *drupal/core* repository on Packagist:

> This is a Git subtree split of Drupal 8's core directory which can be used to build the directory structure for a Drupal site and has the following advantages over pulling in the entire upstream Drupal repository:
>
> * All the components of the Drupal site including Drupal, contributed modules and themes, as well as external libraries can be pulled in via Composer
> * Drupal and any external libraries can be bootstrapped via Composer (i.e. without installing any modules for the external libraries)
> * One has full control over index.php, .htaccess, robots.txt, etc. as those files will not be overridden by a Drupal core update

*drupal/drupal* is the entire project built from the core Drupal Git repository. It comes with other pre-made web config you'll need to run the site as if you retrieved the tarball from the Drupal core project page. This method is considered **deprecated** and is kept around for legacy reasons.

The *drupal/drupal* name is an artifact of the Drupal packagist repository configuration; you're retrieving a Composer package from the *drupal* vendor (the Drupal community) for the *drupal* project (Drupal core).
> 2 votes

---
Tags: composer
---


# Question
Title: How to change calendar entry background based on taxonomy?
Folks, I'm trying to figure out how to style my calendar. I was able to add color stripes based on my taxonomy, but the background of calendar entries is still that ugly yellow #ffc. What I'd like to do is to make the background the same color as the taxonomy color, only brighter/semi-transparent - for example, if the taxonomy color is #00ff00, I want to se the background of that calendar entry to #e0ffe0. I'm pretty new to Drupal and really can't figure out what's the right way to do it.

# Answer
Look at the HTML source of your calendar display, and try to find:

`<div class="block- (whatever)" ... >Calendar entry stuff</div>`

The CSS class name might be something like "block block-calendar block-calendar-entry" but you just want the most specific one that works, and only shows on each calendar entry.

Use CSS transparent coloration of the individual entries:

`/* Colors a calendar entry lighter */

div.block-calendar-entry {

background-color: rgba(255, 255, 255, 0.3)

}`

The first three numbers give the RGB value, and the last one gives the opacity.

Since 255, 255, 255 (maximum red, green, and blue) would be white, an opacity of 0.3 (30%) will lighten any background color that bleeds through from the parent container.
> 0 votes

---
Tags: theming, taxonomy-terms
---


# Question
Title: How to detect mobile viewport with in twig?
Is there a way to detect screen display with in twig? I have a block and I want to render in a twig template using the twig tweak module, but only in mobile screen. It is surely possible to just hide it in CSS, but can it be done in twig? - https://www.drupal.org/project/twig\_tweak

# Answer
> -1 votes
There is a Browser Object in twig which using that you can get some data about user's browser but it does not provide properties like screen width.

its recommended to use css or javascript in these situations but if you want to hide your block in server side so user might access only using a mobile phone then I recommend this steps:

* first of all you should provide a value to check if user is using mobile or not, for this you should use a preprocess function (hook\_preprocess\_page I guess as will fire for any pages loaded) , there use a code like this to detect mobile, then add a boolean value to page which should be TRUE if user is using mobile.
* after that in twig you will have that value, check if it is true and display your block

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


# Question
Title: Is it possible to create an auto-increment field in a content type?
If I am creating a database in MySQL, I can create an auto-increment field for a table.

But is it also possible to create an auto-increment field in a content type in Drupal 8?

# Answer
> 2 votes
There is A module called Serial, for drupal 8 it is in development version but can be downloaded and used, This module provides the same functionality as you desire.

You also can write your own module, you can set a configuration value in your module, set it to zero by default, and using hook\_ENTITY\_TYPE\_presave, increase its value and set it to your entity.

---
Tags: 8
---


# Question
Title: How to stylize the tooltip in a Bootstrap theme?
I've been requested to stylize a tooltip in a Drupal 7 bootstrap theme. I have no idea how to get one going other than hard-coding it all in the web dev tools. Is there a setting in Drupal 7 to turn on tooltips for specific images or text??

# Answer
If I understand you correctly, then you're probably after bootstrap tooltips. If your site is already using the bootstrap theme, then all you would need to do (if it's not already done) is attaching the tooltip functionality via client side javascript code, e.g.:

```
$(YOUR_SELECTOR).tooltip();

```

So if every element in your markup that should use a bootstrap tooltip has the CSS class "tooltip" that would be:

```
$('.tooltip').tooltip();

```

See the docs that I have linked above for more options for the tooltip configuration. As for the styling, there are multiple answers to that on stackoverflow:
> 1 votes

---
Tags: 7, theming
---


# Question
Title: How to programmatically reset user password
I'm trying to create a custom module for resetting the user's password.

In the following block of code I'm attempting to get the password in hash form:

```
$pass='User123@';

$autoloader =require_once(\Drupal::service('file_system')->realpath('autoload.php'));
//echo $autoloader; exit;
$request = Request::createFromGlobals();
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod', FALSE);
$kernel->boot();
$password_hasher = $kernel->getContainer()->get('password');
$newhash =  $password_hasher->hash($pass);

//echo  $newhash ; exit;

```

This is my db update code:

```
 $updatepass = \Drupal::database()->update('users_field_data')
      ->fields(array(
        'pass' => $newhash,
      ))
      ->condition('name', "$id",'=')
      ->execute();

```

Please help me understand what mistake I've made.

# Answer
> 5 votes
Just use the `setPassword()` method to update the user's password:

```
// Get user storage object.
$user_storage = \Drupal::entityManager()->getStorage('user');

// Load user by their user ID
$user = $user_storage->load($id);

// Set the new password
$user->setPassword('User123@');

// Save the user
$user->save();

```

This will take care of all the hashing for you and will trigger all the appropriate hooks for saving a user.

---
Tags: 8, users
---


# Question
Title: How to restrict file access based on file path under private directory?
I have a list of files under `sites/default/files/private/abcde/manuals/`.

I want to add restriction to the files based on certain logic which I can add in the code in a hook. The logic would be based on a parameter set in by the admin. So if the value set to allow in the admin settings form , I would like to give access to view or download files under `'sites/default/files/private/abcde/manuals/'` else would like to prevent user from accessing it.

# Answer
Requests to files in the private file directory are routed through Drupal and access logic for these requests can be added by implementing hook\_file\_download. The only argument to that hook implementation is `$uri`, which is the URI to the file. Using string comparison to see if you want to act upon this request should get you what you need.

Quoting the docs:

> If the user does not have permission to access the file, return -1. If the user has permission, return an array with the appropriate headers. If the file is not controlled by the current module, the return value should be NULL.
> 1 votes

---
Tags: 7, files
---


title: List most recents files used

text:
# Question
Title: List most recents files used
We have a **Documents** bundle which is a list of documents, and an **Accordeon** which includes the previous one.

```
NODE_PAGE
|
|--- DOCUMENTS
|
|--- ACCORDEON
|    |
|    |--- DOCUMENTS

```

With this choice, I can attach documents directly to the node or to *Accordeon* sub-elements.

How can I list the most recent documents in a view? (I have to mix file\_managed directly linked to the node and file\_managed linked to the paragraph which is linked to the node.)

Is it possible from the view setting, or do I have to alter the query with `hook_views_query_alter()`?

# Answer
Finally I choose to create a View of type File and to alter data with the `hook_views_pre_render()`. I can now do queries and other custom treatments and set the results data of my view.
> 0 votes

---
Tags: 7, views, paragraphs
---


# Question
Title: How to set views pager item size programmatically?
I want to set views pager size programmatically. I have tried below code to set pager size.

```
$view = \Drupal\views\Views::getView('english_chart');
$view->pager['items_per_page'] = 5;
$view->execute();

```

It's not working and showing this error:

ResponseText: Error: Cannot use object of type Drupal\views\Plugin\views\pager\Some as array ....

# Answer
The object returned from `$views->pager` is an object implementing `ViewsPluginInterface` and extending `PagerPluginBase`.

If you look at the methods in `PagerPluginBase` you will see the `setItemsPerPage` method.

So you should be able to do something like:

```
$view->pager->setItemsPerPage(5);

```
> 2 votes

---
Tags: views, 8
---


# Question
Title: Where to use setTrustedProxies() or how to set new trusted proxies
I need to set a trusted proxy in my installation so that secure cookie flags are set correctly.

Currently as a temporary measure i am setting the following in index.php

```
$proxies = ['122.128.0.1'];
Request::setTrustedProxies($proxies);

```

However i would like to be able to set a new trusted proxy from a settings file or module that will persist through a core update without needed to patch.

Where is the best place to specify this?

# Answer
Drupal doesn't want you to place custom code in index.php to prepare a request before it is handled by the Drupal kernel. So it was made possible for modules to implement a middleware through StackedHttpKernel.

In this case such a middleware already exists, which reads the reverse proxy addresses from settings.php and adds them as trusted proxies to the request:

Drupal\Core\StackMiddleware\ReverseProxyMiddleware::setSettingsOnRequest:

```
  $proxies = $settings->get('reverse_proxy_addresses', []);
  if (count($proxies) > 0) {
    $request::setTrustedProxies($proxies, Request::HEADER_X_FORWARDED_ALL | Request::HEADER_FORWARDED);

```

So you can simply enable this settings in settings.php:

```
$settings['reverse_proxy'] = TRUE;
$settings['reverse_proxy_addresses'] = ['a.b.c.d', ...];

```
> 5 votes

# Answer
All the other proxy settings are in `settings.php` so I think that would be the most appropriate place.

This would persist after core updates and as a new developer on boarding onto a project that is the first place I would check for this sort of configuration.
> 1 votes

---
Tags: proxies
---


# Question
Title: “Structure->Block” showing when permission is not given to user
I have user role 'Admin', who can see 'taxonomy terms' under 'Structure', I have given same permission but it is showing 'Block' and 'Views' too.

Is there any workaround in Drupal 8?

Any help would be great. Thanks

# Answer
> 2 votes
You've probably given them the *Administer blocks* and *Administer views* permission as well. Withdraw these permissions and the links should disappear.

---
Tags: 8, users
---


# Question
Title: Optional configuration and order of enable modules on profile
I have a bug or a misconfiguration I don't understand. I'm creating a profile to create new web sites with an advance configuration quickly. But I meet a bug during installation with dependencies of with some configurations.

On image style, I add a manual \`crop type than I add on the majority image style. For example, my file for image style large is:

```
langcode: fr
status: true
dependencies:
  config:
    - crop.type.crop_1x1
  module:
    - crop
name: large
label: 'Large (480×480)'
effects:
  ddd73aa7-4bd6-4c85-b600-bdf2b1628d1d:
    uuid: ddd73aa7-4bd6-4c85-b600-bdf2b1628d1d
    id: image_scale
    weight: -9
    data:
      width: 480
      height: 480
      upscale: false
  7cd03233-541d-472e-851c-de8945ee6709:
    uuid: 7cd03233-541d-472e-851c-de8945ee6709
    id: crop_crop
    weight: -10
    data:
      crop_type: crop_1x1

```

I put all images style configuration file in the directory `optional` in `config` directory. My configuration files for crop and the crop type are in the `install` directory. Despite this, when I test my installation, I have always the error message :

> Drupal\Core\Config\UnmetDependenciesException: Configuration objects provided by image have unmet dependencies: image.style.large (crop.type.crop\_1x1, crop) in Drupal\Core\Config\UnmetDependenciesException::create() (line 98 of /var/www/html/core/lib/Drupal/Core/Config/UnmetDependenciesException.php).

I have no configuration which are dependent of `image` module in `install` directory. `Image` module is always enable before `Crop` module instead of to respect dependencies. I tried to put my configuration files for crop in optional but it doesn't fix the problem, I don't know if change the order of modules in dependencies of my profile have an influence. I try without success.

I don't see where is the error in my installation.

Update: This problem happens only with default configuration of `image` module, that is `image.style.large`, `image.style.medium` and `image.style.thumbnail` which are the native configuration. I have other styles which are import later, after `crop` module is enable and configure as expected. I don't know if it's a bug of the configuration manager which try to import necessary default configuration files even if they are in optional.

# Answer
> 1 votes
My problem is a bug of the configuration system. An issue exists for this exact problem: https://www.drupal.org/project/drupal/issues/2922417

---
Tags: 8, configuration, installation-profiles
---


title: Migration configuration

text:
# Question
Title: Migration configuration
I'm setting up a migration from an URL with JSON on it.

Got the first level values without any issues. Currently I'm stuck at nested arrays which resemble something like this:

```
{   "content": [
    {
      "id": 148,
      "hardwares": [
        {
          "hwId": 16,
          "products": [
            {
              "pid": 2097,
              "productName": "ProductName1",
            },
            {
              "pid": 2100,
              "productName": "ProductName2",
            },
            {
              "pid": 2103,
              "productName": "ProductName3",
            },
            {
              "pid": 2094,
              "productName": "ProductName4",
            }
          ]
        }
      ]
    },
   ],
}

```

I have a custom content entity with a text field called Product Names, the field is a multi-value field. I've been trying to get the `productName` values and populate the field. Basically this JSON here would create one entity, and then get the value by this hierarchy:

`hardwares->products->productName`

I can't seem to grasp the usage of the sub\_process plugin and I would really appreciate any hints or any working examples.

# Answer
> 0 votes
What I did:

I defined a field entry in the source:

```
  name: hardwares
  label: 'Hardwares'
  selector: hardwares

```

In my process:

```
_products:
    plugin: sub_process
    source: hardwares
    process:
      products:
        plugin: sub_process
        source: products
        process:
          productName: productName
field_products:
    plugin: flatten
    source: '@_products'
_hwIds:
    plugin: sub_process
    source: hardwares
    process:
      hwId: hwId
field_hardware_ids:
    plugin: flatten
    source: '@_hwIds'

```

In order to get to the 2nd level of my data array, I needed to nest the sub\_process plugin. I flatten the result afterwards in order to get a numerically indexed array which resembles the multiple value field structure.

---
Tags: migrations, 8
---


title: Problem with .gitignore

text:
# Question
Title: Problem with .gitignore
I installed Drupal on ubuntu 16.04 via composer and I'm trying to implement continuous integration with Jenkins. So, I would like to be able to work from another location (for example from a Windows 10 PC), and a push of my changes must trigger a build on jenkins that updates the installation on the ubuntu machine.

I verified that the created .gitignore file is this:

```
# Ignore directories generated by Composer
/drush/contrib/
/vendor/
/web/core/
/web/modules/contrib/
/web/themes/contrib/
/web/profiles/contrib/
/web/libraries/

# Ignore sensitive information
/web/sites/*/settings.php
/web/sites/*/settings.local.php

# Ignore Drupal's file directory
/web/sites/*/files/

# Ignore SimpleTest multi-site environment.
/web/sites/simpletest

# Ignore files generated by PhpStorm
/.idea/

# Ignore .env files as they are personal
/.env

```

So after having pushed the code into my git repository, I noticed that various folders are missing such as the "core" folder and I do not think that the project can work if the "core" folder is missing.

Do I simply have to update the .gitignore file? Or is there anything I need to understand better about the "modus operandi" in Drupal?

# Answer
Your `core` directory is included in your .gitignore. I don't know which strategy you want follow but, like you have `vendor`, `modules/contrib`, `themes/contrib`, etc, you should launch `composer install` to download your core and contrib modules/themes in your workflow to complete your installation (your composer.lock should be commit).

If you prefer commit your modules, themes, profiles, libraries, core, etc., because some parts of your content are not managed by composer or because you don't want risk a bug of network during the build, you should remove these directories from your .gitignore and add them in your git repository.
> 3 votes

---
Tags: 8, version-control
---


# Question
Title: Behavior of taxonomy-term classified paths
We have customer who insists that there is a setting/method that will order the listing-page for taxonomy attributed event-type by date ascending. My exploration has lead me to the .../admin/config/search/path/patterns settings in Taxonomy term paths. We are using the default: \[term:vocabulary\]/\[term:name\].

However I can not find a setting that will allow for date-ordering. Is there such a setting? The behavior of the site is that the ordering is done by the initial-post date.

I've advised that this can be done w/ View.

# Answer
> 0 votes
`/admin/config/search/path/patterns` is an admin page for the module Pathauto, URL alias - Patterns. And the default pattern for Taxonomy terms just happens to be `[term:vocabulary]/[term:name]`.

You can also see that each "vocabulary" of taxonomy terms can have it's own pattern.

To confirm if Views is handling the display of any of the taxonomy terms pages we need to find a view that takes over the default Taxonomy term path and is already enabled. Meaning, the modules View and Views UI must be enabled. If only Views is enabled, enabling Vies UI at this point makes this easier, plus we will need it later to change the "Sort criteria". With install of the of the Views module the `Taxonomy term` view is created. This view has a path of 'taxonomy/term/%' the same as the Taxonomy modules default path and when the view is enabled it overrides the Taxonomy module's handling of the display of the taxonomy terms pages.

For a final conformation that this taxonomy vocabulary's term pages are being handled by views lets look at the final HTML that is out generated.

For a views generated page you will see a few key classes in the content's wrapping elements (unless heavenly custom themed).

```
<div class="content">
  <div class="view view-taxonomy-term view-id-taxonomy_term view-display-id-page view-dom-id-36a8...">
    <div class="view-content">

```

vs the generated page you will see from the taxonomy module.

```
<div class="content">
  <div class="term-listing-heading"><div id="taxonomy-term-1" class="taxonomy-term vocabulary-tags">
    <div class="content">

```

**Bonus tip**: The classes added by the view let us know the machine names of the view being used. `view-id-taxonomy_term` tell you the "taxonomy\_term" view is using used, while `view-display-id-page` tell you it is the "page" display in current view.

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


# Question
Title: How do I load a library using xautoload and libraries?
I am trying to load the facebook SDK (drupal 7) but I am getting the error

```
Error: Class 'Facebook\Facebook' not found in
FbPageSyncProcessSubmission::fbpagesync_facebook_sdk_initialize() (

```

My method

First download the facebook api Facebook API as recommended

```
cd web/sites/all/libraries
mkdir fbpagesync
composer require facebook/graph-sdk

```

Install xautoload

drush dl xautoload && drush en -y xautoload

In my custom module declare the library

```
function fbpagesync_libraries_info() {
  return [
    'fbpagesync' => [
      'name' => 'PHP SDK for Facebook APIs',
      'vendor url' => 'http://developers.facebook.com/',
      'download url' => 'https://github.com/facebook/php-graph-sdk/master.zip',
      'xautoload' => function ($adapter) {
       $adapter->composerJson('composer.json');
     },
      'path' => 'vendor/facebook/graph-sdk/src/Facebook',
      'version arguments' => [
      'file' => 'vendor/facebook/graph-sdk/src/Facebook/Facebook.php',
      'pattern' => "/const VERSION = '([\d.]*(?!-dev$))/",
      'lines' => 60,
    ],
  ],
  ];
}

```

It looks OK in libraries\_load/libraries\_detect

```
array (
 'name' => 'PHP SDK for Facebook APIs',
 'vendor url' => 'http://developers.facebook.com/',
 'download url' => 'https://github.com/facebook/php-graph-sdk/master.zip',
 'xautoload' =>
   Drupal\xautoload\Libraries\SerializableClosureWrapper::__set_state(array(
   'closure' =>
   Closure::__set_state(array(
  )),
 'moduleName' => 'fbpagesync',
 'libraryName' => 'fbpagesync',
)),
'path' => 'vendor/facebook/graph-sdk/src/Facebook',
'version arguments' =>
  array (
  'file' => 'vendor/facebook/graph-sdk/src/Facebook/Facebook.php',
  'pattern' => '/const VERSION = \'([\\d.]*(?!-dev$))/',
  'lines' => 60,
 ),
'info type' => 'module',
'module' => 'fbpagesync',
'machine name' => 'fbpagesync',
'download file url' => '',
'library path' => 'sites/all/libraries/fbpagesync',
'version callback' => 'libraries_get_version',
'files' =>
array (
),
'dependencies' =>
array (
),
'versions' =>
array (
),
'integration files' =>
array (
),
'callbacks' =>
array (
  'info' =>
array (
  0 => 'libraries_prepare_files',
),
'pre-detect' =>
array (
),
'post-detect' =>
array (
  0 => 'libraries_detect_dependencies',
),
'pre-dependencies-load' =>
array (
),
'pre-load' =>
array (
),
'post-load' =>
array (
),
),
'post-load integration files' => false,
'installed' => true,
'version' => '5.6.3',
'loaded' => 0,
)

```

The calling code is

```
use Facebook\Facebook;

...

public static function fbpagesync_facebook_sdk_initialize($reset = FALSE) {
 $settings = variable_get('fbpagesync_settings', []);
 $facebookInit = new Facebook([
    'app_id' => $settings['app_id'],
    'app_secret' => $settings['app_secret'],
    'default_graph_version' => 'v2.2',
  ]);
}

```

# Answer
> 0 votes
It was calling the wrong composer.json. Facebook api has it's own.

The fix is

```
$adapter->composerJson('vendor/facebook/graph-sdk/composer.json');

```

---
Tags: 7
---


# Question
Title: How to render the 'actions' section of a form in twig template?
given a form that is built like the following:

```
public function buildForm(array $form, FormStateInterface $form_state)
{
   $form['#theme'] = 'mymodule_testForm';
   $form['actions']['#type'] = 'actions';
   $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => t('submit'),
      '#button_type' => 'primary',
   );
   return $form;
}

```

How do I access the submit button in my twig template?

# Answer
Hat tip to Clive who already answered the question as a comment:

```
{{ form.actions}}

```

To render the rest of the form, you can do something like `{{ form | without('actions') }}`

So you whole code will look something like this:

In my\_module.module:

```
/**
 * Implements hook_theme().
 */
function my_module_theme($existing, $type, $theme, $path) {
  $result = [
    'custom_form' => [
      'render element' => 'form',
      'template' => 'custom-form',
    ],
  ];

  return $result;
}

```

And in custom-form.html.twig:

```
<div class="col-md-8">
    <h3>Form</h3>
    {{ form | without('actions') }}
</div>
<aside class="col-md-4">
    <h3>Action</h3>
    {{ form.actions }}
</aside>

```

For more reading:

Hope that helps!
> 1 votes

---
Tags: forms, 8, theming
---


# Question
Title: Drupal custom module code working differently for logged in users and anonymous users
I have the below simple if else condition for a custom module form page in buildForm method for recommendation submission. I would like my form to be displayed to all user who visit for the first time and submits and cannot submit again from the same url. If the url is used again it should just display the thank you message(if already submitted). The below code wrks perfectly if the user is logged in. Like if the user is logged in, he comes and submit, thank you message is displayed everything is saved in DB correctly. The problem comes when anonymous user comes. The page loads as expected. But after filling up the details and submit button is clicked. It reloads and the same form is displayed again(instead of the thank yo message) and then if I submit again it displays validation errors even though the fields are there and gives the thank you message. Can anyone explain me why its behaving differently for logged in and anonymous users.

```
    public function buildForm(array $form, FormStateInterface $form_state)
    {
       if($this->CheckRecommendationStatus())
       {
          $form = array();
          $form['form_label'] = [
          '#type' => 'processed_text',
          '#text' => t('<h3<strong>Thank you already submitted</h3>'),
          ];
        }
        else if($this->validateUrl())
        {
           $form = array();
           //it will have controls and submit button.if submit is clicked those values will be saved
        }
        return $form;
     }
     //This below method check the Database whether already the submission is made or not
     public function CheckRecommendationStatus()
     {
           $this->setUniqueIdentifier(htmlspecialchars($_GET["rec"]));
           $query = \Drupal::database()->select('m_tablename', 'mr');
           $query->fields('mr',array('id'));
           $query->condition('mr.column_name',$this->getUniqueIdentifier());
           $query->range(0,1);
           $results = $query->execute()->fetchAll();
           return $results;
     }

```

# Answer
This sounds like a caching issue. Check the cache api and make sure to set the `$form['#cache']` appropriately.

When the anonymous user submits the form, it's submitted fine, but when the form loads the second time Drupal doesn't know that it should not be serving the original cached form.

You can quickly confirm that it is a caching issue by set the form to not be cached like:

```
$form['#cache'] = [
  'max-age' => 0,
];

```
> 1 votes

---
Tags: 8
---


# Question
Title: Account creation emails not being sent but other emails are
I have a site that was upgraded from D6 to D7 and is now hosted on Pantheon. I'm using the SMTP module and SendGrid for deliverability. The "require email verification when a visitor creates an account" setting is checked. When someone registers as a new user, the message saying that an email has been sent to their account is displayed on screen. However, neither watchdog nor Maillog shows any evidence that an email was sent, and no email is received.

Other emails, including password reset, Webform emails, Comment Notify, etc. all are sent and received as expected.

What could be causing the new user email not to be triggered?

# Answer
> 1 votes
I would create a clean Drupal site on Pantheon and configure just SendGrid. Do all emails get sent as expected from the new site? If so, it's likely that there is some custom code running on the problematic site calling hook\_mail\_alter or altering the normal mail handling in some other way.

You'll also find some great tips to help troubleshoot email issues in http://www.webomelette.com/drupal-modules-debug-emails

# Answer
> 0 votes
If you have the profile2 module installed, it automatically disables sending of registration emails in profile2\_form\_before\_user\_register\_submit\_handler() and then re-enables them in profile2\_form\_after\_user\_register\_submit\_handler(). Depending on your settings, and other modules installed (logintoboggan in particular), the second function may never run, preventing email from being sent.

---
Tags: emails, users
---


title: Error when trying to delete user

text:
# Question
Title: Error when trying to delete user
I installed the heartbeat module to track user activities on my website. It took me hours to configure it but everything seemed to be working as I wanted until I tried to delete a test user from the website. I was wondering if anyone is familiar with this error.

> PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table 'etuncel\_drup4.drup\_flag\_content' doesn't exist: DELETE FROM {flag\_content} WHERE (content\_type = :db\_condition\_placeholder\_0) AND (content\_id IN (:db\_condition\_placeholder\_1, :db\_condition\_placeholder\_2, :db\_condition\_placeholder\_3, :db\_condition\_placeholder\_4)) ; Array ( \[:db\_condition\_placeholder\_0\] =\> heartbeat\_activity \[:db\_condition\_placeholder\_1\] =\> 20097 \[:db\_condition\_placeholder\_2\] =\> 20098 \[:db\_condition\_placeholder\_3\] =\> 20101 \[:db\_condition\_placeholder\_4\] =\> 20102 ) in HeartbeatFlagPlugin-\>activityRemoved() (line 106 of /home/public\_html/sites/all/modules/heartbeat/modules/heartbeat\_plugins/includes/heartbeatflagplugin.inc)

# Answer
> 0 votes
Turns out there is an error with the module but someone developed a patch for it.

Here;

https://www.drupal.org/project/heartbeat/issues/2102743

---
Tags: 7, flags, heartbeat
---


# Question
Title: How can I add jQuery to DOM element through drupal.behaviours?
On my site on the navigation panel I have a dropdown language switcher. (Dropdown Language Switcher module). I need to modify the js file and show the message to the user after he switched the language. What is the right way to modify js file?

```
(function ($, Drupal) {
'use strict';

Drupal.behaviors.dropdownLanguagesSelector = {
  attach: function(context, settings) {
   $('.dropdown-language-item .active-language', context).once('dropdown-language-selector')
    .click(function(e) {
      var $wrapper = $(this).closest('.dropbutton-wrapper');
      if ($wrapper.length > 0) {
        e.preventDefault();
        e.stopPropagation();
        $wrapper.toggleClass('open');
      }
    });
  }
};
})(jQuery, Drupal);

```

Language switcher HTML looks like following:

```
<div class="dropbutton-widget">
 <ul class="dropdown-language-item dropbutton">
  <li class="fr dropbutton-action">
   <span class="language-link active-language" hreflang="fr">FR</span></li>
  <li class="dropbutton-toggle"></li>
  <li class="en dropbutton-action secondary-action"></li>
  <li class="de dropbutton-action secondary-action"></li>
 </ul>
</div>

```

I am trying to attach following event:

```
$('.secondary-action').click(function(){
   alert(Message!);
})

```

# Answer
> 2 votes
Here's a skeleton of how you can add functionality to elements using Drupal.behaviors.

```
(function ($, Drupal) {
  'use strict';

  // Create a new function for each element the file attaches
  // handlers to. In this case, $(.secondary-action')
  function secondaryEventListener(context) {
    // Find the elements, ensure that any internal code is executed
    // a single time using $.once(), then loop through the found elements
    // using $.each()
    $(context).find('.secondary-action').once('secondary-event-listener').each(function () {
      // $(this) refers to the current instance of $('secondary-action')
      $(this).click(function () {
        alert("clicked");
      });
    });
  }

  Drupal.behaviors.someArbitraryButUniqueKey = {
    attach: function(context, settings) {
      // Call your function containing the handlers
      secondaryEventListener(context);
    }
  };
}(jQuery, Drupal));

```

---
Tags: 8, javascript
---


# Question
Title: How to not have "-None-" as default in the entity reference display widget
I spend hours to figure this out but no result. I want to auto-populate a field using entity references and views.

* A field has a user entity reference
* Using filters, I made a view narrowing down the results to 1 (the result I want to populate the field with)
* I linked the field with the search result using "Views : ..." as a reference method.

The only thing that's preventing me from succeeding is that the widget always shows 2 results instead of 1 (SEE SCREENSHOT): \- None - (Default) My result (Dreece in the screenshot)

so the "-None-" is preventing me from succeeding to do the auto-populate.

Any way to (NON PROGRAMMATICALLY) ommit the "-None-" (or put it as the second option)? \- By configuring the View \- By using View arguments?

Many thanks in advance!!!

# Answer
As soon as you make this field required it will have no `- None -` option anymore.
> 3 votes

# Answer
You can use function hook\_element\_info\_alter D7:

```
function yourmodule_element_info_alter(array &$types) {
  if (isset($types['select'])) {
    $types['select']['#process'][] = 'remove_element_na';
  }
}

function remove_element_na($element) {
  if (isset($element['#field_name']) && $element['#field_name'] == 'field_name') {
    unset($element['_none']);
  }
  return $element;
}

```
> 1 votes

---
Tags: views, entities
---


# Question
Title: Drupal EU Cookie Compliance module conflict with theme JQuery
When I first installed the module, it'd only appear in admin pages.

After some investigation, I discovered the cause was some sort of conflict with my themes jquery: jquery-1.11.2.min.js.

If I disable it, the module works. If I enable it, the module doesn't work in non-admin pages.

The error message I'm getting is

```
TypeError: $.cookie is not a function

```

I think the module is using a older version of jquery, and that API has since been deprecated in newer version. I can't update the the modules jquery without modifying the module itself, nor can I downgrade my theme's jquery.

How do I have the module strictly use its own jquery and not use my theme's (if that's the cause of the problem)?

# Answer
> 0 votes
You can use https://www.drupal.org/project/jqmulti to manage multiple versions of jQuery on your site

---
Tags: 7, javascript, cookies
---


title: Theme shown without styles

text:
# Question
Title: Theme shown without styles
I executed the config:import: import successfully, but now it seems that the theme settings are no longer found. The site is now seen as in the attached image

How can I solve the problem?

Note: I don't use bootstrap theme. I imported the configuration I had previously exported from another machine on Ubuntu. This problem is on a Windows machine.

# Answer
1. Double check and confirm that the theme files are exactly were they should be.
2. Make sure the /files directory exists and writable (NOT 777 permissions though)
3. Double check and confirm that Drupal can access the files directory via configurations
4. Clear the Drupal cache

If the theme is using external CSS or JavaScript files, make sure they are accessible. (most cases its an internet connection especially for front-end frameworks like Bootstrap)
> 0 votes

---
Tags: 8, theming, configuration
---


# Question
Title: How do I change the machine name of a field once it's been created
I spaced out while typing the field name an now the machine name is not what I wanted it to be. I know it's just an annoyance. but I'm wondering if there is some way to alter the machine name of a field once it is created.

I suppose this leads me into the second part of my question. if I created a field, and it is no longer being used, how do I go about deleting it, does this have to be done from the database, or can it be done somewhere in the UI.

# Answer
In short, you can't change the machine name. In theory, it's obviously possible, but it will require quite a bit of messing with the database. If you've only just created the field, it's far easier to remove it and create a new one.

The basics would be to rename all entries on `field_config` and `field_config_instance`, but as soon as you start using the field, the machine names get's stored in a hundred different places. *Views* config, *Panels* config, *Features* and more, and by then, changing it is *not* fun.

Deleting fields can be done on: `admin/structure/types/manage/[machine_name_of_content_type]/fields`, which you can reach through the "*Manage fields*" tab on any content type.
> 16 votes

# Answer
My procedure is to use drush to clone the field first, then copy the field data with DB queries into the new field table. After I verify the contents of the cloned field, I delete the original field.

I do it this ways because I think the drush method of cloning fields will always be at least as reliable as any cloning code I might craft myself, the data copy query is pretty simple, and I get to check the new field before deleting the original.

1. `drush field-clone field_my_field field_my_field_clone`
2. Insert rows into `field_my_field_clone`, e.g., `INSERT field_my_field_clone SELECT * FROM field_my_field;`
3. Verify the contents of `field_my_field_clone`.
4. Delete the field using the UI, e.g., `admin/structure/types/manage/my-content-type/fields`
> 17 votes

# Answer
In Drupal 7, you can use the Field Rename module. In Drupal 6, you can use CCK field rename module.
> 10 votes

# Answer
I have written an update script, which actually creates a new field and instance with the new machine name, copies all the old field data to the new one and lastly deletes the old instance.

```
// Set variables
$old_name = 'field_old_name';
$new_name = 'field_new_name';
$entity_type = 'node';
$bundle = 'page';

// Get old field info
$old_field = field_info_field($old_name);

// Create new field
$new_field = $old_field;
$new_field['field_name'] = $new_name;

if (!field_info_field($new_name)) {
  field_create_field($new_field);
}
else {
  field_update_field($new_field);
}

// Get old field instance
$old_instance = field_info_instance($entity_type, $old_name, $bundle);
$new_instance = $old_instance;
$new_instance['field_name'] = $new_name;

if (!field_info_instance($entity_type, $new_name, $bundle)) {
  field_create_instance($new_instance);
}
else {
  field_update_instance($new_instance);
}

// Migrate old fields' data to the new ones
$field_data = db_select('field_data_' . $old_name, 'old')
  ->fields('old')
  ->condition('entity_type', $entity_type)
  ->condition('bundle', $bundle)
  ->execute();

while ($data = $field_data->fetchAssoc()) {
  $data_new = array();
  foreach ($data as $column => $value) {
    $column = str_replace($old_name, $new_name, $column);
    $data_new[$column] = $value;
  }
  db_insert('field_data_' . $new_name)
    ->fields($data_new)
    ->execute();
}

// Migrate old fields' revision data to the new ones
$field_revision = db_select('field_revision_' . $old_name, 'old')
  ->fields('old')
  ->condition('entity_type', $entity_type)
  ->condition('bundle', $bundle)
  ->execute();

while ($revision = $field_revision->fetchAssoc()) {
  $revision_new = array();
  foreach ($revision as $column => $value) {
    $column = str_replace($old_name, $new_name, $column);
    $revision_new[$column] = $value;
  }
  db_insert('field_revision_' . $new_name)
    ->fields($revision_new)
    ->execute();
}

// Delete old instance
field_delete_instance($old_instance);

// Purge fields
field_purge_batch(1000);

```
> 6 votes

# Answer
I just had to do this, and found it to not be too difficult, but my site is fairly simple.

Try this:

1. Create a new field with the proper name.
2. Run these queries in MySQL:

```
INSERT INTO field_data_[NEW MACHINE NAME] (entity_type, bundle, deleted, entity_id, revision_id, language, delta, field_fabric_color_pattern_tid) SELECT cf.* FROM  `field_data_[OLD MACHINE NAME]` cf

```

```
INSERT INTO field_revision_[NEW MACHINE NAME] (entity_type, bundle, deleted, entity_id, revision_id, language, delta, field_fabric_color_pattern_tid) SELECT cf.* FROM  `field_revision_[OLD MACHINE NAME]` cf

```

(swap out \[NEW MACHNIE NAME\] and \[OLD MACHINE NAME\] with `field_your_field_names`)

3. Update any views involved to use the new field, and any other modules that point to that specific field (this is where things might get ugly if your site is complicated). You can see any views that use your old field here: `/admin/reports/fields/views-fields`
4. Clear site cache
> 3 votes

# Answer
// Change the field storage table names. Here we are altering the name of the old table with new name.

```
db_rename_table($data_table_name, 'field_data_' . $new_field_name);
db_rename_table($revision_table_name, 'field_revision_' . $new_field_name);

```

// Change the field names in the field\_config and field\_instance\_config tables.

```
db_update('field_config')
  ->fields(
    array(
      'field_name' => $new_field_name,
    )
  )
  ->condition('field_name', $field_name, '=')
  ->execute();

db_update('field_config_instance')
  ->fields(
    array(
      'field_name' => $new_field_name,
    )
  )
  ->condition('field_name', $field_name, '=')
  ->execute();

```
> 2 votes

# Answer
With the drush field-clone answer above you can do the last MySQL step with Drush also (D7 example):

```
drush sql-query "INSERT field_data_field_my_field_clone SELECT * FROM field_data_field_my_field"

drush sql-query "INSERT field_revision_field_my_field_clone SELECT * FROM field_revision_field_my_field"

```
> 1 votes

# Answer
If you don't want to fiddle around in mysql you could try a drush script I wrote called Field value copy.

You will need to setup your new field first and then call

```
drush fieldcopy OLDFIELDNAME NEWFIELDNAME

```

This will move existing data to the new field once done delete the old field.
> 0 votes

# Answer
The db\_change\_field() function may help you.
> -1 votes

# Answer
Export the SQL file of your database, use the command line `sed` to replace all occurrences of the term to change, and re-import your database.
> -3 votes

---
Tags: entities, database, nodes
---


# Question
Title: Metatag images don't work anymore after updating
I was on Drupal 8.5.x and Twitter cards and Open Graph on Facebook were displaying correctly.

After updating to Drupal 8.6.1, the images don't display anymore. The others data (title, description, url...) are OK, it's juste an images problem.

So I've checked the tokens used by the Metatag module and they are the same I used in Drupal 8.5.x without any problem.

The token I use for images is : \[node:field\_image\_article:entity:field\_image\] Indeed, in my content type, I use a field named "Image article" that contain several fields (title, author, licence...) including an "Image" field where I upload the image.

When I look at the source code of my webpages, I have this :

```
<meta name="twitter:image" content="https://example.com" />
<meta property="og:image" content="https://example.com" />

```

instead of the complete URLs of the images...

Does anyone know how to solve this ? Thx.

# Answer
This issue is documented here : https://www.drupal.org/project/metatag/issues/2994433

For the moment (21/09/18), there are two solutions :

* add :entity:url at the end of the token
* downgrade to Metatag 1.5 instead 1.6

Using first solution, change \[node:field\_image\_article:entity:field\_image\] for \[node:field\_image\_article:entity:field\_image:entity:url\] did the job for me.
> 3 votes

---
Tags: 8, tokens, meta-tags
---


title: Retrieve author / owner of term

text:
# Question
Title: Retrieve author / owner of term
I am loading a term and trying to get the author or owner of the term, however I can not see any function under the Term Class

On the other hand I can see the translation author being present on the edit page.

Any way to retrieve author for Term?

# Answer
> 1 votes
This is not part of Drupal core. There's a module which provides this capability for D7, Taxonomy Term Author Info but it's not been officially ported to D8 although there is an unofficial port at https://github.com/worthingtonlibraries/term\_authoring\_info

# Answer
> 1 votes
As Alfred Armstrong states this is not possible as part of Drupal core as the default fields for Taxonomy doesn't include a User field.

However, in D8 Taxonomy is just another entity type so it would be a fairly simply process to add a new field at Structure \>\> Taxonomy \>\> {{ Name }} \>\> Manage fields with the type being Reference \>\> User

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


title: How do I use a field summary in a view?

text:
# Question
Title: How do I use a field summary in a view?
I'd like to make a Drupal 7 view which displays nodes using the following behavior:

1) Show the body summary if it is populated. 2) Never show a trimmed version of anything. 3) If the body summary is empty, show the actual body. 4) If the body summary is not empty, display a "read more" link. 5) If the full body was displayed, don't display a "read more" link.

I've got this entirely working using a separate field for the summary (which may be what I end up with) but I'd hoped to use the body summary instead. As far as I can tell the only way to access the body summary in a view is to use the "summary or trimmed" formatter in the field display, which violates #2.

I looked for modules, and all I found was "Smart Trim" which appears to do the opposite of what I want.

Suggestions?

# Answer
I think this is a good example for using custom formatters.

I Recommend you to use the custom formatters module as you cant get a fast result, but if you think this is useful, you should check the Field Formatter API to make more complex sollutions.

Install the module, and import this example:

```
$formatter = new stdClass();
$formatter->disabled = FALSE; /* Edit this to true to make a default formatter disabled initially */
$formatter->api_version = 2;
$formatter->name = 'test_body';
$formatter->label = 'test body';
$formatter->description = '';
$formatter->mode = 'php';
$formatter->field_types = 'text_with_summary';
$formatter->code = '$output = "";
foreach ($variables[\'#items\'] as $item) {
  if ( $item[\'summary\']) {
    $output = $item[\'summary\'];
  }else{
     $output = $item[\'value\'];
  }
}
return $output;';
$formatter->fapi = '';

```

it doesn't do all the job, but i think it can be enough for you to complete it.

Then go to your view and select the formatter for the body field.
> 4 votes

# Answer
What about using Rules... create a hidden field that would be used in the view, and use rules to automatically copy the contents of the summary to the new field when the content is created. Not sure if Rules can do that with a summary, but might be worth looking into.
> 2 votes

# Answer
Following is the behaviour of the Body field in a view when the formatter is set to "Summary or Trimmed"

1) Display Summary if it is present 2) If Summary is not present, display trimmed version of body.

In your case since you do not need trimming for even the body, you can set the trim length to a very high value.

To implement the "Read More" link you can create a template file for body field in the view and implement the required logic. Here is the format of the template name that needs to be created views-view-field------body.tpl.php. The exact name of the template name can be found in the view configuration.

Advanced -\> Theme: Information
> 2 votes

# Answer
You can use hook\_views\_query\_alter() for that. Create a small module for it.

Some examples are listed here: https://api.drupal.org/api/views/views.api.php/function/hook\_views\_query\_alter/7

You can alter the query to use field\_body.body\_summary table instead of field\_body.body\_value. If that has a value it will be returned. This will make your field empty (returns NULL) if there is no explicit summary for that node. Then you can use the textfield in no results behaviour to display the full body.

This can also be done with a views php field by the way, by running db\_query() from that one on that field\_body.body\_summary tablerow.

It should be something like this if you use php field. You need a hidden nid field then and replace your body-field with this php-field.

```
<?php
$result = db_query('SELECT f.body_value, f.body_summary FROM {field_data_body} f WHERE f.entity_id = :nid', array(':nid' => $row->nid));

foreach ($result as $record) {
  if ($record->body_summary) {
    return $record->body_summary;
  }
  else {
    return $record->body_value;
  }
}
?>

```
> 2 votes

# Answer
To create a summary only formatter within a view, make a custom module, add this code:

```
/**
 * Implements hook_field_formatter_info().
 */
function YOURMODULE_field_formatter_info() {
  return array(
    'summary_only' => array(
      'label' => t('Summary Only'),
      'field types' => array('text_with_summary'),
    ),
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function YOURMODULE_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  // Go through each item and return only the summary value.
  foreach ($items as $delta => &$item) {
    switch ($display['type']) {
      case 'summary_only':
        $element[$delta] = array('#markup' => $item['summary']);
        break;
    }
  }

  return $element;
}

```

Then in your view, select the Summary Only formatter on your Text w/ Summary field = success.
> 1 votes

# Answer
The easiest way is to add the field, select "Rewrite results" and add the token \[body-summary\]
> 0 votes

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