title: How to turn field_label into an h1 tag

text:
# Question
Title: How to turn field_label into an h1 tag
I have a content type containing many fields. I want to attach H1, h2, h3, tags to the field\_labels of the fields.

1. Is this possible?
2. How can I do this?

I am relatively new to Drupal. Thanks.

# Answer
> 7 votes
Yep! This is entirely possible and a very common use case.

If you check out the `field.html.twig` file in the classy base theme of core, it has the following contents:

```
{#
/**
 * @file
 * Theme override for a field.
 *
 * To override output, copy the "field.html.twig" from the templates directory
 * to your theme's directory and customize it, just like customizing other
 * Drupal templates such as page.html.twig or node.html.twig.
 *
 * Instead of overriding the theming for all fields, you can also just override
 * theming for a subset of fields using
 * @link themeable Theme hook suggestions. @endlink For example,
 * here are some theme hook suggestions that can be used for a field_foo field
 * on an article node type:
 * - field--node--field-foo--article.html.twig
 * - field--node--field-foo.html.twig
 * - field--node--article.html.twig
 * - field--field-foo.html.twig
 * - field--text-with-summary.html.twig
 * - field.html.twig
 *
 * Available variables:
 * - attributes: HTML attributes for the containing element.
 * - label_hidden: Whether to show the field label or not.
 * - title_attributes: HTML attributes for the title.
 * - label: The label for the field.
 * - multiple: TRUE if a field can contain multiple items.
 * - items: List of all the field items. Each item contains:
 *   - attributes: List of HTML attributes for each item.
 *   - content: The field item's content.
 * - entity_type: The entity type to which the field belongs.
 * - field_name: The name of the field.
 * - field_type: The type of the field.
 * - label_display: The display settings for the label.
 *
 *
 * @see template_preprocess_field()
 */
#}
{%
  set classes = [
    'field',
    'field--name-' ~ field_name|clean_class,
    'field--type-' ~ field_type|clean_class,
    'field--label-' ~ label_display,
  ]
%}
{%
  set title_classes = [
    'field__label',
    label_display == 'visually_hidden' ? 'visually-hidden',
  ]
%}

{% if label_hidden %}
  {% if multiple %}
    <div{{ attributes.addClass(classes, 'field__items') }}>
      {% for item in items %}
        <div{{ item.attributes.addClass('field__item') }}>{{ item.content }}</div>
      {% endfor %}
    </div>
  {% else %}
    {% for item in items %}
      <div{{ attributes.addClass(classes, 'field__item') }}>{{ item.content }}</div>
    {% endfor %}
  {% endif %}
{% else %}
  <div{{ attributes.addClass(classes) }}>
    <div{{ title_attributes.addClass(title_classes) }}>{{ label }}</div>
    {% if multiple %}
      <div class="field__items">
    {% endif %}
    {% for item in items %}
      <div{{ item.attributes.addClass('field__item') }}>{{ item.content }}</div>
    {% endfor %}
    {% if multiple %}
      </div>
    {% endif %}
  </div>
{% endif %}

```

Most themes extend `classy` as a base. If not, they extend `stable` by default. Both have a `field.html.twig` file in their theme folder. Every field in your site will render with this template by default, unless a more specific template is provided by creating a new file and giving it a specific theme name suggestions, which are mentioned in the comments of the file above.

If you copy this file to your theme, you can then override this markup for your theme.

If you enable twig debugging, it will inject template suggestion names into the source as you view the page. These will allow more granular control over field level markup and help figure out what filenames and their order of specificity are in order to override template output.

Let's say you have a field called Company. For this field, you want the label to be an H3. One of the possible template suggestions would be `field--field-company.html.twig`. If you create that file and place it in your theme, you can do:

```
{#
/**
 * @file
 * Theme override the Company field.
 *
 * Available variables:
 * - attributes: HTML attributes for the containing element.
 * - label_hidden: Whether to show the field label or not.
 * - title_attributes: HTML attributes for the title.
 * - label: The label for the field.
 * - multiple: TRUE if a field can contain multiple items.
 * - items: List of all the field items. Each item contains:
 *   - attributes: List of HTML attributes for each item.
 *   - content: The field item's content.
 * - entity_type: The entity type to which the field belongs.
 * - field_name: The name of the field.
 * - field_type: The type of the field.
 * - label_display: The display settings for the label.
 *
 *
 * @see template_preprocess_field()
 */
#}
{%
  set classes = [
    'field',
    'field--name-' ~ field_name|clean_class,
    'field--type-' ~ field_type|clean_class,
    'field--label-' ~ label_display,
  ]
%}
{%
  set title_classes = [
    'field__label',
    label_display == 'visually_hidden' ? 'visually-hidden',
  ]
%}

{% if label_hidden %}
  {% if multiple %}
    <div{{ attributes.addClass(classes, 'field__items') }}>
      {% for item in items %}
        <div{{ item.attributes.addClass('field__item') }}>{{ item.content }}</div>
      {% endfor %}
    </div>
  {% else %}
    {% for item in items %}
      <div{{ attributes.addClass(classes, 'field__item') }}>{{ item.content }}</div>
    {% endfor %}
  {% endif %}
{% else %}
  <div{{ attributes.addClass(classes) }}>
    <h3{{ title_attributes.addClass(title_classes) }}>{{ label }}</h3>
    {% if multiple %}
      <div class="field__items">
    {% endif %}
    {% for item in items %}
      <div{{ item.attributes.addClass('field__item') }}>{{ item.content }}</div>
    {% endfor %}
    {% if multiple %}
      </div>
    {% endif %}
  </div>
{% endif %}

```

Note where I changed the label div to an h3. The top part of the if statement is only if you set the label to `Hidden` in the Display settings of the content type.

Suppose you always want a label to display for Company, you can simplify the template further:

```
{#
/**
 * @file
 * Theme override the Company field.
 *
 * Available variables:
 * - attributes: HTML attributes for the containing element.
 * - label_hidden: Whether to show the field label or not.
 * - title_attributes: HTML attributes for the title.
 * - label: The label for the field.
 * - multiple: TRUE if a field can contain multiple items.
 * - items: List of all the field items. Each item contains:
 *   - attributes: List of HTML attributes for each item.
 *   - content: The field item's content.
 * - entity_type: The entity type to which the field belongs.
 * - field_name: The name of the field.
 * - field_type: The type of the field.
 * - label_display: The display settings for the label.
 *
 *
 * @see template_preprocess_field()
 */
#}
{%
  set classes = [
    'field',
    'field--name-' ~ field_name|clean_class,
    'field--type-' ~ field_type|clean_class,
    'field--label-' ~ label_display,
  ]
%}
{%
  set title_classes = [
    'field__label',
    label_display == 'visually_hidden' ? 'visually-hidden',
  ]
%}

 <div{{ attributes.addClass(classes) }}>
   <h3{{ title_attributes.addClass(title_classes) }}>{{ label }}</h3>

   {% if multiple %}
     <div class="field__items">
   {% endif %}
   {% for item in items %}
     <div{{ item.attributes.addClass('field__item') }}>{{ item.content }}</div>
   {% endfor %}
   {% if multiple %}
     </div>
   {% endif %}
 </div>

```

After clearing the site cache, Drupal should pick up on this new template file, and render any instance of the Company field with it, getting your new label markup. But note, now that you do this change, setting the Company label to hidden in the future will have no effect! We removed the logic - just to illustrate.

That's the nuts and bolts of whats going on and how you can adapt and theme field output, or nodes, taxonomy, user, paragraphs, views, etc.

If you have a lot of fields and this seems overwhelming right now, there is a module called Display Suite that places a lot of this into the admin UI on the field display settings form. If you are new to Drupal 8, twig, etc - Display Suite is a fine starting point because it will accomplish the same thing, just without much, if any, coding.

For Display Suite check the documentation here about fields and labels.

Furthermore, I recommend Drupalize.me's excellent series on theming in Drupal 8. It will help accelerate your knowledge of theming much faster.

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


# Question
Title: How to programmatically display an image field in Drupal 7 + default value when needed
I've used `field_view_field` to display an image field for a specific entity in Drupal. The problem is when that entity doesn't have any value for field. I expect `field_view_field` to display the default image for field but it doesn't load default value of the field.

How can I do this?

# Answer
> 1 votes
field\_view\_field is a correct function to use if you want to display node image (if provided) or default (attached to field settings) if not.

```
$node = node_load($nid);
print render(field_view_field('node', $node, 'field_image')));

```

# Answer
> 0 votes
In our case we have two set of images

1. Default image
2. another is node specific image

i created two block in views in the **first view get the default image it will always have the default image**

and in the **second block render the image if the image field is empty render the whole default block there**, below is the sample code

in views block 2 select the image field in the view and exclude it from display

in views global php add the code below

```
<?php
    $banner = isset($data->field_field_banner)? $data->field_field_banner : '';
    if(!empty($banner)){
      print drupal_render($banner);
    }else{
          print render_view_block_for_noresult('view_name','block_name');
    }
?>

/* function to render default view blocks if no banner is present */
function render_view_block_for_noresult($view_name='',$block_name=''){
        $view = views_get_view($view_name);
        if(isset($view) && !empty($view))
            return $view->preview($block_name);
}

```

this will help you to print the image and get the default image printed in the view.

# Answer
> 0 votes
By the way, I find a solution for my problem. If there aren't any value for field, it retrieves field instance information then load default image of field and display it.

```
       $user_loaded = user_load($uid);
if ($user_loaded->field_profile_photo[LANGUAGE_NONE][0]) {
  $user_pic = drupal_render(
    field_view_field('user', $user_loaded, 'field_profile_photo',
      array(
        'label' => 'hidden',
        'settings' => array(
          'image_style' => '170_170'
        )
      )));
}
else {
  $instance = field_info_instance('user', 'field_profile_photo','user');
  $user_loaded->field_profile_photo[LANGUAGE_NONE][0] = (array)file_load($instance['settings']['default_image']);
  $user_pic = drupal_render(
    field_view_field('user', $user_loaded, 'field_profile_photo',
      array(
        'label' => 'hidden',
        'settings' => array(
          'image_style' => '170_170'
        )
      )));
}

```

# Answer
> 0 votes
Here's an example of how to use a field instance's default image as a fallback when the individual image field itself is empty.

To briefly explain the concept, use field\_get\_items() to attempt to get the image attached to the entity (e.g. node, user, taxonomy\_term, ...), then fallback to field\_info\_instance() if an image has not been uploaded.

