title: Can I completely exclude a pane title?

text:
# Question
Title: Can I completely exclude a pane title?
I'd like to apply several panes without title to a panel (in Drupal 7).

I can select *Override title* and leave the input field blank, but this still leaves the wrapping HTML.

```
<div class="panel-heading">
  <h2 class="panel-title"></h2>
</div>

```

Can I completely exclude a title?

# Answer
> 0 votes
I learnt adding `<none>` to the title field does this.

---
Tags: 7, panels
---


title: remove save button on a particular page

text:
# Question
Title: remove save button on a particular page
I am creating a form which consists of 3 tabs. In the first tab form submit is by clicking on save button of type submit,in the second tab the submit is by jQuery, in the third tab the submit is by clicking on save button of type submit. My problem is I want the save button to appear on only two tabs i.e., only on first and third tab. I don't want the save button to appear on second tab bcoz that second tab form I submit using jquery.

How can I remove save button in second tab?

# Answer
> 0 votes
```
jQuery(document).ready(function() {
 if (window.location.pathname == '/recruiterForm/2') {
      jQuery('input#edit-submit').hide();
      }
});

```

I have solved this problem using jquery. I have used **window.location.pathname**. This property returns the pathname of current page. If pathname is equal to the required url then I am hiding the save button by using the save button id. This solution works for me.

---
Tags: forms
---


# Question
Title: "Explanation or submission guidelines" missing
In editing a content type on a Drupal 8 site, I added text to the *Explanation or submission guidelines*, but when I surf to the node create/edit form, the text is nowhere to be seen.

Is this a bug, or are there extra steps involved that aren't documented in the UI?

# Answer
That information is displayed in the help block. Make sure the theme you are using on those pages has a help block.

The Seven theme does have that by default, but either you've configured the node add/edit pages to use the front page theme, or you removed the help block.
> 3 votes

# Answer
You have to place the "Help" block in your administration theme block layout. Keep in mind that you need to have the Help module enabled to have the "Help" block available
> 1 votes

# Answer
Note that in Drupal 8, you currently may have to clear caches to see this text in the help block.
> 0 votes

---
Tags: nodes, 8
---


# Question
Title: How to make a popup on a node's content using the colorbox module?
In Drupal 7, all I had to do to add a popup with colorbox was add the CSS class colorbox to the link to create a nice popup. Now, using Drupal 8, I cannot figure out how to do this.

I can add colorbox to my fields, but I want to add it directly to the link `<a class="colorbox" href"".../a>` in the content body, but it is not working. I cannot figure out how to use inline colorbox either, if that is the solution.

How can I add the popup?

# Answer
> -1 votes
For creating pop-up's in colorbox, you can simply use Bootstrap Modal Window.

Don't forget to include the below ones:
1. bootstrap.min.css
2. jquery.min.js
3. bootstrap.min.js

FULL WORKING CODE:

```
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Small Modal</h2>
  <!-- Trigger the modal with a button -->
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Small Modal</button>

  <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog modal-sm">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">×</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
          <p>This is a small modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>
    </div>
  </div>
</div>

</body>
</html>

```

---
Tags: javascript
---


# Question
Title: How do I dump a variable that is too big for dump(var)?
I am working with the views-view-unformatted.html.twig file, and I am trying to use the following code.

```
{{ dump(row.content | keys) }}

```

The returned value is the following.

```
/var/www/html/example_site/vendor/twig/twig/lib/Twig/Extension/Debug.php:60:
array (size=5)
  0 => string '#theme' (length=6)
  1 => string '#view' (length=5)
  2 => string '#options' (length=8)
  3 => string '#row' (length=4)
  4 => string '#field_alias' (length=12)

```

With `{{ dump(row.content['#row'] | keys) }}` I get the following.

```
/var/www/html/example_site/vendor/twig/twig/lib/Twig/Extension/Debug.php:60:
array (size=0)
  empty

```

Based on it being empty, I assume it is not an array and proceed to use `{{ dump(row.content['#row']) }}`. When I do this I get a *504 Gateway Timeout* error. `max_execution_time` is set to 30.

How do I dump a variable that is too big for dump(var)?

# Answer
As a workaround, until Kint will be configurable via UI see #2405179, edit ***modules/devel/kint/kint/config.default.php*** and set `$_kintSettings['maxLevels']` to a lower number (the default is 7).

Try using 4. This will limit the depth of the array that gets dumped.
> 2 votes

# Answer
A good way to get around twig's limits is to add the preprocess function referenced in the twig debug HTML comments. Then use kint to dump the information.

If you are doing something that is called a lot of times and kint is overflowing memory, just add a global counter and limit the output to one or two items. Something like:

```
$mymod_$kint_count = 0;
function mymod_preprocess_page(&$variables) {
  global $mymod_kint_count;
  if ( $mymod_kint_count++ < 1 ) {
    kint($variables);
  }
}

```

Note: You will need the kint module and dev enabled for this to work.
> 0 votes

# Answer
Use of {{ dsm(row.content) }} will solve your problem. This code takes a little time irrespective of how much data, displays it all.
> 0 votes

---
Tags: theming, 8
---


# Question
Title: How do I display image title in "Manage Display"?
How do I display image title in "Manage Display"?

I have add title in my image. But it is not showing in article.

# Answer
> 0 votes
Image title is a part of the image field not the main node title. So, you can't see the image title field under manage display.

---
Tags: 7, nodes
---


# Question
Title: Add taxonomy terms to search autocomplete
I have a Drupal 8 website with default search bar in my homepage. I have installed the Search Autocomplete extension to extend its functionality. Everything works great, except it does not suggest taxonomy terms. Can you give me an idea to add taxonomy terms to its suggestions?

**Update:**

I'm sorry that this is not the question I suppose to ask, as I have mistaken the issue. The default search block, does not search taxonomies, but search for the content which belongs to that taxonomy. Let me show you an example:

Here the ***Vancouver*** is a taxonomy term, and the things that listed(ZHR DEL, Gas Town, etc.) are content which belongs to this term. If you type the same thing in autocomplete, it does not suggest above content nor taxonomy term.

What I want is to suggest the taxonomy in autocomplete, and show the taxonomy term in the search result. Any help is truly appreciated.

# Answer
Default search can either display users or content. Apart from this it won't show you any results.
> 1 votes

---
Tags: 8, search
---


# Question
Title: Programmatically accessing block content
Could anyone tell me how to programmatically access the field content of a custom block?

Thus far I've managed:

```
use Drupal\block\Entity\Block;
$block = Block::load($block_name);

if ($block) {
  $render = \Drupal::entityTypeManager()
    ->getViewBuilder('block')
    ->view($block);
}

```

However this doesn't give me access to the fields and their data.

# Answer
> 14 votes
Your code loads a configured block, not the content of a custom block.

This will load the field data of block content:

```
$custom_block = \Drupal::entityTypeManager()->getStorage('block_content')->load('1');
$fieldcontent = $custom_block->field_myfield->value;

```

# Answer
> 4 votes
I just wanted to explain the example code given in the other answer with more detail, which will save time to many users.

```
$custom_block = \Drupal::entityTypeManager()->getStorage('block_content')->load('1');
$fieldcontent = $custom_block->field_myfield->value;

```
1. block\_content is a database table in your Drupal project
2. 1 in `load('1')` is the ID value from that table
3. field\_myfield is a table field from the block\_content\__body table, for example block\_content\__body.body\_value

If you want to change data from block\_content\__body.body\_value field in your block, simply use this code.

```
$custom_block->body->value = 'TEST';

```

---
Tags: 8, blocks
---


title: How to export a view in Excel format?

text:
# Question
Title: How to export a view in Excel format?
I am using Drupal 8 and I used the Views data export module which handles XML and JSON as exporting formats.

Is there any way to export data in Excel format?

# Answer
As an alternative to the module you are using, try the PHPExcel module. Some details about it (from its project page):

> The PHPExcel module allows developers to export/import data to/from real Excel files.
>
> The idea behind this module is to have a single module for handling the export or import of Excel files, instead of multiple modules handling specific cases.
>
> The module provides no functionality as-is (the .module file is as good as empty). The phpexcel.inc file must be included to use the export or import functions in your own module.
> 1 votes

# Answer
You can add another view display that is a download link. It can then be added to your main view using the "Attachment" option.

The download link can then be in either a CSV or Microsoft XLS.
> 0 votes

---
Tags: views, importing-exporting
---


# Question
Title: Image gallery where I can insert images and video
I'm new to Drupal and is looking for at image gallery, where I can insert images and video, does such exist?

I have tried to search around, but unfortunately without any luck.

# Answer
There are a ton of ways ...

You can create your own view, see Flickr-like responsive photo gallery for Drupal 8

Or go for a module like juicebox, or a simple colorbox or (my favorite) photoswipe gallery. These modules use an image field (with multiple values), and then offer a display for the field. For videos you need to make a view using their handlers, not sure which suppports what now ..

You can go further and further .. fe. by using the media\_entity (now in core ! media 2.0) with slick\_media (more like a slideshow) etc. - see here https://drupal-media.gitbooks.io/drupal8-guide/content/

It really depends on your needs.
> 5 votes

---
Tags: 8, media
---


# Question
Title: Redirect to a specific page when user update their profile
Is there any way to redirect the user after save their profile information.

I would like to redirect them to a specific page.

To be clear, here is the Flow:

1. User go in his profile
2. He change his password information
3. The user click on Save Button
4. The information is save and I want to redirect him on a specific page (node/xxx)

# Answer
> 4 votes
Here's the code for Drupal 8 :

```
function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id === 'user_form') {
    $form['actions']['submit']['#submit'][] = '_mymodule_user_edit_form_submit';
  }
}
function _mymodule_user_edit_form_submit($form, &$form_state) {
  $form_state->setRedirect('entity.user.canonical', ['user' => \Drupal::currentUser()->id()]);
}

```

# Answer
> 3 votes
You can add a custom submit handler to the user edit form and then do the redirect there:

```
function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id === 'user_profile_form') {
    $form['#submit'][] = 'custom_submit_function';
  }
}

function custom_submit_function($form, &$form_state) {
  drupal_goto('node/xxx');
}

```

# Answer
> 1 votes
You can achieve it by rule , create a rule then redirect to a url after user update I create it for you, just change the url and import it

Go to `admin/config/workflow/rules/reaction/import` and import this url ( first change the url , I set it to jean-fransico :) )

```
{ "rules_redirect_after_user_update" : {
    "LABEL" : "redirect after user update",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_update" : [] },
    "DO" : [ { "redirect" : { "url" : "Jean-Francois" } } ]
  }
}

```

