# Question
Title: Display Suite: how can I generate a render array for a field that is not being displayed
What I'm doing is complicated, and there is likely to be a much better way to do it, so I'll try to go into some detail, and edit the question after the fact to tailor more closely to the final answer I get if the answer is to do something different.

Right now for my teaser view for nodes I generate a `generated_cover` field in code to allow me to fallback through a couple of potential sources of cover image. First there is a cover image field. If a user has uploaded a cover image for the node we use that. Second is a cover generated by the pdfpreview module, finally if neither of those are found, it returns a blank, which I then use with field formatter conditions in display suite to replace with a placeholder image. As you'll note from the code used for generating the fields below you'll note that they rely on \`$field\['build'\] to get the generated field.

```
/**
 * Implements hook_ds_fields_info().
 */
function MY_MODULE_ds_fields_info($entity_type) {
    if ($entity_type == 'node') {
        $fields = array();
        $fields['generated_cover'] = array(
            'title' => 'Generated Cover',
            'field_type' => DS_FIELD_TYPE_FUNCTION,
            'function' => '_MY_MODULE_ds_field_generated_cover',
            'formatters' => array(
                'standard' => 'Standard output',
            ),
        );
        return array('node' => $fields,);
    }
}

/*
 * Generate the output for the generated cover image field
 */
function _MY_MODULE_ds_field_generated_cover($field) {

    // Get information about the entity being rated and the formatter we're using.
    $entity = $field['entity'];
    $formatter = $field['formatter'];

    if (!empty($entity->field_doc_cover)) {
//        $output = "cover";
        $output = render($field['build']['field_doc_cover']);
    //    $output = render(entity_view('doc_publication_files', $entity->field_doc_cover, 'teaser', $entity->language));
    } else if (!empty($entity->field_doc_pub_files)) {
//        $output = "preview";
        $output = render($field['build']['field_doc_pub_files'][0]);
    } else {
        $output = "";
    }
    return $output;
}

```

This has worked fine for the teaser view, though the build variable is never populated if the field is disabled for the display, so I need to include the fields in the display and use field formatter conditions to hide them. Now I need to use the same fallback on the full display, and am running into an issue: I need to display the file field using a different formatter AND have the pdfpreview version as an option for the cover fallback. I used a dynamic field to bring a copy of the file field in and set up the formatter as I needed it to be, while still keeping the original file field as a hidden field set up to the pdfpreview format, but now no matter how I try to hide the original file field (with the pdfpreview formatter) and display the dynamic field, if the pdfpreview version is not completely disabled, the dynamic version will not show up.

I'm trying to fix this by not relying on the presence of the original field in my generated form anymore. I'd like `_MY_MODULE_ds_field_generated_cover` to produce and render an appropriate render array for the cover image if it exists (image at medium style linking to nothing) and produce and render an appropriate pdf preview for the first file if it exists and is a pdf file (again medium style). Otherwise it should return nothing. That way I'll be able to use my original file field in my displays without concern that they'll interfere with each other.

# Answer
> 1 votes
I got it worked out, so here is my new code that actually renders the image fields instead of relying on them being prerendered for me:

```
/**
 * Implements hook_ds_fields_info().
 */
function MY_MODULE_ds_fields_info($entity_type) {
    if ($entity_type == 'node') {
        $fields = array();
        $fields['generated_cover'] = array(
            'title' => 'Generated Cover',
            'field_type' => DS_FIELD_TYPE_FUNCTION,
            'function' => '_MY_MODULE_ds_field_generated_cover',
            'formatters' => array(
                'standard' => 'Standard output',
            ),
        );
        return array('node' => $fields,);
    }
}

/*
 * Generate the output for the generated cover image field
 */
function _MY_MODULE_ds_field_generated_cover($field) {

    // Get information about the entity being rated and the formatter we're using.
    $entity = $field['entity'];
    $image_style = ($field['view_mode'] == 'teaser') ? 'list_view_cover' : 'medium';

    if (!empty($entity->field_doc_cover)) {
//        $output = "cover";
        $display = array(
            'settings' => array(
                'image_style' => $image_style,
            ),
            'label' => 'hidden',
        );
        $to_render = field_view_field('node', $entity, 'field_doc_cover', $display);
        $output = render($to_render[0]);

    //    $output = render(entity_view('doc_publication_files', $entity->field_doc_cover, 'teaser', $entity->language));
    } else if (!empty($entity->field_doc_pub_files)) {
//        $output = "preview";
        $display = array(
            'settings' => array(
                'image_style' => $image_style,
            ),
            'type' => 'pdfpreview',
            'label' => 'hidden',
        );
        $to_render = field_view_field('node', $entity, 'field_doc_pub_files', $display);
        $output = render($to_render[0]);
    } else {
        $output = "";
    }
    return $output;
}

```

---
Tags: 7, entities, display-suite
---


# Question
Title: Sorting view results by the number of matched arguments (contextual filters)
I have nodes with tags on them. I also have a view of nodes with a contextual filter that can take multiple tags. I have it set to get nodes that match any, rather than all.

So imagine I have three nodes, Lorem, Ipsum, and Dolor. They have the following tags:

Lorem: foo, bar, baz Ipsum: foo, bar Dolor: foo

When the contextual filter "foo" is passed, of course all three come up. When "foo" and "bar" are both passed, all three also come up. Currently, they come up in no particular order, so passing "foo" and "bar" might give me this (depending on my other filters):

1. Dolor
2. Lorem
3. Ipsum

I want to sort by number of matched items, so passing "foo" and "bar" will bring them up in the order Lorem, Ipsum, Dolor or possibly Ipsum, Lorem, Dolor, but never with Dolor first. And if I pass all three terms I'd expect to see the only the order Lorem, Ipsum, Dolor.

This seems like a common thing to need, and yet searching has not yielded a ready-made solution. How would one go about implementing this with Views 3 in Drupal 7?

# Answer
> 3 votes
Following is one way to achieve the specified ordering

1. Add a relationship to taxonomy terms.

2. Turn on aggregation
3. Set the sort criteria to COUNT DISTINCT of taxonomy term reference field.

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


# Question
Title: Adding column in Views for completed submission plus several days
A have a table column using Views from Webform submission. The variable of this column is submission date \[completed\].

I need to create another column showing another date \[completed\] + 7 days.

I tried Global: Math expression \[completed\]+7 but it does show the correct date but another value.

How can I display \[completed\]+7 in another column.

# Answer
> 0 votes
I have solved my own problem. Using Views PhP module. Add field Global:PHP, in the output code box:

```
<?php
$correctdate = $row->completed;
$correctdate1 =strtotime("+7 days", $correctdate);
$cdate = date("j/n/Y - g:i a", $correctdate1);
echo ($cdate);
?>

```

---
Tags: views
---


# Question
Title: How to display a list of nodes in a block?
I have a custom block and I want to output a list of nodes of a certain type.

This is what I have so far:

```
public function build() {

$nids = \Drupal::entityQuery('node')
  ->condition('type', 'my_content_type')
  ->execute();

$nodes = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->loadMultiple($nids);

    return array(
      '#markup' => $this->t('How to display list here'),
    );
  }
}

```

How do I list the nodes by title and ordered by newest at the bottom of list?

# Answer
Unless you have a specific issue not mentioned in the question, I would recommend using a view to create this block. This would mean that the criteria remained easily editable.

If you had specific need to output the list of nodes within a custom block, or would like to pass arguments to the view from custom code you could use views\_embed\_view.
> 3 votes

---
Tags: nodes, 8, blocks
---


# Question
Title: VBO action on pending node revision (using Revisioning) publishes the revision
I have a View listing pending node revisions (using Revisioning). I have several actions, like changing the node author, which are executed using Views Bulk Operations. Executing, for example, the "Change author" action should update the author, *but* keep the revision in pending state. However, the revision gets published, and becomes the new, current revision.

Anyone else run into this issue? I've been digging around both VBO and Revisionings source code, but I cannot find out which one is to "blame". VBO is correctly loading the pending revision, and executing the action on it. Revisioning's node hooks are correctly invoked as well. Auto-publishing is disabled, and Revisioning does not get into that code flow (I put tracer code in there to make sure it doesn't). So this leads me to think VBO or Entity are at fault, but I can't put my finger on it.

# Answer
So, I found out where the issue is coming from.

Basically, Revisioning works as follows:

1. A node gets saved by Drupal. Drupal doesn't care much about the status. If the node is published, it remains published. It is important to realize that, when using Revisioning, if a node has a published revision, for Drupal the node has a status of 1, regardless of the pending, unpublished revision. Upon saving, Drupal simply stores a new revision, and updates the node database row, pointing the revision ID to this new revision.
2. Revisioning kicks in, with `revisioning_node_update()`. It checks the `revision_operation` property. Based on its value, it "reverts" what Drupal just did, setting the revision ID in the node table back to the previous revision. This is what keeps the published revision one step behind the pending revision.

Now, this `revision_operation` property is only set when in context of a node form. When using VBO (or any way to trigger actions, for that matter), Revisioning doesn't see the `revision_operation` property, and `revisioning_node_update()` doesn't revert the revision ID.

We could patch this in Revisioning, but the project hasn't received much attention lately (for the D7 version). So this is how I solved it (I have several actions, but I'll give the example of the `node_assign_owner_action` action):

```
/**
 * Implements hook_action_info().
 */
function mymodule_action_info() {
  return array(
    'mymodule_assign_to_user_action' => array(
      'type' => 'node',
      'label' => t("Assign to user (Revisioning compatible)"),
      'configurable' => TRUE,
      'behavior' => array('changes_property'),
      'triggers' => array('node_presave'),
    ),
  );
}

/**
 * Assign a node to a user.
 *
 * We need a custom action for this, as actions are not entirely compatible with
 * Revisioning. We need to tweak the node a bit to force a pending revision to
 * stay that way. node_assign_owner_action() does not allow this. See
 * _mymodule_actions_reset_revision_operation() for an explanation on why we
 * need this.
 *
 * @see node_assign_owner_action()
 * @see node_action_info()
 */
function mymodule_assign_to_user_action($node, $context = array()) {
  // Simply proxy to node_assign_owner_action().
  node_assign_owner_action($node, $context);

  // Make sure the revision_operation property is correctly set.
  _mymodule_actions_reset_revision_operation($node);
}

