# Question
Title: How to show a block on the user profile page but not the user edit page?
I have added a block to a region and set it so that it shows on user profile pages.

However, I want the block to be displayed only on the profile pages, not on the profile edit pages.

Is that possible?

# Answer
> 3 votes
First, enable the PHP filter module and give yourself permissions to use PHP in order to input PHP on the Block visibility settings page.

On the Block visibility settings page, you can check for an argument like this:

```
<?php
if(arg(0) == 'user' && arg(2) != 'edit' )
return true;
else
return false
?>

```

Also, see my answer on Stack Overflow.

# Answer
> 0 votes
These days there is another alternative available ... ***which doesn't require the PHP filter to be enabled*** (which you should try to avoid whenever possible) ... Just use the Rules block visibility module. Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.
>
> Need to show a block only for users registered more than a month ago?
>
> Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
>
> What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules "***check the path of the current page***" (so that the block is only shown on your pages with a path that **starts with** "`user/`", but not on those pages that have a path **ending with** "`/edit`").

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?". It includes a Rules Component (in Rules export format), which you should replace by this variation of it to make it match your specific question):

```
{ "rules_block_visibility_show_on_selected_profile_pages" : {
    "LABEL" : "Show block on selected profile pages",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "AND" : [
          { "text_matches" : {
              "text" : [ "site:current-page:path" ],
              "match" : "user\/",
              "operation" : "starts"
            }
          },
          { "NOT text_matches" : {
              "text" : [ "site:current-page:path" ],
              "match" : "\/edit",
              "operation" : "ends"
            }
          }
        ]
      }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

```

Also, if you'd replace the 2nd Rules Condition in the above Rules Component with something using an appropriate regular expression, you could even further refine it, to check for something like "`user/uid/edit`", whereas `uid` corresponds with some user's uid, and so that the block would be shown anyway on pages with a path like "`user/with/some/other/path/edit`".

# Answer
> 0 votes
On Drupal 8, this is possible to be done with the Block Exclude Pages module. You would set it like this:

```
/user
/user/*
!/user/*/*

```

This would cause the block to be displayed on the regular user profile page (www.example.com/user, or www.example.com/user/5), but not on www.example.com/user/5/edit.

This module establishes the (!) sign as a mark for denying access on a given rule.

---
Tags: 7, blocks, users
---


# Question
Title: How to create responsive list items using bootstrap theme
I am using bootstrap theme. I am trying to create responsive list items. When viewing the page in tablet, laptop, desktop, I would like to see items in two columns. When viewing the page in mobile, list should display in a single column. I entered the below code in body field but it is not working for me. I googled for some bootstrap classes but I could not find anything specific. Can you please advise how I can write the code to create responsive list items?

```
<table>
<tr> <td class = "col-lg-6 col-md-6 col-xs-12 col-sm-6">
<ul>
<li>Probate Problems</li>
  <li>Title Issues</li>
  <li>Foreclosure</li>
  <li>Liens</li>
  <li>Judgements</li>
  <li>Code Violations</li>
  <li>Job Transfer</li>
</ul></td>
<td class = "col-lg-6 col-md-6 col-xs-12 col-sm-6">  <ul>
  <li>Mold</li>
  <li>Divorce</li>
  <li>Tenants Issues</li>
  <li>Behind on Taxes</li>
  <li>Fire Damage</li>
  <li>Foundation Problems</li>
  <li>Run-down Properties</li>
</ul></td></tr>

</table>

```

# Answer
You might need to use the Bootstrap column classes with divs instead of table elements, inside of a "row" element, which must be inside a "container" element:

```
<div class="container">
<div class="row">
  <div class="col-lg-6 col-md-6 col-xs-12 col-sm-6">
    <!-- Your first column goes here -->
  </div>
  <div class="col-lg-6 col-md-6 col-xs-12 col-sm-6">
    <!-- Your second column goes here -->
  </div>
</div> <!-- End row -->
</div> <!-- End container -->

```

There is more information about using the Bootstrap grid system in the main Bootstrap page.
> 1 votes

---
Tags: theming
---


# Question
Title: Content in website does not show under the right website name
I have created the contents,

And I want the content should be display like www.kvamsdanl.no.

But It was displaying like www.kvamsdanl.no/node/3(or with one of these numbers 1 , 2 or 5).

How do I achieve this thing ?

Please anyone help me to sort out this issue?

# Answer
> 1 votes
Looks like you have removed the default front page settings. Please head over to /admin/config/system/site-information and add node/3 as default front page. Let me know how you go.

---
Tags: nodes
---


# Question
Title: How to clone a content type and all nodes related
My site is using Ubercart, so now I want to use Commerce module instead, the problem now is Product content type, when I turn off all Ubercart modules, Product content type will be disabled.

I have more than 1000 nodes (Product content type), so now how to clone Product content type and moving all nodes to new content type?

Thank so much.

# Answer
> 1 votes
Drupal commerce stores product in a different way than ubercart. You best bet would be to export product in CSV format using something like Views data export and reimport it to Drupal commerce using Feeds and Commerce feeds

---
Tags: commerce, ubercart
---


title: How do I make a page-specific .tpl?

text:
# Question
Title: How do I make a page-specific .tpl?
I have a global module that has several .tpl files.

I would like to alter these files, but only have the alterations appear on one particular page (or Node Template).

I know I can duplicate the existing .tpl files and place them in my theme directory to overwrite the global .tpl files, but how would I go about creating .tpl files that only get picked up when a particular page is viewed?

Eg, something like:

`/sites/mysite.com/themes/custom/mytheme/templates/gallery.tpl`

and then, for the 'About us' page:

`/sites/mysite.com/themes/custom/mytheme/templates/about-us-page-gallery.tpl`

# Answer
With theme hook suggestions:

```
function MYMODULE_preprocess_page(&$vars) {
  if (some_contextual_condition()) {
    $vars['theme_hook_suggestions'][] = 'page__about_us_gallery';
  }
}

```

The above will correspond to a template file in your theme named *page--about-us-gallery.tpl.php*
> 4 votes

# Answer
> but only have the alterations appear on one particular page (or Node Template).
>
> ...
>
> how would I go about creating .tpl files that only get picked up when a particular page is viewed?

Based on the above, I'm assuming these are all nodes. If so,

```
node--85.tpl.php

```

Where `85` is the nid.

This is built in. Just copy `node.tpl.php`. Inside your theme, paste it and rename each copy with the correct `nid`. Make sure that there are 2 dashes `--` between `node` and `nid`

---

This seems to be a similar question, Template page--node--\<id\>.tpl.php not working and there's some debugging things in the comments. Just in case.
> 1 votes

# Answer
If you don't want to get your hands dirty and want to achieve this functionality using a module, context module is your best bet.

```
Context UI provides an administrative interface for managing and editing Contexts. It is not necessary for the proper functioning of contexts once they are built and can be turned off on most production sites.

```

```
Context layouts provides a formalized way for themes to declare and switch between page templates using Context. It is a continuation of an old Drupal themer's trick to switch to something besides the standard page.tpl.php file for a variety of special case pages like the site frontpage, login page, admin section, etc.

```
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Include multiple blocks in one responsive menu?
It would be really handy to include not just one menu in a responsive dropdown menu, but also the user login block, the main menu etcetera. Is there a way to do that? I have tried several responsive menu modules, but it seems as though I always end up with several different dropdown menus. I only want one (for all).

# Answer
> 0 votes
You may want to investigate Mega menu options.

http://megadrupal.com/blog/7-mega-menu-modules-for-drupal

I've used OM Maximenu before when I wanted a ton of content on the dropdown:

https://www.drupal.org/project/om\_maximenu

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


title: Automatically add node to menu

text:
# Question
Title: Automatically add node to menu
How can I automatically create a menu link for a new node in Drupal 8?

# Answer
You can use a deriver class for this.

## In your `foo.links.menu.yml` file

```
entity.node.canonical:
  deriver: '\Drupal\foo\Plugin\Deriver\FooMenuLinkDeriver'
  route_name: entity.node.canonical

```

## In `Drupal\foo\Plugin\Deriver\FooMenuLinkDeriver`

```
class FooMenuLinkDeriver extends DeriverBase implements ContainerDeriverInterface {
  public function getDerivativeDefinitions($base) {
    $plugin_definitions = [];
    foreach (Node::loadMultiple() as $nid => $node) {
      $plugin_definitions[$nid] = $base;
      $plugin_definitions[$nid]['route_parameters']['node'] = $nid;
      $plugin_definitions[$nid]['title'] = $node->label();
    }
    return $plugin_definitions;
  }

```
> 1 votes

# Answer
As far as I know you will need a custom module implementing `hook_entity_presave` or `hook_entity_insert`

`hook_entity_insert` would be called only when a NEW node is created `hook_entity_presave` would be called any time a node is saved/updated

```
<?php
use \Drupal\Core\Entity\EntityInterface;
use \Drupal\menu_link_content\Entity\MenuLinkContent;

function MODULE_NAME_entity_insert(EntityInterface $entity){

    if ($entity->getEntityType()->id() == 'node') {
        $title = $entity->getTitle();
        //OR
        //$title = $entity->title->value;
        $nid = $entity->id();

        $menu_link = MenuLinkContent::create([
          'title' => $title,
          'link' => ['uri' => 'internal:/node/' . $nid],
          'menu_name' => 'main',
          'expanded' => TRUE,
        ]);
        $menu_link->save();
    }
}
?>

```

If you use `hook_entity_presave` you might need to check whether the MENU item exists otherwise you will end up with a new menu item each time the node is updated.

```
<?php
use \Drupal\Core\Entity\EntityInterface;
use \Drupal\menu_link_content\Entity\MenuLinkContent;

function MODULE_NAME_entity_presave(EntityInterface $entity){

    if ($entity->getEntityType()->id() == 'node') {
        $title = $entity->getTitle();
        //OR
        //$title = $entity->title->value;
        $nid = $entity->id();

        $menu_link_manager = \Drupal::service('plugin.manager.menu.link');

        $menu_links = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $nid));
        if(sizeof($menu_links)){
            foreach ($menu_links as $menu_link) {
                $definition = $menu_link->getPluginDefinition();
                $definition['title'] = $title;
                $menu_link_manager->updateDefinition($menu_link->getPluginId(), $definition);
                //PHP warning pending fix https://www.drupal.org/node/2775665
            }
        }else{
            $menu_link = MenuLinkContent::create([
                'title' => $title,
                'link' => ['uri' => 'internal:/node/' . $nid],
                'menu_name' => 'main',
                'expanded' => TRUE,
            ]);
            $menu_link->save();
        }
    }
}

```