---
Tags: users, forms
---


# Question
Title: How to provide a contextual filter with an OR conjunction to a view?
I have users that can be associated with a single node of type foo. The node has a list of users that are associated with it. I populate the entity reference fields in the content type with a view, which filters users that aren't associated with foo `(user has no foo)`.

What I need to happen is that I need this view to also grab users that are associated with the specific node that I'm looking at, so when I try to add new users to the foo content type, the users that were associated with it beforehand remain associated with it `(user has no foo OR user's foo id equals current foo id)`. The problem is that the first filter is a normal filter, the second is a contextual filter. How can I, programmatically or otherwise, get the views to grab the users I need with those conditions?

**Edit:** Unfortunately, the views-related hooks aren't called when populating an Entity Reference, which makes things like `hook_views_query_alter` not a solution. So a more accurate question would be: *how can I get the entity reference to grab the users I need with the given conditions?*

# Answer
I guess you need to use **hook\_views\_query\_alter** and then you could add your **OR** condition.

```
function hook_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view->id() == 'machine_name_of_your_view' ) {
   //$query->where contains the filter conditions
   //i.e. 'Where' part of the query where you could add yours.
   var_dump($query->where);die;
  }
}

```

more from drupal.org
> 0 votes

---
Tags: 8, entities, views
---


# Question
Title: How to utilize custom form modes to edit a user entity?
My project requires two different pages to edit a user. The first one being at `/settings/{user}/my-profile`, where the user updates their name, address, etc. The other page is at `/settings/{user}/login-credentials`, where the user updates their username, password, etc.

After navigating to `/admin/structure/display-modes/form`, I have created a custom form mode called "My Profile" which has the id `user.my_profile`, and activated it at the bottom of `admin/config/people/accounts/form-display`.

Now I need to create a page that utilizes this new custom form mode, and I'm a bit lost.

I looked into how the standard user edit route is created at `/user/{user}/edit`, and I found the code in the route provider at namespace `Drupal\user\Entity;`. This is what is in that method (other routes have been removed)...

```
public function getRoutes(EntityTypeInterface $entity_type) {
  $route_collection = new RouteCollection();

  $route = (new Route('/user/{user}/edit'))
    ->setDefaults([
      '_entity_form' => 'user.default',
      '_title_callback' => 'Drupal\user\Controller\UserController::userTitle',
    ])
    ->setOption('_admin_route', TRUE)
    ->setRequirement('user', '\d+')
    ->setRequirement('_entity_access', 'user.update');
  $route_collection->add('entity.user.edit_form', $route);

  return $route_collection;
}

```

Then I did some research on the routing system, and I've created a routing.yml file. The name of my module is `sc`, and the file is at `modules/custom/sc/sc.routing.yml`.

sc.routing.yml

```
sc.my_profile.edit:
  path: '/settings/{user}/my-profile'
  defaults:
    _entity_form: 'user.my_profile'
    _title_callback: 'Drupal\user\Controller\UserController::userTitle'
  requirements:
    user: '\d+'
    _entity_access: 'user.update'
    _permission: 'access content'

```

I'm logged in as user1, cleared the cache, and when I navigate to `/settings/1/my-profile`, I get "Page Not Found". Am I on the right track? How do I create these pages with different form modes?

# Answer
> 3 votes
You have to add the form mode in the handlers section of the user entity:

```
/**
 * Implements hook_entity_type_build().
 */
function mymodule_entity_type_build(array &$entity_types) {
  $entity_types['user']->setFormClass('my_profile', 'Drupal\user\ProfileForm');
}

```

Use the standard class `ProfileForm` as you only want a set new form mode, not a new form class.

Then you can use this new handler in place of `user.default` in the routing file:

```
'_entity_form' => 'user.my_profile',

```

---
Tags: 8, users
---


# Question
Title: How to get add term form of taxonomy inside node type form?
I'm trying to render taxonomy add term form inside content type ('article') add form. (`node/add/article`)

In `hook_form_alter`, I called this callback function on abutton.

```
public function _cvv_ajax_callback(VocabularyInterface $taxonomy_vocabulary) {
    $taxonomy_vocabulary = 'cvv';
    $term = \Drupal::entityManager()->getStorage('taxonomy_term')->create(['vid' => $taxonomy_vocabulary->id()]);
    return \Drupal::entityFormBuilder()->getForm($term);
  }

```

But this is not return form in my node/add page, rather giving me error:

> error php Drupal\Core\Entity\EntityStorageException: Missing bundle for entity type taxonomy\_term in Drupal\Core\Entity\ContentEntityStorageBase-\>doCreate()

I tried

```
if ($vocabulary = taxonomy_vocabulary_machine_name_load('jenis_dokumen')) {
  module_load_include('inc', 'taxonomy', 'taxonomy.admin');
  $edit = array();
  $taxonomy_form = drupal_get_form('taxonomy_form_term', $edit ,$vocabulary);
  return drupal_render($taxonomy_form);
}

```

but this is also not working in Drupal 8.

Also tried:

```
 $form = \Drupal::formBuilder()->getForm('\Drupal\taxonomy\Controller\TaxonomyController::addForm','plan_features');

```

didn't worked :'(

Lastly I tried Inline Entity Form , the problem with module is, when a add term form get rendered inside node type form and if you do

`kint($form_id);` inside `hook_form_alter`, you won't get any form id for this inline form. Hence if you want to add custom validations for the term title, it won't be achievable even by hooks this module provides.

Please suggest a way to do this.

# Answer
> 1 votes
Have you tried this module? It's pretty much what you could need:

Inline Entity Form

# Answer
> 0 votes
Your first solution should work. Use the name of the vocabulary instead of the id ..

```
$term = \Drupal::entityManager()->getStorage('taxonomy_term')->create(['vid' => $taxonomy_vocabulary->label()]);

```

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


# Question
Title: programmatically save image to node with link in custom module
Im quite new to drupal 7. But my approach is learning by doing. This have worked fine until now....

My problem is, that I in a custom module, with a form submit, save a node with all the filled fields, including images. (Code below)

My problem is that i want to add a, a href to the images i save, so when opening the node the images will link to the link i have saved.

Is this even possible?

My node\_save with pictures is like this:

```
$who = $user->uid;
$test = 'term_id' . $who;
$test1 = 'sales_id' . $who;
variable_set($test, $base_url . '/Sales/' . $form_state['values']['sales_id_terms']);
variable_set($test1, $base_url . '/Sales/' . $form_state['values']['sales_id_comp']);

$term_id = $form_state['values']['sales_id_terms'];
$file_temp_top = file_load($user->top_banner);
$file_temp_bund = file_load($user->bund_banner);
$file_temp_power = file_load(110);

//$file_temp_top = file_save_data($file_temp_top, 'public://firm_images/', FILE_EXISTS_REPLACE);

$node1 = new stdClass();  // Create a new node object
$node1->type = 'product_link';  // Content type
$node1->language = LANGUAGE_NONE;  // Or e.g. 'en' if locale is enabled
$node1 = node_submit($node1);
node_object_prepare($node1);  //Set some default values
$node1->status = 1;   // (1 or 0): published or unpublished
$node1->promote = 0;  // (1 or 0): promoted to front page or not
$node1->sticky = 0;  // (1 or 0): sticky at top of lists or not
$node1->comment = 1;  // 2 = comments open, 1 = comments closed, 0 = comments hidden

$node1->title = $form_state['values']['sales_name'] . '_1';
$node1->field_betingelser['und'][0]['value'] = $terms;
$node1->field_top_banner['und'][0] = array(
                'fid' => $file_temp_top->fid,
                'filename' => $file_temp_top->filename,
                'filemime' => $file_temp_top->filemime,
                'uri' => $file_temp_top->uri,
                'status' => 1,
                'display' => 1,
);
$node1->field_bund_banner['und'][0] = array(
                'fid' => $file_temp_bund->fid,
                'filename' => $file_temp_bund->filename,
                'filemime' => $file_temp_bund->filemime,
                'uid' => 1,
                'uri' => $file_temp_bund->uri,
                'status' => 1,
                'display' => 1,
);
$node1->field_powerd_by['und'][0] = array(
                'fid' => $file_temp_power->fid,
                'filename' => $file_temp_power->filename,
                'filemime' => $file_temp_power->filemime,
                'uid' => 1,
                'uri' => $file_temp_power->uri,
                'status' => 1,
                'display' => 1,
                'href' => $GLOBALS['root_url'] . '/new-products/',
);
$node1->field_terms_id['und'][0]['value'] = $form_state['values']['kon_id_terms'];

// Add author of the node
$node1->uid = $user->uid;

// Set created date
$node1->date = 'complaint_post_date';
$node1->created = strtotime('complaint_post_date');

$new_path = 'sales/' . $node1->field_terms_id['und'][0]['value'];
$node1->path = array('alias' => $new_path);

// Save the node
node_save($node1);

```

# Answer
I'm assuming the content type you're saving is currently using the included Image field. This field does not allow you to include a url that the image links to (it does allow you to link to the image itself or the content that it belongs to).

Answering your question directly, it sure is (and there's many ways)!

You can use the module linkimagefield. I think this one is closest to what you're asking. It adds a field type that includes a url that the image can then link to.

However, if the url the image links to is to be used in other places too, then the module image\_link\_formatter might be better suited for the task. With this module, you would add a Link field to your content type (that can be shown by itself or hidden), and set up the image field's display (admin/structure/types/manage/\[node\_type\]/display) to use the link field as the target.
> 0 votes

# Answer
The file field will handle the display of the file regarding to its settings in the FieldUI.

So referencing the fid is sufficient:

```
$node1->field_top_banner['und'][0]['fid'] = $file_temp_top->fid;

```
> 0 votes

---
Tags: nodes, media
---


title: Menu settings does not change menu

text:
# Question
Title: Menu settings does not change menu
I have created a new menu called `new-menu`. I go to Admin \> Structure \> Menus \> Settings

And I choose "New Menu" for the "Source for the Main links" option.

However, on my site, it still shows the Main Menu links (instead of New Menu links).

What am I missing?

**Note:** I am running a custom "Drupal core" from my university, and I've never worked with Vanilla Drupal, so I'm not sure if something is missing that should be there.

# Answer
> 1 votes
You need to change the menu under Structure \> Blocks. Find the Main Menu block that is active and click its "Configure" link. The third option is Menu... change this to dropdown to your new-menu.

---
Tags: 7
---


# Question
Title: Get the url for an images in a Field Collection for the Node Template
This is a bit messy so bear with me. I've built a node with a field collection 'field\_meet\_videos'. That field collection contains another field collection 'field\_about\_video'. The inner field collection has 3 fields (two text fields and an image field 'field\_image'). This field collection is also used as multifield so it'll be used more than once (lets say 3 times for this example).

What I'm trying to do is just get a printed output of the image url (with imagecache style) on the node template (to use them as html element backgrounds).

```
<?php
  $content['field_meet_videos'][0]['entity']['field_collection_item'][34]['field_about_video'][0]['entity']['field_collection_item'][35]['field_image']