Once an image is available to work with, set the `$file` variable to the image reference, which will get rendered after calling field\_view\_value().

```
$field_image = field_get_items('node', $node, 'field_image');

if (!empty($field_image)) {
  $file = $field_image[0];
}
else {
  $info = field_info_instance('node', 'field_image', 'blog');

  if (!empty($info) && $info['settings']['default_image'] > 0) {
    $default_image_fid = $info['settings']['default_image'];

    $file = (array) file_load($default_image_fid);
  }
}

if ($file) {
  $image = field_view_value('node', $node, 'field_image', $file, array(
    'type' => 'image',
    'settings' => array(
      'image_style' => NULL,
    ),
  ));

  print render($image);
}

```

All of this logic could be wrapped up into a helper function or simply used wherever needed.

---
Tags: entities
---


title: How to unblock IPs in bulk?

text:
# Question
Title: How to unblock IPs in bulk?
I use the Drupal Core IP blocking feature (`/admin/config/people/ip-blocking`) to block IP addresses during spam attacks. However, as most of these will be dynamic ones owned by legitimate users a day later, I want to remove these blocks.

I could delete them one by one in the IP blocking interface, but with dozens of addresses, that is not a comfortable way. Any alternative?

# Answer
There are several options, choose depending on your requirements:

* You can use module Blocked IPs Expire to add an expiration date to IP blocks when adding them. The Drupal cron job will remove the blockings after expiry.
* You can remove all of the IP blockings at once with this `drush` command:

```
drush sql-query "TRUNCATE TABLE blocked_ips"

```
* You can remove just some IP blockings (e.g. an IP range) with similar `drush` commands. For example to delete all IPv4 blocks:

```
drush sql-query "DELETE FROM blocked_ips WHERE ip LIKE '%.%.%.%'"

```

Note that auto-banning users and IP addresses after a number of unsuccessful login attempts is a different Drupal Core mechanism, resulting in entries in table `flood`more details. To remove these bans, the Flood Unblock module can help you. (But that mechanism is out of the scope of this question anyway.)
> 1 votes

---
Tags: 7, users
---


# Question
Title: How to display all taxonomy terms as links and point them to nid in views
1. I created a taxonomy vocabulary and terms.

2. I created a content type with the taxonomy.

3. I added contents.

4. I would like to create a views block that will display all the taxonomy terms as links as well as each link should point to its NID.

For my views block:

I selected the taxonomy field.

I selected "Rendered taxonomy terms" in Formatter.

Click the Taxonomy field.

Selected output this field as link.

Entered node/\[nid\] as links path.

It did not work. Also, links are not pointed to NID. Can you please help how to edit the views settings?

---

Views settings:

# Answer
Assuming that the basis of your View is a node, you can add a field to your View: `Content: Link` (which is a link to the node of the View's row) and use the `Rewrite results > Rewrite the output of this field` with the contents of the taxonomy term (if I'm not mistaken `[field_cities_we_serve1]`).
> 1 votes

---
Tags: views
---


# Question
Title: Unban repeated attempts via command or mysql?
Natively, in Drupal 7 after repeated unsuccessful attempts a particular user would be banned after repeated offending logins.

Is it possible to programmatically unban a particular user? I heard if you truncate the flood table you can be unbanned. Is this true?

# Answer
Yes, it is true, but it is also excessive.

That table is also used for users sending emails with the contact form. Rather than truncating that table, it is better to remove only the necessary entries.
user\_login\_final\_validate() contains the following code.

```
  if (empty($form_state['uid'])) {
    // Always register an IP-based failed login event.
    flood_register_event('failed_login_attempt_ip', variable_get('user_failed_login_ip_window', 3600));
    // Register a per-user failed login event.
    if (isset($form_state['flood_control_user_identifier'])) {
      flood_register_event('failed_login_attempt_user', variable_get('user_failed_login_user_window', 21600), $form_state['flood_control_user_identifier']);
    }

```

Just remove any row in the "flood" table where the "event" field is equal to "failed\_login\_attempt\_ip" or "failed\_login\_attempt\_user"; in that way, any login ban is removed.
This would remove the login ban for every user, including the ones who are trying to access somebody else's account by brute force. Unfortunately, without to know the IP of the user to unblock, it is not possible to unblock just a specific user: The login validation callbacks first check if the user is login banned basing on the IP, then basing on the user ID for the account used to login.
> 3 votes

# Answer
The Flood Unblock module provides both a UI and a `drush` command to remove bans from excessive failed logins of a particular type:

* `ip` for IP address bans due to wrong usernames
* `user` for IP address bans due to wrong passwords
* `all` for both these types of bans

So while it is not possible with this module to unban a particular user, you can remove all bans resulting from failed logins (as recommended in the other answer) like this:

```
drush flood_unblock all

```
> 0 votes

# Answer
When you *do* know the IP address of the user you want to unblock, for example by letting them google it, you can unban that user with a SQL query like this:

```
drush sql-query "DELETE FROM flood WHERE
    event LIKE 'failed_login_attempt_%' AND
    identifier LIKE '%189.67.116.250'"

```
> 0 votes

---
Tags: users
---


title: Show an "updated" timestamp on nodes

text:
# Question
Title: Show an "updated" timestamp on nodes
Is there a way to show a "Last Updated" timestamp for nodes? Maybe even in views as well?

EDIT: Via a module or core configuration

# Answer
IN views, just include a `NODE/node last updated date` field in your row. For nodes, take the advice of MPD and those commenting in Showing the date of the latest edit, instead of node's posting date about creating the *very* simple preprocess() and/or view() hooks.
> 1 votes

# Answer
I needed this same feature myself on two separate sites, so I wrote a little module you can try: https://www.drupal.org/project/updated
> 0 votes

---
Tags: 7, datetime
---


# Question
Title: How to tell if content has been migrated
I am using drupal2drupal migration. How can I indicate that some content has been migrated as opposed to being manually added.

# Answer
> 2 votes
You could alter the incoming data and attach a taxonomy tag, like 'migrated', to indicate this.

You could also add (migrated) in the title, but you would have to ensure this does not affect users, terms, URL aliases, etc. Hence why I suggest a taxonomy term. I am not that familiar with D2D API but I know this is very easy to do with Migrate Framework.

# Answer
> 0 votes
It has been a while since I have done a proper D2D migration (I do more imports from non-Drupal sources using custom scripts), but you should be able to examine the migration map table(s) for nodes. If the destination node ID exists, then you know that the node in question was migrated.

However, when I have used D2D I would prefer to add `field_old_nid` to each node and add a mapping from `nid => field_old_nid` for that. Then just hide that field from public view.

I have found that having the old nid as a field can come in handy down the road. For example, when you have your old and new sites up, you can easily add an link from the old site to the new site for debug/QA purposes, using the http://example.com/node/nid URL for the old site. I also seem to recall using some filter shenanigans to fixup LinkIt style links in body content.

# Answer
> 0 votes
New tables are created for each migration type, the old and new Entity IDs are stored in that table. The name is different for each table, so I can't specifically tell you the table name, but if you look in the database you can see the tables that start with migrate\_. A query on that table can tell you if the content has been migrated.

---
Tags: 7, migrations
---


# Question
Title: How to list different terms with their nodes in one view?
Now I had a question, is it possible to build a view which can display different terms with multiple content on drupal 8?

For example,

Term 1

* node 1
* node 2
* node 3

Term 2

* node 2
* node 4
* node 6

Term 3

* node 5
* node 7
* node 8

Can someone help me out?

I appreciate your help!

# Answer
You can achieve you requirement by below steps:

1. Create view at **/admin/structure/views**
2. Now add fields which you want to display.
3. Click on **Settings** under FORMAT section.

4. Now add your taxonomy field as **Grouping Field**
> 2 votes

---
Tags: 8
---


# Question
Title: How do I save username and password using a "Remember me" checkbox in the login form?
I want to save username and password using a *Remember me* checkbox. If I click it, the username and password should be save for future. In Drupal I am using Persistent login module to do this but I am not able to save the username and password.

# Answer
I think Remember me module doing the same job which you wants.
> 1 votes

---
Tags: 7
---


# Question
Title: Feeds Module Periodic Import not working
I created a Job portal using the feeds module. I have the Periodic Import on every 3 hours. It says you have to configure your cron. I have read where there are others having issues a few years ago and they say to use Ultimate cron or Elysia Cron. I tried both and am not sure what/ where I am suppose to set and still isn't working.

# Answer
> 1 votes
If you are using Ultimate Cron, make sure you set the 3 hour cron to the Job Scheduler cron and and also to the Feeds crons (there are like 4 of them).

---
Tags: feeds
---


title: How I can unit-test APIs?

text:
# Question
Title: How I can unit-test APIs?
How I can unit-test APIs? Is there any method for asserting API response in drupal 7?

# Answer
> -1 votes
You can find an example in the Examples for Developers module. Here are two excellent guides:

---
Tags: 7, testing
---


# Question
Title: Render entity from entity reference field
(Drupal 8) So I have a content type called Browse, then I have created a paragraph which is a entity reference field for content of Blog. So now when I create a piece of content in Browser I can add multiple blog posts to this page with the entity reference field from paragraphs. I can not figure out how to render the blog data into my twig template. Maybe I am using the wrong twig template file? I am trying with a field--paragraph--blog.html.twig. Does this need to be done in the theme\_preprocessor?

# Answer
> 1 votes
You can enable Twig Debugging in `sites/default/services.yml`. If `services.yml` does not yet exist; copy `default.services.yml` and rename it to `services.yml`.

Set the debug variable to true:

```
parameters:
  twig.config:
    debug: true

```

Now clear cache and refresh your page. Look in the html source and you should see some template suggestions.

---
Tags: theming, 8, paragraphs
---


title: How to add clone of check box values?

text:
# Question
Title: How to add clone of check box values?
I have a field as check-box. This check box should be used unlimited times with the same field but different values. Is there any possible way to do it without writing a module or do I need to write a module for this requirement?

# Answer
> 2 votes
> This check box should be used unlimited times with the same field but different values.

You need to add a field of Type: `List (Text)` with a Widget of `Checkboxes/Radio Buttons`.

For **allowed values list** you can add them like this:

```
Option 1
Option 2
Option 3
Option 4

```

And when you save settings, if you edit it again, you will notice Drupal auto converts it to the proper format of:

```
Option 1|Option 1
Option 2|Option 2
Option 3|Option 3
Option 4|Option 4

```

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


title: Draggable views weights not applied?

