# Question
Title: How to delete a managed folder and its contents programmatically via hook_uninstall?
My hook\_update\_N() implementation looks like this:

```
$directory2 = 'public://folder_name';
file_prepare_directory($directory2, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);

```

How can I remove "folder\_name" and its contents in hook\_uninstall using drupal's API?

# Answer
> 3 votes
Drupal doesn't consider a folder to be a group of files, and doesn't have a method for bulk deleting managed files (like it does for unmanaged files: `file_unmanaged_delete_recursive`). So you'll need to identify which files you want to delete manually. A query with `WHERE uri LIKE 'public://folder_name/%'` might be sufficient in this case, for example, but you'll know you're own setup better than I can guess.

Once you have a list of file IDs, load up the objects, loop through them, and call `file_delete` on each. If you have the File Entity module installed, you can shorten this by using `file_delete_multiple()`, and just pass the IDs.

Once you're happy all the files have been deleted (you could stat the folder after running the loop), then remove the folder with `drupal_rmdir()`.

Bear in mind that `file_delete()` is not guaranteed to remove the file; other parts of the system can declare their interest in a managed file by way of the `file_usage` table. If you want to unconditionally remove files regardless of any other entity in the system that they're attached to, you can use the `file_usage_*` methods in file.inc.

---
Tags: 7, files
---


# Question
Title: How do I implement an image categorization system using Entity Browser and File Entity?
I am currently using the Entity Browser module along with the File Entity module for handling image upload and selection for content editors in a Drupal 8 project.

I have several image fields on different content types and to get some structure for them I would like each image field to be mapped to a certain image category (taxonomy) so that the user can filter between categories when selecting existing images using the entity browser.

To do this I am using the File Entity reference for my image fields. I have added a taxonomy field with my custom ”image category” taxonomy on the Image File entity type. So far so good.

My first problem is that I want automatically populate the image category field with a certain value when adding a new image through the entity browser. So if I upload an image to a ”hero image” field the underlying file entity should get the category ”Hero images” automatically. I’m lost to how to hook into the upload process of the entity browser to set this based on which field it belongs to. How can this be done?

The entity browser also allows the user to select existing images. For this I'm using the view prepackaged with the File entity browser modulle and I have added a taxonomy dropdown filter to that view so that the images can be filtered by category. What I want to do is to have this view automatically set the correct filter when loaded. So when loading the view from a ”Hero Image” field the dropdown has the ”Hero Image” category preselected.

So essentially I'm missing two parts:

* Automatically populating the file entity "image category" field when uploading an image based on which field the image was uploaded to
* Automatically prepopulate the "image category" exposed filter in the "select existing image" view based on which field it was opened from

Can someone help here. Maybe there's a better way to go about this?

# Answer
> 0 votes
For the time being I have solved it in the following way:

1. I have created a separate entity browser configuration for each image category. Each browser has a separate id which is what makes step 2 possible.
2. In a custom module I have implemented an `EventSubscriber` that listens to the `EntitySelectionEvent` that Entity Browser fires when an entity is selected. When this happens my subscriber checks the browser id currently used and based on that it sets the category field for any of the uncategorized entities that was selected. Here is a gist of the `Eventsubscriber` implementation.
3. For each category I have created a separate view display in my "Select existing image" view. The views are very similar and the only difference between them is that they filter the entities to only show items with a specific category.
4. Each separate Entity Browser config created in step 1 is wired to the corresponding view display mode.

This works pretty good. When uploading files using an entity browser with the id `image_library_browser__content` the image will get the category `content` and when selecting existing items the view will only list `content` items.

A problem with this is if you would have alot of different image categories since you need to create one separate entity browser and display per category. On my current project I have 6 so I think it is ok.

One nice thing with having separate entity browsers per category is that you can define separate upload paths, field descriptions and file types per category. (Currently this is not possible in any other way since Entity browser in its current form ignores the image field settings)

# Answer
> 1 votes
For the tagging part, forget about entity browser, that (currently) doesn't know about the context of where it is invoked and to what those files will eventually be added.

Instead, what you want to hook into is hook\_node\_presave(). Go through the referenced files in all your fields that you want to support (could be all image fields or a configurable list), check the image referenced there. If the image doesn't have a category yet, set it based on the field that you're currently looking. Or maybe always ensure it is categorized based on the current field. Whatever you want.

For views, that's currently not possible yet, for the same reason. Entity browser doesn't receive the context yet. There are some related issues like https://www.drupal.org/node/2656196 and https://www.drupal.org/node/2366335. Note that there are many ways to embed an entity browser and you don't always have a field, for example with entity\_embed.

---
Tags: 8, media, files
---


# Question
Title: How to re-create content types using the feature module which removes deleted fields?
I've been looking into the Feature module to move changes from Dev to Staging without redoing everything.

On my Dev site I made changes in the content types (added new fields, deleted some field). Then I exported all content types as a feature and imported in to Staging. But still I see the deleted fields on staging.

I thought to delete all content types on staging and enable the module exported by feature but there is no delete option in content types.

Am I doing it in the correct way?

# Answer
The answer to your question boils down to what is mentioned by the Features maintainer in this comment, i.e.:

> FInally going to mark this as "won't fix" until somebody proposes something better.
>
> 1) Features will never do anything that might cause content to be lost on your site. This includes deleting fields. Just because you remove a field from a feature doesn't mean you might not still have content stored that would be lost if features auto-deleted it. I've never been in favor of any sort of auto-deletion.
>
> 2) Now that fields are split into bases and instances, this gets even more complicated.

The next comment in that same issue includes a link to a 32 steps process, which describes Deleting a Drupal Field Saved in Features. IMHO this is "as good as it gets" today (and my recommended work around until further notice).
> 2 votes

# Answer
The right way of deploying the changes between the environment including delete operations can be achieved by `drush` command or `hook_update()` as part of your deployment, since auto-deletion of any content by Features module is not possible to avoid any content lost (which is the last thing that you want to do on your production). See: #649298 for further details.

### hook\_update

Here is example by using `hook_update()`:

```
/**
 * Deletes fields.
 */
function MYMODULE_update_7001() {
  $fields = array(
    'field_foo',
    'field_bar',
  );
  foreach($fields as $field) {
    if (field_info_field($field)) {
      field_delete_field($field);
      field_purge_batch(10);
      drupal_is_cli() ? drush_log("Deleting field $field", "ok") : NULL;
    };
  }
}
?>

```

or this one posted at GH gist by insparrow:

```
<?php
/**
 * Remove a shared field from a content type.
 */
function custom_module_update_7027() {

  // Fetch instance info.
  $entity_type = drush_field_get_entity_from_bundle('custom_content_type');
  $instance = field_info_instance($entity_type, 'field_to_remove', 'custom_content_type');

  // Mark field for deletion.
  field_delete_instance($instance);

  // Remove field marked for deletion.
  field_purge_batch(10);

  watchdog('custom_module', 'Removed field_to_remove instance from custom_content_type', array(), WATCHDOG_INFO);
}

```
* `field_delete_field`

> Marks a field and its instances and data for deletion.
* `field_purge_batch`

> This function will purge deleted field data in batches. If a deleted field instance with no remaining data records is found, the instance itself will be purged. If a deleted field with no remaining field instances is found, the field itself will be purged.

### drush

Use `drush` which can be invoked as part of your deployment process and its `field-delete` command.

For example:

```
drush field-delete field_name

```

to delete a field and its instances.

To delete only instance attached to specific bundle, try:

```
field-delete field_name --bundle=bundle

```

---

Alternatively you can consider to implement your own `drush` command which find all abandoned fields and removes them.

Here is example code posted by Chi:

```
<?php

/**
 * @file
 * Drush command to find all abandoned fields.
 *
 * @see http://drupal.org/node/649298
 */

/**
 * Implements hook_drush_command().
 */
function abandoned_fields_drush_command() {

  $items['abandoned-fields'] = array(
    'description' => 'Find all abandoned fields',
    'drupal dependencies' => array('features'),
    'aliases' => array('af'),
  );

  return $items;
}

/**
 * Drush command callback;
 */
function drush_abandoned_fields() {
  module_load_include('inc', 'features', 'features.export');

  $commited_fields = array();
  foreach (features_get_default('field') as $id => $field) {
    if (!in_array($field['field_config']['field_name'], $commited_fields)) {
      $commited_fields[] = $field['field_config']['field_name'];
    }
  }

  $rows[] = array('Field name', 'Location');
  $rows[] = array('-------------', '----------');
  foreach (field_info_fields() as $field_name => $field) {
    if (!in_array($field_name, $commited_fields)) {
      $bundle_strs = array();
      foreach ($field['bundles'] as $entity_type => $bundles) {
        $bundle_strs[] = $entity_type . ' (' . implode(',', $bundles) . ')';
      }
      $rows[]= array(
        $field_name,
        implode(' ', $bundle_strs),
      );
    }
  }
  drush_print_table($rows);
}

```

---

For further details, you may want to read Deleting a Drupal Field Saved in Features.
> 1 votes

# Answer
So on staging, you updated the custom content type feature folder/files and did `drush fr machine_name_of_your_content_type_feature -y` right? This assumes that you already have the custom content type feature installed in your staging site.

`drush fr` should apply all the new changes from code into your staging site's DB.

Also if your deleting fields in the staging site, might want to double check if you need to manually delete the field using hook\_upadte\_N. An example and discussion can be found here https://www.drupal.org/node/649298#comment-10219951. It can also be the basis for the code you want to execute.
> 0 votes

# Answer
You may try Features Cleanup sandbox module (GH fork) as add-on to Features which can do cleanup of fields, vocabularies, panel nodes, mini panels, and image styles that are in the database, but not in any enabled features module.

This is potentially dangerous module, since it can irreversibly delete database components once they got removed from the Features, so you should test it first if that meets your expectations and it has been tested with your deployment plan and scripts.