?>

```

This looks to contain enough that I could cobble together a url by sticking these variables into a url string but it feels like there must be a better way to access these variables.

# Answer
> 0 votes
You can find a good example of how to decompose the field\_collection with a foreach in drupal.org

https://www.drupal.org/node/1155752#comment-12170687

```
if (isset($node->field_gallery_images)) {
  $nodeField = field_get_items('node', $node, 'field_gallery_images');
  if (!empty($nodeField)) {
    foreach ($nodeField as $key => $item) {

      $field_collection_item = field_collection_item_load($item['value']);
      $item_wrapper = entity_metadata_wrapper('field_collection_item', $field_collection_item);

      print '<div class="yourCustomClass">';
      $field_image = $item_wrapper->field_gallery_image->value();

      print theme('image_style', array('style_name' => 'large', 'path' => $field_image['uri']));
      print '</div>';
  }
}

```

---
Tags: 7, theming, nodes
---


# Question
Title: How to unpublish a node and any related nodes?
I am currently working on a problem where, when a *Physician* node has been unpublished, its related *Review* nodes will be unpublished as well. They do have an entity reference built in to distinguish which *Review* belongs to which *Physician*.

I have been working with the Rules, Views Bulk Operations (VBO), and Workflow modules to get this to work.
I have many failed attempts using the Rules module, so I don't have any code to supply.

Would anyone be able to point me in a direction?

# Answer
Yes this seems perfectly possible with Rules ... In your case, the crucial part of such rule is a Rules Action to perform a **Loop**. If you're not familiar with such loops, then I strongly recommend to have a look at the tutorial titled "Lists and loops".

In your case, you should use (at least) have a Rules Action to create a loop related to your '*related "Review" nodes*' (as in your question). After you do, you should iterate over each item in that list. And for each iteration you should then perform a Rules Action to "unpublish the review being processed in the loop".

***Done***

PS 1: Refer to my answer to "How to set multiple values to an unlimited Term Refence field with Rules" for some sample rules that are like a variation of your question here.

PS 2: I assume this is about D7 ...
> 3 votes

---
Tags: 7, nodes, rules
---


# Question
Title: Redirect to the front page with a different language
i have a question about redirecting to a page with a different language. I found this old post for drupal 7 but I doesn't really help me - https://www.drupal.org/node/1280468

Now we are in Drupal 8 and the redirect works like this:

```
return new RedirectResponse(\Drupal::url('<front>'))

```

But how can I set the language for the redirect? In my code I have the languagecode like NZ for New Zealand.

# Answer
You can try this code

```
 <?php

 use Drupal\Core\Url;
 use Symfony\Component\HttpFoundation\RedirectResponse;

 $language = Drupal::languageManager()->getLanguage('vi');
 $url = Url::fromRoute('<front>', [], ['language' => $language]);
 $response = new RedirectResponse($url->toString());
 $response->send();

```
> 20 votes

# Answer
Within your controller method:

```
$url = \Drupal\Core\Url::fromRoute('<front>')->toString();
return new RedirectResponse($url);

```
> -1 votes

---
Tags: 8, redirection
---


# Question
Title: How to check whether \Drupal\Core\Archiver\Zip::extract() succeeded?
I called \Drupal\Core\Archiver\Zip::extract() to extract files from an archive. How can I tell whether extraction was successful?

# Answer
The Drupal Zip class is just a wrapper around the PHP ZipArchive class.

As @tenken already mentioned the wrapper just returns itself:

```
  /**
   * {@inheritdoc}
   */
  public function extract($path, array $files = []) {
    if ($files) {
      $this->zip->extractTo($path, $files);
    }
    else {
      $this->zip->extractTo($path);
    }

    return $this;
  }

```

I guess that your best option is to retrieve the ZipArchive object itself via the `getArchive()` method of the Zip class. On the ZipArchive class call the `extractTo()` method and check its output (TRUE or FALSE).

I am currently working on a rewrite of the archiver classes to use PharData: https://www.drupal.org/node/2891871. The PharData class throws exceptions on failure. If this issue is done and the patch lands you are able to catch exceptions to check if the archive operations were successful.
> 3 votes

---
Tags: 8
---


# Question
Title: Why is BaseFieldDefinition::getDisplayOptions($display_context) returning NULL
I'm trying to get the weight of each field (of a form) in its display.

```
$fields = $entityManager->getFieldDefinitions($entity_type, $bundle);

foreach ($fields as $field_name => $field_definition) {
  $field_definition->getDisplayOptions('form'); //returns NULL
}

```

This returns NULL. $field\_definition definitely has stuff inside of it. any ideas?

# Answer
The `getFieldDefinitions()` method returns NULL if the field is not displayed. From the docs:

> Return value
>
> array|null The array of display options for the field, or NULL if the field is not displayed.

The code below is responsible for returning the correct value:

```
  /**
   * {@inheritdoc}
   */
  public function getDisplayOptions($display_context) {
    return isset($this->definition['display'][$display_context]['options']) ? $this->definition['display'][$display_context]['options'] : NULL;
  }

```

As you can see the `$this->definition['display'][$display_context]['options']` array has to be set. If it isn't set the method returns NULL.
> 0 votes

---
Tags: 8, entities
---


# Question
Title: How do I fetch user profile data in search api entity (node) view?
I've one search api index view of node type. Then each user have profile. So I wanted to fetch profile data of that entity created user. In normal view it can be easily done with relationship. But in search api view not able to create relationship. Any idea?

Same way I wanted flag relationship also but it's not happening in search API view. Normal view it's fine.

# Answer
Your search api view is only able to list what has been indexed, so you should add the node author to the search api index.

After this, in search api, you should be able to add 'related fields'.

After adding items to be indexed in search api, make sure you reminded your site!
> 0 votes

---
Tags: users, search
---


# Question
Title: How to fix errors when installing varbase with Composer?
I'm using Drupal 8 and I'm trying to install the varbase distribution from the command line, on Windows with Acquia Dev Desktop.

The steps I did are:

* Disable opcache
* Check `composer -V >>> result`
* Run `composer create-project Vardot/varbase-build:^8.4.06 %1 --no-dev --ignore-platform-reqs`

This is causing the following error:

> * Installing vardot/varbase (8.4.06): Downloading (100%)
> Writing lock file
> Generating autoload files
> PHP Parse error: syntax error, unexpected 'class' (T\_CLASS), expecting identifier (T\_STRING) or variable (T\_VARIABLE) or '{' or '$' in C:\www\tmp\_var\vendor\drupal-composer\drupal-scaffold\src\PrestissimoFileFetcher.php on line 34
> Parse error: syntax error, unexpected 'class' (T\_CLASS), expecting identifier (T\_STRING) or variable (T\_VARIABLE) or '{' or '$' in C:\www\tmp\_var\vendor\drupal-composer\drupal-scaffold\src\PrestissimoFileFetcher.php on line 34

I installed composor on windows Url: https://getcomposer.org/download/

(This is besided the compososer which is included in Acuia Desktop Version 2)

```
C:\www>composer self-update
You are already using composer version 1.5.1 (stable channel).

```

Then I exectuted commando:

```
composer create-project Vardot/varbase-project:^8.4.07 varbaseyellowbird --no-dev >> installlog.txt

```

After running it my project drupal folder was not looking good so I runned it again.

# Answer
Drupal 8 requires PHP 5.5.9 or greater. The error is informing you that you have a lower version than that installed; specifically that the functionality for obtaining class name using `::class`, which was added in 5.5, is missing.

The solution is to upgrade PHP to a version that Drupal supports.
> 2 votes

# Answer
**PHP** must be **5.6**

**Warning:** About composer

https://getcomposer.org/download/

As we dedicated that composer had 3 changes updates under 10 days

1.5.1 (2017-08-09) 1.5.0 (2017-08-08) 1.4.3 (2017-08-06) 1.4.2 (2017-05-17) 1.4.1 (2017-03-10)

Which composer version are you using?!

After updating the composer:

```
   $ sudo composer self-update 1.5.1

```

You could use:

```
$ composer create-project Vardot/varbase-project:^8.4.06 PROJECT_DIR_NAME --no-dev --no-interaction

```

or

```
$ composer create-project Vardot/varbase-project:^8.4.07 PROJECT_DIR_NAME --no-dev --no-interaction

```

As we started to use Vardot/varbase-project from varbase 8.4.06

To read more https://www.drupal.org/node/2903606
> 0 votes

---
Tags: composer
---


title: Image field file upload issue

text:
# Question
Title: Image field file upload issue
I'm using Drupal 8 and paragraphs together, and I've got an image field attached to an image paragraph. When adding content, if I nest this inside of another paragraph (as a paragraph reference field), the file upload fails. I get the throbber gif, and then "No file chosen." If I use this paragraph type without nesting it, it works fine.

Logs and watchdog show no errors, and all other file related things (logo's, other image and file fields) work properly on their own (verified it's not a permissions or other related issue).

# Answer
Spent some time looking around for an answer to this, so I thought I'd write it up even though I figured it out.

The combination of machine names involved in my nesting for the paragraph type and the paragraph reference field were overloading the ajax link length. I shortened the paragraph reference field machine name and nesting now works beautifully!
> 2 votes

---
Tags: files, paragraphs
---


# Question
Title: Views Slideshow: how to change items per slide based on screen resolution
I have a Views Slideshow slider with 3 items per slide (see below).

I am looking for a way to make it change the items per slide number dynamically when the screen width hits a certain breakpoint -for example 2 items per slide on tablet screen and 1 item per slide on mobile screen.

Been trying for few days but without success. I'm able to access the number of slides in the JSON var slideNumber = drupalSettings.viewsSlideshowCycle\["#views\_slideshow\_cycle\_main\_publications\_featured\_slider-block\_1"\].items\_per\_slide;

Any ideas are welcome.

# Answer
> 1 votes
We use the Owl carousel for this. It lets you specify four breakpoints and the number of slides to show.

There is a D8 recommendation for Flickity but it has some licensing restrictions.

# Answer
> 0 votes
I would recommend you do this in a custom way. Output the view in a simple unordered list and use a is library for the carousel. Owl carousel is my favourite, it's got the responsiveness you require.

# Answer
> 0 votes
I agreed with Kevin howbrook and CG Monroe to use owl carousel module or alternative , but You can alter Drupal JS variables by implementing **hook\_js\_settings\_alter** in your module,

```
function MYMODULE_js_settings_alter(array &$settings, \Drupal\Core\Asset\AttachedAssetsInterface $assets) {
  if (isset($settings['viewsSlideshowCycle'])) {
    $settings['viewsSlideshowCycle']['#views_slideshow_cycle_main_publications_featured_slider-block_1']['items_per_slide'] = '1';
  }
}

```

---
Tags: 8
---


# Question
Title: Change the title of date_popup filed in custom form
I'm building a custom form in Drupal 7 and i need to use the date\_popup widget in it. It all works as expected, except the title of the field.

My code is:

```
  $form['filter']['start_date'] = array(
    '#type' => 'date_popup',
    '#date_format' => 'd-m-Y',
    '#title' => t('Start date'),
  );

  $form['filter']['end_date'] = array(
    '#type' => 'date_popup',
    '#date_format' => 'd-m-Y',
    '#title' => t('End date'),
  );

```

But it keeps showing the default label "Date" for the field, as you can see on in the picture below.

Can you please let me know how can i put **Start date** and **End date** as field labels instead of just **Date**, or correct me if i'm doing something wrong

# Answer
> 4 votes
Just use the following code:

```
'#date_label_position' => 'none',

```

your code :

```
$form['filter']['start_date'] = array(
    '#type' => 'date_popup',
    '#date_format' => 'd-m-Y',
    '#title' => t('Start date'),
    '#date_label_position' => 'none',
  );

  $form['filter']['end_date'] = array(
    '#type' => 'date_popup',
    '#date_format' => 'd-m-Y',
    '#title' => t('End date'),
    '#date_label_position' => 'none',
  );

```

# Answer
> 3 votes
You can unset the labels like below:

```
function <module_name>_date_popup_process_alter(&$element, &$form_state, $context) {
  if ($element['#name'] == '<fieldname>') {
    unset($element['date']['#title']);
  }
}

```

# Answer
> 2 votes
Solution i came up with is following:

```
  $form['filter']['start_date'] = array(
    '#type' => 'date_popup',
    '#date_format' => 'd-m-Y',
    '#title' => t('Start date'), //set desired title
    '#title_display' => 'invisible', //but hide it from showing
  );

```

Next, implement hook\_element\_info\_alter():

```
function my_module_element_info_alter(&$type) {
  if (isset($type['date_popup'])) {
    $type['date_popup']['#process'][] = 'my_module_date_popup_process'; //name of the process function, can be anything
  }
}

```

and then set default title equals the title from form element:

```
//process function called from hook_element_info_alter
function my_module_date_popup_process($element, $form_state, $complete_form) {
  if ($complete_form['form_id']['#id'] == 'edit-my-form-id') {
    $element['date']['#title'] = $element['#title'];
  }
  return $element;
}

```

Result is like this:

# Answer
> 1 votes
I only got this to work in Drupal 7.43 by hacking the date\_popup module.

I added the following code in line 336 to the file date\_popup.module found in sites/all/modules/contrib/date/date\_popup/date\_popup.module (your installation might omit the contrib folder)

```
// Fixes bug where title wasn't getting updated in hook
if (isset($element['#title'])) {
  $element['date']['#title'] = $element['#title'];
  $element['#title_display']  =  'invisible';
}

```

Hope this helps someone, I took a long time to figure it out.

---
Tags: forms, datetime
---


# Question
Title: What is the correct way to attach an arbitrary field from a different content type to an existing form?
I have a content type with a title and item id fields. The item ID field is a simple decimal and has unlimited entries. It acts as a reference to another field on a different content type.

In `hook_form_alter()`, I attach an AJAX callback to each existing item ID element. When the AJAX callback is called, I add the values that already exist from the other content type (image, a couple taxonomy terms), and two input elements to the results div. The two inputs are fields that exist on the other content type.

The way I do this is by loading the node whose item ID value correlates and adding it to the form (using a custom view type that only displays the fields I want). As for the inputs, I use `drupal_get_form()` to get the other content type's node form and copy the input element arrays into the form that I'm modifying. (This is the part that feels like cheating.)

On the page, everything displays fine. The problem is the form submission. When the new input elements try to validate, it fails. I've dug into the source code and discovered that the field does not exist in the $form\_state array. That is to say, the corresponding `$form_state['field'][$field_name]` is missing.

My suspicion is that, upon splicing the form elements into the new form, the '#parent' and '#array\_parent' arrays are not being updated correctly, despite being sure to add `$form_state['rebuild'] = TRUE` to `hook_form_alter()`.

Is there a more correct way to add an arbitrary field from a different bundle to my form?

I considered using `field_attach_form()`, but I can't wrap my head around what the `$entity` argument should contain.

PS. I plan to handle the additional fields in a `hook_node_prepare()`, as I doubt shoving them into this content type would work!

# Answer
> 0 votes
> I considered using `field_attach_form()`, but I can't wrap my head around what the `$entity` argument should contain.

It's the entity for which you want to show the form elements to edit its fields. For example, if you want have a reference to a node in `$node`, and you want to add the form elements to edit its fields, you add the following line to the code.

```
field_attach_form('node', $node, $form, $form_state, entity_language('node', $node));

```

The validation handler for the form should then call either one of these functions.

The first function builds the entity object from its `$form_state` parameter; the second function requires the entity object as second parameter.

Keep in mind that, despite the fact the UI allows you to add fields to a content type (e.g. add a *Portrait* image field to a *Biography* content type, but not to a *Blog* content type), for Drupal the entity to which the fields are attached is a node, which means you need a node object. passing as entity a string containing the machine name of the content type doesn't produce the expected result.

---
Tags: nodes, forms
---


# Question
Title: How do I validate the term title in hook_taxonomy_term_presave()?
I rendered the form to create a taxonomy term via the Inline Entity Form module.

Is there a way to validate the values submitted in that form using `hook_taxonomy_term_presave()` or another hook?
I tried with `hook_form_alter()`, but it didn't work.

# Answer
> 0 votes
I assume you should be looking at hook\_form\_FORM\_ID\_alter instead of hook\_taxonomy\_term\_presave for validating the term title before saving.

```
/**
* Implements hook_form_FORM_ID_alter().
**/
function mymodule_form_taxonomy_form_term_alter(&$form,  &$form_state, $form_id) {
  // Check for tags bundle.
  if($form['#bundle'] == 'tags') {
    // Apply custom validator.
    $form['#validate'][] = '_mymodule_custom_term_validator';
  }
}

```

My custom validator.

```
/**
 * My custom validator for tags.
 **/
function _mymodule_custom_term_validtor() {
  // Check for term name is test.
  if(form_state['values']['name'] == 'test') {
    form_set_error('name', 'Title cannot be "test"');
  }
}

```

# Answer
> 0 votes
`hook_taxonomy_term_presave()` is not thought for validating what submitted in a form. In fact, it doesn't have any way to stop Drupal from saving the taxonomy term, nor does it allow users to correct the wrongly submitted value. That is what a validation handler does.

In this case, since the form to create a taxonomy term is added with the *Inline Entity Form* module, the hook to implement is `hook_inline_entity_form_entity_form_alter()`.

```
function mymodule_inline_entity_form_entity_form_alter(&$entity_form, &$form_state) {
  if ($entity_form['#entity_type'] == 'taxonomy_term') {
    // Add the form validation handler.
  }
}

```

The form elements are added by `TaxonomyTermInlineEntityFormController::entityForm()` which uses the following code.

```
$entity_form['name'] = array(
  '#type' => 'textfield',
  '#title' => t('Name'),
  '#default_value' => $term->name,
  '#maxlength' => 255,
  '#required' => TRUE,
  '#weight' => !empty($extra_fields['name']) ? $extra_fields['name']['weight'] : -5,
);
$entity_form['description'] = array(
  '#type' => 'text_format',
  '#title' => t('Description'),
  '#default_value' => $term->description,
  '#format' => $term->format,
  '#weight' => !empty($extra_fields['description']) ? $extra_fields['description']['weight'] : -4,
);

$langcode = entity_language('taxonomy_term', $term);
field_attach_form('taxonomy_term', $term, $entity_form, $form_state, $langcode);

```

---
Tags: taxonomy-terms, hooks
---


# Question
Title: Show video thumbnail and download link in view
I want to show a view page such that a grid of video thumbnails with download button below it will be displayed. As shown below:

I tried video module to display video. But it fails to give file path. Because of which I'm not able to achieve it.

Then I tried with normal file field. But I'm not able to show the video using file field.

I rewrote this file field as:

and then in **Custom Text** field I wrote below code.

```
{% if field_file_vid %}
<div class="col-md-4">
<div class="gallery-video">{{ field_file_vid }}</div>
<div class="download"><a href="{{ field_file_vid }}" download>Download</a></div>
</div>
{% endif %}

```

In this case only download link is working not the video.

How to achieve this requirement?

# Answer
Add *field\_file\_vid* again, check mark exclude from display and this time don't use *URL to File* as formatter, use a different formatter that renders the video.

Rearrange the fields

so that this new field is above the original field.

Now in your original field's rewrite results, use this as your 3rd line:

```
<div class="gallery-video">{{ field_file_vid_1 }}</div>

```
> 1 votes

---
Tags: views, 8
---


# Question
Title: How can I use xx time ago in Drupal 8 comments?
I use Drupal 8 and want the date of comments just show "***xx time ago***".

I added this code to `mytheme.theme`, but it does not work:

```
function mytheme_preprocess_comment(&$variables) {
/** @var \Drupal\Core\Datetime\DateFormatterInterface $formatter */
$date_formatter = \Drupal::service('date.formatter');

$variables['foo'] = $date_formatter->formatDiff(REQUEST_TIME - 12345, REQUEST_TIME, [
'granularity' => 3,
'return_as_object' => TRUE,   ]); }

```

And I use `{{ foo }}` but that does not show "time ago" either. Other things I tried (and which didn't work either):

* `{{ created|date_modify }}`
* `{{ created|time_deff }}`
* `{{ created }}`

Any help/hints about how I can do this?

**Note**: using the same logic as in my previous question (How can I use 'xx time ago' as date format?) and using `MYTHEME_preprocess_comment` instead (as suggested by Neograph734) does not seem to work for comments.

# Answer
> 3 votes
Have a look at what is mentioned on "Formatting the way the date/time is displayed in Drupal 8". Here is a quote from it:

> You can change the date format for comment using template\_preprocess\_comment(). For example, normally in comments the comment created time is displayed like Thu, 12/17/2015 - 23:04. We can change the format to look like 3 weeks 5 Days ago.

And this is the sample code mentioned below it:

```
/**
* Implements hook_preprocess_comment
*/
function THEME_NAME_preprocess_comment(&$variables) {
  // Getting the node creation time stamp from the comment object.
  $date = $variables['comment']->getCreatedTime();
  // Here you can use drupal's format_date() function, or some custom php date formatting.
  $variables['created'] = \Drupal::service('date.formatter')->formatInterval(REQUEST_TIME - $date);
  $variables['submitted'] = t('@username commented !datetime', array('@username' => $variables['author'], '!datetime' => '<span class="comments-ago">' . $variables['created'] . ' ago </span>'));
}

```

I haven't tested this code (yet), but it looks pretty close to what you're asking for ...

---
Tags: 8, datetime, comments
---


# Question
Title: How to save content created by selected roles in an external database?
My Drupal 7 site needs to have articles, faq, pages, blog (not confirmed) and forum. But client can't store any data coming from front end. It can include the registrations from front end. That data need to be stored on external database and admin and users will access that data from the drupal site.

More specific, if user add comment or topic in forum, it should be saved in external database, and if admin adds a page from admin, it should be saved in local database. Moreover, even registration done from front end, needs to saved in external database

I suggested that we can use complete database externally which can be done easily but suggestion is rejected. Anyone can tell me any solution?

**Note**: the only solution I can think of is to create a custom module and use hooks for database functionality where I will check which content type is been called (means create, read, update and delete) and depending on that I will switch the database execute the query and return the data. I need to confirm which hooks I need to use.

# Answer
Yes you can do that.

There are two method for configuring external database.

1. Inside settings.php
2. Inside Module directly.

**1. Inside settings.php**

```
$databases = array();
$databases['default']['default'] = array(
  // Drupal's default credentials here.
  // This is where the Drupal core will store its data.
);
$databases['my_other_db']['default'] = array(
  // Your secondary database's credentials here.
  // You will be able to explicitly connect to this database from your modules.
);

```

In your module:

```
// Use the secondary database we set up earlier
db_set_active('my_other_db');

// Run some queries, process some data
// ...

// Go back to the default database,
db_set_active();

```

**2. Inside Module directly.**

If your module will be alone in using the secondary database you can define the connection directly in your module:

```
  $other_database = array(
      'database' => 'databasename',
      'username' => 'username', // assuming this is necessary
      'password' => 'password', // assuming this is necessary
      'host' => 'localhost', // assumes localhost
      'driver' => 'mysql', // replace with your database driver
  );
  // replace 'YourDatabaseKey' with something that's unique to your module
  Database::addConnectionInfo('YourDatabaseKey', 'default', $other_database);
  db_set_active('YourDatabaseKey');

  // execute queries here

  db_set_active(); // without the paramater means set back to the default for the site
  drupal_set_message(t('The queries have been made.'));

```

Refer https://www.drupal.org/docs/7/creating-custom-modules/howtos/how-to-connect-to-multiple-databases-within-drupal
> 0 votes

---
Tags: database
---


# Question
Title: Commerce - how to allow users to buy 2 free products
For a current site I am building, authenticated users should be able to order 2 free products (of a certain type), after which the prices are back up to full price. Is there any solution which allows this kind of functionality? I can't seem to find the right words to search as nothing is coming up.

If not, any ideas on how to implement this with Rules / code?

I imagine I would have to add a new line item for the 2 free tickets at $0, and deduct these 2 products from the original line item, but I'm not sure at what stage in the process to do this. Any help?

# Answer
By using the Goals module (disclosure: I'm its maintainer) you can have the Rules module take care of "*monitoring users about buying their first 2 products*" (as in your question). The advantage of using the Goals module, is that you can keep track of all sorts of **events that are happening asynchronously** (which you cannot do by only using Rules and its events).

So with that it seems that your question (challenge) is reduced to finding a way to configure the appropriate set of **Goals** and related **Tasks**. For a basic introduction about Goals, have a look at:

Here is what it would take to implement something like a ***frequent buyers*** program:

1. **Goal** = "New customer", with only 1 **Task** = "Buy 1 product" (say with machine name = `buy_product`).
2. **Goal** = "Existing customer", with **Task** = "Buy 2 products".

The interesting part of this is that you'd only have to write 1 rule (related to that machine name = `buy_product`) to keep track of the progress of any user to become either a "new" or "existing" customer (check the video for a similar sample).

***Homework***: how should a rule look like to indicate that a user bought a product (either the very first one, or yet another one)?
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: Postal Address field inline items output
I have a postal address field which I display with an icon in front of it. I have a field template file which is as follows:

```
<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
   <div class="field-items"<?php print $content_attributes; ?>>
     <?php foreach ($items as $delta => $item): ?>
       <div class="glyphicon glyphicon-map-marker"></div>
       <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php print render($item); ?></div>
       <div class="clear"></div>
     <?php endforeach; ?>
    </div>
</div>

```

The rendered item displays the different elements of the postal address on separate lines (Company name, thoroughfare, post code,...). I essentially want to put all these elements inline. But I cannot find how to do that... Any suggestions?

# Answer
I have found a way to access the content of the addressfield. Instead of `<?php print render($item); ?>`, I do this:

```
<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <div class="field-items"<?php print $content_attributes; ?>>
   <?php foreach ($items as $delta => $item): ?>
    <div class="glyphicon glyphicon-map-marker"></div>
    <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>>

            <?php if(!empty($element['#object']->field_where_location["und"][0]["organisation_name"])): ?>
              <?php print $element['#object']->field_where_location["und"][0]["organisation_name"]; ?>,
            <?php endif; ?>

            <?php if(!empty($element['#object']->field_where_location["und"][0]["thoroughfare"])): ?>
              <?php print $element['#object']->field_where_location["und"][0]["thoroughfare"]; ?>,
            <?php endif; ?>

            <?php if(!empty($element['#object']->field_where_location["und"][0]["locality"])): ?>
              <?php print $element['#object']->field_where_location["und"][0]["locality"]; ?>,
            <?php endif; ?>

    </div>
  <div class="clear"></div>
 <?php endforeach; ?>
</div>
</div>

```

The `$element['#object']` is used as if it was $node variable. I just had to read the template instructions a bit better!
> 0 votes

---
Tags: theming, entities
---


title: Redirect after user creation via form

text:
# Question
Title: Redirect after user creation via form
What would be the proper hook to redirect after the user registration form is submitted and is in valid state?

I'm trying to automatically create a certain content-type node when a user registers and I want to redirect the user to that node's edit form *after* the user creation form is submitted **and** validated.

I was thinking of doing this in a `mymodule_user_form_submit` hook, but not sure if **a)** this hook exists and **b)** the validation in place for user registration will still work as intended.

Can anyone share some pointers?

**EDIT:**

Would the `mymodule_user_insert` hook run after the validation and submission of the form? Can I redirect from there? AFAIK, I won't have a `form_state` variable to act on, right?

**EDIT2:**

While researching for a solution, I noticed I have another (probably bigger) problem: the content-type node I need to create must hold a reference to the user's ID, so I'm getting in a chicken-or-egg situation.

I actually need to create said node **after** the user is created (otherwise I'll have no user\_id), but I need to redirect to the node's edit form after user creation, which means I can't redirect with `$form_state`.

I think I got everything right, but I would love to be wrong. :D

Can anyone help?

# Answer
> 0 votes
If you have created a custom user registration form `my_module_user_register_form`, then you can define one or more submit functions for it

```
function my_module_user_register_form($form, &$form_state) {
    $form['#submit'][] = 'my_module_user_register_form_submit';
    // and now add a second submit function if you like
    $form['#submit'][] = 'my_module_user_register_form_another_submit';
}

```

and then place the appropriate redirect at the end of the last submit function.

```
function my_module_user_register_form_another_submit($form, &$form_state) {
   // do other stuff here
   $form_state->setRedirect('node/123/edit');
}

```

---
Tags: 8, forms
---


# Question
Title: Find entity field order and display names in code
In PHP code, in Drupal 8, how can I get the display names and the order of entity fields to be displayed in a particular view mode. I'm specifically trying to get the order of fields in node and paragraphs entities.

I've tried inspecting the node object, using the serializer service and REST interface. I can find the fields and data, but not this metadata.

# Answer
> 1 votes
In Drupal, the display of fields is controlled by display mode configuration entities, which define the configuration for field formatters and the such.

You cannot get this metadata by viewing the node itself (or other entity). You would have to load the display mode for it.

The config object is `entity_view_display` and may be accessible over RESTful endpoints. An example output (in YAML) looks like so:

```
content:
  body:
    type: text_default
    weight: 0
    label: hidden
    settings: {  }
    third_party_settings: {  }
    region: content
  variations:
    type: commerce_add_to_cart
    weight: 1
    label: hidden
    settings:
      default_quantity: '1'
      combine: true
      show_quantity: false
    third_party_settings: {  }
    region: content
hidden:
  created: true
  stores: true
  uid: true

```

---
Tags: entities
---


# Question
Title: Adding a library to a module using composer
I'm working on a module which will require a library that is already in composer.

I added a line to my module's composer.json file:

```
"require": {
   "markrogoyski/math-php" : "dev-master"
}

```

I ran the command:

```
composer update .

```

and a "vendor" directory was created in my module's directory and the files were downloaded. However, If I add a use statement to the file my\_module/src/Controller/Test.php I get an error:

```
----Test.php----

<?php
namespace Drupal\lims\Controller;

use Drupal\Core\Controller\ControllerBase;
use Math\Functions\Map\Single;

class Sample extends ControllerBase {
    public function content() {
        print_r(Single::square([1,2,3,4,5]));
    }
}

```

I see the error:

```
PHP Fatal error:  Class 'Math\\Functions\\Map\\Single' not found in [module path]/src/Controller/Test.php on line 9

```

Is there another step that I need to do to get the library autoloaded in the correct namespace?

# Answer
> 7 votes
Using `composer update`, Composer created the vendor directory, and the autoload.php file, which is necessary to autoload the library. Unfortunately, Drupal doesn't load all the autoload.php files found in each of the directories containing a module.

Instead of adding the dependency of your module in the composer.json file used by Drupal, you should edit its extra/merge-plugin section to include the directory containing the modules you add. (I added the *"modules/\*/composer.json"* line.)

```
"extra": {
    "_readme": [
        "By default Drupal loads the autoloader from ./vendor/autoload.php.",
        "To change the autoloader you can edit ./autoload.php."
    ],
    "merge-plugin": {
        "include": [
            "core/composer.json",
            "modules/*/composer.json"
        ],
        "recurse": false,
        "replace": false,
        "merge-extra": false
    }
},

```

In this way, running `composer update` from the Drupal root directory would add the required classes in the vendor directory used by Drupal, making them automatically loaded.

If the modules you install are all hosted on drupal.org (i.e., you don't use any custom module), you can instead edit the repositories section to contain the following lines.

```
"repositories": {
    "drupal": {
        "type": "composer",
        "url": "https://packagist.drupal-composer.org"
    }
}

```

In this way, you could add a module hosted on drupal.org running `composer require drupal/module-name` from the Drupal root directory, and Composer would install its dependencies (declared in the module's composer.json file) in the vendor directory, making the classes automatically loaded.

# Answer
> 2 votes
Presuming you use the Composer template for Drupal projects:

1. In your custom module run `composer init` and then require a package/library.
2. In your Drupal project run `composer require wikimedia/composer-merge-plugin`.

Then add the following to the `"extra"` array in your Drupal project's composer.json:

```
"merge-plugin": {
    "include": [
        "web/modules/custom/*/composer.json"
    ]
}

```

(See docs on DO: MergePlugin.php.)

(See composer-merge-plugin on GitHub.)
3. In your Drupal project run `composer update`.

That's it.

# Answer
> -1 votes
As per the documentation you will need to use the dump-autoload command to recreate the autoloader file.

# Answer
> -1 votes
You used well composer! The official MathPHP documentation says that you should use it like this:

```
use MathPHP\Functions\Map;
$x = [1,2,3,4];
$x² = Map\Single::square($x); // [1, 4, 9, 16]

```

Then you should not have trouble calling it from your controller. Try using "TestController.php" as filename and "TestController" as the class name. Helps the namespace.

I always use external libraries, oriented to DDD. You can see my repository.

---
Tags: 8, composer
---


# Question
Title: How to get id of selected entity in an "entity_autocomplete" form element?
I have a form element of "entity\_autocomplete" type. Also I have an ajax callback of the element. Here is its code.

```
$form['autocomplete_places'] = [
            '#type' => 'entity_autocomplete',
            '#target_type' => 'node',
            '#selection_settings' => [
                'target_bundles' => ['place'],
            ],
            '#ajax' => [
                'callback' => '::autocompleteGetPlaces',
                'event' => 'autocompleteselect',
            ]
        ];

public function autocompleteGetPlaces(array &$form, FormStateInterface $form_state){
        $ajax_responce = new AjaxResponse();
/// some code here
        return $ajax_responce;
    }

```

Unfortunately, I can't find out how to get the id of selected entity inside the ajax callback function. For example, in my case, it would be id of a node of "place" type.

I tried to debug it, but couldn't find information about it in $form\_state.

Could you clarify me, how to do it ?

# Answer
> 1 votes
Seemingly I managed to find the solution.

The event for the autocomplete element should be "autocompleteclose" instead "autocompleteselect". And in this case it's possible to get entity\_id via

```
$entity_id = $form_state->getValue('autocomplete_places');

```

if the list of values was closed without selected element then $form\_state-\>getValue('autocomplete\_places') is null.

---
Tags: 8, forms, entities, ajax
---


# Question
Title: Is there a risk of having xmlrpc.php on my site?
I recently noticed that all of my sites have the file `xmlrpc.php`.

Searching it led me to "Gain Control of WordPress by Exploiting XML-RPC", and also to "Drupal Core - Critical - Multiple Vulnerabilities - SA-CORE-2016-001".

I'm running Drupal 7.56.

Does this file pose a threat whatsoever to my site? Should I just delete it to be safe?

If I should keep it, what added benefit does it give me?

# Answer
**You are save.** At least to what we know now.

The first linked article is wordpress related. This is totally different code. Not drupal related at all!

> Drupal had a known security flaw in versions lower than 6.38 / 7.43 / 8.04

So your version 7.56 is patched. Always make sure to update to the latest version and you're good.
> 1 votes

---
Tags: 7, security
---


# Question
Title: Creating a caption for images in Drupal 7 Media module
Is there a way to create a caption field on images? I have seen in the latest Media module you can add your own fields on images now but I can't seem to get them to output in the WYSIWYG module correctly or on the final page.

Modules \- Media 7.x-2.10 \- WYSIWYG 7.x-2.4 \- IMCE 7.x-1.11

# Answer
> 0 votes
You would need to edit the output of the media tpl file. First inspect the media html output and find any unique identifying code and then do a search in the media modules folder to find this line of code in the tpl. That's how I would do it.

---
Tags: media, wysiwyg
---


title: Webforms checkbox choices

text:
# Question
Title: Webforms checkbox choices
Is it possible to limit site visitor filling out a webform so that they can only select one of the checkbox and not be able to select any/all checkboxes?

# Answer
That's called a radio checkbox button I believe. You'll have to do this via javascript to prevent users from selecting more than one option if you cant find a radio checkbox option. See: https://stackoverflow.com/questions/37002599/only-one-checkbox-checked-at-a-time-in-javascript
> 1 votes

---
Tags: webforms
---


title: How do you identify a form element?

text:
# Question
Title: How do you identify a form element?
I'm still learning Drupal, and I was trying to use `hook_form_alter()` to resize a text field added from a module. My problem is that I don't think I'm indentifying the element correctly.

Here's the element code:

```
<input type="text" class="form-text form-autocomplete" value="" size="60" id="edit-2" name="2" maxlength="128" autocomplete="OFF">

```

Here's my module code:

```
/**
 * Implements hook_form_alter().
 */
if ($form_id == 'edit-2') {
  $form['text'] = array(
    '#type' => 'text',
    '#size' => 25,
  );
}

```

I'm not sure what to do; any suggestions would be helpful.

Thanks!

# Answer
> 9 votes
The *HTML* id has nothing to do with `$form_id`.

`$form_id` is the name of the whole form. In most cases, it is the name of the function that generates the form unless hook\_forms() is used.

Instead of checking the $form\_id with an if condition, it is often easier to implement the more specific hook\_form\_FORM\_ID\_alter() hook. So if the form\_id is `BLA`, you can directly create a `function yourmodule_form_BLA_alter(&$form, &$form_state)`and don't need to mess with $form\_id at all.

There are exception when this doesn't work or isn't practically, but it most cases, it is recommended to use that hook (It's a performance improvement too, because your function will just be called for that specific form and not every single form in Drupal).

If you are not sure what $form\_id is, implement `hook_form_alter()` and put a `drupal_set_message($form_id)` in there. That should then print all form ids of the page you are on, allowing you to easily pick the one you want to change.

About the name of the form element, you can't guess that from the HTML in most cases, because unless `#tree` is set to TRUE, the names are flattened, so it might be `$form['some_fieldset']['example']` in the $form structure and just `name="example"` in HTML.

So, to find the element you want to change, there are two ways.

a) Look at the source code of the function that defines the form structure.

