# Question
Title: Hook that act on a field being inserted or updated?
I've Created a VBO view to "Modify entity values" .It's working fine. I need to perform an action when particular entity field gets inserted/updated.

So far I've tried `hook_field_update`,`hook_field_storage_write`, `hook_field_insert`, `hook_field_presave`. None of them are working

Any suggestions?

# Answer
> 1 votes
Why not use a hook\_entity\_update()? This hook gets triggered as soon as an entity gets updated. Inside the hook you should include some logic with respect to your field.

---
Tags: 7, hooks, views
---


# Question
Title: How do I use paging in a content type containing a paragraph?
I created a content type with just one **multivalue** field which turns to be an "entity type revisions" (i.e. Paragraphs).

I would like to have paging working on this setup (when number of Paragraphs exceeds some quantity) but just creating a view with paging does not work as the "pageable" content is the content type itself, not its fields.

Having Paragraphs as a standalone content type is a no-go as I do not want to have them scattered in the content section.

How can I achieve this?

# Answer
Build a view for paragraphs and place it in the content type with an EVA display (Entity Views Attachment).

To do this add a EVA display, connect it to the node entity (content) and bundle (content type) in the Entity Content Settings, select as Arguments the ID of the entity the view is attached to and add a contextual filter for the parent id.

Now the view appears as field in the content type and you can use the pager from the view for the paragraphs inside of the field.
> 3 votes

---
Tags: 8, paging, paragraphs
---


# Question
Title: Can I print an image from a separate content type in my page--front.tpl.php?
This is a question in reference to Drupal 7, using the Zurb Foundation base theme framework. I've created a specific content type that only has an image field in it for purposes of making the image itself content manageable by the user so they can add/remove as they'd like.

I thought that I could access that image with the following code in my page--front.tpl.php file per my Googling of the subject, however, I'm getting no output at all.

```
<?php print render(field_view_field('node', $node, 'field_my_image_field', array('label'=>'hidden')));
  ?>

```

I've also attempted several different variations of this to no avail.

How can I access and `print` out the contents of that field from that content type into my custom page template?

# Answer
> 0 votes
Here is what was ultimately the solution in our case in the event that anyone else runs in to this same problem again in the future.

Ultimately, the solution was to load the image from the node directly. Many thanks to my man Mike for helping get to the bottom of this.

```
<?php
      $type = "homepage_hero_background"; // content type machine name
      $nodes = node_load_multiple(array(), array('type' => $type));
      foreach ($nodes as $bg) {
        $uri = $bg->field_chp_background_image['und'][0]["uri"]; // field machine name
        $main_image = file_create_url( $uri );
      }
      ?>

```

# Answer
> 0 votes
You can embed a view inside your front page template, insert this code in propper region. You'll need an image view

```
// Get the embeded view and render it.
drupal_render(views_embed_view('VIEW_NAME', 'DISPLAY_ID'));

```

replace VIEW-NAME and DISPLAY\_ID with your data, you can find those values in last column on your image view

# Answer
> 0 votes
if you want to display any custom field from specific content type , you can refer below code : please change your content type name in $type variable in below code here my content type name is "portfolio" , you will get all fields value from that particular content type.

```
$type = "portfolio";
//$test = array();
$nodes = node_load_multiple(array(), array('type' => $type));
foreach($nodes as $products){
 print_r($products);
}

```

Hope it helps.

---
Tags: theming, entities, media
---


# Question
Title: How to view multiple taxonomy terms content on same page?
In Drupal 6, it was possible to view links like:

`taxonomy/term/1,2`,

`taxonomy/term/1+2`,

`taxonomy/term/2/2` or `taxonomy/term/2/all` which would list multiple taxonomy terms on single page (showing term and its children).

**Issue:** I know, this is not default possible in Drupal 7, and here also. This applies to in Drupal 8 too.

**What I want?** I'm `using Drupal 8`. I'd like to be able to link multiple taxonomy terms by a single link (e.g. in menu; i.e. to get multiple taxonomy terms to single node). I don't like to create special view to each combination. I need (I have rich taxonomy, so that I'd like to avoid dozens of views).

# Answer
I did this successfully myself by:

* choosing "Structure\>content types",
* clicking 'manage fields' on the content type with the taxonomy term link,
* selecting 'edit' on the taxonomy field.

Now you can change the settings by selecting the field settings tab. Simply change ' Allowed number of values ' to the desired number.

Hope this works for you. Ruud
> 0 votes

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


title: Checkbox title as link

text:
# Question
Title: Checkbox title as link
I want to make the checkbox title as link with target \_blank but this doesn't seem working.

```
$form['approve'] = array(
  '#type' => 'checkbox',
  '#title' => l(t('Approve conditions'), 'node/10'),
  '#required' => TRUE,
);

```

So the approve conditions should be a link

# Answer
That code doesn't work on Drupal 8 because `l()` has been removed from Drupal 8. The correct code for Drupal 8 is closer to the following one.

```
use Drupal\Core\Link;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Url;

$form['approve'] = array(
  '#type' => 'checkbox',
  '#title' => Link::fromTextAndUrl(new TranslatableMarkup('Approve conditions'), Url::fromUri('entity:node/10', ['attributes' => ['target' => '_blank']]))->toString(),
  '#required' => TRUE,
);

```

Alternatively, you can put the link in the description.

```
use Drupal\Core\Link;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Url;

$form['approve'] = array(
  '#type' => 'checkbox',
  '#title' => new TranslatableMarkup('Approve conditions'),
  '#description' => new TranslatableMarkup('By clicking this checkbox, you <a href=":conditions">approve the conditions</a>', [':conditions' => Url::fromUri('entity:node/10', ['attributes' => ['target' => '_blank']])]),
  '#required' => TRUE,
);

```

Keep in mind that, as said in the comments for l() and url() are removed in favor of a routing based URL generation API, if the shown code is used in a class using the `StringTranslationTrait` trait, instead of the `TranslatableMarkup` class you use `$this->t()`.
> 2 votes

---
Tags: forms
---


# Question
Title: How do I show a translated the value of a content type in my template
I have a bootstrap banner (jumbotron) on my site, which roughly looks like this:

```
<!-- themes\foo\templates\page.html.twig -->
{% if page.banner %}
   <div class="jumbotron" role="banner">
     <div class="row">
      <div class="col-md-10 col-md-offset-1">
        <h1> Welcome to foo.com </h1>
      </div>
    </div>

     <div class="row">
      <div class="col-md-10 col-md-offset-1">
         <h2> we provide </h2>
      </div>
    </div>
   </div>
{% endif %}

```

Now, instead of hard-coding the texts for h1 and h2 ... I went to `Administration > structure > content type` and created content type called `short texts` and then to `Administration > Structure > Content types` and added a content called `site slogan` and `site description` they both contain the values of h1 and h2.

Now, my question is how do I replace the text inside the H tags with a (translatable) text I created as a content?

This is my first week in Drupal, so I am a bit lost

# Answer
> 2 votes
You need to render either:

* Fields
* Variables created in a preprocess hook in mytheme.theme

Example, if you crated a field called Short Text (field\_short\_text), then in the node template for that type, you do:

`{{ content.field_short_text }}`

Except from the page template level (`page.html.twig`) you won't have access to the node render array.

If you create your own variables in a preprocess hook, you will need to call the translation service against that - it is better to let Drupal work normally for simple cases like these.

What you can do in this situation is create a View that has a node id argument, and either:

* Output Views fields (meh)
* Output that node in a designated view mode (best method)

Generate a Block display from that View, then place the block in the Banner region of your theme from Block Layout in the admin. If you are not familiar with Views, you should get familiar with it *right now*.

However, if you are trying to print the site slogan and site description, these are set under `Admin > Config > Site Information`, and should be available already as variables to the page template. I don't think there is a need to recreate what already exists, unless core doesn't translate site name, site slogan, site description but I am pretty sure it does.

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


# Question
Title: Show accounts with the taxonomy term used from a node
A default user can create a project (a content type with custom fields) with skills he is searching for his project (taxonomy).
There are users (with the *Crew* role) who have the asked skills (taxonomy again).

I want to create a view that displays users (crew) who have one or many of the skills asked for the project.

Is it possible?

# Answer
> 0 votes
Normally we do not do tutorials here, but I like EVA a lot, so here you go. :)

It can be achieved quite easy if you have some skills with views and EVA: Entity Views Attachment.

I assume you already set up the fields on the content type and user, and they are referring to the same taxonomy.

Now create a new view that lists 'user', do not add a page or block. In the top bar (below 'Displays' and next to master) add an 'EVA' display instead. In the middle column you limit this to content of you type. Leave the 'id' setting and optionally show the title:

Now to the right pane. Add a relationship from the user to your taxonomy. It will be called something like *Taxonomy term referenced from field\_skill*. Then add a second relationship *Content using field\_skills*. Finally, add a contextual filter for *Content: ID* and configure it like this:

To customize the display, add some user fields you want to display, or output rendered entities instead. You can control the display order of the EVA field on the *Manage display tab* of your content type.

How does this work?

It actually works in the reverse way we have configured it. EVA provides our view with the content ID we are looking at. This is provided as the first argument for the contextual filter.

By linking all users to nodes via the taxonomy and bv finally limiting that to only the node we are looking at via the contextual filter, we end up with all users that have one or more of the skills on the displayed node.

Good luck!

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


# Question
Title: Entity reference in a content type for a taxonomy. Limit it to a single value
I have a content type. Lets' call it `Events`. For said content type I have a field(`event_type`) set as an entity reference to a taxonomy named `Event Type`.

I've set the limit on the field(`event_type`) to a single value.

However, visually, I can add more than one value as a comma separated list of values.

As far as I can tell the last taxonomy term is kept as the value.

**This raises the problem that at some point in time somebody may very well add more than one thinking that all of them will be kept.**

---

Is there a way I can visually limit the values entered? Perhaps a dropdown or radio buttons or something?

If anybody can point me in the right direction I'd be grateful.

---

Also, I've searched in the Drupal 8 know bug list, but quite frankly the list is huge and I can't find it.

# Answer
> 2 votes
You should change the widget to a "Select list" instead of "Autocomplete (Tags style)".

You can find this on the "Manage form display" tab of the content type.

---
Tags: 8
---