This module is separated into two different tasks:

* Resolve Overrides

You will have new option *Resolve All Overrides* at the bottom of Feature's overview screen which will attempt to cleanup all overrides by deleting existing database components (mainly fields). After that, it will revert this feature.
* Delete existing components that are not in any Features modules

This includes: content types, mini panels, node panels, taxonomy vocabularies, image styles, etc.

Before doing it, you need to enable all features that you want to compare against. Then click on *Features Cleanup* in the Features listing screen.

This module also has drush integration and provides the following commands:

* `drush fca`/`drush features-cleanup-all`

Cleans out all content types, panel pages, mini panels, vocabularies, and image styles from database based on existing enabled features and run `features-revert-all` afterwards. This is useful to include as part of your deployment process before you backup your database.
* `drush fcf`/`drush features-cleanup-feature [feature name] [component list]`

Attempts to resolves all overrides on a single feature module. Run features-revert afterwards.
> 0 votes

---
Tags: 7, features
---


# Question
Title: Add row clearfix after evry three column does any one know how to make it using view?
```
<div class="blog-categories-warp">
     <div class="container">
         <div class="row clearfix">
             <div class="col-lg-4 col-md-4 col-sm-4 col-xs-12">
                 <h3>General</h3>
                    <ul class="archive-list">
                     <li>
                         <a href="#">Diam mus suspendisse eu sed in senectus ut a cum.<span>on 24 April, 2016</span></a>
                        </li>
                        <li>
                         <a href="#">Litora augue parturient suspendisse ullamcorper fermentum velit aliquet augue ullamcorper lobortis.<span>on 24 April, 2016</span></a>
                        </li>
                    </ul>
                    <div class="more-in-blog"><a href="#">More in General</a></div>
                </div>
                <div class="col-lg-4 col-md-4 col-sm-4 col-xs-12">
                 <h3>Selerisque sceler</h3>
                    <ul class="archive-list">
                     <li>
                         <a href="#">Diam mus suspendisse eu sed in senectus ut a cum.<span>on 24 April, 2016</span></a>
                        </li>
                        <li>
                         <a href="#">Litora augue parturient suspendisse ullamcorper ferrtis.<span>on 24 April, 2016</span></a>
                        </li>
                    </ul>
                    <div class="more-in-blog"><a href="#">More in General</a></div>
                </div>
                <div class="col-lg-4 col-md-4 col-sm-4 col-xs-12">
                 <h3>Hac ad sagittis</h3>
                    <ul class="archive-list">
                     <li>
                         <a href="#">Diam mus suspendisse eu sed in senectus ut a cum.<span>on 24 April, 2016</span></a>
                        </li>
                        <li>
                         <a href="#">A ultricies litora habitasse eget condimen <span>on 24 April, 2016</span></a>
                        </li>
                        <li>
                         <a href="#">Scelerisque parturient vestibulum scelerisqu. <span>on 24 April, 2016</span></a>
                        </li>
                        <li>
                         <a href="#">Litora augue parturient suspendisse ullamcorper ferrtis.<span>on 24 April, 2016</span></a>
                        </li>
                    </ul>
                    <div class="more-in-blog"><a href="#">More in General</a></div>
                </div>
            </div>
            <div class="row clearfix">
                <div class="col-lg-4 col-md-4 col-sm-4 col-xs-12">
                 <h3>Selerisque sceler</h3>
                    <ul class="archive-list">
                     <li>
                         <a href="#">Diam mus suspendisse eu sed in senectus ut a cum.<span>on 24 April, 2016</span></a>
                        </li>
                        <li>
                         <a href="#">A ultricies litora habitasse eget condimen <span>on 24 April, 2016</span></a>
                        </li>
                        <li>
                         <a href="#">Scelerisque parturient vestibulum scelerisque dictum a jisse gravida curae at. <span>on 24 April, 2016</span></a>
                        </li>
                        <li>
                         <a href="#">Scelerisque parturient vestibulum scelerisque dictumt fringilla. <span>on 24 April, 2016</span></a>
                        </li>
                        <li>
                         <a href="#">Litora augue parturient suspendisse ullamcorper ferrtis.<span>on 24 April, 2016</span></a>
                        </li>
                    </ul>
                    <div class="more-in-blog"><a href="#">More in General</a></div>
                </div>
                <div class="col-lg-4 col-md-4 col-sm-4 col-xs-12">
                 <h3>Hac ad sagittis</h3>
                    <ul class="archive-list">
                     <li>
                         <a href="#">Diam mus suspendisse eu sed in senectus ut a cum.<span>on 24 April, 2016</span></a>
                        </li>
                       <li>
                         <a href="#">Litora augue parturient suspendisse ullamcorper ferrtis.<span>on 24 April, 2016</span></a>
                        </li>
                    </ul>
                    <div class="more-in-blog"><a href="#">More in General</a></div>
                </div>
                <div class="col-lg-4 col-md-4 col-sm-4 col-xs-12">
                 <h3>General</h3>
                    <ul class="archive-list">
                    <li>
                         <a href="#">Diam mus suspendisse eu sed in senectus ut a cum.<span>on 24 April, 2016</span></a>
                        </li>
                    </ul>
                    <div class="more-in-blog"><a href="#">More in General</a></div>
                </div>
            </div>
        </div>
    </div>

```

I am trying to make structure of html like this using view and i also make views but i can't add `<div class="row clearfix">` at the every third column can any one help me out?

I'm using Drupal 7, Views 3

# Answer
> 0 votes
Probably not what you thought you'd get, but here's a CSS selector that can do this fix for you, no preprocessing needed:

```
.blog-categories-warp > .container > .row:nth-child(3) {
  background: green;
}

```

> Note: As of writing, 97.22% of the browsers in the world would support this CSS selector: http://caniuse.com/#search=nth

I'm interested because your code given doesn't actually give us three rows. So I had to add some to make sure my CSS worked. It does.

Here's the CSS snippet that adds bootstrap's clearfix hack:

```
.blog-categories-warp > .container > .row:nth-child(3):before,
.blog-categories-warp > .container > .row:nth-child(3):after {
  content: " "; /* 1 */
  display: table; /* 2 */
}
.blog-categories-warp > .container > .row:nth-child(3):after { clear: both; }
/* For IE 6/7 only */
.blog-categories-warp > .container > .row:nth-child(3) {
  *zoom: 1;
}

```

And here's a working example:

http://codepen.io/anon/pen/PNzyNw

---
Tags: views
---


# Question
Title: Is there a way to use a generic 'Site is Down' page?
I recently experienced issues with my hosting company and a few of my sites went down. All users could see was a standard Drupal PDO Exception page. Is there a way I can create/use a page to show a generic "we're having issues, please check back later" page instead of this if a major problem occurs?

# Answer
> 0 votes
Yes, it is quite simple. Just go to "admin/config/development/logging" and set "Error messages to display" to "none". You will then have only the error page with message "The website encountered an unexpected error. Please try again later.". The PDO exception will not be displayed.

---
Tags: theming
---