text:
# Question
Title: Draggable views weights not applied?
I have hard time setting up a DraggableViews (DV) view to re-order content. The DV actually **does** save the weights - they appear correct in the draggable table, but on the user side (when viewed on the site page) the weights are all zero (not retrieved?).

The site is bi-lingual and the content is tagged with a vocabulary. The purpose of the DV is to set the order within a term. In the header there's an exposed filter to allow the admin set the correct sequence within a term.

To my eyes, the query run to generate visitor's view is correct, but I'm not an expert.

Please refer to the attached mockup image to get an idea what's going on.

I have the latest version of DV + Views 3.5.

Has anyone been through this? Does this have a known workaround? Is this module limitation or is it the view set up incorrectly?

**Edit:**

**User-facing View:**

```
SELECT draggableviews_structure.parent AS draggableviews_structure_parent, node.title AS node_title, node.nid AS nid, node.language AS node_language, draggableviews_structure.weight AS draggableviews_structure_weight
FROM
{node} node
LEFT JOIN {draggableviews_structure} draggableviews_structure ON node.nid = draggableviews_structure.entity_id AND draggableviews_structure.view_name = 'project_reorder' AND draggableviews_structure.view_display = 'page' AND draggableviews_structure.args = '[]'
WHERE (( (node.status = '1') AND (node.type IN  ('project')) AND (node.language IN  ('en')) ))
ORDER BY draggableviews_structure_weight ASC

```

**Sorting UI View**

```
SELECT draggableviews_structure.parent AS draggableviews_structure_parent, node.title AS node_title, node.nid AS nid, node.language AS node_language, draggableviews_structure.weight AS draggableviews_structure_weight
FROM
{node} node
INNER JOIN {field_data_field_genre} field_data_field_genre ON node.nid = field_data_field_genre.entity_id AND (field_data_field_genre.entity_type = 'node' AND field_data_field_genre.deleted = '0')
LEFT JOIN {draggableviews_structure} draggableviews_structure ON node.nid = draggableviews_structure.entity_id AND draggableviews_structure.view_name = 'project_reorder' AND draggableviews_structure.view_display = 'page' AND draggableviews_structure.args = '{\"field_genre_tid_i18n\":\"1\",\"language\":\"en\"}'
WHERE (( (node.status = '1') AND (node.type IN  ('project')) AND (node.language IN  ('en')) AND (field_data_field_genre.field_genre_tid = '1') ))
ORDER BY draggableviews_structure_weight ASC

```

Note that the sorting view makes use of arguments (derived from exposed filter), while the user-facing one does not. I would think this might case the problem.

# Answer
> 1 votes
Solution from Chris (original post):

**It worked to me.**

" Only solution that worked for me was the following:

* go to your content type/vocabulary
* add a weight field (label: weight | machine name: weight | field type: integer
* edit your sorting view and add sort criteria for your newly added weight field
* edit your draggable views field and change "Handler" from Native to FieldAPI
* under Field select your weight field -go to your content view and add the new weight field as you sort criteria

This is the only thing that worked for me. If it doesn't work immediately, just reorder a few items on your draggable view so that the ordering values are reset.

Hope this works for you too. "

---
Tags: views
---


# Question
Title: No route found for GET /block-render?_format=xml
I have installed render-block 8.x-1.0-alpha1 module in drupal 8 and i try to get all blocks like this:

`http://localhost/drupal8/block-render?_format=xml`

But i get this message error:

```
<response>
    <message>No route found for "GET /block-render"</message>
</response>

```

where is the problem ?

# Answer
> 0 votes
I have installed RestUI module and configured the REST resources for Block Render

admin -\> config -\> SERVICES WEB -\> Rest

and it works now !

---
Tags: blocks, 8
---


# Question
Title: How to add product thumbnails to Checkout?
I am wondering if anyone can help me figure this out. Using Drupal 7, and Ubercart 3x.

I'm trying to add the product thumbnails to the checkout pane as they show up in the "View Cart" pane. The table seems largely the same minus the fact that on the checkout page itself, there are no thumbnails of the products. I'm okay with PHP and poking around haven't been able to find how I could add this. Thanks!

# Answer
> 1 votes
You can override the theme function uc\_cart\_review\_table to accomplish this.

```
function YOUR_THEME_uc_cart_review_table($variables) {
  $items = $variables['items'];
  $show_subtotal = $variables['show_subtotal'];

  $subtotal = 0;

  // Set up table header.
  $header = array(
    array('data' => theme('uc_qty_label'), 'class' => array('qty')),
    array('data' => t('Products'), 'class' => array('products'), 'colspan' => 2),
    array('data' => t('Price'), 'class' => array('price')),
  );

  // Set up table rows.
  $display_items = uc_order_product_view_multiple($items);
  if (!empty($display_items['uc_order_product'])) {
    foreach (element_children($display_items['uc_order_product']) as $key) {
      $display_item = $display_items['uc_order_product'][$key];
      $image = uc_product_get_picture($display_item['#entity']->nid, 'uc_cart');

      $subtotal += $display_item['total']['#price'];
      $rows[] = array(
        array('data' => $display_item['qty'], 'class' => array('qty')),
        array('data' => $image, 'class' => array('image')),
        array('data' => $display_item['product'], 'class' => array('products')),
        array('data' => $display_item['total'], 'class' => array('price')),
      );
    }
  }

  // Add the subtotal as the final row.
  if ($show_subtotal) {
    $rows[] = array(
      'data' => array(
        // One cell
        array(
          'data' => array(
            '#theme' => 'uc_price',
            '#prefix' => '<span id="subtotal-title">' . t('Subtotal:') . '</span> ',
            '#price' => $subtotal,
          ),
          // Cell attributes
          'colspan' => 4,
          'class' => array('subtotal'),
        ),
      ),
      // Row attributes
      'class' => array('subtotal'),
    );
  }

  return theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('class' => array('cart-review')), 'sticky' => FALSE));
}

```

With the code `$image = uc_product_get_picture($display_item['#entity']->nid, 'uc_cart');` you can read out the product image and add it to the table.

---
Tags: 7, media, ubercart
---


title: Flickr module not showing any photos

text:
# Question
Title: Flickr module not showing any photos
I am attempting to use the Flickr module 7.x-1.x-dev to display a block of recent photos from a photostream on Flickr. I have setup the API keys and correct user ID, but the block is not producing any output. I've checked the Drupal logs and can't see any issues. I've also run cron and cleared the cache.

Does anyone know how to get this module working or of any alternatives to this module that work in 7? I tried Flickrippr but it produced a lot of PHP errors that brought the site down.

# Answer
Use the block *Flickr: User photos corresponding with a node's taxonomy term, location and/or date field* and under FILTER / SORT ORDER leave *Flickr tags as node taxonomy terms (choose a vocabulary to use)* on *none*.

The sandbox demo at https://simplytest.me/project/flickr/7.x-1.x shows an example in the sidebar. Log in there and check the settings used with your own.
> 0 votes

---
Tags: 7
---


# Question
Title: When term is not selected, output specific text
I have a content type, Article with a field 'Category' as term reference to 'category' taxonomy.

Category taxonomy has 2 terms, 'Live' and 'Outdoor'

Field's widget type is 'Check Boxes'.

* When Live is checked, it should say 'Program is Live'
* When Live is NOT checked, it should say 'Program is NOT Live'

* When Outdoor is checked, it should say 'Program is outdoor'
* When Outdoor is NOT checked, it should say 'Program is indoor'

Creating a terms view and using conditional field in view, I can check either value is empty or not, and can out put the desire result if there is only ONE term. But cant be done using multiple terms in the vocab.

When both are selected or not, every time both conditions are called for each term. And the output is true or false every time.

# Answer
You can use DDF module to implement this. Module url is https://www.drupal.org/project/ddf
> 0 votes

---
Tags: views, nodes, taxonomy-terms
---


# Question
Title: How to add backgroud image to bootstrap flatly?
Hi Im not a theming hero,

Im an happy user of drupal8 and bootstap theme flatly.

I would like to have this sitebranding logo as a background image.

After 2 days of watching youtube tutorials about theming up bootstrap I can;t figure it out where to make the right modifications?

please help

# Answer
> 1 votes
It's best practice to create a child theme on Bootstrap, the css modifications go into your child theme. That way you can update Bootstrap later on, otherwise your alterations would be overwritten by the update. More info on how to create a child theme can be found here

---
Tags: theming
---


title: Facet-like contextual filters on View

text:
# Question
Title: Facet-like contextual filters on View
I've created an overview to display jobs. All jobs are tagged with taxonomies "location" and "industry".

I'd like to display contextual filters (with checkboxes) in a sidebar to filter the jobs. As in a facet search. I would I go about this?

# Answer
> 0 votes
It's possible to mimic the behaviour of Facets (with checkboxes) using the Better exposed filter module.

"The Better Exposed Filters module replaces the Views' default single- or multi-select boxes with radio buttons or checkboxes, respectively."

If that doesn't help you I suggest just using Search Api with Search Api DB and Facets API to make your filtered view.

---
Tags: 7, views, search
---


# Question
Title: How can I hook into an entityform? So that i could create a custom dropdown which is populated from a database
I am trying to create a custom Dropdown which is populated form a database but I'm not getting which hook to use and how to use it. My module name is "entityform" Plzz Help Thanks :)

# Answer
You can write a hook\_form\_alter()

```
function hook_form_alter(&$form, &$form_state, $form_id) {
    dpm($form);
}

```

After you cleared the cache you can print the form ID or just alter the form right away.

I suggest to check what the form ID is and then add:

```
function hook_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
    dpm($form);
}

```

To alter it. (Make sure to clear cache again)

in both instances hook is to be replaced by your module name. When you want to use the dpm() function you'll have to install the Devel module.

I hope this helps!
> 2 votes

---
Tags: hooks
---


title: Registration problem

text:
# Question
Title: Registration problem
I was testing my users accounts on my site, and login works fine for my admin account I created with MySQL in terminal.

But when I try to create a new account with the registration form I have, it shows the succeed message I created:

> Thank you for registering

Still the succeed message is shown, the account isn't created and an error occurs:

> Unable to send email. Contact the site administrator if the problem persists.

# Answer
**Unable to send email. Contact the site administrator if the problem persists.**

This error is due to email sending failed.

You can use SMTP Authentication Support module for sending email.

> This module allows Drupal to bypass the PHP mail() function and send email directly to an SMTP server. The module supports SMTP authentication and can even connect to servers using SSL if supported by PHP.

You can take the picture as reference for SMTP configuration.
> 0 votes

---
Tags: 8, forms, users
---


title: Content field value as background color

text:
# Question
Title: Content field value as background color
I have a content type with 4 fields

* 1.featured\_pic
* 2.company\_logo
* 3.background\_color

I'm using views for the teaser rewriting the result.

```
<div class="portfolio-background-color" style="background-color:{{ background_color }};" >

       <span class="Portfolio-featured-container">
           {{ featured_pic }}

       <span class="featured-logo-container">
      {{ company_logo }}
        </span>
   </span>
</div>

```

However the background color is not being picked up. How can I use it as an inline style value.

or is it possible to pass the value `{{ background_color }}` to jquery

```
  <script type="text/javascript">
  $(document).ready(function() {
      $(".portfolio-background-color").hover(
      function() {
          //mouse over
          $(this).css('background', '*{{ background_color }}*')
      }, function() {
          //mouse out
          $(this).css('background', '')
      });
  });
  </script>

```

# Answer
Looks like the Views text area filters `style="anything"` out to prevent XSS attacks. If you create a template file for your view, I believe it will work.

As pointed out by @4K4

> If you put a twig variable inside of a style attribute standard sanitizing won't prevent . To protect against this you need to filter even brackets. See XSS attacks and style attributes

Therefore, **you need to make sure** your field is not a text field, where the user has the power to write/put whatever they want. You should use a Select list field or better yet use a color field.
> 1 votes

# Answer
Since you have the markup written I would advise telling Views to use the "Content" rendering, and select the teaser view mode.

Your teaser view mode twig template becomes:

```
<div class="portfolio-background-color" style="background-color:{{ content.background_color }};" >

   <span class="Portfolio-featured-container">
      {{ content.featured_pic }}

      <span class="featured-logo-container">
        {{ content.company_logo }}
      </span>
   </span>
</div>

```

Note that `{{ content.foo }}` is a renderable array for each field - which will call their respective field twig templates and render them according to the field formatter setting.

It is here where you can control the exact markup and not worry about Views escaping anything.

As for the background color, depending on the value or type of input, you may have to do one of two things.

### field--field-background-color.html.twig

You might use this template suggestion to strip out all markup and just print the field value.

```
{% for item in items %}
  {{ item.content }}
{% endfor %}

```

Although you may have minor issues getting it to print what you're looking for.. I don't know if it is a raw color value or hex color. As noted, don't use a text field for this.

### template\_preprocess\_node

Another thing you can do is preprocess a node and add a new variable to it:

```
/**
 * Implements hook_preprocess_paragraph().
 * @param $variables
 */
function mytheme_preprocess_paragraph(&$variables) {
  $node = $variables['elements']['#node'];
  $bundle = $node->bundle();

  if ($bundle == 'your_bundle') {
    $variables['background_color'] = $node->field_background_color->value;
  }
}

```

This would add `background_color` as a variable, and you can print it in your teaser twig template with `{{ background_color }}`.
> 1 votes

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


# Question
Title: Show "create new node" form with "my" and "user I followed" content in a single block
I have a content type. Let us say "articles". When a user wants to create an article, the user will go to `/node/add/article` and it will show a form like it shows on stack exchange when go to `/questions/ask`.

What I want?

I want to create a block which will show the "create new node" form + my articles + articles of the user I am following with follow(user) flag. "My" and "user followed" articles should be shown below the form. The form and articles should always be visible in the block. When user saves a new article, it should show in the list below without page refresh.

The user should not be allowed to select text format. The admin should choose which text format to enable on this particular content type.

**Note: When user visits node/add/articles directly, user must not see the articles. User should only see the form to create a new node.**

I am sure I have explained it quite well. Let me know in case you have any questions.

# Answer
> I have a content type. Let us say "articles". When a user wants to create an article, he will go to /node/add/article and it will show a form like it shows on stack exchange when go to /questions/ask.

Give whichever user you want to create the node, permission to do so /admin/people/permissions

```
What I want?

```

> I want to create a block which will show the "create new node" form as above
>
> * my articles

You mean the articles of admin or of the user creating the form? If admin, create a view with articles and filter by user admin, or filter by currently logged in user.

> * articles of the user I am following with follow(user) flag.

as above. I presume you are giving the user the ability to flag other users to follow somehow? So you could filter by a list of users that are being followed.

> "My" and "user followed" articles should be shown below the form. The form and articles should always be visible in the block.
>
> When user saves a new article, it should show in the list below without page refresh.

You would use ajax to achieve this. Check out 'exposed filters' in views and look for the option to 'use ajax'.

> The user should not be allowed to select text format. The admin should choose which text format to enable on this particular content type.

This is built in. There are permissions for, example, "Use the Filtered HTML text format" and in the settings for the content type, which text formats are available.

> Note: When user visits node/add/articles directly, he must not see the articles. He should only see the form to create a new node.
>
> I am sure I have explained it quite well. Let me know in case you have any questions.

There are multiple questions here, and ideally you would post some code and show what you have already done.
> 1 votes

# Answer
I almost got it working. I have found a module, formblock, which enables the presentation of user registration, site wide contact, or node creation forms in blocks. That was one part. Now How I created current user articles + articles of the user (the current user is following)? I have added the export of view. I also enabled ajax.

I generated a block using form block module and then in the header of the view, I added Global: Block area and selected the block generated by the module. Now it is showing the a form above the view.

**There are few to dos.**

1. When I create an article and send it, it redirects me to the individual node page. For example: site.com/node/1. How to solve it?
2. I want to use filtered html on this content type, but do not want users to make the choice. Currently, there is a dropdown showing which enables users to choose which text format to use to create an article.

Exported View

```
$view = new view();
$view->name = 'contextual';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'users';
$view->human_name = 'Contextual';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Contextual';
$handler->display->display_options['use_ajax'] = TRUE;
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['access']['perm'] = 'access user profiles';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'input_required';
$handler->display->display_options['exposed_form']['options']['text_input_required_format'] = 'filtered_html';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'picture' => 'picture',
  'name' => 'name',
  'title' => 'title',
  'comments_link' => 'comments_link',
  'delete_node' => 'delete_node',
  'edit_node' => 'edit_node',
  'created' => 'created',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'picture' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => 'views-align-left',
    'separator' => '',
    'empty_column' => 0,
  ),
  'name' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => 'views-align-left',
    'separator' => '',
    'empty_column' => 0,
  ),
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => 'views-align-center',
    'separator' => '',
    'empty_column' => 0,
  ),
  'comments_link' => array(
    'align' => 'views-align-left',
    'separator' => '',
    'empty_column' => 0,
  ),
  'delete_node' => array(
    'align' => 'views-align-right',
    'separator' => '',
    'empty_column' => 0,
  ),
  'edit_node' => array(
    'align' => 'views-align-right',
    'separator' => '',
    'empty_column' => 0,
  ),
  'created' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => 'views-align-center',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Header: Global: Block area */
$handler->display->display_options['header']['block']['id'] = 'block';
$handler->display->display_options['header']['block']['table'] = 'views';
$handler->display->display_options['header']['block']['field'] = 'block';
$handler->display->display_options['header']['block']['empty'] = TRUE;
$handler->display->display_options['header']['block']['block_to_insert'] = 'formblock:article';
$handler->display->display_options['header']['block']['title'] = '<none>';
/* Relationship: User: Content authored */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'users';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
/* Relationship: Flags: follow */
$handler->display->display_options['relationships']['flag_content_rel']['id'] = 'flag_content_rel';
$handler->display->display_options['relationships']['flag_content_rel']['table'] = 'users';
$handler->display->display_options['relationships']['flag_content_rel']['field'] = 'flag_content_rel';
$handler->display->display_options['relationships']['flag_content_rel']['required'] = 0;
$handler->display->display_options['relationships']['flag_content_rel']['flag'] = 'follow';
/* Field: User: Picture */
$handler->display->display_options['fields']['picture']['id'] = 'picture';
$handler->display->display_options['fields']['picture']['table'] = 'users';
$handler->display->display_options['fields']['picture']['field'] = 'picture';
$handler->display->display_options['fields']['picture']['label'] = '';
$handler->display->display_options['fields']['picture']['element_label_colon'] = FALSE;
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['name']['element_label_colon'] = FALSE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['relationship'] = 'uid';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['element_label_colon'] = FALSE;
/* Field: Content: Delete link */
$handler->display->display_options['fields']['delete_node']['id'] = 'delete_node';
$handler->display->display_options['fields']['delete_node']['table'] = 'views_entity_node';
$handler->display->display_options['fields']['delete_node']['field'] = 'delete_node';
$handler->display->display_options['fields']['delete_node']['relationship'] = 'uid';
$handler->display->display_options['fields']['delete_node']['label'] = '';
$handler->display->display_options['fields']['delete_node']['element_label_colon'] = FALSE;
/* Field: Content: Edit link */
$handler->display->display_options['fields']['edit_node']['id'] = 'edit_node';
$handler->display->display_options['fields']['edit_node']['table'] = 'views_entity_node';
$handler->display->display_options['fields']['edit_node']['field'] = 'edit_node';
$handler->display->display_options['fields']['edit_node']['relationship'] = 'uid';
$handler->display->display_options['fields']['edit_node']['label'] = '';
$handler->display->display_options['fields']['edit_node']['element_label_colon'] = FALSE;
/* Field: Content: Post date */
$handler->display->display_options['fields']['created']['id'] = 'created';
$handler->display->display_options['fields']['created']['table'] = 'node';
$handler->display->display_options['fields']['created']['field'] = 'created';
$handler->display->display_options['fields']['created']['relationship'] = 'uid';
$handler->display->display_options['fields']['created']['label'] = '';
$handler->display->display_options['fields']['created']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['created']['date_format'] = 'time ago';
$handler->display->display_options['fields']['created']['second_date_format'] = 'long';
/* Field: Content: Add comment link */
$handler->display->display_options['fields']['comments_link']['id'] = 'comments_link';
$handler->display->display_options['fields']['comments_link']['table'] = 'node';
$handler->display->display_options['fields']['comments_link']['field'] = 'comments_link';
$handler->display->display_options['fields']['comments_link']['relationship'] = 'uid';
$handler->display->display_options['fields']['comments_link']['label'] = '';
$handler->display->display_options['fields']['comments_link']['alter']['text'] = '<a href="[comments_link]">Reply</a>';
$handler->display->display_options['fields']['comments_link']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['comments_link']['teaser'] = TRUE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['relationship'] = 'uid';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
$handler->display->display_options['filter_groups']['groups'] = array(
  1 => 'OR',
);
/* Filter criterion: User: Current */
$handler->display->display_options['filters']['uid_current']['id'] = 'uid_current';
$handler->display->display_options['filters']['uid_current']['table'] = 'users';
$handler->display->display_options['filters']['uid_current']['field'] = 'uid_current';
$handler->display->display_options['filters']['uid_current']['value'] = '1';
$handler->display->display_options['filters']['uid_current']['group'] = 1;
/* Filter criterion: Flags: Flagged */
$handler->display->display_options['filters']['flagged']['id'] = 'flagged';
$handler->display->display_options['filters']['flagged']['table'] = 'flagging';
$handler->display->display_options['filters']['flagged']['field'] = 'flagged';
$handler->display->display_options['filters']['flagged']['relationship'] = 'flag_content_rel';
$handler->display->display_options['filters']['flagged']['value'] = '1';
$handler->display->display_options['filters']['flagged']['group'] = 1;

/* Display: CurOrArg */
$handler = $view->new_display('block', 'CurOrArg', 'block_1');

```
> 0 votes

---
Tags: 7, views, nodes, flags
---


title: How to set up URL alias patterns?

text:
# Question
Title: How to set up URL alias patterns?
I would like to set the URL patterns in such a way that the page name of the parent page gets inserted into the URL. For example, in the Main Menu I've got an "About Us" link (about-us) and I would like to create a child page Contact Us (contact-us) underneath it.

How do I set up the URL alias patterns so that the child page URL is automatically set to about-us/contact-us?

# Answer
> 2 votes
URL aliases is supported in Drupal by help of pathauto module; if you enable the Token module, you can use it efficiently by using tokens. Once these modules are enabled, you can visit admin/config/search/path/patterns to set the patterns for URLs.

But as I see in your question, you are looking to set this for menu; you can't do that here.

There is logic behind it for not supporting it. Suppose you have a node/18 for about-us and you have two menu 'About-Us" & "About-Company". Now you can add this same node/18 to both places as child.

How can you have two URL aliases for single node/18? So this is the reason why menu are not supported I think.

You can go for creating content type & use pattern for that. You can set pattern for taxonomy, users, etc.

# Answer
> 1 votes
I can’t check right now, but I remember having used such a pattern. AFAIK you should find corresponding tokens in the Token module. According to this issue, check for `[node:menu-link:parent:url:alias]` (in Drupal 6 it seems to have been `[menu-path-raw]` for the whole path).

The module Pathauto Menu Link seems to be useful when you use such a pattern, as it updates the aliases when the menu items are moved.

The module Menu Trails (for D6) allows "the menu trail to be used in automatic path alias creation".

# Answer
> 0 votes
**I know this is an old post, but for people looking for an answer in DRUPAL 8 this is a way you can do it.**

Pathauto is what you are looking for. It allows you to create paths for content types as well as subpages for each page of that content type using taxonomy definitions. You may want to become more familiar with path auto if you haven't used it before because it can be very powerful.

Here are the basic steps:

1. Create your content type
2. Create your taxonomy with pre-defined values (or not, up to you on how it behaves) for each page of the content type
3. Create secondary page content type
4. In secondary page, create field for entity reference to the taxonomy you created
5. OPTIONAL: Hide this field from display
6. In pathauto, use the tokens to drill down your path (example: \[node:field\_taxonomyname:entity\]/\[node:title\])

Since Drupal 8 is so new you may need to play with your options because each sites definition of taxonomy could be very different, but always make sure to clear your cache before deleting/generating aliases.

There is also a great video I found that walks you through how to do it: https://www.youtube.com/watch?v=D1hEXTC-HV0

# Answer
> -1 votes
This page holds good information on creating url alias in drupal.

http://www.drupalasisee.com/url-alias

---
Tags: uri
---


title: Convert taxonomy to entity reference

text:
# Question
Title: Convert taxonomy to entity reference
I have a migration use case where I can't figure out a way to get along with:

I have a Drupal 7 site which shall be migrated to D8. I don't want to migrate the content 1:1 but rearange some things to better fit the D8 way.

In the old site there are products which have an "ingredients" field which is a reference to taxonomy terms. Additionally there are "griege" nodes which technically represent an ingredient but are not associated with the taxonomy vocabulary "ingredients". They have indeed the same title so could be mapped by string comparison.

Now I want to do the following:

* Import all "Griege" nodess from the old site and save them as "Ingredient" nodes
* Import all "Product" nodes to the new site
* Check if they have ingredients (taxonomy terms) assigned
* If so, search for "Ingredient" nodes in the new site (term name == Ingredient title) and attach them to the newly created "Product"

In short I want the assigned taxonomy terms to be converted into "normal" content entities.

What I did so far is to extend the Drupal 7 node source plugin by adding the following left joins within the query() method:

```
$query->leftJoin('taxonomy_index', 'ti', 'ti.nid = n.nid');
$query->leftJoin('taxonomy_term_data', 'ttd', 'ttd.tid = ti.tid');

```

My problem is that I don't know what to do with that information within the process plugin. I could return the correpsonding Ingredient ID but as it's an 1:N relation between Prdouct and Ingredient that would mean it would overwrite the array holding the product ingredients everytime I process a row.

I hope my problem is somehow clear... :/

Some general questions I have:

1. Is there a way to access the datasource (the D7 source database) within a process plugin? E.g. do a select on the old product (get all terms, do the lookup in the new DB and return an array of Node Ids)
2. Could my solution somehow involve the usage of a destiantion plugin (I haven't fully understood the usage of those I fear)?
3. Is there something completely different I missed out to do the job?

Many thanks in advance!

Dennis

# Answer
I don't have time to fully flesh it out at the moment, but the approach I would take would be to:

1. In your product migration, which presumably is using the d7\_node source plugin, override that source plugin and implement prepareRow() (not forgetting to call parent::prepareRow()!) to query the related ingredient terms and $row-\>setSourceProperty('ingredient\_names', /\* array of term names \*?);
2. Use the migrate\_plus entity\_lookup process plugin to map those ingredient\_names to existing (previously imported) ingredient node titles. You'll be looking at the example with full configuration for your use case...

Hope this helps!
> 1 votes

---
Tags: taxonomy-terms, database, entities, migrations
---


# Question
Title: What happens when you choose a default country during installation?
**In the last step when you install Drupal 8 under "Configure site" you can choose a "default country":**

However no clues are provided about the option...

* What happens when you choose a default country for the site?
* And what happens when you just leaves it as "none"?

# Answer
In drupal core this is only used for date and time formats. If you leave it empty you can set it later in the admin menu:

**/admin/config/regional/settings**
> 2 votes

---
Tags: 8, installation
---


title: How to include menu item in breadcrumb

text:
# Question
Title: How to include menu item in breadcrumb
I've this breadcrumb I've created, where I would like to show it as

Home \> Main menu \> Sub menu

Where sub menu is connected to a node. So when a user click on node, it must show the breadcrumb of the above format.

I've done this, but it is only giving

Home \> Sub menu

Menu is missing.

```
function basis_preprocess_breadcrumb(&$variables) {
  if (($node = \Drupal::routeMatch()->getParameter('node')) && $variables['breadcrumb']) {
    $variables['breadcrumb'][] = array(
      'text' => $node->getTitle(),
      'url' => $node->URL()
    );

  }
}

```

# Answer
> 3 votes
Menu Breadcrumb might be what you're looking for.

# Answer
> 1 votes
If the url reflects the correct path, you can add this to your .theme file.

```
function hook_preprocess_breadcrumb(&$variables) {
  $variables['breadcrumb'] = array();
  $variables['node'] = \Drupal::routeMatch()->getParameter('node');

  /** @var \Drupal\Core\Link $link */
  foreach ($variables['links'] as $key => $link) {
    $variables['breadcrumb'][$key] = array('text' => $link->gettext(), 'url' => $link->getUrl()->toString());
  }

  // As of Drupal 8.1.3, core caches breadcrumb parent. This breaks what I'm trying to do. Good-bye to this caching rule.
  $variables['#cache']['contexts'][] = 'url';
}

```

EDIT

If the url is missing the 'Main menu' part, you can manually set the breadcrumb for any specific content type. Again in the theme file.

```
function hook_preprocess_breadcrumb(&$variables) {
  $variables['breadcrumb'] = array();
  $variables['node'] = \Drupal::routeMatch()->getParameter('node');
  $variables['type'] = \Drupal::routeMatch()->getParameter('node')->getType();

  switch($variables['type']) {

    case 'YOUR-CONTENT-TYPE':
      $variables['breadcrumb'] = array(
        array(
          'text' => 'Home',
          'url' => '/'
        ),
        array(
          'text' => 'Main menu',
          'url' => 'Main menu url'
        ),
        array(
            'text' => $variables['node']->getTitle(),
            'url' => $variables['node']->URL()
          ),
        );
      break;

    default:
      /** @var \Drupal\Core\Link $link */
      foreach ($variables['links'] as $key => $link) {
        $variables['breadcrumb'][$key] = array('text' => $link->gettext(), 'url' => $link->getUrl()->toString());
      }
      break;
  }

  // As of Drupal 8.1.3, core caches breadcrumb parent. This breaks what I'm trying to do. Good-bye to this caching rule.
  $variables['#cache']['contexts'][] = 'url';
}

```

---
Tags: 8, breadcrumbs
---


title: Single sign on with an external AMS?

text:
# Question
Title: Single sign on with an external AMS?
In Drupal 8, how would you go about changing the registration/login process to check with an external source like Personify or NetForum to 'log in' a user to Drupal?

# Answer
The CAS module has a quite stable 8.x-1.0-beta2 release. Take a look at the source code of cas.module and which hooks it uses to overrule the regular user actions like registration, login and logout.

(If that doesn't answer your question, please be more specific about which AMS you'd like to implement.)
> 2 votes

---
Tags: 8, users
---


# Question
Title: How do I pass field variables for a database insert helper function
I am trying to set up a database insert helper function for a group of modules for a program I m using to learn Drupal.

I can't figure out how to use my returned array in my db\_insert query, can anyone assist please.

I assumed I could use a for loop as below but that's not working for me, I really appreciate any help you can offer

```
function my_db_insert($table, $fields) {

// Build up a string based on my returned array via a for loop
$insert_fields="";
foreach ($fields as $key=>$value) {
    $insert_fields = $insert_fields . $key . "=>" . $value . ",";
      //drupal_set_message($key . "=>" . $value . ",");
   }

  // Insert into the database.
$id = db_insert($table)
->fields(array(
  //This is where I need put the result of my array so it will add to the database
  $insert_fields
))
->execute();

return $id;

drupal_set_message(t("Record Added!"));

}

```

# Answer
This was answered on the drupal.org forum by @Jaypan:

```
$id = db_insert($table)
  ->fields($fields)
  ->execute();

```
> 1 votes

---
Tags: 7, database
---


# Question
Title: How do I deploy a Page Manager page using code?
I've created a Page Manager page using a Panels layout and a single Variant to act as the desired page. I'd like to store the settings in code for deployment to a different server.

Using Features to export the Page Manager (page\_manager\_pages) component appears to have done this, however the newly deployed page variant's content tab is empty. The page settings have come through, but the page contents don't show up, even though they're clearly in the featurized module code. The desired content for the page variant is in the file myModule.pages\_default.inc, in the function myModule\_default\_page\_manager\_pages().

The result upon deployment is that the Page Manager page is created, and appears in /admin/structure/pages, but the Content tab for the page variant is empty. I need the code the provide the many blocks I placed, configured, and saved within the development environment.

I've also tried exporting the entire page or just the variant and importing that, and get exactly the same results.

What code or step am I missing, please?

My setup:

* Drupal 7.52
* Panels 7.x-3.6
* Page Manager 7.x-1.9
* Features 7.x-2.10

# Answer
aha. This problem was caused by a forgotten dependency within the Page Manager page. Instead of using a default layout such as 'two column,' I'd used the Bootstrap layout provided by the Panels Bootstrap Layouts, and then forgot about it. Features didn't add Panels Bootstrap Layouts as a dependency, it remained disabled after deployment, and the dependent page content didn't show. After I enabled Panels Bootstrap Layouts, the content items showed right up within the variant's Content tab.

So if your feature or your Panels/Pages import doesn't recreate the entire setup, review the original for any options that might be provided by another module.
> 0 votes

---
Tags: features, panels
---


# Question
Title: What is the custom date format to display Days or Months ago in date field?
I want to display # Days Ago, or # Months Ago, or # Years Ago

Example: 3 Days Ago

I need to add custom symbols in the Date field in views.

# Answer
> 1 votes
I think it's best for you to use the Timeago module: https://www.drupal.org/project/timeago

First, it provides a timeago date formatter option for use with dates anywhere, which answers your need.

Second, it solves the caching and correctness of time-ago dates problem for you automatically. Even though you don't mention this in your question, this is important as it's best to cache pages in live production in one way or another.

Good luck.

---
Tags: views, entities, datetime
---


# Question
Title: Make global results header in a view appear below exposed filters
I need to make the text in a global results header appear below the exposed filters on a view and it doesn't give me an option to wrap the header separately from the exposed filters so I can move it below. How can this be done?

# Answer
You could create a custom block and execute php. Something like this:

```
$view = views_get_view('my_view');
// get global header
$view->execute();
$objects = $view->result;

```
> 0 votes

---
Tags: 7, views, theming
---


# Question
Title: Using a Service to expose better getter methods for a Node instance
Currently we use a Service that takes an NodeInterface object as an argument and then gives back a value, i.e:

```
  public function iFullyBooked(NodeInterface $node) {
    $fully_booked_field = $node->get('field_fully_booked')->first();
    $value = $fully_booked_field->getValue();

    return $value['value'] === "1";
  }

```

This works, is testable, but is this a good approach to take? We don't want to put all these preprocess things in a hook, since that function would be ridiculous long and not very nice to work with.

Would this be considered bad practise, and if so, is there a better way?

# Answer
Having a service for frequently used things like this makes sense.

That said, your code can be simplified a lot.

```
$node->get('field_fully_booked')->value == 1;

```

Does exactly the same. If you want to check something, then do a hasField('field\_fully\_booked') to avoid an error if that field doesn't exist.

This relies on magic methods, see https://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet

And yes, I did not use a type safe check on purpose. There are cases where type safety makes sense, but entity field values are not type safe, it actually makes your code more error-prone, for example if you'd change the value with API and did a = 1, then your method would return FALSE.
> 3 votes

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


title: Alter Search Results display

text:
# Question
Title: Alter Search Results display
Currently when I search for something it displays the title of the node and if there is a match a small excerpt from either the content short summary or a small excerpt from the paragraph bundle. If there is no match it displays nothing.

How can i change this so it displays content even if only the title match. How can i change this so it displays the date it was published as well.

The modules involved are paragraphs, solr, searchAPI, Display Suite.

# Answer
You can simply add a new view mode for search results:

1. Go to admin/structure/types/manage/page/display (where "page" is your content type)
2. Expand the *Show Custom display settings* fieldset
3. Check *Search index*

4. Click Save
5. Go to admin/structure/types/manage/page/display/search\_index (where "page" is your content type)

My advice would be to use the Display Suite module as well for extra fields and more options.
> 5 votes

# Answer
I am assuming you're using Drupal 8. You'll want to modify the `search-result.html.twig` template. By default, I believe the code looks something like this:

```
{{ title_suffix }}
<p{{ content_attributes }}>{{ snippet }}</p>

```

You can modify it to display something like the node's body field summary:

```
{{ title_suffix }}
{% if result.node.body.0.summary %}
  <p{{ content_attributes }}>{{ summary|length > 200 ? summary|slice(0, 250) ~ '...' : summary }}</p>
  <div>{{ result.node.created }}</div>
{% else %}
  <p{{ content_attributes }}>{{ snippet }}</p>
  <div>{{ result.node.created }}</div>
{% endif %}

```

EDIT: formatting
> 1 votes

---
Tags: 7, search
---


title: Node as block: Is there a module?

text:
# Question
Title: Node as block: Is there a module?
Is there any module for Drupal 8 that will do same functionality as nodeblock does, or do we have to programmatically render it?

# Answer
> 2 votes
NodeBlock has been replaced by EntityBlock in Drupal 8.

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


# Question
Title: How to link taxonomy and views in a succinct way?
So here is my use case: I have taxonomy vocabularies titled accommodation, and in the vocabulary, there are 4 terms.

* hotel
* motel
* campground
* guest housing

I want to create a view that displays in a page that has these four terms as menu links that once you click the link all content nodes containing that taxonomy term are listed. I have been struggling with this.

My main Block is creating a menu from taxonomy and linking it to the view(I would like to use a custom URL), I have tried the Taxonomy Menu module, which is close, but cannot figure how to configure it correctly, I have gotten closest creating an attachment display within the view. I am so close.

# Answer
Forget views here and write a few lines of own code here. I had this problem also recently. Views is much to unflexible. You must do the following:

1. Create a route to your controller method
2. Get all relevant nodes in the method
3. Create a template via hook\_theme() for the output.
4. Realize all your details! ;)

I needed around ~1 hour for this.
> 1 votes

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


# Question
Title: Disable welcome message for specific roles but keep for others, user_mail_notify
In Drupal 7...

I am trying to find a solution to disable the sending of the user mail register by admin for certain roles. I have scoured the internet and have come up with using a combo of mailcontrol and Rules or custom code in my module.

I'm using Rules to send the message. I didn't want to completely disable the welcome email message for the other roles.

**How can I create this functionality of sending the system mail to some users but not others? (either programmatically or via Rules)**

I have a custom module already, so I used the following hook but nothing happened. I still get the welcome message.

```
function myMod_fields_user_mail_notify($op, $account, $language = NULL) {

 $notify = variable_get('user_mail_' . $op . '_notify', $default_notify);

if (in_array('Administrator', $user->roles)) {
  if ($op == 'register_admin_created') {
   //don't send system email we'll do this with another rule.
    variable_set('user_mail_register_admin_created_notify', false);
  }
  else if ($notify) {
  $params['account'] = $account;
  $language = $language ? $language : user_preferred_language($account);
  $mail = drupal_mail('user', $op, $account->mail, $language, $params);
}
return empty($mail) ? NULL : $mail['result'];
 }
}

```

# Answer
> 0 votes
I kind of stumbled on this after nobody answered my question. (I was desperate)

**The solutions is to:**

1. Edit your welcome email, under Account Settings.
2. Enable Mail Control and disable the welcome email. This content is saved in the database, so don't worry about losing anything.
3. Create a new Rule to react on a new event: After saving a new user account
4. Add in your condition: User has Role && User is being Notified.
5. Under Actions: Send Account E-mail.
6. Under E-mail Type: Choose Welcome E-mail.
7. Save! Clear Cache! Get More Coffee!

---
Tags: rules, hooks, emails
---


# Question
Title: Views: filter content by a field (username) of someone who has never logged in
We have an application that has a field to enter usernames of people who have never logged in before.

When these users log in, we want to filter these applications in a view to match their currently logged in username.

Is this possible?

Detailed explanation:

There are two roles: student and faculty. Both have sections to fill on the same node. Field permissions hides the fields of the other role. We want students to see the node that a faculty created for them in a view when they log in. Can the faculty fill out a username field (student has not logged in before) so that the view will list only the content assigned to the student?

I was thinking of using contextual filters on a taxonomy term with a default value of a PHP script that grabs the current username. However, I don't know if this is possible/practical and the PHP code I found online didn't end up working. Any thoughts or ideas?

two scripts I've tried:

```
global $user;
$user_uid = user_load($user->uid);
$myuserid = $user_uid->field_std_user_id['und']['0']['value'];
return $myuserid;

global $user;
$term= user_load($user->uid)->field_std_user_id;
return $term['und'][0]['tid'];

```

# Answer
You could use Views' exposed filter to filter by username. But you will have to do some coding to get current user's name in the field.
> 0 votes

---
Tags: 7, views
---


# Question
Title: How do I get an uploaded image URL or the default for use in a template (code improvement)
I have a working preprocess function that allows me to grab an image for use as a background in the page template from a node if the field exists. It falls back on a default image if supplied, the function looks like this:

```
<?php
/**
 * Implements hook_preprocess_page() for page.html.twig.
 */
function mymodule_preprocess_page(array &$vars) {

  // Preprocess the hero image if it exists (it should on all nodes).
  if (isset($vars['node']->field_hero)){
    $field_hero = $vars['node']->get('field_hero')->getValue();

    // If a file has been uploaded, get it.
    if (!empty($field_hero)){
      $hero_id = $field_hero[0]['target_id'];
      $file = File::load($hero_id);

    // Otherwise get the default if there is one.
    } else {
      $default_image = $vars['node']->getFields()['field_hero']->getFieldDefinition()->getSetting('default_image');
      $file = Drupal::service('entity.repository')->loadEntityByUuid('file', $default_image['uuid']);
    }

    // If a file has been found (there might not be a default), get its path.
    if ($file){
      $path = $file->getFileUri();
      $vars['hero'] = ImageStyle::load('hero_image')->buildUrl($path);
    }
  }

}

```

Finding the default file is a convoluted mess of steps that requires loading all of the fields... there has got to be a better way to do this. Is there?

# Answer
> 3 votes
You don't need to load all the fields, you can just load the image field:

```
$uuid = $vars['node']->get('field_hero')->getFieldDefinition()->getSetting('default_image')['uuid'];
$file = \Drupal::service('entity.manager')->loadEntityByUuid('file', $uuid);

```

On a different note, the first line of your code assumes that $vars\['node'\] exists, which it won't on non-node pages, so you should change it to:

```
if (isset($vars['node'], $vars['node']->field_hero))

```

---
Tags: 8, entities
---


# Question
Title: How do I add JS files inside libraries conditionally based on versions of IE7 and IE8?
In Drupal 8, how would you load a JS file inside a library to only load on IE8 but not lte IE7?

I have the following added which correctly loads only on IE8 and lower.

```
js:
    js/script.js: { browsers: { IE: 'lte IE 8', '!IE': false } }

```

But, how would I only load this on IE8? and also how would I load a different js file for IE7? Would this work for example:

```
js:
    js/script.js: { browsers: { IE: 'IE 7', '!IE': false } }

```

# Answer
> 5 votes
You have the right idea. You can do what you've done for IE7 with IE8 as well.

```
js:
  js/script7.js: { browsers: { IE: 'IE 7', '!IE': false } }
  js/script8.js: { browsers: { IE: 'IE 8', '!IE': false } }

```

---
Tags: 8, javascript
---


# Question
Title: Is it possible to attach my own datetime class for using it in fields?
For example, there is a situation, where I need to output date field in some another format. But this format is not supported by PHP.

For example, I want to output year value in Roman numerals format. Or, I want to calculate year not from the Christmas, but from "the Creation of the world", from foundation of Rome ans so on. Or "the week" in my calendar doesn't contain 7 days, but it contains another quantity of them.

In this case, if I'm not mistaken, I should create new class inheriting it from DateTime class and there redefine method format or do something else.

Can I afterwards notice Drupal to it use my own DateTime class instead default ? That is, for instance, I have created new DateTime field for some node type and I can set my date format for this field in the admin date settings page, in Views and so on.

Is it possible in Drupal 7 ? And is it possible in Drupal 8 ? If yes, how to do it ?

# Answer
In your case, you do not need to define a new field type, you just need to write a new field formatter.

In Drupal 8, field formatters are used for displaying fields when displaying the parent entity (eg, a node view page) and when used in a view (even with field output).

Field formatters are easy to write in Drupal 8. In you case you just create a new plugin, and you can likely just extend one of the existing ones. I suspect something like this would work for you

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

use Drupal\datetime\Plugin\Field\FieldFormatter\DateTimePlainFormatter;

/**
 * Plugin implementation of the 'Awesome' formatter for 'datetime' fields.
 *
 * @FieldFormatter(
 *   id = "mymodule_datetime_awesome",
 *   label = @Translation("Awesome"),
 *   field_types = {
 *     "datetime"
 *   }
 *)
 */
class AwesomeDateTimeFormatter extends DateTimePlainFormatter {

  /**
   * {@inheritdoc}
   */
  protected function formatDate($date) {
    // Do something awesome!
  }

}

```

Here, the DateTimePlainFormatter does all of the heavy lifting via inheritance and you just override the method that actually produces the date string to be whatever you need. You can then use this on Manage Field Display, and other places you can choose a field formatter.

In Drupal 7, you can also just create a field formatter, but the process is more involved. You would also need to create a views field output plugin, as Drupal 7 / Views 3 does not use field formatters with field output.
> 3 votes

# Answer
In Drupal 8 you can define any field as plugin. You can create your own custom field type i.e `roman_date_type` and if you want custom widget than `roman_field_widget` and than finally formatter `roman_field_formatter` where you can format your date. If you want existing field type like date\_time than prob. you only need custom formatter. To tell Drupal 8 about your custom plugin `(roman_field_formatter)` you need to put your custom class in `(YOUR_MODULE\Plugin\Field\FieldFormatter\YOUR_CUSTOME_CLASS)` as Drupal 8 uses PSR-4 standard. For reference you can see `datetime` module in core. I hope it will answer your question.
> 1 votes

---
Tags: 8, datetime
---


title: How to process html in twig file

text:
# Question
Title: How to process html in twig file
I've a plain text field, where I've added few text in wrapped in tag. I've tried to get the processed html text in the twig by using

```
   {{ content.field_front_page_description|field_value }}
    {% set text = content.field_front_page_description|field_value %}
      {% set build = {
      '#type':   'processed_text',
      '#text':    text|render,
      '#format': 'full_html',
      } %}
      {{ kint(build) }}
      {{ build }}

```

But it is returning an array with not processed text. How do I do that

# Answer
> 0 votes
**Edited Code** -

```
{% set build = {
      '#type':   'processed_text',
      '#text':    content.field_front_page_description.value,
      '#format': 'full_html',
} %}
      {{ kint(build) }}
      {{ build }}

```

**Or,**

```
{% set build = {
      '#type':   'processed_text',
      '#text':    node.field_front_page_description.value,
      '#format': 'full_html',
} %}
      {{ kint(build) }}
      {{ build }}

```

---
Tags: theming, 8
---


title: Automating exporting of a view

text:
# Question
Title: Automating exporting of a view
I'm running a system where has a view with export functionality in order to export results in xls format.

Is there anyway I can automate it so every week it auto generates a report and email it.

I'm guessing I can use rules to do it but dont know how.

Thanks

# Answer
If you are using the views\_data\_export module and you have command line access you can try the following:

```
cd [your_drupal_docroot]
drush views-data-export [view-name] [display-id] > [path-to-output-file]

```

You could then add this to cron as a one-liner, e.g. this would run every Monday at 5:59 AM:

```
59 5 * * 0 cd [absolute_path_to_drupal_docroot] && drush views-data-export [view-name] [display-id] > [path-to-output-file]

```
> 1 votes

---
Tags: 7, views, rules, importing-exporting
---


# Question
Title: Is there any integration of the Entity registration module with modal forms?
I'm using the Entity Registration module for events registration. I want to open the registration forms in the ctools modal.

I checked the Modal forms module. But on the module page, I can see that it can only work with `login/reset password/user regisration/webform/contact/comment forms`.

So there is any possibility to use these both modules? Or should I look for something else?

# Answer
Few alternative way may helps you.

Entity popup module.

> This module allows you to show an entity in a popup. For flexibility, it doesn't provide any popup plugins itself, but it provides a menu callback that allows you to load the entity into any popup you desire.

NG Lightbox module:

> Lightbox any Drupal page such as the login page or comment reply.
> Works with forms out of the box, including webforms, node edit forms and more.
> Lightweight, only 1.2kbs in D7. D8 uses cores modal.
> Default responsive theme for the lightbox that can be customised.
> 0 votes

---
Tags: 7, chaos-tool-suite
---


# Question
Title: How to embed all comments and comment form to other website
I have two sites.one is Drupal site (example1.com). It has a lot of comments. I want to embed all these comments and comment form to other site (example2.com)\[non-Drupal site\].

Is it possible?

# Answer
> 1 votes
I think the best solution is to expose the comments as a REST resource on example1.com. You can achieve this with the services module (you will probably have to create a custom resource).

Then on example2.com execute a GET request on the REST resource and display the comments.

Edit: If you want to fetch the comments per node you will have to add a query param to the resource containing the node ID for which you want to fetch the comments.

---
Tags: 7, nodes, forms, ajax, comments
---


# Question
Title: How to fetch form state value of a form on clicking custom button?
How to fetch form state value of a form on clicking custom **mobile verification**(required field in register form) button ajax based suppose I want to show mobile number(Form\_state value) of form on clicking ajax based button named **mobile verification**. Here's the code:

```
 if($form_id == 'user_register_form')
 {

        $form['mybutton'] = array(
        '#type' => 'button',
        '#name' => 'mybutton',
        '#value' => 'Mobile Verification',
        '#title' => t('Mobile Verification'),
        //'#submit' => array('my_ajax_callback'),
        '#prefix' => '<div id="dialog" title="Dialog Title" style="display:none;"><span class="close">X</span><div ><form action="#">
                        Enter OTP<br>
                        <input type="text" class="otp" name="otp" value="">
                        <br>
                        <input type="submit" class="otp_submit" value="Submit">
                        </form> </div></div>',
        '#weight' => 19,
        '#ajax' => array(
                'event' => 'click',
                'callback' => 'my_ajax_callback',
                'method' => 'replace',
                'wrapper' => 'form-wrapper',
          ),
        );

}

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

     echo '<pre>';
     print_r($form_state);
     die;
   // return $form;
 }