# Question
Title: How to initiate node_save() on module install?
If I wanted to create a node programmatically when a module is installed what hook should I use to initiate `node_save()`? I found guides on how to make the node I just can't seem to figure out how to initiate it.

# Answer
If it's your own module, use `hook_install()`:

> Perform setup tasks when the module is installed.

or `hook_enable()`:

> Perform necessary actions after module is enabled.

If it's not your own module, use `hook_modules_enabled()`:

> Perform necessary actions after modules are enabled.
>
> This function differs from hook\_enable() in that it gives all other modules a chance to perform actions when modules are enabled, whereas hook\_enable() is only called on the module actually being enabled. See module\_enable() for a detailed description of the order in which install and enable hooks are invoked.
> 2 votes

---
Tags: 7, nodes, hooks
---


# Question
Title: Programmatically adding line items to Ubercart order
Can someone please suggest how do we add line items to an Ubercart order in Drupal 8? When I look at the references in Ubercart module, I get this:

```
// Load line items... has to be last after everything has been loaded.
$order->line_items = $order->getLineItems();

```

I am already setting product details to the order. However when I set line items by above line of code, system doesn't allow me to proceed ahead and doesn't even show any error.

Thanks in advance for any help or suggestions.

# Answer
The issue was I was assigning the value in order total manually from the product details, instead of using ubercart's $order-\>getTotal() , which defines line item initially. Hence, this worked for me to get the order generated after setting product and other payment details in order:

```
$order->total               = $order->getTotal();
$order->line_items          = $order->getLineItems();
$order->save();

```
> 0 votes

---
Tags: 8, forms, ubercart
---


# Question
Title: Where is the php_error.log file in Acquia Dev Desktop?
I'm having problem with a site installed with Acquia Dev Desktop, but I can't find the php\_error.log file to see the errors. There is nothing inside the DevDesktop folder and I can't see anything in the Software Preference.

Where is the php\_error.log file in Acquia Dev Desktop?

# Answer
Just checked in my installation of DevDesktop and found that my PHP logs are located in `/Applications/DevDesktop/apache/logs/error_log`.

Although it says Apache logs, PHP errors get logged there as well.

You can find the log locations via 'Preferences' =\> 'Logs'. DevDesktop version 2 (Apr 13, 2017).
> 6 votes

# Answer
I found the solution, you need to search the php.ini file inside the php version folder that you are using. Open the file and search for this line:

```
;error_log = php_errors.log

```

Delete the `;` to activate the error logging, then you will have:

```
error_log = php_errors.log

```

Save the file and restart your server and the file will be created in your site root folder.
> 3 votes

---
Tags: acquia-dev-desktop
---


# Question
Title: Entities and Plugins. What's the relationship?
As a fairly experienced Drupal 7 developer, I'm thrilled by all the new goodies in Drupal 8, but haven't quite figured out the relationship between entities and the new plugin system.

I've followed a number of tutorials on both topics, but haven't come across how they would fit together? Do they fit together?

I'd be very grateful for an explanation of how these two features coexist and inter-operate within the Drupal 8 ecosystem.

Thanks!

Edit:

# My specific use case

To clarify my question: I'm building a module that provides a method for the site owner to display alerts to their visitors. I've created a new custom Content Entity (cleverly called 'Alert') using Drupal Console and custom code.

I've also followed along with several tutorials that describe how to create a custom plugin type and found this idea exciting, but the gap in my understanding is this: when (or if) there would be a use case for combining a custom Content Entity with a custom plugin type. Does anyone have an example?

Thanks!

# Answer
I am not sure that I quite get your question but in Drupal 8 things like nodes, files and users are entities. They all inherit from ContentEntityBase. Plugins are a way to implement/extend Drupal functionality such as Views filters and Field widgets.

**From the docs:**

Entity API

> **Drupal 7** \- entities were generic stdClass objects.
>
> **Drupal 8** \- entities are now specifically typed objects, with each entity type defining a class that will be used for instances of the given entity.
>
> Entity types in core comes in two variants.
>
> **Configuration Entity**
>
> Used by the Configuration System. Supports translations and can provide custom defaults for installations.
>
> **Content Entity**
>
> Consist of configurable and base fields, can have revisions and support translations.

Plugin API

> Plugins are small pieces of functionality that are swappable. Plugins that perform similar functionality are of the same plugin type.
>
> Drupal contains many different plugins, of different types. For example, 'Field widget' is a plugin type, and each different field widget type is a plugin. The admin user may select from the list of field widget plugins to set the widget that a field uses.

**After author edit:**

Your specific use case would call for a event subscriber approach in my opninion. More specifically an event subscribed to the KernelEvents::REQUEST event. You can check at every page request if there are open `Alert` entities for the user and display them accordingly.

Your question as to if there are use cases for combined entities and plugins I wouldn't know. I only ever created Views and Block plugins and never combined entities and plugins. Perhaps you could create a Block plugin and show your `Alert` entities in there?
> 4 votes

---
Tags: 8, entities, plugins
---


title: hook_flag_flag() is not working

text:
# Question
Title: hook_flag_flag() is not working
I am working in one of the project using the Flag module. I want to add custom event when user flag any content. I am trying to use `hook_flag_flag()` but it is not working. This is the code I am using in a module file.

```
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\Entity\NodeType;
use Drupal\flag\Plugin\Flag\EntityFlagType;
use Drupal\flag\FlagInterface;
use Drupal\flag\Event\FlagEvents;
use Drupal\flag\Event\FlaggingEvent;
use Drupal\Core\Session\AccountInterface;

function nppe_custom_flag_flag( $flag, $entity_id, $account, $flagging) {
  drupal_set_message("This is custom message after Flag.");
}

```

Is there anything I am missing?

# Answer
> 2 votes
To add some custom event on flag/unflag actions in Drupal 8 you need to use Event subscriber:

```
public static function getSubscribedEvents() {
    $events = [];
    $events[FlagEvents::ENTITY_FLAGGED][] = ['onFlag'];
    $events[FlagEvents::ENTITY_UNFLAGGED][] = ['onUnflag'];
    return $events;
}

```

And then in onFlag() and onUnflag() methods you can implement your custom logic.

I just wrote a blog post with some code examples: http://dev.studiopresent.com/blog/back-end/perform-actions-flag-unflag-drupal-8

---
Tags: hooks, flags
---


# Question
Title: Use webprofiler to see entire query from view
I am using Drupal 8. I have webprofiler enabled and am trying to see the entire query from a view since the query that shows on the view is not the complete view, its missing some fields. How do I use webprofiler to get this entire query?

# Answer
> 0 votes
Check the saved profiles by the Webprofiler module via `/admin/reports/profiler/list`.

Go to the profile with the the same URL as your view and open it. Select the `Database` option on the left and search (CTRL+F) for the following string: `D\v\ViewExecutable::execute`.

You will find queries executed by the ViewExecutable class which is responsible for the data generation and query execution of your view.

---
Tags: 8, debugging
---


# Question
Title: Checkboxes in a simple form are not displayed
I have a simple form in a custom module that works well and is displaying my select as it should.

```
$form = \Drupal::formBuilder()->getForm('Drupal\efq\Form\FilterForm');
$form["container"] =  array(
    'categories' => array(
        '#title' => t('Select a Category'),
        '#type' => 'select',
        '#options' =>  array(
            1 => t('Option 1'),
            2 => t('Option 2'),
            3 => t('Option 3'),
        )
    )
);

```

I would like to change Select for Checkboxes. According to this, "Checkboxes" structure is the same as per "Select". But when I change `'#type' => 'select'` for `'#type' => 'checkboxes'` there are no checkboxes created and I got the 2 following warnings:

```
Notice: Undefined index: #title_display in Drupal\Core\Render\Element\Checkboxes::preRenderCompositeFormElement() (line 20 of core/lib/Drupal/Core/Render/Element/CompositeFormElementTrait.php).
Notice: Undefined index: #id in Drupal\Core\Render\Element\Checkboxes::preRenderCompositeFormElement() (line 30 of core/lib/Drupal/Core/Render/Element/CompositeFormElementTrait.php).

```

Adding these in an array makes the notice messages disappear but the checkboxes are still not showing.

Any idea of what's going on ?

# Answer
You code works for me. I used the exact following code and got checkboxes in my form using Drupal 8.3.4:

```
$form['container'] = [
  'categories' => [
    '#title' => t('Select a Category'),
    '#type' => 'checkboxes',
    '#options' => [
      1 => t('Option 1'),
      2 => t('Option 2'),
      3 => t('Option 3'),
    ],
  ],
];

return $form;

```
> 0 votes

---
Tags: 8, forms
---


# Question
Title: How do I give each menu link its own <li> tag?
I have the following bootstrap navbar: JsFilddle

```
<nav class="navbar navbar-inverse" role="nagivation"> <!-- todo: add (.navbar-static-top) to make it static -->
  <div class="container">
    <!-- btn for when the browser is shrinked to mobile size -->
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div> <!-- /navbar-header -->

    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <div class="navbar navbar-inverse site-top-nav">
        <ul class="nav navbar-nav">
          <li> <a href="http://dev.upcounting/html-theme/about.html"><i class="glyphicon glyphicon-tasks"></i> About Us</a></li>
          <li> <a href="#"> <i class="glyphicon glyphicon-cog"></i> Our Services</a></li>
          <li> <a href="#"><i class="glyphicon glyphicon-ok"></i> Pricing </a></li>
          <li> <a href="#"><i class="glyphicon glyphicon-comment"></i> Contact Us</a></li>
        </ul>
        <ul class="nav navbar-nav navbar-right">
          <li><a href="#"><i class="glyphicon glyphicon-shopping-cart"></i> My Orders</a></li>
          <li><a href="#"><i class="glyphicon glyphicon-user"></i> Login </a></li>
            <div class="btn-group" style="margin:0 10px;">
              <button class="btn btn-default btn-xs dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
                FR <span class="caret"></span>
              </button>
              <ul class="dropdown-menu">
                <li><a href="#">EN</a></li>
                <li><a href="#">DE</a></li>
              </ul>
            </div><!-- /btn-group -->
        </ul>
      </div><!-- /navbar navbar-inverse site-top-nav -->
    </div><!-- /collapse navbar-collapse -->
  </div>
</nav>

```

Currently each menu has it's own `<li></li>` and I can target each menu and add fontawesome icons to each links like this:

```
<li> <a href="#"><i class="glyphicon glyphicon-comment"></i> Contact Us</a></li>

```

But now working with Drupal 8, I can only do something like this:

```
{% if page.menu %}
<nav class="navbar navbar-inverse" role="nagivation">
  <div class="container">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>

    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <div class="navbar navbar-inverse site-top-nav">
         <div class="nav navbar-nav">
          {{ page.menu }}
          </div>
      </div>
    </div>
  </div>
</nav>
{% endif %}

```

Which displays all the links, but since `{{ page.menu }}` does not allow me to add style to each menu, the navbar doesn't look like show in the fiddle, and when the page shrink the menus don't become responsive (since it has no li I assume)

So, how can I fix this issue?

If I have 5 menus, is there a way I can echo each of the like

```
...
<li> {{ menu.about_us }} </li>
<li> {{ menu.our_services }} </li>
...

```

Or can I somehow target the html outputted by `{{ page.menu }}` and apply styles to them?

# Answer
You are on the right track with "target the html outputted by `{{ page.menu }}`" but that is likely a region with a menu block in it, you need to target a little deeper inside.

With theming overrides, you have generally have 2 options: writing a preprocess function in your theme's .theme file and/or writing a twig template file for your theme (usually in your theme's template folder).

For preprocess hooks you want to start by looking at this. https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21theme.api.php/function/hook\_preprocess\_HOOK/8.2.x

Going this route, you will probably need to implement `hook_preprocess_menu(&$variables)` & maybe `hook_preprocess_link(&$variables)`. Do some searches on those, there are plenty of examples.

Going the twig template route, you should take a look at https://www.drupal.org/docs/8/theming/twig/working-with-twig-templates

There are also examples out there, but this is one I have found particularly useful: https://medium.com/integral-vision/drupal-8-twig-add-custom-css-classes-to-menus-based-on-menu-name-35b50142521a
> 1 votes

---
Tags: theming, 8, navigation
---


# Question
Title: Revisions are listed, but none of them has content
I observed that the *Revisions* tab lists an entry for every saved revision, but my Twig template doesn't show anything for them.

>

Is this an issue with the Twig files using `{{ node.body.value|raw }}`, a configuration issue, or something else?

If it is a configuration issue, how do I enable revisions for the node.body and other fields in my content types?

\**UPDATE 2017-06-29 \**

The site's base theme is Bootstrap and we have a child theme developed by a third party.

Bootstrap's templates/system/page.html.twig prints body content using `{{ page.content }}`.

When I use `{{ page.content }}` in child theme page.html.twig I get fields other than Body expressed.

With debugging turned on here are the extraneous elements. I need to sort out how to safely express just the body content in a way which the Revision previewer will also display them.

```
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'links__node' -->
<!-- FILE NAME SUGGESTIONS:
   * links--node.html.twig
   x links.html.twig
-->
<!-- BEGIN OUTPUT from 'themes/bootstrap/templates/system/links.html.twig' -->

<!-- END OUTPUT from 'themes/bootstrap/templates/system/links.html.twig' -->

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'field' -->
<!-- FILE NAME SUGGESTIONS:
   * field--node--field-banner-image--page.html.twig
   * field--node--field-banner-image.html.twig
   * field--node--page.html.twig
   * field--field-banner-image.html.twig
   * field--image.html.twig
   x field.html.twig
-->
<!-- BEGIN OUTPUT from 'themes/bootstrap/templates/field/field.html.twig' -->

  <div data-quickedit-field-id="node/42/field_banner_image/en/full" class="field field--name-field-banner-image field--type-image field--label-visually_hidden">
    <div class="field--label sr-only">Banner Image</div>
              <div class="field--item">

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'image_formatter' -->
<!-- BEGIN OUTPUT from 'core/modules/image/templates/image-formatter.html.twig' -->

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'image' -->
<!-- BEGIN OUTPUT from 'themes/bootstrap/templates/system/image.html.twig' -->
<img src="/sites/default/files/2017-05/about-banner_1.jpg" width="1920" height="581" alt="" typeof="foaf:Image" class="img-responsive" />

<!-- END OUTPUT from 'themes/bootstrap/templates/system/image.html.twig' -->

<!-- END OUTPUT from 'core/modules/image/templates/image-formatter.html.twig' -->

</div>
          </div>

<!-- END OUTPUT from 'themes/bootstrap/templates/field/field.html.twig' -->

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'field' -->
<!-- FILE NAME SUGGESTIONS:
   * field--node--field-banner-scroll-image--page.html.twig
   * field--node--field-banner-scroll-image.html.twig
   * field--node--page.html.twig
   * field--field-banner-scroll-image.html.twig
   * field--image.html.twig
   x field.html.twig
-->
<!-- BEGIN OUTPUT from 'themes/bootstrap/templates/field/field.html.twig' -->

  <div data-quickedit-field-id="node/42/field_banner_scroll_image/en/full" class="field field--name-field-banner-scroll-image field--type-image field--label-visually_hidden">
    <div class="field--label sr-only">Banner Scroll Image</div>
              <div class="field--item">

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'image_formatter' -->
<!-- BEGIN OUTPUT from 'core/modules/image/templates/image-formatter.html.twig' -->

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'image' -->
<!-- BEGIN OUTPUT from 'themes/bootstrap/templates/system/image.html.twig' -->
<img src="/sites/default/files/default_images/page-scroll.png" width="63" height="63" alt="page scroll image" typeof="foaf:Image" class="img-responsive" />

<!-- END OUTPUT from 'themes/bootstrap/templates/system/image.html.twig' -->

<!-- END OUTPUT from 'core/modules/image/templates/image-formatter.html.twig' -->

</div>
          </div>

<!-- END OUTPUT from 'themes/bootstrap/templates/field/field.html.twig' -->

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'field' -->
<!-- FILE NAME SUGGESTIONS:
   * field--node--field-banner-quote--page.html.twig
   * field--node--field-banner-quote.html.twig
   * field--node--page.html.twig
   * field--field-banner-quote.html.twig
   * field--text-with-summary.html.twig
   x field.html.twig
-->
<!-- BEGIN OUTPUT from 'themes/bootstrap/templates/field/field.html.twig' -->

  <div data-quickedit-field-id="node/42/field_banner_quote/en/full" class="field field--name-field-banner-quote field--type-text-with-summary field--label-visually_hidden">
    <div class="field--label sr-only">Banner Quote</div>
              <div class="field--item"><h2>ABOUT Freeport-McMoRan</h2>
</div>
          </div>

<!-- END OUTPUT from 'themes/bootstrap/templates/field/field.html.twig' -->

```

# Answer
Yes, the issue is probably with your twig files. If your twig template gets the node from the current route, then `{{ node.body.value }}` won't work, because the route `entity.node.revision` doesn't provide a node entity and even if you would load the node with the nid from the route parameter `node` you only get the current revision. You would have to use the route parameter `node_revision` and the storage method `loadRevision()` to get the revision you want.

You can easily resolve this by rendering the node in the node template and print the body with `{{ content.body }}`. This also removes the security problem with the `|raw` filter, which you never should use on a body field.
> 2 votes

---
Tags: 8, nodes
---


# Question
Title: Add Field to Custom Content Type Programatically
I'm trying to create a module that creates its own content types during installation. I understand that I need to use the Configuration API and the Entity API, but I'm having trouble adding Drupal-included fields to my custom type. From what I understand, I need to have a file for each field called `field.field.node.content_type.field_type.yml`. Am I correct in my understanding? If so, why are their two fields and where can I find the options to place in that configuration file? I have tried scouring through the API and I can't seem to find what I need.

This is the tutorial I'm following: https://www.drupal.org/docs/8/api/entity-api/creating-a-custom-content-type-in-drupal-8

# Answer
Using the *Configuration Manager* module that comes with Drupal core to "automatically" as described in Managing your site's configuration is probably a better way to achieve what you want.

Create the new content types and their fields through the user interface.

On *Configuration » Development » Configuration synchronization » Export » Single item*, you just need to select your various pieces of content, one by one. For example, if you select *Content type* from the *Configuration type* menu and then a content type, you'll see the configuration you would need in the .yml file in the *config/install* directory for your module. Just eliminate that first *uuid* line. If you scroll down past the configuration text area, you'll see the name of the file name you need. For the *Article* content type, that would be *node.type.article.yml*.

You'll also need the field and field storage configuration types. Pay attention to the configuration dependencies and be sure you get all the pieces of configuration you need.

Once you get everything you need into configuration files, you can delete everything you created through the UI, reinstall your module, and verify everything works as expected. Otherwise, you can make changes through the user interface and export the configuration again. You could just edit the files directly, once you understand how everything is organized, especially if you're just making small changes.
> 5 votes

---
Tags: 8, nodes, configuration
---


title: Migrate rows of files for nodes

text:
# Question
Title: Migrate rows of files for nodes
I've got a CSV where every row contains details about a node and then a URL to a file.

Each of the nodes rows has an id number associated representing each specific node.

So eg:

```
id, node name, file url
1, farfitnugen, /documents/foo.pdf
1, farfitnugen, /documents/bar.pdf
2, farfitnugen, /documents/2foo.pdf
2, farfitnugen, /documents/2bar.pdf

```

Using the example above, I've got the migration working such that it creates one record for each node, and downloads and links the appropriate file, but it does not cycle all the entries.

I'm currently mapping by the id, can anyone provide a suggestion of how to get Migrate to import all the documents per node?

# Answer
> 0 votes
I coded two imports; one for the files and one for the nodes. The nodes import then references the files using the oncomplete callback that the migration api provides. Thank you to the Drupal irc channel for pointing out the oncomplete function.

Special thanks to stack exchange for the most depressing achievement ever, the tumbleweed.

---
Tags: 7, nodes, migrations, files
---


# Question
Title: How to show Search API search box? No block available, nothing from <?php print render($search_box); ?>
I'm updating a site to use Search API (with Search API DB) instead of the built-in search module. I've set up my Search API server and search, indexed everything, and now am just trying to replace the old search box with the new one in the theme.

But I can't find any way to do this.

Before disabling the built in search module, there was only one search block. After disabling, there are none, including after clearing caches. According to Integrate core search block with search\_api and Solr and various other sources, I should get a search block automatically, but I don't.