/**
 * Configuration form for mymodule_assign_to_user_action().
 *
 * @see mymodule_assign_to_user_action()
 * @see node_assign_owner_action_form()
 */
function mymodule_assign_to_user_action_form($context = array()) {
  return node_assign_owner_action_form($context);
}

/**
 * Validation callback for mymodule_assign_to_user_action_form().
 *
 * @see mymodule_assign_to_user_action()
 * @see node_assign_owner_action_validate()
 */
function mymodule_assign_to_user_action_validate($form, $form_state) {
  node_assign_owner_action_validate($form, $form_state);
}

/**
 * Submission callback for mymodule_assign_to_user_action_form().
 *
 * @see mymodule_assign_to_user_action()
 * @see node_assign_owner_action_submit()
 */
function mymodule_assign_to_user_action_submit($form, $form_state) {
  return node_assign_owner_action_submit($form, $form_state);
}

/**
 * Set the correct node revision_operation property.
 *
 * @param object $node
 *    The node on which the action is performed.
 */
function _mymodule_actions_reset_revision_operation($node) {
  module_load_include('inc', 'revisioning', 'revisioning_api');

  $is_moderated_content = isset($node->revision_moderation) ?
    $node->revision_moderation :
    revisioning_content_is_moderated($node->type, $node);

  $node->revision_operation = (int) $node->is_pending + (int) $is_moderated_content;
}

```

Thanks to this, we can still use actions provided by core or other modules, but we need to *wrap* them in another, Revisioning compatible action. When calling `_mymodule_actions_reset_revision_operation()`, we use the same logic as Revisioning is using when altering the node form.

It now works.
> 0 votes

---
Tags: 7, views, actions
---


title: Create top 5 of selected options

text:
# Question
Title: Create top 5 of selected options
I would like to create a top 5 of selected options from a webform.

As users fil in the webform i would like to create a view with the top 5 selections of the list. How can i do this with views?

Example: i have a webform with 5 options.

a,b,c,d,e

User get a dropdown to choose 1 or multiple options.

When 10 users have filled out the form these are the results

option a is chosen 4 times option b is chosen 7 times option c is chosen 2 times option d is chosen 1 time option e is chosen 9 times

How can i create a view that show this

Top 5 of selected options: Option e Option b Option a Option c Option d

Kind regard Kevin

# Answer
You can create a view with webform type. Then add a Global PHP field in header.

```
<?php
$nid=62;
$option1_count=0;
$option2_count=0;
foreach($results as $results1) {
    $each_submission=webform_get_submission($nid, $results1->sid);
    //print_r($each_submission->data);
    if($each_submission->data[1][0]==1) {
        $option1_count++;
    }
    if($each_submission->data[1][0]==2) {
        $option2_count++;
    }
}
$top=[$option1_count,$option2_count];
arsort($top);
?>

```

I haven't tested this code but something like this should work.

**EDIT**:

You can make that code generic but if you don't want that then use grouping and aggregation in views and try Views Distinct

First add field Webform submission data:Value(your webform field) and set aggregation to yes. This will help.
> 0 votes

---
Tags: views, webforms
---


# Question
Title: Drush cc gives only two options even when I am in root folder
I am working with `drupal 8, MAMP version 3.5, and drush version 8.1.3`. I have **installed drush globally** and when I enter `drush st` it gives me complete information and shows that drush is installed but when I run `drush cc`, it gives me only two options

1. cancel
2. drush

whereas, it is suppose to give me many options. I am in a root folder of the site I am working on .i.e. `/Applications/MAMP/htdocs/mysites/mysite`. My OS is OSX on macbook pro, just in case if this is mac specific issue.

Done with this step as well:

sudo ln -s /Applications/MAMP/tmp/mysql /var/mysql

Not sure what else to look into, can you anyone please guide? I am new to drush, terminal and mac

# Answer
> 1 votes
Use `drush cr` (container rebuild) rather than `drush cc` (clear cache) for drupal 8.

# Answer
> 0 votes
I found a solution which worked for me on this link : https://www.drupal.org/node/1016268#comment-10466949

And the proposed solution on comment # 31 was:

1. Add this to your .bash\_profile `export PATH=/Applications/MAMP/Library/bin/:$PATH`
2. run this then in terminal `source ~/.bash_profile`

It ended my 3 days search to resolve my issue.

---
Tags: drush
---


# Question
Title: Views Data Export: How can you include a raw database column?
I'm running a data export (using Views Data Export) on some comments and I'd like to include the `thread` column in the result. The only thing I can see is a `Depth` field, which doesn't contain the detailed thread information needed to re-render the comments in the correct order. Is it possible to include the `thread` database column in the results?

Many thanks

# Answer
Table column will not be automatically imported as available views field. Any extra field you want to use in views. You can define it with `hook_views_data`. Anyway, I can find pretty much fields are ready to use.
> 0 votes

---
Tags: views, database, comments, importing-exporting
---


# Question
Title: How do I sort the list of modules by the number of open issues?
Is there any option to sort the list of modules on drupal.org by the number of issues?

# Answer
> 3 votes
No, there isn't.

The number of issues isn't really relevant because you need to see what type of issues there are (cosmetic / blocking), how actively the module is maintained, how many maintainers, etc.

Big modules can have a lot of issues, but if they are frequently updated it's no problem. If a module has only one (blocking) issue but it isn't resolved due to lack of maintenance than it's worse.

---
Tags: community-official-site
---


# Question
Title: why the search result shown in default language only ?
i have a multilingual site with 2 languages and i have a search view , the search view works well in (english) and give me the result but when am changing the language to the second one ( arabic ) its give me the same result that i want but in english !!

English version:

Arabic version:

any suggestion to solve this problem ?

# Answer
> 0 votes
You should add a filter "Indexed node: language" and set it to "Current user language". This should be enough to ensure the results are shown in the current language.

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


# Question
Title: How to show a message to a list of article publishers using Rules?
I am trying to send a simple message **to each user** in a list of particular users (article publishers) on the site, using the Rules module.

More specifically:

1. **Event:** After saving new content
2. **Condition:** Content is of type: Article
3. **Action:** Load a user list with views (using Rules Bonus pack - user list of article publishers)
4. **Action:** Loop (above user list)
5. **Loop action:** Show a message on the site

But with above configuration:

1) the only user who's getting the message is the current article publisher and

2) the message is displayed x times where x is the number of users in the user's list.

Apparently something is missing and/or the rule has mistakes.

Can anyone help?

# Answer
> 3 votes
The loop isn't checking for the current user, so it is showing a message for all the users in the list, like you describe.

You need to check that the current user is in that list.

To do so you really need the http://drupal.org/project/rules\_conditional module. It allows you to have conditions in actions.

So your rule would be something like this:

```
Event: After saving new content
Condition: Content is of type: Article
Action: Load a user list with views (using Rules Bonus pack - user list of article publishers)
Action loop: Loop (above user list)
  Conditional:
    If: Data comparison (Parameter: Data to compare: [site:current-user:uid], Data value: [list-item:uid])
      Action: Show a message on the site

```

However, if you say that the list of users is any user that has created an article, and this message is being displayed after a user creates an article, then you can be sure the user who just created the article is in the list of users who have created an article :) So just show the message when an article is created. No other checks for users.

# Answer
> 1 votes
To my knowledge, Rules Action `Show a message on the site` is always targeted to the current user (how would you show a message to a user not logged in to your site?). And if this is done within a loop, like "*for all users in the users list*" (as in your question), then such message will indeed be "*displayed x times where x is the number of users in the users list*" (as in your question). So I don't think you can get this to work like you're trying to do. So far the bad news ... read on for good news ...

Instead of using the Rules Bonus Pack, and Rules, you could use the Menu Badges module for such notifications, which you can add to any **menu item** and/or **menu tab** of your choice. In your case something like "***New articles***" seems like an appropriate menu item (or menu tab).

Here are some details about it (from its project page):

> Provides a method for adding iOS-style badges to menu items. (see screenshot)
>
> ### Adding Badges to Menus
>
> Once enabled, go to `Administration > Structure > Menus`, and click "list links" next to the menu containing the target item. Click "edit" next to the item and select the badge to display with the Display Menu Badge select box.
>
> ### Adding Badges to Tabs
>
> For adding badges to menu tabs, there is a tab under `Administration > Structure > Menus` called "Tab Menu Badges". Search for the menu router path of the tab you want to alter, then select a badge from the corresponding select box.
>
> ### Badge Types
>
> The module includes five example badges, and new badges can be created easily with Views. Modules can also supply their own badges with a hook implementation. See the README.txt file for details.

Because of how it integrates with the Views module, by using this integration you basically reduce the solution for any type of notification to something like "Just create an appropriate view of it".

However, there is a small caveat: if you really want the actual number (shown in the red circle) to be accurate, make sure you have some field in your view that will actually correspond to the "`After saving new content`" part of your question (as in your Rules Event). To better explain this: have a look at the "`tracker`" view (disabled by default), which has the field "***Content:Has new content***" (or variation: "***Content:Has new comments***"). This is a perfect field to use if you want to use Menu Badges to get notified whenever there is new content (or variation: new comments).

### Video tutorials:

---
Tags: 7, rules
---


title: How to make a composite content type

text:
# Question
Title: How to make a composite content type
I would like to create a content type that has some unique fields but its other fields are references to other existing nodes (not a parent-child relationship but many to many relationship).

I have looked in entity reference module or field collection? Is there another way of doing this?

For example I have a synthesis report made up of smaller topics. I want this report to have a name and author but then it needs to reference multiple of these smaller topics (which are a content type of their own).

I could maybe make a Taxonomy term for every synthesis report?

# Answer
> 3 votes
The simplest way is to use the Entity Reference module. You can add fields to your content type which are a reference to other entities, like taxonomy terms, nodes, etc.

**Note**: You can combine it with field collection, but you need to understand that a field collection is not the same thing. A field collection lets you group fields so you can re-used them. For instance if you have multiple addresses, you can create a field collection with street, zipcode, city, etc. But in itself, it's not an entity. Entity reference lets you point from one entity to another.

# Answer
> 3 votes
You can use both References and Entity Reference module, then you can add a Reference field (Node Reference if using References module) or Entity Reference (in case of using Entity Reference module) , and then **set the number of values for that field to 'Unlimited'** (if you don't know how many references is needed for each report exactly).

##

PS. Entity References is more complicated to work with but it presents much better features in comparison by References Module.

---
Tags: 7, nodes
---


# Question
Title: Custom field type validation in field type definition class
**Scenario**: I created custom field type and need to add my own custom constraint/validation prior to saving.

**Problem**: failed to add custom constraint plugin so I implemented the function in

```
public function preSave() {
$return = $this->custom_check($this->value, $this->getSetting('check_options'));
if(!$return[0]){
  drupal_set_message($return[1]->__toString(), 'error');
  $url = \Drupal::service('path.current')->getPath();
  $response = new RedirectResponse($url);
  $response->send();
  exit;
}
}