```

**In short i just want without saving form data can we show form\_state value on clicking ajax based button in popup form.**

The above code not working for me not able to get form\_state value

# Answer
In that case, you can create a container in the form, and fill it with the values after AJAX has been fired. Then you only need to return that container in your ajax callback.

```
if($form_id == 'user_register_form')
{
  $form['mybutton'] = array(
    // ...
    '#ajax' => array(
      'callback' => 'my_ajax_callback',
      'wrapper' => 'form_state_values_wrapper',
    ),
  );

  $form['form_state_values'] = array(
    '#prefix' => '<div id="form_state_values_wrapper">',
    '#suffix' => '</div>',
    '#markup' => '',
  );

  if(isset($form_state_, $form_state['values']))
  {
    $form['form_state_values']['#markup'] = '<pre>' . print_r($form_state['values'], TRUE) . '</pre>',
  }

}

function my_ajax_callback(&$form, &$form_state,$form_id) {
  return $form['form_state_values'];
}

```
> 1 votes

---
Tags: 7
---


# Question
Title: How to add active class to link which is loaded via views and links comes from content type
1. I have created a content type calls as "XYZ Inner Pages".
2. Here I am adding a Fieldset and inside field set I am adding field type as Link.
3. Now I create a page using XYZ "Inner Pages" Content Type, add content and the links.
4. I am hiding the Links from Manage display because I want to show those on the right side of page.
5. Now I am creating a view which will pull all the links from "XYZ Inner Pages" Content Type.
6. Now I am showing the views block in the right section of "XYZ Inner Pages" Content Type page.
7. This right block will list the link.
8. Now I want to add active class to links so when I open any of the link from that list, then opened link from the list should be highlighted.

# Answer
Example:

In my content type I added a link field called "link", so the machine name is `field_link`

In this link field for url I put http://example.com/node/3

I created a View called "Test".

In fields I added link.

In fields I added link again, but this time I change the formatter to `URL, as plain text`

We are going to use template\_preprocess\_views\_view\_fields

In your theme's **template.php** file you add

```
function mytheme_preprocess_views_view_fields($vars){

  if ($vars['view']->name == "test"){

    $field_link = strip_tags($vars['fields']['field_link_1']->content); // use strip_tags function to remove HTML markup.
    $field_link = str_replace('http://', '', $field_link); // remove http://
    $field_link = str_replace('www.', '', $field_link); // remove www.

    $node_url = $_SERVER['SERVER_NAME'] . '/' . request_path(); // see https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/request_path/7.x

    if ($field_link == $node_url){

      $vars['fields']['field_link']->content = '<div class="active-link">' . $vars['fields']['field_link']->content . '</div>';

    }

    $vars['fields']['field_link_1']->content = null; // hides the field_link_1 field

  }

}

