# Question
Title: How to add autocomplete field to custom form which will fetch data from taxanomy?
I have created a custom form using **FormBase**. In which there are 3 fields City, State & Country. I've created taxanomy for these 3 fields. Now i want to create autocomplete field which will fetch data from database from taxanomy and also add the the term to taxanomy if not exist in the table. Please help me with these. Below is the code :

`HotelForm.php` under `src/Form` directory

```
<?php

/**
 * @file
 * Contains \Drupal\hotel_form\Form\HotelForm
 */
namespace Drupal\hotel_form\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
class HotelForm extends FormBase {

    public function getFormId() {
        return 'hotel';
    }

    public function buildForm(array $form, FormStateInterface $form_state) {

        $form['hotel_title'] = array(
            '#type' => 'textfield',
            '#size' => 50,
            '#title' => t('Hotel Name'),
            '#required' => TRUE,
            '#placeholder' => t('Hotel Name'),
        );

        $form['hotel_city'] = array(
            '#type' => 'entity_autocomplete',
            '#target_type' => 'node',
            '#size' => 50,
            '#title' => 'City',
            '#required' => TRUE,
            '#placeholder' => t('City'),

        );

        $form['hotel_state'] = array(
            '#type' => 'textfield',
            '#size' => 50,
            '#title' => t('State'),
            '#required' => TRUE,
            '#placeholder' => t('State'),
        );

        $form['hotel_country'] = array(
            '#type' => 'textfield',
            '#size' => 50,
            '#title' => t('Country'),
            '#required' => TRUE,
            '#placeholder' => t('Country'),
        );

        $form['hotel_mobile'] = array(
            '#type' => 'number',
            '#title' => t('Mobile Number'),
            '#required' => TRUE,
            '#placeholder' => t('Mobile Number'),
        );

        $form['hotel_phone'] = array(
            '#type' => 'number',
            '#title' => t('Phone Number'),
            '#required' => TRUE,
            '#placeholder' => t('Phone Number'),
        );

        $form['submit'] = array(
            '#type' => 'submit',
            '#value' => t('Submit'),
            '#attributes' => array(
            'class' => array('btn btn-submit'),
                ),
        );
        return $form;

    }

    public function validateForm(array &$form, FormStateInterface $form_state) {

    }

    public function submitForm(array &$form, FormStateInterface $form_state) {

        $name = $form_state->getValue('hotel_title');
        $city = $form_state->getValue('hotel_city');
        $state = $form_state->getValue('hotel_state');
        $country = $form_state->getValue('hotel_country');
        $phone = $form_state->getValue('hotel_phone');
        $mobile = $form_state->getValue('hotel_mobile');

        echo $name;
        $uuid = \Drupal::service('uuid');

        // $uuid->isValid($uuid_to_validate);

        $query = db_insert('node')
         ->fields(array('type','uuid','langcode'))
         ->values(array(
            'type' => 'hotels',
            'uuid' => $uuid->generate(),
            'langcode' => 'en',
            ))
        ->execute();

        $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
        $uid= $user->get('uid')->value;

        $query1 = db_insert('node_revision')
        ->fields(array('nid','langcode','revision_timestamp','revision_uid'))
        ->values(array(
            'nid' => $query,
            'langcode' => 'en',
            'revision_timestamp' => REQUEST_TIME,
            'revision_uid' => $uid,
            ))
        ->execute();

        $query2 = db_update('node')
        ->fields(array(
            'vid' => $query1,
            ))
            ->condition('nid',$query)
            ->execute();

        $query3 = db_insert('node_field_data')
        ->fields(array(
            'nid' => $query,
            'vid' => $query1,
            'type' => 'hotels',
            'langcode' => 'en',
            'title' => $name,
            'uid' => $uid,
            'status' => 0,
            'created' => REQUEST_TIME,
            'changed' => REQUEST_TIME,
            'promote' => 0,
            'sticky' => 0,
            'revision_translation_affected' => 1,
            'default_langcode' => 1,
            ))
        ->execute();

        $query4 = db_insert('node_field_revision')
        ->fields(array(
            'nid' => $query,
            'vid' => $query1,
            'langcode' => 'en',
            'title' => $name,
            'uid' => $uid,
            'status' => 0,
            'created' => REQUEST_TIME,
            'changed' => REQUEST_TIME,
            'promote' => 0,
            'sticky' => 0,
            'revision_translation_affected' => 1,
            'default_langcode' => 1,
            ))
        ->execute();

        $query5 = db_insert('node__field_city')
        ->fields(array(
            'bundle' => 'hotels',
            'deleted' => 0,
            'entity_id' => $query,
            'revision_id' => $query1,
            'langcode' => 'en',
            'delta' => 0,
            'field_city_value' => $city,
            ))
        ->execute();

        $query6 = db_insert('node_revision__field_city')
        ->fields(array(
            'bundle' => 'hotels',
            'deleted' => 0,
            'entity_id' => $query,
            'revision_id' => $query1,
            'langcode' => 'en',
            'delta' => 0,
            'field_city_value' => $city,
            ))
        ->execute();

        $query7 = db_insert('node__field_state')
        ->fields(array(
            'bundle' => 'hotels',
            'deleted' => 0,
            'entity_id' => $query,
            'revision_id' => $query1,
            'langcode' => 'en',
            'delta' => 0,
            'field_state_value' => $state,
            ))
        ->execute();

        $query8 = db_insert('node_revision__field_state')
        ->fields(array(
            'bundle' => 'hotels',
            'deleted' => 0,
            'entity_id' => $query,
            'revision_id' => $query1,
            'langcode' => 'en',
            'delta' => 0,
            'field_state_value' => $state,
            ))
        ->execute();

        $query9 = db_insert('node__field_country')
        ->fields(array(
            'bundle' => 'hotels',
            'deleted' => 0,
            'entity_id' => $query,
            'revision_id' => $query1,
            'langcode' => 'en',
            'delta' => 0,
            'field_country_value' => $country,
            ))
        ->execute();

        $query10 = db_insert('node_revision__field_country')
        ->fields(array(
            'bundle' => 'hotels',
            'deleted' => 0,
            'entity_id' => $query,
            'revision_id' => $query1,
            'langcode' => 'en',
            'delta' => 0,
            'field_country_value' => $country,
            ))
        ->execute();

        drupal_set_message(t('Thank you'));
    }
}

```

This is my routing file:

```
hotel_form.hotel_form:
  path: '/add-hotel'
  defaults:
    _title: 'Hotel Form'
    _form: 'Drupal\hotel_form\Form\HotelForm'
  requirements:
    _permission: 'access content'

```

# Answer
> 1 votes
In order to know how to use the form element 'entity\_autocomplete', either have a look at the form api: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21Element%21EntityAutocomplete.php/class/EntityAutocomplete/8.2.x Or search in core for `'#type' => 'entity_autocomplete'`. For example, the CommentForm uses this form element for users this way:

```
 $form['author']['uid'] = [
  '#type' => 'entity_autocomplete',
  '#target_type' => 'user',
  '#default_value' => $owner->isAnonymous() ? NULL : $owner,
  // A comment can be made anonymous by leaving this field empty therefore
  // there is no need to list them in the autocomplete.
  '#selection_settings' => ['include_anonymous' => FALSE],
  '#title' => $this->t('Authored by'),
  '#description' => $this->t('Leave blank for %anonymous.', ['%anonymous' => $config->get('anonymous')]),
  '#access' => $is_admin,
];

```

---
Tags: 8, ajax
---


# Question
Title: Programmatically Set Default Text Editor
I have a customized module that requires tinyMCE as a library.

After module installation, I still have to set my text editor in the image above. It was found in the `admin/config/content/wysiwyg`.

How will I programatically set tinyMCE as a default text editor right after module installation?

# Answer
> 2 votes
Below code is used in wysiwyg\_profile\_form\_submit() at wysiwyg.admin.inc. You can make use of it.

```
// Insert new profile data.
db_merge('wysiwyg')
  ->key(array('format' => $format))
  ->fields(array(
    'editor' => $editor,
    'settings' => serialize($values),
  ))
  ->execute();
wysiwyg_profile_cache_clear();

```

Another approach is using drupal\_form\_submit() to submit its settings form programmatically. But it would be more compliated.

Also, before settings the profile, you need to check if tinymce is existing.

```
if (wysiwyg_get_editor('tinymce')) {

  // set profile.

}

```

---
Tags: 7, hooks, forms, wysiwyg
---


# Question
Title: Updated >= Drupal 8.0.5+: Rendering forms/entities programmatically on theming level
There are several attempts and questions already asked about near to that topic in combination with the new Drupal core (8), but non of them came down to the bottom of the basic question. And non of them are up-to-date enough (2015) since many late changes in core arrived afterwards (2016). Answering the basic question will hopefully lead to answers for many depending questions and open HOWTO topics and could be a good basis for updated docs on drupal.org.

## The basic question is:

**How to programmatically render path/page based forms or any other entity bundles on the theming level** to display them path independently, e.g. in blocks or other pages other than the given pages/paths of itself? And how can I find the **right routing** for the correct system calls or class paths for the needed preprocess functions in the new D8 core logic if I am new to D8?

## The question arises from 2 points of view:

1. Why should a form be hard binded to a page view or fixed path? It's a page element, not a page. It should be available easely in any other places without complicated coding struggles in a website building CMF like Drupal on the theming level. It's part of theme design to decide to have a form on frontpage, for example. (ok, this is arguable, I know, but in some cases it is)
2. From the basic structure how Drupal is build and what it tries to achieve in these times (the goal to rather build web applications instead of classic and static websites), it should be easily reachable to maintain such task like a form on the bottom of a one-page site or to build a survey or render entities on unexpected pages.

## To keep with the form example:

here are some links to questions regarding this topic and I've tried already to interfere there and suggest to inform about changes in core here and there to update the posts or to link to sources:

## The basic structure

.. how it works is common, mostly clear, and not so far from how it worked in D7:

You will use a `preprocess_xxx()` function in your D8 twig `YOURTHEMENAME.theme` file to call and pipe the form or entity array into the region variable array, to be able to render it via `{{ var }}` twig-tags in your xxx.twig file: e.g. `block.html.twig` or `page.html.twig`, since the form or entity is maybe not known in this layer (enviroment variable) by default.

Just an example (needs update and correction) of your THEMENAME.theme file:

```
preprocess_page(){
  $form = Drupal::routeMatch()->getParameter('contact_form'); // ???
  $message = \Drupal::entityTypeManager() // ???
  ->getStorage('contact_message')
  ->create(array(
      'contact_form' => $form->id(),
  ));
  /// ???
  $form = Drupal::service('entity.form_builder')->getForm($message);
  $variables['contact_form'] = $form;
}

```

Just an example page.html.twig file:

```
<header>
  {{ header_region }}
</header>
<div id="main"> ... </div>
<footer>
  {{ contact_form }} <!-- from $variables['contact_form'] = $form; -->
</footer>

```

## But now comes the tricky part:

The docs are not *up-to-date* enough to make clear how to build the `preprocess_xxx()` function correctly, demonstrated with `\\ ???` here. Using the demo example here as-is (atm) will cause an almost empty frontpage, only rendering html.html.twig but without the nested page.html.twig, obviously caused by a wrong coding in the preprocess function.

Somebody who tries to find updated docs or QA for that will have a hard time ...

# Answer
> How to programmatically render path/page based forms or any other entity bundles on the theming level to display them path independently, \[…\]

Because in Drupal 8/7/6/…, forms do not have dedicated routes/controllers (D8) or page callbacks/paths (D7/6…). Hence they *are* path-dependent.

Once that is solved, then yes, you would be able to do that. For now, it's literally impossible.

See https://www.drupal.org/node/2503429

The only way you could perhaps make this work, but even then only for forms you define (and not for *every* form), is by defining a route where your form always POSTs to, and then setting it as the form action (`$form['#action'] = 'foo';` is mapped to `<form action="foo"`).

---

For now, the recommended approach to be able to put a form anywhere, is to expose it as a block. For an example, see `\Drupal\search\Plugin\Block\SearchBlock` and how it uses `\Drupal\search\Form\SearchBlockForm`.
> 3 votes

# Answer
I'm still new to drupal but here is what i did to render a form in node.html.twig:

```
//file themename.theme
function themename_preprocess_node(&$variables) {
  if(isset($variables['node'])){
    $node = $variables['node'];
    if($node->getType() == 'application') {
        $message = \Drupal::entityTypeManager()
            ->getStorage('contact_message')
            ->create(array(
            'contact_form' => 'webentwickler_job', //ID(Machine name) of form
        ));
        $form = \Drupal::service('entity.form_builder')->getForm($message);
        $variables['application_form'] = $form;
    }
  }
}

//file node--application.html.twig
{{ application_form }}

```
> 4 votes

# Answer
The question is a feature request. Providing this feature "entity/form as a block" can be done in the core module, but usually this kind of features are first provided in contrib and later they may become part of core. There are projects to address this:

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

https://www.drupal.org/project/contact\_block

https://www.drupal.org/project/entityform\_block

In my opinion putting the code in theming is only a short time solution, until this is solved in contrib/core. As the OP has experienced, you don't know how long it works, because this code doesn't get updated.
> 3 votes

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


# Question
Title: Printable Templates for Views using Print Module
Any views related report can be printed using the Print module when enabled. This can be achieved by simply using /print/views-url. It uses the standard print.tpl.php.

I do not want the print version of views output to display the exposed filter. At the same time, I would not want to modify the default print.tpl.php.

Is there a way to use alternative print templates for views in the same line as for content types: print\[--html|--mail|--pdf\]\[--node--node-type\].tpl.php

Thanks.

# Answer
I faced a similar issue quite a while back and below is how I solved it:

1. Create another display of the same view (clone page)
2. Choose 'Remember last selection' in the Views exposed filters' settings in the original page view
3. In the cloned page view, set 'Expose form in a block' to 'Yes'
4. Use the regular 'print/view-url' wherever you want but remember that 'view-url' in this case is the path of the cloned page view.

Hope this helps,

Regards, Supriya Rajgopal
> 0 votes

---
Tags: views, theming
---


title: Form validation throws a strict warning

text:
# Question
Title: Form validation throws a strict warning
I am using the form validation in `hook_form_alter()` as follows.

```
$form['#validate'][] = '\Drupal\module_name\Controller\MyController::_field_p_servicename_validate';

```

In the controller I am defining it as follows.

```
public function _field_p_servicename_validate(&$form, FormStateInterface $form_state) {}

```

It throws the following exception.

> Strict warning: call\_user\_func\_array() expects parameter 1 to be a valid callback, non-static method Drupal\module\_name\Controller\MyController::\_field\_p\_servicename\_validate() should not be called statically in Drupal\Core\Form\FormValidator-\>executeValidateHandlers() (line 88 of core/lib/Drupal/Core/Form/FormValidator.php)

What does it mean? How can I fix it?

# Answer
There are contexts where Drupal allows you to use a notation like `'\Drupal\module_name\Controller\MyController::_field_p_rpservicename_validate'` to refer to a public function of an object. In the case of validation handlers, since Drupal is calling them with `call_user_func_array()`, with a notation like `'\Drupal\module_name\Controller\MyController::_field_p_rpservicename_validate'` you are referring to a static function of a class.

Change the definition of that method as follows, and your code will work.

```
public static function _field_p_rpservicename_validate(&$form, FormStateInterface $form_state) {}

```

Keep in mind that a static method cannot use `$this`.
> 5 votes

---
Tags: forms, 8
---


# Question
Title: How do I implement a notification/subscription solution?
I can't get the Notifications or Subscriptions modules to actually send out emails, and installing the Comment Notify module crashes my entire site.

I realize that Drupal 7 is still fairly young, but I find it pretty remarkable that there is not yet a stable notification/subscription solution. Does anyone have any suggestions beyond the modules I listed here?

Ideally, I would like the following features:

* Automatically become subscribed to nodes you create or comment on (with the option to turn this off, of course)
* Subscribe to taxonomy terms
* Receive notification emails at an interval you specify, such as immediately, once a day, etc.

Seems like maybe 1 & 2 are possible to do through Rules, which I'll begin to explore. But the third point above is pretty critical as well.