To get the basic of custom modules please look here https://www.drupal.org/docs/8/creating-custom-modules

for similar question and answers for drupal 7 look here https://stackoverflow.com/questions/3163537/drupal-automatically-add-menu-items-when-new-nodes-are-added
> 0 votes

---
Tags: 8, navigation
---


# Question
Title: Notice: Undefined index: driver in Database::openConnection() when trying to connect to sqlite db
In one of my modules I try to connect to one SQlite DB to copy from it the info into my MySQL DB, however after creating the db info and trying to add them into the Drupal context, I get the error `Notice: Undefined index: driver in Database::openConnection()`

here is my function:

```
function query_247($table, $conditions = array()){
  $module_path = drupal_get_path('module', 'cw_ticketing' );
  $databases['247cinema']['db1'] = array (
    'driver' => 'sqlite',
    'database' => $module_path.'/247cinema_part1.sqlite',
  );
  $databases['247cinema']['db2'] = array (
    'driver' => 'sqlite',
    'database' => $module_path.'/247cinema_part2.sqlite',
  );
  // die(var_dump($databases));
  Database::addConnectionInfo('247cinema', 'db1', $databases);
  Database::addConnectionInfo('247cinema', 'db2', $databases);
  try {
    db_set_active('247cinema');
    if (count($conditions)) {
      //some logic
    }else{
      $where_s = false;
    }

    //some logic

    db_set_active();
    return$records;
  } catch (Exception $e) {
    $msg = $e->getMessage();
    watchdog('error', $msg);
    db_set_active();
  }
}

```

Anyone has any idea ?

# Answer
The documentation is a bit misguiding as it states that the database array should be identical to the way it is declared on the settings.php file. This is wrong!

After digging a little bit the core module it shows that `addConnectionInfo` is expecting a array that defines the `database` and the `driver`.

Here is the correct implementation:

```
      $module_path = drupal_get_path('module', 'cw_ticketing' );
      $db1 = array (
        'database' => $module_path.'/247cinema_part1.sqlite',
        'driver' => 'sqlite',
      );
      $db2 = array (
        'database' => $module_path.'/247cinema_part2.sqlite',
        'driver' => 'sqlite',
      );
      // die(var_dump($databases));
      Database::addConnectionInfo('247', 'db1', $db1);
      Database::addConnectionInfo('247', 'db2', $db2);

```
> 3 votes

---
Tags: database, configuration
---


# Question
Title: Embedded field collection not saving with node using conditional fields
Why is the field collection portion of my node form not saving? I am working on a form that collects travel plans from staff members. As part of this I have a nested field collection to collect itineraries and legs within those itineraries.

to give you a rough description of the related fields:

This is not all the fields on the form, but this should give the idea of the structure. I fill out the form, save, and the saved node contains all the other information, but nothing that was in the field collections shows up.

Since country is an additional module, I tried deleting the country field, but that didn't solve anything. I'm also using the conditional fields module extensively to show and hide other fields though the fields in the field collection are not affected by this.

Finally I'm using a custom module called missions (**UPDATE:** I've disabled the module, and the problem persists, so it seems not to have been the form\_alter) to show one field in the field\_mr\_fc\_legs field collection when field\_mr\_home\_leave is checked. The entire code of which can be found below:

```
/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function missions_form_mission_request_node_form_alter(&$form, &$form_state, $form_id)
{
  $form['body'][LANGUAGE_NONE][0] += array(
    '#placeholder' => t('Day 1

*  Activity 1
*  Activity 2

Day 2'),
  );
  $form['field_mr_home_leave'][LANGUAGE_NONE]['#ajax'] = array(
    'callback' => 'missions_hide_home_leave_toggle',
    'wrapper' => 'itinerary-section',
  );
  $form['field_mr_fc_itineraries']['#prefix'] = '<div id="itinerary-section">';
  $form['field_mr_fc_itineraries']['#suffix'] = '</div>';
  if ((!empty($form_state['complete form']['field_mr_home_leave']['und']['#value']) && $form_state['complete form']['field_mr_home_leave']['und']['#value'] == 1) || (empty($form_state['values']['field_mr_home_leave']) && $form['field_mr_home_leave'][LANGUAGE_NONE]['#default_value'] == 1)) {
    $home_leave_toggle_access = true;
  } else {
    $home_leave_toggle_access = false;
  }
  foreach ($form['field_mr_fc_itineraries'][LANGUAGE_NONE] as $key => &$itinerary) {
    if (is_integer($key)) {
      foreach ($itinerary['field_mr_fc_legs'][LANGUAGE_NONE] as $key => &$leg) {
        if (is_integer($key)) {
          $leg['field_mr_fc_leg_home_leave']['#access'] = $home_leave_toggle_access;
        }
      }
    }
  }

}

function missions_hide_home_leave_toggle($form, $form_state) {
  return $form['field_mr_fc_itineraries'];
}

```

What is the likely cause of this? The Recent log messages report shows just that the node was updated. Is it my module? Is it nested field collections?

### What I've tried

* I disabled my module, and it didn't make a difference
* I removed the nested field collection and it didn't make a difference.
* I removed the country field to verify that it wasn't the country module causing the issue.
* The issue seems to be caused by conditional fields, when I disable that, the form saves properly.

# Answer
> 0 votes
This appears to be caused by a long running, and judging from the long issue threads about it, complicated and poorly understood, incompatibility between field collections and conditional fields. I fully expected conditional fields to be unable to define conditions for the fields in my field collections, but I didn't expect it to sabotage my field collections even with no dependencies that affect field collection fields. I'm currently rewriting all my field dependencies using #states and custom module validation.

# Answer
> 0 votes
I think, it's because field collection is not part of the node, field collection is a separate entity, which needs to be saved separately.

I once had to add up some number fields and save the value in a field collection field on hook\_node\_presave

```
/**
 * Implements hook_node_presave().
 */
function MYMODULE_node_presave($node)
{
  foreach ($node->field_collection_field[LANGUAGE_NONE] as $key => $value) {
    $fc_id = $node->field_collection_field[LANGUAGE_NONE][$key]['value'];
    $field_collection_item = entity_load_single('field_collection_item', $fc_id);
    $field_collection_item->save(TRUE);
  }
}

```

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


title: Filter node display

text:
# Question
Title: Filter node display
I have this nodes:

I want to filter the nodes display based on the user logged in and the value of a specific field in the 'Document' Content Type.

How will I do that? In the picture above first node must not be displayed.

# Answer
> 1 votes
you have to create a custom template for your nodes : node--"ContentTypeMachineName".tpl.php , then check if the use is login with : user\_is\_logged\_in() and the value for the field inside your content type in your case document , after that you can simply use conditional statements to control the output of your template.

---
Tags: 7, nodes
---


title: How can I use select tag in table

text:
# Question
Title: How can I use select tag in table
I create a module that have a table . I create my select tag with this code :

```
$select = array(
    '#type' => 'select',
    '#options' => array(t('0'), t('1'), t('2'), t('3'), t('4'), t('5'), t('6'), t('7'), t('8'), t('9'), t('10')),
);

```

When I use this code in table, select tag not work :

```
$table = [
   '#markup' => '<table><tbody><tr><td>' . $select . '</td></tr></tbody></table>',
];
return $table;

```

The page that show to me :

```
<html><body>
  <table><tbody><tr><td>Array</td></tr></tbody></table>
</body></html>

```

# Answer
Use for the table the render element Table. There is also an example how to put form elements inside of a table:

```
$form['contacts'] = array(
  '#type' => 'table',
  '#caption' => $this->t('Sample Table'),
  '#header' => array($this->t('Name'), $this->t('Phone')),
);

for ($i = 1; $i <= 4; $i++) {
  $form['contacts'][$i]['#attributes'] = array('class' => array('foo', 'baz'));
  $form['contacts'][$i]['name'] = array(
    '#type' => 'textfield',
    '#title' => $this->t('Name'),
    '#title_display' => 'invisible',
  );

  $form['contacts'][$i]['phone'] = array(
    '#type' => 'tel',
    '#title' => $this->t('Phone'),
    '#title_display' => 'invisible',
  );
}

```
> 1 votes

---
Tags: 8
---


# Question
Title: How can I add a new value for a multi-value field programmatically?
If there is a unlimited user text field named "user\_log\_field", How can I add a new value for it?

I'm planning to log the IP and location for each user every time they login. Is using an unlimited user text field a good idea for this purpose?

# Answer
> 4 votes
Architectually speaking, it would be much better if you use custom table for this functionality.You can take a look for inspiration (or even use) the following module:

https://www.drupal.org/project/uiplog

From the description of the project: User IP Log is a simple module that logs the IP address of users on login event to table **{uiplog}**.

**Updated answer:** Since you want to do it yourself. You can implement a hook\_user\_login in your custom module. https://api.drupal.org/api/drupal/core%21modules%21user%21user.api.php/function/hook\_user\_login/8.2.x

Inside you can just paste the following code.

**Assumptions/ notes :**

* This is simple text field is from the type: "**Text (plain)**". If you choose any other option I am not sure if this snippet would work for you.
* The machine name of the field is field\_field\_1. Not the best name but you could quite easily change that on line 5.

I have added quite a few sanity checks that I think would be helpful on the long run.

```
// Load the current user.
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

// The machine name of the field.
$field_name = 'field_field_1';
// Sanity check against the machine name of the field.
if ($user->hasField($field_name)) {
  $field_config = \Drupal\field\Entity\FieldStorageConfig::loadByName('user', $field_name);
  // Checks if has unlimited cardinality, otherwise the appendItem will throw
  // weird error.
  if ($field_config->getCardinality() == '-1') {
    // This is a fancy way to return $_SERVER['REMOTE_ADDR'].
    // Keep in mind that on localhost, this will return ::1.
    $a = \Drupal::request()->getClientIp();
    $user->$field_name->appendItem(\Drupal::request()->getClientIp());
  }
  $user->save();
}

```

Regards,

Oleg

# Answer
> 0 votes
An unlimited user text field would be best in my opinion. The way I would implement it would be to write a hook to alter the user login form. In this hook you would assign an IP address to your user field and save it.