```
* replace **mytheme** with the actual name of your theme.
* replace **test** with the actual name of your view.
* replace **field\_link** with the actual name of your field.

Then you add the CSS to your theme's style.css file, Example:

```
.active-link a { color: green; }

```
> 1 votes

---
Tags: 7, navigation
---


title: How to get the last record ID?

text:
# Question
Title: How to get the last record ID?
I'm inserting values using `user_save()`. I have used this, but it is returning the wrong values.

```
SELECT LAST_INSERT_ID() FROM <table name>

```

How can I get the ID of the last record `user_save()`inserted?

# Answer
First you acquire the user object by using its return value and then you read the uid, which is also the unique value that belongs to the database row:

```
$user = user_save($user_obj);
$id = $user->uid;

```
> 4 votes

---
Tags: 7
---


# Question
Title: What's are the variables can be used from content.field_name with multiple values
I have created a field using test list type and rendering using custom twig code as below:

```
 {% for key, item in content.field_scope if key|first != '#' %}
    <li class="item-list">{{ item }}</li>
 {% endfor %}

```

In "for" argument, I manage to get value of **key** and **item** from the field. What are the other value which can be used?

# Answer
> 3 votes
`{{ content.field_name }}` is a renderable array. You are meant to simply print out `{{ content.field_name }}`.

If you need to change what is actually in the output, then you should create a **field--field-name.html.twig** or another applicable twig template suggestion name that works for you. Within it, you would have:

```
{% for item in items %}
  <li class="item-list">{{ item.content }}</li>
{% endfor %}