function custom_check($value, $check_options){
//checking goes here
}

```

I user **drupal\_set\_message()** and **RedirectResponse** as I couldn't get the $**form** or $**formState** of the **node/%nid/edit** to set the error at field and dor form rebuid.

I know that solution is not the best practice and I have to create my own constraints and validation but I spent time with no luck to work and I didn't found a working example that suits my case escpicially I need to validate based on field settings so I have to pass two parameters **value** and **setting**.

Please help getting the current form array and formstate in presave to rebuild instead of redirect. or show me how to write simple constraint that takes parameters and how to add it to my custom defined field type.

Thanks in advance.

# Answer
> 1 votes
Form validation checks the user input before it gets submitted. The submitted values don't necessarily go into the database, they can be used for other things. Presave can check values before they are stored in the database. The values don't need to come from a form, they can be generated by other code. So those two things are not connected.

If you want to validate a form, you have to use form validation. Presave doesn't know about forms. It is no problem to double check in presave, then you prevent wrong values to enter into the database from any code. But if you want to give the user a feedback in the form, use form validation. In presave you can only throw an exception after submit.

---
Tags: 8, entities
---


title: REST - Could not find controller on PUT

text:
# Question
Title: REST - Could not find controller on PUT
I'm trying to update a node via REST PUT but failing with the "404 controller not found" error. I have tried everything I know of but still getting the same error.

(No problem on retrieve / index)

Module:

```
function demoapp_feedback_update($edit, $account, $category) {
  cache_clear_all('demoapp_device_validate_pairing_' . $account->uid, 'cache', TRUE);
  cache_clear_all('demoapp_feedback_load_feedback_article_', 'cache', TRUE);
  cache_clear_all('demoapp_feedback_find_feedback_articles', 'cache', TRUE);
}