Before, I got the search box into my template .tpl file with `<?php print render($search_box); ?>`. After, this throws an error.

I can't find anything on what to use instead, and the relevant documentation page about search forms talks only about search results pages, not about how to put a search box on other pages. I'm confused at how hard it is to find how to do something so basic. I can't find anything about how to find the code to either populate this variable in template.php or access any inbuilt template variable.

How do I show a basic search block on the front page that integrates with search api? is similar but the asker reports its answer doesn't work, and I'm not fussy about whether it's specifically a block or specifically on the front page or connected to a view, I just want the search input element.

How do I add a Search API search box to a theme? How do I make it generate the block or load the search box from code?

# Answer
Maybe not the best option, but to get a usable Search Block from the Views module (that includes the Search API Views submodule), you need to activate the "Expose Form \>\> Exposed form in block" option in your Views advanced configuration. This is what it looks like:

Good luck!
> 4 votes

# Answer
In Views Under the Filter Criteria click the 'Add' button. Choose 'Search: Fulltext search'. Check the checkbox 'Expose this filter to visitors, to allow them to change it'. Place the block.

When people submit a search via this Block it will only take them to the View page that is was created on. If that Page is Disabled in your View it will not work. It will give you a page not found.

If you are using a Content Pane in a Panel instead of a Page you need to go into the 'Allow Settings' and check the checkbox 'Path override'. That will allow you to change the path to the path you are using in your Panel page.
> 2 votes

# Answer
Stefanos and heart-cooks are correct, I just wanted to mention that you don't need to try to make a block using the typical views tab as in "add a new block".. ie, don't use this:

Clicking on the "expose form in block" is enough to create the block.
> 1 votes

---
Tags: theming, search
---


# Question
Title: How to export a Field's Allowed Value List in a feature?
I've made a drop-down list type Field and have exported it as part of a Feature. However, whilst every other facet of the Field (Name, Help text, etc) is successfully exported the actual Allowed Values is not.

Does anyone know how I would include this in my Feature?

# Answer
> 0 votes
Turns out this is a bug(?) in Drupal 7.

The Dropdown list field's values are not saved in Features on a per-instance basis.

This can be fixed by using hook\_field\_widget\_form\_alter in the Feature's .module file, eg:

```
/**
 * Implements hook_field_widget_form_alter().
 */
function my_colors_field_widget_form_alter(&$element, &$form_state, $context) {

  if ($form_state['build_info']['form_id'] == 'my_colors_node_form' &&
    $context['field']['field_name'] == 'field_dropdown_text_single' &&
    $element['#entity_type'] == 'node') {
    $form_field_wrapper = entity_metadata_wrapper('node', $element['#entity']);
    $default_field = $form_field_wrapper->field_dropdown_text_single->value();
    $element['#default_value'] = !empty($default_field) ? $default_field : '';
    $element['#options'] = [
    'Red' => 'Red',
    'Blue' => 'Blue',
    'Green' => 'Green',
    ];
  }

}

```

...drupal is so great...

---
Tags: 7, entities, features
---


title: Render View in twig template

text:
# Question
Title: Render View in twig template
I'm pretty new to Drupal, and very new to Drupal 8. I've created a view, and have set up it up with a display block. I'm trying to render this on a specific page. So, I created a page template and a preprocess hook, created the following function.

```
function MYTHEMENAME_preprocess_node__13(&$variables) {
 $block = \Drupal\block\Entity\Block::load('views_block__downloads_block_2');
 $block_content = \Drupal::entityManager()->getViewBuilder('block')->view($block);
 $variables['downloads'] = $block_content;
}

```

When I place `{{ downloads }}` in my page template (`page--node--13.html.twig`) nothing happens.

Any ideas what I might be doing incorrectly?

# Answer
When you configure the visibility of the block in UI you can use a standard region and the standard page template.

If you want to do this with a specific page template similar to the question, add a region `download` to the theme, place the view block in this region and render the region in the page template specific to the node `page--node--13.html.twig`:

```
{{ page.download }}

```
> 1 votes

---
Tags: views, theming, hooks
---


# Question
Title: Get rendered content of one block created as derivative block
I have created derivative blocks using a method such as this and want to get the contents of a specific derivative block.

I can see all the available blocks (even derivative blocks) that have been assigned to a region with

```
 $ids = \Drupal::entityQuery('block')->execute();

```

but can't see unassigned blocks

I have a feeling that I need to use the code from berdir's answer b)

```
$variables['block_output'] = \Drupal::service('plugin.manager.block')
   ->createInstance($plugin, $configuration)
   ->build();

```

but don't know what to use for `$plugin` or `$configuration`

any help example will be appreciated

# Answer
It sems this will do the trick:

```
  $blockManager = \Drupal::service('plugin.manager.block');
  //see all available block plugins (even not instantiated)
  $contextRepository = \Drupal::service('context.repository');
  $definitions = $blockManager->getDefinitionsForContexts($contextRepository->getAvailableContexts());

```

Here is how I used this info:

```
function TEMPLATE_preprocess_node(&$vars) {
  $blockManager = \Drupal::service('plugin.manager.block');
  $vars['content']['derivative_block'] = $blockManager->createInstance('module_name:block_derivative_id')->build();
}

```

If you enable the commented lines `$definitions` will get you all available blocks

Credit goes out to enzo for this solution.

More info about programmatic block placement.
> 2 votes

---
Tags: 8, blocks, plugins
---


# Question
Title: Call javascript right after the form elements are rendered
I have a content-type "Document". I have a multiple select dropdown box in my form.

```
$form['priorities']['selectoffid'] = array(
    '#type' => 'select',
    '#title' => 'Select Signatories',
    '#id' => 'select-chosen',
    '#attributes' => array('multiple' => 'multiple', 'style' => 'width:100%'),
);

```

Each option of the dropdown corresponds to a textfield. Selected option's corresponding text field are shown and unselected option's corresponding text field are hidden.

Now everytime I hit the Save button and some other required form elements are not filled, it reloads and display the form errors. After reloading some text fields that are supposed to be visible is now hidden.

The value of the multiple select dropdown still consist of 3 values, according to the `$form_state` variable , but some of it's corresponding text fields are not visible anymore. How will I make it visible again? I tried using `after_build` form.

```
$form['#after_build'][] = 'document_monitoring_form_after_build';

function document_monitoring_form_after_build($form, &$form_state){

    drupal_add_js(drupal_get_path('module','document_monitoring') . '/myscript.js');

    return $form;
}

```

In my myscript.js :

```
alert('Javascript is called');
document.getElmentById('priority-6').style.display = 'block';
document.getElmentById('priority-22').style.display = 'block';
document.getElmentById('priority-5').style.display = 'block';
alert('Javascript is called');

```

The javascript is called before the multiple select dropdown is rendered. How will I make the javascript be called right after the form elements is rendered?

# Answer
> 1 votes
You need to wait for the DOM to be ready (i.e. when then browser has finished comprehending the HTML).

Drupal's javascript API provides a natural place for your code, in the form of a behavior, e.g.

```
(function($) {
  Drupal.behaviors.mymoduleFoo = {
    attach: function(context, settings) {
      $('#priority-6').show();
      // ...
    }
  };
})(jQuery);

```

The `attach` method is invoked when the DOM is ready, and also at other points in the page execution when something might have changed (e.g. when an AJAX call is made), to give you the opportunity to respond to any new/change elements that might affect your code's functionality.

---
Tags: 7, nodes, javascript
---


title: Change "Remove" button text

text:
# Question
Title: Change "Remove" button text
I'm trying to change the text from Remove button in my file and image fields.
For the field collection items I used this code.

```
function MY_MODULE_field_widget_form_alter(&$element, &$form_state, $context)
{
  $element['actions']['remove_button']['#value'] = t('x');
}

```

It works fine. For file and image fields I tried this code.

```
function MY_MODULE_preprocess_file_widget_multiple(&$variables) {
  if( strcmp($variables['element']['#type'], 'details') == 0 ){
    $variables['element'][0]['remove_button']['#value'] = t('x');
  }
}

```

It doesn't work. With `MY_MODULE_field_widget_form_alter()` I can't get the *Remove* button.

# Answer
The solution for me was the custom add another module.

This is a very simple module that allows you to customise the text of the 'Add another item' button on multi-valued fields.

If your field supports 'unlimited' values then you are offered the option of customising the 'Add another item' button text. This setting is stored per 'bundle', so you can have different button text if you use the same field in two places.

UPDATE:

If you don't want to use unlimited upload you can just write your own module or add some piece of code in your custom module. (A big changed code from custom add another module)

In the hook\_widget\_form\_alter:

```
$field = $context['items']->getFieldDefinition();
  if ($field instanceof FieldConfigInterface) {

    if (isset($element['remove_button']['#value'])) {
      $element['remove_button']['#value'] = t('x');
    }
    if (!empty($element['#type']) && $element['#type'] == 'managed_file') {
      $element['#process'][] = 'custom_file_buttons_labels';
    }
  }

```

And

```
function custom_file_buttons_labels($element, FormStateInterface $form_state, $form) {

  if (isset($element['remove_button']['#value'])) {
    $element['remove_button']['#value'] = t('x');
  }
  return $element;
}

```
> 0 votes

---
Tags: entities
---


# Question
Title: Why is my theme function not called (not in template file)?
I have a simple theme and everything is by documentation/examples:

```
function activit_theme() {

  return array(

      'activit_package_teaser' => array(
          'arguments' => array('node' => NULL),
          'type' => 'module'
      ),

  );
}

```

+

```
function theme_activit_package_teaser($node) {

  $output = '
    <div class="package-teaser">
      package
    </div>
  ';

  return $output;
}

```

and

```
function activit_packages_block() {

  $nids = db_select('node', 'n')->fields('n', array('nid', 'status'));
  $nids->join('field_data_field_important', 'f', 'f.entity_id = n.nid');
  $nids->fields('f', array('field_important_value', 'entity_id'));
  $nids->condition('n.status', 1)->condition('f.field_important_value', 1);
  $nids = $nids->execute()->fetchCol();

  $nodes = node_load_multiple($nids);

  $packages = '';
  foreach($nodes as $node) {
    $packages .= theme('activit_package_teaser', array('node' => $node));
  }

  return '
    <div class="important-packages wrapper">
      <h2>'.t('Important packages').'</h2>

      <div class="cont">
        '.$packages.'
      </div>
    </div>
  ';

}

```