b) Use `dpm($form)` (requires devel.module).

I prefer the second method, and this is usually the second step after figuring out the $form\_id, if I don't know exactly what I want to do. dpm() prints complex array/object structures in a very nice and browseable way. That is actually something you should get used to all the time when you work with Drupal. Don't just guess things. You're going to be wrong pretty often. Instead, if there are any variables that you want to use but don't know the exact structure of them, add a dpm($var), load the page/trigger the action and then you can exactly see what you are working with.

Edit:

The last problem is that right now, your code does completely replace that form element. Instead, you only want to override the #size property, like this:

```
$form['finder_form'][2]['#size'] = 25;

```

# Answer
> 4 votes
The problem is that you are looking at the HTML produced by Drupal, to decide which is the identifier of the form field that you want to modify.

* `hook_form_alter()`, `hook_form_FORM_ID_alter()`, and hook\_form\_BASE\_FORM\_ID\_alter() (introduced in Drupal 7) don't directly alter the HTML output produced from Drupal; they alter an array containing the values described in Form API Quickstart Guide, Form API Reference (for Drupal 7, there are Form generation and Form API Reference).
* The form you are trying to alter could contain a form field that is contained in another form field; this normally happens with form fields that are part of a field set. The structure of the form array used by the form API is difficult to interpret basing on the HTML output.

