# Question
Title: How do I attach AJAX click events on <button> or <div> tags?
There are many examples how to make ajax form submits and also many examples how to make drupal ajax links. How do I attach AJAX click events on, for example, `<button>` or `<div>` tags?

# Answer
> 0 votes
You need to write code for this element. Copied from d.o..

## STEP BY STEP

Select the element to attach Drupal.ajax object to. Lets create HTML element first.

```
/**
 * Menu  callback.
 *
 * Build container to load ajax content to.
 */
function my_module_remote() {
  $wrapper = array();
  $wrapper['#attached']['js'] = array(
    drupal_get_path('module', 'my_module') . '/my_module_ajax.js'
  );
  $wrapper['#attached']['library'] = array(
    array('system', 'drupal.ajax')
  );
  $wrapper['container'] = array(
    '#type' => 'container',
    '#attributes' => array(
      'id' => 'remote-content-wrapper',
      'title' => t('click to reload')
    )
  );
  $wrapper['container']['content'] = array(
    '#markup' => t('Loading data...')
  );
  return $wrapper;
}

```

This callback will create simple page with div container and text "Loading data..." on it. Pay attention to element with id "remote-content-wrapper". This div container we will be base DOM element for our Drupal.ajax object. In JS code we select it is with #:

```
$('#remote-content-wrapper').once('remote-content-wrapper', function() {
  var base = $(this).attr('id');
...
});

```

NOTE: I use '$.once()' method here to attach behaviour only once. Read more. So, the HTML element selected and it is div#remote-content-wrapper.

Build object of options for new AJAX element. ...

```
    var  element_settings = {
          url: window.location.protocol + '//' + window.location.hostname +  settings.basePath + settings.pathPrefix + 'ajax/remote',
          event: 'click',
          progress: {
            type: 'throbber'
          }
        };

```

... The only required keys is:

```
'url' - the path to make ajax call to, any drupal full path.
'event' - the javascript/jQuery event to react to, any string or one of the registered like 'click', 'change', 'keypress'
'progress' - the progress type. Object contain 'type' key, which can be either 'throbber' or 'bar'.

```

Other settings:

```
    keypress: true,
    effect: 'none', // jQuery effect.
    speed: 'none', // setting for jQuery effect.
    method: 'replaceWith', // Will be rewritten with ajax command.
    // The additional data to submit.
    submit: {
      'js': true
    }

```

Add the new AJAX object to global Drupal.ajax object. It is simple easy:

```
Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings);
Drupal.ajax() function-constructor takes 3 parameters:
- element id,
- DOM object,
- settings object

```

NOTE: The new element should be stored in global Drupal.ajax array of ajax objects under the element id key. Every Drupal.ajax object on the page are stored in this array.

That it! The Drupal.ajax element created. To trigger new ajax reaction we should call registered in element\_settings object event:

```
$(this).click(); // $('#remote-content-wrapper').click();

```

I use here click, but you could pass as parameter any event you want, and then trigger it with .trigger() method. AJAX callback should return array of Drupal commands or any custom registered AJAX commands which will be executed after success ajax call.

The complete js part:

```
(function ($) {
  /**
   * Load remote content after the main page loaded.
   */
  Drupal.behaviors.my_module_load_remote_content = {
    attach: function(context, settings) {
      $('#remote-content-wrapper').once('remote-content-wrapper', function() {

        var base = $(this).attr('id');

        var element_settings = {
          url: window.location.protocol + '//' + window.location.hostname +  settings.basePath + settings.pathPrefix + 'ajax/remote',
          event: 'click',
          progress: {
            type: 'throbber'
          }
        };
        Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings);
        $(this).click();
      });
    }
  };
})(jQuery);

```

The complete PHP part:

```
/**
 * Implements hook_menu().
 */
function my_module_menu() {
  $items['ajax/remote'] = array(
    'title' => 'Data',
    'page callback' => 'my_module_remote_ajax',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  $items['page'] = array(
    'title' => 'Data',
    'page callback' => 'my_module_remote',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

/**
 * Menu callback.
 *
 * Output the page with the container to load AJAX content to.
 */
function my_module_remote() {
  $wrapper = array();
  $wrapper['#attached']['js'] = array(
    drupal_get_path('module', 'submit_ajax') . '/submit_ajax.js'
  );
  $wrapper['#attached']['library'] = array(
    array('system', 'drupal.ajax')
  );
  $wrapper['container'] = array(
    '#type' => 'container',
    '#attributes' => array(
      'id' => 'remote-content-wrapper',
      'title' => t('click to reload')
    )
  );
  $wrapper['container']['content'] = array(
    '#markup' => t('Loading data...')
  );
  return $wrapper;
}

/**
 * Ajax callback.
 *
 * Load remote information.
 */
function my_module_remote_ajax() {

  $commands = array();

  $selector = '#remote-content-wrapper';
  $html = my_module_function_to_request_data_form_remote_server_and_build_html();
  // Debug messages, we can use dpm() here.
  $messages = theme('status_messages');
  $commands[] = ajax_command_prepend('body', $messages);
  // Add command with insert new requested content
  $commands[] = ajax_command_html($selector, $html);

  print ajax_render($commands);
  drupal_exit();
}

```

---
Tags: 7, ajax
---


title: Hide some buttons

text:
# Question
Title: Hide some buttons
I do not want to display the submissions button, the download button, and the customize button on the webform results tab for the user.

How can I do that?

# Answer
> 0 votes
The best way to hide menu item from the secondary tabs should be to alter the access callback of the menu item.

```
function mymodule_menu_alter(&$item) {
  // This hides the sbmissions item. Others should work simillary.
  $item['node/%webform_menu/webform-results/submissions']['access callback'] = 'mymodule_webform_result_access';
}

function mymodule_webform_result_access($node, $account = NULL) {
  // You can put here any custom logic of your needs.
  return FALSE;
}

```

# Answer
> 0 votes
To alter the tabs see https://www.drupal.org/docs/8/modules/webform/webform-cookbook/how-to-alter-local-tasks-aka-tabs

You might want to consider creating a custom view using the Webform Views module

# Answer
> -1 votes
The simpler way is with css, `display:none` to the elements you want

---
Tags: 8, webforms
---


# Question
Title: How do I set the total submissions limit when I create a node?
I'm using "Webform Node" module to create event registrations.

Now I can set the total submissions limit of event in **Structure\> Webforms\> my webform type**

and when I create a webform node, there is no setting option:

---

Because every event has different submissions limit, I want to set the limit when I create the webform node, instead of in the webform type, how can I do it? thank you so much!

# Answer
> 0 votes
* Go to the Webform's settings (/admin/structure/webform/manage/contact/settings)
* Scroll to 'Submission Limits'
* Set 'Total submissions limit per entity' or 'Per user submission limit per entity'

I think the labeling and additional help text could help better define this features. Feel free to create a ticket in the Webform module's issue queue

---
Tags: 8, webforms
---


title: Cache form Drupal change expire time

text:
# Question
Title: Cache form Drupal change expire time
I made cache\_form table work (see How to keep cache\_form small). But cache\_form, though expired cache is now cleared, is enormous anyway (nearly 2 Gb, and we have only 1000 unique users in a day). How can I change expire time? Is this caching really needed?

BTW, can you recommend any module for caching handling in Drupal? Seems there are lot of them but mostly obsolete.

# Answer
Look at the function that's used to save form "cache", `form_set_cache`:

```
function form_set_cache($form_build_id, $form, $form_state) {
  // 6 hours cache life time for forms should be plenty.
  $expire = 21600;

```

As you can see, it's hardcoded and you can't really change it without **hacking core**. Now the question is - should you?

## {form\_cache} as cache

Form data is kept as a cache bin, but it is not a "real" cache. Let's look at the definition from Wikipedia:

> In computer science, a cache (/ˈkæʃ/ KASH) is a component that transparently stores data so that future requests for that data can be served faster.

Now, that's pretty much what **{form\_cache} is not** \- it is kept to save temporary data that needs to be consistent, and that are never stored anywhere else during form processing. It means that when someone is using APC or Memcache, he needs to take extra care to prevent their "it can be deleted without any reason, for performance purposes" approach from corrupting forms. Most Drupal admins I know simply exclude form cache bin from them.

If you will shrink the time data is kept, you risk all kinds of errors. So keep in mind that your form cache bin should preserve data significantly longer than you expect anyone to need between first form display and the end of it's processing.
> 5 votes

# Answer
To contradict the accepted answer given by Mołot , I'll note that **hacking core** to change this expiry-time is ***not*** necessary; I was able to achieve this using a database-trigger. (I actually *increase* the expiry-time by 18 hours in the code I show here, but you can modify it to suit your needs).

Note that you will need to check **settings.php** to determine what `<PREFIX>` should actually be below.

If the connected database is ***MySQL***:

```
delimiter //
CREATE TRIGGER form_state_lifetime_hack BEFORE INSERT ON <PREFIX>_cache_form FOR EACH ROW
BEGIN
    SET NEW.expire = NEW.expire + (18*3600);
END;//
delimiter ;

```

For ***PostgreSQL*** it would be more like:

```
CREATE OR REPLACE FUNCTION form_state_lifetime_hack() RETURNS trigger AS
$$
    BEGIN
        NEW.expire = NEW.expire + (18*3600);
        RETURN NEW;
    END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER form_state_lifetime_hack BEFORE INSERT ON <PREFIX>_cache_form
FOR EACH ROW EXECUTE PROCEDURE form_state_lifetime_hack();

```

Note also that Drupal stores data for both `$form` and `$form_state` variables in `cache_form`, so you might want to add an `IF` block within your trigger, depending on which one you want to target. You can do this based off of the `"cid"` column:

```
+-------------------------------------------------------------+
| cid                                                         |
+-------------------------------------------------------------+
| form_form-bCxaf_A-P5-IRAmXv6K7gadd0zFF3C-UoLsIyovQMvI       |
| form_form-VV8a20AjZHWE9TkhXb1urlNNjzLmnibHulO3oH8QJiw       |
| form_form-ZQGYHDpBMqrNsQlxDoVovuiqcH_oVduYHnaqf4VijAI       |
| form_state_form-4mn85-8W5mDpsqXcTVHNsNy2Jk5G20onUt1CgropnY8 |
| form_state_form-ZQGYHDpBMqrNsQlxDoVovuiqcH_oVduYHnaqf4VijAI |
+-------------------------------------------------------------+

```

In an ideal world, changing this expiry-time could be done in a more native way using `db_update()` from a `hook_form_alter()` or `hook_submit()` implementor-function, but unfortunately these calls occur ***before*** calls to `form_set_cache()`, meaning the relevant row you want to modify won't yet be present.... even if it were, you wouldn't have the new build-ID which would allow you to identify it.

