title: How to completely turn off caching?

text:
# Question
Title: How to completely turn off caching?
I am developing a site in Drupal 7 and caching slows my work significantly. For example, I had a theming function for a form. I was puzzled, why doesn't it work. Until I cleared the cache and it was fixed.

How to turn it off completely?

# Answer
Theme functions are handled by the theme registry: rebuilding (or worse, disabling) all your site's caches to pick up a new theme function is unnecessary and overkill.

What you can do is use the Devel module to rebuild your theme's registry on every page reload. Once installed, go to Configuration → Development → Devel settings. There, check "Rebuild the theme registry on every page load" and press the "Save configuration" button. Remember to uncheck it (or better yet, disable Devel entirely) when you're done with development.
> 22 votes

# Answer
You can replace the default cache backend to one which does not actually do anything. Simply add this to your settings.php file:

```
if (!class_exists('DrupalFakeCache')) {
  $conf['cache_backends'][] = 'includes/cache-install.inc';
}
// Default to throwing away cache data.
$conf['cache_default_class'] = 'DrupalFakeCache';
// Rely on the DB cache for form caching - otherwise forms fail.
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

```

Just to be sure, set the cache expiration time to none on the Performance page.

I actually use this in a settings.local.php file which, if it exists, gets included at the bottom of my settings.php file so I can sync settings.php from the live or staging environments to my dev environment without having to worry about using the wrong database settings, accidentally pushing dev settings to live, etc.

**settings.php:**

```
if (file_exists(__DIR__ . '/settings.local.php')) {
  require_once __DIR__ . '/settings.local.php';
}

```
> 29 votes

# Answer
You can't turn of *all* caching completely. And if you actually did, it would slow down your progress *so* much more. Consider the time it takes it actually clear the cache, that's what *every* single page load would be like.

There are so many hooks running for building information about the available entities, fields, forms, implemented hooks etc that only need to execute once currently, you don't want to prevent that.

As you get used to Drupal, you will soon learn what things that require a cache clear, and probably get friendly with either the admin menus shortcut or `drush cc all`, and this will no longer be an issue.
> 10 votes

# Answer
The approach in this example is version agnostic. The code is for Drupal 7.

https://stackoverflow.com/questions/4436496/drupal-disable-css-cache/41776131#41776131
> 1 votes

---
Tags: 7, caching
---


# Question
Title: Display menu Shopping cart (# items) and total amount
In the user menu, I added a menu link to the shopping cart:

Title: "Shopping cart (# items)"

Path: "cart/my"

How to add the total amount of the order, at the end of the title ?

I think it is necessary to use the file "template.php" of my theme.

```
/**
 * Implements hook_menu().
 */
function commerce_cart_menu() {
  $items = array();

  $items['cart'] = array(
    'title' => 'Shopping cart',
    'page callback' => 'commerce_cart_view',
    'access arguments' => array('access content'),
    'file' => 'includes/commerce_cart.pages.inc',
  );

  $items['cart/my'] = array(
    'title' => 'Shopping cart (# items)',
    'title callback' => 'commerce_cart_menu_item_title',
    'title arguments' => array(TRUE),
    'page callback' => 'commerce_cart_menu_item_redirect',
    'access arguments' => array('access content'),
    'type' => MENU_SUGGESTED_ITEM,
  );

  $items['checkout'] = array(
    'title' => 'Checkout',
    'page callback' => 'commerce_cart_checkout_router',
    'access arguments' => array('access checkout'),
    'type' => MENU_CALLBACK,
    'file' => 'includes/commerce_cart.pages.inc',
  );

  // If the Order UI module is installed, add a local action to it that lets an
  // administrator execute a cart order refresh on the order. Modules that
  // define their own order edit menu item are also responsible for defining
  // their own local action menu items if needed.
  if (module_exists('commerce_order_ui')) {
    $items['admin/commerce/orders/%commerce_order/edit/refresh'] = array(
      'title' => 'Apply pricing rules',
      'description' => 'Executes the cart order refresh used to apply all current pricing rules on the front end.',
      'page callback' => 'drupal_get_form',
      'page arguments' => array('commerce_cart_order_refresh_form', 3),
      'access callback' => 'commerce_cart_order_refresh_form_access',
      'access arguments' => array(3),
      'type' => MENU_LOCAL_ACTION,
      'file' => 'includes/commerce_cart.admin.inc',
    );
  }

  return $items;
}

/**
 * Returns the title of the shopping cart menu item with an item count.
 */
function commerce_cart_menu_item_title() {
  global $user;

  // Default to a static title.
  $title = t('Shopping cart');

  // If the user actually has a cart order...
  if ($order = commerce_cart_order_load($user->uid)) {
    // Count the number of product line items on the order.
    $wrapper = entity_metadata_wrapper('commerce_order', $order);
    $quantity = commerce_line_items_quantity($wrapper->commerce_line_items, commerce_product_line_item_types());

    // If there are more than 0 product line items on the order...
    if ($quantity > 0) {
      // Use the dynamic menu item title.
      $title = format_plural($quantity, 'Shopping cart (1 item)', 'Shopping cart (@count items)');
    }
  }

  return $title;
}

```

# Answer
> -1 votes
You can use https://www.drupal.org/project/menu\_badges to accomplish that.

> Once enabled, go to Administration \> Structure \> Menus, and click "list links" next to the menu containing the target item. Click "edit" next to the item and select the badge to display with the Display Menu Badge select box.

Or you can set the parent menu item of the *Shopping cart (# items)* link provided by the cart module to your menu. This menu item is provided by commerce and by default can be found in the navigation menu at *admin/structure/menu/manage/navigation*

---
Tags: 7, commerce
---


# Question
Title: Is there any away to randomize a display message in rules?
I would like to disable drupal's standard message when a new node has been saved and then via Rules (or any other recommendations) provide a pool of random messages to be displayed to the end user when a node is then saved. They will essentially say the same thing, but just in a different way.

# Answer
> 3 votes
The display message can be customized by following this procedure. You might also want to write a custom module, which may enable you to control your message display by user role.

If you want to display the status message in a different way, (there is a module for that ;-) too) try Better Messages module.

> Better Messages is a very simple module that provides "Popup-like" Drupal messages.

# Answer
> 0 votes
### Step 1: Disable Messages module

You could use the Disable Messages module to "*disable Drupal's standard message*" (as in your question). Here is a quote from its project page:

> Gives a site owner options to disable specific messages shown to end users. The core drupal message system as offered by drupal\_set\_message is an excellent way for modules to send out messages to the end users. However not all drupal site owners are keen to show all the messages sent out by drupal core and all modules to their users. This module gives site administrators a reasonably powerful way to filter out messages shown to the end users.

Some of its features are:

> * Filter out messages that match a full text string exactly.
> * Filter out messages that match a regular expression.
> * Permissions to specifically hide all messages of a given type from any role.
> * Disable all filtering for specific users.
> * Disable all filtering for specific paths.
> * Apply filtering only for specific paths.
> * Debug system to get messages in the HTML without showing it to the end users.

### Step 2: Conditional Rules module

You could use the Conditional Rules module in a custom rule (with a case/when construct), to display a Drupal message, based on whatever test you'd want to use to pick the random message to be shown.

With that all that's left for you is to think about which of the available tokens in your Rules Actions (triggered by Rules Event "After saving a new node", as in your question) is the most appropriate to make the result of that test random enough.

---
Tags: 7, rules
---


# Question
Title: Can I use the Rules module to send mass emails to authors of selected nodes?
How can I leverage the Rules module to look for nodes where a CCK field has a specific value, and when found, email those node authors?

For example, if I wanted people to login and update their profile when I add a new CCK field, how would I do that?

# Answer
If you want to use rules for that, you would have to create your own event: when you add a CCK field. You would then have to write some code to trigger then event when a new CCK field is added, and supply rules with the nodes of that type or whatever data you would need in your rule.

My guess is that the amount of custom coding needed for this to work, would be more than what is needed to just do this yourself in a custom module, with `hook_mail`. Also you might have problems configuring the rule to do what you need. I haven't tried using an array of data types in rules, so that might make things more complicated for you as well.
> 1 votes

# Answer
You might be able to accomplish this using Rules and Views Bulk Operations. The following screencast might get you started: NodeOne talks Drupal: Rules + VBO, revisited!
> 1 votes

# Answer
Take a look at the Content Access Mail module (disclosure: I made it). Here are some details about it from its project page:

> It provides an action for the Rules module that allows you to send rule-based emails to all users with permission to view a specific node.

It almost does what you want, so following on from @googletorp's comment about using hook\_mail, this might give you a head start towards your own module.
> 1 votes

# Answer
Just another bit of input here: http://www.midwesternmac.com/blogs/jeff-geerling/sending-thousands-automated-sc

I had to build a system that was much more scalable than directly shooting off hundreds or thousands of emails through Rules. Instead of doing it that way (and risking overutilizing server resources when new emails were sent), I installed the SimpleNews module, and used a few of its hooks via Rules to schedule an email that will be sent in batches on cron runs.

Of course, once you get to the scale of hundreds or thousands of emails, you might start considering using an external resource such as Amazon SES. I'm guessing you're not quite to that level :-)
> 1 votes

# Answer
An article I just wrote about combining Rules and the Queue API, for Drupal 7 is the following: Using Rules and the Queue API to batch send mass mails.
> 1 votes

# Answer
I trust you can create a view (using the Views module) of the nodes (with their authors) for which you want to send such eMails. After you succeeded in creating such view, continue like so:

1. Use Views bulk operations to enable bulk operations for each result in your view.
2. Create a Rules Component which uses Rules action "Send a message". If you want, add 2 "variables" to this Rules Component, named something like "MsgSubject" and "MsgBody". By doing so, you can use those variables as "tokens" for constructing the actual Subject and Body of your message.
3. Within your VBO settings, just execute this Rules Component. If you then use this VBO-view, you can specify the desired values for the variables used to create your Rules Component (like "MsgSubject" and "MsgBody"). So you avoid hardcoding the "***Subject***" and "***Body***" for the "Send a message" action (without those variables it would only allow you to send predefined messages). And this simply by using these variables of your Rules Component (to implement that "Subject" and "Body" of the message). That way, each time you use your VBO to send such messages, you can enter the desired "Subject" and "Body" for each of those messages.

For some other illustrations about using VBO in combination with Rules Components, refer to the answers to these questions:
> 0 votes

---
Tags: 7, rules
---