What you would need to do is to

* find out the module that creates the form field you are trying to alter
* find out the form building function that generates the form containing that form field
* read the array containing the description of the form field you need to alter

Once you have done it, you can create the implementation of the hook that will allow you to alter that form field.

If the form builder function is, for example, `path_admin_form()` and your module is mymodule.module, then you can implement `mymodule_form_path_admin_form(&$form, &$form_state)`.

# Answer
> 1 votes
First you want to look for the form in HTML of the loaded page.

```
<form class="node-form node-article-form" enctype="multipart/form-data" action="/cruzr/node/226/edit?destination=admin/workbench" method="post" id="article-node-form" accept-charset="UTF-8"><div><div class="form-item form-type-textfield form-item-title">

</form>

```

Here the ID is 'article-node-form'.

Then you want to use the HOOK\_form\_FORM\_ID\_alter() callback function.

# Answer
> 0 votes
# 1 For a quick answer I'd use the html. The form tag tells you

```
<form action="/yhivebook/class/917/1503856800?XDEBUG_SESSION_START=10676" method="post" id="yhivebook-booking-form"

```

# 2 In hook\_form\_alter the 3rd parameter is the form\_id

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

```

# 3 Any function with $form\_state has it in

```
$form_state['build_info']['form_id']

```

Point your debugger there.

For example, submitting the form with the form id will work.

```
drupal_form_submit($form_state['build_info']['form_id'], $form_state);