Edit: This is the best option, in the absence of a module wich already provides this functionality. If a module already exists, use it.

---
Tags: 8
---


# Question
Title: Show initially 4 fields for Text field with unlimited value
I am building a website using Drupal 7. In my website there is a form for user to add some content.

In the form there is a field of type "Text Field" (core). The "Number of values" for this text field is "unlimited". Thus, when the form appear in the first time,there is only one text field and a button- "add another item". Then users can add more items / fields just by clicking on the button. the problem is that every clicking takes time to process, and this is not best-practice for my opinion.

I want that always will appear at least 4 fields on the form (and not one).
If the users will want, they will be able to just click on the button and "add another item" (regularly).

How can I can display 4 text fields (and not only one)?

here is a screen-shot for example:

# Answer
> 0 votes
Check Multivalue Settings Module

> Warning: this module is still very buggy. Actually, it only works in very few use cases. I suggest to only attempt using it with core fields (not fields from contrib modules). Even this may not work. I'm working on fixing things, but don't have much time. Help is welcome.

Functionality:

```
Number of values allowed
Number of values required
Number of empty widgets to display initially (Drupal usually displays all fields for non-unlimited fields. This allows you to only display a few, followed by the 'Add More' button, which will disappear after the maximum number of fields has been filled.)
Number of empty widgets to display on edit forms after the field contains some values (Drupal usually displays one extra)

```

Though the module is buggy but can be a good starting point for building a custom solution or patching the same module.

# Answer
> 0 votes
```
    Better to Write your own custom form

    **for example**

        function ajax_example_menu() {
          $items = array();
        $items['examples/ajax_example/dependent_dropdown_degrades'] = array(
            'title' => 'Dependent dropdown (with graceful degradation)',
            'page callback' => 'drupal_get_form',
            'page arguments' => array('ajax_example_dependent_dropdown_degrades'),
            'access callback' => TRUE,
            'weight' => 5,
            'file' => 'ajax_example_graceful_degradation.inc',
          );
        return $items;
        }
    /**
     * Form with 'add more' and 'remove' buttons.
     **/
    function ajax_example_add_more($form, &$form_state, $no_js_use = FALSE) {
      $form['description'] = array(
        '#markup' => '<div>' . t('This example shows an add-more and a remove-last button. The <a href="!ajax">AJAX version</a> does it without page reloads; the <a href="!multistep">non-js version</a> is the same code but simulates a non-javascript environment, showing it with page reloads.',
          array('!ajax' => url('examples/ajax_example/add_more'), '!multistep' => url('examples/ajax_example/add_more_no_js')))
        . '</div>',
      );

      // Because we have many fields with the same values, we have to set
      // #tree to be able to access them.
      $form['#tree'] = TRUE;
      $form['names_fieldset'] = array(
        '#type' => 'fieldset',
        '#title' => t('People coming to the picnic'),
        // Set up the wrapper so that AJAX will be able to replace the fieldset.
        '#prefix' => '<div id="names-fieldset-wrapper">',
        '#suffix' => '</div>',
      );

      // Build the fieldset with the proper number of names. We'll use
      // $form_state['num_names'] to determine the number of textfields to build.
      if (empty($form_state['num_names'])) {
        $form_state['num_names'] = 2;
      }
      for ($i = 0; $i < $form_state['num_names']; $i++) {
        $form['names_fieldset']['name'][$i] = array(
          '#type' => 'textfield',
          '#title' => t('Name'),
        );
      }
      $form['names_fieldset']['add_name'] = array(
        '#type' => 'submit',
        '#value' => t('Add one more'),
        '#submit' => array('ajax_example_add_more_add_one'),
        // See the examples in ajax_example.module for more details on the
        // properties of #ajax.
        '#ajax' => array(
          'callback' => 'ajax_example_add_more_callback',
          'wrapper' => 'names-fieldset-wrapper',
        ),
      );
      if ($form_state['num_names'] > 1) {
        $form['names_fieldset']['remove_name'] = array(
          '#type' => 'submit',
          '#value' => t('Remove one'),
          '#submit' => array('ajax_example_add_more_remove_one'),
          '#ajax' => array(
            'callback' => 'ajax_example_add_more_callback',
            'wrapper' => 'names-fieldset-wrapper',
          ),
        );
      }
      $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
      );

      // This simply allows us to demonstrate no-javascript use without
      // actually turning off javascript in the browser. Removing the #ajax
      // element turns off AJAX behaviors on that element and as a result
      // ajax.js doesn't get loaded.
      // For demonstration only! You don't need this.
      if ($no_js_use) {
        // Remove the #ajax from the above, so ajax.js won't be loaded.
        if (!empty($form['names_fieldset']['remove_name']['#ajax'])) {
          unset($form['names_fieldset']['remove_name']['#ajax']);
        }
        unset($form['names_fieldset']['add_name']['#ajax']);
      }

      return $form;
    }

    main thing u need to change code to get initially four text fields is
    ****$form_state['num_names'] = 4;****

U can add your other fields in the same change accordingly as u need.

```

---
Tags: entities
---


# Question
Title: How to redirect from confirmation page back to page of form?
Is it possible to have a form redirect the user after landing on the confirmation page back to the previous page (page of the form)?

Note: I'm using Webform for D8

# Answer
```
I have written the code for d7 where the article node form once submitted it is redirected back to the form.
    It will help you for d8.
    /**
     * Defines hook_form_alter()
     */
    function demo_form_alter(&$form, $form_state, $form_id) {
        if (strstr($form_id, 'article_node_form')) {
          $form['actions']['submit']['#submit'] = array('demo_form_submit');
        }
    }
    // custom submit handler for '_node_form'
    function demo_form_submit($form, &$form_state) {
      // call default action
      node_form_submit($form, $form_state);
      $form_state['redirect'] = url('node/' . 'add' . '/article', array(
          'absolute' => TRUE
        )
      );

      $_GET['destination'] = $form_state['redirect'];
    }

```
> 1 votes

---
Tags: 8, webforms
---


# Question
Title: How To Override Webform's Submission Template in Drupal 8
The template provided by the Webform module for theming a submission is rather plain. Basically, it looks like a `print_r` of the data variable. If you try to add HTML to validation function before it gets submitted, the HTML just gets rendered as plain text.

So I was trying to find a way to override the template from a *module* as opposed to a theme. I'm not able to find much documentation for this right now.

How do I override webform's default submission HTML template from a module?

# Answer
Create a custom module and in the `custom.module` file add this code:

```
/**
 * Implements hook_theme_registry_alter
 */
function custom_theme_registry_alter(&$theme_registry) {
  $theme_registry['webform_submission_html']['path'] = drupal_get_path('module', 'custom') . '/templates';
  $theme_registry['webform_submission_html']['template'] = 'custom-submission-html';
}

```

You should have in the custom module your template at the location `custom/templates/custom-submission-html.html.twig`

The contents of that Twig file look like this.

```
{{ data }}
{{ data.r }}
{{ data.n }}

```

You can add HTML that suits your specific case.
> 0 votes

---
Tags: 8, webforms
---


# Question
Title: How to specify translation for strings in twig template & php files
I've found a lot of examples and modules where such expressions are used .

In php files

```
 t('Submit this form'),

```

In twig files

```
 {{ 'Send'|trans }}

```

So as I know this is used for the translation purpose, and I've also used these functions in my theme & modules.

But the question is where I can specify translation for these words & phrases ?

# Answer
I think you could do that with the User interface translation, "/admin/config/regional/translate" (which is part of the multilingual core package). By the way you can also use:

```
{% trans %} Your english text {% endtrans %}

```
> 2 votes

---
Tags: theming, 8, i18n-l10n
---


# Question
Title: how can I get a list of all of the permissions a user has?
if I have the current user object, how can i get a list of all of the permissions he has in drupal 8 custom module ? I dont want to check for one particular permission which would be $current\_user-\>hasPermission("permission\_name").

I want to get the entire list of his permissions.

thanks

# Answer
Can you try the following snippet:

```
$user = \Drupal::currentUser();
$user_roles = $user->getRoles();
$roles_permissions = user_role_permissions($user_roles);

```

This will give you permissions grouped by roles. But most likely you want them in one array.

Therefore you can use this

```
$final_array = array();
foreach ($roles_permissions as $role_key => $permissions) {
  foreach ($permissions as $permission) {
    $final_array[] = $permission;
  }
}

```

In case you want to load different user than the currently logged-in user, you can use

```
$some_user = \Drupal\user\Entity\User::load(123);

```

Where 123 stands for the user id. For more information:

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21Entity.php/function/Entity%3A%3Aload/8.2.x

Best regards,

Oleg
> 20 votes

---
Tags: 8, users
---


# Question
Title: Compress images before generating PDF file
I am working with Views PDF Module, and I used it to export any node of content type "Appointment" as PDF file and then send it by email...

In my case the content type "Appointment" should have a field of type "Image", so that mean I will have many images included on the PDF file.

Let's imagine that the client upload 10 images with 1MB for each one , so that will make my website so slow in generating the PDF file and maybe will not continue all the process .

I need a tool which can compress images before saving the node and that will make it easier for generating the PDF file.

Is there any solutions guys!

# Answer
> 0 votes
The "standard" way to go would probably be to create a "reduced" image style (in `admin/config/media/image-styles`) and use it for the image field in your "Appointment" content type. Like that, you would let Drupal itself do the compressing of the images.

---
Tags: files
---


title: HTTP error 500 when backup entire site

text:
# Question
Title: HTTP error 500 when backup entire site
Using Backup and Migrate module on a D7 site

* separate backups (data / files) give no problem (backup to nodesquirrel AND download)
* but backup entire site (data + files) generates "http error 500" (without "internal server error")

Error reporting

* I have no access to Apache error log
* Cpanel error: no error messages
* Drupal error log: no error messages

Shared hosting | db 10.1.21-MariaDB | php 5.6.30 | drupal 7.53 | backup and migrate 7.x-3.1 | civicrm 7.x-4.7.14

\[update\]

The web host provider received next message:

```
 Uncaught exception 'PDOException'
 with message 'SQLSTATE[HY000]:
 General error: 2006 MySQL server has gone away'
 in <drupal root>/includes/database/database.inc:2227
 Stack trace:
 #0 /includes/database/database.inc(2227): PDOStatement->execute(Array)
 #1 /includes/database/database.inc(697): DatabaseStatementBase->execute(Array,  Array)
 #2 /includes/database/database.inc(2406): DatabaseConnection->query('SELECT expire, ...', Array, Array)
 #3 /includes/lock.inc(167): db_query('SELECT expire, ...', Array)
 #4 /includes/lock.inc(146): lock_may_be_available('schema:runtime:...')
 #5 /includes/bootstrap.inc(433): lock_acquire('schema:runtime:...')
 #6 /includes/bootstrap.inc(455): DrupalCacheArray->set(Array)
 #7 [internal function]: DrupalCacheArray->__destruct()
 #8 {main} in <drupal root>/includes/database/database.inc on line 2227

```

# Answer
This is your error:

```
General error: 2006 MySQL server has gone away

```

You can try to fix this in two ways:

1. `my.ini`

Open your `my.ini` file and locate max\_allowed\_packet. By default this is 1M. Setting it to 16M and restart your MySQL server. If the problem persists, try setting it to 512M and restart your MySQL server.

2. `MySQL prompt`

Enter your MySQL prompt, log in as user root or as a user with the SUPER privilege. Run the following command:

```
SET GLOBAL max_allowed_packet = 1024 * 1024 * 512;

```

This method doesn't require you to restart the server.
> 2 votes

# Answer
You are most likely hitting a resource limit. Enable PHP error logging in the index.php file so you can get an error output. But most likely it's a memory issue or a timeout issue which you will need to make adjustments in your PHP.ini file to fix them.

It sounds like it's specific than to your MySQL limits. Try increasing your packet size.

Here is a link that describes a similar issue with some possible solutions. https://www.drupal.org/node/259580
> 1 votes

---
Tags: backups, http-request
---


title: Creating content via PHPMYADMIN

text:
# Question
Title: Creating content via PHPMYADMIN
I'm trying to add content to my Drupal 8 from the PHPMYADMIN.

You may be wondering *Why this way?* The fact is that I have a web in Drupal 6 and I tried a lot to migrate using the tools Drupal has, without success.

I'm not so good at programming, and the time is passing, so I decided to try the manual approach.

I created an article and inspected the database and saw what tables where altered to discover which tables where affected when I create an article.

Then I proceeded to manually create them.

The involved tables where:

* node
* node\_revision
* node\__body
* node\_revision\__body
* node\__comment
* node\_revision\__comment
* node\_field\_data
* node\_field\_revision
* node\__field\_tags
* node\_revision\__field\_tags
* taxonomy\_term\_field\_data
* taxonomy\_index
* taxonomy\_term\_data
* taxonomy\_term\_hierarchy
* comment\_entity\_stastics

I noticed that "menu\_tree" and "cache\_entity" are altered when creating an article, but I do not know how to manually insert data there because they have blob data.

After that, I re-built the cache, but the content I created wouldn't show.

I wonder if there are some tables I'm missing, or if with this method I won't be able to achieve what I'm trying to accomplish.

If I have to choose between spending time in trying to learn something hard for me (something I don't know if will be or not 100% a success) and manually creating the 1500 articles with the Drupal 8 UI, then I would stick with the second option, because manually creating content is 100% secure and won't consume my desire to live the way the alternatives I'm trying with no effort are doing.

But there may be something. to automatize the process at least a bit. Is there?

What should I do?

I wonder if investigating the import.php as some kind of method to which I can pass and array of info and achieve what I'm trying to do!

Ps: I have already tried with the Migrate, Migrate Plus, etc with no result.

# Answer
> 5 votes
Don't even bother. This level of effort is not even necessary.

If you are just moving content from Drupal 6 to Drupal 8, use the built in Migration modules that come with core. It is *designed* to do this. I can't even quantify how long this would take to do in PHPMYADMIN of all things. You'd likely wind up corrupting the database itself. The schema is nowhere near as simple as it once was.

Please try using the tools and check the docs for more: https://www.drupal.org/node/2257723

All you have to do is point it at your Drupal 6 database and let it work. If you have basic content (sounds like Articles and blog posts) it should work very well. It will even build out the content type and taxonomy for you.

Even if the automatic route doesn't totally work, still attempt to use the Migration tools available to you. You will save a ton of hours (probably hundreds) vs editing a database manually.

# Answer
> 1 votes
Another option for you would be to export somehow the data you have into CSV, and then use a module like https://www.drupal.org/project/feeds to import your content.

---
Tags: 8, database, migrations
---


title: Entity reference in custom field type

text:
# Question
Title: Entity reference in custom field type
hello i am trying to create a custom field type in drupal 8 containing two text fields and an entity reference field to a user , but i get this error when i try to save .

> Error: Call to undefined method Drupal\Core\TypedData\DataDefinition::getTargetDefinition() in Drupal\Core\Entity\Plugin\DataType\EntityReference-\>getTargetDefinition() (line 51 of core/lib/Drupal/Core/Entity/Plugin/DataType/EntityReference.php).

below is my custom field definition :

```
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    // Prevent early t() calls by using the TranslatableMarkup.

    $properties = [];

    $properties['street'] = DataDefinition::create('string')
      ->setLabel(t('Street'));

    $properties['city'] = DataDefinition::create('string')
      ->setLabel(t('City'));

    $properties['user']   = DataDefinition::create('entity_reference')
            ->setLabel(t('user'))
            ->setSetting('target_type', 'user');

    return $properties;
 }

```

Any help or tip would be very welcome , thank you :)

# Answer
> 15 votes
EntityReferenceItem is more complicated than just the "entity" DataReferenceDefinition.

It has a DataReferenceDefinition for "target\_id" as well.

I solved a similar issue by extending EntityReferenceItem.

Then you can get the entity from the parent definition, which is a bit long and complex and then just add your custom fields on top:

```
  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties = parent::propertyDefinitions($field_definition);

    $properties['street'] = DataDefinition::create('string')
      ->setLabel(new TranslatableMarkup('Title'));

    $properties['city'] = DataDefinition::create('string')
      ->setLabel(new TranslatableMarkup('Title'));

    return $properties;
  }

```

Here's the code I used to add one text field to an EntityReferenceItem:

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

use Drupal\Core\TypedData\DataDefinition;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Validation\Plugin\Validation\Constraint\AllowedValuesConstraint;
use Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem;
use Drupal\Component\Utility\Random;

/**
 * Defines the 'entity_reference' entity field type.
 *
 * Supported settings (below the definition's 'settings' key) are:
 * - target_type: The entity type to reference. Required.
 *
 * @FieldType(
 *   id = "entity_reference_with_title",
 *   label = @Translation("Entity reference with title"),
 *   description = @Translation("An entity field containing an entity reference and a text field."),
 *   category = @Translation("Custom"),
 *   default_widget = "entity_reference_with_title_autocomplete",
 *   default_formatter = "entity_reference_with_title_entity_view",
 *   list_class = "\Drupal\Core\Field\EntityReferenceFieldItemList",
 * )
 */
class EntityReferenceWithTitle extends EntityReferenceItem {

  /**
   * {@inheritdoc}
   */
  public static function defaultStorageSettings() {
    return array(
      'target_type' => \Drupal::moduleHandler()->moduleExists('node') ? 'node' : 'user',
      'title' => '',
    ) + parent::defaultStorageSettings();
  }

  /**
   * {@inheritdoc}
   */
  public static function defaultFieldSettings() {
    return array(
      'handler' => 'default',
      'handler_settings' => array(),
    ) + parent::defaultFieldSettings();
  }

  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties = parent::propertyDefinitions($field_definition);

    $properties['title'] = DataDefinition::create('string')
      ->setLabel(new TranslatableMarkup('Title'));

    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public static function mainPropertyName() {
    return 'target_id';
  }

  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {

    $schema = parent::schema($field_definition);

    $schema['columns'] = array(
      'title' => array(
        'type' => 'varchar',
        'length' => 255,
      ),
      'target_id' => $schema['columns']['target_id'],
    );

    return $schema;
  }

  /**
   * {@inheritdoc}
   */
  public function getConstraints() {
    $constraints = FieldItemBase::getConstraints();
    // Remove the 'AllowedValuesConstraint' validation constraint because entity
    // reference fields already use the 'ValidReference' constraint.
    foreach ($constraints as $key => $constraint) {
      if ($constraint instanceof AllowedValuesConstraint) {
        unset($constraints[$key]);
      }
    }
    return $constraints;
  }

  /**
   * {@inheritdoc}
   */
  public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
    $manager = \Drupal::service('plugin.manager.entity_reference_selection');
    if ($referenceable = $manager->getSelectionHandler($field_definition)->getReferenceableEntities()) {
      $random = new Random();
      $group = array_rand($referenceable);
      $values['target_id'] = array_rand($referenceable[$group]);
      $values['title'] = $random->sentences(2);
      return $values;
    }
  }

}

```

---
Tags: 8, entities
---


# Question
Title: How do I redirect in a class sub-classing the EventSubscriber class?
I want to redirect to a specific URL in an `EventSubscriber` class instead of showing the *Page not found* page. I followed Symfony2 redirect for event listener? but the redirect goes to the home.

This is the code I am using.

```
use Drupal\Core\Url;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class PageNotFound implements EventSubscriberInterface {
  public function pageNotFound(GetResponseEvent $event) {
    $request = $event->getRequest();
    $id = '1234';
    $scheme_and_http_host = $request->getSchemeAndHttpHost();
    $url = Url::fromRoute('myroute', ['id' => $id])->toString(); // this url exist (checked)

    $response = new RedirectResponse($scheme_and_http_host . $url, Response::HTTP_MOVED_PERMANENTLY);
    $event->setResponse($response);
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['pageNotFound'];
    return $events;
  }
}

```

### mymodule.services.yml

```
services:
  mymodule.page_not_found:
    class: Drupal\mymodule\EventListener\PageNotFound
    tags:
      - {name: event_subscriber}