# Question
Title: How to add properties to ConfigurableLanguage config entity?
I need to add some properties to the `ConfigurableLanguage`. I need to have them editable when editing or adding a language and when getting language object from language manager service.

I can handle altering forms, but what about storing those properties and having them available with Language objects?

I was tempted to extend `ConfigurableLangue` and use hook\_entity\_type\_build() to replace `ConfigurableLangue` class with my own implementation. However I'm not sure if works for config entities too (I've used this method with content entities). Nevertheless I've noticed scattered around core few calls to static `ConfigurableLanguage::createFromLangcode()` which returns instance of `ConfigurableLanguage` class. So extending `ConfigurableLangue` won't solve my problems.

# Answer
> 2 votes
Even if it might be late for the OP, here is the way to achieve this.

As language is stored as ConfigEntity, you can use ThirdPartySettingInterface.

Here is an example<sub> entity types are not correctly define in the link.</sub> which I based my own implementation on.

Steps to follow to achieve adding properties on language entity are a set of pretty common drupal development actions :

```
// Step 1 : Altering the configuration form ( language_admin_edit_form ) in this case.

/**
 * Implements hook_form_FORM_ID_alter().
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 * @param $form_id
 */
function {our_module_name}_form_language_admin_edit_form_alter(
    &$form,
    \Drupal\Core\Form\FormStateInterface $form_state,
    $form_id) {

  //Step 2. We can retrieve the ConfigEntity the form is working on

  /** @var {\Drupal\language\Entity\ConfigurableLanguage} $language */
  $language = $form_state->getFormObject()->getEntity();

  //Step 3. Add our custom property(ies)
  $form['{name_of_our_property_1}'] = array(
    '#type' => 'checkbox',
    '#title' => t('Our custom property 1'),

    //Ok this is already a step ahead but, for the default_value
    //we can get the stored value in thirdPartySetting property of the ConfigEntity
    '#default_value' => $language->getThirdPartySetting('{our_module_name}', '{name_of_our_property_1}'),
  );

  //Step 4. We will need to hook before the entity is saved as config,
  //in order to retrieve the property values on form,
  //and adding thoses in the ConfigEntity thirdPartySetting property.
  $form['#entity_builders'][] = '{our_module_language_entity_builder_function_name}';
}

```

This will add form input with previously saved values on thirdPartySetting and add our custom entity builder. So lets define our custom entity builder :

```
/**
 * Our custom entity builder
 * @param $entity_type
 * @param \Drupal\language\Entity\ConfigurableLanguage $language
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 */
function {our_module_language_entity_builder_function_name}(
    $entity_type,
    \Drupal\language\Entity\ConfigurableLanguage $language,
    &$form,
    \Drupal\Core\Form\FormStateInterface $form_state){

    //If our property can be found from form_state values
    if ($form_state->getValue('{name_of_our_property_1}')) {
        //We can update the linked property on thirdPartySetting
        $language->setThirdPartySetting(
            '{our_module_name}',
            '{name_of_our_property_1}',
            $form_state->getValue('{name_of_our_property_1}')
        );
    }else{
        //User surely wanted to remove the previous value,
        //so remove it from thirdPartySetting property too
        $language->unsetThirdPartySetting('{our_module_name}', '{name_of_our_property_1}');
    }
}

```

Ok, now the edit form shows our property, our custom entity builder save it. Last step ahead, using our custom value somewhere else of the language edit form.

```
//So we have a language, it doesn't matter how you get it.
//Here is from the currentLanguage property

/** @var {\Drupal\Core\Language\LanguageInterface} $language */
$language = \Drupal::languageManager()->getCurrentLanguage();

//The language itself doesn't own the thirdPartySetting,
//So we need to use its matching ConfigEntity

//Getting the ConfigurableLanguageManager
/** {\Drupal\language\ConfigurableLanguageManager} $configManager */
$configManager = \Drupal::entityTypeManager()->getStorage('configurable_language');

//now load the matching ConfigEntity of Language
/** @var ConfigurableLanguage $config */
$languageConfigEntity= $configManager->load($language->getId());

//Do what you want of your property
$ourPropertyValue = $languageConfigEntity->getThirdPartySetting('{our_module_name}', '{name_of_our_property_1}');

//Alternatively we could get an array of all our module thirdPartySetting properties
$allOurProps = $languageConfigEntity->getThirdPartySettings('{our_module_name}');

//And it's done.

```

---
Tags: 8, entities
---


title: How do I hide fields conditionally?

text:
# Question
Title: How do I hide fields conditionally?
i made my own module in my drupal 7 website to hide a boolean when its value is "0" but something won't work

this is the code

```
   function MYTHEME_node_view($node, $view_mode, $langcode) {
if($node->content['field_members_only']['#items']['0']['value']=="0") {
                      hide($node->content['field_members_only']);
                    }
}

```

what's wrong? i think the conditional part is wrong if i save the statement without the IF part it's working perfectly

thanks

# Answer
You need to set access to FALSE.

```
function MYTHEME_node_view($node, $view_mode, $langcode) {
  if(isset($node->content['field_members_only']) && count($node->content['field_members_only']) && $node->content['field_members_only']['#items']['0']['value']=="0") {
    $node->content['field_members_only']['#access'] = FALSE;
  }
}

```
> 3 votes

# Answer
Try this:

```
$node->content['field_members_only']['#access'] = FALSE;

```

You might also want to consider making the if statement like this:

```
if(empty($node->content['field_members_only']['#items']['0']['value'])) {

```

From the php.net docs on empty(), the following things are considered to be empty:

* `""` (an empty string)
* `0` (0 as an integer)
* `0.0` (0 as a float)
* `"0"` (0 as a string)
* `NULL`
* `FALSE`
* `array()` (an empty array)
* `$var;` (a variable declared, but without a value)
> 1 votes

---
Tags: 7, entities
---


title: How do I get the rate vote number?

text:
# Question
Title: How do I get the rate vote number?
How do I get the rate vote number, e.g. the number after "funny," "angry," or "mad"?
I looked for the values in the database, but I didn't find a column that stores it.thank you.

# Answer
> 1 votes
I think that is the rate module, like many such modules it uses the voting api.

You should use votingapi\_select\_results() to get the results. The $criteria array that you pass to it will be

```
$criteria = array(
    'content_type' => $content_type,
    'content_id' => $content_id,
    'tag' => $widget->tag,
  );

```

I have only skimmed the code but I belive that $content\_type and $content\_id are node type and node id. The $widget-\>tag will be specific to your widget.

# Answer
> 0 votes
@Jeremy French , your Solution worked well for me (drupal 7) if you alter the array indexes like this:

```
$criteria = array(
    'entity_type' => $content_type,  //ALTERED
    'entity_id' => $content_id,      //ALTERED
    'tag' => $voting_api_tag,
);
$res = votingapi_select_results($criteria);

```

You can get `$voting_api_tag` (when `$content_type=='node'`) if you print out the node (e.g. `dsm($node)`). In my case the value was stored in

`$node->field_vote['und'][0]['votingapi_tag']`

Cheers

---
Tags: 7, rating
---


# Question
Title: Is there a solution, allowing to fill a string field by decoding the bar code?
Do you know if is there a solution which would allow to input data to a string field decoding an image with bar code ?

That is, there is a field, containing a button. Having pressed at the button, I upload an image with bar code, which immediately is decoded and received value (string, number and so on) is placed in the field. And beside that the field can be filled manually, with keyboard.

Or, is there a simular solution ?

# Answer
There is no quick fix for this for Drupal 8. The only thing that comes near for Drupal 7 is the Commerce Barcode Scanner module.

If you're willing to get your hands dirty, I can advice this Q: Reading barcode from an image using javascript.

**tl;dr**

Implement one of these three javascript libraries:
> 5 votes

---
Tags: 8
---


# Question
Title: How to prevent node creation using hook_node_submit?
Could you clarify me, how can I prevent node creation if I use `hook_node_submit` ?

What should I do in code of the hook for it ?
Do returning false ? Or throw an exception ?

That is, if some condition is true then the node simply does not create, without output of any error message.

# Answer
To stop a node being created, you need to implement `hook_node_validate` instead, and raise an error. The hook is specifically to:

> Perform node validation before a node is created or updated.

Which is what you want.

The example in the docs page is probably quite close to what you'll need:

```
function hook_node_validate($node, $form, &$form_state) {
  if (isset($node->end) && isset($node->start)) {
    if ($node->start > $node->end) {
      form_set_error('time', t('An event may not end before it starts.'));
    }
  }
}

```

For the record, `hook_node_submit` is both conceptually the wrong place to try to stop a node being created, and too late in the process to do so anyway. The node hasn't been saved by that point, but you've lost any simple opportunity to stop the remaining submit handlers running and the default process completing. Even if you found a way to short out that functionality, there would be no sensible method to feed that back to the user.

You can throw an exception or kill the page request of course, yes, but Drupal obviously won't be able to recover from that and the request will terminate.
> 2 votes

# Answer
I don't 'think you can prevent node creation using `hook_node_submit`. Once this function execute it create node.

You can modify or something like that once node created depend on your conditions.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: How can I add a playlist to content type?
I need to add a playlist of mp3 or waves to custom content type. I installed some modules, but nothing seems to work:

* I installed audiofield that allows upload of files.
* I installed some plugins, such as wordpress player, but it isn't accessible to screen readers (flash buttons are unlabeled).
* I installed jPlayer, but there are many errors when I attempt to display content, such as undefined index.continuous, undefined index.entity etc.
* I installed able player, an accessible able player, but tracks are not visible.
* I try to install jw\_player, but it doesn't install due an error index.description undefined.
* I tried to set file field as an audio file, but track are not visible.
* I tried to change theme, switched to bootstrap instead of bartik, but nothing change.

I don't know how to do. Is Drupal able to play audio files?

# Answer
> 5 votes
The aptly named AudioField module has the functionality you're describing

> Audio Field module adds new field that allows you to upload and play audio files in HTML5 audio player or one of selected Flash players. Currently it supports 6 different Flash players

It definitely works, I've used it, and it has support for both of the formats you mentioned. Follow the installation instructions and you shouldn't have any problems.

Just to nitpick, and perhaps clear up some confusion: Drupal cannot play audio files, no - your browser can, when it is given the right HTML (or when flash is used). But Drupal just generates the HTML, it doesn't have anything to do with the audio files themselves (beyond facilitating upload/storage) or how the browser interprets them.

# Answer
> 2 votes
You might also want to give the Media module a try. Make sure you download the latest 7.x-2.0-rc3 release. One of its features:

> Makes files fieldable, enabling the use of text fields to store captions on images, taxonomy fields for audio file genres, etc.

---
Tags: 7, entities
---


title: Which cache should I disable?

text:
# Question
Title: Which cache should I disable?
I have the following cache enabled:

* Memcached
* Normal Page cache enabled (from Drupal performance settings)
* Enabled optimize Javascript files (through Drupal performance settings)
* Gzip via Apache

Then I have the following enabled as well:

* Cloudflare (normal paid setting)

Should I disable some settings to improve speed and any conflicts/redundancies, or will they all work together fine?

# Answer
> 3 votes
All of those modules should play nicely together, but if you are using mod\_deflate to compress text files on the wire, then there is a Drupal setting you should disable.

On admin/config/development/performance, disable the "Compress cached pages" setting. This will prevent Drupal from compressing HTML. If this setting is on, and you are using mod\_deflate, then there can be some instances where pages get compressed twice (once by Drupal and then again by Apache). In the case, the browser will decompress the response once, and garbage is displayed to the user.

I typically override this in settings.php.

```
$conf['page_compression'] = FALSE;

```

I then implement `hook_form_alter()` to add a note under that field and disable the input element.

```
/**
 * Implements hook_form_FORM_ID_alter for form_system_performance_settings().
 */
function MYMODULE_form_system_performance_settings_alter(&$form, $form_state) {
  $form['bandwidth_optimization']['page_compression']['#default_value'] = 0;
  $form['bandwidth_optimization']['page_compression']['#disabled'] = TRUE;
  $form['bandwidth_optimization']['page_compression']['#description'] = t('Handled by Apache.');
}

```

I also tend to pair this with the following lines, to let Apache handle it.

```
$conf['css_gzip_compression'] = FALSE;
$conf['js_gzip_compression'] = FALSE;

```

After you implement all this with your Apache compression, test it out with the network analyzer in Chrome or Firefox to make sure the files are compressed on the wire.

As a side note, I typically use the mod\_deflate and mod\_header caching rules from the HTML5 Boilerplate Server Config with good success with and without a CDN. (I usually use CloudFront.)

---
Tags: caching
---


title: Twig name for field of view

text:
# Question
Title: Twig name for field of view
I have an view that uses the *Unformatted list* format and *Show: fields*.

I've added the fields to it and the view has \_Content type: my\_content\_type\_ filter.

I want to write a template file for the fields in that view, with the following code.

```
{% if field_name == 'field_photo' %}
    ...
{% elseif field_name == 'field_something_else' %}
<div class="something">
    {% for item in items %}
        {{ item.content }}
    {% endfor %}
</div><!-- .something -->

```

I don't know which name to use for the template file.

I've tried the following names, but they don't work. MY\_CUSTOM\_TYPE stays for the content type I have set in filter for that view.

* field--MY\_CUSTOM\_TYPE.html.twig
* field--node--MY\_CUSTOM\_TYPE.html.twig

What is the correct filename for the template file I am trying to use?

# Answer
> 2 votes
You could use:

**views-view-fields--\[view-name\]--\[machine-name\].html.twig**

Use the machine name if you only want to affect a specific view Display. (IE: when you click + Add button, that other view/display does not get affected). If you wan't all displays to be affected, then don't include the machine name.

**views-view-fields--\[view-name\].html.twig**

```
{% if fields.field_photo.content|striptags == 'some value' %}
    ...
{% elseif fields.field_something_else.content|striptags == 'some value' %}
<div class="something-specific">
        {{ fields.field_something_else.content }}
</div><!-- .something-specific -->
{% endif %}

```

If you just want to add a div class regardless of the value of the field and not depending on some condition, then simply

`<div class="something">{{ fields.field_machine_name.content }}</div>`

OR you can do this through the Views UI:

Now, if you need something more global, IE: You want to affect **all Views** that contain your field **and future views** that will contain your field, then you need to use:

**views-view-field--\[field-name\].html.twig**

```
<div class="something">{{ output -}}</div>

```

# Answer
> 0 votes
There is a detailed answer in this Q: Overriding views-view-field.html.twig for specific fields. I'm not quite sure what the options for a content type are, but this is the answer for a template per fieldname: you can use `views-view-field--fieldname.html.twig`.

Of course, don't forget to clear your cache after creating the new template.

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


# Question
Title: Are shared user tables still supported and working?
I have tested a Drupal 7 multi-site before, and it worked for me perfectly. With Drupal 8, it doesn't work as expected.

Suppose there are two sites, site1 with site1\_ as table prefix and site2 with site2\_ as table prefix.
The documentation says that I should add the following lines in the settings.php file.

```
  'prefix' => array(
     'default'   => 'site2_',
     'users'     => 'shared_',
   ),

```

It doesn't work because the users table in Drupal 8 doesn't have username and password information.

If I add this lines, Drupal won't work normally too.

```
  'prefix' => array(
     'default'   => 'site2_',
     'users'     => 'site1_',
     'users_data'     => 'site1_',
     'users_field_data'     => 'site1_',
     'user__user_picture'     => 'site1_',
   ),

```

For example if a user in site1 changes password, this user cannot login with the new password on site2, but the user can login with the old password once, and sign out; then the new password works!

I expected that the migration path from Drupal 6 to Drupal 8 would support migration of the shared table too, but this doesn't seem to be true. Even reading https://www.drupal.org/node/2551549 and https://www.drupal.org/node/2768219 doesn't help me much.

Are shared user tables still supported and working, on Drupal 8?

# Answer
Don't.

Per table-sharing is a relict of the past, deprecated and will be removed in Drupal 9. With all the layers on top that dynamically create tables for fields, cache invalidation and so on, this is **never** going to work.

If you want to have a shared authentication system, then look into an actual single sign on projects.
These are some links to get started; I don't have a lot of experience with either yet.
> 7 votes

# Answer
You could use **Domain Access**

> The Domain Access project is a suite of modules that provide tools for running a group of affiliated sites from **one Drupal installation and a single shared database**. The module **allows you to share users**, content, and configurations across a group of sites such as:
>
> ```
> example.com
> one.example.com
> two.example.com
> my.example.com
> thisexample.com <-- can use any domain string
> example.com:3000 <-- treats non-standard ports as unique
>
> ```
>
> By default, these sites share all tables in your Drupal installation. The Domain Prefix module (for Drupal 6) allows for selective, dynamic table prefixing for advanced users.
> 0 votes

---
Tags: 8, users, multi-sites
---


# Question
Title: How do I add an attribute in an anchor tag?
I want to make a module which will add some attributes in an anchor tag, whether the user adds in CKEditor or it is from Drupal menu system, before rendering it to the browser.

I can do it through jQuery with `$('a').attr('data-anchor', 'arial');`, but is there any way to do it through a module?

# Answer
You can do it using hook\_link\_alter

```
/**
 * Implements hook_link_alter().
 */
function mymodule_link_alter(&$variables) {

    $variables['options']['attributes'] = array('data-anchor' => 'arial');

}

```
> 4 votes

---
Tags: 8
---


# Question
Title: Correct permission for site, default and files folders?
I just need to know if these permission are corrects:

```
site --> 775
site/default -->775
site/default/files --> 775
site/default/setting.php --> 555

```

# Answer
> 15 votes
Actually the permissions should be

```
sites -> 755
sites/default -> 755
sites/default/files -> 775
sites/default/settings.php -> 444

```

See the top 3 answers to this question for some great details.

# Answer
> 5 votes
From Drupal's official handbook:

Copy this into a file and name it as "fix-permissions.sh"

```
#!/bin/bash
if [ $(id -u) != 0 ]; then
        printf "This script must be run as root.\n"
        exit 1
fi
drupal_path=${1%/}
drupal_user=${2}
httpd_group="${3:-www-data}"
# Help menu
print_help() {
cat <<-HELP
This script is used to fix permissions of a Drupal installation
you need to provide the following arguments:
1) Path to your Drupal installation.
2) Username of the user that you want to give files/directories ownership.
3) HTTPD group name (defaults to www-data for Apache).
Usage: (sudo) bash ${0##*/} --drupal_path=PATH --drupal_user=USER --httpd_group=GROUP
Example: (sudo) bash ${0##*/} --drupal_path=/usr/local/apache2/htdocs --drupal_user=john --httpd_group=www-data
HELP
exit 0
}
# Parse Command Line Arguments
while [ $# -gt 0 ]; do
        case "$1" in
                --drupal_path=*)
drupal_path="${1#*=}"
;;
--drupal_user=*)
drupal_user="${1#*=}"
;;
--httpd_group=*)
httpd_group="${1#*=}"
;;
--help) print_help;;
*)
printf "Invalid argument, run --help for valid arguments.\n";
exit 1
esac
shift
done
if [ -z "${drupal_path}" ] || [ ! -d "${drupal_path}/sites" ] || [ ! -f "${drupal_path}/core/modules/system/system.module" ] && [ ! -f "${drupal_path}/modules/system/system.module" ]; then
printf "Please provide a valid Drupal path.\n"
print_help
exit 1
fi
if [ -z "${drupal_user}" ] || [ $(id -un ${drupal_user} 2> /dev/null) != "${drupal_user}" ]; then
printf "Please provide a valid user.\n"
print_help
exit 1
fi
cd $drupal_path
printf "Changing ownership of all contents of "${drupal_path}":\n user => "${drupal_user}" \t group => "${httpd_group}"\n"
chown -R ${drupal_user}:${httpd_group} .
printf "Changing permissions of all directories inside "${drupal_path}" to "rwxr-x---"...\n"
find . -type d -exec chmod u=rwx,g=rx,o= '{}' \;
printf "Changing permissions of all files inside "${drupal_path}" to "rw-r-----"...\n"
find . -type f -exec chmod u=rw,g=r,o= '{}' \;
printf "Changing permissions of "files" directories in "${drupal_path}/sites" to "rwxrwx---"...\n"
cd sites
find . -type d -name files -exec chmod ug=rwx,o= '{}' \;
printf "Changing permissions of all files inside all "files" directories in "${drupal_path}/sites" to "rw-rw----"...\n"
printf "Changing permissions of all directories inside all "files" directories in "${drupal_path}/sites" to "rwxrwx---"...\n"
for x in ./*/files; do
find ${x} -type d -exec chmod ug=rwx,o= '{}' \;
find ${x} -type f -exec chmod ug=rw,o= '{}' \;
done
echo "Done settings proper permissions on files and directories"

```