For modules you plan to distribute to others, you'd need to include the appropriate `CREATE TRIGGER` language in the ***your\_module\_name*.install**-file, and decide which SQL-flavor to use based off of the local settings.
> 1 votes

---
Tags: caching, cron
---


# Question
Title: Should I edit a closed issue with the issue summary template?
Once you go to create a new issue in drupal.org you can see a message that says:

> Learn how to report an issue. Use the issue summary template to summarize the issue in the Description field below. Others can also change the summary. Editing the summary does not subscribe you to the issue or notify subscribers, so add a comment describing your changes after any significant edit.

But there are some closed issues like Incorrect call to urldecode() in the www.drupal.org site that don't follow the template format.

Should I edit a closed issue with the issue summary template?

# Answer
Yes. It's completely appropriate to edit an issue to clarify the findings, solutions, workarounds etc. and make it easier for people who may look to that issue for reference.
> 3 votes

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


# Question
Title: Is there a way to show users that the content has been automatically translated?
I am using the Translation Management Tool module to translate my nodes automatically. What I want is for users to see whether the node they are seeing (in their language) is the translated, or the original one. I managed to make the translation (when node is saved, it is translated) and with rules I can change value of e.g. some integer field, but it changes on both nodes: original and the translated one.

How can I change it only in translated one?

# Answer
Instead of setting an integer field, create a text field called original language or source language. Use Rules to store the language code of the source language when the node is created. That way the value of the field is correct regardless of which language the user is viewing the node.

You can then compare the source language of the node with the user's current language and display a message if they do not match.
> 1 votes

---
Tags: rules, i18n-l10n
---


title: what is the use of Backup Folder?

text:
# Question
Title: what is the use of Backup Folder?
I'm going to migrate my site to another server. so, i need to backup my database if i dump my database using `mysqldump` command into backup folder. does database manage it by updating the changes done into database to the sql file.

# Answer
> 1 votes
No, the database does not update your dump-file afterwards. You should prepare your new site with a database dump.

Then when you are ready to move the site finally you should put your original site in maintenance mode, and dump and import your database with the latest content. In this way you ensure that you will get the most recent content from your old live site.

---
Tags: 7, database, backups
---


# Question
Title: How to resolve composer autoloader not found error?
So, I'm running a D7 site with composer manager. I have successfully run the `composer install` command from inside the /sites/default/files/composer directory. The libraries appear to be successfully installed, but my watchdog is loaded with `RuntimeException: Autoloader not found: /var/www/html/psrlivetoupdate/sites/all/vendor/autoload.php in composer_manager_register_autoloader() (line 173 of /var/www/html/psrlivetoupdate/sites/all/modules/composer_manager/composer_manager.module).` and there's also a notice in the site's status report that composer's dependencies haven't been installed. Any idea what's going on and or how to address it?