```

How do I redirect users from an `EventSubscriber` class?

# Answer
> 3 votes
To catch a 404 exception you need to subscribe to a `KernelEvents::EXCEPTION` event. As there is already a base class for html exceptions you don't need to code this yourself. You can simply put the code in an `on404()` method of a class that extends HttpExceptionSubscriberBase:

> Utility base class for exception subscribers.
>
> A subscriber may extend this class and implement getHandledFormats() to indicate which request formats it will respond to. Then implement an on\*() method for any error code (HTTP response code) that should be handled. For example, to handle 404 Not Found messages add a method:
>
> `public function on404(GetResponseForExceptionEvent $event) {}`
>
> That method should then call $event-\>setResponse() to set the response object for the exception. Alternatively, it may opt not to do so and then other listeners will have the opportunity to handle the exception.

---
Tags: 8, event-subscribers
---


# Question
Title: How to configure a view accessible on user's profile only by that user
I have a view listing the nodes a user created on /user/{user}/mycontent.

How should I configure the view so that other users won't have access it?

# Answer
If you don't want them to see their own content instead of the user which profile they are currently viewing, you need to add a **contextual filter**

skip to 8:52 and watch Views Relationships and Contextual Filters

Note: this is for drupal 7, but I imagine the drupal 8 views look the same.
> 2 votes

# Answer
Since you want the view visible only to the users who are watching their own user page, you cannot merely achieve that using the settings a view has for the access. You need to compare the user ID of the currently logged-in user with the user ID of the user object associated with the user page; that doesn't involve checking the logged-in user has a specific permission (although you can additionally check for the user having a specific permission), nor a specific role.

You can use the code shown on Drupal 8 Views: How to set as admin path as start for your code.

### my\_module.services.yml

```
  services:
    my_module.route_subscriber:
      class: Drupal\my_module\Routing\RouteSubscriber
      tags:
        - { name: event_subscriber }

    my_module.access_view_checker:
      class: Drupal\my_module\Access\AccessViewChecker
      arguments: ['@current_user']
      tags:
        - { name: access_check, applies_to: _access_view_check }

```

### my\_module/src/Routing/RouteSubscriber.php

```
namespace Drupal\my_module\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Class RouteSubscriber.
 *
 * @package Drupal\my_module\Routing
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    $admin_routes = ['view.my_example_view.page_1'];
    foreach ($collection->all() as $name => $route) {
      if (in_array($name, $admin_routes)) {
        $route->setRequirement('_access_view_check', TRUE);
      }
    }
  }
}

```

See also Altering existing routes and adding new routes based on dynamic ones and Access checking on routes to understand which code to use for the access control class.
> 0 votes

---
Tags: views, 8
---


# Question
Title: How can I have device-specific block layouts?
I'm fairly new to Drupal. In my current project, I'm using Drupal 8. The site is supposed to have a fairly different look depending on the device, in a way such that being responsive is not enough here.

So, within a single custom theme, I would like my site to have two different block layouts depending on the type of device (mobile / desktop) on which it is displayed. This can be achieved by showing / hiding blocks depending on the device. For performance reasons it is important for the hidden blocks to not be rendered at all in the HTML code (i.e. merely hiding with CSS won't do).

For this it seems that a combination of the Context module and its little brother Context Mobile Detect would do the trick. However, Context Mobile Detect is not yet available in Drupal 8, preventing me of using the Context module with the relevant condition.

* Is this the right approach? Any other solutions for achieving what I'm trying to do here? This seems like a common enough problem to me and I'm expecting other developers to have found a way.
* If it is: I'm tempted to write my own custom condition (wrapping the project Mobile Detect) so I can use it with the Context module. It seems Context uses the Drupal 8 Condition API, but I can't find any useful resource on how to write my own custom conditions in version 8 of Drupal. The official doc is sparse at best and I would rather avoid trying to reverse-engineer the thing. Any of you have a useful link/video/advice for this?

# Answer
> 1 votes
I followed the counsel of Berdir and Ash Upadhayay. Having a sub-domain dedicated to mobile devices is a sound advice as many important websites currently use this method. As they say, using the same domain for both version could cause problems with caching and referencing by indexation robots.

This however doesn't clash with my requirements, and I was able to fulfill them using the Drupal 8 version of the Domain Access module.

The Domain Access module allows to define specific sub-domains that Drupal 8 will be able to recognize. The module then makes possible to condition all manner of things depending on the current domain, including the block layout.

I installed the module itself and its contrib module (packaged with it) Domain Alias. This last module allows you to associate various patterns to a domain that works as an alternative way of detecting the domain. This allows to match the URLs of local installs of the project without changing the Domain configuration.

This is the perfect solution for me as I am now able to condition the display of blocks from a single page - the block layout page.

All that's left to do then is to redirect the user on the correct sub-domain depending on the device, using a module such as Mobile JS Redirect.

---
Tags: 8, blocks
---


# Question
Title: How to modify the page at admin/structure/types?
Using Drupal 8, I'm trying to modify the page at "`/admin/structure/types`" .This page is not a form (instead it is an entity list), so it cannot be modified with **hook\_form\_alter**.

\_entity\_list: The value is entity\_type. Provides a list of entities using the EntityListController of the respective entity. E.g. \_entity\_list: view\_mode returns the render array of a list of view modes.

Which hook can I use to modify an entity list ?

I have tried

* mymodule\_structure\_types\_prepare\_form
* mymodule\_structure\_prepare\_form

and none of those is triggered.

# Answer
> 6 votes
see Can you change the list builder class used by an entity?

Using hook\_entity\_type\_alter() you can override the list builder for nodes.

You can add a custom NodeListBuilder in your module that extends or replaces /core/modules/node/src/NodeListBuilder.php

This class is pretty simple, so it should be easy to add or remove rows to the table displayed.

# Answer
> 3 votes
Inside \core\modules\node\node.routing.yml you can see that the path "admin/structure/types" is having defaults: \_entity\_list

From https://www.drupal.org/docs/8/api/routing-system/structure-of-routes I can see that:

> **\_entity\_list**: The value is entity\_type. Provides a list of entities using the EntityListController of the respective entity. E.g. \_entity\_list: view\_mode returns the render array of a list of view modes.

So, the question would be to modify the output of this EntityListController.

Update: Apparently this has already been answered , as other people suggested.

I just found this. It might be helpful as a complete example. How do I add a column to the table shown in the vocabulary listing page?

# Answer
> 2 votes
I solved this by using hook\_clone\_entity\_load( $entities, $type), and when the type==block I am on that page

---
Tags: 8
---


# Question
Title: Attach javascript library and settings to a node page
Normally, to attach javascript (settings or just a library) to a Drupal 8 node type (page), you should use template\_preprocess\_node and add it to the #attached array. (example)

Problem with the display suite is that the function is never reached. So you can't add the library and optionally the settings for that library to that node.

Although the hook\_preprocess\_field function would suffice, I have the issue that I want to add it to a non-renderable field. So the field will never be displayed. I just need some javascript settings based on that field.

---

Example:

I have a node type: background\_carousel\_page With a field: images (field type: image, multiple allowed)

I need to be able to add the images url to the settings of javascript to make the carousel displaying the images.

---

*So to summarize: I need a solution where I can add the library + settings to a specific node based on a field that's not being rendered.*

# Answer
> 8 votes
try hook\_entity\_view or hook\_node\_view\_alter:

```
/**
 * Implements hook_entity_view().
 */
function mymodule_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {

  if ($entity->bundle() == 'background_carousel_page' && $view_mode == 'full') {
    $build['#attached']['library'][] = 'mymodule/mylibrary';
  }

}

```

or

```
/**
 * Implements hook_ENTITY_TYPE_view_alter().
 */
function mymodule_node_view_alter(array &$build) {
  // @see \Drupal\Tests\embed\Functional\EmbedPreviewTest::testPreview
  $build['#attached']['library'][] = 'mymodule/mylibrary';
}

```

---
Tags: 8, display-suite, theming
---


title: Syncing LDAP users

text:
# Question
Title: Syncing LDAP users
We're using LDAP as our source for users. This works fine, and everyone can simply log in using their LDAP info, and it will create a Drupal user for that person. However, one of our requirements is having a (searchable) list of users on the site. This means that we regularly need to check LDAP for new and changed entries, and merge them with our drupal users.

The LDAP for Drupal 7 module has a list of events that trigger LDAP provisioning. One of them says: `On cron runs. Not implemented yet.` I haven't found anything about the state of this, as this is basically what we need.

Because of problems in migrating our website to new versions, we're currently trying to rewrite everything to use community modules. Therefore, we'd very much prefer an official solution. We've currently switched the user list to a LDAP query view, but this is only a temporary solution.

# Answer
> 3 votes
I've worked with LDAP and i have done a function on cron execution, to create automaticly user (of a certain role) who are not already created by login

I hope this will help you

```
function _synchro_ldap(){

  $server = "serveur.com";
  $rootdn = "name";
  $rootpw = "pwd";
  $ds = ldap_connect( $server );
  $r = ldap_bind( $ds, $rootdn, $rootpw );

  $dn = "OU=AAAAA,OU=BBBB";

  $filtre="cn=test";

  $sr = ldap_search($ds, $dn, $filtre);

  $info = ldap_get_entries($ds, $sr);

  for ($i = 0; $i < $info[0]["member"]["count"]; $i++) {

    $sr2 = ldap_search($ds, $info[0]["member"][$i], "cn=*");

    $info2 = ldap_get_entries($ds, $sr2);

    $name       = $info2[0]["samaccountname"][0];
    $mail       = $info2[0]["mail"][0];
    $nom        = $info2[0]["sn"][0];
    $prenom     = $info2[0]["givenname"][0];
    $dn         = $info2[0]["distinguishedname"][0];

    if( !empty($mail) && !empty($name) && $name!= "admin" ){

        $u = user_load(array("name" => $name));
        $m = user_load(array("mail" => $mail));

        if( !$u && !$m) { // user does not exist in drupal

            // Create a user
            $details = array(
                'name'                  => $info2[0]["samaccountname"][0],
                'mail'                  => $info2[0]["mail"][0],
                'access'                => 0,
                'status'                => 1,
                'ldap_authentified'     => TRUE,
                'ldap_dn'               => $dn,
                'ldap_config'           => "1"
            );

            $u = user_save( null, $details ); // Creation du user
            $user_id = $u->uid;
            user_multiple_role_edit( array( $user_id ), "add_role", $role_id_custom );
        }
    }
  }
  ldap_close( $ds );
}