# Question
Title: In Drupal 8, how do you add attributes to a link generated by the core Link field? (or, generally a render array with #type set to "link")
So I have a situation where I have a core Link field on a node. I wanted to style that link with custom attributes, so I created a field.html.twig override to do that, only to find that the link itself is printed elsewhere. There doesn't appear to be a template or theme hook for the link; given that the core Twig debug functionality doesn't report a child template being invoked.

I tried pulling the URL out directly and rendering my own link, but that class (Drupal\Core\Url) isn't on the Twig whitelist, so getting the URL out will just cause a WSOD. There doesn't appear to be an Attributes object that I could add things into.

I could use theme\_preprocess\_field to call Drupal\Core\Url-\>toString() directly and store it in another variable, but I'd be throwing out whatever attributes are generated by default. I'd rather participate in however Drupal is rendering this link directly; or, if it's not extensible, at least know how to replicate what core does.

(For the record, the solution recommended in another question of using theme\_preprocess\_field to write attributes into #options does not appear to work.)

EDIT: As requested, here is the code I tried for a preprocess hook to add attributes:

```
function MYTHEME_preprocess_field(&$variables) {
    $element = $variables['element'];
    if ($element['#name'] == 'field_extra_links') {
        $variables['items'][0]['content']['#options']['attributes']['class'][] = 'Button';
    }
}

```

# Answer
Answering my own question: the original suggestion was actually a valid solution; the way I had my theme configured meant that the hook wasn't loading. Stupid mistakes!
> 0 votes

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


# Question
Title: How to manage and delete orphaned node references?
I have a product node type and a review node type. The review node type has a node reference field that points to product. I can make one product and many users can add through using the node reference URL widget several reviews. I've been deleting the products while the reviews have been sitting orphaned in the database. This hasn't been a problem till I installed the Search API module. Perhaps the error being caused by the Entity module is a bug but those pesky node references have no business existing if the product has been erased or at least they shouldn't be published.

I can think of many solutions to this including never letting a product be deleted so that all content stays in the database till the end of time.

However, I would like to just delete all the reviews when a product is deleted. How do I do this.

# Answer
This situation is exactly like deleting comments which are entities when deleting the node they are attached to. So I looked at the code in comment.module to see how it is handled there. Here is my solution:

```
/**
 * Implements hook_node_delete().
 */
function helper_node_delete($node) {
  if ($node->type == 'product'){
    $nids = db_query('SELECT entity_id FROM {field_data_field_review_reference} WHERE field_review_reference_nid = :nid', array(':nid' => $node->nid))->fetchCol();
    node_delete_multiple($nids);
  }
}

```

This also means that I can test to see if the node type is a review so all node types that reference the review can be handled too since hook\_node\_delete is recursive in this instance.
> 3 votes

# Answer
Install Views Bulk Operations. Create a view (let's call it `referencing_nodes`) that will select the list of nodes referencing the Product passed in argument.

**View type:** Node
**Add argument:** Content: Node reference
**Style:** Bulk Operations
**Selected operations:** Delete node
**Add field:** Node ID

Use Rules to fire an action on product deletion:

**Event:** After deleting content
**Content has type:** Product

**Add an action:** Execute a VBO programmatically on node
**View:** referencing\_nodes
**Operation:** Delete node
**View arguments:** return array($object-\>nid);

Tested, worked! However, it would be great if Rules could *cascade* and also delete nodes referencing the nodes being deleted by the VBO. Unfortunately, I only get a debugging message saying that's not gonna happen to prevent recursion... Fair enough. :-)
> 2 votes

# Answer
> This handy little function will delete all children nodes that reference a parent node when you delete it
>
> Helpful if you have multiple users adding content to your site.
>
> Or if a workflow of attaching many nodes to one node has a short life cycle. For instance, if a system of petitions attaches requests to it, it is helpful to be able to delete all requests when you delete the petition.
>
> Create a simple module with the code below
>
> In the info file:
>
> ```
> name = mymodule
> description = Utility module that performs operations on nodes
> project = Custom Modules
> core = 7.x
>
> ```
>
> In the module file:
>
> ```
> /**
>  * Implements hook_node_delete().
>  */
> function mymodule_node_delete($node) {
>
>   $query = new EntityFieldQuery();
>   $query->entityCondition('entity_type', 'node')->fieldCondition('field_referencing_parent_node', 'target_id', $node->nid);
>   $results = $query->execute();
>
>   if (!empty($results['node'])) {
>     $nodes = array_keys($results['node']);
>     node_delete_multiple($nodes);
>   }
> }
>
> ```
>
> Replace `field_referencing_parent_node` with the field that references the parent node. Replace mymodule with the actual module name. Entity Field Query will do the rest.

Source: bradallenfisher comment on How to delete orphaned entity (node) references at Drupal.org
> 1 votes

# Answer
You may try Delete Orphaned Terms module for cleaning "orphaned" taxonomy terms that are no longer referenced by any node (orphans). This can be configured automatically (cron) according to several parameters with support for whitelist/blacklist.

## WHITELIST AND BLACKLIST LOGIC

```
- Term pruning: [YES/NO]

  whitelisted ----> blacklisted ----> is tag (t) ----> tags only (T) ----> [YES]
       |       no        |       no      |         no       |          no
   yes |             yes |           yes |              yes |
      \_/               \_/             \_/                \_/
     [YES]              [NO]           [YES]               [NO]

  In boolean logic: (w OR (NOT b AND (T => t)))

- Vocabulary pruning: [YES/NO]

            blacklisted ----> is empty (e) ----> [NO]
                 |       no       |         no
             yes |            yes |
                \_/              \_/
               [NO]             [YES]

  In boolean logic: (NOT b AND e)
  (Yes, the whitelist and tag pruning have no meaning here.)

```

Source: README.txt
> 0 votes

---
Tags: 7, nodes, entities
---


# Question
Title: Show or hide fields in view based on a user relationships
I have a table on my site made with views. I have the User Relationships module installed so users can connect with each other. I want most of the fields to be visible for all users but there is one field that must only be showed if the author of the content and the logged in user have a relation with each other.

Is this even possible? I have tried different settings. It is possible with a filter criteria to hide the complete node if the users aren't related. But that is not what I want. It is just one field of that node type that must be hidden if the users aren't related.

# Answer
> 0 votes
The Views Conditional module works for me! Thank you J. Reynolds! I have the price field set to be hidden, and created a conditional field that shows the price field (with the token), if the relationship field (also hidden), haves the value of "the name of the relationship". If it has not that value it shows "----". I am going to fine tune some things around the relationships module but this is exactly what I needed. Thanks again!

---
Tags: views, entities, users
---


# Question
Title: How do I make an ajax callback in Field Plugin formElement() reload form?
I've created a custom field as a module Plugin and have the following code in the formElement() method of the field's Widget.php. The intention is to populate options in the second select element based on the value chosen in the first element:

```
$element += array(
  'sheet_name' => [
    '#title' => 'Sheet',
    '#description' => 'Select the sheet',
    '#type' => 'select',
    '#options' => $options,
    '#required' => TRUE,
    '#element_validate' => [
      [$this, 'validate'],
    ],
    '#ajax' => [
      'event' => 'change',
      'callback' => [$this, 'getPositions'],
      'progress' => [
        'type' => 'throbber',
        'message' => 'Getting positions.',
        'method' => 'replace',
      ],
    ],
  ],
  'position' => [
    '#type' => 'select',
    '#options' =>['Select'],
    '#title' => 'Position',
    '#description' => 'Position',
    '#prefix' => '<div id="position-select">',
    '#suffix' => '</div>',
  ],
);
return array('value' => $element);

```

My callback is as follows:

```
$options = ['Select' => 'Select'];
foreach ($positions as $position) {
  $options[$position['position']] = ucfirst($position['position']);
}

$sheet_position = [
  '#type' => 'select',
  '#options' => $options,
  '#title' => 'Position',
  '#required' => TRUE,
  '#description' => 'Position',
];

$response = new AjaxResponse();
$response->addCommand(new HtmlCommand('#position-select', $sheet_position));
$form_state->setRebuild(TRUE);
return $response;

```

This puts the option values I want into the second select element, but the form isn't being rebuilt, even with the call to $form\_state-\>setRebuild(), so my updated select element isn't being associated with a form field. I'd love to understand why, but I'll settle for any way to force the form to rebuild after the callback runs.

Update: I have tried $form\['position'\] instead of $sheet\_position in my callback but no joy there, either.

# Answer
> 1 votes
Here is what I did in TVI which does something similar to what you are doing (changing out options):

```
    // form code ...

$form['tvi']['view'] = [
  '#type' => 'select',
  '#title' => 'Using the view',
  '#description' => $this->t('The default view that you want to use for all vocabularies and terms.'),
  '#default_value' => $config->get('view'),
  '#options' => $view_options,
  '#states' => [
    'visible' => [
      ':input[name="enable_override"]' => array('checked' => true),
    ]
  ],
  '#ajax' => [
    'callback' => '::loadDisplayOptions',
    'event' => 'change',
    'wrapper' => 'tvi-settings-wrapper',
    'progress' => array(
      'type' => 'throbber',
    ),
  ],
];

// form code ...

  /**
   * Ajax callback - null the value and return the form.
   * The value gets nulled because we cannot overwrite #default_value in an ajax callback.
   * @param array $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   * @return mixed
   * @see https://www.drupal.org/node/1446510
   * @see https://www.drupal.org/node/752056
   */
  public function loadDisplayOptions(array &$form, FormStateInterface $form_state) {
    $form['tvi']['view_display']['#value'] = '';
    $form_state->setRebuild();
    return $form;
  }

```

In my form code, I am reading the values from $form\_state and checking them - which is passed to a function that populates the option list. Therefore, when the AJAX callback rebuilds the form, the new option list will be populated.

```
  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $values = $form_state->getValues();
    $config = $this->config('tvi.global_settings');
    $views = Views::getEnabledViews();

$view_options = ['' => ' - Select a View -'];
$display_options = ['' => ' - Select a View Display -'];
$default_display = '';

foreach ($views as $view) {
  $view_options[$view->id()] = $view->label();
}

if (isset($values['view'])) {
  $display_options += $this->getViewDisplayOptions($values['view']);
}
elseif ($config !== NULL) {
  $view = $config->get('view');
  $view_display = $config->get('view_display');

  if (isset($view)) {
    $display_options += $this->getViewDisplayOptions($view);
  }

  if (isset($view_display)) {
    $default_display = $view_display;
  }
}

$form['#prefix'] = '<div id="tvi-settings-wrapper">';
$form['#suffix'] = '</div>';

// irrelevant fields redacted...

$form['tvi']['view'] = [
  '#type' => 'select',
  '#title' => 'Using the view',
  '#description' => $this->t('The default view that you want to use for all vocabularies and terms.'),
  '#default_value' => $config->get('view'),
  '#options' => $view_options,
  '#states' => [
    'visible' => [
      ':input[name="enable_override"]' => array('checked' => true),
    ]
  ],
  '#ajax' => [
    'callback' => '::loadDisplayOptions',
    'event' => 'change',
    'wrapper' => 'tvi-settings-wrapper',
    'progress' => array(
      'type' => 'throbber',
    ),
  ],
];

$form['tvi']['view_display'] = [
  '#type' => 'select',
  '#title' => 'With this view display',
  '#description' => $this->t('The view display that you want to use from the selected view.'),
  '#default_value' => $default_display,
  '#options' => $display_options,
  '#states' => [
    'visible' => [
      ':input[name="enable_override"]' => array('checked' => true),
    ]
  ],
  '#prefix' => '<div id="tvi-view-display">',
  '#suffix' => '</div>',
];

return parent::buildForm($form, $form_state);
}

```

(Sorry for the broken paste) So when the form rebuilds, the options are populated from another method, while the AJAX callback just triggers a rebuild.

As a side note, the reason I am setting #value to '' is to force the field to default to the placeholder 'Select a Value' on change. Otherwise, it will stick to the last selected position by the user.

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


# Question
Title: How to extend a module hook from another module?
I want to be able to clone/replicate a node from one language to another on click of a button using a custom module. Basically we have a view which displays all nodes in the system and under the "operations" column, we have Edit, Delete, Clone.

On click of the Clone button, I want to replicate the node (keeping the same exact data values as is except for the language field) to other languages.

I have installed the node\_clone and replicate modules to help me, but I am struggling to see how I can create a custom module that can call the hooks in those contrib modules in such a way that I can save the node in different languages automatically instead of click on the "Translate" tab and manually doing it one by one.

I have tried calling the `clone_node_save` from the Node clone module from my custom module, but that does not work.

How can I extend a module hook in a custom module?

# Answer
You can use the following code to solve your problem:

```
//clone the node
$new = clone $node;
//set the node to new
$new->is_new = true;
//unset the nid and the vid
unset($new->nid);
unset($new->vid);
//setting the new language
$new->language = 'fr';
//save the new node
node_save($new);

```

Reference: Programmatically create a new node from an existing NID
> 3 votes

# Answer
I assume you're triggering the clone using the "clone item" VBO action provided by the node\_clone module? If so, have you looked at `hook_clone_node_alter()`? It gives you the node (and some context data - see `clone_action_clone()` in clone.module) and lets you change values before the cloned node is saved.

If you are not using the VBO action, and therefore don't have the hook available, you might want to look at `clone_action_clone()` and copy the relevant code.
> 2 votes

# Answer
I think you don't need the node clone module. Look at this solution from the comment: https://www.drupal.org/node/1069774#comment-4834192 This is actually utilizing the entity translation module's translation handler. Here is the code again:

```
<?php

$translation = array(
  'translate' => 0,
  'status' => 1,
  'language' => 'sv', // here is the language you're translating to
  'source' => 'en', // here is the source language
);

$node = node_load($nid); // If you've called node_save($node) before, you'll have the node object already and you can omit this
$handler = entity_translation_get_handler('node', $node);
$values['name_field']['sv']['0']['value'] = $sv_name; // You can write the array like this, I find it easier to read
$handler->setTranslation($translation, $values);
field_attach_update('node', $node);

?>

```

Create a module with hook\_menu and a page callback that holds the snippet above.
> 2 votes

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


# Question
Title: Getting current node paragraphs content from block
I'm trying to build a block to insert on the side of the page that would list all "paragraphs" titles (from paragraph module) and link to them via an anchor (a little bit like the book module does but inside the same page)

For now i managed to get the list of paragraphs :

```
$node = \Drupal::routeMatch()->getParameter('node');
$paras = $node->field_paragraphes;

```

but can't get to the list of fields and their values inside that paragraph. When i loop over them all i seem to get is an `EntityReferenceRevisionsItem` or at best an array like :

```
array (size=2)
  'target_id' => string '8' (length=1)
  'target_revision_id' => string '12' (length=2)

```

But i can't find their fields and values ?

Thanks a lot !

# Answer
Paragraphs are separate entities, the field just stores the reference. To access them, you can do something like this:

```
foreach ($node->field_paragraphes as $item) {
  // Access the paragraph entity like this:
  $item->entity;
}

```
> 9 votes

---
Tags: 8, blocks
---


# Question
Title: How to load aggregated styles / js in an 'external' script via DRUPAL_BOOTSTRAP_FULL?
I have an external script / php application that I now have to implement into a running D7 site. So far DRUPAL\_BOOTSTRAP\_FULL seems to do the job just fine – I can read the session, check the user etc.

But I am currently stuck trying to load the `$styles` and `$scripts` into the head of that external application. I tried `drupal_get_css();`, also checked the `$variables` and also tried `template_preprocess_html();` to preprocess the variables –– but D7 won't return anything.

What I have so far:

```
define('DRUPAL_ROOT', $_SERVER['DOCUMENT_ROOT']);
$base_url = 'http://'.$_SERVER['HTTP_HOST'];
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

```

I hope somebody can direct me in some direction – any pointers appreciated. Thank you!

**Update:** The solution suggested by oksana-c works quite well if you 'only' need to load the top css and js files. The site I'm working on however *caches* and *aggregates* all js and css files into one – including various files provided by different modules… So what I would actually need to find out is how to link to those ***aggregated js and css files***. Anybody?

**Update2:** I could 'crawl' the folders where the aggregated css and js are stored – however currently I can see 4 different js files and 4 different css files in the head. Also according to the files' timestamps sometimes only 2 files were generated and loaded in the past – so I have basically no indication of how many of the most recent files I should include. Probably some hook would help that would let me list whatever cached/aggregated files are loaded *at this time* – but I still have no idea where/how to hook into the caching/aggregating functions…

# Answer
Here's the gist of it (w/ commentary).

```
<?php
// ... your code
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// get current theme and it's variables
$current_theme = variable_get('theme_default','none');
$themes = list_themes();
$theme_object = $themes[$current_theme];

// uncomment to display structured information about $theme_object
// var_dump($theme_object);

// get current theme path
$theme_path = dirname($theme_object->filename);

    // get path of each stylesheet from current theme
  $final_stylesheets = array();
    if (!empty($theme_object->stylesheets)) {
    foreach ($theme_object->stylesheets as $media => $stylesheets) {
      foreach ($stylesheets as $name => $stylesheet) {
        $final_stylesheets[$media][$name] = $stylesheet;
      }
    }
  }
  foreach ($final_stylesheets as $media => $stylesheets) {
    foreach ($stylesheets as $stylesheet) {
            // will print relative path to the stylesheet
            // here you can wrap each stylesheet in <link type="text/css" ....> tags
            // and compose the output for hte head section of your script
            print $stylesheet;
    }
  }

    // Do same for scripts
  if (!empty($theme_object->scripts)) {
    foreach ($theme_object->scripts as $name => $script) {
      $final_scripts[$name] = $script;
    }
  }
  foreach ($final_scripts as $script) {
    print $script;
  }
?>

```

all you have left to do is to wrap each `$stylesheet` and `$script` in appropriate tags and insert that into the head.
> 3 votes

---
Tags: 7, theming, caching, bootstrapping
---


# Question
Title: Drupal 7 - Get pages created from custom modules listed under Entity reference field
I'm using Drupal 7 Entity Reference field in one of the content types. I want to populate the Auto complete field with pages created using my custom module.

Currently in the options, it is showing only the content types that are existing. How can I achieve this?

# Answer
why don't you serve regular nodes of a new content-type in your hook\_menu callback ? so you could easily reference them !

```
$html = node_view(node_load(948));

```
> 0 votes

---
Tags: 7, entities, database
---


# Question
Title: Some drupal database operations won't complete
On a development server (and it's sister staging server), I'm not sure how I got myself into this situation. When running `drush updatedb` I get this error below.

```
$ drush updatedb
The following updates are pending:

redirect module :
  7101 -   Add status field.
  7102 -   Disable redirects that could cause infinite loops.

webform module :
  7322 -   Add index on {webform_submitted_data}.data.

Do you wish to run all pending updates? (y/n): y
Cannot add field redirect.status: field already exists.                                       [error]
Performed update: redirect_update_7101                                                        [ok]
Cannot add index data to table webform_submitted_data: index already exists.                  [error]
Performed update: webform_update_7322                                                         [ok]
Finished performing updates.

```

I occasionally dump the production server database onto dev and stage to have an updated copy.

Is there a way I can push through this?

# Answer
> 0 votes
Is everything working fine on the production server? If so, try erasing the development database, and then copy the production database over it again. Drush sql-sync does not delete the target database by default.

```
drush @dev sql-create
drush sql-sync @prod @dev

```

---
Tags: drush, updating
---


# Question
Title: How to alert users when new content is added via email and/or text message?
I have a membership Drupal 7 website and I'd like to automatically alert users via their email address and/or text message to their cell phone when new content is added? I'd also like to give registered users the ability to select/change these communication preferences.

Is there any Drupal way/technique that can provide this functionality?

# Answer
> 0 votes
Have a look at my answer to "How to send an SMS message when a Webform is submitted?", which is a variation of your question here. It describes how you can use the Rules module to get this to work. In your case just use a Rules Event like "after saving new content", and optionally add some appropriate Rules Conditions to better fit your exact needs.

---
Tags: 7, users
---


# Question
Title: How do you display all the tpl.php template files that are being loaded on the current page?
Is there a function to show all the tpl.php template files being loaded on the page? Also showing the overrides too. I'm looking for a specific tpl file, but i have hundreds of the same tpl file that all have the same code and I'm not sure which file is the correct one.

# Answer
> 1 votes
the only thing that comes to mind is to uncomment `$conf['theme_debug'] = TRUE;` in setting.php. The description for this setting pasted below.

> **Theme debugging:**
> When debugging is enabled:
> -- The markup of each template is surrounded by HTML comments that contain theming information, such as template file name suggestions.
>
> -- Note that this debugging markup will cause automated tests that directly check rendered HTML to fail. For more information about debugging theme templates, see https://www.drupal.org/node/223440#theme-debug.
>
> Not recommended in production environments.

If anyone knows of a better way - please share.

---
Tags: 7, theming
---


# Question
Title: I'm looking for a way to force the migration to process entries with identical keys
# The full scenario is as follows:

We have two entities (Foo and Bar). Foo has a multi-value entity reference field to Bar entities.

The migration source outputs each Foo-Bar pair in a single CSV line (manual aggregation is not possible because there are thousands of entries).

My plan was to put several entries with identical keys and using the --update flag and a custom process plugin, update the entry's entity by adding the Bar entity to the existing Bar entities instead of replacing them.

When I tried to put two entries with identical keys in a single CSV file, the migration module processed the first entry and ignored the second.

My understanding of the migration module is that each entry is assigned a key and that that key is mapped to the entity that was created by the migration.

Is there a way force the migration module to process multiple entries with identical keys?

I've asked the question on drupal.org as well

# Answer
> 0 votes
You can do this with `drush migrate-import --update`. See the migrate\_tools module.

---
Tags: migrations, importing-exporting
---


# Question
Title: Allow users to edit just the vocabulary that belong to them?
I allow users to create a taxonomy vocabulary. Then I need to be able to give permission to each user to edit their own vocabulary. I looked at the permission page but I don´t see anything like **Edit own vocabularies**.

Is there any way I can accomplish this.

Thanks.

# Answer
The Taxonomy Delegate module (http://drupal.org/project/taxonomy\_delegate) and the Vocabulary Permissions (http://drupal.org/project/vocabperms) let you delegate administration of a taxonomy to a role, but they do not do it for an individual user. You might be able to write a custom module from here, but what you're proposing goes a little against the role-based permission architecture. My search didn't seem to find one that does exactly what you want.
> 1 votes

# Answer
Personally, I'd lean toward having users create nodes and using node references or relates in place of term references. Then use a view on the node reference that limited the choices to those items the user had created. I'm not a big fan of terms tho, so I'll admit my solution is a little biased.
> 1 votes

# Answer
The nesting can be achieved with draggable views https://www.drupal.org/project/draggableviews
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: Is there a significant performance difference between the Computed Field module and writing code?
When I got started using Drupal 7, I added several fields to my site using the Computed Field module (to calculate age, zodiac sign, and so on).

Now that I have been using Drupal 7 for a few years, I realize that it is generally not a great practice to write PHP code in the UI, as the Computed Field module requires. But, the code I am using has worked for the past few years, so that is no longer an issue.

However, I am wondering if there is a significant performance difference between using the Computed Field module (saving the result in the DB) vs. running the PHP in `hook_node_presave()` or in a similar fashion somewhere in a custom module.

Would removing my computed fields (and uninstalling the Computed Field module) and replacing them with fields in a custom module significantly increase performance?

# Answer
I have used the computed field module a few years ago, and immediately started to "not" use it.

* In most cases, data that goes into computed fields do not need to be stored at all. They are often simpler calculations. Storing then and their retrieval cost can easily go more than the time it takes to calculate them.
* Performance difference between an `eval()`d code and code in a file, I wouldn't call it significant. But in best practices perspective, a custom module is significantly better.
* If you update your Drupal core version between major versions, chances are that you will need to update the code anyway, because Computer Field cannot migrate the PHP code for you.
* In most cases, you wouldn't even have to save data in your custom module. `hook_node_view` would be a great candidate because you have your full node objects there, and you can easily modify a lot of things. Extra field hooks can be useful as well. As you can see, a custom module can have different approaches.

Bottom line, I would go ahead and put the code to a custom module.
> 1 votes

# Answer
"Significant" really depends on too many things - how often such nodes are created, how many users (anon/auth) does your website have, which other modules you have installed, what's your workflow setup (e.g. Rules, moderation modules, etc.) and so on.

While doing this through your code is definitely going to be faster, I doubt you will really notice performance improvements. Doing things in code will in most cases have lower overhead than installing a module to do the same.
If you're really wondering about exact performance differences, you will have to benchmark it with Devel and xdebug for example.

However, you already mentioned another important point - it's generally not a good practice to have raw PHP code entered anywhere in admin. Sometimes it's faster to do it (e.g. in Rules, Views or other contrib modules), but over time you should look to migrate those changes to code. Not to mention that you will reduce the number of modules on your website, which is generally a good thing.
> 1 votes

# Answer
There is a performance difference - code entered through the UI is executed by running through PHP's eval() function. Code run through eval() cannot be cached via APC or OpCache, so it naturally runs slower than corresponding code in a module.

However, ultimately this likely won't be a huge difference performance-wise if you aren't creating and updating nodes too often. However, it is generally not best practice, and makes it impossible to apply change management / version control processes to that code.
> 1 votes

# Answer
If you're interested in a possible alternative for the Computed Field module, which doesn't require the **PHP filter** to be enabled, then have a look at the Math field module as another alternative.

Refer to my answer to "How to use Computed\_field as a product of an existing one?" for way more details on that.
> 1 votes

---
Tags: 7, performance, entities
---


# Question
Title: Limit reference field to nodes with referenced user
I have two content types, Restaurant and Lunch.

Restaurant content is created by content admins, and can be viewed by anyone.

Lunch has an entity reference field that references nodes of type Restaurant.

Logged in users need to be able to create their own Lunch content, but only see their own Restaurant in the referenced node select list.

Content admins can also create Lunch content, but they need to see all available Restaurants in the select list.

I'm thinking I need to put a user reference field to the Restaurant content type, and then I could filter a reference view by the referenced user? But here is where I get stuck, how then will content admins be able to see all Restaurants in the select list?

# Answer
> 1 votes
I found this solution that works:

> Permissions (for a given content-type) Administrator & Staff - Edit ANY content Normal Member - Edit OWN content
>
> Views Contextual Filter - Content: Author UID
>
> WHEN THE FILTER VALUE IS NOT AVAILABLE \- Provide default value: Type - "User ID from Logged in User"
>
> WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED \- Specify validation criteria: Validator - "USER" \- Type of user filter value to allow - "Only allow numeric UIDs" \- Restrict user based on role: Restrict to the selected roles - SELECT the role who can only edit his own content \- Action to take if filter value does not validate - "Display All Results for the specified data" \[important\]
>
> The last step (marked important), makes all the data (view results) available to other users, who have access to edit any content.

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

---
Tags: users, entities
---


# Question
Title: Views to Recognize my Custom Entity's One-to-Many Reference
I have a drupal 8 custom entity and have it referencing another custom entity of a different type. It is a one-to-many relationship like a department with assets. It won't recognize the assets relationship (but it will recognize the one-to-ones). How do I make that bridge in my EntityViewsData extended class so that I can use assets in the Relationships section of the Views UI? I have scoured the docs and core entities and cannot find the answer.

More info: The department has a base table 'department' and another table 'department\__assets' that the reference created. 'department\_assets' has a field 'entity\_id' that connects the table to the department and a field 'asset\_target\_id' that connects the asset table. The assets base table is 'asset'.

# Answer
That's currently a gap in the automatic entity views data integration, it can only do multi-value configurable fields.

Work is going on to improve this, not sure if it will make it into 8.1 now, probably it will have to wait for 8.2, but you could already use the patch: https://www.drupal.org/node/2477899
> 0 votes

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


# Question
Title: How do I insert a <span> </span> tag inside the <a> </a> tag on my main menu
I have asked exactly this question on Stack Overflow, but it makes more sense to ask it here.

I'm trying to make the text between my tag not display by wrapping it in a and then styling that.

I've added the following function to my template.php file, but I cannot see any difference on the front end; the span just does not appear. (I have cleared my cache.)

Am I using the right function? What am I doing wrong?

```
function my_theme_link($variables) {
  return '<a href="' . check_plain(url($variables['path'], $variables['options'])) . '"' . drupal_attributes($variables['options']['attributes']) . '><span>' . ($variables['options']['html'] ? $variables['text'] : check_plain($variables['text'])) . '</span></a>';
}

```

# Answer
> 8 votes
Rather than building the anchor tag, and passing the result of `url()` to `check_plain()`, you should call l(), which builds the tag for you.
Remember to set `$options['html']` to `TRUE` (where `$options` is the last parameter passed to `l()`), when the string you pass as first argument to `l()` contains HTML tags; by default the function assumes `$options['html']` is `FALSE`.

# Answer
> 4 votes
Have a look at http://drupal.org/node/457740 / http://drupal.org/node/988842 and the devel / theme developer module might be useful too.

I think the function your using is for Links in general and is non specific to any menu..

```
function THEMENAME_links__system_MENUNAME_menu($variables) {
  $output = '';
  foreach ($variables['links'] as $link) {
    $output .= l('<span>'. check_plain($link['title']) .'</span>', $link['href'], $link);
  }
  return $output;
}

```

EDIT: included span.

# Answer
> 2 votes
I found the solution to this problem after a lot of searching. By the way this works to customize the output of the links of any specific menu.

Let me just say first that customizing the primary or main menu links is something essential to any theming, and the only reason I can think of why Drupal programmers made it so hard to do is so that professional Drupal themers can keep their jobs!

I saw solutions using the theme\_link function : bad idea because this will alter the output of ALL your links, which will break your site's layout.

So my approach is to you override the theme\_menu\_link function. I add a condition to use the override only on the specific menu I want. In this example I chose the primary links. To know the name of the menu you want to theme you have to put dsm($variables) and usse the Devel module.

```
function yourtheme_menu_link(array $variables) {

  $element = $variables['element'];
  $sub_menu = '';

// Replace 'menu_link__menu_block__1' with the name of the menu you want to theme.
if ($element['#theme']['0'] == 'menu_link__menu_block__1') {
  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }

  $title = $element['#title'];

// I put the span tags in the title.
  $element['#title'] = '<span class="yourclass1"></span><span class="yourclass2">' . $title . '</span><span class="yourclass3"></span>';
// I tell the l() function to keep the HTML tags.
  $element['#localized_options'] += array(
    'attributes' => array(),
    'html' => TRUE,
  );
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}
// The function renders the links from all the other menus without modification.
if ($element['#below']) {
  $sub_menu = drupal_render($element['#below']);
}
$output = l($element['#title'], $element['#href'], $element['#localized_options']);

return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

```

# Answer
> 2 votes
This outputs the same result than the code shown by Taerno, and it works fine in Drupal 7.12.

```
function yourtheme_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }

  $element['#localized_options']['html'] = TRUE;
  $linktext = '<span class="your_class">' . $element['#title'] . '</span>';

  $output = l($linktext, $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

```

You could add in the following code, where "menu\_link\__menu\_block\__1" is the name of your menu.

```
if ($element['#theme']['0'] == 'menu_link__menu_block__1') {

}

```

I found the name of the menu by printing `$element['#theme']['0']` for my menu.

I am trying to add the span to the parent link only, so I will post when I have done that.

# Answer
> 1 votes
You might be interested in the Theme Developer module. It lets you click on elements of a Drupal page to discover which theme function/template generated them, what arguments were passed in, which alternatives are available, etc.

# Answer
> 1 votes
Most of the cases where you would have needed an extra span before can now be solved with css only:

```
li {
  position: relative;
  padding-left: 25px;
}

li:before {
  content: "";
  position: absolute;
  left: 0;
  top: 0;
  width: 20px;
  height: 20px;
  background: url('../images/icons.png') no-repeat;
  background-position: 0 0;
}

```

---
Tags: routes, theming
---


# Question
Title: How do you save an entity reference value programmatically?
I am using organic groups, which creates an entity reference field on a content type. Now i have a custom module that is supposed to create a node programatically and i am having trouble with saving the entity reference field.

Error message i get:Notice: Undefined property: DatabaseStatementBase::$nid

Here is what i have tried:

```
$qry= db_select('node', 'n')
           ->condition('type', 'some_og_content_type', '=')
           ->condition('title', 'some_title', '=')
           ->fields('n', array('nid'));
$ogRef= $qry->execute();

$ogNid = $ogRef->nid;

$node->og_group_ref['und'][0] = array('target_id'=>$ogNid);

//i also tried this
$node->og_group_ref['und'][0]['target_id']=$ogNid;

```

# Answer
> 2 votes
You need to get the results of your query after `$query->execute()` by for example calling `$query->fetchAssoc()` or `$query->fetchAllAssoc(..)`.

Using `$node->og_group_ref[LANGUAGE_NONE][0]['target_id']` is correct.

Be aware of the fact that your query might have multiple results. Do something like this to traverse them all:

```
$result = $query->execute();
while($entry = $result->fetchAssoc()) {
  $node = node_load($entry['nid']);
  // set the field and save the node
}

```

Depending on the number of expected entries you could also use EntityFieldQuery explained here https://www.drupal.org/node/1343708.

Another edit: When you want to set a field on a newly created node better use `hook_node_presave` or `hook_node_insert` then you do not need to care about searching for your node.

---
Tags: nodes, database, entities, organic-groups
---


# Question
Title: Need to save node twice to get wanted result
I have made 2 custom tokens that I use to determine the URL alias in the Pathauto pattern. They work fine too, but since my custom tokens rely on certain (taxonomy) fields in the node, they always get the "old" field value when the user changes them. The url alias isn't correct until the second time I save the node. Thus I need to "presave" the node immediately when the user changes the field value, so that the new token value is taken into consideration when saving the node... How can I do that?

Since the change is done on the client side I would need to use Ajax to call node\_save or hook\_node\_presave directly when the field value is changed?

Any help is appreciated :-)

EDITED: I have realized that I probably need to write a JS script that uses ajax to call a php function that saves the node when the field is changed. So the question now is if that is wise to do when the user is in the editing mode… ?

Edited again:

I finally worked it out. I skipped the JS solution and opted for using field\_attach\_presave('node', $node) and field\_attach\_update('node', $node) in the function hook\_node\_presave. Doing so permits to save 2 specific fields programmatically just before the node is saved definitely by the user. And Pathauto can use those 2 fields as tokens for my URLs. It works too :-). There are many reasons for this non straight-forward solution, a bit to lengthy to explain here (migration is involved among other tings). But I am happy with this solution. Thanks for the input though!

# Answer
Happy you solved it without walking around it via AJAX, I think it was a good call. I am still gonna pick up on this thread though, simply out of stubbornness, please bear with me. :-)

So, your hook\_node\_presave entry point is fine and in all practical aspects you probably will not need to read further down. However, your tokens should have been available from the very beginning to Pathauto. The problem was - following your code from this revision \- the use of the menu\_get\_object() function. I assume the following caused the problem:

1. You created and saved a new node with your migration code
2. Your hook\_tokens implementation was called from the Pathauto module during node\_save
3. menu\_get\_object was called and returned nothing
4. New node was created with the wrong URL path

The reason menu\_get\_object returned nothing is because the new node was not yet available via Drupal's routing. This is expected since all new nodes need to be properly saved once to get a route like node/NID ). This also explains why your code worked properly for a - now - existing node, with a registered route.

Your code would actually have worked fine if you had used the $data parameter, you could have picked your node object from there like this:

```
// $node = menu_get_object();
$node = $data['node'];

```

I tried this quickly in my sandbox and I could both reproduce the original problem and also solve it.

Conclusion: Your code, if you still want to use it, and get rid of the additional hook\_node\_presave implementation, should work fine if you apply the above change.

Cheers!
> 3 votes

---
Tags: 7, tokens
---


# Question
Title: Add multiple friends at once with user relationships
I am using the User Relationships module and I created a table in Views with all of the site users.

There is a field where you can add or remove a friend. But (especially the first time) the users must be able to add multiple friends add once. For example with check boxes and a "send friend request" on the bottom of the page.

I have tried to accomplish that with Views Bulk Operations but there is not a integration with that module. What can I do?

# Answer
> 2 votes
Write your own integration!

Really, Views Bulk Operations is quite an easy module to write a plugin for and optionally you can submit it to the User Relationship project to have it maybe embedded in the main project. There is a complete tutorial here, but I will briefly explain each step of the process.

First off, you need to create a custom module. Create a folder with a fitting name for your module, like `user_relationships_vbo` or something. Add a `user_relationships_vbo.info` (writing .info files) and a `.module` file. The module file should contain several specific functions to have it work with VBO.

## The action

Implementation of hook\_action\_info(), this defines the action. On what entities it can act, what the action is called, how it can be configured and if it has an extra VBO configuration option.

## The VBO configuration form

This is an optional form that adds settings the the Views VBO config form, allowing you to define additional settings. In your case this is not really important as you probably just want to relate users.

## The bulk configuration form

This forms shows after your chose your action in VBO, and can be used to define settings for the current batch. You could for instance use this the choose to have the requester specify the relationship type. Again in the simplest form you would not need this.

## The actual action

This is what will eventually relate the users. You can make this as long and as complicated as you like with all kind of notifications, etc. But the basics is to just add the relation.

## So the code

Your .module file might look like this:

```
<?php
// The action definition
function user_relationships_vbo_action_info() {
  return array(
    'user_relationships_vbo_relate_users' => array(
      'type' => 'user',
      'label' => t('Relate users to the current user'),
      'configurable' => FALSE,
      'vbo_configurable' => TRUE,
      'triggers' => array(),
    ),
  );
}

//The per batch form
function user_relationships_vbo_relate_users_form($settings, &$form_state) {
  $form = array();
  $form['type'] = array(
    '#type' => 'select',
    '#title' => t('Choose your relation type'),
    // This assumes all users have access to all relationships. You might want to add a filter to check access somehow.
    '#options' => user_relationships_types_load(),
    '#required' => TRUE,
    '#default_value' => isset($settings['settings']['type']) ? $settings['settings']['type'] : '',
  );
  return $form;
}

// The form submission
function user_relationships_vbo_relate_users_submit($form, $form_state) {
  $return = array();
  $return['type'] = $form_state['values']['type'];
  return $return; //Note, return value here must be an array.
}

// The actual action
function user_relationships_vbo_relate_users(&$target_user, $context) {
  // Get the current user
  global $user;

  // See user_relationships_request_relationship()
  // http://api.drupalhelp.net/api/user_relationships/user_relationships.module/function/user_relationships_request_relationship/7

  user_relationships_request_relationship($user->uid, $target_user->uid, $context['type'], FALSE)

}
?>

```

Read the rest of the tutorial, but this should get you started.

---
Tags: views, users
---


# Question
Title: What's the alternative for my failing PHP code about block visibility based on user?
I would like to remove certain blocks, so that admin can not see them. In block visibility settings - in pages tab, I try to put followng php code but with no effect. (In user tab there is no php field to put code.)

```
<?php
if(arg(0) == 'administrator' )
return true;
else
return false
?>

```

What I am doing wrong?

EDIT: On my other D6 site I use argument:

```
 user_access('access administration pages')

```

but on D7 site it does not work, what can be another way of doing it?

# Answer
> 2 votes
You could perhaps just set the "Roles" options under the block visibility settings.

Alternatively, something like:

```
global $user;
return in_array('administrator', $user->roles) ? FALSE : TRUE;

```

# Answer
> 0 votes
Just using "r**O**les" (as in the comments below the prior answer) is indeed not going to help/work. Instead, if you're willing to consider using "r**U**les", then there is a solution for this question, as further explained below.

# Part 1: Rules block visibility

Have a look at the Rules block visibility module. Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:
>
> * Need to show a block only for users registered more than a month ago?
> * Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
> * What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules intercept the actual user who's using the site, i.e. if it is **YES** or **NO** (a boolean, right?) the user with `uid = 1`.

# Part 2: Create an appropriate Rules Component

The Rules block visibility module doesn't have a lot of documentation, except in the README.txt that comes with this module. Here is what the crucial part of it is (to get the idea):

> Configuration is done on a per-block basis. To control a block visibility using a rule component, go to the block settings page, scroll down to the "Rules" tab, and select the Rules component that you want to use.
>
> Notice that to be able to be used by this module, a Rules component *must* be constructed in a very specific way. See the next section for more information.

This module comes with 2 sample Rules Components, that should help to understand the concept behind it.

By looking at these samples, I was able to create another Rules Component which looks like so:

```
{ "rules_block_visibility_hide_block_for_user_1" : {
    "LABEL" : "Hide block for user 1",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "NOT data_is" : { "data" : [ "site:current-user:uid" ], "value" : "1" } }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

```

You should be able to import this rule in your own environment.

What this Rules Component does is "only" return a boolean (**1** or **0**), based on the condition if the user's uid is YES or NO equal to `1`.

With that, we're coming close to an actual answer to your question. But note that, as a variation, you could also have used a rules condition like "does this user yes or no have a role like administrator".

# Part 3:

Head over to the "Block" settings for the block you want to hide for the user with `uid = 1`. At the bottom of it's settings, within the typical "Visibility settings", there is now (after you enabled the Rules block visibility module as in Part 1) an extra tab labeled "*Rules*". Using that tab will allow you to select a "Rules Component" that will do what's documented below that selection list field, ie: "***Show this block only if the selected rule returns a positive value. Important: to be listed here, a block visibility rule must have specific parameters and return values.***".

And guess what, in my case I just selected my Rules Component from Part 2

**Note**: it doesn't matter what type of block it is (created by a view, or something else), it works in all cases.

---
Tags: 7, blocks
---


# Question
Title: How to make "Page specific visibility settings" for blocks more flexible?
My problem is that depending on a running mode my Drupal website might have either regular permalinks, or pretty, aliased ones. And "Page specific visibility settings" for blocks on specific pages (*Show on only the listed pages*) do not work across the modes.

It would be logical if let's say: **node/23** syntax could work in any case, but it seems that it doesn't.

Do I have to change every setting for every block every time I switch permalink structure? Or there is more flexible solution to this?

# Answer
If you need to control block visibility then the Context module is the way to it.

(edit) If you use the Context module you won't have to mess around with these types of things and more importantly neither does Drupal which in fact makes it faster. You can read more about Blocks, Context and Panels, another alternative to Blocks, here.
> 1 votes

# Answer
Below is a solution that should work for `domain.com/?q=node/23` **AND** `domain.com/about-us` (as in one of the comments), by using the Rules module.

# Part 1: Rules block visibility

Have a look at the Rules block visibility module. Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:
>
> * Need to show a block only for users registered more than a month ago?
> * Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
> * What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules intercept the actual URLs your using.

# Part 2: Create an appropriate Rules Component

The Rules block visibility module doesn't have a lot of documentation, except in the README.txt that comes with this module. Here is what the crucial part of it is (to get the idea):

> Configuration is done on a per-block basis. To control a block visibility using a rule component, go to the block settings page, scroll down to the "Rules" tab, and select the Rules component that you want to use.
>
> Notice that to be able to be used by this module, a Rules component *must* be constructed in a very specific way. See the next section for more information.

This module comes with 2 sample Rules Components, that should help to understand the concept behind it.

By looking at these samples, I was able to create another Rules Component which looks like so:

```
{ "rules_block_visibility_hide_block_for_user_1" : {
    "LABEL" : "Hide block for user 1",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "NOT data_is" : { "data" : [ "site:current-user:uid" ], "value" : "1" } }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

```

What this Rules Component does is "only" return a boolean (**1** or **0**), based on the condition if the user's uid is YES or NO equal to `1`.

You should be able to import this rule in your own environment. After you do, you should replace the Rules Condition. Which in the example here was about which user is using the site, i.e. if it is **YES** or **NO** (a boolean, right?) the user with `uid = 1`.

With that, we're coming close to an actual answer to your question.

# Part 3: Set Block Visibility using the Rules Component

Head over to the "Block" settings for the block(s) you want to hide. At the bottom of its settings, within the typical "Visibility settings", there is now (after you enabled the Rules block visibility module as in Part 1) an extra tab labeled "*Rules*". Using that tab will allow you to select a "Rules Component" that will do what's documented below that selection list field, ie: "***Show this block only if the selected rule returns a positive value. Important: to be listed here, a block visibility rule must have specific parameters and return values.***".

So to complete the picture, you just select the Rules Component from Part 2 (which you should have tuned to fit your URL requirements).

# Part 4: Further refinements

If you have a lot of such nodes, you may want to also add the Rules URL Argument module to the mix. Have a look at my answer to "How to use the Rules module to implement a custom redirect for an outdated URL?" to get an idea what you can do with that module.

**Note**: it doesn't matter what type of block it is (created by a view, or something else), it works in all cases.
> 0 votes

---
Tags: blocks
---


# Question
Title: How to apply coupon in commerce order programmatically?
I'm working on creating web services for mobile applications to use drupal as backend. When ever the user applying a coupon code through mobile application, I'll get the coupon code through web services as JSON data.

So, How can I validate and apply the coupon to the order programmatically. I found the below answer from StackExchange (programmatically add line item of commerce\_discount type to order). But, what value I need to pass for $discount\_name. And how can I get it?

```
commerce_discount_fixed_amount(EntityDrupalWrapper $wrapper, $discount_name);

```

# Answer
When you are creating a discount, you will enter the name and the system will automatically generate machine-name. You need to use the machine name as an argument for `commerce_discount_fixed_amount()` function.

Here's a screenshot:

Here's how you would use it:

```
commerce_discount_fixed_amount(EntityDrupalWrapper $wrapper, 'discount_test_discount');

```
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: Add a new role using the Drupal Services Rest api
I'm trying to create a new role using the drupal services module. I am able to update a user with an already created role but can't find a way to add a new role. I'd rather not build a custom service for this so wondering if anyone knows of a way to do this without resorting to that.

# Answer
> 0 votes
**First** of All you could create the custom resource in a custom module and enable it, for doing that follow that tutorial

**Second** in the callback function use that code to create a new role

```
$role = new stdClass();
$role->name = 'editor';
// $role->weight = 10;
user_role_save($role);

```

**Let** the role name be an argument taken from the request.

---
Tags: services, users, 8
---


# Question
Title: How can I make my Drupal website automatically reflect the changes when the DB values change?
In performance I have caching turned off, yet if I update a value in the DB directly I have to flush the cache to see changes on my site. Why is that? (ex: using phpmyadmin and changing a value)

I'm inserting/updating values to my DB externally from another server that is not using Drupal. (using mysql)

How can I make my Drupal website **automatically** reflect the changes when the DB values change?

# Answer
The settings you are referring just tell Drupal to use the cache\_page table.
See `drupal_page_footer()` that contains the following code.

```
  if (variable_get('cache', 0) && ($cache = drupal_page_set_cache())) {
    drupal_serve_page_from_cache($cache);
  }
  else {
    ob_flush();
  }

```

For the fields, there is the cache\_field table (cleared by `field_cache_clear()`), which is used from the field CRUD API, but also from the field attach API, which includes functions like `field_attach_load()` or `field_attach_update()`. If you are writing a field table without using one of the field API functions, such as in your case, then you need to clear the field cache; if you look at the code of `field_attach_update()` you can understand exactly which cache ID you should pass, to avoid clear all the cache for no reason.
> 1 votes

# Answer
> Keep in mind there is a table for the field revisions. Then, that page is for caching pages, not for caching other things; you aren't telling Drupal to completely avoid caching. – kiamlaluno♦

You got my wheels turning.

After looking at the DB, it's true, I see cache\_field table. It's probably best not to tell drupal to completely avoid caching.

I think it will be better if I just tell mysql to delete the row that I need in table cache\_field.
> 0 votes

---
Tags: 7, database, caching
---


# Question
Title: use "php code" in page manager access rules to evaluate if current og_group has content of a specific type
I'm grateful for the amazing organic groups module (and so many other drupal modules), which I am using for a civil society and social economy network platform.

I have a question, which I think would be interesting for others too. I couldn't find the answer anywhere.

Usecase: I have a page (in page manager) which outputs a tab in og\_group nodes, showing a view panel pane of og\_group content (together with other panes). Specifically, og\_group are organizations, and og\_group contents are events. So I'm showing events of each organization in a separete tab.

I wish this tab "events" to be visibile only if there is at least one node of type "event" listed as group content of the og\_group page being viewed.

In order to do this, I am trying to use page manager "access rules", which, to quote specific documentation:

> are used to test if the page is accessible and any menu items associated with it are visible.

The "only" og related rules available are:

> "Node is an OG group" "Node is an OG group content" "user membership in group" "user permissions in group"

So, I think my logic is possible with the generic "php code" rule. But I'm no coder, yet.

Anybody could give me a hint about what code should I write to check if te viewed node (which is an OG group) has at least one event associated with it as group content?

Thanks!!!

Config: D7 7.41, php 5.2.4, panopoly 7.x-1.28, og 7.x-2.7, ctools 7.x-1.8, panels 7.x-3.5

Update: as @Stefanos suggested in his answer, I am searching for a kind of "no results" behavior of views module, in page manager.

@Stefanos, here is the context available in the page:

# Answer
> 1 votes
Direct answer: To do this with the code you provided, you should use something like the following:

```
$node = $contexts['argument_entity_id:node_1']->data;
$args = array($node->nid);
return empty(views_get_view_result('rbv_view_group_content','panel_pane_3',$args));

```

Alternative answer: I have an alternative suggestion, and unless you absolutely want to use the Page Manager, it should allow you to solve your problem without any coding.

So, if you read so far... :-), I would suggest using Views and setting up a path that will 'link' your view to your group node's URL. You are probably already using a view to list your Events. You can set up a page for that view that has a path like the following:

```
node/%nid/events

```

You should further configure your page to be rendered as a "Menu Tab", titled "Events".

This Views Page will now be linked to your Group page, and you will be able to handle its behaviour in the case of no results (Events) for that og\_group node; for your case to simply hide it.

To get this all working, you would also need to set up your contextual filters to use the og\_group nid.

This is a bit theoretical, but I am not entirely sure of your setup. I hope it helps you though!

---
Tags: organic-groups, chaos-tool-suite
---


# Question
Title: Looking for informaton on Drupal core security process, audits and benchmarking
I'm looking for information on Drupal's security processes, any audits carried out, benchmarking against securty standards, what happens security-wise before a new Drupal release etc...

The most useful info i have found thus far is here:

http://drupalsecurityreport.org/

and here:

https://www.drupal.org/security-team

But it doesn't give much detail on internal processes or on accreditations etc.

Danny.

# Answer
> 1 votes
There are 2 websites you should look at, http://buytaert.net/greg-knaddison-and-drupal-security and http://crackingdrupal.com.

---
Tags: security
---


# Question
Title: How to link price to the product display?
I have a page of product teaser links (image, title, price) and I was able to successfully link all except the price to the content with the module Linked Field.

The price field acts differently. The settings are pulled from the Variation settings, and even when a link is set there, the price display remains as before - no link.

Is there a way in Drupal commerce to link the price to the product display?

# Answer
You normally don't link all fields to your product display, but you reference the product from your product display using the `commerce_product_reference` that ships in the Drupal Commerce package.

You can create a content type and a product type. Then on the content type add a product reference field. Now the node and the product are linked and all fields (including price) and other properties are accessible for both entities in Views, Rules, etc.

Optionally you can enhance the experience using Inline Entity Form as a widget for the commerce product field. That allows you to fill all the product properties (such as price) when creating a node.
> 0 votes

---
Tags: commerce, navigation
---


# Question
Title: How to hide block while field in database is empty?
I have 2 blocks for the same content type (Banner):

* block 1 = filter criteria : field video:input(not empty)
* block 2 = filter criteria :

+ field video (is empty)
    + field image (is not empty)

What I want :

* if field video is empty : show only block 2 and hide block 1
* if field video is not empty : show only block 1 and hide block 2

Any suggestions how to make this work?

# Answer
# Part 1: Install the Rules block visibility module (and Rules)

You should be able to get this to work using the Rules block visibility module. Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:
>
> * Need to show a block only for users registered more than a month ago?
> * Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
> * What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules intercept the value of your field video (i.e. if it is empty or not).

# Part 2: Create 2 appropriate Rules Components

The Rules block visibility module doesn't have a lot of documentation, except in the README.txt that comes with this module. Here is what the crucial part of it is (to get the idea):

> Configuration is done on a per-block basis. To control a block visibility using a rule component, go to the block settings page, scroll down to the "Rules" tab, and select the Rules component that you want to use.
>
> Notice that to be able to be used by this module, a Rules component *must* be constructed in a very specific way. See the next section for more information.

This module comes with 2 sample Rules Components, that should help to understand its concept.

By looking at these samples, I was able to create another Rules Component which looks like so:

```
{ "rules_block_visibility_hide_block_for_user_1" : {
    "LABEL" : "Hide block for user 1",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "NOT data_is" : { "data" : [ "site:current-user:uid" ], "value" : "1" } }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

```

You should be able to import this rule in your own environment.

What this Rules Component does is "only" return a boolean (**1** or **0**), based on the condition if the user's uid is YES or NO equal to `1`.

With that, we're coming close to an actual answer to your question: create 2 such Rules Components (1 for your block 1, and 1 for your block 2). And within each of those 2 Rules components, you only have to adapt the Rules Condition (as compared to my sample Rules Component here, apart probably from its machine name or so):

* Rule 1 (which will be used to manage the visibility of Block 1) should have a condition like "field video is NOT empty".
* Rule 2 (which will be used to manage the visibility of Block 2) should have a condition like "field video is empty".

# Part 3: Set Block Visibility using the Rules Component

Head over to the "Block" settings for each of your 2 blocks. At the bottom of its settings, within the typical "Visibility settings", there is now (after you enabled the Rules block visibility module as in Part 1) an extra tab labeled "*Rules*". Using that tab will allow you to select a "Rules Component" that will do what's documented below that selection list field, ie: "***Show this block only if the selected rule returns a positive value. Important: to be listed here, a block visibility rule must have specific parameters and return values.***".

Obviously, all you have to do is select Rule 1 for Block 1, and Rule 2 for Block 2.

**Note**: it doesn't matter what type of block it is (created by a view, or something else), it works in all cases.
> 1 votes

---
Tags: entities, database, blocks, views
---


title: Custom display suite field

text:
# Question
Title: Custom display suite field
# In a custom module I have defined a display suite field like so:

```
namespace Drupal\custom_dsfields\Plugin\DsField;
use Drupal\ds\Plugin\DsField\DsFieldBase;
//Views
/**
 * Plugin that renders the field.
 *
 * @DsField(
 *   id = "total_hours",
 *   title = @Translation("Total hours"),
 *   entity_type = "node",
 *   provider = "custom_dsfields",
 *
 * )
 */
class MyField extends DsFieldBase
{
    /**
    * {@inheritdoc}
    */
    public function build(){

        $node = \Drupal::routeMatch()->getParameter('node');
        $entities = [];
        $hours = [];
        foreach ($node->field_hours as $key => $value) {
            array_push($entities, $value->target_id);
        }
        $entities = entity_load_multiple('user_entities', $entities, $reset = FALSE);
        foreach ($entities as $key => $value) {
            array_push($hours, $value->field_hours->value);
        }
        $hours_sum = array_sum($hours);

        return array(
            '#markup' => '<strong>Total hours for this day ' . $hours_sum . '</strong>'
            // '#theme' => 'item_list',
            // '#items' => $hours_sum
            );
        }
    }

```

In the default display this works perfect. (open to improvements But **when I use a view, and display the teaser display with this field in it then the field is not working. Why is this?**

Some things I am questioning...

* Am I loading the node in the correct way as I am not entirely sure what routeMatch() is doing.
* Should I be doing this in a view template (hope not)

Thanks DSE!

# Answer
> 2 votes
I found a better way to access the node so this will work anywhere.

```
$this->entity();

```

Inside the current class it will load the entity, in this case, the node.

Happy drupaling!

---
Tags: views, 8, display-suite
---


title: Context taxonomy term

text:
# Question
Title: Context taxonomy term
I have a context set up:

```
Condition > taxonomy term > vocabulary.

Reaction > some blocks displayed somewhere

```

This works ok for path like `taxonomy/term/term_id` but it doesn't work for something like `taxonomy/term/term_id_1+term_id_2`

Any ideas? Thanks

# Answer
> 1 votes
This is a bit of code can help you I hope,

```
 <?php
   check_vocabulary = FALSE;
     $path = drupal_get_path_alias($_GET['q']);
     $pathnew = explode('/', $path);
     if ($pathnew[2]) {
        $vocabulary = explode('+', $pathnew[2]);
     }
    if ($vocabulary[0] == "your taxonomy") {
       check_vocabulary = TRUE;
    }
  return check_vocabulary;
?>

```

You should put it in the block under the tab `Page specificy visibility setting`, click on `Show if the following PHP code returns TRUE (PHP-mode, experts only).`

Now I'm not sure it's going to work with your setting and name but it could be a way for a solution.

```
 check_vocabulary = FALSE;

```

As we know, the system wants you to return **TRUE** to print the block so we set it false in the beginning so it's no going to print it and then remove it.

```
$path = drupal_get_path_alias($_GET['q']);
$pathnew = explode('/', $path);

```

In this part we take the path and we explode it so we get an array like this.

```
$pathnew[0]; Taxonomy
$pathnew[1]; Term
$pathnew[2]; Term_id_1+term_id_2

if ($pathnew[2]) {
    $vocabulary = explode('+', $pathnew[2]);
  }

```

We check first that `$pathnew[2]` exists and then we explode it to get all the vocabularies (if you want it separated). We split it by + so you will get

```
$vocabulary[0]; Term_id_1
$vocabulary[1]; term_id_2

```

Now we create the condition;

```
if ($vocabulary[0] == "your taxonomy") {
   check_vocabulary = TRUE;
}

```

You can compare what you want, that is just an example.

```
check_vocabulary = TRUE;

```

This is what the system wants to print the block.

```
return check_vocabulary;

```

This will return the variable **FALSE** or **TRUE**.

Let me know if it works.

# Answer
> 0 votes
Can you not change the condition to just be the vocabulary and not the term? That way it will work with any term in that vocabulary?

Also you could use the path as a condition:

```
taxonomy/term/*

```

---
Tags: 7
---


# Question
Title: Order confirmation email with html content?
I'm using drupal commerce with its submodules and need to change order's confirmation message to html format and add line items and customer profile. How can I organize this?

# Answer
> 2 votes
Use Commerce Message. It's the best supported way to handle sending emails. It includes several message types out of the box.

# Answer
> 1 votes
If HTML emails are a requirement, check out the Commerce Invoice Receipt module. Here's an excerpt from the project page:

> Provides an additional 'Invoice' display for Commerce orders, as well as a Rules action to email this invoice out to customers.
> The HTML email can be customised through template files.

---
Tags: commerce, emails
---


# Question
Title: Disclose billing cycle information on order page to customers
When customer clicks on a recurring order page he can see:

> Billing information:
> Name Lastname Some Address Some City, State 11111 United States

and then immediately after that:

> Billing cycle: \- Restricted access -

I looked high and low, tried all the different permissions for products, orders, licenses, but can't figure out how to get billing cycle information displayed on order page. I don't know why billing cycle should be restricted for the customers.

# Answer
> 0 votes
It's a module error i can display the cycle type after adding access callback on $entity\_info\['cl\_billing\_cycle'\] (commerce\_license\_billing\_entity\_info function) on commerce\_license\_billing.module.

Here is the patch file:

```
--- commerce_license_billing.module.bak 2016-03-31 00:02:29.017204562 +0100
+++ commerce_license_billing.module 2016-03-31 00:04:25.376291062 +0100
@@ -85,6 +85,7 @@
     'label' => t('Commerce License Billing Cycle'),
     'module' => 'commerce_license_billing',
     'base table' => 'cl_billing_cycle',
+    'access callback' => 'commerce_license_billing_cycle_type_access',
     'entity class' => 'CommerceLicenseBillingCycle',
     'controller class' => 'EntityAPIController',
     'metadata controller class' => 'CommerceLicenseBillingCycleMetadataController',

```

# Answer
> 1 votes
Make sure that in your roles/permissions that users have permissions to view licenses:

---
Tags: commerce
---