```

That way, any time you render either `{{ content }}` containing this field or `{{ content.field_name }}` it will use that template and render it consistently.

Here is a real world example. I am working on a project where one of the fields is a select list of about 20 options. These option values correlate to icons in the theme, and they can use this field to attach an icon to a title field for presentation purpose.

Here is my twig file for **field--field-icon.html.twig**:

```
{% for item in items %}
  <svg class="icon"><use xlink:href="/themes/custom/mytheme/build/img/svg-sprite.svg#{{ item.content }}"></use></svg>
{% endfor %}

```

`item.content` is just my field value, you don't have to do anything special here. So if the editor selects 'Alert', which the select list value is 'alert', `item.content` will print `alert` and the proper icon will display from the svg spritesheet.

Here is a similar question I answered which may provide further insight on theming fields.

---
Tags: theming, 8
---


# Question
Title: Using filter strtolower in custom Twig Extension return no result
I created a module to extend Twig Extension for filter functions. However the usage of strtolower in custom module end up with no result. Below are the sampel code of my custom module.

```
  public static function removeSpaces($string) {
    $string = str_replace(' ', '-', $string);
    $string = strtolower($string);

    return $string;
  }

```

Filtering `{{ title|removeSpaces }}` in template end up with empty.

# Answer
You have to render the array and then use the custom twig filter:

```
{{ title|render|removeSpaces }}