```

# Answer
> 1 votes
Ok. This is an old question... But I want to give the answer I have found after many hours of work.

To import (I mean create a Drupal user for) ALL users from LDAP, first create a query named something like ***'all\_employees'*** on **admin/config/people/ldap/query** page. This should be the machine name for your query. Make sure your query returns all the users you want to import.

Here is a function that you can use in a custom module that imports ldap users using the built-in LDAP functionality:

```
function importUsers($ldap_query_id='all_employees') {
  $ldapQuery = ldap_query_get_queries($ldap_query_id, 'all', TRUE, TRUE);
  $ldap_users = $ldapQuery->query();

  foreach ($ldap_users as $ldap_user) {
    $username = $ldap_user['samaccountname'][0];
    if (!empty($username)) {

      $ldap_user_conf = ldap_user_conf();
      $user_edit = array('name' => $username);
      $save = true;
      $ldap_user_conf->provisionDrupalAccount(NULL, $user_edit, NULL, $save);

    }
  }
}

```

There might be warnings or errors if you already have some users from LDAP but that's okay.

# Answer
> 0 votes
It sounds like you are looking for LDAP Feeds https://www.drupal.org/node/1300812 which we have used to do this fine. LDAP User module will only handle the authentication, and only triggers when the user logs in, as you've found. But for a stafflist, we needed the other 90% of staff who never even use the CMS to be updated also. LDAP Feeds does that, and also lets you sync additional data fields from LDAP to Drupal 7 user accounts.

We run it nightly. Example results are (the lower table on) https://www.niwa.co.nz/atmosphere/key-contacts

The biggest remaining problem was *deleting* users from the stafflist once they disappeared from LDAP - that's still tricky.

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


# Question
Title: Form in a block with results is the same block
I have a custom module that uses a form in a block that will be displayed on a node page. This form is used to retrieve datas from a custom table. What I want to achieve is :

1. The user arrives on the page : the form is displayed and the 10 lasts items retrieved from the database are also displayed
2. The user selects a data via the form
3. The user submits the form
4. The node page containing the block is refresehed with the 10 new items retrieved from database. I also need the form to be displayed on top of the block with previously selected values selected

I've been able to create a form class extending the FormBase class. Then I've created a block extending BlockBase class. In the build method I get the form using the Drupal::formBuilder()-\>getForm() method

```
public function build(){

$form = \Drupal::formBuilder()->getForm('Drupal\my_module\Form\my_form');

  return array(
      '#theme' => 'my_theme',
      '#form' => $form,
    );
}

```

At that step, my node page + the block containing the form is correctly displayed, but I've not been able to render the default 10 last items. I've no idea on how to achieve this since the buildForm method of the form class is supposed to return an array to render the form. I've tried to implement it in the build method of my block :

```
return array(
      '#theme' => 'my_theme',
      '#items' => $items,
      '#form' => $form,
    );