```

---
Tags: 7, forms
---


# Question
Title: How to write big updation code using Batch API?
I am writing a script to update all website registered user's Username & Email address. I have more then 5000+ users in my website which causes PHP execution time out error.

So I tried to implement Batch API but I am unable to implement it. I passed whole user list to Batch API and perform operations on it. But Batch API also shows the same PHP time out error.

Can someone help me to implement Batch API?

Here is my code:

```
function anonymize_data_menu() {
  $items = array();
  $items['admin/config/content/anonymize-user-data'] = array(
    'title' => 'Anonymize User Data',
    'description' => 'Click this link to anonymize user data',
    'type' => MENU_LOCAL_ACTION,
    'page callback' => '_anonymize_users_data',
    'access arguments' => array('administer user anonymize'),
    'file' => 'anonymize_data.user.inc',
  );
  return $items;
}

function _anonymize_users_data() {
  $users = entity_load('user');
  $chunks = array_chunk($users, 20);
  $count_user = count($chunks);

  foreach ($chunks as $chunk) {
     $operations[] =  array('user_anonymize_op', array($chunk));
      //user_anonymize_op($chunk);
     //krumo($chunk);
  }
  $batch = array(
    'operations' => $operations,
    'title' => t('Import batch'),
    'init_message' => t('Initializing'),
    'error_message' => t('An error occurred'),
    'finished' => 'user_anonymize_op_finished'
  );
  batch_set($batch);
  batch_process('admin/people');
}