# Answer
So, this is something that is a little bit wonky in the user interface for composer manager. The file path to where the autoloader should be gets generated automatically in reference to the drupal root of where you configure composer. If your live and development environments have different doc roots, as is likely with a shared host (e.g. `/var/www/html/mysite` vs `/yourhost/public_html/blahblah`, your path will be different and drupal won't know where to look. To solve this problem you have to modify the composer manager file directory variable to reflect where the file actually is. You can't change this through composer manager's settings tab, because it will generate a site error that prevents navigating to the tab and editing it there. You can most easily edit this variable with the devel module's variable editor function.
> 2 votes

---
Tags: 7, composer
---


# Question
Title: How to set required to TRUE or FALSE based on the GIVEN #states?
I have problem with the required. It does not return a required validation when I clicked submit button. What is wrong with this code?

```
$form['fieldset1']['last_name'] = array(
  '#type' => 'textfield',
  '#title' => t('Last Name'),
  '#states' => array(
    'required' => array(
      ':input[name="payment_method"]' =>  array('value' => array('credit', 'debit')),
    ),
  ),
  '#attributes' => array(
    'placeholder' => array('Last Name'),
  ),
);

```

# Answer
> 2 votes
States are used to set properties/values by javascript. The `#required` property is for the server-side validation, it can't be controlled using states.

You could either implement an AJAX callback on the text field change to update the required status and rebuild the form, or implement a validation handler which checks the status of the text field and throws an error if it contains text but no payment method has been selected.

---
Tags: forms
---


title: Views header language in url

text:
# Question
Title: Views header language in url
I am trying to add a link in views header. I enabled multilingual module. Added a Global Textarea in the header. Then added

```
<a href="/my-tickets">Click</a>

```

I want to set the url as

```
<a href="SELECTED_LANGUAGE_CODE/my-tickets">Click</a>

```

So the link may be

```
<a href="en/my-tickets">Click</a>

```

or

```
<a href="fr/my-tickets">Click</a>

```

SELECTED\_LANGUAGE\_CODE is the language selected in the url.

English version of my site is http://example.com/en French version http://example.com/en

# Answer
> 2 votes
You can use the token \[site:url\] which includes the languages prefix:

```
<a href="[site:url]/my-tickets">Click</a>

```

---
Tags: views, 8
---


title: What's best module to built pie chart?

text:
# Question
Title: What's best module to built pie chart?
I want to build a pie chart to make a statistic for all my events. But, there are a lot of module. I want to know what's the best and responsive? I'm using drupal

# Answer
I would suggest https://www.drupal.org/project/easychart. It has support for both Drupal 7 & 8. I don't have a lot of experience with the module itself but I have used the Javascript library (http://www.highcharts.com/products/highcharts) it uses and it is nice.
> 1 votes

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


# Question
Title: Drupal 8.2.5 no internal pages on fresh install
Just installed Drupal 8 on a Ubuntu 16.04 server. Everything looked great until the final install and then there was no stylesheets on the site and all of the links give an

```
The requested URL /admin was not found on this server.

Apache/2.4.18 (Ubuntu) Server  ###########.net Port 80

```

error. This error persists for all linked pages.

I installed it previously on the server with the same issue, except before it had the Bartik theme. I realized I had built the database on it incorrectly and it was faster to reimage the server then go in and delete everything and put things back proper, plus I figured that way it would be fresh.

Thanks in advance for the help,
Joey

# Answer
Try to clear caches using drush from the terminal.

```
drush cr

```

Also uncheck the following under **Bandwidth optimization**

External resources can be optimized automatically, which can reduce both the size and number of requests made to your website.

Aggregate CSS files

Aggregate JavaScript files

from http://drupal.local/admin/config/development/performance
> 0 votes

---
Tags: theming, 8, installation
---


title: Inserting a field to multiple regions

text:
# Question
Title: Inserting a field to multiple regions
I have a content type with field\_slides and I want to use it on multiple region in the same page. its a slide show using light gallery, at mobile view I want to hide the first div and show it on the second one.

```
<body>
<div class="first-div"> {{content.slides}} </div>
<div class="second-div">{{content.slides}} </div>
</body>

```

The issue is the slides works fine on the first div but if i try to open it on the second div it keeps scrolling to the top ( first div )/reloading the page sometimes. However if I removed the region from the first div it works fine on the second div, I want to have it working on both the divs. Is this possible ?? please help

I also tried this

```
<script type="text/javascript">

jQuery(document).ready(function() {
  if (($(window).width() < 701 )) {
    $(".first-div").empty();
    $(".second-div").append( "{{content.slides}}" );
   }
  else {
    $(".first-div").append( "{{content.slides}}" );
    $(".second-div").empty();
  }
});
</script>

```

Its not working either ---

Here is the actual twig template

```
{% set slider2 = content.content_2_project %}
   <body>
      <div id="fullpage">
        <div class="section">
          <div class="portfolio-section1">
            <div class="port-top">
              {{content.content_1_project}}
              {{content.content_1_punch}}
          </div>
        </div>
      </div>

        <div class="section">
          <div class="portfolio-section2">
              <div class="port-left">
                <div class="port-left-inner">
                  {{content.content_2_body}}
                  {{content.content_2_body_details}}
                </div>
              </div>
              <div class="port-right">
                <div class="port-right-slide-container">
                    {{content.content_2_project}}
                </div>
              </div>
          </div>
        </div>
        <div class="section mobile-section">
          <div class="port-mob-slide-container">
                {{ slider2 }}
          </div>
        </div>
      </div>
    </body>

```

i'm using Fullpage.js on the drupal 8 site.

# Answer
Try this tricky method

```
{% set slider2 =content.slides %}
<body>
<div class="first-div"> {{content.slides}} </div>
<div class="second-div">{{slider2}} </div>
</body>

```
> 0 votes

---
Tags: theming, 8
---


# Question
Title: Change the subtotal amount in commerce_email_order_items
First, sorry for my poor English, and the faults you will probably found.

Globally, what I am trying to do , is to add the shipping amount into the 'base\_price' component price, also labelled subtotal.

So far, it's working correctly on the site itself with the use of the hook **hook\_commerce\_price\_formatted\_components\_alter().** To give you an idea, here is the code that handle it.

```
function base_price_shipping_commerce_price_formatted_components_alter(&$components, $price, $entity) {
    // We modify $variables to "merge" base_price and shipping
if ( isset($components['base_price']) && !empty($components['base_price']) &&
    isset($components['flat_rate_expedition_internationale']) && !empty($components['flat_rate_expedition_internationale'])) {
    // We calculate the new price with included expedition
    $price_with_shipping_amount = $components['base_price']['price']['amount'] +
        $components['flat_rate_expedition_internationale']['price']['amount'];
    // We format this price with the used currency
    $price_with_shipping_formatted = commerce_currency_format($price_with_shipping_amount, $components['base_price']['price']['currency_code']);
    // We update the display of base_price component with the new price
    $components['base_price']['price']['amount'] = $price_with_shipping_amount;
    $components['base_price']['formatted_price'] = $price_with_shipping_formatted;
    // We unset the display of shipping
    //unset($components['flat_rate_expedition_internationale']);
}
}

```

Now the problem is to do the same thing with the token \[commerce-order:commerce-email-order-items\]. I know it's generated with commerce\_email\_order\_items() and by commerce\_email\_prepare\_table() specially. But I don't get to understand how to make it work, or where to make the change.

**Directly and overide the function commerce\_email\_prepare\_table() ?** It will probably be around the ligne 174 in the commerce\_email.module file :

```
$data = $wrapper->commerce_order_total->data->value();
 if (!empty($data['components'])) {

   foreach ($data['components'] as $key => &$component) {

     if ($data['components'][$key]['name'] == 'base_price') {
    $rows[] = array(
      'data' => array(
        ' ',
        array('data' => t('Subtotal:'), 'style' => array('font-weight: bold; text-align: right;')),
        array('data' => number_format(commerce_currency_amount_to_decimal($data['components'][$key]['price']['amount'], $currency_code), 2), 'style' => array('font-weight: bold; text-align: left;')),
      )
    );
  }

```

**Another possibility is to change the amount of the 'base\_price' component, not on a formatted level (which just change it before display), but at the "root", for real.** I don't know if I am clear enough. But after days of research and try to understood the Price API, I still don't get it, and which hook or function to use : http://www.drupalcontrib.org/api/drupal/contributions%21commerce%21modules%21price%21commerce\_price.module/7

Which way do you think is the best ? Thank you for reading. Pierre.

# Answer
> 0 votes
Well, after re-examining the code of the commerce\_email.module, I had an epiphany, and finally get it.

Here is the code before my change (starting line 169) :

```
$data = $wrapper->commerce_order_total->data->value();
  if (!empty($data['components'])) {

foreach ($data['components'] as $key => &$component) {

  if ($data['components'][$key]['name'] == 'base_price') {
    $rows[] = array(
      'data' => array(
        ' ',
        array('data' => t('Subtotal:'), 'style' => array('font-weight: bold; text-align: right;')),
        array('data' => number_format(commerce_currency_amount_to_decimal($data['components'][$key]['price']['amount'], $currency_code), 2), 'style' => array('font-weight: bold; text-align: left;')),
      )
    );
  }

```

And now with my change :

```
$data = $wrapper->commerce_order_total->data->value();
 if (!empty($data['components'])) {
  foreach ($data['components'] as $key => &$component) {
         if ($data['components'][$key]['name'] == 'flat_rate_expedition_internationale' || $data['components'][$key]['name'] == 'flat_rate_expedition_outremerre' ) {
            $amount_expedition = $data['components'][$key]['price']['amount'];
          }

  }
  foreach ($data['components'] as $key => &$component) {
      if ($data['components'][$key]['name'] == 'base_price') {

          $amount_base_price = $data['components'][$key]['price']['amount'];
            if (isset($amount_expedition)) {
                $amount_base_price += $amount_expedition;
            }
          $rows[] = array(
              'data' => array(
                  ' ',
                  array('data' => t('Prix HT :'), 'style' => array('font-weight: bold; text-align: right; margin-top: 10px')),
                  array('data' => number_format(commerce_currency_amount_to_decimal($amount_base_price, $currency_code), 2), 'style' => array('font-weight: bold; text-align: right;')),
              )
          );
      }

```

It's not a great solution, and I will try to make a full module, to select dynamically the components to add to the base\_price. Until then, this will do the job.

---
Tags: commerce
---


title: Add exposed filter for user roles

text:
# Question
Title: Add exposed filter for user roles
In Ubercart, the uc\_order view (admin/structure/views/view/uc\_orders) uses exposed filters for status and order ID.

I can add another filter, for example username, email and so on by clicking on *Add filter criteria* and selecting the criteria (user:username, user:email).

I need to add a filter to filter orders by the roles assigned to customers. There is no option such as user:roles in the filter criteria list to select.

How can I achieve this?

# Answer
> 0 votes
By configuring the **Access**: section on the **Page settings**, we can manage Page: Access restrictions.

Choose the **Roles** and assign the required user role.

# Answer
> 0 votes
The solution is to open "advanced" section, add new "relationship" marked as "order:customer". After this new options in "add filter" will be available. So click at "add filter" and select "user:role" and set it as "exposed to users".

---
Tags: 7, views, ubercart
---


# Question
Title: #states not detecting a change to form via ajax_command_invoke
I have a form. On an elements I have an ajax call back. In the callback I use the `commands[]` to update some elements on the screen. One of the elements i have updated is used by another form element using the `#states`. When the ajax call is executed the first time the `#states` sees that the value has changed and updates.

When I call the ajax event for a second time the `#states` does not see the same. One my ajax\_commands is invoking the jQuery `change()`.

I have an `alert()` being thrown when the element is changed and can see that it is being hit every time. However the `#states` is not updating.

Is there a way to get `#states` for the form to reevaluate from JavaScript?

# Answer
> 1 votes
For those who might come across this post, I think the problem is related to these issues :

I found the solution to my problem (close to this one) by reading them.

Actually states may be no longer valid after an AJAX modification because some elements are still flagged as already initialized by the states system. This case produces when just the dependee element or the dependent element is altered by the AJAX request, not both. Only a side of the relation is updated, the other side keeping its old information. Dependee and dependent are therefore no longer linked and the state has no more effect.

---
Tags: 7, forms, ajax, javascript
---


# Question
Title: How to remove reference field value after delete its reference node
Let say, I have 2 nodes.
In first node, I add a reference to an existing node, e.g. *Test node \[nid:2\]*; I delete the referenced node. When I edit the first node,the reference field shows *\[nid:2\]*.

How can I make that reference field empty, once the referenced node is deleted?

# Answer
Try using Reference Delete module..

Project page says

> Deletes values in reference fields created with Entity Reference or References when the referenced entity is deleted.
> 1 votes

# Answer
If you want to add code for that purpose to a custom module you already have, then you can use the code the Reference Delete module is using as guide.

In short, the code used in the 7.x-1 branch:

* When an entity is deleted, it adds its ID and type to a queue
* During cron task, delete the reference to the deleted entities found on the tables used from the reference fields

The first part is done implementing `hook_entity_delete()`. For the second part, this is the relevant code used from that module.

```
/**
 * Returns an array of fields, filtered by module.
 */
function _reference_delete_get_reference_fields($module) {
  $fields = field_info_field_map();

  $reference_fields = array();

  foreach ( $fields as $field_name => &$properties ) {
    $properties = field_info_field($field_name);

    if ($properties['module'] == $module) {
      $reference_fields[$field_name] = $properties;
    }
  }

  if ( !empty($reference_fields) ) {
    return $reference_fields;
  }
}

/**
 * Implements hook_reference_delete_delete_references().
 */
function entityreference_reference_delete_delete_references($entity_id, $type) {
  $module = 'entityreference';

  if ( $fields = _reference_delete_get_reference_fields($module) ) {
    foreach ( $fields as $field_name => $properties ) {
      // Acts only if the target entity is of the same type of the entity that's being deleted
      if ( $properties['settings']['target_type'] == $type ) {
        $tables = reset($properties['storage']['details']);

        foreach ( $tables as $table ) {
          $keys = array_keys($table);
          $table_name = reset($keys);
          $column_name = $table[$table_name]['target_id'];

          db_delete($table_name)
          ->condition($column_name, $entity_id, '=')
          ->execute();

          watchdog('reference_delete', 'Deleted all references to entity %entity_type #!entity_id from table !table', array('%entity_type' => $type, '!entity_id' => $entity_id, '!table' => $table_name), WATCHDOG_NOTICE);
        }
      }
    }
  }
}

/**
 * Implements hook_reference_delete_delete_references().
 */
function references_reference_delete_delete_references($entity_id, $type) {
  switch ($type) {
    case 'node' :
      $module = 'node_reference';

      if ( $fields = _references_reference_delete_make_table_names($module) ) {
        foreach ( $fields as $field => $tables ) {
          foreach ( $tables as $table ) {
            db_delete($table)
              ->condition($field . '_nid', $entity_id, '=')
              ->execute();

            watchdog('reference_delete', 'Deleted all references to entity %entity_type #!entity_id from table !table', array('%entity_type' => $type, '!entity_id' => $entity_id, '!table' => $table_name), WATCHDOG_NOTICE);
          }
        }
      }
    break;

    case 'user' :
      $module = 'user_reference';

      if ( $fields = _references_reference_delete_make_table_names($module) ) {
        foreach ( $fields as $field => $tables ) {
          foreach ( $tables as $table_name ) {
            db_delete($table_name)
              ->condition($field . '_uid', $entity_id, '=')
              ->execute();

            watchdog('reference_delete', 'Deleted all references to entity %entity_type #!entity_id from table !table', array('%entity_type' => $type, '!entity_id' => $entity_id, '!table' => $table_name), WATCHDOG_NOTICE);
          }
        }
      }
    break;
  }
}

/**
 * Creates table names (used only for References).
 */
function _references_reference_delete_make_table_names($module) {
  if (isset($module)) {
    $fields = _reference_delete_get_reference_fields($module);

    if ( count($fields) ) {
      $tables = array();
      foreach ( $fields as $field ) {

        $tables[$field] = array('field_data_' . $field, 'field_revision_' . $field);
      }

      return $tables;
    }
  }
}

```

`hook_reference_delete_delete_references()` is a hook used from that module. You don't need to implement it, but use that code to write a function, or a hook, for example `hook_cron()` or the worker callback of a queue, in the case you want to follow the same approach used from that module.

I would rather implement `hook_entity_delete()` and delete any reference to the deleted node from the tables used from the reference module being used.
> 0 votes

---
Tags: nodes
---


# Question
Title: How to render a field in a Views' PHP code field?
in a view, I would like to render the field `$data->field_field_video[0]` in a PHP code field. It seems that it contains all the information needed to be formatted but how can I output in the HTML ?

```
 [rendered] => Array
    (
     [0] => Array (
                [#theme] => image_style
                [#path] => public://video_embed_field_thumbnails/vimeo/58413545.jpg
                [#style_name] => square_thumbnail-100 [#children] =>  [#printed] => 1 )
      ...

```

Thanks

# Answer
> 3 votes
```
<?php
  print drupal_render($data->field_field_video);
?>

```

# Answer
> 0 votes
Just for information of new visitors, data contains field\_ as suffix in original field. So field\_name will be rendered using

```
<?php
 print drupal_render($data->field_field_name);
?>

```

# Answer
> 0 votes
The correct way of the rendering one of the view pages where you list custom fields of different article types is using the `$view->render_field()` function.

```
<?php print $view->render_field('field_your_field_name', $row_number);?>

```

based on your example it should look like this:

```
<?php print $view->render_field('field_video', $row_number);?>

```

as it is declared in the documentation.

If you use `drupal_render()` or `render()` functions, it works in 7.50, but you will get a lot of warnings in 7.54.

---
Tags: views
---


# Question
Title: Show/hide views on content-type based on taxonomy-terms
I have an activity-content-type with a taxonomy field, where I can choose from different taxonomy terms related to the activity. Now I have different views and I want to show the specific view on every activity-page, which is related to the chosen taxonomy-fields.

Lets say I have different bike-tours and diff. hikes (activities). Some are for beginners and some are for pros - some are for families and some are for couples and so on. Now I want to cross-link between the different activities and give more inspiration regarding suitable activities. If someone clicks on a bike-tour that is tagged with "beginners" and "families", drupal should show a view that offers other activities (bike-tours and hikes) that suit that criteria - also tagged with "beginners" and "families". Something like "Other familyfriendly beginner activities".

The machine names of the views don't relate with the chosen option at the moment. I would need to build a view for every combination at the moment - this is fine now (few combinations) but not scalable. I thought about combining all in one view (ideal), but couldn't find a solution yet.

Emanuel

# Answer
> 0 votes
The general idea is the following:

You create a custom block (via custom module). You place it through the interace to be visible only on nodes of type "A".

The code checks the value of field\_tags.

1. if it is "tag1" -\> views\_embed\_view('test\_view\_1', 'block\_1');
2. if it is "tag2" -\> views\_embed\_view('test\_view\_2', 'block\_1);

You can see code below:

```
namespace Drupal\form_overwrite\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'DefaultBlock' block.
 *
 * @Block(
 *  id = "default_block",
 *  admin_label = @Translation("Default block"),
 * )
 */
class DefaultBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {

    // Gets current node.
    $node = \Drupal::routeMatch()->getParameter('node');

    // Assuming only 1 value here.
    $tid = $node->get('field_tags')->getString();

    // If there are more values you have to loop through them. The format is.
    // $tid = $tag[0]['target_id'];

    // Loads the taxonomy term.
    $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($tid);

    // Gets the label.
    $name = $term->label();

    // TODO: probably a better idea would be to use uuid of those terms, since
    // the names tend to change overtime.
    // TODO: Didn't test a case with translations.
    if ($name == 'tag1') {
      // Using the old but gold function views_embed_view() to get renderable array.
      // The render function spits the html, based on views_embed_view output.
      $content = render(views_embed_view('test_view_1', 'block_1'));
    }
    elseif ($name == 'tag2') {
      $content = render(views_embed_view('test_view_1', 'block_1'));
    }
    else {
      // Case where there is not tag.
      $content = '.....';
    }
    $build = [];
    $build['default_block']['#markup'] = render($content);
    // TODO: Remove it after development. It is used only to invalidate the cache.
    $build['#cache']['max-age'] = 0;

    return $build;

  }

}

```

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


# Question
Title: Appending string causing link to render as plain html
The following code is returning html in plain text instead of link.for example its printing Edit slides intead of converting in to link.

```
$editslides = Url::fromUserInput('/admin/dexp_layerslider/'. $row->id . '/editslides');
      $editslides_link = (Link::fromTextAndUrl('Edit slides', $editslides)->toString());
      $exportslides = Url::fromUserInput('/admin/dexp_layerslider/'. $row->id . '/export');
      $exportslides_link =  (Link::fromTextAndUrl('Export slides', $exportslides)->toString());
      $deleteslides = Url::fromUserInput('/admin/dexp_layerslider/'. $row->id . '/delete');
      $deleteslides_link =  (Link::fromTextAndUrl('Delete', $deleteslides)->toString());
      $tmp[] =  $editslides_link .' ,' .$exportslides_link .' ,' .$deleteslides_link;

```

Though if i don't append string in `$tmp[]` code render the links. For example

```
  $tmp[] =  $editslides_link;

```

The complete code is as below

```
  public function dexp_layerslider_list() {
    $header = [
      'ID',
      'Name',
      'Action',
    ];
    $results = \Drupal::database->select('dexp_layerslider', 'd')->fields('d', [
      'id',
      'name',
    ])->execute();
    foreach ($results as $row) {
      $url = Url::fromUserInput('/admin/dexp_layerslider/'. $row->id . '/edit');
      $row->name = (Link::fromTextAndUrl($row->name, $url)->toString());
      $tmp = (array) $row;
      $editslides = Url::fromUserInput('/admin/dexp_layerslider/'. $row->id . '/editslides');
      $editslides_link = (Link::fromTextAndUrl('Edit slides', $editslides)->toString());
      $exportslides = Url::fromUserInput('/admin/dexp_layerslider/'. $row->id . '/export');
      $exportslides_link =  (Link::fromTextAndUrl('Export slides', $exportslides)->toString());
      $deleteslides = Url::fromUserInput('/admin/dexp_layerslider/'. $row->id . '/delete');
      $deleteslides_link =  (Link::fromTextAndUrl('Delete', $deleteslides)->toString());
      $tmp[] =  $editslides_link .' ,' .$exportslides_link .' ,' .$deleteslides_link;
      $rows[] = $tmp;
    }
    $table = array(
      '#type' => 'table',
      '#header' => $header,
      '#rows' => $rows,
      '#attributes' => [],
      '#caption' => '',
      '#colgroups' => [],
      '#sticky' => FALSE,
      '#empty' => t('No slider created yet.'),
       );
     return  $table;
  }

```

# Answer
> 3 votes
The toString method of Link returns the HTML string for the link object.

HTML strings in the table render array are wrapped in a **markup** element which escapes many HTML tags for security concerns.

You can, however, pass your own render array in the row as follows:

```
$table['#rows'][0]['item']['data'] = [
  '#type' => 'inline_template',
  '#template' => '{{ link1 }}, {{ link2 }}, {{ link3 }}',
  '#context' => [
    'link1' => $link1->toRenderable(),
    'link2' => $link2->toRenderable(),
    'link3' => $link3->toRenderable(),
  ]
];

```

# Answer
> 0 votes
This is the working code , if it helps any one. `public function dexp_layerslider_list() {
 $header = [
 'ID',
 'Name',
 'Action',
 ] ;
 $results = db_select('{dexp_layerslider}', 'd')->fields('d', [
 'id',
 'name',
 ])->execute();
 foreach ($results as $row) {
 $url = Url::fromUserInput("/admin/dexp_layerslider/". $row->id . "/edit");
 $row->name = (Link::fromTextAndUrl($row->name, $url));
 $editslides = Url::fromUserInput('/admin/dexp_layerslider/'.$row->id.'/editslides');
 $editslides_link = (Link::fromTextAndUrl('Edit slides', $editslides))->toString();
 $exportslides = Url::fromUserInput('/admin/dexp_layerslider/'. $row->id . '/export');
 $exportslides_link = (Link::fromTextAndUrl('Export slides', $exportslides))->toString();
 $deleteslides = Url::fromUserInput('/admin/dexp_layerslider/'. $row->id . '/delete');
 $deleteslides_link = (Link::fromTextAndUrl('Delete', $deleteslides))->toString();
 $tmp = [
 '#type' => 'inline_template',
 '#template' => '{{ link1 |raw }}, {{ link2 | raw }}, {{ link3 | raw}}',
 '#context' => [
 'link1' => $editslides_link->getGeneratedLink(),
 'link2' => $exportslides_link->getGeneratedLink(),
 'link3' => $deleteslides_link->getGeneratedLink(),
 ]
 ];
 // Row with attributes on the row and some of its cells.
 $rows[] = array(
 'data' => array($row->id,$row->name,$tmp )
 );
 }
 $table = array(
 '#type' => 'table',
 '#header' => $header,
 '#rows' => $rows,
 '#sticky' => FALSE,
 '#empty' => t('No slider created yet.'),
 );
 for($i= 0; $i
 $table['#rows'][$i]['data'][2] = $tmp;
 }
 return $table;
 }`

---
Tags: theming, 8
---


title: Will the support for jQuery 3 be added?

text:
# Question
Title: Will the support for jQuery 3 be added?
I'm trying to use the jQuery Chosen library with the image-select plugin in Drupal, but I can't get the element to render correctly. The example page uses jQuery 3 and Drupal 8 doesn't.

Will Drupal 8 support jQuery 3?

# Answer
There is an ongoing discussion on the Drupal core issue queue: Update jQuery to version 3.

The issue has been marked fixed on August 1, 2017. The patch has been committed on Drupal 8.4.x and Drupal 8.5.x.
> 3 votes

# Answer
As Clive said, you can add whatever version of jQuery you want to a page. However, there's an issue here worth following Update jQuery to version 3

> Now that jQuery 3.0 has been released jQuery 2.x will only be receiving security updates. I know what we've had discussions about updating specific libraries in the past. But there are a few compelling reasons why we should consider updating jQuery to 3.x
> 1 votes

---
Tags: 8, javascript
---


# Question
Title: Temporary disable ordering in Drupal Commerce
I need to temporary disable ordering until some date. So, I need to unable users to have add to cart button and unable them to go to checkout or cart.

But still I need to enable everything after this date.

How I can do this in Drupal Commerce? I'm using v7.x-1.13.

# Answer
The simplest thing to do would be to disable "Access checkout" permission for these non-privileged users. That may result in some usability issues where links appear that would be inaccessible, so you'll want to confirm that and adjust those interfaces appropriately.
> 1 votes

---
Tags: 7, commerce, rules
---


# Question
Title: How to make my user notifications module notify node authors about new comments?
I need to send a notification to the article owner when some user comments on the review added to an article.

But in the Rules module, while adding a Rules Action, there is this action: '`Send notification to user when flag is applied`' (part of a custom module I inherited from a prior mantainer of this site). With this action, notification is only sent to the reviewer, not the article owner.

Can anyone help to get this to work? Or is there another way to make this work without the custom module I'm struggling with?

Here is my rule:

```
{ "rules_send_notification_when_commented_on_article_listing" : {
    "LABEL" : "send notification when commented on article\/listing",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "user_notifications", "comment" ],
    "ON" : { "comment_insert" : [] },
    "IF" : [
      { "entity_is_of_bundle" : {
          "entity" : [ "comment" ],
          "type" : "comment",
          "bundle" : { "value" : {
              "comment_node_article" : "comment_node_article",
              "comment_node_page" : "comment_node_page",
              "comment_node_comment" : "comment_node_comment",
              "comment_node_company" : "comment_node_company",
              "comment_node_review" : "comment_node_review"
            }
          }
        }
      },
      { "NOT data_is" : { "data" : [ "comment:node:author" ], "value" : [ "comment:author" ] } }
    ],
    "DO" : [
      { "user_notifications_action_send_notification_flag" : {
          "flag_as_flag" : "commented",
          "content" : [ "comment:node" ],
          "message" : "commeted on ",
          "heading" : "d"
        }
      }
    ]
  }
}

```

# Answer
> 0 votes
As per the "*Or is there another way to make this work without the custom module I'm struggling with?*" in your question, IMO the answer is **yes**. Read on for more details about how to "*send a notification to the article owner when some user comments on the review added to an article.*" (as in your question).

Have a look at this, rather basic, rule (in Rules export format):

```
{ "rules_notify_node_author_about_new_comment" : {
    "LABEL" : "Notify node author about new comment",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "comment" ],
    "ON" : { "comment_insert" : [] },
    "IF" : [
      { "NOT data_is" : { "data" : [ "comment:node:author" ], "value" : [ "comment:author" ] } }
    ],
    "DO" : [
      { "mail" : {
          "to" : [ "comment:node:author:mail" ],
          "subject" : "A new comment was posted to the node you authored",
          "message" : "A new comment was posted, you can find it at [comment:url]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

Use the Rule UI to import it in your own environment. Some more details about this rule:

* **Event**: After saving a new comment.
* **Condition**: Check that the user who posted the comment is different from the node author (I'd think it doesn't make sense to notify the node author of comments posted by the node author, right?).
* **Action**: Send an eMail to the node author, with a link to the comment that got posted.

Feel free to add any rules conditions that may fit to further improve the above prototype, to fit your actual requirements.

Note that the above rule doesn't depend on any other module, though you could make it way more sophisticated if you'd also get the Message module involved (eg to create a log file of all such eMails ever being produced, if that's what you'd want to do).

BTW: no need for custom code ...

---
Tags: rules, notifications
---


# Question
Title: Which Rules event can I use to send a weekly mail to all users using Rules?
I'm using Drupal 7 and I need to send a weekly mail to all users.

I want to use the Rules module to do this. But I couldn't find a Rules Event which allows for this.

How can I implement that?

# Answer
> 1 votes
Below is a blue print of how I would resolve this challenge, without any custom code needed ...

### Step 1: Enable the 'Rules Once per Day' module

Have a look at the "Rules Once per Day" module. Here is how it works (as per the comment in issue 2495775, from the module owner):

* You specify a **trigger hour** on the administration settings page for this module.
* The Rule trigger will then **run when cron tasks are first run after the start of that hour**. The actual run time will depend on your cron task timings.

So this is another way to understand/Read this:

* The "Event" will only be triggered when a cron job is run.
* And that event will only be triggered 1 time / day, i.e. "next time cron runs after the trigger hour has passed".

On top of that, also note what's mentioned on its project page, ie:

> The module also provides a "**Day of the week is a**" Rules condition, to further restrict actions to being run on specific day(s) of the week, on working days only, or at weekends only.

With that, you should be able to adapt any rule to perform its rules actions **only once a week**.

### Step 2: Create your custom rule

As per your "mail to all users" requirement (for which you want to use the Rules module), just create some custom rule to do so. The most straight forward Rules Action to use for this, seems to be "Send an eMail to all users of a selected role", whereas role is just authenticated users.

If however you want more granularity in the set of users to be selected, you could use the Views Rules module instead. for more details on such approach, refer to the `Plan b` part of my answer to "What's wrong in my rule for sending e-mails using VBO?".

---
Tags: rules, emails
---


# Question
Title: Get node bundle (content type) from EntityInterface
trying to find if node is bundle `article` (node bundle = content type) before executing the rest of the statements in the following example

I can test if the entity is `node` but I can't figure out how to test if content type is `article`

```
<?php

use \Drupal\Core\Entity\EntityInterface;

function MODULE_NAME_entity_presave(EntityInterface $entity){

    //if content type is article
    if ($entity->getEntityType()->id() == 'node') {
        //do wonderful stuff ...
    }
}

```

# Answer
> 7 votes
I did manage to find it after all `$entity->bundle()` it was pretty easy ...

```
 if ($entity->getEntityType()->id() == 'node' && $entity->bundle() == 'article') {

```

---
Tags: 8, entities
---


# Question
Title: How to create my own custom simple action in D8?
I'm creating a view that is used to review migrated content that was flagged for review during the migration process. I want to provide a bulk action on this view that allows the user to select a bunch and mark them as "resolved".

I created a custom action to do this following some guidance from https://www.drupal.org/node/2330631:

`config/install/pu_news_migrate.action.resolve_news_migration_flag.yml`

```
langcode: en
status: true
dependencies:
  module:
    - node
id: resolve_news_migration_flag
label: 'Resolve news migration flag'
type: node
plugin: resolve_news_migration_flag
configuration: {  }

```

And created the action plugin implementation:

\`src/Plugin/Action/ResolveNewsMigrationFlag.php

```
<?php

namespace Drupal\pu_news_migrate\Plugin\Action;

use Drupal\Core\Action\ActionBase;
use Drupal\Core\Session\AccountInterface;

/**
 * Removes the "needs review" flag on a migrated news article.
 *
 * @Action(
 *   id = "resolve_news_migration_flag",
 *   label = @Translation("Resolve news migration flag"),
 *   type = "node"
 * )
 */
class ResolveNewsMigrationFlag extends ActionBase {

  /**
   * {@inheritdoc}
   */
  public function execute($node = NULL) {
    if ($node) {
      /** @var \Drupal\node\NodeInterface $node */
      if (!$node->hasField('field_news_migration_review')) {
        throw new \RuntimeException("News migration field not found on node.");
      }
      $node->set('field_news_migration_review', FALSE);
      $node->save();
    }
  }

  /**
   * {@inheritdoc}
   */
  public function access($object, AccountInterface $account = NULL, $return_as_object = FALSE) {
    /** @var \Drupal\node\NodeInterface $object */
    $result = $object->field_news_migration_review->access('edit', $account, TRUE)
      ->andIf($object->access('update', $account, TRUE));

    return $return_as_object ? $result : $result->isAllowed();
  }

}

```

I also added a schema file: `config/schema/pu_news_migrate.schema.yml`:

```
action.configuration.resolve_news_migration_flag:
  type: resolve_news_migration_flag
  label: 'Remove the "needs review" flag from a migrated article.'

```

I uninstalled the module and re-installed it so that the action definition is loaded into Drupal's config.

However, when I view the list of actions I can select in views, it doesn't appear there. I enabled the "Actions" module which displays a list of all actions, and it does not appear there either.

What did I do wrong here?

# Answer
> 10 votes
Action plugin yaml definitions need to be prefixed with the name `system.action.action_name.yml`, and not `mymodule.action_name.yml`.

For reference, check the provided action plugins for node and user module in core in their `config/install` and `config/schema` folders.

Uninstall the module, rename the files, and install the module again so the changes are picked up. You should then see your custom action.

So:

`config/install/system.action.resolve_news_migration_flag.yml`

---
Tags: plugins, 8
---


# Question
Title: How i can increase the Block settings limit?
We are implementing blocks through features and features extra module.

Here only 50 blocks are displaying in `admin>structure>features>create Components`. We want to increase that limit to **100**. Please find the attached snapshot.

# Answer
> 0 votes
There are a couple of things you could do for increasing the limit on blocks that you can add to your site. For instance, have you tried increasing max\_input\_vars limit in your .htaccess or in your php.ini file? From 1000 to, let's say, 2000?

Or increasing your limit in your settings.php file if not?

See if this post here (its second half rather) can be of any help: https://www.optasy.com/blog/how-add-more-lot-more-blocks-your-drupal-site

---
Tags: features
---


# Question
Title: What is wrong with my custom Entity form validation?
I add

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

```

to MymoduleMyentityForm.php which starts with

```
namespace Drupal\association\Form;
use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Form\FormStateInterface;

```

Then I run the form and when I submit it, I get this error: *Uncaught PHP Exception Drupal\Core\Entity\EntityStorageException: "Entity validation was skipped." at /Applications/MAMP/htdocs/JdP8/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php line 770*

Any idea why? What am I doing wrong?

# Answer
Documentation of `ContentEntityForm::validateForm`:

> Button-level validation handlers are highly discouraged for entity forms, as they will prevent entity validation from running. If the entity is going to be saved during the form submission, this method should be manually invoked from the button-level validation handler, otherwise an exception will be thrown.

Even if you don't use button-level validation this should be the cause for the exception. Did you call the parent method?

```
parent::validateForm($form, $form_state);

```

If you don't run the entity field validation in some way the exception is thrown.
> 7 votes

---
Tags: 8, entities
---


title: What is going on with Drupal Packagist?

text:
# Question
Title: What is going on with Drupal Packagist?
I was using

```
  "repositories": {
   "drupal": {
       "type": "composer",
       "url": "https://packagist.drupal-composer.org/"
   }
  },

```

in my composer.json file, but now it started saying that it can't load it and it is deprecated so go to https://www.drupal.org/node/2822344 instead. However, the info on there suggests changing it to point to https://packages.drupal.org/7 but this also doesn't seem to exist.

Can anyone shed some light?

# Answer
> 8 votes
https://packages.drupal.org/7 is the correct url, its just that drupal.org does not server any content under this url. Composer will call https://packages.drupal.org/7/packages.json

# Answer
> 2 votes
packagist.drupal-composer has been shut down

https://medium.com/@dcorbacho/packagist-drupal-composer-has-been-shut-down-9a6c47b9eaa4#.ylaxgo3n9

You must use the official Package Repository from Drupal.org, see https://www.drupal.org/docs/develop/using-composer/using-packagesdrupalorg

for Drupal 7 use https://packages.drupal.org/7

for Drupal 8 use https://packages.drupal.org/8

---
Tags: 7, composer
---


# Question
Title: PDOException when setting field value in node presave
I have a hook\_node\_presave implementation to set the value of a node field based on one of the user-entered values.

The code for it looks like this:

```
function er_pr_node_presave($node) {
  .....
  foreach($nameResult as $row) {
    $node->field_co_pi[LANGUAGE_NONE][$i]['value'] = intval($row->entity_id);
  }

  dpm($node);
}

```

With the dpm function I can see the values in the node, and the correct value is set to the field\_co\_pi field. However, the placeholder field doesn't get set when the insert query for that custom field is ran, resulting in a PDOException:

# Answer
> 1 votes
Sounds like you should be setting `target_id` instead:

```
foreach ($nameResult as $row) {
  $node->field_co_pi[LANGUAGE_NONE][$i]['target_id'] = intval($row->entity_id);
}

```

Note that not all fields have the same data column (such as '`value`'). Reference fields have `target_id` which holds the referenced entity id.

Aside from that, just make sure that it has a value before setting, or you will get the same error again.

You redacted other parts of the code, so, I can't see if you set `$i` or not. Are you incrementing that per loop with `$i++`? I just assumed it is a multivalued field since you are doing a foreach instead of setting `[0]` directly.

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


# Question
Title: How can I filter a view by "has translation"?
Filter a view by "Current user language" creates an empty div when missing translation. This is problematic because it breaks my layout. See the below image for my criteria.

# Answer
This is not tested but you could probably add the filter "Node translation: Child translation" to your view. Together with the current user language fiter this could work. Description is: "Content that is a translation of a source translation."
> 0 votes

# Answer
Well this can easily be solved by adding a "**No results behavior**" to be a global: text area, global:view or anything you have to say when it's empty.

just add whatever the HTML you want to display there. this can be a workaround for the problem that you are having.
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to change data type from varchar to text?
I'm trying to change the data type of column "mail" from table "simplenews\_subscriber" from varchar to text using hook\_update\_N but its not getting reflected.

```
/**
 * Implements hook_schema().
 */
function simplenews_schema() {
  $schema['simplenews_subscriber'] = array(
    'description' => 'Subscribers to {simplenews_category}. Many-to-many relation via {simplenews_subscription}',
    'fields' => array(
      'snid' => array(
        'description' => 'Primary key: Unique subscriber ID.',
        'type' => 'serial',
        'not null' => TRUE,
      ),
      'activated' => array(
        'description' => 'Boolean indicating the status of the subscription.',
        'type' => 'int',
        'size' => 'tiny',
        'not null' => TRUE,
        'default' => 0,
      ),
      'mail' => array(
        'description' => "The subscriber's email address.",
        'type' => 'varchar',
        'length' => 64,
        'not null' => TRUE,
        'default' => '',
      ),
      'uid' => array(
        'description' => 'The {users}.uid that has the same email address.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
      ),
      'language' => array(
        'type' => 'varchar',
        'length' => 12,
        'not null' => TRUE,
        'default' => '',
        'description' => 'Subscriber preferred language.',
      ),
      'timestamp' => array(
        'description' => 'UNIX timestamp of when the user is (un)subscribed.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'changes' => array(
        'description' => 'Contains the requested subscription changes',
        'type' => 'text',
        'serialize' => TRUE,
      ),
      'created' => array(
        'description' => 'UNIX timestamp of when the subscription record was added.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
    ),
    'primary key' => array('snid'),
    'indexes' => array(
      'mail' => array('mail'),
      'uid' => array('uid'),
    ),
    'foreign keys' => array(
      'uid' => array(
        'table' => 'users',
        'columns' => array('uid' => 'uid'),
      ),
    ),
  );

  return $schema;
}

```

Update Hook:

```
function MY_MODULE_update_7001() {
  db_drop_index('simplenews_subscriber', 'mail');
  db_change_field('simplenews_subscriber', 'mail', 'mail', array(
    'type' => 'text',
    'size' => 'medium',
    )
  );
}

```

Any help of this will be appreciated.

# Answer
You are missing recreating the index. Also you can use your schema changes:

```
$schema = drupal_get_schema_unprocessed('my_module', 'simplenews_subscriber');
db_change_field('simplenews_subscriber', 'mail', 'mail', $schema['simplenews_subscriber']['fields']['mail']);

```

Another thing you can do is test out altering the table manually just so you can see what errors are popping up.
> 2 votes

---
Tags: hooks, emails
---


title: Display node in view only

text:
# Question
Title: Display node in view only
I've created a views slideshow which uses a custom content type for each slide. However I want to prevent any user to access these nodes using the url itself like `.../node/1`. There seems to be a module from another stackoverflow post, but it's not supported by drupal 8.

# Answer
You'll want to use the Rabbit Hole module for this.

https://www.drupal.org/project/rabbit\_hole

You can block the view route for nodes by content type.
> 3 votes

---
Tags: 8
---


# Question
Title: Targeting a Specific Contact Form for Altering
I'm writing a custom module to format the email I receive from a user who fills out a contact form. I've created two contact forms and I want a separate email format for each form.

**Code**

I'm using this code as the basis of my module

But, I'm having trouble targeting a particular form. This is the code I'm trying to use, but it doesn't seem to be working:

```
    // further restrict mail_alter to machine name of a particular contact form
    if ($message['params']['contact_form']->id() ==
    'contact_message_contact_technical_support_form') {
    ...code to format message... (from linked article)
}
elseif ($message['params']['contact_form']->id() ==
'contact_message_feedback_form_form') {
    ...code to format message... (from linked article)
}

```

**Question**

Would someone please tell me how to properly id my forms so I can target them?

# Answer
> 0 votes
Thanks for your help everyone. The comments were helpful. I ended up using the var\_dump($message) as suggested and then whittled that down to what I needed. As one of you suggested the form name wasn't as long as I originally thought (and it WAS NOT the ID for the form). I think one ended up being 'feedback' and the other was, as you suggested 'contact\_technical\_support' or something like that.

The other issue I was having was that I was ignorantly naming my module with the word 'alter' in it which was overriding, or being overridden, by the alter hook it was using, I think.

At any rate, short answer is, my code basically works, but use var\_dump($message) to find the correct ID of the forms and don't use 'alter' in the module name.

---
Tags: 8, forms, emails
---


# Question
Title: How to detect when $form_state data have expired (and gotten deleted)?
***Problem:*** a user opens a multi-page form and fills out several sections – submitting each time – before returning hours later to finish the remaining parts, leaving their browser open (perhaps needing to look for additional documents or consult with a colleague). When they come back, they are still logged in, but the hard-coded 6-hour limit on storage of their `$form_state` data has elapsed, and the values they submitted in the previous sections of the form will not load on their next navigation-action since they have been deleted.

***Background:*** for multi-page forms, Drupal stores working `$form_state` information in the `cache_form` table until the final submission-step is complete, but its `"expire"` column is set so that deletion occurs 6 hours after creation. Even if this value is changed, sites featuring multi-page forms may still encounter the above situation, wherein an in-progress form is submitted after `$form_state` information has been discarded.

How can one detect when this circumstance arises (so the user can be informed of this or so that recovery-actions can be silently taken)?

***Note:*** Though you're welcome to post a Javascript answer if you have one, I won't assume Javascript is always available, and therefore do not consider answers which rely on Javascript to be robust.

# Answer
Although this arrangement is probably more complicated than it needs to be, here's how I was able to achieve it. I'd be happy to accept another answer if someone has a more elegant solution.

```
/**
 * Implements hook_form().
 */
function my_module_form($form, $form_state) {

    if (isset($form_state['storage']['elements_to_append'])) {
    // If other functions want us to add elements to the form:
        $elements = $form_state['storage']['elements_to_append'];
        foreach( $elements as $key => $element ) {
            $form[$key] = $element;
        }
    }

    $form['submit'] = array(
        '#type' => 'submit',
        '#submit' => array(
            'my_module_submit',
            'my_module_submit_safety',
            // ^ Depending on your requirements, you may wish to switch the
            // run-order of these two functions. Having my_module_submit_safety()
            // put first prevents subsequent actions in the case that $form_state
            // was lost since last navigation, but your users may lose more pages
            // of work before this check becomes effective; it's a tradeoff
            // either way unless you want to run the safety-check twice.
        ),
    );

    return $form;

} // my_module_form() OUT

/**
 * Implements hook_submit().
 */
function my_module_submit($form, &$form_state) {

    $form_state['rebuild'] = true;

    $form_state['storage']['elements_to_append']['navigated'] = array(
        '#type' => 'hidden',
        '#value' => 1,
    );

} // my_module_submit() OUT

/**
 * Implements hook_submit().
 */
function my_module_submit_safety($form, &$form_state) {

    $form_state_cid = '';
    if (isset($form_state['input']['form_build_id'])) {
        $form_state_cid = 'form_state_' . $form_state['input']['form_build_id'];
        // ^ This is effectively the same way the CID is built in @see
        // form_set_cache()
    }

    $statement = db_select('cache_form','cf');
    $statement->fields( 'cf', array('expire') );
    $statement->condition('cid', $form_state_cid);

    $navigated = isset($form_state['input']['navigated']);

    if ( $statement->execute()->fetchAssoc() === FALSE && $navigated ) {
        throw new Exception("The state-information for this form has expired.");
        // ^ I just place an exception here because recovery-actions for this
        // case are going to be system-dependent. If you know what those are for
        // your situation, they'd go here instead of this `throw` statement.
    }

} // my_module_submit_safety() OUT

```

Above, we use `$form_state['input']` rather than `$form_state['values']` since the latter will ***not*** include the results of the hidden field sent from the client's stale page in the case that `$form_state` information has been deleted. The strange dance of appending elements from a `'#submit'` step is done so that we don't run aground of the fact that `my_module_form()` is actually invoked ***twice*** (once immediately before `'#submit'` functions are called, and once after, each time with different values).

***To test whether it works:***

1. Load the form.
2. Navigate once.
3. Do: `mysql -u <userName> -D <databaseName> [-p<password>] -e\
"DELETE FROM <prefix>_cache_form";`.
4. Navigate again. You should see the message appear after this step.

---

**Note:** for security purposes, one might actually want to encrypt the hidden field's value (salting, timestamping, and including it no matter what), then reject the form outright if the value is found to be missing or adulterated in some way.
> 0 votes

---
Tags: hooks, forms
---


title: Create nodes in a installation profile

text:
# Question
Title: Create nodes in a installation profile
How can I create nodes in a installation profile? Can this be done in the .info file, or does it have to be done in the .install file?

# Answer
When a profile needs to create something to make it accessible once the profile is installed (e.g. blocks, content types, fields), it does it in its `hook_install()` implementation. For example, the standard profile creates content types, fields, and input formats in its `standard_install()`; it also enables some of the standard blocks, and it set the Seven theme as administrative theme.

Drupal doesn't use any directives in the .info file to automatically create nodes, but a profile could implement code to parse extra directives in a .info file, for example in `hook_modules_installed()`.

I would rather go with implementing `hook_install()`. I may consider using directives in the .info file if there is a module handling them and I am writing more than three profiles for which being able to change the nodes added from the profile is much important. I understand that avoiding to keep changing the code make less probable to introduce errors; since I know the code to use to create nodes, and the task is relatively simple, using directives in the .info file doesn't simplify much the code I would write for a profile.
I would take more in consideration a module that would back-port to Drupal 7 the code that in Drupal 8 handles the configuration files used to create content types, and fields for those content types, using YAML files. For example, this is the core/modules/forum/config/optional/node.type.forum.yml file that in Drupal 8.3 allows the Forum module to create its content type.

```
langcode: en
status: true
dependencies:
  enforced:
    module:
      - forum
name: 'Forum topic'
type: forum
description: 'A <em>forum topic</em> starts a new discussion thread within a forum.'
help: ''
new_revision: false
preview_mode: 1
display_submitted: true

```
> 2 votes

---
Tags: 7
---


# Question
Title: set multiple taxonomy values programmatically
I have a view that has a "Has taxonomy term ID" contextual filter and also a nid contextual filter.

I execute this view programmatically, but I need to pass also multiple values for the taxonomy contextual filter.

I tried this:

```
$view->set_arguments(array($tid, $nid));
$view->execute();

```

and it works only if $tid is only a number.

I tried to put more than one tid using "+", but it doesn't work. (example 3+5+8)

Any idea on how I can set a multiple taxonomy argument programmatically? thank you in advance

---

**I found a solution, but I don't like it**. I removed the filter from contextual filter and I added an exposed filter for the same field. Then I changed the code in this way:

```
$view->set_arguments(array($nid));
$view->exposed_input['field_myfield_tid'] = $tid;  //note that $tid is an array of tid
$view->execute();

```

# Answer
> 0 votes
You could also implement the "hook\_views\_pre\_view" function in order to alter the contextual filter arguments of your view and display. In order to add multiple taxonomy values for the same argument, you can change the $args\[0\] element from the $args variable of the hook.
For example: $args\[0\] = '22+14+64';
Remember to check the "Allow multiple values" option of the contextual filter.

Take into account that altering contextual filter arguments inside the previous hook may produce troubles when using a views exposed form. Specifically, the form "action" attribute may have a wrong URL. If that issue appears, you can solve it by implementing the "hook\_form\_views\_exposed\_form\_alter" function and changing the $form\['#action'\] element with the correct URL.

# Answer
> 0 votes
For achieving this requirement there are several methods , the first one is in your Taxonomy Contextual filter enable **Specify validation criteria** and put **Filter value type** on `Term IDs separated by , or +`,

with this settings the following code will works for you.

```
   $tid = "3,4,5"; // or  $tid = "3+4+5";
   $view->set_arguments(array($tid, $nid)); $view->execute();

```

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


# Question
Title: How can I get the file id if I use the file_save_data function?
I will be adding new media files in D8 programmatically, how do I determine what the fid should be for each one? also how do i put the actual file contents into the media type?
this is my code

```
$file_name=$file_info['file_name'];
  $file = file_get_contents($fullpath."/".$file_name); // string
 $filesaved = file_save_data($file, 'public://'.$file_directory_name."/".$file_info['file_name')',FILE_EXISTS_REPLACE);
  $fid = ???;
  $static_media = Media::create([
      'bundle' => 'document',
      'uid' => '1',
      'langcode' => Language::LANGCODE_DEFAULT,
      'status' => Media::PUBLISHED,
      'your_image_field_name_here' => [
        'target_id' => $fid,
        'alt' => t('foo'),
        'title' => t('bar'),
      ],
    ]);
    $static_media->save();

```

# Answer
Try

```
$filesaved = file_save_data($file, 'public://'.$file_directory_name."/".$file_info['file_name']), 'FILE_EXISTS_REPLACE');
$fid = $filesaved->id;

```

**file-\>id** is the id if file that you can use it as entity reference target\_id (I mean file field).

and a good example how save and attach file to Node

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

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

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

```

What if the file is already present in your local file system and you want to attach it to an existing node? Here's an example for that too:

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

// Create file object from a locally copied file.
$uri  = file_unmanaged_copy('public://source.jpg', 'public://destination.jpg', FILE_EXISTS_REPLACE);
$file = File::Create([
  'uri' => $uri,
]);
$file->save();

// Load existing node and attach file.
$node = Node::load(1);
$node->field_image->setValue([
  'target_id' => $file->id(),
]);
$node->save();

```

And lastly, what if you want to stick a placeholder file to a node? Thanks to Drupal 8, this is too easy:

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

$node = Node::create([
  'type'  => 'article',
  'title' => 'Generated image test',
]);
$node->field_image->generateSampleItems();
$node->save();

```
> 13 votes

# Answer
file\_save\_data returns a file object on a successful save. That object must be an instance of FileInterface.

As such, then you can just do:

`$fid = $filesaved->id();`
> 1 votes

# Answer
The function `file_save_data()` returns a file entity. So i suppose you need `$filesaved->fid->value`. And `$filesaved->id()` returns the same result.
> 1 votes

---
Tags: 8, entities, files
---


title: Module dependent on extension

text:
# Question
Title: Module dependent on extension
I am developing a small module which is dependent on the `php_ldap` extension. I would like to make sure that this extension is enabled before activating the module and if it is not display a message telling the user that the ldap extension needs to be installed and enabled. I have tried using `hook_enabled()` for this purpose, but since this hook is fired after the module is enabled it will not work as expected:

```
function example_enable() {
  if (!function_exists('ldap_connect')) {
    // Here I would like to halt the activation of the module
    drupal_set_message(t('The Ldap extension needs to be enabled.'), 'error');
  }
}

```

I am not sure how to stop the user from enabling a module if a specific extension is not installed or loaded. I was thinking about using `hook_install()`, but I am not sure that would work either.

# Answer
> 1 votes
The best solution for you is using hook\_requirements .

```
function hook_requirements($phase){
       if ($phase =="install"){
         $requirements['php'] = array(
           'title' => 'LDAP extension',
           'value' => "LDAP",
          );
 if (function_exists('ldap_connect')) {
      $requirements['php']['description'] = 'YOU NEED TO install LADAP';
      $requirements['php']['severity'] = REQUIREMENT_ERROR;
     }
    }
return $requirements;

}

```

and another tricky solution (but **NOT RECOMMENDED**) is : Create Another module for `php_ldap` extension (let name it B), and on that module on hook\_enable check the `php_ldap` extension is exists if not, uninstall module(uninstall B module) , and set your main module dependent on first one(I mean Module B) . with this method you will be sure if the extension Available Module B can be installed and consequence Your main Module.

Something like following snippet could help you to implement that

```
function MODULEB_enable() {
  if (!function_exists('ldap_connect')) {
        module_disable(array('MODULEB'));
       drupal_uninstall_modules(array('MODULEB'));
       drupal_set_message(t('The Ldap extension needs to be enabled.'), 'error');
  }
}

```

---
Tags: 7, installation
---


# Question
Title: How to validate a value against an existing field
I'm doing some custom stuff with programmatically saving fields with EMW:

```
$wrapper->my_field->set('my_value');

```

Problem is, this doesn't validate before trying to save the field. How can I validate the value against the field before trying to save it?

# Answer
install entity\_validator module .

> Unlike Drupal 8, Drupal 7 has not validation for entity objects what so ever. One of your modules can create a node object without any title or a language and you don't want that.

for drupal 8 Use Entity Validation before save your fields.

as a example

```
 $violations = $typed_data->validate();
    $definition = DataDefinition::create('integer')
      ->addConstraint('Range', ['min' => 5]);
    $typed_data = \Drupal::typedDataManager()->create($definition, 10);
  if ($violations->count() == 0) { // this means there is not any validation error
     // save Entity
  }

```
> 0 votes

---
Tags: 7, forms
---


# Question
Title: How to make friends ajax with dynamically created links?
I created leaflet map, when you hover the marker in popup window is a reference to the content.

I wrote module that loads ajax content in the custom region. For dynamic links added class **use-ajax**, but Drupal does not process them as I needed. I check and found that static links with class **use-ajax** have additional class **ajax-processing**. My dynamic link looks like:

```
<a id="jslink" class="use-ajax" href="nojs/problem/83">засорение реки</a>

```

Static link looks like:

```
<a class="use-ajax ajax-processed" href="nojs/node/231">node</a>

```

As I understand Ajax Drupal does not work with dynamic links. I found issue in what asks in what need to change the href attribute of a link and make the ajax call to the new url. Change 'href' attribute in AJAX enabled links Wrote JS code but it doesn't work for me.

```
(function ($) {
  Drupal.behaviors.test_module = {
    attach: function (context, settings) {
        $("#jslink").click(function(){
            var href = $("#jslink").attr("href");
            Drupal.ajax['jslink'].options.url = href;

        });
    }
  };
})(jQuery);

```

Is it possible to somehow make Drupal to work with dynamic links? What am I doing wrong?

# Answer
I found solution, for loading balloons I use module IP Geolocation Views & Maps it has js file **ip\_geoloc\_leaflet\_goto\_content\_on\_click.js** where I add line **Drupal.attachBehaviors();** Now it works as designed.

```
jQuery(document).bind('leaflet.feature', function(event, marker, feature) {
  // marker is the feature just added to the map, it could be a polygon too.
  // feature.feature_id is the node ID, as set by ip_geoloc_plugin_style_leaflet.inc
  // Need to set this up for code below.
  // The same code is used for cross-highlighting. See ip_geoloc_leaflet_sync_content.js
  if (feature.feature_id) {
    marker.feature_id = feature.feature_id;
  }
});

jQuery(document).bind('leaflet.map', function(event, map, lMap) {

  if (map.settings.gotoContentOnClick) {
    for (var leaflet_id in lMap._layers) {
      lMap._layers[leaflet_id].on('click', function(e) {
        var id = e.target ? e.target.feature_id : null;
        if (!id && e.layer) id = e.layer.feature_id;
        if (id) {
            //document.location.href = Drupal.settings.basePath + 'node/' + id;
            document.location.href = Drupal.settings.basePath + 'load_node/' + id;
        }
      });
    }
  }
  if (map.settings.openBalloonsOnHover) {
    for (var leaflet_id in lMap._layers) {
      lMap._layers[leaflet_id].on('mouseover', function(e) {
        this.openPopup();
         Drupal.attachBehaviors(); <<<<--------ADDED LINE
      });
    }
  }

});

```
> 1 votes

---
Tags: 7, ajax, navigation
---


# Question
Title: Monthly change images directory Drupal 8
I am working on a news portal site. We have a lot of posts and also a lot of pictures are saved daily.

At the moment, the size of `/sites/default/files` directory is around 6GB and contains almost 23k files. And that is a problem.

What I want is to have directory for every month, for example:

```
/sites/default/files/3-17
/sites/default/files/4-17
...

```

Does anybody know how to do this?
Also, is there a way to keep live posts working?

# Answer
> 0 votes
I solved this problem using this module: https://www.drupal.org/project/filefield\_paths You can change path for every field type and use tokens like /\[date:custom:Y\]/\[date:custom:m\] to achive what I wanted...

---
Tags: 7, files, media
---


# Question
Title: "Unable to send e-mail" Error in drupal 7
Just now I migrated my website to server machine. I noticed that website is not able to send any email. It is showing "Unable to send e-mail" error.

Below is the screenshot of the error-

I can see some directory permissions error in status report at admin/reports/status. Are these related to each other?

# Answer
> 4 votes
It's very likely that your new server does not allow mail to be sent from the web service. This could be because it blocks the SMTP port, or because it doesn't allow PHP to use mail(). You should be able to contact their tech support to ask. If not, you can try uploading your own PHP script that uses the mail() function and see what errors it gives you.

IMO, this is a good thing... web servers shouldn't be sending emails for a variety of reasons.

I would recommend using something like this: https://drupal.org/project/smtp

It will let you send email through a real email account, of course you'll have to make sure there's not a block on the port it uses.

# Answer
> 1 votes
Following settings worked for me on windows.

Download and enable SMTP Authentication Support module

If You use Gmail to set up STMP follow these steps:

SMTP server: smtp.gmail.com

SMTP port: 465

Use encrypted protocol:Use SSL

SMTP Authentication -- Your gmail User Name and password

Leave the other options by Default

# Answer
> 0 votes
Use SMTP module.

Do not forget to check **Access for less secure apps**. It should be Access for less secure apps enabled.

https://www.google.com/settings/security/lesssecureapps

---
Tags: emails
---


# Question
Title: How to apply css to all pages in custom module
I have created one custom module in drupal-7. I want to apply same css to all pages belonging to that module.

I am able to apply css to one page by using **drupal\_add\_css()** but not able to do for all pages.

# Answer
> 15 votes
In module's info file, add following line:

```
stylesheets[all][] = folder/module.css

```

Substitute `folder` with a name of subfolder within your module you keep your CSS files in (or remove it). Repeat for all CSS files you need.

More about info files in the manual on Drupal.org.

# Answer
> 0 votes
1- Place style.css in my\_module folder

2- in my\_modulefolder/my\_module.module

```
function my_module_preprocess(&$vars, $hook) {
  if($hook == 'page')
   drupal_add_css(drupal_get_path('module', 'my_module') .'/style.css');
}

```

---
Tags: 7, theming
---


# Question
Title: How to get a custom field label in a specific language?
In order to get the label of a field I just do :

```
$fii = field_info_instance('node', 'field_app_area', 'products');
$label = $fii['label'];

```

But it returns the label in the original language of the field, not the current user language.

I have seen some code here to get the translated label from the $content variable of a node template, but I don't have the template variables available.

So my question is either : how do I get the label translation or how do I get the $content (or similar) variable available without being on a template.

# Answer
Turns out that using t(), doesn't work for translated field labels.

To get the translated field label text (in the current language), just use the `i18n_field_translate_property` function

```
  $field_instance = field_info_instance('node', 'field_application_area', 'products');
  $label = i18n_field_translate_property($field_instance, 'label');

```

Or, for a specific language :

```
  $label = i18n_field_translate_property($field_instance, 'label', 'fr');

```

Found on this related answer.
> 1 votes

# Answer
Try this

```
$fii = field_info_instance('node', 'field_app_area', 'products');
$label = t($fii['label']);

```

and according to this if you want to get on specified language try

```
$fii = field_info_instance('node', 'field_app_area', 'products');
$en_label = t($fii['label']);
$fr_label = t('language', array(), array('langcode' => 'fr'));

```
> 0 votes

---
Tags: 7, entities, i18n-l10n
---


# Question
Title: Disabling the site cache brakes the page output
I have just finished my development and uploaded a website to a hosting. But unfortunately I've got another weird problem..

If I disable the site cache another template is used for rendering a view node. I cannot catch the error. The problem is that in case I disable all caches, this problem appears. But when I try to debug the problem it disappears)) So I am not able to find what is wrong with it ? Sometimes it appears after commenting these lines

```
#$settings['cache']['bins']['render'] = 'cache.backend.null';
#$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

```

Sometimes it appears after disabling `Twig Debug`

The problem that it swaps view node templates between two views. For exampl I have a view for rendering teasers, and another view is for rendering a node preview. So it swaps them. I really cannot understand what is going on and what is the problem.

Please suggest what can cause such weird behavior ?

Thanks

**NOTE 1**

The same problem occurs locally when I disable caches.

**NOTE 2**

I've found the weird part of debug output

```
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'views_view_unformatted__latest_works' -->
<!-- FILE NAME SUGGESTIONS:
   x views-view-unformatted--latest-works.html.twig
   x views-view-unformatted--latest-works.html.twig
   * views-view-unformatted.html.twig
-->

```

The same template is suggested twice

**NOTE 3**

I've noticed another weird behavior

```
#$settings['cache']['bins']['render'] = 'cache.backend.null';
#$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

```

Comment these lines the view on the main page doesn't work, outputs nodes with template from another page. Go to menu, Devel -\> Clear Cache. Now view on the main page works correctly, but on the other page output nodes using template from the main page.

And these behavior repeats

**FINALLY**

The problem is caused by the render cache I guess. To get this error I have to do following steps :

1. Consider there are two pages the `front` and the `category` page.
2. If current page is displayed incorrectly, then stay on this page open admin panel, clear the site cache, refresh the page - everything is rendered correctly.
3. Go to the category page, now it rendered incorrectly and nodes that are also present on the `front` page rendered incorrectly using the `front` page template.
4. If I clear cache again and refresh the category page it will work, but the front page will be rendered using the view template from the category page.

I hope I've described the problem clearly. It seems that the problem is similar to that one https://www.drupal.org/node/2359955

# Answer
It seems that I've found a temporary solution to this problem.

Edit `core/includes/entity.inc`

Comment reset check lines.

```
function entity_view(EntityInterface $entity, $view_mode, $langcode = NULL, $reset = FALSE) {
  $render_controller = \Drupal::entityManager()->getViewBuilder($entity->getEntityTypeId());
  //if ($reset) {
    $render_controller->resetCache([$entity]);
  //}
  return $render_controller->view($entity, $view_mode, $langcode);
}

```

If someone has the same problem, please let me know whether the solution works.
> 0 votes

---
Tags: views, theming, 8, caching, media
---


# Question
Title: Node paths come through empty unless view result is programmatically changed
Task: to retrieve a list of nodes in JSON format including their aliases generated by Pathauto module. The configuration of my view is this:

Problem: path fields come empty - they won't include original Drupal path to it nor an alias generated by Pathauto:

The current solution I've got is to programmatically amend view's result in the following way:

```
function my_custom_views_pre_render(\Drupal\views\ViewExecutable $view) {
foreach($view->result as $value) {
    $url = \Drupal\Core\Url::fromRoute('entity.node.canonical', ['node' => $value->_entity->get('nid')->value], ['absolute' => false]);
    $url = $url->toString();
    $value->_entity->set('path', $url);
}

```

}

And that populates the path fields:

I'd like to know if there is a way to avoid the hook and make views return node paths without it, or is it normal Drupal Views behaviour?

P.s.: If I chose "Fields" instead of "Entity" in the Format section in the Views UI, it does return me the correct paths. However I want to get the full entity due to extensive data it consists for later consumption. Thanks!

# Answer
Put **Show** on field, then remove "title" field and add **Path** field

and if you want result be Absolute Url on **Rewrite** secion Check *Use absolute link (begins with "http://")*
> 0 votes

---
Tags: views, 8
---


# Question
Title: Getting a translated country name from an address field
I have an address field from which I'm getting a country code and then, using the `address.country_repository` service, checking the country's name.

```
$full_country_list = \Drupal::service('address.country_repository')->getList();
$country_code = $user->field_nationality->first()->get("country_code")->getValue();
$result['nationality'] = t($full_country_list[$country_code], [], ['langcode'=>$user->get('langcode')->value]);

```

This repository returns a list with the country names translated in Drupal's default language (in my case, portuguese), but I'm trying to `t()`-function it to translate the string into other languages.

The `t()` function doesn't cut it, even if I pass the `langcode` option.

How can I get a translated version of the list so that I don't have to translate the string with `t()`?

# Answer
The country name in the country list is already a translatable markup object. It's not possible to add new options to it. So your idea to translate the country name again, this time with a specific `langcode` in options, is right. But you have to get the untranslated string if you want to translate it again

```
t($full_country_list[$country_code]->getUntranslatedString(), [], ['langcode' => 'de'])

```

because how you do it you get the translated string when running the code in a non english language context and translating from a non english language is not supported.

---

Edit: this answer is valid for the core country list

```
$full_country_list = \Drupal::service('country_manager')->getList();

```

there are probably other versions in contrib, see comment from @Berdir.
> 1 votes

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


# Question
Title: Form Ajax not working when rendered from Ajax callback
I am trying to load a Drupal form through an AJAX callback when the user selects an option from a select list. The code used to generate this form as follows:

```
public function buildForm(array $form, FormStateInterface $form_state) {
    $form['dashboard_list'] = array(
    '#title' => t('Select Dashboard:'),
    '#type' => 'select',
    '#ajax' => array(
        'callback' => 'Drupal\dashboard\Controller\DashboardController::OnPanelSwitch',
        'effect' => 'fade',
        'event' => 'change',
        'progress' => array(
            'type' => 'throbber',
            'message' => NULL,
            ),
        ),

   );
return $form;
}

```

Inside of OnPanelSwitch(), which is called when the user selects an option from the list. I am using the renderer service to get the form's HTML and then inserting the form into a div.

```
 public static function OnPanelSwitch(array &$form, FormStateInterface $form_state) {
    $ajax_response = new AjaxResponse();

    $AddChartForm = \Drupal::formBuilder()->getForm('Drupal\dashboard\Form\AddChartForm');
$AddChartFormHTML =\Drupal::service('renderer')->render($AddChartForm);

    $ajax_response->addCommand(new HtmlCommand('#formarea', $AddChartFormHTML));

    return $ajax_response;

```

}

This HTML is then inserted into a DIV in the page. The form being loaded via AJAX is built in the following manner and contains a single select list:

```
public function buildForm(array $form, FormStateInterface $form_state) {
   $form['query_type'] = array(
      '#title' => t('Query Type'),
      '#title_display' => 'invisible',
      '#type' => 'select',
      '#options' => array(t('Chart'), t('Table')),
      '#prefix' => '<div class="floatLeft"',
      '#suffix' => '</div>',
      '#ajax' => array(
          'callback' => 'Drupal\dashboard\Controller\DashboardController::OnQueryFieldChange',
          'effect' => 'fade',
          'event' => 'change',
          'progress' => array(
              'type' => NULL,
              'message' => NULL,
              ),
          ),

  );
return $form
}

```

The OnQueryFieldChange() callback is not being called when this form is being loaded via the initial AJAX call. If I load this form without AJAX through the twig template everything works correctly. So it seems to be an issue of the form being loaded via AJAX.

From my research it seems like I might have todo something with Drupal Behaviors to enable AJAX for this form? Any guidance would be really helpful.

# Answer
> 2 votes
I have fixed the issue I was having by just returning the render array of the form rather than trying to get the form's HTML. So my AJAX callback function now looks something like this:

```
public static function OnPanelSwitch(array &$form, FormStateInterface $form_state) {

   $ajax_response = new AjaxResponse();

   $AddChartForm = \Drupal::formBuilder()->getForm('Drupal\dashboard\Form\AddChartForm');

   $ajax_response->addCommand(new HtmlCommand('#formarea', $AddChartForm));

return $ajax_response;

```

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