```
> 1 votes

---
Tags: theming, 8
---


title: File migration finds 0 (zero) items

text:
# Question
Title: File migration finds 0 (zero) items
I'm trying to import all files from a D7 database via a custom migration. As thinks weren't working as expected I started off with a copy of the stanard d7\_file migration template:

```
    # Every migration that references a file by Drupal 7 fid should specify this
# migration as an optional dependency.
id: lbdp7_files
label: Files
migration_group: lbdp7
migration_tags:
  - Drupal 7
source:
  plugin: lbdp7_file
  constants:
    # source_base_path must be set by the tool configuring this migration. It
    # represents the fully qualified path relative to which uris in the files
    # table are specified, and must end with a /. See source_full_path
    # configuration in this migration's process pipeline as an example.
    source_base_path: ''
process:
  # If you are using this file to build a custom migration consider removing
  # the fid field to allow incremental migrations.
  fid: fid
  filename: filename
  source_full_path:
    -
      plugin: concat
      delimiter: /
      source:
        - constants/source_base_path
        - filepath
    -
      plugin: urlencode
  uri:
    plugin: file_copy
    source:
      - '@source_full_path'
      - uri
  filemime: filemime
  # filesize is dynamically computed when file entities are saved, so there is
  # no point in migrating it.
  # filesize: filesize
  status: status
  # Drupal 7 didn't keep track of the file's creation or update time -- all it
  # had was the vague "timestamp" column. So we'll use it for both.
  created: timestamp
  changed: timestamp
  uid: uid
destination:
  plugin: entity:file

```

The source plguin lbdp7\_file is also just the standard version:

```
<?php

namespace Drupal\lb_dp7_migration\Plugin\migrate\source;

use Drupal\Core\Database\Query\Condition;
use Drupal\migrate\Row;
use Drupal\migrate_drupal\Plugin\migrate\source\DrupalSqlBase;

/**
 * Drupal 7 file source from database.
 *
 * @MigrateSource(
 *   id = "lbdp7_file"
 * )
 */
class File extends DrupalSqlBase {

  /**
   * The public file directory path.
   *
   * @var string
   */
  protected $publicPath;

  /**
   * The private file directory path, if any.
   *
   * @var string
   */
  protected $privatePath;

  /**
   * The temporary file directory path.
   *
   * @var string
   */
  protected $temporaryPath;

  /**
   * {@inheritdoc}
   */
  public function query() {
    $query = $this->select('file_managed', 'f')
      ->fields('f')
      ;

    // Filter by scheme(s), if configured.
    if (isset($this->configuration['scheme'])) {
      $schemes = array();
      // Accept either a single scheme, or a list.
      foreach ((array) $this->configuration['scheme'] as $scheme) {
        $schemes[] = rtrim($scheme) . '://';
      }
      $schemes = array_map([$this->getDatabase(), 'escapeLike'], $schemes);

      // uri LIKE 'public://%' OR uri LIKE 'private://%'
      $conditions = new Condition('OR');
      foreach ($schemes as $scheme) {
        $conditions->condition('uri', $scheme . '%', 'LIKE');
      }
      $query->condition($conditions);
    }
    //echo $query->__toString();
    return $query;
  }

  /**
   * {@inheritdoc}
   */
  protected function initializeIterator() {
    $this->publicPath = $this->variableGet('file_public_path', 'sites/default/files');
    $this->privatePath = $this->variableGet('file_private_path', NULL);
    $this->temporaryPath = $this->variableGet('file_temporary_path', '/tmp');
    return parent::initializeIterator();
  }

  /**
   * {@inheritdoc}
   */
  public function prepareRow(Row $row) {
    // Compute the filepath property, which is a physical representation of
    // the URI relative to the Drupal root.
    $path = str_replace(['public:/', 'private:/', 'temporary:/'], [$this->publicPath, $this->privatePath, $this->temporaryPath], $row->getSourceProperty('uri'));
    // At this point, $path could be an absolute path or a relative path,
    // depending on how the scheme's variable was set. So we need to shear out
    // the source_base_path in order to make them all relative.
    $path = str_replace($this->configuration['constants']['source_base_path'], NULL, $path);
    $row->setSourceProperty('filepath', $path);
    return parent::prepareRow($row);
  }

  /**
   * {@inheritdoc}
   */
  public function fields() {
    return array(
      'fid' => $this->t('File ID'),
      'uid' => $this->t('The {users}.uid who added the file. If set to 0, this file was added by an anonymous user.'),
      'filename' => $this->t('File name'),
      'filepath' => $this->t('File path'),
      'filemime' => $this->t('File MIME Type'),
      'status' => $this->t('The published status of a file.'),
      'timestamp' => $this->t('The time that the file was added.'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getIds() {
    $ids['fid']['type'] = 'integer';
    return $ids;
  }

}

```

If I evaluate the query in the source plugin query() function via `echo $query->__toString();` I see that the query is `SELECT f.* from file_managed f;` just as expected.

The problem is that `drush ms` says that there are 0 items to import. Can't be a database config problem as I have other migrations which work perfectly using the same db connection from settings.php. The table `file_managed` is populated with over 7000 items...

Any ideas what the problem could be?

Many thanks in advance!

# Answer
Ok, turns out it was a simple mistake I made. I forgot about setting the right database conenction in the migration.yml. So setting the attributes `key` and `target` for the source plugin resolved the issue.
> 0 votes

# Answer
Have you checked the migrate messages and message map for the migration? I'm guess you might see that all the migrations have failed. Does the D8 site have access to the files? And is source\_base\_path set (see the comment in the migration template)?
> 0 votes

---
Tags: 8, files, migrations
---


title: Remove default "Home" link?

text:
# Question
Title: Remove default "Home" link?
In Drupal 8, there is a 'Home' link in the "Main Navigation" menu provided by core. However, you can only disable this link, you cannot delete it.

How can I remove it? I don't need it and would rather just delete the menu link but the admin is prohibiting it. I had an issue where a content editor tried to set the menu link of a node to 'Home (Disabled)' by mistake - which caused a WSOD I have not yet diagnosed (somewhere when rendering the menu and/or breadcrumb on the page). Changing the menu link to `<Main Navigation>` root fixed this behavior, but I don't want it to happen again, so, I would like to delete it.

# Answer
I opened a drupal.org bug report on 20 december 2016 for this exact same request. The patch passes all tests and is now in the "Needs review" stage. Feel free to test the patch and mark the issue as RTBC.
> 9 votes

---
Tags: 8, navigation
---