# Answer
Have a look at the Message Stack, which consists of these modules (quotes are from the module's project page):

* Message:

> The Message module is the core of the message stack. It enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.
* Message Notify.

> This module provides a method for sending a message via a notifier plugin. Message Notify comes with plugins for email and SMS and may be extended to other transport mechanisms as required.
* Message Subscribe.

> With this module, users who subscribe to content will be notified when events occur that involve that content. The module leverages the Flag module, which provides a subscribe functionality to users.

These are the basic components and dependencies of the message stack:

Quite a few popular Drupal distributions already adopted to this Message Stack, such as such as Commerce Kickstart, Drupal Commons, ERPAL and Open Atrium. And it will make you well positioned for Drupal 8 also (because of he modules' object orientated architecture).

If you want to have a closer look at the Message Stack in your own environment, then experiment a bit with the Answers module (disclosure: I'm a co-maintainer), together with the *Answers Notification* sub-module, which allows logged in users to subscribe to selected questions, so that they receive notifications (using the Message Stack) when Questions receive Answers.
> 1 votes

---
Tags: 7, notifications
---


title: How to save entire term lineage

text:
# Question
Title: How to save entire term lineage
I need to **save term lineage** in Drupal 8, not only the deepest term. I know there are modules like *Hierarchical select, Simple hierarchical select or Client-side hierarchical select* but these are not for Drupal 8, or not solves "save term lineage" functionality.

I need to get my "nodes" visible on both child term and parent term pages too. I know, I can use the "**Content: Has taxonomy term ID (with depth)**" (under contextual filters) functionality in "views", but it slows the database queries very much. Or maybe I'm doing something wrong.

Is there some reasonable solution?

Thank you!

EDIT: The hierarchy is very simple. Only two-tiered: **Country / City**.

Can someone help me to re-save my nodes with "lineage" structure? For example, using the **TermStorage** functions listed below?

# Answer
> 2 votes
Depends on your understanding of reasonable. Until *hierarchical select* or similar modules become available you could save the parent terms programmatically on node save - the code probably wouldn't exceed 30 lines or so, especially when you don't have many taxonomy fields where you want to do this.

You can access a term's parents with the following code utilizing TermStorage:

```
$parents = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadParents($termId);

```

Then you only need to go recursively through the tree and grab all parents (if your terms can have more than one), get their ids and set them in the node you want to save.

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


title: How to increase exposed filter speed?

text:
# Question
Title: How to increase exposed filter speed?
I have three better exposed filter in views.when apply any filter it takes 4 to 5 secs to give a result.

# Answer
You can use Views Cache to make better performance.

Click on Caching in right side of view edit page
> 0 votes

---
Tags: ajax, views
---


# Question
Title: How can I add extra text fields to the image field when adding/ editing nodes?
What is the best way to add additional text fields to the image module, other than the title and alt value, when adding/ editing content? Is there a module which already does this?

Edit

I've read through Add custom fields to image field and unfortunately this fella got stuck and I guess this was at 7 times. The fieldable files module is no big help. It does a lot of magic but it doesnt effect images added via node entity form.

# Answer
> 3 votes
Image is a file entity and to make it fieldable you can use this module:

File Entity (fieldable files)

From the documentation:

> File Entity
>
> The File entity module extends the capabilities of the core File module.
>
> File Entity defines 5 File Types - Application, Audio, Image, Text, Video. The Media module adds an additional File Type - Other (currently these File Types are hard coded and cannot be changed).
>
> When files are uploaded they are automatically assigned the appropriate File Type based on the file suffix.
>
> The File Types as currently defined are:
>
> Images - .png, .gif, .jpg, .jpeg, .ico Videos - .mov, .mpg, .flv, .m4v, .mp4, ,ogg, .ovg, .wmv Sound files - .mp3 Text - .txt Document files - .doc, .xls, .pdf, .ppt, .pps, .odt, .ods, .odp Other - ??
>
> Each File Type can have fields. This allows for additional information to be stored along with a media file such as Title, Description, Taxonomy References, Node References, Location, Date created, License information etc.

---
Tags: entities, 8, media
---


# Question
Title: How to enable highlighted search functionality?
I want to enable search functionality such that:

1. I have one word say "school" in my website and if I put "sc" word in search box, then search result should give "school" word with "sc" word highlighted.
2. I have one word say "school" in my website and if I put "oo" word in search box, then search result should give "school" word with "oo" word highlighted.

How can I solve this problem?

# Answer
You can use the Highlight module:

> * Highlight the keywords from referrer search engine
> * Highlight the keywords from local search

If you need more information you can read this posts:
> 2 votes

---
Tags: 7, search
---


title: Translate string passed to twig's macro

text:
# Question
Title: Translate string passed to twig's macro
does Twig provide any way to translate string which is passed to macro? I thought that it would work in similar way to Wordpress translation function where instead of string I just provide the variable. But it does not work.

Here is my macro:

```
{% macro input(type, name, placeholder, value, class) %}
<input type="{{ type|default('text') }}" name="{{ name }}" placeholder="{{ placeholder | t}}" value="{{ value | e }}"
       class="{{ class }}">
{% endmacro %}

```

Then I call it in this way:

```
{{ macro.input('text', 'name', 'Name...') }}

```

I want just to translate the placeholders but when I use | t filter drupal returns the error:

```
InvalidArgumentException: $string ("") must be a string. in Drupal\Core\StringTranslation\TranslatableMarkup->__construct() (line 140 of F:\xampp\htdocs\va\core\lib\Drupal\Core\StringTranslation\TranslatableMarkup.php).

```

I am aware that input is not great example and I should use form API, it's just the easiest to explain. Is there any way of translating strings which are passed to macros?

# Answer
> 1 votes
I found the solution. The |filter has to be included while calling macro like this:

```
{{ macro.input('text', 'name', 'Name...' | t) }}

```

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


# Question
Title: Get logged in user's username as twig variable
Is there a way to get the currently logged in user's username as a variable to use in any twig template?

# Answer
> 10 votes
You would have to target a specific one. All twig templates are not possible because of caching. Many page elements don't get rebuilt on every request and will display the wrong user.

And if you try to remove caching from all elements your site will be very slow.

If you add this to a specific twig template, then you can adjust the cache data of this render element:

```
function MYTHEME_preprocess_HOOK(&$variables) {
  $variables['currentusername'] = \Drupal::currentUser()->getUsername();
  $variables['#cache']['contexts'][] = 'user';
  $variables['#cache']['tags'][] = 'user:' . \Drupal::currentUser()->id();
}

```

with the cache context to vary by user and the cache tag to invalidate the user name if the user is modified in the database. `HOOK` is your template type.

---
Tags: theming, 8, users
---


# Question
Title: Render updated node data during views render
I have a view page which display node titles?

I'm also using workbench moderation module. During views rendering I check nodes and on certain condition I'm publishing the node from draft state using `workbench_moderation_moderate($node, 'published');`.

So is there any views hook Where i can use to set a revision of a node to publish and then views fetch the node's updated data?

I have tried `hook_preprocess_views_view(&$vars)` but it moderate the node to publish but then display the updated data on 2nd page referesh.

# Answer
Assuming this is Drupal 7.

`hook_preprocess_views_view()` runs after the query is performed. You could try using `hook_views_pre_view()` or `hook_views_query_alter()`, both of which happen before the query runs, and save the nodes at that time. Of course the results of the view will not be available to you then, so you would have to select the nodes in some other way.

Also neither of these hooks work in themes, you would have to use a custom module.

https://api.drupal.org/api/views/views.api.php/group/views\_hooks/7.x-3.x
> 1 votes

---
Tags: 7, views
---


# Question
Title: A views & CSS only solution for a previous post & next post buttons in a blog-node?
I found the Previous/Next API module that lets you create `previous-post` & `next-post` buttons, that you could put on any node.

For example, if you have nodes of the content type "Blog" you could put such two buttons under them in one div.

A core-only way would most likely include 2 view-blocks styled with some css (most probably `display: flex; flex-wrap: wrap;` etc).

# Answer
This you can do easily with the Core `Book` module. As you can see on the any Drupal.org page for example, Drupal.org page.

>

Using Book module

* You can create a Book which is like index and add the nodes in-order you want, and it will show `Next` and `Prev` as shown in above page as title of that node.

D8 site scree shot:

**Configuration page**

>

**Example Page:**

>
> 4 votes

# Answer
As you said you can simply achieve that by using views.

Configure the view as follows:

1. Create a view of **show** "content" **of type** "Blog".
2. You can select Format as Grid and Add Fields as many you want from that content type.
3. Set Pager as **Mini**.
4. Configure the Mini Pager settings like follows

5. Save the view and the output will looks like follows.

That's it. Hope this provides an answer to your question.
> 1 votes

---
Tags: views, 8, nodes
---


# Question
Title: How to run alter query to modify mysql database using hook_schema?
I want to change data-type of a field in for a particular table in database. I want to use hook\_schema\_alter() to do so. The ALTER query is:

```
ALTER TABLE `abcd` CHANGE `session_number` `session_number` INT( 255 ) NOT NULL COMMENT 'Session number to get number.'

```

Is it possible to implement such query using hook ? If yes please guide me. Tonnes of thanx in advance.

# Answer
> 1 votes
As you mentioned you are having single Drupal code base for multiple sites. I assume that you only want one of the sites having schema change. So you need a separate module for altering schema.

You need to implement `hook_schema_alter()` and `hook_enable()` in .install file of your custom module.

```
/**
 * Implements hook_enable().
 */
function mymodule_enable() {
  // other_module is the module name which define the schema of 'abcd' table.
  $schema = drupal_get_schema_unprocessed('other_module', 'abcd');
  db_change_field('abcd', 'session_number', 'session_number', $schema['fields']['session_number']);
}

/**
 * Implements hook_schema_alter().
 */
function mymodule_schema_alter(&$schema) {
  $schema['abcd']['fields']['session_number'] = array(
    'type' => 'int',
    'size' => 'tiny',
    'not null' => TRUE,
    'default' => 0,
    'description' => 'Session number to get number.',
  );
}

```

Please note that `'size' => 'tiny'` means 1 byte size for integer type. More details can be found here.

# Answer
> 2 votes
Changes to the schema are typically handled with hook\_update\_N and you will normally locate this file in the `module.install` file.

For example with the update from Drupal 6.x-7.x the some of the base permissions were rename:

```
/**
 * Rename blog and forum permissions to be consistent with other content types.
 */
function system_update_7000() {
  $result = db_query("SELECT rid, perm FROM {permission} ORDER BY rid");
  foreach ($result as $role) {
    $renamed_permission = $role->perm;
    $renamed_permission = preg_replace('/(?<=^|,\ )create\ blog\ entries(?=,|$)/', 'create blog content', $renamed_permission);
    $renamed_permission = preg_replace('/(?<=^|,\ )edit\ own\ blog\ entries(?=,|$)/', 'edit own blog content', $renamed_permission);
    $renamed_permission = preg_replace('/(?<=^|,\ )edit\ any\ blog\ entry(?=,|$)/', 'edit any blog content', $renamed_permission);
    $renamed_permission = preg_replace('/(?<=^|,\ )delete\ own\ blog\ entries(?=,|$)/', 'delete own blog content', $renamed_permission);
    $renamed_permission = preg_replace('/(?<=^|,\ )delete\ any\ blog\ entry(?=,|$)/', 'delete any blog content', $renamed_permission);

    $renamed_permission = preg_replace('/(?<=^|,\ )create\ forum\ topics(?=,|$)/', 'create forum content', $renamed_permission);
    $renamed_permission = preg_replace('/(?<=^|,\ )delete\ any\ forum\ topic(?=,|$)/', 'delete any forum content', $renamed_permission);
    $renamed_permission = preg_replace('/(?<=^|,\ )delete\ own\ forum\ topics(?=,|$)/', 'delete own forum content', $renamed_permission);
    $renamed_permission = preg_replace('/(?<=^|,\ )edit\ any\ forum\ topic(?=,|$)/', 'edit any forum content', $renamed_permission);
    $renamed_permission = preg_replace('/(?<=^|,\ )edit\ own\ forum\ topics(?=,|$)/', 'edit own forum content', $renamed_permission);

    if ($renamed_permission != $role->perm) {
      db_update('permission')
        ->fields(array('perm' => $renamed_permission))
        ->condition('rid', $role->rid)
        ->execute();
    }
  }
}

```

---
Tags: hooks
---


title: Force a new line item on cart

text:
# Question
Title: Force a new line item on cart
I'm developing my own module for a customizable bundle of commerce products.

I'm saving the subproducts in a field collection in a line item field.

For some reasons I'm doing this with my module, not using "Include this field on Add to Cart forms for line items of this type" in the line item field settings.

Well, when I use my module I use

```
$form['#submit'][] = 'commerce_custom_bundle_add_to_cart_form_submit';

```

inside a

```
commerce_custom_bundle_form_commerce_cart_add_to_cart_form_alter

```

(is hook\_form\_BASE\_FORM\_ID\_alter)

Then my function is executed after the product is added to the cart.

The problem is if I choose to add to cart the same product no new line item is created and the existing quantity is increased in 1, obviously.

But I need a new line item, because my custom field changes and I need to not merge the values chosen in the existing line item. I don't know How to force the creation of a new line item.

I tested, if I not use my code and I expose this field in the add to cart form enabling the "Include this field on Add to Cart forms for line items of this type" in the line item field settings. If the same product is added to the cart with a different value in my custom field, is created a new line item.

How do I force the creation of a new line item?

# Answer
To force to create a line\_item for every same product added to the cart you just need to uncheck the option "Attempt to combine like products on the same line item in the cart." in the Add to cart form settings of your product reference in your product display content type.

In other words. You have to change the content type that you use to show your product, you had added a product reference to this content type. Then you just has to change in the "Manage display" of your content type, the settings of the "Add to cart Form" of the product reference field, and you have to uncheck "Attempt to combine like products on the same line item in the cart."

This is a screenshot of the manage display page:
> 0 votes

---
Tags: commerce
---


# Question
Title: Is it possible to include external libraries in a twig template?
I think I know the answer, because I tried to attach an external library like this:

```
{% set location = {'type': 'external'} %}
{{ attach_library('//example.com/example.js/v3/example.js', location) }}

```

This did not attach the desired library, am I missing something, or is this a non-starter?

# Answer
> 4 votes
Add external files in libraries: https://www.drupal.org/developing/api/8/assets

See the section on "CDN / externally hosted libraries".

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


# Question
Title: Images uploaded with CKeditor disappear after cron run
When i upload images with CKeditor in a directory inline-images - they disappear after each cron run. Why is that happened? I had a look at db table `file_managed` it's status set to 0.

What it might be?

# Answer
Whatever text editor are you using either Basic HTML, Restricted HTML or Full HTML.

In setting if `Limit allowed HTML tags and correct faulty HTML` is enabled under the `Enable filters` setting. Check under the `Filter setting` in the list of `Allowed html tags`, `<img>` tag has been enabled or not? If not listed in that list, the image will be strip off from the content as for that case it is restricted html element.

**Update-1**

>
> 0 votes

---
Tags: 8, wysiwyg
---


# Question
Title: How to set up custom Entity Storage per bundle?
Is it possible to use custom entity storage per bundle? Let's say I have node (entity type) which is called article (bundle). I want to store articles in different storage engine than every other nodes (like recipes). So far I have found no way to store single bundle in different storage engine. I could create custom entity type with custom bundle (that works, yes) but I really would like to use nodes and specify custom storage engine for one of them.

# Answer
> 2 votes
I'd *strongly* recommend against doing that. That's what separate entity types are for, bundles are just variations with different settings/configurable fields.

The assumption in many places is that all entities of a type a stored in the same places, for loading, querying and so on.

You could probably make it work by replacing the storage and have every relevant method (save, delete, load, query, ...) branch of into two different methods. Very likely more work and more complicated than just doing this for a separate entity type. and some things are impossible to get right (e.g. doing queries against a field shared by multiple bundles. core expects that to work).

---
Tags: 8, entities
---


# Question
Title: How to add an image to a term in a HOOK_install() of a module
I was able to add a taxonomy term in the .install file in the hook\_install() function, like this:

```
use Drupal\taxonomy\Entity\Term;

class feature_basic_page_class{

  const feature_basic_page_terms = array('default', 'inverted');
  const feature_basic_page_vid = 'basic_page_layout';
}

function feature_basic_page_install(){
  $feature_basic_page_terms = feature_basic_page_class::feature_basic_page_terms;
  $feature_basic_page_vid = feature_basic_page_class::feature_basic_page_vid;
  foreach($feature_basic_page_terms as $feature_basic_page_term){
    $term = Term::create(array(
      'name' => $feature_basic_page_term,
      'description' => '',
      'parent' => array(0),
      'vid' => $feature_basic_page_vid
    ));
    $term->save();
  }
}

function feature_basic_page_uninstall(){
  $feature_basic_page_terms = feature_basic_page_class::feature_basic_page_terms;
  $feature_basic_page_vid = feature_basic_page_class::feature_basic_page_vid;
  $terms = array();
  foreach($feature_basic_page_terms as $feature_basic_page_term){
    if($terms_name = taxonomy_term_load_multiple_by_name($feature_basic_page_term, $feature_basic_page_vid)){
      $terms = array_merge($terms, $terms_name);
    }
  }
  foreach($terms as $term){
    $term->delete();
  }
}

```

I use a class because I tried a `global` variable and it was not working I don't know why...

Anyway, now I need to do the same thing for another module but this time the taxo term has an additional image field. I tried a few things but no success at this point:

```
use Drupal\taxonomy\Entity\Term;

class feature_carrousel_class{

  const feature_carrousel_terms = [
    array('name' => 'left', 'overlay' => 'images/BRAVA_Image_Forme.png'),
    array('name' => 'right', 'overlay' => 'images/BRAVA_Image_Forme.png')
  ];
  const feature_carrousel_vid = 'layout';
}

function feature_carrousel_install(){
  $feature_carrousel_terms = feature_carrousel_class::feature_carrousel_terms;
  $feature_carrousel_vid = feature_carrousel_class::feature_carrousel_vid;
  foreach($feature_carrousel_terms as $feature_carrousel_term){
    $term = Term::create(array(
      'name' => $feature_carrousel_term['name'],
      'field_overlay_image' => $feature_carrousel_term['overlay'],
      'description' => '',
      'parent' => array(0),
      'vid' => $feature_carrousel_vid
    ));
    $term->save();
  }
}

function feature_carrousel_uninstall(){
  $feature_carrousel_terms = feature_carrousel_class::feature_carrousel_terms;
  $feature_carrousel_vid = feature_carrousel_class::feature_carrousel_vid;
  $terms = array();
  foreach($feature_carrousel_terms as $feature_carrousel_term){
    if($terms_name = taxonomy_term_load_multiple_by_name($feature_carrousel_term['name'], $feature_carrousel_vid)){
      $terms = array_merge($terms, $terms_name);
    }
  }
  foreach($terms as $term){
    $term->delete();
  }
}

```

I get this error:

`The website encountered an unexpected error. Please try again later.
Error: Call to a member function getFileUri() on null in Drupal\image\Plugin\Field\FieldType\ImageItem->preSave() (line 317 of core/modules/image/src/Plugin/Field/FieldType/ImageItem.php).
Drupal\image\Plugin\Field\FieldType\ImageItem->preSave() (Line: 244)
Drupal\Core\Field\FieldItemList->delegateMethod('preSave') (Line: 202)
Drupal\Core\Field\FieldItemList->preSave() (Line: 449)
Drupal\Core\Entity\ContentEntityStorageBase->invokeFieldMethod('preSave', Object) (Line: 406)
Drupal\Core\Entity\ContentEntityStorageBase->invokeHook('presave', Object) (Line: 435)
Drupal\Core\Entity\EntityStorageBase->doPreSave(Object) (Line: 291)
Drupal\Core\Entity\ContentEntityStorageBase->doPreSave(Object) (Line: 389)
Drupal\Core\Entity\EntityStorageBase->save(Object) (Line: 747)
Drupal\Core\Entity\Sql\SqlContentEntityStorage->save(Object) (Line: 358)
Drupal\Core\Entity\Entity->save() (Line: 24)
feature_carrousel_install()
call_user_func_array('feature_carrousel_install', Array) (Line: 391)`

This sound like a bad path for my image, but I don't know how to call my image correctly. My images are located at the root of my module in an images/ folder.

# Answer
An image field is basically an entity reference field.

So what you do is you create a file entity first, save that, and then assign the file id or file entity object to your image field, plus alt/title if you want that.

http://realityloop.com/blog/2015/10/08/programmatically-attach-files-node-drupal-8 seems like a pretty good blog post about that. nodes or terms doesn't a difference here.

The critical part ( to make drupal answers moderators happy ;)):

```
use \Drupal\node\Entity\Node;

// Create file object from remote URL.
$data = file_get_contents('https://www.drupal.org/files/druplicon.small_.png');
$file = file_save_data($data, 'public://druplicon.png', FILE_EXISTS_REPLACE);

// Create node object with attached file.
$node = Node::create([
  'type'        => 'article',
  'title'       => 'Druplicon test',
  'field_image' => [
    'target_id' => $file->id(),
  ],
]);
$node->save();

```

That assumes fetching the file data from somewhere, there are also examples that create it with an already existing file.
> 3 votes

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


title: "Digging Deeper" with Twig

text:
# Question
Title: "Digging Deeper" with Twig
I created a custom twig file that outputs a few basic fields, such as images and text. Here's what my twig file looks like:

```
<div class="image">
    {{content.field_image}}
</div>

<div class="year">
    {{content.field_year}}
</div>

<div class="heading-text">
    <h3>{{content.field_heading_text}}</h3>
</div>

```

I'm trying to have a little more control of the HTML that gets output. Here's what I'm seeing for a few of these fields:

I want to either, A, get rid of the div element that outputs "1963" or "Imagining a better world" or, B, get control over the div element so I can add a class to it and later style it.

Thank you in advance!

# Answer
The easiest way to avoid the standard field divs is to only print out the first delta. That works well for single-value fields, for multiple, you'd need to loop over it yourself.

So, just do this: `{{ content.field_year.0 }}` and it will only print out the actual field content, without the wrapping field type. Might not work for every formatter, depending on what they do, but it should work for most of them.
> 5 votes

# Answer
The theme debug info in the source gives you a hint. If you want control of how certain fields are displayed you can create templates for them using a filename that refers to that specific field. For example if we wanted to change the output of the year we could create

```
field--field-year.html.twig

```

in the templates folder of your theme. First I would copy the default contents of the core field.html.twig file into field--field-year.html.twig first. You can find the default field template in /core/themes/classy/templates/field/field.html.twig. In case you can't find it the contents are

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

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

```

Once you copy and paste that into your field--field-year.html.twig you can start editing it however you want. If you change

```
 <div{{ item.attributes.addClass('field__item') }}>{{ item.content }}</div>

```

to

```
{{ item.content }}

```

It will output only the content of the field not the surrounding div or classes.
> 4 votes

# Answer
```
cp themes/custom/aqair/templates/field/field.html.twig themes/custom/aqair/templates/field/field-string.html.twig

```

Or any of the other suggestions noted in your twig debug, then just edit the template to not include the surrounding div element.

Clear your cache `drush cr`
> 0 votes

---
Tags: theming, 8
---


# Question
Title: How can I create a Views RSS of members only content?
We have a website with a members only content in the form of a forum.

I have already created the RSS feed and I can see that when I load the feed URL in a web browser that it is working. The problem is that I can only see it when I am logged into the website itself, and therefore when I load it into my web based reader, or Microsoft Outlooks RSS feed; that it can not see any posts.

The views screenshot I used is below:

Does the fact that a user needs to be logged into the website to view the content prevent me from doing this?

EDIT: I have been editing drupal/modules/system/system.api.php to include suggestions below including changing 'forum/%forum\_forum' for the explicit 'forum/rss.xml' - it loads the xml but with no content when I am not logged into the website itself.

EDIT 24/09: After a bit of a break I have come back to this one for a fresh look.

I installed Custom Menu Permissions as advised, found the forums/rss.xml and forums/%forums\_forum/rss.xml and allocated them to a custom permission which I then allowed for both Anonymous and Authenticated users.

I flushed all the caches and tries while logged off. Still nothing.

I **can** see the rss feed still while logged in, so I know it is there. That would discount anything stopping it being produced.

I also ensured that I had removed my custom hook\_alter code as suggested below to ensure there were no conflicts.

Any further assistance to the right direction would be appreciated....

# Answer
> 0 votes
Yes. The **forum/%forum\_forum** route created by the Forum module does a `user_access()` check for the `access content` permission; any subpath of this route (e.g. your RSS view, **forum/%forum\_forum/rss.xml**) will be checked as well.

You can override this via a `hook_menu_alter()` implementation:

```
/**
 * Implements hook_menu_alter().
 */
function MYMODULE_menu_alter(&$items) {
  $items['forum/%forum_forum']['access callback'] = 'MYMODULE_forum_override';
}

function MYMODULE_forum_override() {
  return preg_match('/^forum\/(\d+)\/rss.xml$/', request_path());
}

```

---
Tags: 7, views, feeds
---


# Question
Title: How do I get JSON data from a custom entity
I would like to GET JSON data from drupal 8 custom entity. I am using ubuntu 14.04 and vagrant. For that i have done these steps.

I have taken reference to Create drupal 8 custom entity from this link.

Enable this modules:

* HAL - Core module
* HTTP Basic Authentication -Core module
* RESTful Web Services - Core module
* Serialization - Core module
* Restui - Contributed module

RESTui Configuration:

* redirect to admin/config/services/rest
* Enable content\_entity\_example\_contact entity
* GET Settings done for custom entity

Save.

Permissions given for Rest full web services

Postman Plugin is integrated in to chrome. below settings is done for postman.

Above steps i have done to GET JSON from custom entity but getting error in postman. Any suggestion or starting point will help for me.

Interestingly when i perform similar steps for drupal 8 node entity i am able to GET JSON data.

Thanks

# Answer
> 0 votes
Dou you have an access control handler or an admin permission to control view/create/update/delete access to your entities?

You need to have that, in addition to the rest specific permissions. In fact, those will go away in 8.2, only the generic entity access will matter then.

# Answer
> 0 votes
I have given all permissions to Content Entity Example:

1. Add entity content
2. Administer settings
3. Delete entity content.
4. Edit entity content
5. View entity content

Clear the cache and restart the Postman.

URL: http://localhost:8080/d8\_entity/content\_entity\_example\_contact/1?\_format=json

Header : none or blank

Send

Surprisingly got JSON.

Thanks Berdir, your suggestion worked for me.

---
Tags: entities, 8
---


# Question
Title: What might cause drupal to give me Japanese values for the user profile, when the site is set to English?
I'm playing whack-a-mole bug edition with drupal yet again. Recently I've done a number of things including installing the neutral\_path module. I just discovered that now my user profiles (which all have English and Japanese name values) are giving me Japanese values when the site should be in English. Examining the variable that is passed into `MYTHEME_preprocess_user_profile()` I see that the field values are in Japanese and that `$variables['elements']['#language']` is set to `'ja'`

What could be causing this? What are reasonable steps to take to try and debug this?

I notice that after drupal\_bootstrap() runs, I have $language reflecting English, but $language\_content reflecting Japanese.

# Answer
> 0 votes
Using a debugger and some spot googling, I finally found an answer for this. In my language detection and selection options I had session turned on as one of the means of detection, and saw that the query variable used for setting this option was language. adding ?language=en to the end of my url caused the language to switch back and stay that way, but I am not sure how it got that way in the first place, or how to make sure it doesn't happen unintentionally again without disabling the session option.

---
Tags: 7, i18n-l10n, path-aliases
---


title: Form field validator

text:
# Question
Title: Form field validator
Is there a way to validate fields individually like you would've done for the file upload (Eg: file\_validate\_extension etc)? I want to do something like this:

```
$form["field_name"] = array(
  "#type" => "textfield",
  ...
  "#field_validate" = array("field_validate_numeric") // or "field_validate_email" or "field_validate_url" etc
);

```

I know there are new html5 field types but I want to be able to validate textfields.

Also, I need this because I might not know the actual tree structure or field parents and I want to validate the field no matter how the form looks.

# Answer
You can do this with a callback, so that it will work whereever you use it in the form tree:

Add this to your form element:

```
'#element_validate' => [[get_class($this), 'validateNumber']],

```

And put the callback in the form class:

```
public static function validateNumber(&$element, FormStateInterface $form_state, &$complete_form) {
    $value = $element['#value'];
    if ($value === '') {
      return;
    }

    $name = empty($element['#title']) ? $element['#parents'][0] : $element['#title'];

    // Ensure the input is numeric.
    if (!is_numeric($value)) {
      $form_state->setError($element, t('%name must be a number.', array('%name' => $name)));
      return;
    }
}

```

(for the callback I've used some of the code from the html5 number element)
> 4 votes

# Answer
The properties that are common to all the form fields are listed in `FormElement`. Those include also `#element_validate`, which is described as the following.

> **#element\_validate**: (array) Array of callables or function names, which are called to validate the input. Arguments: `$element`, `$form_state`, `$form`.

The code you are showing works when:

* You replace `#field_validate` with `#element_validate`
* You fix the syntax error (i.e. replace `= array(` with `=> array(`)
* You use a validation handler that exists in Drupal 8 (Drupal 8 doesn't have any `field_validate_numeric()` function)
> 3 votes

---
Tags: 8, forms
---


title: List "edit Menu" links on a custom page

text:
# Question
Title: List "edit Menu" links on a custom page
I am attempting to create a simple user dashboard that will let a user do things throughout the site like edit menus and content.

I would like to have a dropdown that lists all the custom menus on the site and after they select one it would take them to the edit page.

How would I go about doing this within my module?

# Answer
This feature is already done in core in D8, however not in one menu but in multiple one (in the wrapper divs of the elements).

First of all I would make a list exactly what I want to include in the custom menu (menu items edit, content edit, etc..).

And then trying to look inside the core for the existing solution for that and unite them into one menu.
> 1 votes

---
Tags: 8
---


# Question
Title: Form field not show on Ajax Callback even the callback is called
I have a form with one shown field of type select with ajax callback to show another form field dynamically of type select and with ajax callback again, the problem is second field ajax callback should show a third field dynamically but nothing is shown. here is my code

```
public function buildForm(array $form, FormStateInterface $form_state) {
    $controller = new Place_AdsController();
    $terms = $controller->content();

    $form['#attached']['library'][] = 'Place_Ads/general';
    $form['level1value'] = array(
        '#type' => 'hidden',
    );
    $form['level1'] = array(
        '#type' => 'select',
        '#description' => 'Please select level one term',
        '#options' => $terms,
        '#attributes' => array(
            'class' => array(
                'mycategory'
            ),
        ),
        '#ajax' => array(
            // Function to call when event on form element triggered.
            'callback' => '::level1SelectedCallback',
            // Effect when replacing content. Options: 'none' (default), 'slide', 'fade'.
            'wrapper' => 'ajax-wrapper2',
            'effect' => 'fade',
            // Javascript event to trigger Ajax. Currently for: 'onchange'.
            'event' => 'change',
            'progress' => array(
                // Graphic shown to indicate ajax. Options: 'throbber' (default), 'bar'.
                'type' => 'throbber',
                // Message to show along progress graphic. Default: 'Please wait...'.
                'message' => NULL,
            ),
        ),
    );
    $form['ajax_wrapper2'] = [
        '#type' => 'container',
        '#attributes' => ['id' => 'ajax-wrapper2'],
    ];
    $form['ajax_wrapper3'] = [
        '#type' => 'container',
        '#attributes' => ['id' => 'ajax-wrapper3'],
    ];

    if ($form_state->getValue('level1') != false) {
        $form['ajax_wrapper2']['level2'] = array(
            '#type' => 'select',
            '#description' => 'Please select level two term',
            //'#options' => '',
            '#attributes' => array(
                'class' => array(
                    'mycategory'
                ),
            ),
            '#ajax' => array(
                // Function to call when event on form element triggered.
                'callback' => '::level2SelectedCallback',
                // Effect when replacing content. Options: 'none' (default), 'slide', 'fade'.
                'wrapper' => 'ajax-wrapper3',
                'effect' => 'fade',
                // Javascript event to trigger Ajax. Currently for: 'onchange'.
                'event' => 'change',
                'progress' => array(
                    // Graphic shown to indicate ajax. Options: 'throbber' (default), 'bar'.
                    'type' => 'throbber',
                    // Message to show along progress graphic. Default: 'Please wait...'.
                    'message' => NULL,
                ),
            ),
        );
    }
    if ($form_state->getValue('level2') != false) {
        //$form['ajax_wrapper3'][0]['#suffix'] = '</div>';
        $form['ajax_wrapper3']['level3'] = array(
            '#type' => 'select',
            '#description' => 'Please select level three term',
            //'#options' => '',
            '#attributes' => array(
                'class' => array(
                    'mycategory'
                ),
            ),
            '#ajax' => array(
                // Function to call when event on form element triggered.
                'callback' => '::level3SelectedCallback',
                // Effect when replacing content. Options: 'none' (default), 'slide', 'fade'.
                'wrapper' => 'ajax-wrapper4',
                'effect' => 'fade',
                // Javascript event to trigger Ajax. Currently for: 'onchange'.
                'event' => 'change',
                'progress' => array(
                    // Graphic shown to indicate ajax. Options: 'throbber' (default), 'bar'.
                    'type' => 'throbber',
                    // Message to show along progress graphic. Default: 'Please wait...'.
                    'message' => NULL,
                ),
            ),
        );
    }

    return $form;
}

public function level1SelectedCallback(array &$form, FormStateInterface $form_state) {
    // Instantiate an AjaxResponse Object to return.
    $ajax_response = new AjaxResponse();
    $controller = new Place_AdsController();
    $terms = array();
    if ($form_state->getValue('level1') != false) {
        $val = $form_state->getValue('level1');
        $terms = $controller->getTerms($val);

    }

    $form['ajax_wrapper2']['level2']['#options'] = $terms;
    $ajax_response->addCommand(new HtmlCommand('#ajax-wrapper2', $form['ajax_wrapper2']['level2']));
    // We can still invoke the change command on #edit-user-name so it triggers Ajax on that element to validate username.
    $ajax_response->addCommand(new InvokeCommand('#ajax-wrapper2', 'change'));
    $ajax_response->addCommand(new InvokeCommand('#level2', 'change'));

    return $ajax_response;
}

public function level2SelectedCallback(array &$form, FormStateInterface $form_state) {

    $ajax_response = new AjaxResponse();
    $controller = new Place_AdsController();
    $terms = array();
    if ($form_state->getValue('level2') != false) {
        $val = $form_state->getValue('level2');
        $terms = $controller->getTerms($val);

    }

    $form['ajax_wrapper3']['level3']['#options'] = $terms;
    $ajax_response->addCommand(new HtmlCommand('#ajax-wrapper3', $form['ajax_wrapper3']['level3']));
    // We can still invoke the change command on #edit-user-name so it triggers Ajax on that element to validate username.
    $ajax_response->addCommand(new InvokeCommand('#ajax-wrapper3', 'change'));
    $ajax_response->addCommand(new InvokeCommand('#level3', 'change'));

    return $ajax_response;

}

public function level3SelectedCallbackold(array &$form, FormStateInterface $form_state) {
    return null;
}

```

# Answer
> 0 votes
Changing the option list in an ajax callback like this

```
$form['ajax_wrapper2']['level2']['#options'] = $terms;

```

does not work, because the formbuilder does not know about this and will not recognize the new options. You have to move this code to `buildForm()`.

Otherwise you will see a select element, but when you choose an option, nothing will happen or an error occurs that you have chosen the wrong option.

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


title: Using computed field value

text:
# Question
Title: Using computed field value
I'm using Commerce module and I have a line item with a computed field that's calculating a date. This field finally shows a date.

Then during the checkout process I have a form with a Date field (part of the Order). I'm running some Rules and finally I have to copy one of the calculated dates to this field but i couldn't by rules.

I tried with a simple rule "set a data value" trying to copy the Computed field value to the other field. I put a "has field" with the CF. Then in actions, the field doesn't appear in the data selector.

This is normal? Is there another method to do it?

# Answer
You may want to give it a try to use the NOT commonly known/used alternative available for the Computed Field module, i.e. the (fairly new) Math Field module (for D7). Some more details about this module (from its project page), which also details when the calculations actually happen:

> The Math Field module defines a new field type to dynamically calculate values on entity forms. **This is an alternative to Computed Field that does not require the use of PHP Filter.**
>
> Math expression fields are dynamically updated via ajax on the entity form as soon as all necessary fields are populated. If JavaScript is disabled, the field will be evaluated when the form is submitted. The result is stored in the database when the form is submitted.

For more details (step-by-step instructions), refer to either of these links:

**Known issues**

As this is a fairly new D7 module, there are still a few (known) issues with it, as mentioned also on its project page:

**Bonus**: you would not need the "PHP filter" (IMO only that should be a valid reason to investigate this alternative) ...
> 0 votes

# Answer
**Anyone running into this recently, I found a work around.**

I used "**Entity has field**" as a condition on the Computed Field Value.

I then used the "**Add a variable**" action to add a text value of the Computed Field as a variable.

Then added a "**Convert Data Type**" action to turn the value into an integer.

I could then use "**Set a data value**" as normal.

Here is an export of my rule (for a different use case), but still setting Computed Field values as a Variable...

```
{ "rules_set_default_remaining_balance" : {
    "LABEL" : "Set Default Remaining Balance",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "entityform" ],
    "ON" : { "entityform_insert" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "entityform" ], "field" : "field_total_price" } },
      { "entity_has_field" : { "entity" : [ "entityform" ], "field" : "field_remaining_balance" } },
      { "data_is_empty" : { "data" : [ "entityform:field-remaining-balance" ] } }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : [ "entityform:field-total-price" ] },
          "PROVIDE" : { "variable_added" : { "variable_total_price" : "Total Price" } }
        }
      },
      { "data_convert" : {
          "USING" : { "type" : "integer", "value" : [ "variable-total-price" ] },
          "PROVIDE" : { "conversion_result" : { "conversion_result" : "Conversion result" } }
        }
      },
      { "data_set" : {
          "data" : [ "entityform:field-remaining-balance" ],
          "value" : [ "conversion-result" ]
        }
      }
    ]
  }
}

```

In the example above, the field "Total Balance" is being Computed.
> 0 votes

---
Tags: 7, entities, rules
---


# Question
Title: Where can I put helper functions for my theme?
I wrote few helper functions and now I want to add these functions somewhere, so that I can call them from any template files.

Where should I put them?

# Answer
> 0 votes
Helper functions is a bit vague for a description (so there may be better places where to put this, like a custom module), but theme functions are usually put into the `template.php` file of your theme.

It is not generally adviced to put much php code into your templates however (save for printing variables) - best practice usually calls for the use of alter hooks or other preprocess functions. Get a (small) overview here: template.php

---
Tags: 7, theming
---


title: Advagg and Nginx

text:
# Question
Title: Advagg and Nginx
I have the following errors displayed on my status report page:

```
Adv CSS/JS Agg - HTTP Request   HTTP requests to advagg for js files are not getting through.
AdvAgg will issue a request for a file that does not exist inside of the AdvAgg directory. If AdvAgg sends a 404, everything is ok; if something else sends a 404 then that means that AdvAgg will not be able to generate an aggregate if it is missing as something else is handling the 404 before AdvAgg has a chance to do it. If you are reading this, it means that something else is handling the 404 before AdvAgg can. Raw request info:

stdClass Object
(
    [request] => GET /sites/default/files/advagg_js/js__1407579810.js HTTP/1.0
Host: www.example.com
Connection: close
Referer: https://www.example.com/admin/reports/status
User-Agent: Drupal (+http://drupal.org/)

    [data] => <html>
<head><title>404 Not Found</title></head>
<body bgcolor="white">
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.4.6 (Ubuntu)</center>
</body>
</html>

    [protocol] => HTTP/1.1
    [status_message] => Not Found
    [headers] => Array
        (
            [server] => nginx/1.4.6 (Ubuntu)
            [date] => Sat, 09 Aug 2014 10:23:31 GMT
            [content-type] => text/html
            [content-length] => 177
            [connection] => close
        )

    [code] => 404
    [error] => Not Found
)

```

and

```
Adv CSS/JS Agg - HTTP Request   HTTP requests to advagg for css files are not getting through.
AdvAgg will issue a request for a file that does not exist inside of the AdvAgg directory. If AdvAgg sends a 404, everything is ok; if something else sends a 404 then that means that AdvAgg will not be able to generate an aggregate if it is missing as something else is handling the 404 before AdvAgg has a chance to do it. If you are reading this, it means that something else is handling the 404 before AdvAgg can. Raw request info:

stdClass Object
(
    [request] => GET /sites/default/files/advagg_css/css__1407579810.css HTTP/1.0
Host: www.example.com
Connection: close
Referer: https://www.example.com/admin/reports/status
User-Agent: Drupal (+http://drupal.org/)

    [data] => <html>
<head><title>404 Not Found</title></head>
<body bgcolor="white">
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.4.6 (Ubuntu)</center>
</body>
</html>

    [protocol] => HTTP/1.1
    [status_message] => Not Found
    [headers] => Array
        (
            [server] => nginx/1.4.6 (Ubuntu)
            [date] => Sat, 09 Aug 2014 10:23:31 GMT
            [content-type] => text/html
            [content-length] => 177
            [connection] => close
        )

    [code] => 404
    [error] => Not Found
)

```

I was thinking that this may be due to ubuntu/nginx handling the error messages before drupal could handle it. My questions are: 1. Is it correct?

1. If yes, how can I solve this error?
2. Will making drupal handle all 404 errors create any performance/security implications on the server? Will this improve the performance of the website?

Any help will be greatly appreciated.

Edit: Here is a link to my present nginx configuration file:

location: /etc/nginx/sites-available/www.example.com.vhost

http://pastebin.com/7Unp0qbc

# Answer
> 0 votes
Solved the problem by asking nginx to forward all 404s to drupal so that 404s can be handled at the level of drupal itself. So I added the following to my www.example.com.vhost file located at /etc/nginx/sites-available

```
error_page 404 /index.php

```

This will ensure that all 404s are handled by drupal. This made the error messages to disappear (even though now I am getting a

> Self Request Failure HTTP loopback requests to this server are returning a non positive response code of -1002

error which I think is unrelated).

# Answer
> 3 votes
Workflow of AdvAgg is (as far as I understand) is to create a file URL when it's needed, and create file itself when it's requested.

Your nginx should forward non-existing JS / CSS requests to Drupal. Configure it to do so, and you should be OK.

# Answer
> 0 votes
You can safely add this to your settings.php file.

```
   $conf['advagg_skip_404_check'] = TRUE;

```

It'll definitely help.

---
Tags: performance, css-js-aggregation
---


# Question
Title: How to find number of assigned content to all user
I have book content type, where i attached user entity reference fied. In which i can select user to assign the books.

How can i find list of users and its number of assigned books.

Thanks

# Answer
Basically you need to add the entity reference field using relationship to the view. Then use aggregation to find the count.

Refer https://www.ostraining.com/blog/drupal/entity-reference-views/ on how to create view using entity reference field. To find the count, you can use aggregation. For using aggregation you can refer https://drupal.stackexchange.com/a/31542/48290.
> 2 votes

---
Tags: views
---


# Question
Title: Add additional fields in Drupal 8 node edit form
With the functionality of core drupal 8 module I could view, edit nodes. But what I need is that I need to add some extra fields to the node edit form. Is there any method to do this ? Any help?

# Answer
> 2 votes
You can add fields to nodes both utilizing the UI and programatically.

To do it over the interface, go Structure \> Content Types (in the admin menu) - you will see a list of all node types currently available to your site. Find the node type you want to add fields to and hit 'manage fields' (preselected in the dropdown button to the right).

Now you can use 'add field' to add fields of any type you have enabled/downloaded from drupal. (If you don't have a whole lot of field types to select from, check if their modules are enabled under 'Extend'.)

---
Tags: 8
---


title: Taxonomy saving order on node

text:
# Question
Title: Taxonomy saving order on node
Coming from a different CMS, I am diving little by little into the Drupal philosophy and I have already bumped into a problem. (being a beginner sucks :/ )

I have installed the hierarchical select module to facilitate my user to add the taxonomies they want. But the user is not happy with the way that the list is displayed.

What I wanted to do is to find a way for the user to define the display (and thus the saving) order of the taxonomies on each node independently.

I thought of weights but that would have an impact on the taxonomy order and not the node.

I did a few searches on the fora and also googled a bit but I always go around the views related topics and I am not able to find a module that does this.

It might be impossible (I have no clue yet on how the taxonomies are saved and treated in the database) so I explain a bit more the situation as there might be a better solution or an alternative to what I am thinking.

In practice, my user wants to be able to choose out of a list of taxonomies one to be displayed before the others, and ideally to be able to arrange the rest of the terms at will.

eg.

```
node 1 -> Term3, term 2, term 5

node 2 -> Term1, term 5, term 6

```

The user suggested that could also "work" with 3 fields that define the order of the chosen terms but I find this solution very short term solution and will cause problems the day that I need to add a 4th or a nth field on the same node.

Any suggestion apart from creating my own module?

Thanks a lot for you input,

# Answer
Thanks for your input @JPMC. In the end I just used Simple Hierarchical Select and did what I wanted to do.
> 0 votes

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


title: Multi Column Menu

text:
# Question
Title: Multi Column Menu
Is there some easy way to create a multi-column (or grid) menu, eg:

```
item 1   item 4   item 7
item 2   item 5   item 8
item 3   item 6

```

There are no parents in this menu.

I would rather not install a module just to do this.

You can do it easily with views, is there no way built in to do it with menus?

# Answer
> 3 votes
You can change the menu twig with an additional row loop with 3 items per row:

**menu.html.twig**

```
  {% if items %}
    {% for row in items|batch(3) %}
    <ul class="row">
      {% for item in row %}
        <li{{ item.attributes }}>
        {{ link(item.title, item.url) }}
        </li>
      {% endfor %}
    </ul>
    {% endfor %}
  {% endif %}

```

This is a simplified version for only one level as your menu items have no parents.

# Answer
> 2 votes
There is no build-in way to set Drupal's menus to fill multiple columns from the UI, however, since menus in Drupal are html lists, you can use css to break them into multiple columns:

```
ul {
    -moz-column-count: 3;
    -moz-column-gap: 10px;
    -webkit-column-count: 3;
    -webkit-column-gap: 10px;
    column-count: 3;
    column-gap: 10px;
}

```

This will work in all browsers save Internet Explorer 9 or lower. If you need to support old versions of IE, you would need to use a little js helper like Columnizer jQuery Plugin or Modernizr.

The advantage of this approach is, that you can use media queries to set the number of columns to fit different devices/screen widths.

---
Tags: 8, navigation
---


# Question
Title: How to export all users with all custom fields?
I want to export users list with all custom fields. I have tried the Users Export module but its export only below fields:

* uid
* mail
* name
* created
* access
* login

Is there any solution to solve this problem?

# Answer
You can use the Drush Entity module:

> With drush entity you can query the entity system available for Drupal 8, 7 and (some of) 6.

**Getting all users with some fields:**

```
drush entity-read user `drush entity-read user` --fields=uid,mail,name,created,access,login

```

**Getting one user with all the fields:**

```
drush entity-read user 1 --fields=* --format=json

```

**Getting all the users with all the fields:**

```
drush entity-read user `drush entity-read user` --fields=*

```

**Getting some users with some fields:**

```
drush entity-read user 1 2 --fields=uid,mail,name,created,access,login --format=export

```

**Output (for the last command):**

```
 1  mail@gmail.com  admin  1353518169  1470089957  1469713365
 2  other@gmail.com  webadmin  1353518169  1470089957  1469713365

```

If you want to try with another options you can read this page: http://build2be.com/content/drush-entity-support-patch-needs-review
> 2 votes

# Answer
There are many option to achieve this.

You can create a user view and use Views data export module for export.

Another option to achieve this is Data export import module.
> 1 votes

# Answer
# Start from a Forena's sample report (Active users)

Install the Forena module (disclosure: I'm a co-maintainer of it) and start from the "Active Users" report (part of ***Drupal Administration*** report category) which is delivered with it. Here is a sample output of it:

```
+-----------+-----------------------+-------------------------+---------+
| User      | Email                 | Last Logged in          | Actions |
+-----------+-----------------------+-------------------------+---------+
| Webmaster | webmaster@example.com | Sun, 03/27/2016 - 18:39 | logs    |
| Admin     | info@example.com      | Thu, 04/07/2016 - 12:47 | logs    |
| Pierre    | pierre@example.com    | Fri, 04/01/2016 - 18:19 | logs    |
+-----------+-----------------------+-------------------------+---------+

```

# Refine the delivered report

Next, just customize this reports, or create a clone from it that fits your needs. For example by using the query writing tool that comes with Forena, which is called the **Forena Query Builder**. This is a separated (sub-)module which can be enabled as per standard Drupal instructions to enable an additional module. For a video tutorial about this query writing tool, checkout Define data blocks with optional filters. Add any of the "*custom fields*" (as in your question) you want.

# Set the report's export options

For the report you create, set the appropriate "document types" that fit your needs. Such as CSV, XLS, PDF, XLS, etc. For those document types you enable, an authorized report user will be able to click a hyperlink to export the report (in this case the list of users with the custom fields you added), in any of the formats you enabled within document types. Should you rather want JSON or XML format (as export format), that is also possible (just a slightly different approach, which is typically restricted to selected user roles only).
> 1 votes

---
Tags: 7, users, entities, importing-exporting
---


# Question
Title: Show specific fields in a list to everybody, but only registered user can see that node
My Drupal version is 7.50.

I want to show to anonymous user a list with a specific fields (title, image, body abstract), but when you click in title, the content of that node would only be available to registred users.

I tried combining Views to make that list with "Node Access" to limit access to node... but I'm lost. Surely, I'm doing something wrong.

Any suggestion about it? Thanx!

# Answer
I think Field Permissions is right module for you.

> **Features**
>
> * Enable field permissions on any entity, not just nodes.
> * Role-based field permissions allowing different viewing patterned based on what access the user has.
> * Author-level permissions allow viewing and editing of fields based on who the entity owner is.
> * Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields where this feature is needed.
> * Field permissions overview
> 0 votes

# Answer
If I understood properly.

Create a page view with your fields(which you want to show to all users) title, image, body abstract and set the access to all.

And give the node view access only to authenticated user.

Hope that will help.
> 0 votes

# Answer
The Field Permissions module CodeNext propose is nice because it will allow you to define witch fields are available for witch role.

However, it can be also really interesting for you to look at the Node Option Premium module, witch allow you to define roles with proper privileges to view the full content of the node. User without the proper permission will only see the teaser of your content and a message saying this content is reserved for members.

> When a node is published as premium content, only users with proper privileges may view the full content of the node.
>
> Non-premium users can still access premium nodes but only get the content rendered in teaser context, even when trying to view the full content. An additional message informs them that the content is available to premium users only.

You can also use both module together (Field Persmissions and NOPremium), and also have some fields shown to specific roles.
> 0 votes

---
Tags: 7, nodes, users
---


# Question
Title: Custom Region doesnt render at the same position
I have created a region in my theme that contains only menus. Each menu has its own visibility settings. For e.g. my main-menu is everywhere visible except at /blog/\* and my blog-menu only at /blog/\*. I use this as my main navigation bar region.

My issue is that i call this region in my `page.tpl.php` with

```
<section class="top-bar-section">
<?php //print zurb_foundation_links__topbar_main_menu($main_menu); ?>
    <?php print render($page['menu']);
    ?>
</section>

```

but the html structure that is printed is different to what I need. The following is what gets printed. As you can see its creating a new section with a list inside. I want to get that menu in the section that is currently empty (be aware that I'm printing it at the correct position in my tpl.). I also need to change its ID & CSS Classes.

```
<section class="top-bar-section"></section>
<section class="block block-system contextual-links-region block-menu block-system-main-menu">
        <ul class="menu">
             <li class="first collapsed"><a href="/rubelhp/lernumgebungen">Lernumgebungen</a></li>
             <li class="collapsed"><a href="/rubelhp/unterstuetzung">Unterstützung</a></li>
             <li class="collapsed"><a href="/rubelhp/foerderung">Förderung</a></li>
             <li class="collapsed"><a href="/rubelhp/projekte">Projekte</a></li>
             <li class="last collapsed"><a href="/rubelhp/kontakt">Kontakt</a></li>
        </ul>
</section>

```

I want to avoid to call the menu directly instead of the region. The reason behind it is as I wrote in the beginning the visibility settings. The region contains menus that differ by the URL.

# Answer
> 0 votes
You can override the block template use by your position (block--menu.tpl.php) directly in your theme folder. By default, the render of your menu must use block.tpl.php from the block module.

I recommend you to have a look at the Working with template suggestions page, and to enable the Theme debug mode to see witch template are used for your block menu.

After, to modify the Classes and the ID of your menu, I recommend you to work with template\_preprocess\_block hook to modify the block object before the render print it.

You can also have a look at the theme\_menu\_tree hook, to be able to modify a wrapper of the menu tree, depending on conditions (menu names). There is also a THEMENAME\_menu\_tree\__MENU\_NAME possible method, that work only for one specific menu.

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


# Question
Title: How can I differentiate between third-party and custom modules in the list of modules?
If I have administrative access to a Drupal site, I can see the list of the modules enabled for the site.

How can I differentiate between third-party and custom modules?

# Answer
You can just do this by looking at sites/all/modules folder - if the sitebuilder was a good one you will see two folders "custom" and "contrib". In modules administration page there is no simple way to differentiate between them.
> 2 votes

# Answer
Since custom modules are not hosted on Drupal.org, their .info files will not containing their version info. A module hosted on drupal.org (for example, the *Entity API* module) will contain the following information that a custom module will not have.

```
; Information added by Drupal.org packaging script on 2016-03-17
version = "7.x-1.7"
core = "7.x"
project = "entity"
datestamp = "1458222244"

```

So, in the *Version* column shown in admin/modules, you will not see any version number.

The *User flag* module you see in the screenshot is a custom module I created.
> 2 votes

# Answer
Use Hacked module to differentiate.

> This module scans the currently installed Drupal, contributed modules and themes, re-downloads them and determines if they have been changed. Changes are marked clearly and if the diff module is installed then Hacked! will allow you to see the exact lines that have changed.

If it is a custom module you can see that module in different color from "/admin/reports/hacked"
> 1 votes

# Answer
Or Use Module filter and have all of your custom modules in Custom package. Then you will be able to see all of the custom modules in Custom tab on admin/modules page.
> 1 votes

# Answer
If the Update manager module is enabled, you can simply go to the Available updates page (/admin/reports/updates).

Custom modules, not hosted by drupal.org, will not have information available and will be shown in grey.
> 1 votes

---
Tags: 7
---


# Question
Title: Is Search API module 'English-speaking' only?
I am developing a multilingual (English-Ukrainian) Drupal website using Entity translation module. Everything went smooth before I tried to use the search module. I have Search API, Database search, Search API Entity Translation and Search API Entity Translation Database Search enabled and configured.

As far as I understand, only the English version of content is being indexed. All search queries in Ukrainian have zero results.

As an experiment I added some English words to the page in Ukrainian and used them as search terms. To my surprise, the page containing these words immediately appeared in search results. Furthermore, when performing the same seach from the English version, the English version of the Ukrainian-language page containing these keywords was retrieved (there are no such keywords in English version).

Is it possible for Drupal search to index content in Ukrainian (or other cyrillic language)? Are there any guidelines or tutorials how to acheieve this in multilingual environment organized with Entity translation?

UPDATE:

Continue experiments. I have three nodes, all of them translated. After disabling "Search API Entity Translation Database Search" module the situation changed. Two of nodes have their Ukrainian versions indexed only, the third one has only English version indexed. I have re-indexed the website several times. All three nodes and their translations are similar.

# Answer
> 2 votes
You;d need to use the Search API Entity Translation module to have this work as expected.

Going further if you wanted more control of the system and were using Database based indexes you would also want to install Search API Entity Translation Database Search

---
Tags: i18n-l10n, search
---


# Question
Title: Cannot create hook_menu subitems with proper position in administrative menu
I would like to add an hook\_menu item and generate its expandable subitems under ubercart's 'admin/store/' path.

For now I have:

```
function activit_menu() {

  $items['admin/store/products-fabrics'] = array(
      'title' => 'Látky produktov',
      'access arguments' => array('access administration menu'),
      'type' => MENU_NORMAL_ITEM,
  );

      $items = array_merge($items, activit_generate_products_fabrics_menu_items());

    }

function activit_generate_products_fabrics_menu_items() {

  $products = activit_get_products_with_fabrics();

  $items = array();

  foreach($products as $product) {

    $items['admin/store/products-fabrics/'.$product['nid']] = array(
        'title' => $product['title'],
        'access arguments' => array('access administration menu'),
        'file' => 'd_forms.inc',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('activit_eshop_fabrics_of_products_form'),
        'type' => MENU_LOCAL_ACTION
    );

  }

  return $items;

}

```

But this code will create both 'products-fabrics' item and all its subitems at the same level in administration menu and 'admin/store/products-fabrics' item is not expendable. After clicking at 'products-fabrics' item you will see the same andimistration page as aftre clicking at 'admin/store' plus the subitems links at the top oft he page. I can hide this page with css an let only the subitems to be visible. But I need to create expandable 'admin/store/products-fabrics' item in order to be able to click directly at 'admin/store/products-fabrics/subitem'.

I was trying all the possible item types but no success. Is there something I am missing?

# Answer
I think the MENU\_LOCAL\_ACTION type for your sub-menus is not the good choice.

The Menu item types documentation tell us :

> MENU\_LOCAL\_ACTION : Menu type -- An action specific to the parent, usually rendered as a link.

If you want to have a menu with sub-menus, you need to also define a page call back for it. You can use the system\_admin\_menu\_block\_page, witch display a bloc with all the sub-menus links.

```
// Main menu link
$items['admin/store/products-fabrics'] = array(
    'title' => 'Látky produktov',
    'page callback' => 'system_admin_menu_block_page',
    'access arguments' => array('access administration pages'),
    'file' => 'system.admin.inc',
    'file path' => drupal_get_path('module', 'system'),
    'type' => MENU_NORMAL_ITEM,
);

// Sub menu links
$items['admin/store/products-fabrics/'.$product['nid']] = array(
    'title' => $product['title'],
    'access arguments' => array('access administration menu'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('activit_eshop_fabrics_of_products_form'),
    'type' => MENU_NORMAL_ITEM,
    'file' => 'd_forms.inc',
);

```
> 1 votes

---
Tags: 7, routes, hooks, ubercart, navigation
---


# Question
Title: Want to allow a form on another domain to submit registration to a drupal form
I know this is probably a bad idea/imposible, but have to ask. Is there a way to allow a form on domain "example.com" to submit to the user registration form on "example2.com/user/register".

# Answer
> 0 votes
I mean, it *has* to be possible, because if you don't turn on spam filters you'll get a bazillion fake accounts from automated bots. I'd play around with posting the values from your first site's form using drupal\_http\_request, something like: `drupal_http_request($second_site_url, array('method' => 'POST', 'data' => $querystring_from_form_values))`

---
Tags: forms
---


# Question
Title: How to obtain the complete list of available Drush Output Formats?
I'm trying to obtain the complete list of Drush Output Formats. I'm using drush 9.0-dev and in the Output formats section of the Drush Documentation it says:

> The list of formats shown is abbreviated; to see the complete list of available formats, run the help command with the --verbose option.

I tried `drush help --verbose`, but I can't find the information.

Is there another way to have access to this information?

# Answer
To see the verbose list of output formats use `help` with a command name. For example the help for the watchdog list command `drush help wd-list`:

Normally you get:

```
 --format=<json>                           Select output format. Available: table, csv, html, json, list, var_export, yaml.
                                           Default is table.

```

But if you use `--verbose`:

```
drush --verbose help wd-list

```

You get the full list:

```
 --format=<json>                           Select output format.
                                           All available values are:
                                            - table: A formatted, word-wrapped table.
                                            - config: A configuration file in executable php format. The variable name is
                                           "config", and the variable keys are taken from the output data array's keys.
                                            - csv: A list of values, one per row, each of which is a comma-separated list of
                                           values.
                                            - html: An HTML representation
                                            - json: Javascript Object Notation.
                                            - labeled-export: A list of php exports, labeled with a name.
                                            - list: A simple list of values.
                                            - php: A serialized php string.
                                            - print-r: Output via php print_r function.
                                            - var_export: An array in executable php format.
                                            - variables: A list of php variable assignments.
                                            - yaml: Yaml output format.
                                           Default is table.

```

To get a global detailed list of all formats defined in drush you can use the drush function outputformat\_drush\_engine\_outputformat():

```
drush ev 'var_dump(outputformat_drush_engine_outputformat())'

```

***EDIT:***

If you want to see only the format names you can use:

```
drush ev 'print_r(array_keys(outputformat_drush_engine_outputformat()))'

```

**Output:**

```
[0] => table
[1] => key-value
[2] => key-value-list
[3] => json
[4] => string
[5] => message
[6] => print-r
[7] => var_export
[8] => yaml
[9] => php
[10] => config
[11] => list
[12] => nested-csv
[13] => csv-or-string
[14] => csv
[15] => variables
[16] => labeled-export
[17] => html

```
> 3 votes

---
Tags: drush
---


# Question
Title: Filter views on Current user OR Administrator
I have a total of 770 users, 760 with the custom role of `"certified provider"`, 10 with the role of `"certified administrator"`.

Using views, and relationships I am able to allow the certified provider to each see only their own created nodes. But I need the "certified administrator" to see ALL nodes from ALL providers. I have a `relationship of Content:Author`, and `filter of User:Current`. I have read everything I can get my hands on to figure out what to do and where to go next.

Have tried to follow https://stackoverflow.com/questions/20840490/drupal7-filter-view-based-on-current-users-roles But haven't been able to get the filter values to work.

Any help would be greatly appreciated.

# Answer
> 1 votes
When dealing with multiple roles, make sure the access control module has all the correct control settings. In Admin-\>structure-\>Content Type-\>Access Control I had the `"View any **Content Type** content"` checked. As soon as I removed that, the suggestion by @Jimmy Ko, worked, Thanks Jimmy. Easy to overlook when you have 3 different places where the content type is limited.

---
Tags: views
---