```

It works, but after form submission, those first 10 default items are always displayed because the block build them on every refresh. Is there a way to know if the included form has been submitted ?

Concerning the form validation, redirection is definitly not the way I should go since a need the results of the database query to be displayed in the same page / block.

Based on this topic, I feel the $form\_state-\>setRebuild() / $form\_state-\>isRebuilding() methods are the way to go. Do you confirm ?

I've been able to refresh the item list after form submission doing so :

```
  if ($form_state->isRebuilding()) {
  $myfield_value = $form_state->getValue('myfield ');

  $model = Drupal::service('my_module.model');
  $items = $model->getLastItems(10, $myfield_value );

  return array(
    '#theme' => 'my_theme',
    '#form' => $form,
    '#items' => $items,
  );

```

}

This works, but only half of the time the form is submitted. The second time it's like it never passes in the if($form\_state-\>isRebuilding()) {} statement. Moreover, the results are nested in the form markup. Maybe it's not the proper way to inject the form...

For information here is an example of my twig markup :

```
{{ form }}
<div class="row">
    {% for track in tracks %}
        {# print stuff...#}
    {% endfor %}
</div>

```

To be able to inject the form in the if($form\_state-\>isRebuilding()) statement of the buildForm of the form class, I must wait the form array is completly defined in code... Doing so, I'm unable to set fields values to the ones the user has submitted.

In brief, my questions are :

* How can I populate the default items list before the form is submitted ?
* How can I properly inject the form from the if($form\_state-\>isRebuilding() statement, so that everything works
* How can I set the fields selected values after form submission.

Sorry for this long post, but I'm quite new to the drupal ecosystem, so any help would be greatly appreciated !...

Cheers

PS : I've also read about the BlockBase::blockForm and BlockBase::blockSubmit methods, but as far as I understand, it's more about block configuration froms. Does somebody confirm that ?

# Answer
Thanks 4k4, the main point I was missing here is that a form is just a specific form of render array... I though it was only possible to define form elements to be rendered. But as you pointed me out, it's possible to define anything one wants to render, like... form result... Since what I need to render is a bit more complicated than simple markup, I've created a new template in my .module file :

```
function my_module_theme() {
return array(
'my_module_form' => array(
  'variables' => array(
    'form' => array(),
  ),
'template' => 'my-module-form',
),
 'my_module_results' => array(
  'variables' => array(
    'tracks' => array(),
  ),
 }

```

And then, my buildForm method looks approximately that way :

```
public function buildForm(array $form, FormStateInterface $form_state) {
// define default values...
$defaultValue = 3;

// define form fied + submit button...
 $form['my_field'] = array(
  '#type' => 'select',
  '#required' => true,
  '#default_value' => $defaultValue,
  '#options' => array(1 => 1, 2 => 2, 3 => 3)
);

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

// define field default value that will be overwritten whe  form is submitted
$my_field_value = 1;

//get submitted value
if ($form_state->isRebuilding()){
    $my_field_value =  $form_state->getValue('my_field');
}

//get datas from database
$results = $model->getResultFromDb($my_field);

 $form['result'] = array(
    '#theme' => 'my_module_results',
    '#results' => $results,
    );

return $form;
}

```

Then is the "my\_module\_results" you can use the $results var as in any other template :

```
<ul>
  {% for result in results %}
  <li> {{ result.title }}</li>
  {% endfor %}
</ul>

```

For the results not to be nested in the "form" markup, I had to build manually the form in its own template and call the result var where I needed the result template to be inserted :

```
<div id="form">
    <form method="{{ form['#method'] }}">
        {{ form.form_build_id }}
        {{ form.form_token }}
        {{ form.form_id }}
        {{ form.my_field }}
        {{ form.submit }}
    </form>
</div>
<div id="results">
    {{ form.result }}
</div>

```

Not sure it wes the only way to do that, but it works like a charm...

Hope this would help somebody...
> 2 votes

---
Tags: forms, blocks
---


# Question
Title: how to add .js programatically when in an entity list
I'm in the hook\_entity\_load in my module and I want to dynamically add a .js library which I already have defined.
The thing is i need to get to the block objec I'm on to add the library using $block\['#attached'\]\['library'\]\[\]

How do I get this block object?

# Answer
> 3 votes
The correct approach is doing it using a custom list builder, assuming you are using that and not a view.

```
class MyListBuilder extends EntityListBuilder {

  public function render() {
    $build = parent::render();
    $build['#attached']['library'][] = 'yourmodule/library';
  }
}

```

Then specify it in the annotation of your entity type.see Node/User or so on how to do that, most entity types specify either the default or a custom list builder.

If it's a view then you can implement one of the many views hooks, if it's not your own entity type then I'm not exactly sure why you need to add a JS there and you should explain in more detail what kind of list it is and what your JS does.

---
Tags: 8
---


# Question
Title: Label for Child in Simple Hierarchical Select by using a module
While using Simple Hierarchical Select Module, I have 2 levels of Hierarchy for my Phone. Is it possible to label for child by using a module ?

# Answer
> -1 votes
I guess this is possible by Client side hierarchical select.

Let me know if there is any other option.

Thanks.

---
Tags: webforms
---


# Question
Title: How to use hook_form_BASE_FORM_ID_alter() to save variable?
I am attempting to use hook\_form\_BASE\_FORM\_ID\_alter() to 1) add a field to the node edit form, which then is 2) turned into a token, and 3) used in Rules. This question is only about the first part of this process.

The following code is in place. It creates a field, but nothing is getting saved to the variable in question, `additional_email`, after the node edit form is submitted. I know I'm doing something very wrong here, but I don't know what.

**How can I save the variable entered by the user to be accessed by a different function in my module?**

Edit Form Code

```
function MYMODULE_form_node_form_alter(&$form, $form_state) {
   $email_default = 'john@example.com';
   $form['additional_email'] = array(
      '#title' => t('Additional E-mail'),
      '#type' => 'textfield',
      '#default' => variable_get('additional_email', $email_default),
      '#description' => t('If you would like to notify an additional person, please supply the e-mail address.'),
   );

   $form['options']['additional_email'] = $form['additional_email'];
   $form['options']['additional_email']['#title'] = t('Additional Notification');

   $form['#submit'][] = 'MYMODULE_submit';
}

function MYMODULE_submit($form, $form_state) {
   if (isset($form_state['values']['additional_email'])) {
      variable_set('myvariable', $form_state['values']['additional_email']);
   }
 }

```

Token Creation Code

```
 function MYMODULE_tokens($type, $tokens, array $data = array(), array $options = array()) {
    ...
    $notify_email = variable_get('additional_email', '0');
    $concat_array = implode(' ',$notify_email);
    $section_users['add_email'] = $concat_array;
    ...
  }

```

**Update**: I added a submit handler, shown above (and clarified the variable I accidentally omitted when copying the code). Unfortunately, I'm still getting the old garbled array that was somehow saved in there previously.

The code which assigns the variable's value to the token is above, in case that's the problem.

# Answer
> 2 votes
`return system_settings_form($form);` will do nothing in this context. An alter function like this has no return.

What you should do if you want to save the value is add a submit handler into the form instead:

```
function MYMODULE_form_node_form_alter(&$form, $form_state) {
   $form['additional_email'] = array(
      '#title' => t('Additional E-mail'),
      '#type' => 'textfield',
      '#default' => variable_get('additional_email', $email_default),
      '#description' => t('If you would like to notify an additional person, please supply the e-mail address.'),
   );

   $form['options']['additional_email'] = $form['additional_email'];
   $form['options']['additional_email']['#title'] = t('Additional Notification');

   $form['submit'][] = 'mymodule_submit';
}

function mymodule_submit($form, $form_state) {
  if (isset($form_state['values']['additional_email'])) {
    variable_set('additional_email', $form_state['values']['additional_email']);
  }
}

```

This adds a new submit handler to the form, which will trigger upon submit. If a value was supplied, it will set the variable.

What is `$email_default`? That is never defined.

However I would suggest a different approach, because:

* Variable can only hold one value, and this form item exists on every node. Every submission with a value will override the previous.
* Rules can read fields, why not add an email field on the node, and use *that* in the Rule
* You should do extra validation on the entered value to make sure it is a legit email value and not just any string with valid\_email\_address
* You can default the email field to be the `$email_default` you are checking for
* You could add cardinality for the email field and adjust the Rule if multiple people need to be notified

If you didn't use a custom form field, and instead added a real field on the node, you could ensure that any node can have any email address without relying on `variable_set` which as stated, will only ever allow one value to exist.

Rules is able to inspect your node and fetch a field value from it in order to use as a data variable in a later action, in this case, to send an email. If you do that, you don't really need any code at all.

---
Tags: 7, forms
---


# Question
Title: Lingotek Translation showing interim status for every translation
I am working with lingotek module in Drupal 8 and I am following all the procedures but still facing some issues on local setup. The automatic translation is taking place and it is displaying `interim status` every time after the translation is done, which is a state where incomplete translations can be published.

So, the translation part is not fully completed. I have followed the steps on fresh installation but still getting nowhere.

# Answer
That happens when the translation is not complete. This could happen because you have a pending review phase in your workflow. What happens if you use the "Check target status" operation?

PS: As @user73757 said, it's easier to get support in the Lingotek module issue queue.
> 0 votes

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


# Question
Title: How to modify the language switcher block to only use the language code instead of its full name?
In the Language selection block, I have only the possibility to use the full language name. How can I change it to use the language code, for example *FR* instead of *French*?

# Answer
> 3 votes
One possible solution would be to insert this snippet in your .theme file

In this example I am using bartik as a theme.

```
/**
 * Implements hook_preprocess_HOOK() for block.html.twig.
 */
function bartik_preprocess_block(&$variables) {
  if ($variables['plugin_id'] == 'language_block:language_interface') {
    foreach ($variables['content']['#links'] as $key => $value) {
      $variables['content']['#links'][$key]['title'] = strtoupper($key);
    }
  }
}

```

Please, let me know if this solution works for you.

Best regards,

Oleg

# Answer
> 1 votes
An issue for bringing that as settings in Drupal core: https://www.drupal.org/node/2135379

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


# Question
Title: How can I allow a person to create multiple orders at once, for both themselves and others?
I have a site that offers in-person trainings and I'm currently using CRM Core to track registrations. That is working just fine, but I am having trouble coming up with a flexible way to pay for these registrations online.

Example use case:

I have a group who will be taking a class together, say 5 people. I'd like to allow a single person (the person organizing the group) be able to register all 5 people (already possible), but then select which of these registrations to pay for, creating separate orders for those the organizer doesn't want to pay for.

Say I am registering myself, my spouse, my kid, and 2 friends. Each registration should create a line item, but I want the first 3 (me, spouse, kid) to be on one order I'll pay for immediately, with the other two becoming separate orders each owned by the other students.

Once I figure this out, it should be easy to then send emails to the other two students letting each know a new account has been created for them w/instructions on how to log in and pay for their registration.

This seems like something others would have thought about before, but I can't find any info on how to make it happen. Any suggestions?

# Answer
Honestly, this sounds like a place where your best option will be custom code. The only thing I could see you doing without custom code is creating two variants for your event registration products, one that is free as a "reservation" and one that is the full price as an actual registration. This means the line items would be present on the order until the customer completes checkout, at which point you could process the order to split it up and then send out e-mail notifications as needed. To capture the e-mail address information, I'd add a field to your line item type to collect it as part of the Add to Cart form, allowing you to loop over the line items later and create user accounts / generate e-mails on a line-by-line basis. The main challenge there will be grouping multiple "reservations" into a single order via a simple rules loop... at the end of the day, this really smells like an ideal use case for custom code.
> 1 votes

---
Tags: commerce
---


# Question
Title: How to have no more than 20 Entity references to another content type?
I have a content type with a entity reference to another content type/view. The current possible relations could be 1,2,3 .... until 10 or unlimited. These are given in the field attributes screens.

I need 20. After that the user is not allowed to add another field in the gui.

Any solutions how to do this?

# Answer
You should select unlimited as possible relations. Then, using a custom module, you can alter the node edit form to don't allow more than 20 items.

To do this, implement hook form alter:

```
function mymodule_form_node_form_alter(&$form, &$form_state, $form_id) {
  // do magic.
}

```

Inside you have to:

* Check the if the relations field has 20 item; if yes delete the element widget that adds another one (so user don't get confused because it seems more items can be added).
* Add a new validate handler to check related items are less than 21.
> 1 votes

---
Tags: 7, entities
---


title: Module not found via Composer

text:
# Question
Title: Module not found via Composer
I recently switched to drupal\_composer to manage my dependencies and updates. And so far I can really see the benefit of this work method, and highly encourage everyone to switch.

However, I tried installing the module Simple Oauth, but composer can't find it.

```
$ composer require "drupal/simple_oauth:^2.0-alpha4"
./composer.json has been updated
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
    - The requested package drupal/simple_oauth could not be found in any version, there may be a typo in the package name.

Potential causes:
 - A typo in the package name
 - The package is not available in a stable-enough version according to your minimum-stability setting
   see <https://getcomposer.org/doc/04-schema.md#minimum-stability> for more details.

Read <https://getcomposer.org/doc/articles/troubleshooting.md> for further common problems.

Installation failed, reverting ./composer.json to its original content.

```

When browsing composer, nothing is found either.

```
$ composer browse drupal/simple_oauth
Package drupal/simple_oauth not found
Invalid or missing repository URL for drupal/simple_oauth

```

Is this due to the alpha release not being published or something?

# Answer
It doesn't say the module was not found, it says there is no compatible version.

My composer version gives a much better error:

```
$ composer require "drupal/simple_oauth:^2.0-alpha4"
./composer.json has been updated
> DrupalProject\composer\ScriptHandler::checkComposerVersion
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
    - Conclusion: remove drupal/core 8.2.3
    - Conclusion: don't install drupal/core 8.2.3
    - drupal/simple_oauth 2.x-dev requires drupal/core ^8.3 -> satisfiable by drupal/core[8.3.x-dev, 8.4.x-dev].
    - drupal/simple_oauth 2.0.0-alpha4 requires drupal/core ^8.3 -> satisfiable by drupal/core[8.3.x-dev, 8.4.x-dev].
    - Can only install one of: drupal/core[8.3.x-dev, 8.2.3].
    - Can only install one of: drupal/core[8.4.x-dev, 8.2.3].
    - Installation request for drupal/core (locked at 8.2.3, required as ~8.2.0) -> satisfiable by drupal/core[8.2.3].
    - Installation request for drupal/simple_oauth ^2.0-alpha4 -> satisfiable by drupal/simple_oauth[2.x-dev, 2.0.0-alpha4].

```

2.0-alpha4 requires Drupal 8.3. Leaving out the version specifier installs it as "1.0.0-beta5", which is however not listed anymore on the project page and therefore probably not really supported anymore.

8.3.0 will be released pretty soon, so if this is a new project, you could already switch to the recently released 8.3.0-rc1, there will likely only be very few changes until 8.3.0. See https://www.drupal.org/core/release-cycle-overview
> 2 votes

---
Tags: 8, composer
---


title: Expose Custom Form in Block

text:
# Question
Title: Expose Custom Form in Block
A form was created with codes in a custom module, with three items that must be filled. After submission, the code will do it's magic and return the result on the same page, below the form.

I'll like to have the form alone in a block so that it can be placed anywhere on the websites and when filled from there, it will redirect to the main page and show the results.

I don't know which way to go please.

# Answer
First thing you have to do is to move the form into it's own block. That will require a `hook_block_info()`, to define the block, and `hook_block_view()`, to create the content of the block.

https://api.drupal.org/api/drupal/modules%21block%21block.api.php/function/hook\_block\_info/7.x https://api.drupal.org/api/drupal/modules%21block%21block.api.php/function/hook\_block\_view/7.x

Define the block:

```
function my_module_block_info() {
  $blocks['your_block'] = array(
    // info: The name of the block.
    'info' => t('Your Block Name'),
  );

  return $blocks;
}

```

Then create the content. You can use another function that contains the form.

```
function my_module_block_view($delta = '') {
  // This example is adapted from node.module.
  $block = array();

  switch ($delta) {
    case 'your_block':
      $block['subject'] = t('My Form');
      $block['content'] = drupal_render(drupal_get_form('my_module_myform_form'));
      break;
  }
  return $block;
}

function my_module_myform_form() {
  // Your form will go here.
  $form['my_value'] = array
  (
    '#type' => 'select',
    '#options' => array('' => '---', 1 => t('One'), 2 => t('Two'), 3 => t('Three')),
    '#required' => TRUE,
  );
  $form['submit'] = array
  (
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}

```

Next is to create a submit callback which redirects to your page. You don't need to register the callback. Drupal looks for the form function name with '\_submit' appended.

```
function my_module_myform_form_submit($form, &$form_state) {
  $form_state['redirect'] = 'some/path/' . $form_state['values']['my_value'];
}

```

And then we need to create the page:

```
function my_module_menu()
{
  $menu['some/path/%'] = array
  (
    'title' => 'My form submitted values',
    'page callback' => 'my_form_submitted_value_callback',
    // array(2) will pass the value of the wildcard to the callback function
    'page arguments' => array(2),
    'access callback' => TRUE,
  );
  return $menu;
}

function my_form_submitted_value_callback($submitted_value)
{
  return t('The value you submitted was: @value', array('@value' => $submitted_value));
}

```

If you need more than one value, there are more methods on this page like using $\_GET and session variables: https://www.drupal.org/node/1990276

Sources:
> 2 votes

---
Tags: 7, blocks
---


# Question
Title: How can i display user name and email address fields to the user on "My Account Page"?
I want to show the user, his/her email address on their "My Account" Page. I am not using any modules for the registration page, but just the default Drupal 7 registration fields.

How can i display user name and email address fields to the user on "My Account Page"?

# Answer
> 0 votes
You will need to create a custom module to achieve that functionality.

If you want to override tabs in view page

```
function mymodule_menu_alter(&$items) {
  $items['user/%user/view']['title'] = t('My account');
  $items['user/%user/edit']['title'] = t('Edit account information');
}

```

If you was to display additional info in view page

```
function mymodule_user_view($account, $view_mode, $langcode) {
  // hide unwanted fields
  hide($account->content['summary']['member_for']);
  hide($account->content['summary']['blog']);
  hide($account->content['user_picture']);

  // add information
  $account->content['summary']['#title'] = t('My Account');
  $account->content['summary']['personal'] = array(
    '#type' => 'user_profile_item',
    '#title' => t('Personal'),
    '#markup' => get_profile_details($account),
    '#weight' => -100,
  );
  $account->content['summary']['login'] = array(
    '#type' => 'user_profile_item',
    '#title' => t('Login'),
    '#markup' => get_profile_details($account, 'login'),
    '#weight' => -99,
  );
}

```

This function returns details in list. Feel free to add/delete details based on your requirements

```
function get_profile_details($account, $view = 'personal') {
  // profile details
  $items = array();
  switch($view) {
    case 'personal':
      if($account->picture) {
        $items[] = theme('image_style', array('path' => $account->picture->uri, 'style_name' => 'thumbnail'));
      }
      $items[] = t('Name: ').$account->field_account_first_name['und'][0]['value'].' '.$account->field_account_last_name['und'][0]['value'];
      $items[] = t('Email: ').l($account->mail, 'mailto:'.$account->mail);
      $roles = array();
      foreach($account->roles as $role) {
        if($role != 'authenticated user') {
          $roles[] = ucwords($role);
        }
      }
      if(count($roles) > 0) {
        $items[] = t('Role: ').implode(', ', $roles);
      }
      else {
        $items[] = t('Role: ').t('General user');
      }
    break;
    case 'login':
      $items[] = t('Username: ').$account->name;
      $items[] = t('Timezone: ').$account->timezone;
      $items[] = t('Member since: ').format_interval(REQUEST_TIME - $account->created);
      $items[] = t('Last login: ').format_interval(REQUEST_TIME - $account->access);
    break;
  }
  return theme('item_list', array('items' => $items));
}

```

Let me know if you need any help

---
Tags: views, users
---


# Question
Title: How do I create a new admin sub page and how to make it appear in the admin menu?
Let's say I have to create an extra users management views block for contributors role only, with some different columns, filters and actions available.

How do I create a simple page which is restricted to some roles only and automatically has the backend theming to put my views block in there? (I always put views blocks on pages, it makes editing views easier)

And last, how can I make that page appear in the admin toolbar as sub item of admin/people?

Do I have to write a custom module for that or maybe create a template file? Or is that maybe all in all a wrong approach?

# Answer
> 3 votes
I know there is already an accepted answer, which works perfectly fine, but I want to add an additional answer for those of us who arrive here from Google and, like me, need an answer based on php code that can be implemented in an custom module.

If you want to achieve the desired result, you can set your `hook_menu` entry to be of type `MENU_LOCAL_TASK`, this way the new page will be a new tab under the parent page, e.g. if the parent page is `admin/people` you set the path to `admin/people/mytab`:

```
function example_menu() {
  $items['admin/people/mytab'] = array(
    'title' => 'My Tab',
    'type' => MENU_LOCAL_TASK, // NB: this is a constant not a string
    // Etc.
  );
}

```

Now, regarding the theme: since this is under the `admin/` path, it should use automatically the admin theme.

However if you still want to use a custom theme for this page, you can do it in code by setting `theme_callback` in your `hook_menu` entry. The corresponding callback function should return a string with the machine-readable name of the theme. E.g.

```
function example_menu() {
  $items['my/path'] = array(
    'title' => 'My Tab',
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'my_page_callback',
    'theme callback' => 'my_theme_callback', // This is it.
  );

  return $items;
}

```

and the callback function:

```
function my_theme_callback() {
  return 'mytheme';
}

```

# Answer
> 5 votes
Easiest way I think of is to create a page display for you view. Set the path to admin/people/mypage and under the menu settings in views choose tab, give your menu item a title and keep the menu setting at Navigation as it defaults to.

Now if you navigate to admin/people you will see a new tab with your page and menu title.

In the views configuration you can add access restriction to your URL / menu item.

If you insist on not creating a page display and instead want to place your block on a page, without coding you own module I would use Panels and Page Manager. You will need the modules Ctools and Panels. Under structure and pages, create a new page and give it your URL, set it to have a menu item (as described in the Views example) and use Panels as variant type. Once your Panel is created you can place your block into any region available in the layout you choose.

---
Tags: 7, users, theming
---


# Question
Title: Delete node: Remove header, footer and rightbar in delete node page
I want to remove the header, footer and rightbar in a delete node page (node/.../delete). How can this be reached?

I already tried editing page--node--delete.tpl.php, but this does not work.

# Answer
Please follow suggestion from this link for page **https://www.drupal.org/docs/7/theming/template-theme-hook-suggestions**

If you have created a page using views then you can call template for views like (page--viewname.tpl.php).

if you go with the content node, You need to call template like (page--node--nodeid.tpl.php)
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: How to get form variables data into twig templates?
I have a form like:

```
 public function buildForm(array $form, FormStateInterface $form_state, $short_title = '') {
$title = 'xyz';
}

```

In my .module file, I have a theme function:

```
function ip_mcq_theme() {
  return [
    'take_mcq_form' => [
      'render element' => 'form',
    ],
  ];
}

```

How to get form variables like `$short_title` and `$title` mentioned in form build function in my `take-mcq-form.twig.html` file?

# Answer
> 4 votes
Put the custom variable in a key with a '#', so that the formbuilder doesn't try to render this as a form element.

*buildForm():*

```
  $form['#myvars']['var1'] = 'xyz';

```

In twig you can access the variable in `element`:

*form.html.twig:*

```
  {{ element['#myvars'].var1 }}

```

If you set a template in `#theme` of the form build

*buildForm():*

```
  $form['#theme'] = 'take_mcq_form';

```

you get a second template inside of *form.html.twig*, where you can access the variable in `form`:

*take\_mcq\_form.html.twig:*

```
  {{ form['#myvars'].var1 }}

```

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


# Question
Title: How to add a title attribute from a different field to a link produced by a view
I have a view that uses one field to produce a list of links to content.

I want to add a 'title' attribute to the link produced by the view that takes its value from a different field.

How does one do this in Drupal 8?

# Answer
> 1 votes
Thanks to zhilevan for pointing me in the right direction. After much trial and error this is the only thing I got to work other than completely rewriting the input with custom html.

1. I needed to add a "path to content" field. Note my fields are called 'field\_heading' and 'title' respectively.

Note: the field that will actually host the link has to be **at the bottom** of the list. I wasted ages trying to figure out why I couldn't target my title text before realising this...

2. You need to uncheck "Link to content" in the setting for the host field - in my case 'Heading'

3. In the 'Rewrite output' section you need to actually provide a link or it will not work - or at least I could not get it to work without it. So the 'path' field I added earlier was used here as the path for the link. I could then add title field to the title attribute. You can see the available replacement patterns in the drop down with that name.

and the title attribute override...

Anyhoo, that was what i had to do to get it to work. Hopefully it is useful to someone else. I would love to see a simpler way to do this.

# Answer
> 1 votes
You can achieve this by using views `Rewrite results` feature, Rewrite your Link with checking `Override the output of this field with custom text` and put your markup there and with Replacement patterns put your title as your link attribute title.

More details Provided by @Raf

Thanks to zhilevan for pointing me in the right direction. After much trial and error this is the only thing I got to work other than completely rewriting the input with custom html.

1. I needed to add a "path to content" field. Note my fields are called 'field\_heading' and 'title' respectively.

Note: the field that will actually host the link has to be **at the bottom** of the list. I wasted ages trying to figure out why I couldn't target my title text before realising this...

2. You need to uncheck "Link to content" in the setting for the host field - in my case 'Heading'

3. In the 'Rewrite output' section you need to actually provide a link or it will not work - or at least I could not get it to work without it. So the 'path' field I added earlier was used here as the path for the link. I could then add title field to the title attribute. You can see the available replacement patterns in the drop down with that name.

and the title attribute override...

Anyhoo, that was what i had to do to get it to work. Hopefully it is useful to someone else. I would love to see a simpler way to do this.

---
Tags: views, 8, navigation
---


# Question
Title: How to show 2 instances of the user profile form, displaying different form modes, on the same page?
I would like to show 2 instances of the User Profile edit form on the same page. One form mode only shows the username/password widget with the submit button. The other form mode only shows the contact information with the submit button.

When I try the following, I get `Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException: The "user" entity type did not specify a "user.change_password" form class`. Note that I've changed the form class to `change_password` as well.

```
$user = User::loadMultiple([$this->account->id()]);
$form = $this->entityFormBuilder->getForm($user[$this->account->id(), 'change_password']

```

I asked a similar question regarding custom entities but using that solution would require modifying core files.

Is it possible to do this?

# Answer
> 0 votes
You don't need to modify core files, you can modify the "user" entity type in a hook. This is how you add a form class for the form operation `change_password`:

*mymodule.module*

```
function mymodule_entity_type_build(array &$entity_types) {
  $entity_types['user']->setFormClass('change_password', 'Drupal\user\ProfileForm');
}

```

---
Tags: 8, forms
---


# Question
Title: how do i get fields value of webform before entering into database?
I want value of a hidden field of webform in custom module so that i could match it with other value from database to validate it

# Answer
> 1 votes
You can use `hook_form_alter` to achieve this in your custom module.

```
/**
 * Implementation of hook_form_alter().
 */

function your_custom_module_name_form_alter(&$form, &$form_state, $form_id) {
  // Add validation for a particular Webform node:
  if ($form_id == 'webform_id') {
    // Simply add the additional validate handler.
    $form['#validate'][] = 'mycustom_extra_validate';

    //$first = array_shift($form['#submit']);
    //array_unshift($form['#submit'], $first, 'mycustom_extra_submit');
  }
}

/**
 * Validation handler for Webform .
 */
function mycustom_extra_validate(&$form, &$form_state) {
  //condition to check validation
}

```

# Answer
> 0 votes
I am just giving the example how you can access hidden field in custom module,in my case i have added value to hidden field by doing custom code,you can take reference of below code:

```
function your_module_form_alter(&$form, &$form_state, $form_id){

 if ($form_id == 'webform_client_form_28') {

  $uid = arg(1);
   if ( arg(0) == 'user' && is_numeric($uid) ) {
       $account = user_load($uid);
       $form['submitted']['user_email']['#value'] = $account->mail;
       $form['submitted']['uid']['#value']=$uid;
   }
 }
}

```

---
Tags: webforms
---