function user_anonymize_op($users, &$context) {
  foreach ($users as $user) {
    # code...
    //krumo($user);
   $context['message'] = t('processing user @user', array('@user' => $user->name));
    //
      if($user->uid != 0 && $user->uid != 1) {
      $user->name = $i . '-' . $user->name;
      $user->pass = user_hash_password('blah');
      user_save($user);
    }
  }
}

function user_anonymize_op_finished($success, $results, $operations) {
  if ($success) {
    $message = count($results) . ' processed.';
  }
  drupal_set_message(t($message));
}

```

I am very confused about that how to process chunk of users.

Can someone help me it will be great.

# Answer
The timeout is caused because you're trying to load all 5K+ users before you start the batch. Instead get the User IDs first and load when processing. Check an example below. Also have a look at Batch API Overview documentation page, before you continue:

```
function anonymize_data_menu() {
  $items = array();
  $items['admin/config/content/anonymize-user-data'] = array(
    'title' => 'Anonymize User Data',
    'description' => 'Click this link to anonymize user data',
    'type' => MENU_LOCAL_ACTION,
    'page callback' => '_anonymize_users_data',
    'access arguments' => array('administer user anonymize'),
    'file' => 'anonymize_data.user.inc',
  );
  return $items;
}

function _anonymize_users_data() {
  // Instead of loading all users at once,
  // first get there uid and then load chunk of user while processing.
  // $users = entity_load('user');
  $uids = db_select('users', 'u')
    ->condition('u.uid', 1, '>')
    ->fields('u', array('uid'))
    ->execute()->fetchAllKeyed(0, 0);

  $chunk_count = 20;
  // We've all rows here, split them in chunks.
  $chunks = array_chunk($uids, $chunk_count, TRUE);
  // Get all rows count.
  $num_operations = count($uids);

  $operations = array();
  foreach ($chunks as $chunk) {
    $operations[] =  array('user_anonymize_op', array(
      $chunk,
      array(
        'max' => $num_operations,
        'chunk' => $chunk_count,
      )
    ));
  }

  $batch = array(
    'operations' => $operations,
    'title' => t('Import batch'),
    'init_message' => t('Initializing'),
    'error_message' => t('An error occurred'),
    'finished' => 'user_anonymize_op_finished'
  );

  batch_set($batch);
  batch_process('admin/people');
}

function user_anonymize_op($rows, $batch_data, &$context) {
  // Define variables on start of batch operation.
  if (!isset($context['results']['progress'])) {
    $context['results']['progress'] = 0;
    $context['results']['chunk'] = $batch_data['chunk'];
    $context['results']['max'] = $batch_data['max'];
    $context['results']['failed'] = array();
  }

  // Do your processing here. START HERE.
  $names = [];
  $users = entity_load('user', $rows);
  foreach ($users as $account) {
    if (!empty($account->uid) && ($account->uid > 1)) {
      // What is $i here?
      $account->name = $i . '-' . $account->name;
      $account->pass = user_hash_password('blah');
      user_save($account);
      $names[] = $account->name;
    }
  }
  // Do your processing here. END HERE.

  // Update completion count.
  $context['results']['progress'] = $context['results']['progress'] + count($rows);

  $context['message'] = t('Processed @name user data.', array('@name' => implode(', ', $names)));

  // Inform the batch engine that we are not finished,
  // and provide an estimation of the completion level we reached.
  if ($context['results']['progress'] != $context['results']['max']) {
    $context['finished'] = $context['results']['progress'] % $context['results']['max'];
  }
}

function user_anonymize_op_finished($success, $results, $operations) {
  if ($success) {
    $message = count($results) . ' processed.';
  }
  drupal_set_message(t($message));
}

```
> 3 votes

# Answer
First time it could seems to be a huge learning curve, but it isn't.

And once Batch API is learned, it is really powerfull and easy to implement.

Best way for starting, is looking at core example. The keyword you should look for is `$sandbox`. Which is the object that will be injected into each call of the batch. Often used on hook\_update\_n( $sandbox )

Here is a truncated example from `system.install` I commented out

I suggest to put your Batch into a hook\_update and put your site in maintenance during the update process to prevent new user entry during the batch process, which could invalidate the batch somehow.

```
function system_update_8001(&$sandbox = NULL) {
      $database = \Drupal::database();
      $schema = $database->schema();

      // It checks if something has to be done
      if ($schema->tableExists('menu_tree')) {

            // If our sandbox object doesnt have the current property
            // It means this is the first call of the batch
            if (!isset($sandbox['current'])) {

                  [... truncated code ]

                  // So lets initiate the needed properties
                  $sandbox['current'] = 0;
                  $sandbox['max'] = $database->query('SELECT COUNT(mlid) FROM {menu_tree}')
                     ->fetchField();
           }

          // request the data from database
          // this is where $sandboc['current'] will be usefull
           $menu_links = $database->queryRange('SELECT mlid, system_update_8001_title AS title, system_update_8001_description AS description FROM {menu_tree} ORDER BY mlid ASC', $sandbox['current'], $sandbox['current'] + 50)
             ->fetchAllAssoc('mlid');

          foreach ($menu_links as $menu_link) {

                // Process each items
                [...truncated code]

                // update the counter for next batch call
                $sandbox['current']++;
          }

          // Lets Batch APO know the percentage done
          // Used internally by Batch API
          // Batch won't stop until $sandbox['#finished'] is less than one
          // So this function will be call again and again until completion
          $sandbox['#finished'] = empty($sandbox['max']) ? 1 : ($sandbox['current'] / $sandbox['max']);

          // Once finished you can take some more actions
          if ($sandbox['#finished'] >= 1) {
                [... truncated code]
          }

         // Print message to batch api
         return t('Menu links converted');
    }
    else {
          // Print message to batch api
           return t('Menu link conversion skipped, because the {menu_tree} table did not exist yet.');
    }
}

```

Also have a look at Batch Example https://api.drupal.org/api/examples/batch\_example%21batch\_example.module/7.x-1.x
> 0 votes

# Answer
I've done this in a hook\_update\_N() hook. Pay attention to the &$sandbox array parameter in the update hook. What that allows you to do is to chunk off your users into byte sized bites and since it's passed by reference, it allows you to keep track of how many users you have processed.
> 0 votes

---
Tags: 7, batch-operations
---


# Question
Title: How do you join a custom table to a node from a field with hook_views_data()
I have a custom table that contains (for simplicity) two fields:

* id
* client\_id

On my node content type, I have an integer type field called: field\_dashboard\_id. All my nodes have the field\_dashboard\_id set to ids from the custom table. I have a content view that I would like to also display the client id from the custom table. (FYI I am able to create a view if I use Dashboard Entries instead of Content but I want to use Content and join to Dashboard Entries)

I tried the following code but when I try to add a relationship, I am not seeing my custom table in Views.

```
/**
 * Implements hook_views_data().
 */
function mydashboard_views_data() {
  $data = [];

  $data['mydashboard_site']['table']['group'] = t('Dashboard');

  $data['mydashboard_site']['table']['base'] = [
    'field' => 'id',
    'title' => t('Dashboard entries'),
    'help' => t('Contains a list of dashboard entries.'),
  ];

  $data['mydashboard_site']['table']['join'] = array(
    'node' => array(
      'left_table' => 'node__field_dashboard_id',
      'left_field' => 'entity_id',
      'field' => 'id',
    ),
  );

  $data['mydashboard_site']['id'] = [
    'title' => t('ID'),
    'help' => t('Unique Site ID.'),
    'field' => [
      'id' => 'numeric',
    ],
    'filter' => [
      'id' => 'numeric',
    ],
    'argument' => [
      'id' => 'numeric',
    ],
    'sort' => [
      'id' => 'standard',
    ],
    'relationship' => [
      'base' => 'node', // The name of the table to join with.
      'base field' => 'field_dashboard_id', // The name of the field on the joined table.
      // 'field' => 'nid' -- see hook_views_data_alter(); not needed here.
      'handler' => 'views_handler_relationship',
      'label' => t('Default label for the relationship'),
      'title' => t('Title shown when adding the relationship'),
      'help' => t('More information on this relationship'),
      'extra' => [
        [
          'field'    => 'field_dashboard_id',
          'value'    => 'value',
          'operator' => '=',
          'numeric'  => true,
        ],
      ],
    ],
  ];

  $data['mydashboard_site']['client_id'] = [
    'title' => t('Client ID'),
    'help' => t('The client id'),
    'field' => [
      'id' => 'standard',
    ],
    'filter' => [
      'id' => 'string',
    ],
    'argument' => [
      'id' => 'string',
    ],
  ];

  return $data;
}

```

**Update**

Also tried the following:

```
$data['mydashboard_site']['table']['join'] = [
  'node__field_dashboard_id' => [
    'left_field' => 'field_dashboard_id_value',
    'field' => 'id',
  ],
];

'relationship' => [
  'base' => 'node__field_dashboard_id', // The name of the table to join with.
  'base field' => 'entity_id', // The name of the field on the joined table.
   // ID of relationship handler plugin to use.
  'id' => 'standard',
   // Default label for relationship in the UI.
  'label' => t('Example node'),
],

```

# Answer
When you have a field you have a table for it with stored values, so you just add the fields table to your query Like

```
/**
 * Implements hook_views_query_alter().
 */
function HOOK_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
   $query->addTable('my_fields_table');
   $query->addWhere(<condition group id>, '<table_column>', <value>, '<operator>');
   // These you can use to alter the behaviour for your condition group.
   //$query->setWhereGroup('OR/AND', <condition group id>);
   // This one is for the global group behavior.
   //$query->setGroupOperator('<OR/AND>');
  }
}

```
> 0 votes

---
Tags: 8, views
---


# Question
Title: Problem with IF command in comment.html.twig
I create a "select" field (field\_points) in comment section that users rating my content and in "manage display" I set "key" for my field format.

```
5|Excellent
4|Good
3|No Idea
2|Bad
1|Very Bad

```

Now I use this code in comment.html.twig:

```
{% if content.field_points == 5 %}
   *****
{% elseif content.field_points == 4 %}
    ****
{% elseif content.field_points == 3 %}
    ***
{% elseif content.field_points == 2 %}
    **
{% elseif content.field_points == 1 %}
    *
{% endif %}