there are 4 nodes, but my theme is not called at all and nothing is inserted into `<div class="cont"></div>`. No error in "recent log messages". Why it does not work?

---

**UPDATE:** When the template is in activit\_package\_teaser.tpl file it works:

```
  'activit_package_teaser' => array(
      'arguments' => array('node' => NULL),
      'template' => 'activit_package_teaser',
      'path' => drupal_get_path('theme', 'activit') . '/templates/',
  ),

```

But why it does not work as a theme function?

# Answer
> 0 votes
`arguments` was for Drupal 6, you need to use `variables` for Drupal 7. One of `variables` or `render element` is required, hence nothing is showing up at the moment as the item isn't making it into the theme registry.

```
function activit_theme() {

  return array(

      'activit_package_teaser' => array(
          'variables' => array('node' => NULL),
          'type' => 'module'
      ),

  );
}

```

---
Tags: 7, theming
---


# Question
Title: hello_world_page_attachments is not called
I was following the documentation about creating a custom hello world module. I got to the point where you are told how to attach custom JavaScript and CSS files using hooks. I want to get a JavaScript file attached on every page. Unfortunately, I can't manage it to work. Everything was working, so far.

This is the code I am using.

### hello\_world.libraries.yml

```
hello_world:
  version: 1.x
  css:
    theme:
      css/style.css: {}
  js:
    js/hello_world.js: {}
  dependencies:
    - core/jquery

```

### hello\_world.module

```
function hello_world_page_attachments(array &$attachments) {
  $attachments['#attached']['library'][] = 'hello_world_for_drupal_8/hello_world';
}

```

### hello\_world.js

```
alert("outside script");
console.log("outside script");

```

# Answer
Libraries are refererred to as *module\_machine\_name/library\_name*

If the other names in your post are accurate, in your case that should be:

```
$attachments['#attached']['library'][] = 'hello_world/hello_world';

```
> 2 votes

---
Tags: 8
---


title: Each results from drupal_view

text:
# Question
Title: Each results from drupal_view
I need to create a select with the results of all elements of a particular content-type.

The results of all the elements of said content-type I get them like this:

```
{{drupal_view ('areas_practicas', 'areas_all')}}

```

But it generates preformatted results (with HTML in between) (or with the output of the development mode, with reference to the template that uses that sample)

* 1) Is it possible to return only one array of strings to be able to paint them in the select, without HTML or anything?
* 2) Is it possible to traverse the results of this block since twig? Something like

```
{% for area in drupal_view ('areas_practicas', 'areas_all') %}
    {{area.title}}
{% endfor%}

```

# Answer
I would do it like this: first get a set of all needed nodes with a query, and then process the node to create your select

For all published articles of content type 'areas\_practicas' for example:

```
$query = \Drupal::entityQuery('node')
        ->condition('status', 1)
        ->condition('type', 'areas_practicas');
$nids = $query->execute();
foreach ($nids as $node)
{
    $n = node_load ((int)$node);
    // get title of node and process it
}

```

I hope this helps, Ruud
> 0 votes

---
Tags: views, theming
---


# Question
Title: How can I export a group of settings in Drupal 8
Drupal 8 has this new configuration management tool at `/admin/config/development/configuration`. I have an experimental site running Drupal 8 beta14, and I want to import a few settings into my new beta15 site. I don't want to copy everything, I experimented with various things on the old site and only need a few things on the new one.

What I want to copy are content types, the fields in those content types as well as image styles. But looking at the export tool, it seems I can only export a single item at a time.

Is there a way to export all items of a specific group at once, e.g. all content types or all image styles? And for content types, is there a way to export all the fields as well together with the content type?

# Answer
> 3 votes
There are two different things you can do.

You can, as you found, export and import single objects.

Or, you can do a config sync. Which means everything and is usually used to import configuration changes from staging to production or similar.

So you can do a full config export, then all the files will be in your staging folder (not the same as a staging environment) and import them in a different site. Note that there are some limitations, for example, you always need to do a full import (so export the existing config of a site, update it with some changes, then import it again) and the sync only works if the UUID in system.site matches, as it is not supported to import from a separate installation. (But you can import a group of files that don't exist yet.. careful with the UUID's, as the same object with a different UUID is treated as a delete + create, not update).

So you need to pick the files you want to re-use and put them either into an existing export from the target site or put them in a config/install folder of a module, then it will be imported when that module is installed (and *only* then, there are no automated updates).

You can also look at the 8.x version of the Features project, which basically offers a UI to pick a number of configuration files, similar to what you might know from D7.

# Answer
> 2 votes
I don't think this is currently supported. The best candidate for that would be Drush, and its `config-export` command. But as you can see below, there's no indication that groups are supported.

```
$ drush config-export --help
Export config from the active directory.

Examples:
 drush config-export --skip-modules=devel  Export configuration; do not include the devel module in the exported configuration,
                                           regardless of whether or not it is enabled in the site.

Arguments:
 label                                     A config directory label (i.e. a key in $config_directories array in settings.php). Defaults
                                           to 'staging'

Options:
 --add                                     Run `git add -p` after exporting. This lets you choose which config changes to stage for
                                           commit.
 --branch=<branchname>                     Make commit on provided working branch. Ignored if used without --commit or --push.
 --commit                                  Run `git add -A` and `git commit` after exporting.  This commits everything that was exported
                                           without prompting.
 --destination                             An arbitrary directory that should receive the exported files. An alternative to label
                                           argument
 --message                                 Commit comment for the exported configuration.  Optional; may only be used with --commit or
                                           --push.
 --push                                    Run `git push` after committing.  Implies --commit.
 --remote=<origin>                         The remote git branch to use to push changes.  Defaults to "origin".
 --skip-modules                            A list of modules to ignore during export (e.g. to avoid listing dev-only modules in exported
                                           configuration).

Aliases: cex

```

My best bet at this point would be to file an issue against the Drush project so that you submit a feature request. I agree with you it'd make sense because currently it's pretty painful not to miss dependencies.

# Answer
> 1 votes
You can try Config partial export module which allows you to exports only the selected files from the list of modified config files. It is able to export to a tarball only modified configuration files. After export you can copy the files from the tarball to your config/install folder in order to add them to your install profile and apply those changes on next install.

The module adds *Partial config* tab to *Configuration management*. It also provides a new drush command (see: `drush cpex --help` for help).

# Answer
> 0 votes
You can use Features module for grouping configurations which is not stable yet for D8 or checkout Drupal Console

Take a look at this answer: https://drupal.stackexchange.com/a/190242/23477

# Answer
> 0 votes
I've written a Python script which exports **a group of configuration items** using `drush`. You can find the script on a related thread, here.

---
Tags: 8, configuration
---


title: How to use hook_node_view?

text:
# Question
Title: How to use hook_node_view?
I'm new to using hooks and I am tryng to use a hook\_node\_view to my custom module.

Here's my code:

```
function myportfolio_node_view($node, $view_mode, $langcode) {

$node->content['my_additional_field'][0] = array(
    '#markup' => 'Hello World',
    '#weight' => -1
);

}

```

$view\_mode and $langcode appear in gray.

I need to understand... what is this doing exactly? Am I adding a Hello World to all nodes in my site? Because, I need to add it to a node of type "my portfolio" but nothing happens.

What am I missing? Do I need to call this function somewhere in the site? How do I know it is working?

# Answer
It looks like the hook\_node\_view is not called when using panels, unless you include node\_content (add content \> node \> node content). Once done that, the "No extras" should be unchecked.

Found the solution here: https://www.drupal.org/node/1606912#comment-9009727
> 2 votes

---
Tags: nodes, hooks
---


# Question
Title: D6 - Create a files table entry for a file
I have to migrate some content and everything is fine except the images.

I'm getting the images using file\_get\_contents() and save the file in the drupal /files folder using the following code:

```
    $image = file_get_contents('http://www.someurl.com/xx/util/yy.jpg');
    $file = file_save_data($image, 'yy.jpg',FILE_EXISTS_REPLACE);
    print $file; // returns the path to the file ( /files/yy.jpg )

```

So the image is uploaded in the /files folder.

What I'm not able to understand is, how can I add the image to the files table so that I can be able later to use the file object?

I was looking through the files.inc functions for Drupal 6 but I wasn't able to find anything that could help. Should I insert the data manually using db\_query()?

Thanks.

# Answer
> 0 votes
It's just done manually, e.g.:

```
$file = new stdClass();
$file->filename = 'foo.bar';
$file->filepath = $file;
$file->filemime = file_get_mimetype($file->filename);
$file->uid = $user->uid;
$file->status = FILE_STATUS_TEMPORARY;
$file->timestamp = time();
drupal_write_record('files', $file);

```

See `file_save_upload()` for a much broader example, including validation.

---
Tags: 6
---


title: How to change Node's authored on date?

text:
# Question
Title: How to change Node's authored on date?
What is the proper way to address and modify a node's authored on date? I created a slew of new nodes via a CSV import via the Feeds module. These nodes now have the date of 2013-07-11 as the authored on date as that's when I did the import. But each node refers to a previous date and I need the authored on date to reflect that.

I have a content type I've created that has a separate Date field where I choose the date. I'd like to eliminate that and just use the authored on date instead.

I'm trying to use VBO to run a custom PHP snippet to make this change but the examples I've found so far do not work.

```
$object->created = $object->field_date[0]['value'];
node_save($object);

```

This snippet when run through VBO returns errors:

> Notice: Undefined variable: object in eval() (line 1 of /home/chriscor/public\_html /hi\_tracker/sites/all/modules/contrib/views\_bulk\_operations/actions/script.action.inc(20) : eval()'d code).
>
> Notice: Trying to get property of non-object in eval() (line 1 of /home/chriscor/public\_html/hi\_tracker/sites/all/modules/contrib/views\_bulk\_operations/actions/script.action.inc(20) : eval()'d code).
>
> EntityMalformedException: Missing bundle property on entity of type node. in entity\_extract\_ids() (line 7693 of /home/chriscor/public\_html/hi\_tracker/includes/common.inc).

Any idea what I'm missing?

# Answer
It looks like the $object variable doesn't exist, or isn't in scope. Check the arguments your function receives for the proper node object.
> 0 votes

# Answer
So, you have probably figure this out by now but in Drupal 7 I had to change $object to $entity and it work - kind of...it is printing today's date in there and not copying the date from the `field_post_date` into created. Anyway this change will get rid of the error.

This video helped me along with this link:

This code worked...

```
$entity -> created = strtotime($entity->field_post_date[LANGUAGE_NONE][0]['value']);
node_save($entity);

```
> 0 votes

---
Tags: datetime, importing-exporting
---


# Question
Title: Multiple language node import with Feeds
I am using Feeds to import a very huge CSV file with products to my Drupal Commerce site. My site must be in two languages and it appears that Feeds hasn't support for this. How can I import nodes in multiple languages with Feeds?

# Answer
There was a fantastic Solution not so long ago that addressed something similar.

I believe that the best thing to to would to be to split each node into two nodes (one in Language A, one in Language B) and import each one in a separate feeds import, and then use the SQL query in the above solution to link the translation. This way, each node can contain otherwise identical information about the same item, in its own language, and simply be displayed based upon which translation the user/viewer would prefer.

Let us know how you go with the SQL script and if you have any issues that you need help with!
> 3 votes

# Answer
I have not tried this but it looks like it should do what you need it to do - Feeds: Entity Translation.

> This module adds support for importing data through Feeds into translatable fields handled by Entity Translation.
>
> The module exposes fields that are translatable into all enabled languages, enabling the creation of translations of entities when importing.

It's still in dev, but give it a shot.
> 2 votes

# Answer
It is possible to achieve this without needing SQL queries. Feeds now had multilingual support for fields. Make sure you have a current version. Newer than a year ago, because of https://www.drupal.org/node/1183440

You can create two feeds, one for each language. In the processor you should set a common unique identifier as unique in both feeds. Also you can, for each field, set the language variant for that field and feed.

Make sure that the fields you want to translate have entity transltion enabled though!
> 0 votes

---
Tags: commerce, feeds, i18n-l10n
---


# Question
Title: Change Created Date to date from field_post_date
I am changing a large amount of news content types 'Created' dates. I figured out to use VBO with execute php and this code...

```
$entity -> created = strtotime($entity->field_post_date[LANGUAGE_NONE][0]['value']);
node_save($entity);

```

This code works!

# Answer
I had 'create' not 'created' - Doh! Now it works...
> 0 votes

---
Tags: 7, datetime, views
---


title: How to add html tag in a form element?

text:
# Question
Title: How to add html tag in a form element?
How to add html tag in a form element drupal 8?

```
$form['buttons']['submit'] = [
  '#type' => 'submit',
  '#value' => T('Send'),
  '#prefix' => '<div class="modal-footer">',
  '#suffix' => '<button type="button" class="btn btn-sm btn-default" data-dismiss="modal">' . $this->t('Close') . '</button></div>',
  '#attributes' => [
    'class' => ['btn-success'],
  ]
];

```

I try to add allowed\_tags:

```
$form['buttons']['submit'] = [
  '#type' => 'submit',
  '#value' => T('Send'),
  '#prefix' => '<div class="modal-footer">',
  '#suffix' => '<button type="button" class="btn btn-sm btn-default" data-dismiss="modal">' . $this->t('Close') . '</button></div>',
  '#allowed_tags' => ['button'],
  '#attributes' => [
    'class' => ['btn-success'],
  ]
];

```

OR

```
$form['buttons']['#allowed_tags'] = ['button'];
$form['#allowed_tags'] = ['button'];

```

Not working... Help me please!

# Answer
> 3 votes
I can't tell which element is giving you trouble.

For the div, instead of prefix/suffix you can create a container element:

```
$form['submit_container'] = array(
  '#type' => 'container',
  '#attributes' => array(
    'class' => ['modal-footer'],
  )
);

```

And then you can put a submit input inside of that:

```
$form['submit_container']['submit'] = array(
  '#type' => 'submit',
  '#value' => $this->t('Submit'),
  '#attributes' => array(
    'class' => ['btn', 'btn-sm', 'btn-default'],
    'data-dismiss' => 'modal',
  )
);

```

If you need a button type='button' just to fire Javascript and not submit the form, that is somewhat problematic, it seems. One method is to override the button template.

Type inline\_template may be the best bet:

```
$form['submit_container']['button'] = array(
  '#type' => 'inline_template',
  '#template' => '<button type="button" class="btn btn-sm btn-default" data-dismiss="modal" onclick="closeButton()">Close</button>',
);

```

Change a normal submit 'input' type to 'button' type with button tag

# Answer
> 3 votes
If you are looking to add a custom HTML tag use the new type in the form api `html_tag`, here's an example from the form API documentation :

```
$build['hello'] = [
  '#type' => 'html_tag',
  '#tag' => 'p',
  '#value' => $this->t('Hello World'),
];

```

---
Tags: forms
---


title: theme_hook_suggestions on custom theme?

text:
# Question
Title: theme_hook_suggestions on custom theme?
I have a module that implements `HOOK_theme()` to define a 'petition' theme like so:

```
function mymod_theme() {
  return [
    'petititon' => ['variables' => ['foo'=>NULL], 'template' => 'petition']
  ];
}

```

Which I then use like:

```
$some_render_array[] = [ '#theme' => 'petition', '#foo' => 'Bar' ];

```

Which is then rendered by a `petition.tpl.php` template file.

However, I would like to do this:

```
$some_render_array[] = [
  '#theme' => 'petition',
  '#theme_hook_suggestions' => ['petition__1'],
  '#foo' => 'Bar'
];

```

...and have it look for `petition--1.tpl.php`, in the same way you can for nodes, pages etc.

But this doesn't seem to work. Is it possible to have a theme that can take a template suggestion? I have a bunch of things to render which all require the same processing but use different templates.

# Answer
> 0 votes
To suggest specific templates you probably need to do it in your theme's template file, use the `hook_preprocess_HOOK` where the first `hook` is the name of your theme and seconde `HOOK` is either `page` to suggest a page template or `node` to suggest a node page.

Here's an example

```
/**
 * Implementation of hook_preprocess_HOOK().
 */
function mymodule_preprocess_page(&$variables){
  // change the condition to whatever you like
  if(isset($variables['node']) && arg(2) != 'edit')
    $variables['theme_hook_suggestions'][] = 'page__'. $variables['node']->type;
}

```

---
Tags: 7, theming
---


title: Why does hook_menu_link not work?

text:
# Question
Title: Why does hook_menu_link not work?
theme\_menu\_link allegedly "Returns HTML for a menu link and submenu."

In attempting to use this 'hook' I added code to my template.php as such:

```
function themename_menu_link(array $vars) {
  dpm($vars);
}

```

It didn't work. Nothing appears.

I confirmed that the template.php code is executing and cleared caches several times.

Every other hook\_ or theme\_ function I've tested runs without issue, however this one does not.

I've also tested the alternative method, themename\_menu\_link\__your\_menu\_name with no success. The code seems to be ignored.

# Answer
Try print\_r instead of dpm --

```
function theme_menu_link(array $variables) {
  return print_r($variables['element']);
}

```

or use hook\_menu\_link\_alter --

```
hook_menu_link_alter($variables){
  var_dump($variables);
}

```
> -1 votes

---
Tags: 7, theming
---


# Question
Title: Recreating Feature generates no text-format related code
* My D7/Panopoly site has 3 text formats: plain\_text, panopoly\_html\_text and panopoly\_wysiwyg\_text.
* I added Pathologic to the filter list for all text formats; I now need to to capture this to code.
* If I check Text Formats \> Plain Text and recreate, relevant code is written to mtms\_config.features.filter.inc.
* But when I select "filter panopoly\_html\_text" and "filter panopoly\_wysiwyg\_text" from Feature Overrides and recreate, no relevant code gets written!

You can see the Feature code at https://kopy.io/j9hrv .

Why is Features Override not writing config code for these text formats? I've been pulling my hair out for days. (And yes, there's been plenty of cache-clearing involved.) Thanks for your help.

# Answer
The reason was simple: that site was running an **old version of Features.** Updating Features made things work as expected.

I'm leaving this up as a reminder to other users. The simplest things can be the easiest to overlook.
> 0 votes

---
Tags: features
---


# Question
Title: Commerce 2.x confusion about multiple order types and order item types
I have two different order types and two different order item types. Let's say they're "Default" and "Custom". On the configuration page for the Default order item type, I've specified Default as the Order type. On the configuration page for the Custom order item type, I've specified Custom as the Order type. For both order types, I use the "Inline entity form - Complex" widget for the Order items. I've set the "Allow users to add new order items" option and left the "Allow users to add existing order items" option unselected.

I expect that when I create an order of type Default, I will only be allowed to add Default order items. And when I create an order of type Custom, I will only be allowed to add Custom order items.

However, what I get instead is the option to choose from a select list whether I want to add a Default or Custom order item, regardless of the order type. So it's possible to create orders that have a mix of Default and Custom type order items. I do not understand why this is so. It seems that the "Order type" value for order item types is being ignored.

Is there a way to set up commerce order/order item types so that an order item can only be added to an order if the order type is the one specified in the order item type configuration?

# Answer
> 0 votes
As BojanZ (the maintainer of the module) has stated in his comment above, you have located a bug :) Congrats! Post it to the Commerce issue queue here:

https://www.drupal.org/project/issues/commerce?categories=All

---
Tags: 8, commerce
---


# Question
Title: How do I utilize Drupal commerce to sell large files stored on Amazon S3
I am working on a project for work that involves replacing a current "tape and staple" file delivery system. It's a Drupal site, but with many many third party outdated VERY unstable software. However, it successfully sells very large files from S3.

My job is to use Drupal 7 with Drupal Commerce Module set, Commerce file Module 7.x-2.0, AmazonS3 7.x-2.0 Module. Also, the files that will be associated with one specific field live in various S3 Buckets.

I successfully got all of the above modules working as advertised. But my functionality is not complete.

What I need:

1. The ability to choose buckets within the field when creating a product.
2. link to an existing .zip file already stored on S3