Now run this script as: sudo bash fix-permissions.sh --drupal\_path=your/drupal/path --drupal\_user=your\_user\_name

Viola! Your permissions are automatically fixed.

# Answer
> 3 votes
This is how I decided to set permissions for my Drupal instance:

```
mkdir sites/default/files
chgrp -Rv apache sites/default/files
chmod 2775 sites/default/files

```

We do this by using 2775 in our chmod command. The 2 means that the group id will be preserved for any new files created in this directory. What that means is that apache will always be the group on any files, thereby ensuring that web server and the user will both always have write permissions to any new files that are placed in this directory. The first 7 means that the owner (example) can R (Read) W (Write) and X (Execute) any files in here. The second 7 means that group (www-data) can also R W and X any files in this directory. Finally, the 5 means that other users can R and X files, but not write.

Another point is to set correct permissions for your settings.php

```
chmod 444 sites/default/settings.php

```

Other permissions are to be default.

Complete Drupal Installation guide: http://itvictories.com/node/21

# Answer
> 2 votes
Selected answer is not quite correct, especially when there are few unknowns there, however **Aleks** explained it quite extensively, and it's very similar approach that I take on Drupal sites.

Also, I thought I would share my script here as well, but as a Drupal Module, that I've created some time ago. You can place it in `~/.drush` subdirectory and simply execute `drush file-permissions` while being in any working Drupal site subdirectory.

It bootstraps your Drupal site, checks for `file_private_path`, `file_public_path` and sets them to correct Apache user and group. Apache user / group is being determined automatically, so it's not relying on the user specifying them manually or having them hard-coded in a script file.

Module page: https://www.drupal.org/project/file\_permissions

# Answer
> 0 votes
As the other guys mentioned the correct permission is