```

When I use this code nothing is displayed But when I use {{ content.field\_points }} , print for example 5 ( 5 is field key ).

How can I fix this problem in drupal 8?

# Answer
> 1 votes
Use the comment entity to get the raw field value instead:

```
{% if comment.field_points.value == 5 %}
   *****
{% elseif comment.field_points.value == 4 %}
   ****

...

{% endif %}

```

This doesn't work with `{{ content }}`, because it contains a build array to render the fields.

---
Tags: 8, comments
---


# Question
Title: Customize autocomplete field to show children terms depending on another field
I have a taxonomy with 2 levels

```
City1
-Park1
-Park2
-Park3
City2
-Park4
-Park5
-Park6

```

In my form, I created a field that links to this taxonomy with an autocomplete widget. I also have a second field where the user chooses the city.

I would like to dynamically change the autocomplete value depending on the selected city. Which means if the user selects City1, the autocomplete will only filter through the values under City1.

After checking the form I've found that the widget `entity_autocomplete` have an attribute `#selection_handler`. Will it be possible to change this handler and somehow send the value of the selected city?

I think there should be an easier approach. Creating a custom autocomplete field based on a `textfield` doesn't seem like a good solution since it will not have (or I will need to do it manually) all the error handling and entity links.

Any suggestions ?

# Answer
You can drop using entity\_autocomplete and instead it use custom autocomplete field. Here is an example of using, you can translate this page from Russian to your language. Also the example contains the attached source files.

https://niklan.net/blog/77

In the example you can see a controller what creates the list with values. I suppose that you can pass a parameter to the controller (city\_id) and SQL query will return set of resuts according the parameter.

You can add the parameter to the controller inside function buildForm() of your form. Also you can recreate the autocomplete element with new parameter after you selected a city from the list.
> 0 votes

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


# Question
Title: Fix 404 error when adding conditional action to Rule?
Subsequent to what I saw in the question 'Don't calculate shipping for specific item', I tried to create a rule with a **conditional action** (screen capture below), but it causes 404 error:

The export for the rule looks like so:

```
{ "rules_test_please_delete_" : {
  "LABEL" : "Test (please delete)",
  "PLUGIN" : "reaction rule",
  "OWNER" : "rules",
  "REQUIRES" : [ "rules_conditional", "rules" ],
  "ON" : { "node_delete--page" : { "bundle" : "page" } },
  "DO" : [ { "CONDITIONAL" : [] } ]
}
}

```

How can I fix the 404 error?

Related resources:

# Answer
> 0 votes
Not sure (yet) what is causing your 404 error, but at this point I'm not convinced it is a bug ...

I imported your exported rule in my own site to experiment with it, this is what happened:

* The import worked fine (of course), so I started from the very same Rule as your exported rule.
* I then used the Rules UI to also add such "If", and then just show a Bingo-message on the site.
* If I would want to add another "if", the URL that would be used for that would have relative path "`/admin/config/workflow/rules/reaction/manage/rules_attempt_to_recreate_a_404_error/add/3/if`".

Here is the proof of my experiment (an exported Rule, which includes some additional logic within that Conditional Rules Action, and for which I changed the label and machine name also, though only after I imported the rule):

```
{ "rules_attempt_to_recreate_a_404_error" : {
    "LABEL" : "Attempt to recreate a 404 error",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules_conditional", "rules" ],
    "ON" : { "node_delete--page" : { "bundle" : "page" } },
    "DO" : [
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is" : { "data" : [ "node:promote" ], "value" : "1" } },
            "DO" : [
              { "drupal_message" : { "message" : "Bingo, this one seems to work ... using \u0022Conditional Rules\u0022 ..." } }
            ]
          }
        ]
      }
    ]
  }
}

```

The scenario described above was completed in a Drupal 7.5x site, using these versions of related modules:

* Rules: 7.x-2.9
* Conditional Rules: 7.x-1.0-beta2

I suggest you try to import "my" rule here in your site, and see if you get any other messages while trying to perform that import.

To further pinpoint your issue, have a look at the typical Drupal logging information, you may find there some other indication about what's happening in your site around the time the 404 error occurs.

**Notes**:

1. I'm not sure if it could be an explanation for your issue (what it is that causes it), but I noticed that your scenario uses `https://`, while my scenario was performed using `http://` ... Debugging is the art of taking away all possible causes for an issue, so you may want to try in a site using `http://` instead of `https://` ... FYI: I tried a similar scenario using `https://`, and did not encounter any problem or 404 error.
2. As an alternative to using the Conditional Rules module, you can also create corresponding Rules Components, with similar Rules Actions to be performed. For more details on that, refer to the answer to "What's the alternative to using the Conditional Rules module?".

---
Tags: rules
---


# Question
Title: Openlayers3 - Tiles not Loading - Failed to load resource: net::ERR_NAME_NOT_RESOLVED
I setup a Drupal Website with Openlayers3.

* Openlayers Module: 7.x-3.1 - 2016-Jan-03
* Openlayers Library: 3.11.2
* Drupal Version: 7.56

The settings are the default. I'm just trying to show a Geofield through a widget Openlayers with a setup like this:

* Openlayers map: Openlayers Geofield: Formatter Map
* Openlayers layer: openlayers\_geofield\_layer\_formatter
* Data options: Use full geometry

The map is there, controls and marker are ok, but either on the preview and on the field display I see no tiles, they are being loaded from the wrong place. This is the screenshot of the error I get:

Errors are like this:

```
GET https://otile1-s.mqcdn.com/tiles/1.0.0/osm/3/3/3.jpg:1 GET https://otile1-s.mqcdn.com/tiles/1.0.0/osm/3/3/3.jpg net::ERR_NAME_NOT_RESOLVED
Image (async)
Mz @ ol.js?ov6n8a:756
l.load @ ol.js?ov6n8a:688
Lk @ ol.js?ov6n8a:190
l.Qk @ ol.js?ov6n8a:439
c.port1.onmessage @ ol.js?ov6n8a:139
[...]

```

JQuery Update is Installed and I tried many jquery versions combination (default, 1.7, 1.10...)

I can't get it work... I just want to show a geofield as a map. Any other workiaround in order to achieve that?

# Answer
You can find the solution with the patch, HERE.

MapQuest, which is the default map of Openlayers, doesn't work. You need to switch to another map, e.g., Openstreetmap.
> 0 votes

---
Tags: javascript
---


# Question
Title: Programmatically create a taxonomy and attach a field to it
I created a vocabulary using the following code.

```
$vocab = entity_create('taxonomy_vocabulary', array(
  'name' => 'vocab_name',
  'vid' => 'vocab_id',
  'description' => 'description'
));
$vocab->save();

```

I need to attach a custom field to it. I created the field with `BaseFieldDefinition::create('string')`, bu I couldn't figure out how to attach the created field to `$vocab`.

How can I achieve it?

# Answer
> 1 votes
Assuming that you want that to be default configuration as part of a module, @larowlan's answer is correct.

Sometimes things do need to be created in code/dynamcally. Look at node\_add\_body\_field() as an example that adds a configurable body field to a node type. Note that it does not create the necessary FieldStorageConfig entity, as that is default configuration again, but if you search for FieldStorageConfig::create() in the code base, you should find dozens of examples on how to do that. Preferably look in the module of the field type you want to use, as that will likely contain examples with the necessary settings.

# Answer
> 3 votes
Create them in the ui, export them to yaml using the single config export ui, put the yaml files in your\_module/config/install - done

# Answer
> 2 votes
Posting the complete solution here, hoping it might be helpful.

```
//create a vocabulary

entity_create('taxonomy_vocabulary', array(
            'name' => 'taxonomy test',
            'vid' => 'taxonomy_test',
            'description' => 'some description'
                ))->save();

//add term to the vocabulary
entity_create('taxonomy_term', array(
                    'name' => 'term test',
                    'vid' => 'taxonomy_test',
                        ))->save();
//attach a field to teh vocabulary

 \Drupal\field\Entity\FieldStorageConfig::create(array(
      'field_name' => 'taxonomy_test_field',
      'entity_type' => 'taxonomy_term',
      'type' => 'boolean',
      'settings' => array(
        'on_label' => 'on',
        'off_label' => 'off',
      ),
    ))->save();

 \Drupal\field\Entity\FieldConfig::create(array(
      'field_name' => 'taxonomy_test_field',
      'entity_type' => 'taxonomy_term',
      'bundle' => 'taxonomy_test',
      'label' => 'Field Label',
      'required' => TRUE,
    ))->save();

```

# Answer
> 0 votes
```
use Drupal\taxonomy\Entity\Vocabulary;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\field\Entity\FieldConfig;

$vicId = "commitee_list";
$vocName = "Commitee List";
$vocDescription = "Used for commitee list.";

$vocabulary = Vocabulary::load($vocId);
if (!$vocabulary) {
  $vocabulary = Vocabulary::create(array(
        'vid' => $vocId,
        'description' => $vocDescription,
        'name' => $vocName,
  ));
  $status = $vocabulary->save();

// Attach a field to the vocabulary.
  FieldStorageConfig::create(array(
  'field_name' => 'field_committee_id',
  'entity_type' => 'taxonomy_term',
  'type' => 'string',
  'settings' => array(
    'max_length' => 255,
    'is_ascii' => FALSE,
    'case_sensitive' => FALSE,
  ),
  'module' => 'core',
  'locked' => FALSE,
  'module' => 'core',
  'cardinality' => 1
))->save();

   FieldConfig::create(array(
  'field_name' => 'field_committee_id',
  'entity_type' => 'taxonomy_term',
  'bundle' => $vocId,
  'label' => 'Committee ID',
  'required' => TRUE,
))->save();

```

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


# Question
Title: How to disable parent term options in select list?
I have a view with an exposed filter of taxonomy terms. The terms are displayed as a hierarchical structure in the select list. I want to disable the parent terms in the select list. How to do it in Drupal way?

# Answer
I wanted to disable the parent term in the select list (views exposed filter) so that the user is not able to select it. This is how I achieved the desired functionality -

As mentioned by @Neograph734, using `<optgroup>` creates a grouping of options within `<select>` element. I applied the patch at drupal.org/node/1695658 that @Neograph734 provided.

Then in the views filter section, I selected the desired taxonomy reference field. Selected options as shown below -  Configured the field as an exposed filter. As as result you can see it as per below -

Now the user can select only child terms and not the parent terms.
> 0 votes

---
Tags: 7, forms, views
---