**About Bucket Selection: I have files located in various buckets. These files relate to the same Content type and product type. (at the time the business started they didn't understand what buckets meant. so files are a bit disorganized) I need to have the file attachment field have the ability to select a file from S3, from various buckets. Example: Product A has a file in Bucket A. Product B has a file in Bucket B. Etc... So when creating a product, the file field (that will contain the file being sold) will need to have the ability to attach an S3 file located in various buckets**

Am I on the right path? Are the above modules the correct ones to have? Is there another one i need to make my connection complete or will I have to design one to get my final needs?

**Update:** I just found the Amazon S3 File System Module Is this something that would help me?

# Answer
> 0 votes
You really want to use the Drupal License and License Billing modules to sell access to Commerce Files.

It might take a little custom code (a few simple objects and a few hooks) to make sure your amazon S3 links are getting licensed correctly to the right user.

In terms of your two requests:

1. The ability to choose buckets within the field when creating a product.
2. link to an existing .zip file already stored on S3

Yeah, it looks like s3 file system module is the way to go for S3 API ... they even have a migrate module and a proxy module that could make a simple file on your website, load to an s3 of your choice and still be linked to your local.

If you installed the S3 module mentioned above, you could:

1. Use `hook_form_alter()` to modify the file field
2. Use `hook_form_alter()` to add pre-empt the normal submit handler
3. Use your new submit handler to save the file to your preferred bucket.

---
Tags: 7, commerce, files
---


title: Remove Drupal Login Link

text:
# Question
Title: Remove Drupal Login Link
I'm trying to remove the login link from the Drupal site.

However, despite the User login being set to none. It still shows on the site.

Is there a way to hide the link?

Thank you, Kevin Davis

# Answer
There is a login block that you need to disable. structure \> blocks disable the login block.
> 1 votes

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


# Question
Title: How to redirect to edit page on node create?
I am trying this code in my custom module but it does not redirect to the node edit page.

```
 function mymodule_entity_insert(EntityInterface $entity) {
   if ($entity instanceof \Drupal\node\NodeInterface){
        $id=$entity->id();
        return new RedirectResponse("/node/$id/edit");
      }
   }

```

# Answer
> 4 votes
When not in a Controller call the `send()` method on the `RedirectResponse` object.

```
$response = new RedirectResponse("/node/$id/edit");
$response->send();

```

# Answer
> 1 votes
I have a problem very similar and this is how I solved the situation:

```
 use Drupal\Core\Url;

 function mymodule_entity_insert(EntityInterface $entity) {
   if ($entity instanceof \Drupal\node\NodeInterface){
        $id = $entity->id();
        // You should use the route instead of path.
        $url = Url::fromRoute('entity.node.edit_form', ['node' => $id])->toString();
        // Redirecting to edit.
        $response = new RedirectResponse($url);
        $response->send();
      }
   }

```

---
Tags: 8, redirection
---


title: Update no results search text

text:
# Question
Title: Update no results search text
I want to change the default search help text '*Check if your spelling is correct. Remove quotes...'* that is displayed when there are no results.

What's the best method of practice for this? Should I override the value in a template.php function? If so how do I go about this?

# Answer
> 8 votes
The easiest thing for you to do would be to override the actual template file which displays that language.

Look at the template file called **search-results.tpl.php** in the core **search** module.

It has the following code at the bottom:

```
<?php else : ?>
  <h2><?php print t('Your search yielded no results');?></h2>
  <?php print search_help('search#noresults', drupal_help_arg()); ?>
<?php endif; ?>

```

Copy the entire template file (you don't even need to rename it, it'll override the file in the module) and paste it into your own theme's /templates folder. Re-write the section I've pasted at the top to be whatever you want. The part that prints the **search\_help()** is the bulleted list you're looking to change.

Of course, before the system will pick up your new template file, you need to clear all your caches!

Let us know if this works!

# Answer
> 0 votes
This works via hook\_page\_alter so can be placed in a custom module. It replaces the empty results with a single fake result. So the standard *no results* test does not get displayed, and you can set here what it actually shown instead.

```
/***
 * Implement hook_page alter.
 * Here we override what gets displayed on the search page when no results are found.
 **/
function MYMODULE_page_alter(&$page) {
  // Reference the search results (if present).
  $results = &$page['content']['system_main']['search_results']['#results'];
  // If we are on the search results page but there are no results...
  if (isset($results) && empty($results)) {
    // Replace empty results with a single fake result showing info.
    $results = array(
      array(
        'title' => '',
        'link' => '',
        // Display the translated standard message (or whatever you want).
        'snippet' => t('Your search yielded no results'),
      ),
    );
  }
}

```

# Answer
> 0 votes
I'm using ds\_search and neither of the answers here worked for me. What did work was to install the stringoverrides module, then visit /admin/config/regional/stringoverrides. I put the entire text of the no results t() string in the "Original" column, then the text I wanted in the replacement column.

Be sure to grab the full text of the original string found in Core's search.module file. It should be something like this:

```
<ul>
 <li>Check if your spelling is correct.</li>
 <li>Remove quotes around phrases to search for each word individually. <em>bike shed</em> will often show more results than <em>"bike shed"</em>.</li>
 <li>Consider loosening your query with <em>OR</em>. <em>bike OR shed</em> will often show more results than <em>bike shed</em>.</li>
</ul>

```

---
Tags: 7, search, theming
---


title: Preprocess function per content type

text:
# Question
Title: Preprocess function per content type
I have a couple of content types which I need to preprocess in different ways. So `template.php` in my theme `foo` currently looks like:

```
function foo_preprocess_node(&$variables) {
    if ('news' ==$variables['type']) _preprocess_news($variables);
    if ('event'==$variables['type']) _preprocess_event($variables);
    if ('alert'==$variables['type']) _preprocess_alert($variables);
    ...
}

function _preprocess_news(&$variables) {
    ...
}

function _preprocess_event(&$variables) {
    ...
}

function _preprocess_alert(&$variables) {
    ...
}

```

I'd like to be able to specify a Drupal specific preprocess function which would hook on the content type's machine name. I tried using `foo_preprocess_news` but it is never called.

Is there a better way?

# Answer
> 11 votes
The name of the preprocess function is based on the theme name, so for `theme_table()` your preprocess function is `MYTHEME_preprocess_table()`.

Since there is no `theme_node_node_type` function a preprocess hook such as `foo_preprocess_news` or `foo_preprocess_node_news` won't work out of the box.

You *could* go about overriding the theme registry so that it behaves differently for nodes, but I really wouldn't recommend it; it could get very messy.

I'm a huge fan of refactoring code but in your case I don't think it's necessary; if you have complex logic that needs to run in your preprocess hook dependent on node type then farming it out to different functions in the way you currently doing seems like good practice to me.

The other method, of course, would be to implement a custom module for each of the different content types and implement `hook_preprocess_node()` in each. That way, each module's preprocess function can be responsible for a different content type.

However this may be overkill for your situation; if you don't have extra logic (i.e. non theme preprocess logic) to perform on each content type, then this method probably doesn't add any extra value.

# Answer
> 32 votes
The zen subtheme accomplishes this by adding this to its theme\_preprocess\_node function:

```
function foo_preprocess_node(&$variables, $hook) {
  ...
    // Optionally, run node-type-specific preprocess functions, like
  // foo_preprocess_node_page() or foo_preprocess_node_story().
  $function = __FUNCTION__ . '_' . $variables['node']->type;
  if (function_exists($function)) {
    $function($variables, $hook);
  }
  ...
}

```

If you have a content type called 'news', then you would be able to create a function called foo\_preprocess\_node\_news in your template.php file.

# Answer
> 3 votes
I only just had a similar *issue* which is why google brought me to this page: my node preprocess function was growing so enormously big, that i would rather split the function into multiple files.

I've already done a similar approach in my template.php file which contains all the alter functions, and since the same method works perfectly well here, I thought I'd share my approach:

**file setup** inside the folder `MYTHEME/preprocess`:

```
- node.preprocess.inc
- node--blog-post.preprocess.inc
- node--device-variation.preprocess.inc
- (...)

```

you should already have `node.preprocess.inc`, the others you can create yourself. how you call them really is rather arbitrary, but better give them names that nicely identify them and fit the whole drupal naming system.
onwards to the content of these files!

> **`node.preprocess.inc`**, here I'm doing doing something like this:

```
<?php

function MYTHEME_preprocess_node(&$variables) {

    switch($variables['type']) {

      case 'blog_post':
        // if the type of the node is a Blog Post, include this:
        include 'node--blog-post.preprocess.inc';
        break;

      case 'device_variation':
        // if Device Variation, include this:
        include 'node--device-variation.preprocess.inc';
        break;

      case 'foo':
        // ...
        break;
    }

    // additional stuff for all nodes

}

```

we basically switch through the type of the current node. what you switch through is up to you; `#id`, `#view_mode`, all depending on your exact needs.
once there is a match, it will load the specified file and act upon its content just as if it was written right inside this function.

the content of these `included` files looks exactly like you'd put it in the `node.preprocess.inc` file, except we don't call the preprocess function again:

> **`node--device-variation.preprocess.inc`**

```
<?php

    // Device Name
    $device = drupal_clean_css_identifier(strtolower($variables['title']));

    // Determine whether only Device Version is of type 'N/A' and set ppvHasVariations accordingly
    $deviceHasVariations = true;
    if( $variables['content']['product:field_model_variation'][0]['#options']['entity']->weight == 0 ) {
        $deviceHasVariations = false;
    }
    //...

```

you can basically do this with as many files as you want and even cascade multiple switches, for example further splitting up specific node preprocess files depending on the `#view_mode`, having one file for the `full` view mode and another for the `teaser`

hope this helps, should someone ever stumble upon this question again (:

# Answer
> 1 votes
`call_user_func()` doesn't pass parameters by reference. So, in case of `$variables` your `preprocess_foo()` functions will work on copies of the original array only; changes on non-objects will not apply during the remaining render process.

# Answer
> 1 votes
In your main hook\_preprocess\_node Implement the following code at the end

```
$preprocess_function = 'themename_node__' . $node->type . '__preprocess';
if (function_exists($preprocess_function)) {
 $preprocess_function($variables);
}

```

So you would have now preprocess by node type

---
Tags: 7, theming
---


title: Adding a hook to a contrib module

text:
# Question
Title: Adding a hook to a contrib module
I am trying to hook into the Print module after to call a custom function *after* the pdf is generated. I've got this working by simply patching a call back on the wkhtmltopdf.pages.inc:

```
 if (!empty($pdf)) {
  _callback_for_pdf();
  return $pdf;
}

```

This is pretty nasty. So ideally I would like to try and extend this contrib module to have a hook for this functionality.

How do I go about *adding* a hook to something to then use in a custom module?

# Answer
> 0 votes
Check out this documentation: https://www.drupal.org/docs/7/creating-custom-modules/creating-drupal-7-hooks

For your case, the simplest may work

So lets say your hook you want to be hook\_pdf\_generated()

module\_invoke\_all('pdf\_generated');

in your custom module, have a function YOURMODULE\_pdf\_generated()

If you wanted to be able to alter the $pdf variable, use a \_alter() hook

So in that code you posted, add:

drupal\_alter('pdf\_generated', $pdf);

and in your custom module you'd have YOURMODULE\_pdf\_generated\_alter(&$pdf)

---
Tags: 7, hooks, files
---


# Question
Title: how to enable workflow submodules in Modules administration page
I am a very beginner to Drupal. In order to understand how Drupal-Workflow works, I try to install Workflow Module into my site. Following the installation guide on Drupal Documentation, i place the entire workflow directory into your Drupal modules directory, but when i go to the Modules administration page, and try to enable the following workflow submodules, i get into the trouble, like this, i couldn't check the submodules. So, who can give me a hand, appreciate enough！

# Answer
> 0 votes
This page has suggested you the reason. You didn't install Entity module, you can get this module on Entity cache module.

This module has no user interface, if you enable it, entities will start being cached, if you disable it, they'll stop.

---
Tags: workflows
---


# Question
Title: How to creating custom links that can be echo'ed individually
Let's assume I have a footer with this div for which I have created a custom block named as `custom_footer`:

```
{% if page.custom_footer %}
<div class='footer' style='background-image:url('/images/bg.jpg')">

</div>
{% endif %}

```

Now, I would like to put links inside the footer that are created using `Home > Administration > Structure > Menus > Add menu` in other words I don't want to insert hard-coded menus like `<a href='/services'>services</a>` inside the footer div.

So, is there anyway to echo all the custom links for page created inside my footer?

# Answer
This can be implemented using blocks.

* First create the required menus from `Home > Administration >
Structure > Menus > Add menu`
* Place the new menu as a block under footer section in `Home > Administration > Structure > Block layout`
* Save blocks

Find the reference images:

* Add user account menu to footer block (You can also include your custom menus),

* Image listng user account menu on footer
> 1 votes

---
Tags: 8, theming
---


# Question
Title: View filter to include title and body text
I created an exposed view filter so that users can search for words in the body of a node type but I would like the search to also look for words in the title without having a separate search box for titles. Can this easily be done?

See code for exported view.

# Answer
> 1 votes
This module will help to do you job **Views filters populate**

> This is an utility module. Its sole purpose is to fill in one blank that seems not easy to be done using normal views, which is to use one exposed string filter to search on multiple fields.
>
> Bear in mind, that, for now, only populates STRING exposed filters, so those filters that take an array (options) or special types won't work, although it may not be difficult to extend it.

You need to make use of `Global: Populate filters` or `Global: Combine fields filter` its explained in steps here

---
Tags: 7, views
---


# Question
Title: Loading a form from a form include file in a module
I have an external form that needs to be loaded inside a template file, used by a block. Right now, i'm a bit confused as to how to load this .inc. Looking at the API docs point to module\_load\_include() which I've tried with no luck (see example 1, from the template file):

```
module_load_include('inc', 'example2');
print(render(drupal_get_form("example2_form"))); //Form method in inc file is called "example2_form();

```

The actual form method is just a few settings for now, once I prove this works...

```
function example2_form($form, $form_state) {
  $form['fname'] = array(
    '#type' => 'textfield',
    "#attributes" => array(
      'placeholder' => t("First Name"),
    ),
  );

  $form['#validate'][] = "example2_form_validate";
  $form['#submit'][] = "example2_form_submit";

  return $form;
}

```

I figure the cleanest approach (besides figuring out what could cause the .inc to not load here) is to just drop the form code into the .module, and load the Form array in the blocks `hook_block_view().` However, I like to keep stuff clean, so if there's something I'm overlooking here, or how to best do this, it would be cool to know.

File name for the form include is *example2.form.inc*.

# Answer
> 0 votes
Module\_load\_include includes the file with extension and filename. Sinds your file is called example2.form.inc and you include the file example2.inc, it doesn't work.

You should be using

```
Module_load_include('inc', 'example2.form');

```

# Answer
> 0 votes
The syntax for module\_load\_include is

```
module_load_include('suffix', 'module', 'file_without_suffix');

```

Files can be loaded in module.info via the files\[\] array but this should be for classes or interface files. enter link description here

If you want to load a form into a template manually, then yes define the block and hook\_block\_view($delta) will need to load the form include file.

---
Tags: 7, forms
---


# Question
Title: Is there a way to restrict access to a particular node?
One of my teammates created a simple page that displays links to important contents. However, since it is simple content, the page itself is restricted but the link still shows up in the main menu.

I'm looking for a way to add a permission such as `custom_module.permission.yml` where the client will be able to define who can access this page.

Is there a way to do so without installing any external module?

# Answer
You can use this module **Permissions by Term**

> Frontend Features
>
> * Restricts users from accessing the nodes related to specific taxonomy terms by their roles and/or specific user accounts.
> * Restricts users from access to forbidden nodes in views.

Tag the node to the specific taxonomy term and restrict access to nodes tagged with that specific node.
> 1 votes

---
Tags: 8, nodes, routes, users
---


title: How to make wkhtmltopdf work on Drupal

text:
# Question
Title: How to make wkhtmltopdf work on Drupal
I have installed the drupal Print module, but have not been successful in getting wkhtmltopdf to work. The drupal print documentation is outdated and despite of a number of request to update it, it still is outdated. https://www.drupal.org/node/306882

CASE DESCRIPTION In my case, I want to allow the creation of pdf versions of nodes. The Nodes have inline CSS (using Tinymce editor with Wysiwyg). I tried using Dompdf library, but the inline css is not being used for the created pdf.

I have read that wkhtmltopdf creates an internal browser that renders a html page, so that should be the ideal solution in this case.

However, after downloading the rpm file from http://wkhtmltopdf.org/ into the sites/all/libraries folder of my website, and installing it using rpm -Uvh wkhtmltox-0.12.2.1\_linux-centos6-amd64.rpm in my website, the library is not recognized, not visible in the status report page and not in the pdf configuration page /admin/config/user-interface/print/pdf

# Answer
> 1 votes
In addition to Yuri's answer, I wanted to provide more detail for how I solved this issue, where I couldn't resolve the following error:

> No PDF generation tool found! Please download a supported PHP PDF generation tool

1. install the print module
2. install pdf php handlers and libraries for your environment from https://wkhtmltopdf.org/downloads.html; see note
3. create symlink in `sites/all/libraries/wkhtmltopdf` to library in server; make sure symlink is executable to the server `sudo chown -h [owner]`and `sudo chgrp -h [group]`
4. install and enable phpwkhtmltopdf
5. run `drush make --no-core -y sites/all/modules/contrib/phpwkhtmltopdf/phpwkhtmltopdf.make`
6. enable `print_pdf_wkhtmltopdf`
7. set up and customize; see recommendations in this blog for more info

Note: My local dev environment is on a Mac OS X so I had to download and run the package, then create a symlink to `sites/all/libraries/wkhtmltopdf`from `/usr/local/bin/wkhtmltopdf`

Sources:

---
Tags: 7, files, theming
---


title: Change display format of date in token

text:
# Question
Title: Change display format of date in token
I am using the token for the quiz close date (`[node:quiz:quiz-close]` in a certificate for the quiz module and would like to change the format. I looked at Date & Time in the configuration settings and have already defined a custom one that is just the date (called `just_the_date`).

How can I embed a token for a field that records a more detailed date, but just have it show in my custom format or change the display format for this field?

# Answer
Turns out I just needed to take the token, `[node:quiz:quiz-close]` and append it with the custom date format machine name `:just_the_date]` to get `[node:quiz:quiz-close:just_the_date]`. Also, it's in the list of tokens, once you expand the date item further.
> 0 votes

---
Tags: 7, datetime, tokens, quiz
---


# Question
Title: How to use lazy_builder to load and replace content asynchronously
In my tests, I was able to make content be loaded asynchronous with

```
function callback_function() {
    sleep(5);
    return ['#markup' => time()];
}

...

$build['timestamp'] = [
  '#lazy_builder' => ['callback_function', []],
  '#create_placeholder' => TRUE,
];

```

In the case above, drupal renders whatever it wants to render and after the 5 seconds from the sleep it prints the timestamp. So it runs asynchronous.

But when having placeholders attached, it will waits 5 seconds before rendering everything, its not asynchronous. Like the code below:

```
$build['#markup'] => 'The timestamp is [timestamp]';
$build['#attached']['placeholders']['[timestamp]'] = [
  '#lazy_builder' => ['callback_function', []],
  '#create_placeholder' => TRUE,
];

```

My ultimate goal is to have for example "The timestamp is 1498827840" and then get it replaced to "The timestamp is 1498827845" after the 5 seconds sleep.

# Answer
> 1 votes
Normally placeholders are used for elements that are not cacheable, like a timestamp, so that the rest of the render array no longer depends on the dynamic data and can be cached. On a cache hit the placeholder gets replaced by the result of the lazy builder. This is the asynchronous part.

What you are trying to do looks more like asynchronous loading of web content in the browser. You can use BipPipe for this, but then don't put a sleep command in the lazy builder, try to solve this in javascript.

---
Tags: theming, 8
---


title: Show block only on "Page Not Found"?

text:
# Question
Title: Show block only on "Page Not Found"?
Using a Block's visibility setting of *Show block on specific pages: Pages on which this PHP code returns TRUE (experts only)*...

...what PHP would I write that returns `TRUE` so that the block only shows on "Page Not Found" pages?

# Answer
> 2 votes
Can I recommend not doing it with PHP?

I would suggest making a page (via Admin-\>Content-\>Add Content), this assumes that you have the node module installed.

And then set that page as your "Default 404 (not found) page" in Admin-\>Configuration-\>System-\>Site Information

And then you can use that page's path in the block set up, but list under "Only the listed pages"

---
Tags: blocks
---