> All Drectories -\> 755
> All files -\> 755
> sites/default -\> 755(this override up rule this directory)
> sites/default/files -\> 775 (this override up rule for this directory and it's contents)
> sites/default/settings.php -\> 444(this override up rule for this file)

The appropriate commands to achieve mentioned Rules comes in the following,at the root of your Drupal website

```
find . -type f | xargs chmod 644
find . -type d | xargs chmod 755
chmod 444 sites/default/settings.php
chmod 775 -R sites/default/files

```

to make it writeable by webserver you can use the following command

```
chcon -R -t httpd_sys_rw_content_t sites/default/files

```

---
Tags: users
---


# Question
Title: How do I see if it's improving my response time?
I installed memcached for a Drupal 6 site. The status report shows it's properly installed.

How do I check if it's working as expected, and speeding up my site?

# Answer
You can check the status at /admin/reports/memcache.
> 1 votes

# Answer
Use webpagetest or one of its brethren to see how long it takes for the backed to deliver the HTML. You'll have to compare with and without memcache, warm vs cold cache. There are better analyses you can do, like new relic and blackfire, either requires a web server agent running.
> 0 votes

---
Tags: 6, caching
---


title: How do I add Emoji smileys?

text:
# Question
Title: How do I add Emoji smileys?
I want to add Emoji smiles in Drupal 7 comments without using a sandbox project like https://www.drupal.org/sandbox/mparker17/2078481.

Does anyone have any idea how to add Emoji smiles in comments?

# Answer
According to **Drupal 7.50 released**, Emojis were added as a new feature in 7.50

> Support for full UTF-8 (emojis, Asian symbols, mathematical symbols) is now possible on MySQL
>
> If content creators on your site have been clamoring to use emojis, it's now possible on Drupal sites running MySQL (it was previously possible on PostgreSQL and SQLite). Turning this capability on requires the database to meet certain requirements, plus editing the site's settings.php file and potentially other steps, as described in the change record.
> 9 votes

# Answer
You might want to have a look at Smiley

> Smiley is a text filter that substitutes text emoticons, like :-) with images.
>
> It comes with a set of example smileys, but you can import ready-to-use packages (e.g.: from phpBB's "pak"s and Adium Emoticon packs) or define your own.
>
> To use your own smileys, simply upload them into FILES\_DIRECTORY/smiley (usually sites/default/files/smiley) and import them using the "Smiley Import" module.

Since it is a text filter, you should be enable to for `filtered-html` and have it apply to comments.
> 5 votes

# Answer
Emoji's are also commonly referred to as Smileys. Take a look at the Smiley module for Drupal 7.
> 4 votes

---
Tags: 7, comments
---


# Question
Title: CKeditor is not working with jquery > 1.8
I'm trying to get superfish accordion working on my pages. I have to have my jquery\_update set to 1.9 or greater to get that function working.

But when I do I lose ckeditor on the comment fields for things like forums and such. I'm not sure what to do to resolve this problem.

Currently running Drupal 7.53

CKEditor for Drupal module 7.x-1.17

Superfish menu module 7.x-2.0

# Answer
> 2 votes
Okay, this may have been the cause.

I use AdaptiveTheme for my base theme on everything really. Right now the default theme makes use of a FooTheme created with a Corolla base. I had menu setting in the theme turned on and I think it was interfering with the Superfish menu.

If you are using Superfish then turn off all mobile menu options in AdaptiveTheme.

---
Tags: 7, wysiwyg, navigation, javascript
---


# Question
Title: How to implement content access for groups of users?
I am building a Drupal 7 site, and I am quite new to Drupal. I want to assign each authenticated to a group which I define myself, for instance "friends", "family", "coworkers", "mortal enemies" and so on. I want the content access permissions to depend on this group, so that my friends and family are allowed to see all my images with cute kittens, whereas my mortal enemies should only have access to my archive of taunts and elaborate verbal abuse.

Any suggestions?

# Answer
> 3 votes
The Organic Group module will come to your rescue. Read the documentation about how to use the module.
More about the module:

> Enable users to create and manage their own 'groups'. Each group can have subscribers, and maintains a group home page where subscribers communicate amongst themselves.
>
> They do so by posting the usual node types: blog, story, page, etc. A block is shown on the group home page which facilitates these posts. The block also provides summary information about the group.
>
> Groups may be selective or not. Selective groups require approval in order to become a member, or even invitation -only groups. There are lots of preferences to configure groups as you need.

# Answer
> 0 votes
Maybe you want to give it a try to use the Group module, which is an alternative for Organic Groups.

Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. It is designed to be an alternative to Organic Groups. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

For this specific question, you'd enable the `gnode` submodule, and for each group type you would define the appropriate permissions (view, edit, delete, etc) for the various Content Types. That's it.

For more details about how Group compares to Organic Groups, refer to my answer to "What are the features of the Group module versus Organic Group module?".

# Resources

---
Tags: 7, users
---


# Question
Title: Migrate-d2d UI - Where does sites/default/files source content go?
I am setting up a dedicated development environment on my home LAN where I can work on a Drupal 6 to Drupal 7 migration. So far, I have a clean Centos 7, LAMP stack, and Drupal 7 install and have configured periodic file and image backups to my local NAS. The D6 drupal database has been imported and connected in settings.php and appears to be recognized by the migrate\_D2D UI.

What I am unclear about is how to migrate the D6 site's downloadable file content and images under sites/default/files. Although the D6 site is live and remote, I was thinking about copying relevant portions of the sites/default/files path over to the development system, but I don't know where to put it or how to reference it as a data source in the migration process.

I would assume that the format or field mapping conventions for content in sites/default/files is different between Drupal 6 and 7 and source and destination content must remain separate, but I am not sure about this. So can anyone advise me as to the best approach for incorporating this D6 content into D7? I would be happy to either copy the content over or read it remotely from the live site if this is supported. Thanks.

19 hours later:

I haven't resolved this yet so let me ask my question again with a couple of visual aids. Here is the file tree of the sites/default/files section from my legacy Drupal 6 website:

Here is the file tree of the sites/default/files section from the clean install of the Drupal 7 website I am trying to migrate into:

My question is where migrate\_d2d wants me to put the legacy (source) Drupal 6 files. Do I put it inside the new sites/default/files tree or somewhere separate from where the post-migration Drupal 7 files will be?

Thanks again.

# Answer
> 0 votes
I'll post this as a preliminary answer, but please feel free to comment with better suggestions.

Step 4 (Files) of the migrate\_d2d UI asks for path where the source files can be found. I took the conservative approach and uploaded the legacy sites/default/files file system to a separate source directory on the development server, but I don't see why you couldn't directly import the legacy file content into the sites/default/files directory on the destination server.

At least this seems to work so far.

---
Tags: migrations
---


title: How to Add Image Field in CIVICRM

text:
# Question
Title: How to Add Image Field in CIVICRM
I am trying to add an Image as Custom field in Civicrm Contact, but the Image Field type is not in the Custom Field section. It has only Field type as File.

How to apply Drupal Image styles for Images uploaded on Civicrm Contact.

I have integrated Civicrm in Drupal 7.

# Answer
Well if you want a Drupaly solution you could try installing the CiviCRM Entity module along with the Views in Contact Pages module

With CiviCRM Entity you can add Drupal fields to CiviCRM entities, so you could add you a normal Drupal image field and get all the wonderful goodies Drupal provides such as image styles.

Now this field data would live in Drupal field table not in CiviCRM custom field tables.

You add your field on the CiviCRM Entity Contact entity Manage Fields page at admin/structure/civicrm-entity/civicrm\_contact

If you can live with the data being in the Drupal DB, not the CiviCRM db, then this can work for you.

Then if you want to display the image on the CiviCRM backend admin contact summary page, you use the Views in Contact Pages module to create a view that displays the image, along with any other data you want, and put that view either as a tab on the contact page, or a pane on the Summary tab.
> 0 votes

---
Tags: media, civicrm, webforms
---


# Question
Title: Access CiviCRM event fees via Drupal Views
I'm trying to access the Regular Fees data inside of Drupal Views 3. I can see the Fee Label but can't see how I pull in Regular Fees? I've looked at Price sets and setting up a relationship but this seems overly complex for whats required. Wondering if anyone has attempted this/had any joy? Using Drupal 7.42 and CiviCRM 4.7.1

# Answer
Try using Views Field View following: https://www.ostraining.com/blog/drupal/views-field-view/

You'll need to create the context on Price Set ID in **Price Fields**, not Price Set.

I don't think this is an efficient way to do this.
> 0 votes

# Answer
Try installing the CiviCRM Entity module, and its sub module CiviCRM Entity Views Extras...

CiviCRM Events, Contributions, Participants, ParticipantPayment, LineItems, PriceSet, PriceField, PriceFieldValues, FinancialTrxn, and other necessary entities are exposed, and some of the relationship handlers are provided by the CiviCRM Entity Views Extras modules, but a few more may need to be added depending on your use case.

But it can be done, lots of the heavy lifting has been done already.
> 0 votes

---
Tags: views, civicrm
---


# Question
Title: How to Associate Drupal content type with CiviCRM groups?
I have created the 10 contents in Drupal. This contents are Article content type and also created the new group(group name: students) in civicrm.

Now I want to associate these content with the student group in civicrm.

could you please anyone tell me how to achieve this one ?

# Answer
> 0 votes
With the CiviCRM Entity module, many CiviCRM API entities are exposed as proper Drupal entities. You can then create Entity Reference fields to reference particular entities. So on your node types, create an entityreference field, target CiviCRM Groups, and you will be able to reference the groups this way

---
Tags: 7, nodes, civicrm
---


# Question
Title: Change directory where MySQL saves its data
Is there a way to get Acquia Dev Desktop to save the MySQL data to a different location other than the one it chooses by default?

Imagine to reinstall Acquia and thus needing to save the MySQL data from a Drupal instance into an alternate drive.

Acquia Dev Desktop places the database in C:\Program Files (x86)\DevDesktop\mysql\data.

Looking into the preferences, the config files contain the following.

```
[client]
port=33067
user=drupaluser

[mysql]
max_allowed_packet = 128M

[mysqldump]
max_allowed_packet = 128M

[mysqladmin]
user=root
port=33067

[mysqld]
pid-file="C:/Program Files (x86)/DevDesktop/mysql/data/mysql.pid"
log-error="C:/Program Files (x86)/DevDesktop/mysql/data/mysql.err"

# The TCP/IP Port the MySQL Server will listen on
port=33067

#Path to installation directory. All paths are usually resolved relative to this.
basedir="C:/Program Files (x86)/DevDesktop/mysql"

#Path to the database root
datadir="C:/Program Files (x86)/DevDesktop/mysql/data"

#set innodb as default
default-storage-engine=InnoDB

innodb_log_buffer_size=32M
innodb_buffer_pool_size=512M
innodb_log_file_size=32M

innodb_file_per_table=1

#Max open files
open_files_limit=10000

#Max packets
max_allowed_packet = 128M

#The log buffer is written out to the file at each commit. Flushing on the log file takes place once per second
innodb_flush_log_at_trx_commit=2

#Enable slow query log
long_query_time=1
slow_query_log=1
slow_query_log_file=slow.log

```

If the data directory is changed, then I get the following error.

# Answer
Stopping the Acquia Dev server and moving/copying the files form the original data directory to the new data directory appeared to address the issue - thanks to cilefen for help

The following lines were updated to reflect the new location of the data directory

```
[mysqld]
pid-file="<<new path>>/data/mysql.pid"
log-error="<<new path>>/data/mysql.err"

```

and

```
#Path to the database root
datadir="C:/Program Files (x86)/DevDesktop/mysql/data"

```
> 1 votes

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


# Question
Title: Drupal Commons make group content visible for anonomous users?
I have a Drupal (7.52) Commons (commons-7.x-3.40) website which currently requires users to log-in to see published content.

Now I need to publish content so it is visible to non-authenticated users... I'm not sure the best way to accomplish this. I'm not very experienced with Drupal, the most logical thing to me would be to simply create a new Group which allows anyone (anyone|Any site member can contribute) to view content but this option seems to still require authentication.

Other options seem to be add:

Not sure where to start looking - please help!

Thanks

# Answer
Simple solution - in Permissions (People), check 'Anonymous User' for the 'Node' setting 'View Published Content'.
> 0 votes

---
Tags: organic-groups
---


title: calling a block views by ajax

text:
# Question
Title: calling a block views by ajax
I have a views with three displays which sorts comments of a node in newest, oldest and most popular order. These views are shown below the content and works with contextual filters. I have used *ajax\_comment* and *rate* and *vote api* module in order to add/reply comments by ajax and let users vote other people's comments too. Now I want to load one of these views at a time so I have created an HTML like this:

```
<select name="sort" onChange="return sort1()">
    <option value="newest">newest comments</option>
    <option value="oldest">oldest commenst</option>
    <option value="popular">most popular comments</option>
</select>
<div id="cm"></div>

```

and a jquery code like this:

```
<script>
function sort1(){
$.ajax({
    url: Drupal.settings.basePath + '/views/ajax',
    type: 'post',
    data: {
        view_name: 'comments_views',
        view_display_id: 'block_2', //your display id
    },
    dataType: 'json',
    success: function(html){
        $('#cm').html(html);
    }
});
    return false;
}
</script>

```

But it does not work.

I have tested *quicktabs* module too but comment reply link does not work with ajax\_comment then. I have seen *JQuery AJAX Load* module too but it needs a url to load.

If my code is incorrect please correct it or if you have a better solution please let me know it.

# Answer
I post my answer for anyone who is facing this problem. After all it worked by some changes:

```
<div onclick="return sort1()">newest comments</div>

<div onclick="return sort2()">oldest commenst</div>

<div onclick="return sort3()">most popular comments</div>
<div id="cm">
     <div id='news'><?php print views_embed_view('comments_views', 'block_3'); ?>

```

and jQuery code is:

```
function sort1(){
var nid='<?php echo $node->nid; ?>';
$.ajax({
    url: 'http://www.yoursitename.com/views/ajax',
    type: 'post',
    data: {
        view_name: 'comments_views', //view name
        view_display_id: 'block_3', //view display
        view_args: nid,   //view contexuall filter
    },
    dataType: 'json',
    success: function(response){
        //alert(response[1].data);
        $('#cm').html(response[1].data);
    }
});
    return false;
}

```

for each of the sort functions above it must be exist.
> 0 votes

---
Tags: 7, views, javascript, ajax, comments
---


# Question
Title: How can I bulk add existing commerce products to a display node?
pretty simple, i want the ability to add more than one existing product at a time to a node. i am already using bulk product creation to help me create all the variations of the product quickly. but then after that, i have to add them 1 by 1 to the display node. i would love the ability to just add a product range by product ID or something.

# Answer
> 1 votes
entity reference view widget module solved my problem. it basically allows you to replace the add existing product button with a view. just customize the view to select any range of existing products you want and add them to the display node. saved my a boatload of time.

# Answer
> 1 votes
You say you're using "bulk product creation", does that mean you're the using the Feeds module? You can use it along with Commerce Feeds in two steps. First create all products, and then create all product displays linked to those products. You can, for example, use the `title` field as an identifier to link the two.

There's a handy tutorial on Vimeo by Randy Fey called Importing Products with Commerce Feeds.

---
Tags: commerce
---


# Question
Title: How do I export a content type, views as a single module
I've a view, content type, field collection, flexslider to satisfy a single user case. May I know how to export all these three as a single module.

# Answer
You could use some Drupal Console export commands for this:

You could use the `--module` option to specificy which module to export.

It's easier to use the Features module though. From the project page:

> A feature is a collection of Drupal entities which taken together satisfy a certain use-case.
>
> Features provides a UI and API for taking different site building components from modules with exportables and bundling them together in a single feature module. A feature module is like any other Drupal module except that it contains additional information in its info file so that configuration can be checked, updated, or reverted programmatically.
>
> Examples of features might be:
>
> * A blog
> * A pressroom
> * An image gallery
> 3 votes

# Answer
Install and configure Features module.

> Features provides a UI and API for taking different site building components from modules with exportables and bundling them together in a single feature module.

To export using terminal use ***Drush***.

Drush commands for features : https://drushcommands.com/drush-7x/features/features-add/
> 2 votes

---
Tags: console
---


# Question
Title: How can I add a constraint to a custom field I created?
I have created a complex field type (my class extends `DateRangeItem`) that supports recurring dates by adding a property for storing an RRULE string:

```
class DateTimeRecurItem extends DateRangeItem {

  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties = parent::propertyDefinitions($field_definition);
    // Prevent early t() calls by using the TranslatableMarkup.
    $properties['rrule_string'] = DataDefinition::create('string')
      ->setLabel(new TranslatableMarkup('RRule String'))
      ->setRequired(FALSE);

    return $properties;
  }

  ...

```

I want to validate the RRule string (there's a RFC to validate it against). I can do this by creating a custom constraint and applying it like this:

```
$properties['rrule_string'] = DataDefinition::create('string')
  ->setLabel(new TranslatableMarkup('RRule String'))
  ->setConstraint('MyCustomConstraint')
  ->setRequired(FALSE);

```

The problem is I also need to know the value for the `value` property of the field (which is inherited by `DateRangeItem`). Implemented as above, my constraint validator will only be passed the raw string value of the `rrule_string` property.

**I can't figure out how I can define a constraint that applies to the entire field** (thereby having access to all of its field properties). There seems to be no interface for doing that.

To be clear, this is not a field I've added to a custom entity definition. This is just a custom field I defined that can be added to any entity.

# Answer
> 3 votes
In case of a field type, you can simply put it in the annotation.

Have a look at FileItem for example:

```
/**
 * Plugin implementation of the 'file' field type.
 *
 * @FieldType(
 *   id = "file",
 *   label = @Translation("File"),
 *   description = @Translation("This field stores the ID of a file as an integer value."),
 *   category = @Translation("Reference"),
 *   default_widget = "file_generic",
 *   default_formatter = "file_default",
 *   list_class = "\Drupal\file\Plugin\Field\FieldType\FileFieldItemList",
 *   constraints = {"ReferenceAccess" = {}, "FileValidation" = {}}
 * )
 */
class FileItem extends EntityReferenceItem {

```

Actually a bit surprised that the date classes don't have any constraints, that sounds like a bug.

# Answer
> 0 votes
Override the `getConstraints` method.

```
public function getConstraints() {
  $constraint_manager = \Drupal::typedDataManager()->getValidationConstraintManager();
  $constraints = parent::getConstraints();
  $constraints[] = $constraint_manager->create('CustomConstraint', array());
  return $constraints;
}

```

---
Tags: 8
---


title: Updating cached REST resources

text:
# Question
Title: Updating cached REST resources
I'm building my first custom REST resources. I have a custom entity and returning specific fields from it. However, it's *very* important that if a specific field changes (a status field) that it is reflected in the response.

What I'm seeing is that I have to clear the cache every time I update the entity. How do I make sure the response is up-to-date?

I have tried using both `\Drupal::entityQuery` and `\Drupal::entityTypeManager()->getStorage()...` but both require a cache clear. Maybe I'm loading the entity incorrectly?

# Answer
> 2 votes
It's not about how you load the entity. It's how you build the response. You have to add the correct cache tags. A cacheable response has the method `addCacheableDependency()`, which accepts objects which provide cache metadata:

```
$response->addCacheableDependency($entity);

```

This adds the tag `custom_entity:[id]` to the cached response. All cached responses with this tag will be invalidated, when the entity is updated.

This is an example from core for the cache data and access checks you need in a response which contains entity data:

*Drupal\rest\Plugin\rest\resource::get()*

```
public function get(EntityInterface $entity) {
    $entity_access = $entity->access('view', NULL, TRUE);
    if (!$entity_access->isAllowed()) {
      throw new AccessDeniedHttpException();
    }

    $response = new ResourceResponse($entity, 200);
    $response->addCacheableDependency($entity);
    $response->addCacheableDependency($entity_access);

    if ($entity instanceof FieldableEntityInterface) {
      foreach ($entity as $field_name => $field) {
        /** @var \Drupal\Core\Field\FieldItemListInterface $field */
        $field_access = $field->access('view', NULL, TRUE);
        $response->addCacheableDependency($field_access);

        if (!$field_access->isAllowed()) {
          $entity->set($field_name, NULL);
        }
      }
    }

    return $response;
  }

```

---
Tags: caching, 8
---


# Question
Title: Restrict content to a user role in a template file
I want to restrict a single node to anonymous users in Drupal 8. I don't want to use any module for it as its useless for single restriction as per me.

I know that I can do it with something like this.

```
{% if user.hasPermission('myPermission') %}
     //my template HTML
{% else %}
    //some login for the customer
{% endif %}

```

I don't want to restrict the content via permission, instead I want to restrict it with something like

```
{% if user.hasRole('authenticated') %}

```

Is this possible with a theme hook or do I have to use a module?

# Answer
To check in twig if the user is authenticated you can use the default variable `logged_in`:

```
{% if logged_in %}
  <p>The user is authenticated".</p>
{% endif %}

```

This works because the user module provides the variable in preprocess for all templates:

```
/**
 * Implements hook_template_preprocess_default_variables_alter().
 *
 * @see user_user_login()
 * @see user_user_logout()
 */
function user_template_preprocess_default_variables_alter(&$variables) {
  $user = \Drupal::currentUser();

  $variables['user'] = clone $user;
  // Remove password and session IDs, since themes should not need nor see them.
  unset($variables['user']->pass, $variables['user']->sid, $variables['user']->ssid);

  $variables['is_admin'] = $user->hasPermission('access administration pages');
  $variables['logged_in'] = $user->isAuthenticated();
}

```

**Generic roles**

If you want to check a generic role, you can't use `hasRole()`, because this method is not available for accounts. You would have to use `getRoles()` and check if the role is in the returned array:

```
{% if 'example_role' in user.getroles  %}
  <p>The user has the role "example_role".</p>
{% endif %}

```

---

**Drupal 10.1.x**

You can use `hasRole()` now. See the change record https://www.drupal.org/node/3002289.
> 20 votes

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


# Question
Title: Views: filter by the highest (max) field value of all items
In this case, ‘Volume’ is a text field of type integer. Using the Views module, I want to display only those articles which have the highest value in the volume field.

I am able to do it using contextual filter but I have to provide a default value like 6. Please see the attached screenshot.

Is there any way in views, to detect the highest value of the field and use that as a filter?

# Answer
I fear you will need a subquery for that. You can do that in a custom module.

```
/**
 * Implements hook_views_query_alter().
 */
function MODULE_NAME_views_query_alter(&$view, &$query) {
  $max = db_query('select max(YOUR_TABLE_COLUMN) from YOUR_TABLE')->fetchField();
  $query->add_where(0, db_and()->condition('TABLE.YOUR_FIELD_NAME', $max));
}

```

The tricky part here is to create your select query and find the correct field name/alias. Have a look at the query output of your view to find the correct parts.

**Original answer (before clarification)**

Instead of a contextual filter you can use a sort on the 'Volume' field. Sort descending. That way the articles with the highest 'volume' are at the top.

If you want to show only articles with a number higher than X you could add a regular filter for that.
> 0 votes

# Answer
Well, I made it in a tricky way. I created a first view, with just two fields in it: Volume and Issue. Once hidden both, I rewrited them in a custom text field, in a way like this: \<`<p>Magazine nr. [field_issue] / [field_volume]</p>` Ordered by Volume DESC and Issue DESC. Showing just 1 item. So I have always displayed the last issue. Then I created another view, to display my articles as I wanted, and I added 2 contextual filters: Volume and Issue. Finally I embedded the second view in the first as a field, passing from first to second the values of the two fields. So I get the view as attached. Of course if you don't want to display the "Magazine nr. etc." you can hide it by css.
> 1 votes

---
Tags: entities, views
---


# Question
Title: Multiple upload image using managed_file
I'm trying to do a very simple thing (seems not that simple at all) in my custom form, to add multiple files using the managed\_file form api. Like in the admin, select a file, upload, then a new input file appears.

But I can't achieve that... do I need a callback ???

```
    'gallery' => array(
        '#type' => 'managed_file',
        '#name' => 'gallery[]',
        '#title' => t('Gallery'),
        '#upload_location' => 'public://',
        '#attributes' => array(
            'multiple' => 'multiple',
        ),
    ),

```

Thanks

# Answer
In Drupal 8, add '#multiple' =\> TRUE

Example:

```
$form['images'] = array(
  '#type' => 'managed_file',
  '#upload_location' => 'private://images/',
  '#multiple' => TRUE,
  '#upload_validators' => array(
    'file_validate_extensions' => array('png gif jpg jpeg'),
    'file_validate_size' => array(25600000),
    'file_validate_image_resolution' => array('800x600', '400x300'),
  ),
);

```

More about form api: Introduction to Form API
> 7 votes

# Answer
Complete details of upload multiple images using from API

```
/**
 * our example system settings form
 */
function mf_settings_form($form,&$form_state) {
  $form = array();

  $form['managed_file_example'] = array(
    '#type' => 'managed_file',
    '#title' => t('Managed File Example'),
    '#default_value' => variable_get('managed_file_example',''),
    '#upload_location' => 'public://managed_file_example/',
  );

  $form = system_settings_form($form);
  $form['#submit'][] = 'mf_settings_submit';

  return $form;
}

```
> -1 votes

---
Tags: forms, files, media
---


title: How do I inject services in a service?

text:
# Question
Title: How do I inject services in a service?
How do I inject services in a service?

I am using the following code, but it throws an error.

```
class RoleNegotiator implements ThemeNegotiatorInterface {

  public static function create(ContainerInterface $interface) {
    return new static(
      $interface->get('router.admin_context')
    );
  }
  public function __construct(RouteMatchInterface $route) {
    $this->route = $route;
  }
}

```

# Answer
You define the necessary services as arguments of the service you implement.

Since you are showing a class that implements `ThemeNegotiatorInterface`, see the theme.negotiator.default service and the class implementing it, `Drupal\Core\Theme\DefaultNegotiator`.

### Service definition

```
  theme.negotiator.default:
    class: Drupal\Core\Theme\DefaultNegotiator
    arguments: ['@config.factory']
    tags:
      - { name: theme_negotiator, priority: -100 }

```

### Class constructor

```
public function __construct(ConfigFactoryInterface $config_factory) {
  $this->configFactory = $config_factory;
}

```

There isn't any static `create()` method as in your code.
> 12 votes

# Answer
You need to implement `ContainerInjectionInterface` as well to inject the dependency in your class (if its not a service). But if you are creating a new service you can inject it in `module.services.yml` itself as said by @kiamlaluno in his answer.

```
class RoleNegotiator implements ThemeNegotiatorInterface, ContainerInjectionInterface {

}

```
> 3 votes

---
Tags: 8
---


# Question
Title: "\Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container."
I am attempting to write a PHPUnit test for a service of mine.

My test looks like the following.

```
class CustomServiceTest extends UnitTestCase {

  public function testDefaultBehavior() {
    $service = new CustomService(\Drupal::service('custom_utils.some_resolver'), \Drupal::configFactory());
    $service->execute();
  }
}

```

However, it raises the following exception.

```
Drupal\Core\DependencyInjection\ContainerNotInitializedException:
\Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container.

```

What am I doing wrong?

# Answer
You need to mock the services you will be using in your test, so that they return values. You can do that as follows:

```
public function testDefaultBehavior() {
  $some_resolver = $this->getMockBuilder('Drupal\namespace\for\custom_utils\someresolver')
    ->disableOriginalConstructor()
    ->getMock();
  $config_factory = $this->getMockBuilder('Drupal\Core\Config\ConfigFactory')
    ->disableOriginalConstructor()
    ->getMock();
    $service = new CustomService($some_resolver, $config_factory);

```

}

Note that you should use the actual interface (or class if you have no interface) instead of `Drupal\namespace\for\custom_utils\someresolver`

You'll need to set up expectations to return the values from the services you mocked. You can read more on that here:

https://www.drupal.org/docs/8/phpunit/understanding-phpunit-expectations
> 13 votes

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


# Question
Title: How can I repeat a group of fields in a content type?
I'd like to create a content type named `image gallery` then add two fields as `caption` as text and `image` as image. Then make these two bundled and repeatable indefinitely when entering content for this content type.

* Is it something possible to achieve without using third party modules or creating multiple content types?
* If so, how?
* If not, what would you suggest to use to do this?

I've tried to use Paragraph module and working fine but it seems it doesn't provide the image dimensions unless you loop the whole bit and get the dimensions for each item.

PS: Sorry about the tag by the way but it seems tags for `content type` and `structure` doesn't exist.

# Answer
> 4 votes
You should look into the new media entity suite of modules for Drupal 8. You can create media bundles and add fields to them (like title, caption, link, copyright). You can then create a simple Paragraph that holds a media reference field, and set it to unlimited - the theming is up to you to get the display to grid out like a gallery. I'm not sure why you need the image dimensions though. But with media entity, media renders out like normal entities meaning they gain access to display modes and various twig template possibilities.

Here is a walkthrough that covers in depth the technique I'm describing and how to set up a media based workflow:

https://www.annertech.com/blog/reusable-media-drupal-8-tutorial

Using Paragraphs is basically the only way to get 'bundled fields' without resorting to using Entity Construction Kit and entity reference fields - but by the time you engineer all that, you'll have spent three times as long and your field data won't live on the media object itself ( which is another drawback to Field Collection), and for that you will definitely want the Media Entity approach. Please don't make them multiple content types either. Media is media.

# Answer
> 2 votes
> Is it something possible to achieve without using modules or creating multiple content types?

To my knowledge, it is not possible using the modules / features that Drupal 8.2.x Core provides.

Another way, besides using Paragraphs, that I know of is to use the Field Collection module.

You basically create a collection where you add your two fields (both allow only 1 value).

Then add a new field of Type: Field Collection to your content type and change the allowed values from 1 to unlimited.

If you are then using Views to display them, you need to add a relationship of Field Collection.

---
Tags: theming, 8
---


# Question
Title: Create a custom Link to a File-Field in Twig
I'm trying to customize a download-link for a file-field in my entity. In a similar setup, i was able to customize a link-field in the following way:

```
<a href="{{ node.field_publication_link.uri }}"> Link </a>

```

So, for the file-field, i tried something similar:

```
<a href="{{ node.field_publication_file.0.uri }}"> Download </a>

```

However, there is no such thing as a `uri` field available. I have a hard time figuring out which fields actually are available for me to use in the template. I found `kint` to be way too noisy, i had to restrict memory consumption and still have no clue which fields are usable.

Alternatively, i tried to create a custom template for the specific file field, called `field--field-publication-file.html.twig`. The debug info tells me that it is used for rendering. I had a look at the field that my theme (bootstrap) normally uses and tried to mimick its behavior. Specifically, i wanted to use the field `link`, which is also used in the bootstrap version. However, this field is always empty when using my version.

What more could i try?

# Answer
After more research, i found the answer by accident on this page. One can refer to the link by using:

```
<a href="{{ file_url (node.field_publication_file.entity.uri.value) }}">
  Download
</a>

```

The fields that were defined in the bootstrap theme don't seem to be accessible in a sub-theme of bootstrap. I'm sure I could have written a custom preprocessor to do the same thing, but this solution works for me and I don't have to write PHP code.
> 2 votes

# Answer
You can do it either way, using the file\_url available on twig template or you can use `file_create_url($file_uri);` in the preprocessor, so that your template can easily consume the processed output.

Code at preprocess layer, assuming node as the host entity.

```
function mymodule_preprocess_node($node) {
   if (!$node->your_file_field_machine_name->isEmpty()) {
     $file_entities = $node->get('your_file_field_machine_name')->referencedEntities();
     if(count($file_entities)) {
        foreach($file_entities as $file_entity) {
            $variables['file_renderable'][] = file_create_url($file_entity->getFileUri());
        }
     }
   }
}

```

Other way is what you mentioned, use `file_url` at your twig template.

```
<a href="{{ file_url (node.field_publication_file.entity.uri.value) }}">
  Download
</a>

```
> 1 votes

---
Tags: theming, 8, files
---


# Question
Title: How to change page title of Manage Fields screen based on bundle name?
Is it possible to change admin screen page title based on bundle related to the screen. For example, I would like title of `admin/structure/types/manage/datasheet/fields` page to be `Manage datasheet fields`. Is it possible?

# Answer
You need to replace the static title with a dynamic title.

Reference: https://www.drupal.org/node/2067859

This describes how to define dynamic titles for new routes in yaml files. You need to change the existing route `entity.node.field_ui_fields` in a route subscriber:

```
$route->setDefault('_title_callback', '\Drupal\mymodule\Controller\MyController::getTitle');

```

Reference: https://www.drupal.org/docs/8/api/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones
> 1 votes

---
Tags: 8
---


# Question
Title: Is it possible to add a default URL parameter inside a theme template_XYZ function?
I have a view with a pulldown menu within an exposed form. I want to set that URL parameter to a default value based on the currentLanguage() of the session. Is there a way to edit the URL parameters that a View can see within a custom module or the theme's `template_` functions?

# Answer
Within a custom module, it is possible to use the hook\_views\_pre\_view hook. You can alter the `$args` array passed as parameter, in order to add or remove arguments.
> 1 votes

# Answer
I ended up doing this to get it working:

```
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if($form['#id'] == 'views-exposed-form-BLAH-page-1e' &&
        $form_id ="views_exposed_form") {
    $request = \Drupal::request();
     // check that no URL param is already set
      if (!$request->get('MYEXPOSEDFIELDID', NULL)) {
        // reference to user input object (for editing)
        $input = &$form_state->getUserInput();
        $input['MYEXPOSEDFIELDID'] = NEWVALUE;
      }
    }

```
> 0 votes

---
Tags: views, 8
---


title: Slide image bottom on mouse hover

text:
# Question
Title: Slide image bottom on mouse hover
I have some kind of image that I want to have in all my pages of my website to use to return to my homepage.

So far, I managed to get the image in position I want and I already have displayed in all my webpages with reference link to the homepage.

But I want to go a bit far and had an animation to it, so when somebody use the mouse to hover the image I wanted the image to move some px (50px for example) to the bottom.

Yet, all I could do so far was this:

```
.penduricalho{
  background-repeat: no-repeat;
  position: relative;
  top: -200px;
  right: -200px;
  margin-bottom: -500px;
  -webkit-transition: bottom 0.3s;
  -moz-transition: bottom 0.3s;
  -o-transition: bottom 0.3s;
}

```

But with the piece of code above the image was in fact moving but it originated other problem that it would move all the content beneath it.

I tried this other code:

CSS:

```
.penduricalho{
  background-repeat: no-repeat;
  position: relative;
  top: -200px;
  right: -200px;
  margin-bottom: -500px;
}

figcaption {
  position: absolute;
  background: rgba(0,0,0,0.75);
  color: white;
  padding: 10px 20px;

  opacity: 0;
  bottom: 0;
  bottom: : -30%;
  -webkit-transition: all 0.6s ease;
  -moz-transition:    all 0.6s ease;
  -o-transition:      all 0.6s ease;
}

figure:hover figcaption {
  opacity: 1;
  left: 0;
}

```

HTML:

```
<div class="penduricalho">
    <figure>
        <a href="http://10.0.1.43/"><img src="http://alojamento.fct.unl.pt/sites/all/themes/javali_theme/images/penduricalho.png"></img></a></p>
        <figcaption>
            aye!!
    </figure>
</div>

```

Still with this code the image wasn't moving, only appteared a text sliding. And that is similarly to want I want, that is, slide my image a bit to the bottom. But when I try to alter this latter code the page unconfigured itself.

# Answer
> 0 votes
Ok, now with this code I have my image doing the animation/transition that I wanted, moving down smoothly:

CSS:

```
.penduricalho{
  background-repeat: no-repeat;
  position: relative;
  top: 0px;
  left: 200px;
  margin-bottom: -500px;
  display: block;
  position: absolute;
  z-index: 2;
  height: auto;
  margin-right: auto;
  margin-left: auto;
  overflow: hidden;
}

.penduricalho:hover{
  -moz-transform: translateY(50px); /* Firefox */
  -webkit-transform: translateY(50px); /* Safari | Chrome */
  -o-transform: translateY(50px); /* Opera */
  transform: translateY(50px);

  -moz-transition-duration: .5s;
  -webkit-transition-duration: .5s;
  -o-transition-duration: .5s;
  transition-duration: .5s;
}

```

HTML:

```
<div class="penduricalho">
    <a href="http://10.0.1.43/"><img src="http://alojamento.fct.unl.pt/sites/all/themes/javali_theme/images/penduricalho.png"></img></a></p>
</div>

```

Run it here if you want to see the result:

https://jsfiddle.net/sn1hs9hp/

---
Tags: theming, 8, media
---


# Question
Title: Where do I programmatically create new roles?
I want to programmatically create new roles in Drupal 8. I found this code in this post.

```
//your data array
$data = array('id' => 'client', 'label' => 'Client');
//creating your role
$role = \Drupal\user\Entity\Role::create($data);
//saving your role
$role->save();

```

But I don't know where I should put it, in which file, which folder? And how do I run it?

# Answer
You have many place to create your roles, a simple way for you (As you says that you don't know nothing about Drupal) can be create a custom page (read the post) if you follow the example in the `myPage()` function you can go trough your list of roles and create each role in a loop, something like this;

```
public function myPage() {
...
  /* Read your roles
   * $my_roles[0]['id'] = 'client';
   * $my_roles[0]['label'] = 'My Client';
   */
  for ($i = 0; $i < count($my_roles); $i++) {
    //your data array
    $data = array('id' => $my_roles[$i]['id'], 'label' => $my_roles[$i]['label']);
    //creating your role
    $role = \Drupal\user\Entity\Role::create($data);
    //saving your role
    $role->save();
  }
...
}

```

And if you go to your page you will create your roles.

**EDIT:** As Kevin says is better in other places like the hook\_install()

Follow the steps to create a module and implement the `hook_install()` (Read at the end of the page how to do it)

Inside the hook implementation you will put the code:

```
/**
 * Implements hook_install().
 */
function YOUR_MODULE_install() {
    /* Read your roles
     * $my_roles[0]['id'] = 'client';
     * $my_roles[0]['label'] = 'My Client';
     */
    for ($i = 0; $i < count($my_roles); $i++) {
      //your data array
      $data = array('id' => $my_roles[$i]['id'], 'label' => $my_roles[$i]['label']);
      //creating your role
      $role = \Drupal\user\Entity\Role::create($data);
      //saving your role
      $role->save();
    }
}

```

To create your roles you only need install your module.
> 4 votes

---
Tags: 8, users
---


# Question
Title: Results of GET Request inside block are being cached and not updating when GET request values are changed
I have a block plugin that contains a form that performs a get request and reloads the current page. Currently it's set to allow a user to submit a state from a drop down box to be used as a filter.

This issue I'm having is the results from the get request are cached. It works after clearing the cache but right after, once I submit again with a new value for the dropdown the results do not update on the page, even though I can clearly see that the get request has changed. Below is the code I currently have

```
public function build() {
    $request = \Drupal::request();
    /* GET Variables */
    $state = (empty($request->get('state')))?'':$request->get('state');

    $render = '
    <form method="GET" class="relief-network-form">
    <br/>
    <strong>State:</strong><br/>
    <select class="state" name="state">
        <option value="">Pick One</option>
        <option value="AL">Alabama</option>
        <option value="AK">Alaska</option>
        <option value="AZ">Arizona</option>
        <option value="AR">Arkansas</option>
    </select>

    <input type="submit" value="Filter">
    </form>';
    return array(
        'test'    => [
            '#type'  => 'html_tag',
            '#tag'   => 'p',
            '#value' => 'State:'.$state.'-',
        ],
        'form'       => [
            '#type'     => 'inline_template',
            '#template' => $render,
        ],
    );
}

```

When submitting this form after the cache is cleared it displays the proper state in the p tag above the form, but afterwards it never changes. I have a feeling it has to do with using cache tags after reading the documentation here https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays but to be honest I'm having trouble making sense of it, and I'm not sure how I would apply the examples to the current situation. Is there a way to prevent the results of a GET request inside a block plugin from being cached?

# Answer
> 4 votes
You don't need cache tags, you need a cache context for the query key `state`:

```
$build['#cache']['contexts'][] = 'url.query_args:state';

```

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


# Question
Title: Where to store JS and CSS that is not associated with a module?
I've been given a ZIP file with the JS, CSS, HTML, and assets for a stand-alone jQuery application. We would like to host this application through our Drupal 7 site hosted on Acquia Cloud. I am looking for best practices on where to store this application. I've included additional info below but can supplement if there's other relevant info. Can anyone suggest where I should store these files?

Due to some business-related decisions, we will always receive updates to this application in a ZIP file. It may or may not receive updates. If it does, we'd like our content admin team to be able to manage it through Drupal or FTP. It has not yet been decided if the application will be embedded in a page or accessed on it's own.

In our current site, we are not able to upload an entire directory and keep it in the same structure. Each file must be uploaded manually. We are fairly new to Drupal so I don't know if there is a module that would get us around this issue.

I am not allowed to make changes to the code or alter the directory structure (as that would require changes to the file references).

If there are no best practices for this, we can store it somewhere else and link out to it. I would prefer to avoid this but if that's the recommended best practice, we can do it.

# Answer
> 1 votes
My gut feeling would be to place it in a folder in the root of your website and access it through a subdomain. I'm not sure, without knowing more about the application, if there is an effective way to integrate it with Drupal. It seems like it should stand on its own, in it's own directory structure, as it is a separate entity. I stand to be corrected here, but i don't see a problem with hosting it concurrently with your Drupal installation. It won't be manageable through the CMS, but without building the functionality in Drupal itself, it wouldn't be anyway.

# Answer
> 1 votes
If you have a library (js and css files) called MyOwnLibrary

You can create a folder called myownlibrary in `sites/all/libraries` and placed the js file `myownlibrary.js` in the folder, so the structure is like this:

> YourSite/sites/all/libraries/myownlibrary/myownlibrary.js

And you can use the Libraries API module to use your library

> The common denominator for all Drupal modules/profiles/themes that integrate with external libraries.
>
> This module introduces a common repository for libraries in sites/all/libraries resp. sites//libraries for contributed modules.

You can check more info in the Libraries documentation page.

---
Tags: 7, javascript, files
---


# Question
Title: Change the google marker icon on Geofield module
I need to change the default google marker icon on geofield displayed in my view for a custom marker. I tried adding style google map module but it didn't work. Any idea how to do it?

# Answer
> 1 votes
Have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

> Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
>
> The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (**Google**, **OpenLayers** or **Leaflet**) with any location storage module of your choice, e.g.:

> This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
>
> Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
>
> But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
>
> These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).

Head over to its (impressive) project page for even more information about it (it would be way too long to include a quote of it all here). That project page also includes various screenshots.

**Note**: Uploading custom markers should be possible also, similar to what you can see in the screenprint in the feature request about Custom markers.

---
Tags: views, google-maps
---


# Question
Title: Check if Workbench Content Has Published Revision
We are using Rules for advanced Workbench notifications. However, we have a notification that needs to change depending on whether content actually has a previously published version or is entirely new content.

Does anyone know of a way, using Rules, to check for whether Workbench content has a published *revision*? (Note: **Not** whether the current revision is published.)

# Answer
> 1 votes
I'm assuming this question is about D7 ...

### Step 1 - Flag published revisions

Use the Flag module to flag Workbench content whenever a published revision gets created. The flag you'd want to use is a *global* flag. To actually flag such content, use the Rules module.

### Step 2 - Check if flagged

Adapt your existing Rule(s) (for advanced Workbench notifications) to take into account if your content has yes or no been flagged. To do so, you have a choice:

* Split your current Rules Action (for those notifications) in 2 Rules Components (in which you can use Rules Condition to check the flag).
* Use the Conditional Rules module so that you can include the required Rules Condition(s), to check the status of the flag, within the Rules Actions of your existing rule.

---
Tags: 7, rules, workbench
---


# Question
Title: Where should I download libraries for modules through composer?
I've started to use Drupal 8 and some modules requires some libraries. For example search api solr. When I'm installing these libraries via composer it downloads the libraries into directory of the module. For example modules/contrib/search\_api\_solr/vendor. I don't think that it's correct because contrib modules should be stored in clean state.

What the right way to install libraries for modules via composer? Where should I store them?

# Answer
Composer manager which was used with Drupal 7 is obsolete for Drupal 8 and should not be used with it. The right way to work with composer for with Drupal 8 is described here
> 2 votes

# Answer
Install Composer Manager, then you won't need to think about it:

> Composer expects each project (Drupal installation, in our case) to have a single composer.json file listing all required packages. Composer Manager allows each contributed module to ship with its own composer.json file, listing the module-specific requirements. It then merges the requirements of all found modules into the consolidated composer.json file. This results in a single vendor/ directory shared across all modules which prevents code duplication and version mismatches.
> 5 votes

---
Tags: 8, composer
---


# Question
Title: How do I check that the private file system is setup correctly from hook_requirements()?
I'm working on a module that will need to place files in the private file directory. I'd like to check that the private file system is working from within `hook_requirements()` so I can provide both an install requirement and a status check.

# Answer
> 5 votes
There are a few different ways.

Use the \Drupal\Core\Site\Settings class static method `get`:

```
if (\Drupal\Core\Site\Settings::get('file_private_path')) {

}

```

Check for the existence of the `stream_wrapper.private` service, which is only instantiated when the above check passes. Need to catch the appropriate exception coming from Symfony. **Update 2017.01.23** @Berdir suggests using the getContainer method, which means we don't have to catch the exception!

```
if (\Drupal::hasService('stream_wrapper.private')) {

}

```

Use the `file_system` service to check if it's a valid scheme. This will basically check if the above service's class exists.

```
$fileSystem = \Drupal::service('file_system');

// Check if the private file stream wrapper is ready to use.
if ($fileSystem->validScheme('private')) {

}

```

---
Tags: 8, hooks, files
---


# Question
Title: How to avoid losing custom CSS/JS on a form using Ctools Modal when Validation Errors Occur
I have a regular content type form that has been customized quite a bit with a form alter. I am wanting to see about getting that form in to a ctools modal window for the creation of that content. I am able to do so, and I am able to create content. However, my form\_alter customizes this form with some JS and CSS which is being added by specifying an #after\_build on the form.

```
/**
* implements hook_form_alter to add in some custom submit and validation callbacks
*
* @form
* the activity form at node/add/activity-log
*/
function activity_log_form_alter(&$form, &$form_state, $form_id) {
 global $user;
 //activity log form
 if($form_id == 'activity_log_node_form') {
  //specify an after build function where i can add JS and CSS files
  $form['#after_build'][] = 'activity_log_entry_form_after_build';

  //change the submit buttons text value
  $form['actions']['submit']['#value'] = t('Save this task');
  $form['actions']['submit']['#weight'] = 30;
  unset($form['actions']['preview']);

  if(isset($form['actions']['delete'])) {
    $form['actions']['delete']['#value'] = t('Delete this task entry');
    $form['actions']['delete']['#weight'] = 35;
  }

  //submit handler and validation handler
  $form['#submit'][] = 'activity_log_form_submit';
  $form['#validate'][] = 'activity_log_form_validate';

  } //end check for activity log form
}

/**
 * This function is ran after the node/add/activity-log form is built. The css and js files are added here
 * because if they are added in the form alter, they won't get included when the form throws validation errors.
 *
 * @form
 * the activiyt log form at node/add/activity-log
 */
 function activity_log_entry_form_after_build($form, &$form_state) {
    //add the chosen library in there
    drupal_add_js(libraries_get_path('chosen') . '/chosen.jquery.min.js');
    drupal_add_js(libraries_get_path('chosen') . '/chosen.proto.min.js');
    drupal_add_css(libraries_get_path('chosen') . '/chosen.min.css');

    //activity log js and css
    drupal_add_css(drupal_get_path('module', 'activity_log') . '/css/activity_log.css');
    drupal_add_js(drupal_get_path('module', 'activity_log') . '/js/activity_log.js');

   return $form;
}

```

This works great when I browse to the normal forms create content url, and if there are validation errors, all is well. However, when using the form in the modal window, if there are validation errors, I lose my JS/CSS on form rebuild even though the form\_alter and after\_build are still being called. Any ideas why?

# Answer
> 0 votes
Turns out that the JS and CSS files were not being dropped, but since the modal window uses ajax, all the ID's were being incremented when the form was rebuilt after a validation error.

So JS and CSS selectors such as edit-field-act-property-ref

```
<div id="edit-field-act-property-ref">

```

would become

```
<div id="edit-field-act-property-ref--1">

```

which is a problem if you have CSS/JS targeting the original. I thought I would share in case this helps out somebody else in the future.

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


# Question
Title: Unable to display field value in node template
If I devel the contents of my custom node--view--news.html.twig template, I get this array:

```
'body' => array(1)

  'x-default' => array(1)

    array(3)

        'value' => string(112) "<p>Curabitur ut augue at mi eleifend lobortis. Ut t asdfincidunt lacinia nisi ph…"

            <p>Curabitur ut augue at mi eleifend lobortis. Ut t asdfincidunt lacinia nisi pharetra. Quis lacinia dolor</p>

        'summary' => string(0) ""

        'format' => string(10) "basic_html"

'field_titel' => array(1)

  'x-default' => array(1)

    array(1)

        'value' => string(29) "Lorem / Ipsum / Dolor"

```

I can display the value of body by using

> {{ content.body }}

However using

> {{ content.field\_titel }}

does not display the contents of the field\_titel field. How would I display the value of a custom field in a node template?

# Answer
> 0 votes
Sounds like the same sort of question I answered over here.

Check your node display settings to see that the field is not hidden for this applicable display mode (default, teaser, etc). It is not in the content renderable array because it is likely hidden in the display settings.

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