function demoapp_services_resources() {
  return array(
 'demoapp_feedback' => array(
  'retrieve' => array(
    'help' => 'Retrieves a feedback article',
    'file' => array('type' => 'inc', 'module' => 'demoapp', 'name' => 'resources/feedback_resource'),
    'callback' => 'demoapp_resources_feedback_retrieve',
    'access callback' => 'demoapp_resources_feedback_access',
    'access arguments' => array('retrieve'),
    'access arguments append' => TRUE,
    'args' => array(
      array(
        'name' => 'article_id',
        'type' => 'int',
        'description' => 'The id of the feedback article to get',
        'source' => array('path' => '0'),
        'optional' => FALSE,
      ),
      array(
        'name' => 'view_mode',
        'type' => 'int',
        'description' => 'Defines what data fields to return',
        'source' => array('param' => 'view_mode'),
        'optional' => TRUE,
        'default value' => 0,
      ),
    ),
  ),
  'index' => array(
    'help' => 'Retrieves a listing of feedback articles',
    'file' => array('type' => 'inc', 'module' => 'demoapp', 'name' => 'resources/feedback_resource'),
    'callback' => 'demoapp_resources_feedback_index',
    'access callback' => 'demoapp_resources_feedback_access',
    'access arguments' => array('index'),
    'access arguments append' => TRUE,
    'args' => array(
      array(
        'name' => 'view_mode',
        'type' => 'int',
        'description' => 'Defines what data fields to return',
        'source' => array('param' => 'view_mode'),
        'optional' => TRUE,
        'default value' => 0,
      ),
      array(
        'name' => 'checksum',
        'type' => 'string',
        'description' => 'Checksum of the local data',
        'source' => array('param' => 'checksum'),
        'optional' => TRUE,
        'default value' => NULL,
      ),
      array(
        'name' => 'offset',
        'type' => 'int',
        'description' => 'Offsets a list by X number of items',
        'source' => array('param' => 'offset'),
        'optional' => TRUE,
        'default value' => 0,
      ),
      array(
        'name' => 'limit',
        'type' => 'int',
        'description' => 'Limits a list by X number of items',
        'source' => array('param' => 'limit'),
        'optional' => TRUE,
        'default value' => 10000,
      ),
    ),
  ),
  'actions' => array(
    'update_poll' => array(
      'help' => 'Update a poll',
      'file' => array('type' => 'inc', 'module' => 'demoapp', 'name' => 'resources/feedback_resource'),
      'callback' => 'demoapp_resources_feedback_update_poll',
      'access callback' => 'demoapp_resources_feedback_access',
      'access arguments' => array('update_poll'),
      'access arguments append' => TRUE,
      'args' => array(
        array(
          'name' => 'node_id',
          'type' => 'int',
          'description' => 'The id of the node',
          'source' => array('data' => 'node_id'),
          'optional' => FALSE,
          'default value' => 0,
        ),
        array(
         'name' => 'vote',
         'type' => 'int',
         'description' => 'The vote chid',
         'source' => array('data' => 'chid'),
         'optional' => FALSE,
        ),
      ),
    ),
  ),
),

```

(Inc: nothing to see here)

Resource:

```
function demoapp_resources_feedback_update_poll($node_id, $chid) {
  global $user;
  global $demoapp_device;

  if (demoapp_validate_not_empty($node_id)) {
    if (!demoapp_validate_not_empty($node_id) || !demoapp_validate_not_empty($chid)) {
  services_error(RESOURCE_ERROR_400_MESSAGE, 400);
    }
  }
  //

  $retrievedVoteID = $chid;

  $node = node_load($node_id);
  $node_wrapper = entity_metadata_wrapper('node', $node);

  $selectedVote = $node_wrapper->poll[$chid]['chvotes'];
  $newVote = (int)$selectedVote + 1;

  $node_wrapper->poll[$chid]['chvotes']->set($newVote);
  $node_wrapper->save();

  watchdog('Poll update', 'Retrieved poll update query', $variables = array(
    'Node id' => $node_id,
    'Node object' => $node,
  ), $severity = WATCHDOG_NOTICE, $link = NULL);

  // Event (POLL_VOTE)
  $event = new demoappEvent();
  $event->type = 'POLL_VOTE';
  $event->name = NULL;
  $event->device_id = ($demoapp_device && $demoapp_device->device_id) ?       $demoapp_device->device_id : NULL;
  $event->user_id = $user->uid;
  $event->registered = time();
  $event->created = time();
  $event_id = demoapp_event_create_event($event);

  if (!$event_id) {
    services_error(RESOURCE_ERROR_500_MESSAGE, 500);
  }
  //

  return array('status' => 'SUCCESS:DONE');
}

function demoapp_resources_feedback_access($op, $args) {
  global $user;

  // Authenticate
  demoapp_services_authenticate();
  //

  $access = FALSE;

  switch ($op) {
    case 'retrieve':
      $access = user_access('access demoapp content');
      break;

    case 'index':
      $access = user_access('access demoapp content');
      break;

    case 'update_poll':
      $access = user_access('access demoapp content');
      break;
  }

  return $access;
}

```

Output:

```
Failed to load resource: the server responded with a status of 404 (Not found : Could not find the controller.)

```
* Services & ops enabled
* Index/retrieve works
* Authenticated
* Permissions set up properly

Thanks for your time.

Edit: JS function

```
postOpinion: function(data, onProgress, onSuccess, onAbort, onError){
    var httpHeaders = demoapp.auth.getHttpHeaders();

    var params = {
        node_id: data.nodeId,
        chid: data.vote
    };

    console.log('Params: ', params);

    demoapp.feedbackRemote.restClient.call(config.serverURL + '/' + config.serviceEndPoint + '/demoapp_feedback/update_poll', JSON.stringify(params), {requestMethod: 'PUT', requestDataType: 'application/json', httpHeaders: httpHeaders, responseDataType: 'json'},
        function _onProgress() {
            onProgress(demoapp.feedbackRemote.restClient);
        },
        function _onSuccess(result) {
            onSuccess(result.status);
        },
        function _onAbort() {
            onAbort();
        },
        function _onError(error) {
            console.log('Error: ', error);
            console.log('Sent url: ', config.serverURL + '/' + config.serviceEndPoint + '/demoapp_feedback/update_poll', JSON.stringify(params));
            onError(error);
        }
    );
},

```

# Answer
> 1 votes
**PUT** method is only work for creating item, but you didn't define `create` operation in `hook_services_resources`.

If you want to update node, please use **POST** method and define `post` operation instead.

```
function demoapp_services_resources() {
  return array(
  'demoapp_feedback' => array(
    'create' => array(
      // your custom code
    ),
    'update' => array(
      // your custom code
    ),
  );
}

```

---
Tags: services, updating, 8
---


# Question
Title: How to use Rules for sending an email to all users with same field value in some select list?
When users registers on my site, they choose their *State of Origin*.

Using Rules I would like to configure a rule which sends an email to all users from the same state when a user from that state edits his/her profile.

Is this possible using Rules or is there another approach?

# Answer
Without knowing anything about your entity & field setup I can't give you an exact rules that will work however it is possible and I can give you a pseudo rule:

* Install the rules bonus pack module.
* Install the rules conditional module (I think you need this but I'm not actually looking at a site to confirm).
* Create a view that lists all users with a contextual filter of the state field. - So when you call the view with a specific state you get all users who have selected that state.
* **Event**: Before user profile is saved.
* **Action**: Rules bonus pack action "Load a user list with Views". Use the user email list view from earlier and pass in the value of the state from the new user object (from after the edit).
* **Action**: Loop through the user list you loaded from the view.
* **Action**: In the user list loop send an email to the loop user object.

This will also send an email to the user who is actually changing their profile. if you want to exclude them you can either add more conditions in the rule to check against the edited user object or you can add another contextual filter to the view for uid, check the box in that contextual field to exclude that user from the results and then also pass in the uid as a contextual filter in the rule.

I would do that latter because it is a less complex rule and I would assume it would use less resources to run.
> 4 votes

# Answer
Yes this is possible with Rules, if combined with Views Bulk Operations, as further detailed below ...

What you actually need to do is similar to what is shown in the video about Using VBO to load list of objects into Rules, starting from about 5:30, up to 11:30. Here is a summary of what is shown in this video (quote from the linked page):

> * You need a view that lists the entities you want to work on in Rules. Note that you don't need a display of the view – and it might even be better not to have one if you don't want the view to be displayed somewhere.
> * However, you need one bulk operations field. The type of bulk operations field determines what entity type will be sent to Rules. Note that you don't need any actions enabled for the field – it is enough that it is present.
> * You need a rule that, as an action, loads entities from a VBO. (This is available under the "Views bulk operations" group.) All view displays with at least one VBO field will be selectable.
> * The action provides a list of entities, that can be used just like other lists in Rules. Combine with loops, actions and Rules Scheduler to make awesomeness happen.

In your case you want to start from a VBO list of all the users you want to get processed (= "*all users from the same state*", as in your question). And for each user in the list you want the Rules Action to be "send an eMail" (instead of "remove sticky").

Easy, no? Happy VBO-ing with Rules ... ( or Rules-ing with VBO if you prefer)!
> 1 votes

---
Tags: rules, emails
---


# Question
Title: How to have a Conditional Field in node form?
My goal is to hide the field until certain value in another field is selected in the node edit form. Is there a way for achieve that?

# Answer
You have the Conditional Fields module that works very well in Drupal 7, unfortunately there is not a Drupal 8 version, you can check this issue to find out its progress. If you want you can test the dev version, but I don't know if it works.

Other module in dev is the Field States UI

> Field States UI allows sites builders with minimal PHP/Dev skills to configure the Field States API. This lets you configure a field to for example hide if another field has a certain value or hasn't been filled. While doing it via PHP can be be more powerful the UI can be very handy and in some cases quicker.

In the other hand you can make use of the #states property.

**EDIT:** As the OP says in the comments there is another module named Field Formatter Condition that can be used for accomplish this task.
> 6 votes

---
Tags: 8, forms
---


# Question
Title: How can I Pass a javascript variable value to PHP in Drupal 7
I am currently working on a project where i am required to pass Javascript variable value to php, i am able to do it vice-versa but unable to accomplish, this one. Is there any way to get this done in Drupal 7 ?

# Answer
If you want to pass the value during loading page. You can do it by appending the JS value as query variable in path (e.g. http://www.example.com/new/page?demo=true) for requesting the next page. In PHP, you can use API `drupal_get_query_parameters` to read the data.

```
// retrieve data from www.example.com?data=value
$query = drupal_get_query_parameters();
$value = $query['data'];

```
> 1 votes

# Answer
You can do it via a AJAX call. First you need to create a custom module, with a hook\_menu() implementation. Then you can call that path via AJAX and process the value with PHP. Don't forget to filter the user input ;-)
> 0 votes

---
Tags: javascript
---


# Question
Title: How can I get the url from an user selected image?
**Version: Drupal 8**

I want to make the header region of my drupal customizable. The region consists of a title and a background image. I want the user to upload an image or select an image. That has to be echoed into the background: url("test.jpg");.

```
<div style="background: url(Image url)">

```

This should be available on every page except the homepage. I have tried some solutions for older versions of drupal but I couldn't find one for drupal 8.

# Answer
I just fixed it by using:

```
{{ file_url(node.field_image.entity.fileuri) }}

```

in combination with imce. IMCE had an option of selecting from the server as an extra option on top of the uploading functionality.The function

```
 node.field_image.entity.fileuri

```

got the url of the field: field\_image. This is where I found it: link
> 1 votes

---
Tags: theming, 8
---


title: How to add a view mode for entity type?

text:
# Question
Title: How to add a view mode for entity type?
I want to add a view mode for particular entity type programmatically in Drupal 8.I think the documentation on view modes for Drupal 8 has not been provided like it was provided for Drupal 7 hence I am facing problem in implementing this.Any reference from module in core would help.Thanks

What needs to be done if I want to add view modes to many entities?

# Answer
> 16 votes
View modes are configuration entities.

Like anything else that is a config entity, it's very simply to put into "code": Make it default configuration. Create it in the UI, do a configuration export (`admin/config/development/configuration/single/export`), and then place `core.entity_view_mode.$entity_type.$view_mode.yml` file into `config/install` inside your module.

The view mode will then automatically be imported and created when the module is installed.

Note that it's not hardcoded then, so a user could remove it. If you want to prevent that, you can implement `hook_entity_view_mode_access()` to deny delete access to your entity for everyone.

By default, you will have a problem re-installing the module because it will not remove that view mode when you uninstall the module and display an error when you install it again. There are two ways to fix that:

* Move the config to config/optional instead of config/install. Then it will only be created if it doesn't exist yet.
* Add an enforced dependency on your module, which will ensure that it will be removed when the module is uninstalled. Note that this only works if you had this in place when you installed the module the first time.

Like this:

```
  dependencies:
    enforced:
      module:
        - yourmodule

```

# Answer
> 6 votes
To create a **View mode** in Drupal 8 (i.e. a custom `manage display`), this can now be accomplished through the UI:

`admin/structure/display-modes/view`

Or if you'd like to programatically provide a **View mode** with your module, follow these steps:

1. Create a custom module
2. Create a `config/install` directory within your module
3. Inside of `config/install`, create a file called `core.entity_view_mode.node.my_module.yml`

Then inside of `core.entity_view_mode.node.my_module.yml` add this:

```
langcode: en
status: true
dependencies:
  module:
    - node
    - my_module
id: node.my_module
label: 'My Module'
targetEntityType: node
cache: true

```

Then install your module (you'll have to uninstall and then re-install your module if it is already installed). You'll now have a custom view mode that can be enabled for all of your content types.

To support other types of entities (e.g. comment, user) just create a new `.yml` file and replace occurrences of `node` with your desired entity type.

# Answer
> 1 votes
```
$entity_type="node"; //The entity for which you want to create the view mode
$view_mode="example"; //The name of the new view mode
$settings=Array();
$settings["id"]=$entity_type.".".$view_mode;
$settings["targetEntityType"]=$entity_type;
$evm=Drupal\Core\Entity\Entity\EntityViewMode::create($settings);
$evm->save();

```

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


# Question
Title: How to prepend a text of string to a content_type's field?
For my assignment I have to write a module that when enabled will prepend a text of string "Hello World" to the body of a text field of hello\_world\_article content type.

I first tried to use Drupal 8 config export to try to set a default value (hello World) by using a yml file. However I get an error enabling the module that " field.field.node.hello\_world\_article.body already exists in active configuration."

My yml file is:

```
uuid: 42c51471-d897-4cb1-ac37-b2b6cddc6f0e58
langcode: en
status: true
dependencies:
  config:
    - field.storage.node.body
    - node.type.hello_world_article
  module:
    - text
_core:
  default_config_hash: e_0gHBXrh9sHHe-XksjIYpOmFEiugHbtoJdYPxbftAI
id: node.hello_world_article.body
field_name: body
entity_type: node
bundle: hello_world_article
label: Body
description: ''
required: false
translatable: true
default_value:
  -
    summary: ''
    value: "<p><em>Hello World!</em></p>\r\n\r\n<p> </p>\r\n"
    format: basic_html
default_value_callback: ''
settings:
  display_summary: true
field_type: text_with_summary

```

How else would I get about approaching this problem. Help would be much appreciated.

# Answer
> 0 votes
Create a template override for the field. Because it sounds like a class assignment, I'll leave the actual coding to you.

---
Tags: entities, 8
---


# Question
Title: How to create entity reference field from custom entity to another custom entity?
I'm on Drupal 8 and I created a custom entity `custom_entity_one` following the Drupal 8 examples, the `content_entity_example` module. Now, in another custom entity, `custom_entity_two` I'm trying to create a `BaseFieldDefinition` like so:

```
$fields['cid'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('custom_entity_one ID'))
  ->setSettings(array(
    'target_type' => 'custom_entity_one',
    'multiple' => TRUE,
    'handler' => 'default'
  ))
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'type' => 'id',
    'weight' => -1,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'entity_reference_autocomplete',
    'settings' => array(
      'match_operator' => 'CONTAINS',
      'size' => 60,
      'placeholder' => '',
    ),
    'weight' => -1,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

```

In the add form of the `custom_entity_two`, the reference field appears, however, it doesn't find any value, even though I have multiple entities of type `custom_entity_one`.

I thought that it will look for the `label` propriety of the entity, but it doesn't seem so. What I am missing ? Should I create a custom handler ? I'm not very sure how.

# Answer
> 2 votes
Yes, I was right, right after I posted the question I checked if I'm missing the entity\_key label, and I was. I added it in the entity annotation definition, like so:

```
entity_keys = {
  "id" = "id",
  "uuid" = "uuid",
  "label" = "title",
},

```

---
Tags: 8, entities
---


# Question
Title: Diferences between "mysqldump" and "backup and migrate module"
I always make backup using "backup and migrate" module. But now, need to automate this process using scripts.

When execute backup using "backup and migrate" this module generate .mysql file with approximately 3.3 MB(compacted) and 9MB(uncompacted) , but using the following script command, file have 17MB(compacted) and 53MB+(uncompacted) and .sql extension.

```
mysqldump -u user_mysql -pMY_PASS  --databases my_database | gzip > /home/my_user/my_docs/database.sql.gz

```

How generate ".mysql" extension file using "mysqldump"?

# Answer
> 0 votes
My hosting is a non dedicated version, so, I don't install drush. But I found a good solution. In config BAM (/admin/config/system/backup\_migrate) have an tab "Schedules". In this option u can add backup schedule. Excellent solution, because winscp script (my script backup hosting) will get .mysql.gz generated in BAM private folder automatically. Additionally, about file size backup, BAM really exclude some data tables. This option is personalizable in "/admin/config/system/backup\_migrate/profile/list/edit/default", "DEFAULT DATABASE BACKUP OPTIONS" option "Exclude the data from the following tables".

---
Tags: database, backups
---


# Question
Title: How do I attach a file to a file field when saving (update/insert) a node?
After creating programmatically a PDF file with TCPDF, I am trying to attach it to my field "file\_fichier", here is what my code looks like

```
/**
 * Implements hook_node_presave().
 */
function hook_node_presave($node) {

  if($node->type=='profil'){

    $uri = 'public://profiles/fichier';
    $filename = $node->title.' - PDF - '.$node->language.'.pdf';
    $file_path = $uri . '/' . $filename;

    // Output PDF with TCPDF
    $pdf->Output($file_path, 'F');

    $file = new stdClass;
    $file->uid = $node->uid;
    $file->filename = pathinfo($file_path, PATHINFO_BASENAME);
    $file->uri = $file_path;
    $file->filemime = file_get_mimetype($file_path);
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);

    dpm($file);

    // Now attach file to the file field.
    $node->field_fichier[$node->language][] = (array) $file;

  }

}

```

The PDF file is well saved to `public://profiles/fichier/file_name.pdf` as expected, and it's also recorded to the 'file\_managed' table.

But the problem is that it's not attached to the field `field_fichier`, and nothing seems to happen to the `field_data_field_fichier` table

# Answer
I think that you don't have the fid.

```
/**
 * Implements hook_node_presave().
 */
function hook_node_presave($node) {

  if($node->type=='profil'){

    $uri = 'public://profiles/fichier';
    $filename = $node->title.' - PDF - '.$node->language.'.pdf';
    $file_path = $uri . '/' . $filename;

    // Output PDF with TCPDF
    $pdf->Output($file_path, 'F');

    $file_temp = file_get_contents($file_path);

    // Saves a file to the specified destination and creates a database entry.
    $file_temp = file_save_data($file_temp, $file_path, FILE_EXISTS_RENAME);

   $node->field_fichier = array(
     'und' => array(
       0 => array(
        'fid' => $file_temp->fid,
        'filename' => $file_temp->filename,
        'filemime' => $file_temp->filemime,
        'uid' => $node->uid;,
        'uri' => $file_temp->uri,
        'status' => 1,
        'display' => 1
    )
  )
);

```
> 1 votes

---
Tags: 7, entities, files
---


# Question
Title: Send php variable to js in drupal 8 block
I am trying to attach js files attach\_library() inside a custom block.

However, I can neither add the libraries via block nor add a library. attach\_library() does not accept variables like drupal\_add\_js.

Any ideas on A) how to send a php variable in the block::build() function and how to attach the library through the build() instead of the twig templates?

# Answer
> 5 votes
This is from the documentation how to attach libraries to a render array of a block plugin and send php variables to js:

> Attaching to a render array of a Block Plugin
>
> To give another example of attaching a library to a render array, If you are building a block plugin in your module, you can attach the libraries to the render array in the build() function of your class extending the BlockBase class (as of Drupal 8 beta 6).

```
return array(
      '#theme' => 'your_module_theme_id',
      '#someVariable' => $some_variable,
      '#attached' => array(
        'library' =>  array(
          'your_module/library_name'
        ),
      ),
    );

```

> Attaching configurable JavaScript
>
> In some cases, you may want to add JavaScript to a page that depends on some computed PHP information.
>
> In this case, create a JavaScript file, define and attach a library just like before, but also attach JavaScript settings and have that JavaScript file read those settings, via drupalSettings (the successor to Drupal 7's Drupal.settings). However, to make drupalSettings available to our JavaScript file, we have to do the same work as we had to do to make jQuery available: we have to declare a dependency on it.
>
> So that then becomes:

```
cuddly-slider:
  version: 1.x
  js:
    js/cuddly-slider.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

```

and

```
$build['#attached']['library'][] = 'fluffiness/cuddly-slider';
$build['#attached']['drupalSettings']['fluffiness']['cuddlySlider']['foo'] = 'bar';

```

https://www.drupal.org/developing/api/8/assets

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


# Question
Title: Is the rules event "Before saving a user account" applied every time a user edits their account?
I would like to apply a rule that allows existing users whose email addresses come from a certain domain to continue using their existing accounts, but to prevent the creation of future accounts from these domains.

I have configured my rule to react on the ***After saving a new user account*** event, but I'm unsure as to whether to have it react also on ***Before saving a user account.***

Does *saving* here refer to only to account creation, or also to account updates such as a password change?

# Answer
***Before saving a user account*** will react before you make a change in the user account.

And ***After saving a new user account*** will react After you create the user account.

But if you have the 2 events once you create a new user account you will trigger first the ***Before saving a user account*** event and after the ***After saving a new user account*** event.

If you go to create or update a user account always you need to call the user\_save() function. The difference is in the first param. See this question with an example:

Create a user programmatically and give they a role
> 1 votes

---
Tags: users, rules
---


# Question
Title: How to enable field_ui "Manage display" for a custom entity?
I have written a module that creates a custom Content Entity that has a number of fields including an entity\_reference field with a "file" target type. The field\_ui module adds location task tabs, alongside my entity settings page, for editing field properties (good!). However, clicking on the field\_ui "Manage display" tab for my custom Entity settings crashes Drupal (and not in my code). Has anyone else seen this problem? What "file" plugin is it referring to? This happens in multiple versions of Drupal (8.0.6, 8.1.1, 8.1.7):

The website encountered an unexpected error. Please try again later.

Drupal\Component\Plugin\Exception\PluginNotFoundException: The "file" plugin does not exist. in Drupal\Core\Plugin\DefaultPluginManager-\>doGetDefinition() (line 57 of core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php). Drupal\Core\Plugin\DefaultPluginManager-\>getDefinition('file') Drupal\Core\Field\FormatterPluginManager-\>createInstance('file', Array) Drupal\Core\Plugin\DefaultLazyPluginCollection-\>initializePlugin('file') Drupal\Component\Plugin\LazyPluginCollection-\>get('file') Drupal\Component\Plugin\LazyPluginCollection-\>getIterator() Drupal\Core\Plugin\DefaultLazyPluginCollection-\>getConfiguration() Drupal\Core\Config\Entity\ConfigEntityBase-\>preSave(Object, 1) Drupal\Core\Entity\EntityDisplayBase-\>preSave(Object) Drupal\Core\Entity\EntityStorageBase-\>doPreSave(Object) Drupal\Core\Entity\EntityStorageBase-\>save(Object) Drupal\Core\Config\Entity\ConfigEntityStorage-\>save(Object) Drupal\Core\Entity\Entity-\>save() Drupal\Core\Config\Entity\ConfigEntityBase-\>save() Drupal\field\_ui\Form\EntityDisplayFormBase-\>buildFieldRow(Object, Array, Object) Drupal\field\_ui\Form\EntityViewDisplayEditForm-\>buildFieldRow(Object, Array, Object) Drupal\field\_ui\Form\EntityDisplayFormBase-\>form(Array, Object) Drupal\Core\Entity\EntityForm-\>buildForm(Array, Object) call\_user\_func\_array(Array, Array) Drupal\Core\Form\FormBuilder-\>retrieveForm('entity\_view\_display\_edit\_form', Object) Drupal\Core\Form\FormBuilder-\>buildForm(Object, Object) Drupal\Core\Controller\FormController-\>getContentResult(Object, Object) call\_user\_func\_array(Array, Array) Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>Drupal\Core\EventSubscriber{closure}() Drupal\Core\Render\Renderer-\>executeInRenderContext(Object, Object) Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>wrapControllerExecutionInRenderContext(Array, Array) Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>Drupal\Core\EventSubscriber{closure}() call\_user\_func\_array(Object, Array) Symfony\Component\HttpKernel\HttpKernel-\>handleRaw(Object, 1) Symfony\Component\HttpKernel\HttpKernel-\>handle(Object, 1, 1) Drupal\Core\StackMiddleware\Session-\>handle(Object, 1, 1) Drupal\Core\StackMiddleware\KernelPreHandle-\>handle(Object, 1, 1) Drupal\page\_cache\StackMiddleware\PageCache-\>pass(Object, 1, 1) Drupal\page\_cache\StackMiddleware\PageCache-\>handle(Object, 1, 1) Drupal\Core\StackMiddleware\ReverseProxyMiddleware-\>handle(Object, 1, 1) Drupal\Core\StackMiddleware\NegotiationMiddleware-\>handle(Object, 1, 1) Stack\StackedHttpKernel-\>handle(Object, 1, 1) Drupal\Core\DrupalKernel-\>handle(Object)

# Answer
> 0 votes
I'm pretty sure your view display configuration there is invalid, there is no "file" formatter. There are many formatters for file fields but none is called just file, there is file\_link, file\_uri, file\_default and many more, you have to pick the one you want.

Granted, the error handling there could be better. Feel free to open a core issue about that.

---
Tags: entities, 8
---


# Question
Title: How to list all nodes attached to a vocabulary?
I have a custom vocabulary called "healthcare\_terms" that has enabled terms attached to a custom content type called "health\_posts".

I just want to find all nodes that are tagged with enabled terms from "healthcare\_terms"

I tried the following but it does not seem to be working.

```
   $query = \Drupal::entityQuery('node')
      ->condition('type', 'health_posts')
      ->condition('status', 1)
      ->condition('field_tags.entity.name', 'healthcare_terms');
    $ids = $query->execute();

```

Clearly I am lost. Any help or tips?

Thanks guys

# Answer
> 3 votes
Are you sure that you are using the tags field for this?

You're filtering on the term name, but you want to filter on the term vid instead:

```
 $query = \Drupal::entityQuery('node')
  ->condition('type', 'health_posts')
  ->condition('status', 1)
  ->condition('field_tags.entity.vid', 'healthcare_terms');
$ids = $query->execute();

```

If you have a standalone field that only allows terms from your healthcare\_terms vocabulary, which is usually the better approach, then you can just look for -\>exists('field\_something').

---
Tags: nodes, 8
---


title: Deciphering Views SQL

text:
# Question
Title: Deciphering Views SQL
I am trying to understand Views SQL, and am using a query of some Commerce data to increase my understanding. Here is the start of a query:

```
SELECT commerce_order.order_id AS order_id,
commerce_customer_profile_field_data_commerce_customer_billing.profile_id
AS commerce_customer_profile_field_data_commerce_customer_billi, ...

```

The first part of this is straightforward enough, it is just picking up the `order_id` from the `commerce_order` table. The second item, though is puzzling: the first part, `commerce_customer_profile` is just a table, but then the second part `field_data_commerce_custom_billing` is another table, and the two are connected by an underscore.

In other words, the construct looks like this: `SELECT table1_table2.field`. I have searched at length for an explanation of this syntax, but cannot find anything

# Answer
how table aliases are created in joins is pretty simple - to have unique alias views takes names of both tables and combines them. you can check more simple example: `SELECT node.created AS node_created, node.nid AS nid, users_node.mail AS users_node_mail
FROM
{node} node
LEFT JOIN {users} users_node ON node.uid = users_node.uid`

users table is joined to node table and unique name becomes "users\_node". For files table it would files\_node.

I think it is the only way to have unique aliases. Also it is easy to understand from which join data is coming
> 1 votes

---
Tags: views, commerce, database
---


# Question
Title: How to show People menu in Admin for role restricted user?
Created role "tech support" for help desk to address user account issues.

Granted this role the following privs:

```
Administration
  Access administration menu

User
  Administer permissions
  Administer users
  View user profiles
  Change own username
  Cancel own user account
  Select method for cancelling own account

```

The Administration menu does not display for the user - I see the home icon and nothing else. I did enable clear cache just to see something will display and it does.

Yet if I go to /admin/people, the user with this role can perform the actions I desire. My issue is simply displaying the People menu item.

Any thoughts/pointers? This is a production environment, I need to be able to do this without adding new modules to the system.

# Answer
> 1 votes
I think you need to grant them "Use the administration pages and help"

---
Tags: users
---


# Question
Title: How to speed up Drupal 8 when pages are not cached yet (1st time visit after clearing cache)?
D8 has awesome core caching and opens pages very quickly in second-third and so on visits.

But when I clear caches (making design improvements) the response is too long. Very long response during first time page visit in my shared hosting.

I want to move on VPS, so please what to do with my server to speed up drupal 8?

# Answer
You'll want a crawler (e.g. a cron script running wget) to trigger a local cache rebuilding or some proxy caching solution (e.g. Varnish, CloudFlare) to prevent your server from being hammered on every request upon Drupal page cache flush. Use a crawler if you have a relatively small/fixed amount content and a proxy cache for large/dynamic amount of content.

There really isn't a Drupal-centric solution here. The closest thing might would be the Boost project which has a proxy (local file)/crawler solution, but that's for D7.
> 1 votes

---
Tags: caching
---


title: Changing "add new node" button

text:
# Question
Title: Changing "add new node" button
I have a content type "consultation" that has an inline entity reference to 1 node of a content type "prescription". This content type prescription has multiple inline entity references to the content type "medecine".

I'm using the module Inline Entity Form so I create/add all of these nodes in the creation form of "consultation".

I'm trying to change the text "Add new node" in the form to something else. I know how to do this when it's a direct entity reference, but how do I get to the "Add new medecine" for "medecine"?

This is my code so far:

```
function node_change_form_alter(&$form, $form_state, $form_id) {
switch ($form_id) {
case 'consultation_node_form':
  $form['field_prescription_med']['und']['actions']['ief_add']['#value'] = t('Add new medecine');
  $form['field_prescription_med']['und']['form']['#title'] = t('Add new medecine');
  $form['field_prescription_med']['und']['form']['actions']['ief_add_save']['#value'] = t('Add new medecine');
  break;
}}

```

In this code:

* field\_prescription is the name of the entity reference field in "consultation" (to a "prescription")
* field\_prescription\_med is the name of the entity reference field in "prescription" (to "medecine")

# Answer
> 1 votes
You can use hook\_field\_widget\_WIDGET\_TYPE\_form\_alter() to alter the button name

example:

```
/**
 * Implements hook_field_widget_WIDGET_TYPE_form_alter().
 */
function example_field_widget_inline_entity_form_form_alter(&$element, &$form_state, $context) {
  // Rename the button in specific form.
  if($form_state['build_info']['form_id'] == 'eck__entity__form_edit_sample_sample') {
    $element['actions']['ief_add']['#value'] = t('Add new medecine');
  }
}

```

---
Tags: 7, entities
---


# Question
Title: sf Smallscreen menu button reverts to full desktop menu when scrolling down
To prevent my Superfish Main Menu from stacking as screen size decreases - and thus obscuring the content below it, I set sf-Smallscreen to change the Superfish Main Menu to an accordion when the screen size scales down to 990px. This accommodates tablets in portrait orientation, for example.

Problem: When you scroll down on a tablet, the accordion "Button" reverts to the Desktop rendering of the Main Menu, "stacking up" because it's too wide for the narrow screen.

Scroll back up and the Desktop Main Menu is replaced by the accordion.

Question: How can make the accordion button persist when scrolling down on a tablet-sized screen?

# Answer
> 0 votes
I can't say for sure without seeing your code, but I wonder if this is maybe because you have some Javascript that does an add/remove class or changes the structure of the menu in order to make sticky nav items take up less space when you scroll. This symptom could only be caused by Javascript detecting the scroll behaviour, and as far as I know, Superfish does not have this feature natively (though I could be wrong, I am not overly experienced with this specific module).

If this is the case, right click and inspect code, then look for things that change dynamically on scroll. Any names of classes that are added might give you a clue as to which module is causing this. It does sound like a conflict, though, and not Superfish itself.

If that is not helpful, do you have a dev site up that we can take a look at?

Good luck!

---
Tags: navigation
---


# Question
Title: How can I make views page with unique dates?
I've made views page with node titles and dates:

```
Title       Post date
node1125    2016-08-09
node1137    2016-08-09
node1138    2016-08-09
node1139    2016-08-10
node1140    2016-08-10
node1141    2016-08-10
node1142    2016-08-13
node1143    2016-08-13

```

How can I make views page for these nodes with unique dates only:

```
2016-08-09
2016-08-10
2016-08-13

```

?

# Answer
> 0 votes
I've made grouping (agregation) on date field.
Then I override **views-view-unformatted.tpl.php** for the view with

```
<?php print $title; ?>

```

# Answer
> 0 votes
Im not sure i fully understand your question. However, assuming you want to simply have a list of dates.

Edit the view Make sure the format uses fields In the field section add or remove field as required (fields can be removed using the rearrange menu item , under the arrow next to add)

# Answer
> 0 votes
I'd start by trying aggregation on the date field

---
Tags: 7, views
---


# Question
Title: How to toggle price display with and without tax?
In Europe it is normal for trade suppliers to show prices exclusive of VAT, but for retail suppliers to display prices including VAT.

For the use case where merchants who supply both trade and retail. Many e-commerce sites have the option to toggle the price display to show values with and without tax.

See https://www.tool-wise.com/ (radio button, top right)

Does such an option exist for Drupal Commerce? I haven't found anything in contrib.

# Answer
> 0 votes
Check out commerce price by components module. You can show both prices with and without VAT. If you want to toggle I'm afraid you will have to write a custom module... .

---
Tags: commerce
---


# Question
Title: How to link block and view to basic page
Please tell me how to link a block and view with to a basic page.

for example I want to add a block for featured service and assign with view, my problem is how to assign with a basic page.

# Answer
> 0 votes
You can assign a view and/or block to a basic page in `structure > blocks`. You can add both view and block to the page.

---
Tags: views, blocks
---


title: Link two content types by mutual value

text:
# Question
Title: Link two content types by mutual value
I have two content types: `man` and `food`;

The `man` content type contains the man's name several more fields and a unique id field created by the serial module.

The second content type is created by the users via an external form. The results from the form are set as the `food` content type. One of the fields is equal to the unique id field at the `man` content type.

My question is: 1. I want to create a view that will show me all the `man` values, But when the value is clicked, it will lead me to a table that contains all the food content type entries where the unique id in food is equal to the man unique id value.

It so easy to do this in php but I am new to drupal.

Any help of lead will be great.

# Answer
> 0 votes
Create a views page and list all food results with a contextual filter on the unique id. Give it a path with a wildcard `%` . In another block or page list the `man` names. Include the unique id and put that field on top and exclude it from display. Rewrite the output of the name as a link to the views path but replace the wildcard with the token of the unique id.

---
Tags: views
---


# Question
Title: How to soley wrap the <input>-field in a custom <div>-wrapper in Webform 4.x?
I've a fairly simple question. Due to a given CSS I need to wrap the `<input>`-field (as well as `<select>` or `<textarea>`) of webform-component with a custom `<div>`-wrapper.

Change the follwoing -\>

```
<div class="webform-component webform-component-textfield webform-component--title">
    <label for="edit-submitted-title">Name</label>
    <input type="text" id="edit-submitted-title" name="submitted[title]" value="" size="60" maxlength="128" class="form-text required">
</div>

```

to -\>

```
<div class="webform-component webform-component-textfield webform-component--title">
    <label for="edit-submitted-title">Name</label>
    <div class="my-custom-class">
         <input type="text" id="edit-submitted-title" name="submitted[title]" value="" size="60" maxlength="128" class="form-text required">
    </div>
</div>

```

I tried this snippet (changing #prefix and #suffix with hook\_form\_alter()), but it wraps the whole webform-componoent in a custom div.

Result is like this:

```
<div class="my-custom-class">
    <div class="webform-component webform-component-textfield webform-component--title">
        <label for="edit-submitted-title">Name</label>
        <input type="text" id="edit-submitted-title" name="submitted[title]" value="" size="60" maxlength="128" class="form-text required">
    </div>
</div>

```

I also tried to modify #field\_prefix and #field\_suffix with, but it doesn't result in any output at all. It seems, that these doesn't allow to have any custom html in it.

Any suggestions? Thanks.

# Answer
Use hook\_form\_alter and add "'#title\_display' =\> 'none'," and use label in prefix. e.g.

```
if($form_id == "content_type_node_form"){
   $form['field_name']['#prefix'] = '<label for="edit-submitted-title">name</label><div class="newclass">';
   $form['field_name']['#suffix'] = '</div>';
}

```

I have not tested it but this can work.
> 1 votes

# Answer
It is not supported currently - not in any easy way - and you should not need it. Creating `div` for only one element provides no benefit over adding a class to that element, you should be able to style it however you feel like if you will use `hook_form_alter` with something like:

```
$field['#attributes']['class'][] = 'my-custom-class';

```

And then just attach whatever styles you want directly to input - it should be possible to achieve whatever look you need that way.
> 0 votes

# Answer
if you exactly mention your field name as in content type that will add the div in that field

add this in form alter for that particular form.

```
if($form_id == "content_type_node_form"){
    $form['field_name']['#prefix'] = '<div class="newclass">';
    $form['field_name']['#suffix'] = '</div>';
}

```

this is how i used to add and wrap div hope it will help you.
> 0 votes

# Answer
You can customize all input template files ( and maybe that need some work), another simpler solution is using jquery

use jquery wrap function and try something like

```
$("input.edit-submitted-title").wrap("<div class='my-custom-class'></div>");

```
> 0 votes

---
Tags: 7, webforms, forms
---


# Question
Title: How do I set the value of a hidden form element using form_set_value()?
When validating a form, I need to set the value of a hidden form element. I tried using this code, but it didn't work.

```
\Drupal::formBuilder()->setValue($form['maintenance_type'], 'R', $form_state);
form_set_value($form['maintenance_type'], 'I', $form_state);

```

What is the correct way to use `form_set_value()` to achieve what I want? Am I using the wrong function and there is a different function/method I should use?

# Answer
> 2 votes
Use `$form_state->set('store_value', "value to assign");` to set the hidden form element, and `$value = $form_state->get('store_value');` to retrieve its value.

Don't use `getValue()` or `setValue()`, because they are for submitted values.

If you are migrating forms from Drupal 7 to Drupal 8, $form\_state is now a classed object may help you.

---
Tags: forms, 8
---


title: How do I implement a time picker?

text:
# Question
Title: How do I implement a time picker?
I tried to implement a time picker for a field opening hours. I used **Bootstrap Date & Time picker** and I set the **FIELD TYPE** to *date*, but I couldn't see any widget for BDT Picker in widget selection.

Then, I used **jQuery UI Timepicker**. The time picker is showing, but I can select only 0 for hours and 00 for minutes; all other cells are disabled. Also, the default time in the field is the current time.

What could the issue be?

When I select the date field type, the form has a date field with a full calendar. I need a field to pick only the time. How can I do it?

# Answer
Create a field , select field type as Date (ISO format) or Date. And choose only year, hour, minutes, seconds(if needed). Select Date entry options under MORE SETTINGS AND VALUES , choose custom format as **H:i**

Add time format for H:i and also go-to admin/config/regional/date-time and add date type (to display in node view). In add/edit page for time picker(only hours)

In view page

Hope this helps you with out any help of other modules.
> 1 votes

---
Tags: 7, datetime
---


# Question
Title: How to trigger a Rule when content is viewed with Panels activated?
Easy problem: when users visit a node page on my website, one of the node's integer fields should be changed. Answer: Rules. Now comes the tricky part...

I installed Panels and enabled the node template `node_view` via the Pages UI. I added the Pane *"Node being viewed" content* (build mode: *Full content*), but none of my Rules with an event *Content is viewed* is triggered anymore on the node pages. After searching around a whole day on the internet, I think my problem is a classic, but I didn't find a clear answer anywhere. Hopefully, we can get over it here once and for all.

Here are some things that I tried so far:

1. This comment suggested to disable the *No extras* option in the Pane's settings (which works), but that also renders the comments, comment form, etc.; which is not what I want, since I add those as separate Panes.
2. Combining the power of Conditional Rules and Rules URL Argument. The general idea is to check on *Drupal is initializing* whether the path starts with *node*, save the nid `arg(1)` as a variable, load the node and make the necessary changes afterwards. Unfortunately, I couldn't find a way to use the nid in the path without using custom PHP (I want to avoid that).
3. Forgetting about Rules and trying to code is also fine for me, but I haven't found the correct hook yet. Using `hook_node_view` doesn't work, because it doesn't get called (that's precisely why the Rules aren't triggered). I also tried to use

```
function hook_init() {
  if (arg(0) == 'node') {
    $node = node_load(arg(1));
  }
}

```

in my custom module, but that results in some theme related errors, so I'm afraid that my node templates are getting messed up by this. Lastly, different sources referred to `hook_ctools_render_alter`, so that seemed promising. Though, after some debugging, I quickly gave up trying to understand how this hook works. If this is the correct way to go, I would like to have some more information about the hook or some example code.

Do you have any suggestions to fix this frustrating problem?

**Note:** I'm using the currently latest versions of all modules, i.e. CTools 1.11, Panels 3.8 and Rules 2.9.

# Answer
> 0 votes
You should use Rules Bonus Pack which allows to create a new event when a panel variation is loaded.

**Detailed instructions:**

1. Download Rules Bonus Pack and enable "Rules Bonus: Miscellaneous" sub module.
2. From the panel settings page you will see a new "Reactions" tab. On this tab you will select the new option "Create a Rules event for this variant".
3. Now open the rule and add a new event. You will find a new section "Rules Bonus: Miscellaneous" with the selected panel variation. Use this event instead the "Content is viewed" one.

It should work as you expect.

**Alternative solution**

An alternative solution is to write a custom module. You should take a look to the Rules Bonus Pack source code. You can find some inspiration to solve the problem.

Instead using *hook\_node\_view()* you can implement *hook\_ctools\_render\_alter()*.

First you should check the handler (node\_view) and after load the node data from the ctools/panels context.

Example:

```
function yourcustommodule_ctools_render_alter(&$info, &$page, &$context){
  // Verify if the page/node is the one you want to interact with
  // and set the field value as you wish.

  // First check if the handler is node_view:
  if($context['handler']->task == "node_view"){

    // Then verify the node content from the context sub array
    // The $context variable contains the node data but you
    // have to dig in.
    $node = $context['contexts'][key($context['contexts'])]->data;

    // [... your code ...]

}

```

Happy coding :-)

# Answer
> 0 votes
I think it has got something to do with the node's 'view mode'. Which view mode are you showing the node in, in Panels - Teaser, Default or any custom view mode?

The following steps may help the rule to get triggered when content is viewed in the desired view mode:

1. Go to Admin \> Configuration \> Workflow \> Rules \> edit your rule
2. Under 'Condition', choose 'Data Comparison' \> Compare 'view-mode equals Teaser/Full content/etc.'
3. Save the rule

I hope you are aware that your rule will get triggered whenever the content is viewed in this view mode anywhere in the site and not just in Panels.

Hope this helps.

Regards, Supriya Rajgopal

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


# Question
Title: Render View or Block not Working in Drupal 7
So i have made a view and a block for a carousel. I want to call this view or block in my template. (**panels-pane.tpl.php**).

I have tried to call the view with this function :

```
<?php $view = views_embed_view('carousel', 'carousel-block_1'); print $view; ?>

```

Unfortunately this is not working. Variable $view is NULL

I also tried to call a block in this template file with this function :

```
$block = module_invoke('views', 'block_view', 'carousel-block_1');
var_dump($block); // Empty ;s

```

Also not working..

The Delta ID is right. See Screenshot below for more information.

Do i something wrong?

Full page code with other view render (also not working):

```
<?php
// @codingStandardsIgnoreFile

/**
 * @file panels-pane.tpl.php
 */

?>

<?php if ($pane_prefix): ?>
  <?php print $pane_prefix; ?>
<?php endif; ?>
<div
  class="<?php print $classes; ?>" <?php print $id; ?> <?php print $attributes; ?>>
  <?php if ($admin_links): ?>
    <?php print $admin_links; ?>
  <?php endif; ?>

  <div class="pane-content">
    <?php $view = views_embed_view('downloads', 'downloads-product_downloads'); print $view;     var_dump($view); ?>
    <?php print render($title_prefix); ?>
    <?php if ($title): ?>
    <<?php print $title_heading; ?><?php print $title_attributes; ?>>
    <?php print $title; ?>
  </<?php print $title_heading; ?>>
<?php endif; ?>
  <?php print render($title_suffix); ?>

  <?php if ($feeds): ?>
    <div class="feed">
      <?php print $feeds; ?>
    </div>
  <?php endif; ?>

  <?php print render($content); ?>
</div>

<?php if ($links): ?>
  <div class="links">
    <?php print $links; ?>
  </div>
<?php endif; ?>

<?php if ($more): ?>
  <div class="more-link">
    <?php print $more; ?>
  </div>
<?php endif; ?>
</div>
<?php if ($pane_suffix): ?>
  <?php print $pane_suffix; ?>
<?php endif; ?>

```

# Answer
> 1 votes
I hope views will never use ***hypens***. May be you typed wrong.

**Views always use underscores.**

```
<?php $view = views_embed_view('carousel', 'carousel-block_1'); print $view; ?>

```

I think it should be

```
<?php $view = views_embed_view('carousel', 'carousel_block_1'); print $view; ?>

```

As per your template.php

```
<?php $view = views_embed_view('downloads', 'downloads_product_downloads'); print $view;     var_dump($view); ?>

```

# Answer
> 1 votes
This is how it works:

```
print views_embed_view('view_name','machine_name', $parameter);

```

In case you are wondering, this is the machine\_name

`$parameter` is optional

Example:

```
$parameter = 1;
print views_embed_view('hello_world','block_1', $parameter);

```

---

So for your case, assuming your view is literally called/named Carousel, then it's probably:

```
<?php $view = views_embed_view('carousel', 'block_1'); print $view; ?>

```

# Answer
> 0 votes
Double check that your view is working. I have similar template code that works.

---
Tags: 7, views, blocks
---


title: Change HTML output of a view

text:
# Question
Title: Change HTML output of a view
I have a view which displays products. The fields shown are altered via hook, and I want to add `<div>` and `<h3>`, when I find an appropriate field value. (I tried with adding style to the field in the UI, but the logic is somehow convoluted, so I would need to hard-code it.)

I need to encapsulate a complete row inside a `<div>` when some field has some value. I have tried with views-view-fields.tpl.php and views-view-unformatted.tpl.php, but they seem not to "talk to each other", so I am failing miserably. Maybe should I approach by using `views_view_result()` and building the HTML myself?

# Answer
> 0 votes
To theme/design the complete row, you need to use **Style output** template file.

Click on **Theme: Information** in your view, in pop-up see the last file in **Style output** section. Copy the name and create file with same name and save this file at **sites/all/themes/YOURTHEME/templates**.

Then click on **Style output**, copy the code and paste into the newly created file. In this file, you can add your own HTML display the result.

Hope this helps.

Thanks

# Answer
> 0 votes
If you want to design the complete Row try **Row Style Output** which you found inside **Theme Information**

Try to create a file **views-view-fields--view-name.tpl.php** inside the themes/template folder and copy paste the content from **views-view-fields.tpl.php** file and design the view page yourself.

Thanks

---
Tags: 7, views
---


title: Custom page with form

text:
# Question
Title: Custom page with form
i am new to drupal i want to make custom page with form , i googled and was able to built custom form using guide at Link

but i need form as part of my page content not just form so basically i need custom page with form ,please guide me with this .

Have i to recode it or can use buildForm at certain place in my html, please help me with suitable link or guide

# Answer
> 2 votes
You need to create a route, and a controller that builds the response on that route - in your case a form.

---
Tags: forms, 8, blocks
---


# Question
Title: Drupal views print date 'time ago' as a PHP conditional field
I am trying to make a custom PHP field that returns the value of 'user last access' field as an integer of minutes 'time ago'.

I have created a normal views field for 'user last access' which returns almost exactly what I want from the normal field value:

x mins - this being x mins time ago, created by using 1 as the time units to display.

I just don't know how to return this value through a new PHP field that just references and displays the integer value for this field without ' mins' text ?

I want to then take this raw value and use a conditional statement of:

If user last access is less than 3 minutes print 'Online' else Print 'Offline'

# Answer
> 0 votes
In **User Last access** field UI, under the Date Format, select 'Custom' and then enter custom date format. For minutes you can enter 'i' which will show the number.

Refer http://php.net/manual/en/function.date.php for date formats.

Thanks

---
Tags: views
---


# Question
Title: How to use a custom template for a custom view in Drupal 7?
I'm working with panels and views. I'm trying to understand how to create a view and also create a custom template for that view. I'm able to create the view through the Drupal admin and also create the demo.tpl.twig template (using twig, rather than php for templating), but not sure how to tell Drupal to use a specific template for my view.

Any and all help is appreciated. Thanks.

# Answer
> 0 votes
You dont need to tell drupal use your template to display output. In your view, click on Theme: Inforamtion (at bottom right), see the file names in **Display Output and Style Output** section (Last file in both the sections). Create files with same name and save them at **sites/all/themes/YOURTHEME/templates** directory.

To design whole page use last file from Display Output and to design each row use last file from Style Output. First create and save the files. Then click on Display Output or Style Output, copy the code and paste it respective file. Use your HTML/CSS to design the page. Clear the cache and you will see the result.

---
Tags: theming
---


# Question
Title: Drupal 8: make Taxonomy terms translatable
How to translate Taxonomy terms? I have 2 languages in my site added here: /admin/config/regional/language I have turned the Types here /admin/structure/types marked "Show language selector on create and edit pages" in "Language settings" of each type. But I cannot really understand what to do in Vocabulary settings? I have terms but I cannot see button "Translate" that it was in Drupal 7. Should I create 2 languages terms separately one from another? Please give me manual.

# Answer
To translate terms of taxonomies, you need to activate the Content Translation module.
> 1 votes

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


title: Where to place sar module?

text:
# Question
Title: Where to place sar module?
I want to replace some of the links which I am using in my website, i came to know there is a module called Drush Search & Replace. I have installed also to use this module. But I am not getting where should I keep this module in the drush installed folder or modules folder. I tried by placing this in module folder It will not list out in the modules list because it doesn't have .module file.

I have installed drush in this path

```
Drush script  C:\Users\name\AppData\Roaming\Composer\vendor\drush\drush\drush

```

According to the README.txt of this module:

```
Place the sar directory in ~/.drush/commands (create it if you don't have one)
and run `drush help sar'.

```

I tried by placing this module in the `C:\Users\name\AppData\Roaming\Composer\vendor\drush\drush\commands` folder also,but when I use `drush help sar` command it will say invalid command sar. Please help me regarding this, Thanks in advance..

# Answer
Have you cleared the drush cache (`drush cc drush`)?
> 0 votes

---
Tags: 7, database, drush, search
---


# Question
Title: Ctools Multi step form throws error when form_validate is from another file
Ctools Multi step form throws error when form\_validate is from another file even I had included the file using module\_load\_include.

As per this example I used a function not from the current file but by using module\_load\_include this is working fine. But when it comes to form\_validate it is throwing an error.

Any suggestions?

# Answer
Figured it out, we need to include using the below function

```
form_load_include($form_state, 'inc', 'module_name', 'module_name.file');

```
> 1 votes

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


# Question
Title: Organic Group OG membership relationships
I'm trying to display on a views, only the nodes which the user is part of the Organic group.

I have a field og\_group\_ref in my content type which relate to a group.

What I want is for each user, display only the one he his part of. It seems relationship is the trick but somehow I can't make it work .

So far I tried in Relationship:

```
 OG membership: OG membership from Node group

(OG membership from node group) OG membership: User from OG    membership

```

and to add in contextual filter:

```
(user from OG membership) User: Uid (with default value set to "user id from logged in user")

```

But it doesn't seem to work!

# Answer
> 2 votes
You just need to add `OG membership: Group ID` as a contextual filter,
click `Provide Default: The OG groups of the logged in user`
and under `More` at the bottom of the filter's settings,
click `Allow multiple values`.

---
Tags: 7, organic-groups, views
---


# Question
Title: How do I fetch the password from the database?
Suppose I entered *ABC* as password; its hash is like $S$DNcgO9.CUWosQrms0/CqWvLIUFikmoczZ42n9bL6wxiH1OhIQbd5, which is stored in the *user* table. I need to retrieve the plain password.

How can I achieve this?

# Answer
The short answer is you cannot. Drupal is using a `SHA-512` which is a cryptographic hash function. `SHA-512` is one way which means it is not possible to get the original data back.

You can check this api. https://api.drupal.org/api/drupal/includes%21password.inc/function/user\_check\_password/7.x and this https://api.drupal.org/api/drupal/includes%21password.inc/function/user\_hash\_password/7.x.
> 3 votes

# Answer
You cannot get the password from its hash, if not by brute force. That is why the hash is saved in the database: Even if somebody would be able to read the database content, they would not get any password from the database.

There isn't any need to give the user their password; if they forgot their password, Drupal has a way to let them set a new one, which is done by sending an email with a link.

Directly disclosing passwords from the site is a bad idea. Are you sure the user asking for the password is the legitimate person, and not somebody that is trying to get access to somebody else's account?
> 0 votes

# Answer
To how many users do you want to give their passwords? If you have very less users on your site, then you can reset password for each user from admin panel (from edit user page) and send updated password to each user.

You will not get password from the database as password are saved using SHA-512 (cryptographic hash function).
> 0 votes

# Answer
You can reset the password and sent email about new password to the users.
> 0 votes

---
Tags: users
---


# Question
Title: How to distinguish between drush and HTTP request
How can I distinguish whether a function is called from drush or by a real HTTP request?

# Answer
> 3 votes
Drush is PHP executed over the CLI (Command Line Interface), so perhaps this question can help.

# Answer
> 8 votes
From drush.php:

`function_exists('drush_main')` may be used by modules to detect whether they are being called from drush. See http://drupal.org/node/1181308 and http://drupal.org/node/827478

# Answer
> 6 votes
In Drupal 7:

```
if (drupal_is_cli()) {
  // Cli only code here
}

```

if you want to specifically check for drush use the above along with a check for `drush_main`.

```
if (drupal_is_cli() && function_exists('drush_main')) {}

```

In Drupal 8

```
if (PHP_SAPI == 'cli') {
  // CLI only code here
}

```

Changelog for D8: https://www.drupal.org/node/2295037

# Answer
> 0 votes
# Request from command line

For Drupal 7, use `drupal_is_cli()`

For Drupal 5, 6 and 8, use `PHP_SAPI == 'cli'`

# Request from drush

Always use `function_exists('drush_main')`

---
Tags: 7, drush
---


title: Is hook_boot() removed from drupal 8?

text:
# Question
Title: Is hook_boot() removed from drupal 8?
Is `hook_boot()` hook removed from drupal 8?

If yes then what is alternative method which can be used instead?

# Answer
You can see here

> In Drupal 8 hook\_boot() was removed since the same results can be achieved with other ways, for example:
>
> * A module that needs to interrupt the request very early based on certain conditions can use an event listener (see #1794754: Convert ban\_boot() to an event listener) (Note that modules are loaded by this stage unlike in Drupal 7.)
> * A module that needs to run on cached pages should prompt its users to add code in settings.php
> 4 votes

---
Tags: 8, hooks
---


# Question
Title: How to get the parent name if chid taxonomy term id is known?
How to get the parent name if child taxonomy term id is known??

# Answer
* Drupal 5.x: Taxonomy\_get\_parents()
* Drupal 6.x: Taxonomy\_get\_parents()
* Drupal 7.x: Taxonomy\_get\_parents()
* Drupal 8.0.x: TermStorage::loadParents()
* Drupal 8.1.x: TermStorage::loadParents()
* Drupal 8.2.x: TermStorage::loadParents()
> 3 votes

---
Tags: taxonomy-terms
---


title: Allow users to see own content only

text:
# Question
Title: Allow users to see own content only
I have two content types, `provider` and `products`.

The `providers` is a list of titles filtered by logged in user (each user can only see the providers he enterd). By clicking the `provider` the user is taken to a page that contains a table with all the provider products.

the `provider` and the `products` content type are linked via a unite content field using contextual filter (the mutual field called `lpid`).

In the products page the path is `provider/%/products` while the wildcard represents the lpid field.

Everything works great, what I am trying to do is to **prevent** from users to see other users content.

Is there a way to pass the wildcard via $\_POST so the user will not be able manualy change the url?

TNX

# Answer
"Allow users to see own content only", You can achieve this using contextual filter and relationships in advance settings in views module, Given by you already set the contextual filter set filter to login user,

1.) In Advanced settings add field Content:author in relationships.

2.) Then in Contextual Filters add User: Uid and choose provide default value and set Provide default value Type User ID from logged in user.
> 1 votes

---
Tags: views, users
---