# Question
Title: Don't load jQuery, even when modules have it as a dependancy
How can I stop jQuery being loaded in Drupal 8, even when modules which use jQuery are on the page?

I have an existing style guide which I'm pulling into a Drupal 8 site. I already have all the JavaScript including jQuery as part of the style guide and I want to keep this separate from Drupal.

For anonymous users everything works fine. However admin users have access to the admin toolbar. This loads in Drupal's own version of jQuery which conflicts with the style guide's and causes the admin toolbar to break.

I tried adding this to my theme's libraries file:

```
core/jquery: false
core/jquery.once: false
core/jqueryui: false

```

Inspecting the page it did appear to block some jQuery references but not all of them:

However when I remove my entries from my theme's libraries file I can see that in fact all of the same jQuery files are being loaded, so I don't actually think it achieves anything.

I know that normally one would not load in jQuery themselves and just use Drupal's version, but the style guide requires the latest version and is also consumed by other applications so I cant change it very much.

# Answer
> 3 votes
You should be able to alter the JavaScript files include on the page with an implementation of `hook_js_alter()`.

# Answer
> 1 votes
In THEMENAME.theme:

```
<?php

function THEMENAME_js_alter(&$javascript, \Drupal\Core\Asset\AttachedAssetsInterface $assets) {
  $javascript['core/assets/vendor/jquery/jquery.min.js']['data'] = '';
  $javascript['core/assets/vendor/jquery.ui/ui/core-min.js']['data'] = '';
  $javascript['core/assets/vendor/jquery.ui/ui/widget-min.js']['data'] = '';
  $javascript['core/assets/vendor/jquery-form/jquery.form.min.js']['data'] = '';
  $javascript['core/assets/vendor/jquery.cookie/jquery.cookie.min.js']['data'] = '';
  $javascript['core/assets/vendor/jquery.ui/ui/mouse-min.js']['data'] = '';
  $javascript['core/assets/vendor/jquery.ui/ui/draggable-min.js']['data'] = '';
  $javascript['core/assets/vendor/jquery.ui/ui/resizable-min.js']['data'] = '';
  $javascript['core/assets/vendor/jquery.ui/ui/dialog-min.js']['data'] = '';
  $javascript['core/misc/dialog/dialog.jquery-ui.js']['data'] = '';
  $javascript['core/assets/vendor/jquery-joyride/jquery.joyride-2.1.min.js']['data'] = '';
}

```

---
Tags: javascript
---


# Question
Title: Node specific template with custom html header
From time to time I have pages within the Drupal architecture that I don't want to use the standard page.tpl.php.tpl and html.tpl.php. I want to create a template for specific nodes that uses a unique one for each. It cannot have any drupal code in it. Is this possible?

# Answer
This applies to Drupal 7...

## page.tpl.php

Make a copy of `page.tpl.php` from your active theme's directory e.g

```
/sites/all/themes/your_theme/page.tpl.php

```

If the theme does not have `page.tpl.php` file then make a copy of Drupal's default version at

```
/modules/system/page.tpl.php

```

Rename your copied file in your theme folder with one of the following naming convention. Use this format for a node content type (example uses a custom content type called 'news'):

```
page--node--news.tpl.php

```

Or for a specific node use the ID number (example uses node ID of 12):

```
page--node--12.tpl.php

```

## html.tpl.php

The same applies for `html.tpl.php` For a specific content type use:

```
html--node--news.tpl.php

```

For a specific node

```
html--node--12.tpl.php

```

These will take precedence over the generic `html.tpl.php` or `page.tpl.php` if the ID or content type matches.
> 1 votes

# Answer
You should use theme\_debug if you are dealing with Drupal 7.33 or newer. That will give you all the information you need in the html source code, for the active templates used in your page and - most importantly - for suggested template files that would allow you to override as you see fit.

And yes, you can have a tpl.php file without any php code in it, be it Drupal specific or not.

Good luck!
> 0 votes

---
Tags: theming, nodes
---


# Question
Title: How to edit how Commerce outputs the Billing and Shipping information in the checkout review table?
Drupal Commerce on the Review page of the checkout process (e.g. `checkout/4/review`) by default outputs billing and shipping information above each other in a table, with each line as a different `<tr>` row containing one table cell:

I'm trying to re-theme this such that it's responsive and has the two addresses side-by-side on wider breakpoints. I know how to code that HTML, my problem is, how to get my HTML into the Commerce page template?

* There's no corresponding tpl file I can find anywhere in the Commerce module, and other answers linked below seem to confirm there isn't one
* I can't find a corresponding View to edit
* I've read theming checkout pages in Drupal commerce, where an answer suggests creating a file `page--checkout--review.tpl.php` \- but no such file exists already, and I don't want to recreate the template from scratch and potentially miss some important subtlety from the logic of the original, I want to read, understand and then *edit* the original.
* The answer to Customize drupal commerce checkout page doesn't offer the HTML control I need, likewise How to theme checkout completion page in Drupal Commerce. I know I can edit the form array using hooks, but I can't use hooks to make the fine adjustments to the HTML output that I need, removing them from the table to make them responsive.
* I wrote the answer to Customize commerce cart form page, which uses a custom module to allow the table to be editted in Views - but this only works for the cart, not checkout

How can I edit (not re-write from scratch) the HTML of the checkout review table?

# Answer
At time of writing, this isn't a viable solution, but I'm posting it because it might become one, one day.

## Commerce Responsive UI module

There's a massive long 5-year-old issue matching my problems theming Commerce checkout in the Commerce issues queue. The "fix" was the creation of a module, Commerce Responsive UI, that aims to modernise the markup of the checkout (and other) pages and make them themable. It sounds like exactly what I'm looking for.

Problem is, there's no stable release, no release at all since November 2015, and it appears to have some serious unresolved issues, like breaking normal cart/checkout page paths. This might become a good answer to the question, but right now it's an unfinished work in progress.
> 1 votes

---
Tags: theming, commerce
---


# Question
Title: How to change widget's icons in the service-links module?
I am using the Service links module in Drupal 7.

I tried to change the icons of the links, but only the "general services" links are changed. The "widget services" staying like the original. I saw that is because the icon is coming from an URL and not from a picture on the computer.

How can I change the widget icon?

Is there a patch or an option on the module?

# Answer
> 1 votes
CSS solution for position: for services widgets (FB, pinterest, linkedin) you can not change images, for General Services (twitter, G+) you can upload your own images.

Here is my CSS code and links appear centered inline.

```
/* services share links */`
.service-links ul li {
 text-decoration: none;
 display: inline;
 overflow: hidden;
 list-style: none;
 padding-right: 10px;
 vertical-align: baseline;
 float: left;
 }

.service-links li {
 display:inline;
 vertical-align: bottom;
 position: relative;
 }
.service-links .service-links-linkedin-share-button {
top: 5px;
}

.service-links .service-links-facebook-share {
bottom: 5px;
}

```

# Answer
> 0 votes
The ideal way would be if the module allowed us to insert our own images to the site, but this was requested previously and Closed (won't fix) https://www.drupal.org/node/1895012#comment-10310687

I did however managed to find a workaround for this by inserting my own custom images using CSS, and adding the new images to my theme. I +1 this as a feature request, as hiding the existing images with 'display:none' is certainly not ideal.

You can see a live example of this code in action at http://www.kindconsumer.com in the 'Share' section at the bottom.

\`.service-links a { width: 30px; height: 30px; color: #fff; display: block; overflow: hidden; float: left; padding-right: 5px; }

.service-links img { display: none; }

.service-links-facebook { background: url(../img/facebook.png) 0 0 no-repeat transparent; }

.service-links-linkedin { background: url(../img/linkedin.png) 0 0 no-repeat transparent; }

.service-links-twitter { background: url(../img/twitter.png) 0 0 no-repeat transparent; }\`

---
Tags: 7
---


# Question
Title: Create a Redirect for a page if its unpublished / deleted
We have an issue when a page is deleted/ unpublished someone forgets to add a redirect.

Now what i am looking for is when someone is about to unpublished a page or delete it, we pop something up that will offer a user a list of pages and they can select which one it should go to.

Any ideas where I should start with this and what hooks I could use.

# Answer
> 2 votes
There is a module that does much of what you describe: Save Redirect on Delete. It will push the user to a predefined page and you could put popular items on that destination page.

If you want the recommended content to be customized for the page they tried to reach you'll almost certainly want to build something custom. This module would probably give you a starting point, but in addition to what it provides you'd also need to preserve some kind of taxonomy reference (or similar) information to be able to provide something sensible.

# Answer
> 0 votes
Another option might be to use Rabbit Hole and instead of deleting, just change it to a redirect:

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

While this may not be an exact answer/solution to the original post, it may serve as an inbetween to make it all work.

---
Tags: 7
---


# Question
Title: How to make select option works like a button?
I have created a contact form by using webform module, in that I have added one component as `reset` and the type is `select options`.

My requirement is when I choose this reset option from that dropdown and submitted the form, I want to reset my form. I have no idea how can I achieve this. I tried following but not worked, please help me regarding this.

```
function test_form_alter(&$form, &$form_state, $form_id) {
   if ($form_id == 'webform_client_form_111') {
    $form['submitted']['reset']['#option'] = 'test_reset';
  }
}
function test_reset(&$form, &$form_state){
  $form_state['rebuild'] = FALSE;
}

```

# Answer
> 0 votes
You can write a simple jQuery script for achieving this.

```
$('select').on('change', function() {     // you can refine this with your field id.
  if( this.value == 'reset' ) {           // Replace value for your 'reset' option.
    $('#yourid').find('form')[0].reset(); // Replace id here
  }
})

```

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


# Question
Title: Attach js to the module using libraries with inline property
I have a module in which I have created a libraries.yml file and have attached it to the module:

```
$var[$delta] = array(
  '#theme' => 'example_theme',
  '#attached' => array(
    'library' => array(
      "example_theme/example-styling",
    ),
  ),
  '#file' => $output,
);

```

I want to provide a variable to the js defined in libraries.yml

How can I achieve this?

```
drupal_add_js('example = "' . $example . '";', 'inline')

```

# Answer
drupal\_add\_js() has been deprecated, and you cannot use it anymore.

Pass the inline variables with the `#attached` property as :

```
$var[$delta]['#attached']['drupalSettings']['yourmodule']['example'] = $example;

```

And then access the `example` variable in the JS file as

```
drupalSettings.yourmodule.example

```

*Note:* I have not tried this code, but I think it should work.
> 2 votes

# Answer
This can be done using `#attached` in Drupal 8. Try the following code:

```
return array(
  '#theme' => 'your_module_theme_id',
  '#someVariable' => $some_variable,
  '#attached' => array(
    'drupalSettings' => array(
      'your_module_settings' => array(
        'foo' => 'bar',
        'baz' => 'bee',
      )
    ),
    'library' =>  array(
      'your_module/library_name'
    ),
  ),
);

```

Here, `your_module/library_name` will be able to access this `drupalSettings` JavaScript via `drupalSettings.your_module_settings` and more granular `drupalSettings.your_module_settings.foo` etc.

For further reading you can look at the below links https://www.drupal.org/node/2269515 https://www.drupal.org/node/2274843

I've used this in one of my module. This module Visualization API has the same as well. Might be good as example.
> 2 votes

---
Tags: forms, 8
---


title: Anonymous user cache issue

text:
# Question
Title: Anonymous user cache issue
We're having a problem with caching that is affecting anonymous users.

We have a form in a block that when the user fills out the form, they are able to download a PDF. We hide the block on pages where we don't want this PDF download form to appear. Ideally the block is hidden, if no PDF is available for a particular page, but the block is being cached and displayed regardless the of the actual page. This only is a problem for anonymous users. Logged in users do not have the problem of the seemingly cached PDF download blocks appearing on the wrong pages.

For example after clearing the cache, somebody first visits page A with a PDF available, then that PDF download form block is being cached and the cached version is also displayed for page B which does not have a PDF download.

Same vice versa, if you visit Page B first, than the block is being cached with it's attribute display:none, and it will not be displayed for Page A either Basically, we need the visibility to be re-evaluated on each page load.

We're fairly certain it's a cache issue as when we inspect the live rendered code we can see the block IDs being mixed up on the page. For example: we'll see a body-tag includes a class "node-164", it's node 164 and the Download the PDF includes a class "PDF-node-205", so it's the cached version for node 205, it also includes the filename as a CSS classname, it's clearly the block for a different page node.

We've tried disabling the page cache, dynamic cache, and the twig cache and we're still having the same problem. And again it is only happens for anonymous users, logged in users do not see these cached blocks appearing on the wrong pages.

Has anyone run into this or know of another caching method that Drupal may be using that we're not aware of?

# Answer
> 2 votes
If I understand correctly, it is okay for the block to be cached, but each path/URL can have its own "version" of the form, right? In that case, you need to inform Drupal that this block changes depending on the current path/URL. Drupal 8 introduced the concept of "cache contexts" to do that. The cache context defines the external factors by which the return value can vary.

Now that you know this, you'll notice that this question is pretty similar to yours.

As documented in the change record, blocks can define their cache context by overriding the `getCacheContexts()` method from the BlockCase class. Overriding that method would probably look like this in your block class:

```
/**
 * {@inheritdoc}
 */
public function getCacheContexts() {
  return Cache::mergeContexts(parent::getCacheContexts(), ['url.path']);
}

```

As you can see I'm using the `url.path` context here. A list of contexts provided by Drupal core can be found in the documentation.

# Answer
> 0 votes
The quickest and most effective way in this case is to disable caching for the block by setting max-age to zero:

```
$build['#cache']['max-age'] = 0;

```

There is no point in defining a cache context in this case, because the cached blocks for every url will fill up the cache bin, but will never be used.

Anonymous users are served from the page cache, which will cache for every url a different page by default.

Your debugging efforts were not successful, because you were not able to switch off block caching. It is not enough to uninstall the caching modules. Core can cache blocks without this. You have to use a null cache backend.

---
Tags: 8, users, caching, files
---


title: How to use views exposed filters in d8?

text:
# Question
Title: How to use views exposed filters in d8?
I have a view like as follows using exposed fliter fields in d6 , how can i recreate like that in d8 ?

Here the `from date` and `to date` is to be selected and result will come accordingly

for the date . Here the date field is exposed filter .

view page :

and in view

**How can i recreate a form like this using view in D8 ?**

For the same purpose in d8 i have only this option : Any help is appreciated .

# Answer
1) Checkmark ☑ expose filters

2) Select Single Filter

3) Select is between

which will result in

Unfortunately there is no way to do it in drop downs like you have it until the better exposed filters module gets ported.

Well you could do it in Drop downs using Group Filter with is between, but you would only be able to do it by year only though.
> 3 votes

---
Tags: 8, views
---


title: The modal doesn't appear

text:
# Question
Title: The modal doesn't appear
I want to output a link in a modal window, using the *Simple Link* approach shown on Make Mine a Modal.

When the link is clicked, the little animated spinner appears, and I can see the response returned via AJAX using the browser inspector. Still, no modal appears and there aren't errors reported in the console.

Do I need to add some markup to the theme I am using, which will be used as modal container?

# Answer
The markup I was using contained the wrong CSS attribute: Instead of `data-accepts`, it should use `data-dialog-type`, as in the following example.

```
    <a href="/blah" class="use-ajax" data-dialog-type="modal" data-dialog-options="{"width":500}">Show me a 500px wide modal</a>

```

I was using the wrong attribute after reading some outdated articles. Once I found the following comment on Understanding Drupal 8's Modal API and Dialog Controller, I understood what my error was.

> The dialog API changed since the blog post was created. Maybe you'll update your samples based on my example.
>
> ```
> // Build link for dialog.
> $link_url = Url::fromRoute('entity.taxonomy_term.add_form', ['taxonomy_vocabulary' => 'vocab_name']);
> $link_url->setOptions([
>   'attributes' => [
>     'class' => ['use-ajax'],
>     'data-dialog-type' => 'modal',
>     'data-dialog-options' => Json::encode(['width' => 700]),
> ]));
> $link_add_unit_display_name = \Drupal::l('Create unit display name', $link_url);
>
> Regards,
> SteffenR
>
> ```
> 5 votes

---
Tags: 8, ajax
---


# Question
Title: Programmatically populate file field using Entity API
I need to programmatically generate nodes using some data that I extract from different import files. For the node creation I use Entity API. I've written a simple function to which I pass the node data in a structured array and the function imports each field depending on how it's defined:

```
  function my_module_create_function($item, $node_type, $language) {
    $node = entity_create('node', array ('type' => $node_type));
    $entity = entity_metadata_wrapper('node',  $node);
    $entity->language = 'es';//LANGUAGE_NONE; // Or e.g. 'en' if locale is enabled
    //strings
    foreach ($item as $key=> $field) {
      switch ($field['field_type']) {
        case 'multiple-reference':
          if(is_array($field['value'])){
            $entity->$key = $field['value'];
          }else{
            //some alert log
          }
          break;
        case 'file':
          if (file_exists($field['value']) && isset($field['filename']))
          {
            $file = file_get_contents($field['value']);
            $filename = $field['filename'];
            if(isset($field['folder']) && file_exists($field['folder'])){
              $folder = $field['folder'];
            }else{
              $folder = "public://";
            }
            $file = file_save_data($file, $folder.$filename, FILE_EXISTS_REPLACE);
            $entity->$key= (array)$file;
          }
          else
          {
            // some alert log
          }
          break;
        case 'long-text':
          $entity->$key->set(array(
            'value' =>  $field['value'],
            //'summary' => '',
            'format' => 'full_html',
          ));
          break;
        case 'geolocation':
          $entity->$key->set(array(
            'latitude' => $field['value']['latitude'],
            'longitude' => $field['value']['longitude'],
            //other elements added here (province, postal_code, country [es, en,...],additional, ...)
          ));
          break;
        default:
          $entity->$key= $field['value'];
        break;
      }
    }
    $entity->status = 1; //(1 or 0): published or not
    $entity->promote = 0; //(1 or 0): promoted to front page
    $entity->comment = 0; // 0 = comments disabled, 1 = read only, 2 = read/write
    // Save the entity
    return $entity->save();
  }

```

This function works great except for the file field type. When I try to import a node with a file it gives me this error:

> PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1048 Column 'my\_field\_display' cannot be null

the thing is that I have used the same structure:

```
        $file = file_get_contents("file_path");
        $file = file_save_data($file, $folder.$filename, FILE_EXISTS_REPLACE);
        $entity->$key= (array)$file;

```

for image fields (or multiple image fields using "`[] =`" instead of " `=` ") it works without any problem. Anyone knows if I'm doing anything wrong with this file field?

Any advice would be helpful

# Answer
Ok, I found the answer to this question here.

Instead of:

```
        $file = file_save_data($file, $folder.$filename, FILE_EXISTS_REPLACE);
        $entity->$key= (array)$file;

```

It should be:

```
        $file = file_save_data($file, $folder.$filename, FILE_EXISTS_REPLACE);
        if($file !== false)
        {
          $entity->$key->file->set($file);
        }

```

This '`if($file !== false)`' is optional just to be sure that we're passing a file object.

> \*Note that the difference is that we're not passing the file object as an array and also we're passing it to a 'file' atribute instead of passing it directly to the field.
> 0 votes

---
Tags: nodes, entities, files
---


# Question
Title: How to pass required arguments to a custom content type with services?
I am trying to create a Room Reservations Reservation through a Service using the Node Creation resource, but looking at the Room Reservations module code, the module does not allow the creation of nodes, or the passing of the form data for that matters, unless specific parameters are passed as arguments in the URL.

So far I have tried using the node create resource with the following data formatted as JSON, to no success

```
{"title":"fulano de tal","type":"room_reservations_reservation","reservation_block_title":{"und":[{"value":"0"}]},"reservation_date":{"und":[{"value":{"year":"2016","month":"6","day":"1","hour":"10","minute":"0","second":"0"},"timezone":"America/Bogota","timezone_db":"America/Bogota"}]},"reservation_length":{"und":[{"value":"60"}]},"reservation_repeat_type":{"und":[{"value":"1"}]},"reservation_repeat_until":{"und":[{"value":{"year":"2016","month":"6","day":"1","hour":"10","minute":"0","second":"0"},"timezone":"America/Bogota","timezone_db":"America/Bogota"}]},"reservation_room":{"und":[{"value":"163"}]},"reservation_time":{"und":[{"value":"1000"}]},"reservation_series_id":"","field_codigo_reservation":{"und":[{"value":"654535184561"}]},"field_email_registro":{"und":[{"email":"dshaooner@unisabana.edu.co"}]}}

```

The response is the whole webpage and no node is created.

i think the solution here is to pass the required arguments so that Room Reservations creates the node, would something like the following work?

example.com/endpoint/node.json/add/room-reservations-reservation/6/1/1200/160

Along with the rest of the data in the JSON POST request.

# Answer
> 1 votes
1) Firstly you will create your custom resource for POST request. Add Below Code to your module file.

```
function Your_Module_Name_services_resources() {
     $resources = array();
     //$_SERVER['REQUEST_METHOD'] = 'POST';
     //Include the necessary inc files.
    module_load_include('inc', 'Your_Module_Name', 'includes/Your_Module_Name.services');

   //Service Apis for contents.
    $resources += Your_Module_Name_resource();
    return $resources;
}

```

2) Create Your\_Module\_Name.services.inc file and write below code for your custom callback as given below.

```
function Your_Module_Name_resource() {
  $api = array(
'applicant_validate' => array( // Resource Name
 'operations' => array(
    'create' => array(
    'help' => 'Validate Applicant',
    'file' => array(
        'type' => 'inc',
        'module' => 'your_module_name',
        'name' => 'includes/your_module_name.services',
    ),
    'callback' => 'your_callback_function_name',
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'access arguments append' => FALSE,
    'args' => array(
        array(
        'name' => 'body',
        'type' => 'string',
        'description' => 'Function to perform',
        'source' => 'data',
        'optional' => FALSE,
        'default' => '0',
        ),
    ),
    ),
    ),
  ));
   return $api;
 }

```

// variable name $body as you mentioned above in args part with name parameter

```
function your_callback_function_name($body)
{
  // It's called when you will hit to your web service url from your from submission.

}

<h2>Validate Web Service</h2>
 <form id="frm" method="post" action="http://example.com/api/endpoint/applicant_validate">
 <input type="text" placeholder="Application Id" name="appno" id="appno"/>
 <input type="text" placeholder="Email Id" name="emailid" id="emailid"/>
<input type="text" placeholder="Mobile Number" name="mobno" id="mobno"/>
<input type="text" name="userpwd" placeholder="Password" id="userpwd"/>
<input  type="submit" value="submit"/><br/>
</form>

```

---
Tags: 7, services
---


# Question
Title: Block visibily condition programatically
I want to display a block I implemented in a module when `$_SESSION['Group_id']` is set.

How can I achieve this?

# Answer
> 0 votes
In the block ::build() method, return an empty array() if the condition is false.

---
Tags: 8, blocks
---


# Question
Title: How to flag node when "event date" has passed and send notice to authors of flagged nodes?
I have a "delivery date" field in my content type that users choose when creating a node. When this date passes I want the notice to be sent to the nodeauthor.

As far as I see, I need to flag the node with expired date with Flag module. I know that it's possible to set exiry date when node is created. In my case I need to compare the user set "delivery date" and current date.

Can I do it with the Rules module?

# Answer
> 1 votes
Yes it's perfectly possible to produce such notification using the Rules module. But I don't see any reason why you'd want, or need, to ***flag*** (using the Flag module?) such nodes.

Instead you can use an approach which is pretty similar to what I described in my answer to "How to send an email to an author on a specific date using date field specified in a node?", which uses the **Rules Scheduler** (submodule of Rules):

* Change the *weaning* date to your expiration date.
* Add some additional Rules Condition (in Step 3) to avoid sending such notification to checks if the delivery is still outstanding (if it is delivered already, you may not want to send such notification anymore ...). For that you could simply add some boolean field like "Delivered? (Yes/No), which you'd that use in that Rules Condition to be added.

Happy Rules-ing!

PS: should you have some reason to flag the node anyway, then that would be a straight forward enhancement you could add to this solution also.

---
Tags: 7, nodes, datetime, flags
---


# Question
Title: Creating multiple URL aliases for the same node with their own context
I want to solve the following problem with Drupal 7 solely using existing modules and without any extra code.

* I have a contenttype called 'News'
* I create a news item and assign a taxonomy term called 'Sport' and a taxonomy term called 'Entertainment'.

---

Is this possible without custom code? And if custom code is neccesary how would I proceed?

# Answer
This should be working using the Rules and Pathauto modules. There's already a similar question that is answered: How to automatically generate multiple aliases for one node?
> 0 votes

---
Tags: 7, path-aliases, uri
---


title: Search according to language

text:
# Question
Title: Search according to language
We are using 3 different languages by multilingual module. If we search by the English word, then search content should be in English, and if we search by Marathi/Hindi word, then search content should be in that particular language.

How can I perform multilingual specific search?

# Answer
> 1 votes
I had the same requirements, and I used the Custom search module, which includes a submodule called **Custom Search Internationalization** : "*search content from all or current language only, and all label and selectors translation handling*" (note this module provides also several other helpful features like custom search blocks). Works perfectly.

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


title: Why are tokens added to image URLs?

text:
# Question
Title: Why are tokens added to image URLs?
When I'm use the `image_style_url()`, function I got this token at the end of the URL: `?itok=yjoxJwQh`.

Drupal uses a different token for styles and script, eg `?mk4o7m`.

How does this affect caching and SEO?

# Answer
> 17 votes
This was a change that was introduced in Drupal 7.20, which addressed a denial of service vulnerability:

> Drupal core's Image module allows for the on-demand generation of image derivatives. This capability can be abused by requesting a large number of new derivatives which can fill up the server disk space, and which can cause a very high CPU load. Either of these effects may lead to the site becoming unavailable or unresponsive.

From the release notes:

> The security fixes in this release change all image derivative URLs generated by Drupal to append a token as a query string. ("Image derivatives" are copies of images which the Drupal Image module automatically creates based on configured image styles; for example, thumbnail, medium, large, etc.)

Drupal 7.21 revised this a little:

> Drupal 7.20 fixed a fundamental security flaw in the Drupal core Image module and therefore introduced incompatibilities with a number of contributed modules and sites (see the Drupal 7.20 release notes). To help mitigate the effect of these changes, an optional `image_allow_insecure_derivatives` variable was provided, which sites could use to turn off the security fix.
>
> Drupal 7.21 adds additional security protection for sites that use this variable. Although they will still not receive the full benefit of the security fix, they will now have protection against the most damaging and easiest-to-inflict vulnerabilities that were addressed in Drupal 7.20.

# Answer
> 4 votes
Since version 7.20, Drupal adds a security token to the URL of derived images (that is, images that are manipulated by an image style, e.g. to get a thumbnail or an otherwise cropped version of a base image). The token is created when the appropriate HTML to render an image with a given image style is generated and usually shouldn't change after it has been created. The reason for this is that without it, anyone could request derived versions for any image they knew existed on a site (which is not hard to find by examining img tags in use on the site) for any image style they knew existed on a site (which is also not that hard to find with the same method). Since the derived image is created when it is first requested, this would put a high load on the system, creating a denial of service. With the token, it is first checked before starting generation of the derived image. This means derived images will only be created for base image and image style combinations that were intentionally output in the site's HTML.

Since version 7.21, this behaviour can be disabled using a hidden configuration variable (i.e. it would need to be set in the settings file, or through a tool like drush), image\_allow\_insecure\_derivatives.

See the release notes of these Drupal versions 7.20 and 7.21 for more details.

"Tokens" on JS files and CSS files are simply "cache busters", i.e. intended to force clients to re-download the resource, usually because it has changed.

Image tokens should have minimal impact on caching, because they usually remain the same from the first moment the html for the derived image is generated (possibly, the tokens are wiped too when the image styles are flushed, but that shouldn't happen under normal circumstances). "Tokens" on other resources are, as said, *intended* to affect caching; they are designed to force redownloading of the resource (but only when that is needed).

Effect on SEO should, I think, also be minimal, although I am less qualified to comment on that. AFAIK, search engines are pretty good at knowing whether a GET variable should be considered part of the URL (i.e. it determines the actual content of the resource) or just something technical. Even if they don't consider that, I think JS and CSS URLs shouldn't really have any impact on SEO anyway. With images, it shouldn't really matter whether the token is considered to be part of the URL or not, since it shouldn't really change, normally (and then still, the only place where I think it might be actually relevant is in image search results).

---
Tags: uri
---


# Question
Title: How to resolve the error when adding an entity reference relationship?
Multifield Contributed Module - https://www.drupal.org/project/multifield

Company Content Type has multifield

1) Company Division - Entity reference
2) Company Categroy - list

While adding relationship as entity reference node company division in views an error is thrown.

> SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'field\_fieldname\_node.id' in 'on clause'

# Answer
> 1 votes
It looks like your issue is because of the Multifield issue Add Views API integration for the multifield field type. And that the patch attached to comment nr 96 of this issue solves it.

---
Tags: 7, views
---


# Question
Title: Apply view contextual filter only if user role is not administrator
I have a view that filter a list of taxonomies based on the taxonomies associated to the logged in user. This works fine. Now, I need to create an exception only for users with role "administrator" that must see the complete list of taxonomies, without any filter applied. I know how to check the logged user role in views, but I can't figure out how to avoid the contextual filter for the specific case.

IMPORTANT NOTE: sorry guys, I forgot to mention that the view will filter the taxonomies list in admin content-type form and not for the front-end pages.

# Answer
Not entirely an answer to the question, more a workaround, but you could do it as follows.

Make sure to create a second page. It has to be identical to the original one (including the path), so you can clone it from the `edit view name/description` dropdown button. Then make sure to remove the contextual filter from this display only, and limit the access to users with the administrator role. Finally make sure this views page is listed before the other one (`reorder displays` in the `edit view name/description` dropdown button).

This works because views attempts to load the path, if there is no access for the first display, views attempts to load the second display. So all users that have no administrator role will see the second display, while the admins will get the first display without contextual filter.
> 2 votes

# Answer
You can use `hook_views_query_alter` to alter the views query. So that you can use 2 different query for "administrator" role and the other roles.

Refer : https://api.drupal.org/api/views/views.api.php/function/hook\_views\_query\_alter/7.x-3.x
> 0 votes

# Answer
Thanks a lot to all for the answers! I think I've found a good solution to my specific problem by following this discussion Using the Views PHP module I can set basic or even complex php controls on a contextual filter in the view.
> 0 votes

---
Tags: 7, views
---


title: Parse REST Json replay

text:
# Question
Title: Parse REST Json replay
I create a views with `REST export` display, result are serialized with `Json`,

In my formBuild method I want to parse JSON and Convert it to array and use it in select option

```
    $host = \Drupal::request()->getHost();
    $response = \Drupal::httpClient()
        ->get($host.'/get/slider' );

    $json_string = $response->getBody()->getContents();
    kint($json_string);

```

I see Symfony serialize class and find `Deserialize` method with this example

```
 $person = $serializer->deserialize($data, 'Acme\Person', 'xml');

```

According to this,I guess maybe I should something like

```
     $results = $serializer->deserialize($json_string, '???', 'josn');

```

but what I should write in second param(???)? I try

```
    $serialize = new Serializer\Serializer();
    $json_string = $response->getBody()->getContents();
  $entity = $serialize->deserialize($json_string, '\Drupal\node\Entity\Node::class', 'json')  ;

```

but face me with error `Symfony\Component\Serializer\Exception\UnexpectedValueException: Deserialization for the format json is not supported in Symfony\Component\Serializer\Serializer->deserialize()`.

And if you have better solution tell me **How Can I deserilized views REST results?**

**update** Also,I tried

```
    $json_string = $response->getBody()->getContents();
    $serializer = \Drupal::service('serializer');
    $deserialized = $serializer->deserialize($json_string, \Drupal\node\Entity\Node::class, 'json');

```

but `Symfony\Component\Serializer\Exception\UnexpectedValueException: A string must be provided as a bundle value. in Drupal\serialization\Normalizer\EntityNormalizer->denormalize()`

# Answer
> 3 votes
Drupal has a service for serialisation, pre-configured with the normalisers and encoders you need. The error you currently have is because you're not setting up the instance of the serialiser with the `Symfony\Component\Serializer\Encoder\JsonEncoder`, but you'll also need, for example, the `Drupal\serialization\Normalizer\ConfigEntityNormalizer` normaliser.

This code works well for me:

```
$serializer = \Drupal::service('serializer');
$node = \Drupal::entityTypeManager()->getStorage('node')->load(1);

$output = $serializer->serialize($node, 'json');
$deserialized_node = $serializer->deserialize($output, \Drupal\node\Entity\Node::class, 'json');

```

As always, inject the services if possible.

# Answer
> 1 votes
Try `json_decode`, first `use Drupal\Core\Serializer;`

then in your code use

```
 $json_string = $response->getBody()->getContents();
 $res =json_decode($json_string);

```

---
Tags: views, 8
---


# Question
Title: Why is submit handler not called if $state['rebuild'] == true?
I have a simple form that shows a form fields and after submitting shows just a download link:

```
function activit_report_download_file_form($form, &$state, $node) {

// check if form was already submitted
$submitted = false;
if(isset($state['triggering_element'])) {
  $submitted = true;

  if(!valid_email_address($state['values']['email'])) { $submitted = false; }
  if(strlen($state['values']['name'])<2) { $submitted = false; }
  if(strlen($state['values']['surname'])<2) { $submitted = false; }
}

if(!user_is_logged_in() && !$submitted) {

  $form['info'] = array(
      '#type' => 'markup',
      '#markup' => '<div class="info">'.t('Po vyplnení Vaších údajov si budete môcť stiahnuť PDF report').'</div><br>'
  );

  $form['email'] = array(
      '#type' => 'textfield',
      '#attributes' => array('placeholder' => t('Váš email'))
  );

  $form['name'] = array(
      '#type' => 'textfield',
      '#attributes' => array('placeholder' => t('Váše meno'))
  );

  $form['surname'] = array(
      '#type' => 'textfield',
      '#attributes' => array('placeholder' => t('Váše priezvisko'))
  );

  $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Získať link na stiahnutie reportu'),
      '#attributes' => array('class' => array('button', 'btn-blue')),

  );

} else {

  $form['link'] = array(
      '#type' => 'markup',
      '#markup' => '
        <div class="info">Report stiahnete kliknutím na toto tlačítko.</div><br>
        <a href="" class="button btn-orange">'.t('Stiahnuť PDF report').'</a>'
  );

}

return $form;
}

```

In validation handler is $state\['rebuild'\] = true;

```
function activit_report_download_file_form_validate($form, &$state) {

  $state['rebuild'] = true;

}

```

In submit handler is:

```
function activit_report_download_file_form_submit($form, &$state) {

  db_insert('t_report_download')->fields(array(
      'email' => $state['values']['email'],
      'name' => $state['values']['name'],
      'surname' => $state['values']['surname'],
      'anonymous' => 1,
  ))->execute();

  dsm('submitted');
}

```

Problem is that submit handler is triggered only if $state\['rebuild'\] = true; in validation handler is commented. If it is not, submit handler will never be triggered.

What's the logic behind this behavior?

# Answer
When form validation fails submit handler should not be executed because there are errors in the form.

In a similar way, when a form is mark as *rebuild* in the validation phase submit handlers should not be executed because the form is going to be rebuilt. This means that form is going to change and the user interaction with the form is not finished.

You can check the (complex) workflow of FAPI in this illustration:  (Illustration from https://www.drupal.org/node/165104)
> 2 votes

---
Tags: forms
---


# Question
Title: How to move whole Drupal website on USB for localhost use using XAMPP?
My cPanel subscription will come to an end soon and I want to move my site to a USB stick or CD and still be 'runnable' / executed. It is currently on a cPanel server...

I have seen these options but they all seem outdated and might not be ideal as my website is nearly 300MB in size.

I want to keep the site static and lose the editing features that come with the modules - essentially I want to freeze what I have done up to now and keep a record of it that will always work locally on a medium.

# Answer
If you are married to the idea of running your website via a USB Drive, you can always just download a lamp stack to your computer and configure it to look at usb drive as it's default home directory.

There are several options for this.

* Xampp: General one size fits all lamp stack
* DEV Desktop: A Drupal specific lamp stack
* Mamp
* Wamp

This is great for doing dev work on a duplicate copy of a site for testing in order to not screw up the production. The only problem with this is if you are trying to plug the usb to multiple computers you will have download the software each time and configure it look at the usb for it's root directory.

On the plus side using a local lamp stack you won't lose you ability to edit the site. It'll operate exactly the same way. With the exception that ftp ability will vary. Also it's good practice for doing standard Drupal Migrations.

**NOTE:** I would suggest if you try these options you operate from a desktop and not a USB. The USB could be for just keeping backups.

If this is something you deem acceptable I can expand on this idea.
> 1 votes

---
Tags: 7, backups
---


title: How to apply xss filter on a csv file

text:
# Question
Title: How to apply xss filter on a csv file
I have a CSV file from which I am importing some data. Should I need to apply XSS filter? How do I achieve this?

```
   while (!feof($handle)) {
    $data = fgetcsv($handle);
    $path[] = $data[0];
    $title[] = $data[1];
    $description[] = $data[2];
    $abstract[] = $data[3];
    $keywords[] = $data[4];
}

```

# Answer
> 2 votes
Well to my knowledge Drupal doesn't mind the input/import data that much, as long as it's rendered in a secure way.

> So what we really have to do is make sure that, regardless the data, **its content can never be interpreted as SQL**. To do this, we use the escaping functions provided by the database API. We do this escaping in the database layer and not directly after receiving input as it may not be the only escaping (or filtering) we have to do. - https://www.drupal.org/node/101495

Just my 2 cents :)

---
Tags: security
---


title: Organizing content in a hierarchy

text:
# Question
Title: Organizing content in a hierarchy
I created a website with some content nodes in D8. Right now, all the nodes are on the same level, however, I would like to achieve something like this:

```
- Products
- - Product A
- - Product B
- - Product C
- About Us
- - Offices
- - Contact

```

Naturally, I would like the nodes' URLs to respect the hierarchy, so that there would be URLs like `mydomain.com/products` and `mydomain.com/products/product-a` and so forth.

I know about Node Hierarchy being available for 7, but it seems there's no such solution for D8 - however, since this is such a basic requirement, I suppose there's a way how to do this I don't know about. So, how to? Is the book module maybe the right solution for this?

# Answer
I would set up a vocabulary, with a machine name such as site\_nav,

then on your nodes, you would add a taxonomy term reference field to the site\_nav vocabulary.

Then set up automatic path aliases using pathauto at /admin/config/search/path/patterns

You could use the title of the page or add an additional field, such as field\_short\_name to use in the url.

Then the pattern would be

```
[node:field_site_nav:url]/[node:field_short_name]

```

or

```
[node:field_site_nav:url]/[node:title]

```

or some such (I forget the exact pattern for urls of terms).

You could also use the content type names, if you have content types such as "products" and "about us", then the pattern would be

```
[node:content-type]/[node:title]

```

There are some more examples here:

https://www.drupal.org/node/1044980
> 2 votes

---
Tags: 8, nodes
---


title: GraphicsMagick in Drupal 7

text:
# Question
Title: GraphicsMagick in Drupal 7
`D7` has `ImageAPI` and that `ImageMagick Module` is also installed. However I want to use `GraphicsMagick` with D7 but haven't been successful till now. I have both ImageMagick and GraphicsMagick installed in my Ubuntu Box, I also have `pecl imagick` and `pecl gmagick` installed. I know both `pecls` doesn't work at the same time, but I have been changing configs whenever necessary.

I have tested both `ImageMagick and GraphicsMagick` from command line, both works perfectly, but I couldn't make it work with `Drupal`. According to `ImageMagick Module` I just need to change in `Image Toolkit` from `convert` to `gm`, Drupal reads the `executable binary` perfectly. I try to upload photo which doesn't show after processing and is also not uploaded in the file. But when I change it back to `convert` and `pecl imagick` everything works smoothly.

Any suggestions how to use `GraphicsMagick` with `Drupal 7` ?

I even tried that this http://drupal.org/sandbox/W32/1077458 sandbox project, but no luck...

# Answer
> 0 votes
Many years later, but for future reference, the problem might be related to the fact that you are using the PECL gmagick PHP extension. I believe the ImageMagick module is not meant to work with the gmagick PHP extension. There is a module meant to be used specifically with PECL's gmagick: https://www.drupal.org/project/gmagick . I hope that helps somebody.

---
Tags: 7, media
---


# Question
Title: How can I edit the 'Title' field label of a Node content type within a module?
I'd like to do this in Drupal 8:

---

I need to change the label of the Title field on a custom content type ***without using admin panels***.

I know this is possible via the admin menu, but I feel like I should be able to have the module fully set up when it is installed. Is there a flag in the content type's configuration file that I can add to override the default value?

Here's my `node.type.employee.yml` file

```
langcode: en
status: true
dependencies: {  }
name: 'Employee'
type: employee
description: ''
help: ''
new_revision: false
preview_mode: 1
display_submitted: true
third_party_settings: {  }

```

# Answer
This is stored as a field override configuration. It's a separate config entity with the name `core.base_field_override.node.your_node_type.title`.
> 5 votes

# Answer
Go to /admin/structure/types/manage/examplecontenttype

change the the title label to what you want.

export the config, on the command line using drush, you'd use

```
drush cex -y

```

then commit the resulting .yml file

/sites/default/sync/node.type.examplecontenttype.yml

Such as:

```
uuid: 5b0d84b8-b264-48c4-b726-1150966d955e
langcode: en
status: true
dependencies:
  config:
    - node.type.examplecontenttype
id: node.examplecontenttype.title
field_name: title
entity_type: node
bundle: examplecontenttype
label: 'Your Custom Label Goes Here.'
description: ''
required: true
translatable: true
default_value: {  }
default_value_callback: ''
settings: {  }
field_type: string

```
> 2 votes

---
Tags: nodes, entities, 8
---


# Question
Title: How to escape strings before insert query?
I've used `mysql_real_escape_string()` to make strings safe before using Drupal.

Must I escape string before inserting it to database? If the answer is yes, then how must I do it?

I use something like this to insert into database:

```
\Drupal\Core\Database\Database::setActiveConnection('mydb');
$connection = \Drupal\Core\Database\Database::getConnection();
db_insert($table_name)->fields(array(
'myfield1' => 'My String',
))->execute();
\Drupal\Core\Database\Database::setActiveConnection();

```

# Answer
No need to worry about escaping. The Drupal database abstraction layer is taking care of query parameter escaping by turning them into placeholders and escaping the data.
> 4 votes

---
Tags: 8, database
---


# Question
Title: theme_hook_suggestions based on empty field
I'm trying to implement theme\_hook\_suggestions in preprocess node template based on the fact that a field (field\_logo) is empty or not.

The template change is not working.

Can anyone help?

This is the code that I have so far:

```
function community_alpha_preprocess_node(&$vars) {
  $node = $vars['node'];
  if(($node->type == 'advertorial') && !$teaser && $node_top){
    $advertorial_type = $node->field_logo['und'][0]['tid'];
    if(!empty($advertorial_type)){
      $vars['theme_hook_suggestions'] = 'node__advertorial';
    }else{
      $vars['theme_hook_suggestions'] = 'node__advertorial__alt';
    }
  }

}

```

Thanks.

# Answer
> 0 votes
I believe there was a problem with the first conditional loop. I also removed \['und'\], \[0\] and \['tid'\] from field\_logo.

So here's the final code that seems to work.

Thanks for the help.

```
function community_alpha_preprocess_node(&$vars) {
  $node = $vars['node'];
  if($node->type == 'advertorial'){
    $advertorial_type = $node->field_logo;
    if(!empty($advertorial_type)){
      $vars['theme_hook_suggestions'][] = 'node__advertorial';
    }else{
      $vars['theme_hook_suggestions'][] = 'node__advertorial__alt';
    }
  }
}

```

# Answer
> 0 votes
You need to clear the cache after making changes in the template.php file.

For Drupal 7 version please run below command to clear the cache and check aftewards.

drush cc all

For Drupal 8 version please run below command to clear the cache and check afterwards.

drush cache-clear

---
Tags: theming
---


# Question
Title: How do I programatically change default values in a contact form?
I have a Drupal 8 contact form where the form's placeholder values are the default values of the fields. Unfortunately, this site is multilingual and I don't think it's possible to translate default field values.

Is there a way I can set the fields' default values equal to the (translatable) field labels in either a module or preprocess function?

# Answer
> 2 votes
You can override your contact forms(both the default and the custom ones) by adding a field widget hook. Why a field widget hook and not the usual form alter hook like D7? Because overriding the default value of the field can be done only in the respective field widget and not at the form level.

Here's the sample code:

```
function <mymodule>_field_widget_form_alter(&$element,  \Drupal\Core\Form\FormStateInterface $form_state, $context) {
   $field_definition = $context['items']->getFieldDefinition();
   $entity = $context['items']->getEntity();
   if(($entity->getEntityTypeId() == 'contact_message') && ($entity->bundle() == '<your-custom-form-machine-name>')) {
     if($field_definition->getName() == '<your-field-machine-name>') {
       $element['value']['#default_value'] = 'Hi there!';
     }
   }
}

```

**NOTE** This has been tested with Drupal 8.1.1.

# Answer
> 0 votes
I managed to figure it out with a preprocess function using hook\_form\_id\_alter. I got an array of the necessary field names, and looped through it assigning the field label value to the placeholder value. If this is bad form, let me know.

```
function yourtheme_form_yourformid_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $field_list = array_keys($form['#group_children']); //you might need to find a different array to get the names of your fields
  foreach ($field_list as $field) {
    $field_name = $field;
    $form[$field_name]['widget'][0]['value']['#placeholder'] = $form[$field_name]['widget'][0]['value']['#title'];
  }
}

```

---
Tags: entities, i18n-l10n, emails
---


# Question
Title: Including a large amount of raw data with a module
I have a module that demonstrates how to use another module (a graphing library). One of my controllers uses a large dataset to generate one of the example graphs. I currently have this data assigned to a variable in the controller. However, this takes up a large amount of space in the file. If I want to meet Drupal code style guidelines, I would have to break up the array after every `[x,y]` pair, making it even more difficult to review.

Should I move this data into some sort of include file, and read the text file into my controller? What's the "Drupal Way"?

# Answer
> 0 votes
Your intuition is correct; you should break out your large dataset into some include file. I don't believe there's a strict mention of large datasets in the Drupal coding standards, but isolating out large datasets is good way to isolate concerns (i.e. code-readability vs. dataset referencing).

A good reference example of this would be the Transliteration module. It has a transliteration dataset of include files indexed by unicode byte that's loaded on demand as it needs to transliterate a unicode characters to ASCII.

Your data will obviously be structured to fit your own use case, but given you're probably not the first person to work with large graphic library datasets and PHP, there's probably some general practices to glean from others who've worked on the same problem.

---
Tags: 8
---


# Question
Title: Do I need BOTH jQuery wrappers or just one?
* \[Drupal 7.43\]
* \[Production Linux Environment\]
* \[Omega4 Sub-Theme\]
* \[jQuery-Update-Module-7.x-3.0-alpha3\]

(Some Questions) I am using jQuery on my website to accomplish several fixes:

1. Make iPhones respond to Hover Events.
2. Add a Div-wrapper to enclose a group of Navigation-Links.
3. Create an Accordion Navigation Drop-Down.
4. Stop Google-Maps-Windows from scrolling in Mobile environments, eclipsing the regular page scroll.

I have integrated jQuery using the MyTheme-Info strategy. That is, that I have added the script-tag of the fixes individually to the MyTheme.info file. Then I have uploaded the corresponding Fix-01.js files to the server. Basically, this seems to be working, but I have some questions and these concern the BONUS weirdness that Drupal adds to the already amply weird jQuery itself.

I know that I have to wrap the "Fix-0x.js" files in the code:

Code Wrapper #1

`(function ($) {
 //Some amazing code here
}(jQuery));`

As I understand it, this allows jQuery to use the '$' symbol without clashing with other libraries that also use this same symbol.

I know that jQuery also MUST wait for the DOM to load before the script can have any access to the elements of the DOM. Often this is done with the code:

Code Wrapper #2

`$(document).ready(function() {
 //Some amazing code here
});`

Or sometimes it is written:

Code Wrapper #3

`$(function() {
 //Some amazing code here
});`

The question is, does the first jQuery wrapper (Code-Wrapper #1) include the Document-Ready function or not (Code-Wrapper #2). Do I have to wrap the jQuery in BOTH wrappers? I know that Code-Wrapper #2 and Code-Wrapper #3 are equivalent.

# Answer
> 3 votes
> does the first jQuery wrapper (Code-Wrapper #1) include the Document-Ready function or not (Code-Wrapper #2).

No it doesn't.

> Do I have to wrap the jQuery in BOTH wrappers?

If you need DOM ready, yes you do, but in Drupal 7, they suggested `Drupal.behaviors`. See https://www.drupal.org/node/756722#behaviors

---
Tags: javascript
---


# Question
Title: How to change uploaded file name after save node?
Hello and thanks for looking my question.

On Drupal 7 I use this hook hook\_file\_presave() for change file name.

```
function mymodule_file_presave($file) {
  $parts = pathinfo($file->filename);
  $file->filename = $file->uid . $file->timestamp . '.' . $parts['extension'];
}

```

But how to do it on Drupal 8.1.x? Programmatically or module ways or something else?

# Answer
> 1 votes
`hook_entity_presave`?

Description from the DocBlock:

> Act on an entity before it is created or updated.
> You can get the original entity object from `$entity->original` when it is an update of the entity.

---
Tags: 8, hooks
---


# Question
Title: How to prevent my site to crash when adding video content using the Media Colorbox module?
I'm having a lot of issues when trying to set up my Media Colorbox module.

For images, the Colorbox module works just fabulous, but whenever I try to add some video content in this Colorbox overlay, the site just crashes: I get a white screen, and the site just keeps loading. It's like it's looking for a file, but it cannot find it, although the link is correct because the file is actually there. The permissions for the files are correctly set.

I've tried many setups, tips and tricks documented on the Drupal pages, with no luck. What I want to achieve is perfectly demonstrated on this page, and although my code looks exactly the same, my content just wouldn't load.

I'm using the most recent versions of all modules:

I don't think there is an issue with that.

I've tried any possible CSS class: colorbox-inline, colorbox-load, and colorbox-video. I cannot access those movies by surfing to them, although the path is correct.

# Answer
> 1 votes
Might there be an incorrect link to a video player library or something? Maybe it's the setup of the player and not colorbox, media colorbox, or file entity. Just guessing....

# Answer
> 1 votes
Your issues may also have to do with Colorbox not playing well with inline images in Drupal 7. One way of getting around this is using the Insert module to place content in the body field of your node, or to create an image field that can be used to display Colorbox images.

---
Tags: 7, media, javascript
---


# Question
Title: How to change fields to not be required before they are validated
In Drupal 7, How can I change certain fields to not be required using the form api, depending on which button they click to submit? It seems the validation is occuring before the validate function. Where can I change this before it gets there?

# Answer
> 5 votes
I believe the form validate hook triggers after the default validation which would include checking required fields. It might be easier to not mark the fields required by default and check in your validate hook if they need to be required and then throw a form error if necessary.

---
Tags: 7, forms
---


# Question
Title: Correct Database settings for pushing a Drupal site live
I have a Drupal 7 site.

I have it working fine on localhost and my own test domain, with individual settings folders setup such as:

sites/localhost sites/test.mydomain.co.uk

I am now putting it up onto a site where there is no domain set, but I can access it by visiting: sitename.org/folder1/folder2

i have duplicate settings files in; sites/folder1.folder2 sites/www.upcomingfinaldomainname.com

Have I got these right?

I keep getting the message:

PDOException: SQLSTATE\[HY000\] \[2013\] Lost connection to MySQL server at 'reading initial communication packet', system error: 111 in db\_table\_exists()

I'm using the user and pass I have been provided, and the correct db names. I have also set host as localhost and removed the port number.

Any suggestions?

# Answer
If your connection parameters were incorrect, you would get a different error from MySQL.

I have seen connection problems on Drupal systems for a few different reasons.

* Overloaded server
* Low timeout values on a busy server
* Low value for `max_allowed_packet` (this normally is a 2006 or 2020, though, in my experience).

Assuming other sites work, then the first two likely aren't the problem. I would check your `max_allowed_packet` and see if that helps matters. I typically use 32M; large values can help with restoring backups.
> 0 votes

# Answer
Looks like a database hosts misconfiguration. Check out the /etc/hosts.allow and set mysqld: ALL. Also, check if it's blacklisted in /etc/hosts.deny.

Also, check if the database server port and host are set correctly. If running on the same server, they should be 127.0.0.1 and port is 3306 (default).
> 0 votes

---
Tags: database
---


# Question
Title: How can users buy nodes they can create?
I want users to pay 5$ for each node they want to create.

They should be able choose, on registration, to pay from 1 to 400 nodes and more later if needed. The nodes should unpublish after a year with an option for a user to renew. Another option is to have multiple roles for purchase, each with a predefined number of nodes he can create, and let users choose the role on registration.

Is this possible?

# Answer
There's already a Commerce subproject called Commerce Node Checkout that does node publish purchasing with the option for expiration.

> Integrate with Commerce in order to allow you to charge users to create nodes. It is possible to have multiple different product offerings for each node type, so the user can pick the product they want to purchase when creating the node. An example use-case would be a classifieds site that charges people to post listings.

It's purchase process is on demand, rather than purchasing a credit quota, so you might have to look at something different to base your project on depending on how important the quota functionality is.

An alternative role-based approach would be the Commerce License Roles submodule and something like the Node Limit module to setup your quota-per-role requirement. You'd also have to find a node expiration solution (e.g. Node Expire) as well.
> 2 votes

---
Tags: 7, commerce
---


# Question
Title: Render a referenced node via token in field
This feels like it should be something people have tried, but I can't find anything after some googling. My use case is simple, I have a node type that only has 2 fields, `body` and `media`. The media field is, in fact, an entity reference field pointing to another node type (this is done because there are special cases where the media needs to be rendered HTML). All, I'm trying to do is render the referenced media field, by delta, in the main content area.

I can use the token `[node:field-media:0]` and print the title with no problem, I can print individual fields without an issue. Is there an existing method to print the rendered entity? I'm good with it using the default view mode.

I know I can code this up, but it seems like such a simple thing I figured there would already be a contrib module out there.

# Answer
If I understand you correctly, you are trying to render a node inside another node.

In the past, I have used the Display Suite module to perform exactly this task.

With DS you can create custom view modes for content types. For example, for your media content type, you can create a new view mode called 'Embedded' and structure the display to include the fields you want.

Then, in your first content type, you can set the entity reference field to display a rendered entity and select the view mode you just created. The node page will display 'both' nodes as you've structured them.

Note: DS also exposes a Token view mode for you to be able to manage how the token version of a content type gets rendered. The token view mode is useful if you must use tokens (i.e. inject node into the body text), however rendering the entity just in the field formatting should cover a majority of the use cases.

DS is actually quiet deep in functionality - I use it for every build to structure content types, render html in the way I want, etc.

Hope that helps.
> 2 votes

# Answer
I would still like to find a module that supplies this functionality (with a little less bulk than DS), but in the interim, I just implemented this in a custom module:

```
function MYMODULE_token_info(){
    return array(
        'tokens' => array(
            'node' => array(
                'rendered' => array(
                    'name' => 'Rendered Node',
                    'description' => 'Render the Node using the provided view mode',
                    'dynamic' => true
                )
            )
        )
    );
}

function MYMODULE_tokens($type, $tokens, array $data = array(), array $options = array()){
    $return = array();
    if($type == 'node'){
        foreach($tokens as $key => $full){
            $parts = explode(':', $key);
            if($parts[0] == 'rendered'){
                $prep = node_view($data['node'], $parts[1]);
                $return[$full] = drupal_render($prep);
            }
        }
    }
    return $return;
}

```

Not terribly robust, and it will fail in the case of recursion (not something that can happen with my setup), but it works pretty simply.

This just adds a token `[node:rendered:?]` where `?` is the view mode you wish to render the node in. So for my use case I can use:

`[node:field-media:0:rendered:default]`

And it prints the media node, at the 0 delta, attached through the entity reference field.
> 1 votes

---
Tags: 7, tokens, entities
---


title: Closest nodes with Locations and Views

text:
# Question
Title: Closest nodes with Locations and Views
I'm using Drupal 7 with Views 3 module and Location 3 module installed.

I have a content type that has a Location type field and I would like to build a view that given a latitude/longitude input and a maximum distance i have to retrieve all the nodes that are in this range. Is that possible with views or I have to build something by my own (in this case can you show me the way on how to implement it).

Thanks a lot for your help

Danilo

## **Resuming the question problem is the following:**

I have a problem setting a View to show the closest nodes of another (I'm using last dev version of views and locations on drupal 7). So my scenario is the following: I have 2 differents node types (A and B) both with a location field. I want to build a view that given a node A (with a determinate location) a have to retreive all the nodes B in a distance of 2Km. So to do that I created a view with the following filters:

1. Content: Type = B
2. Location: Distance / Proximity, with the parameters
    * {origin:"node's lat/lon from views nid argument"}
    * {Node ID argument to use: (it doesnt allow me to select any data)}
    * {Location to use:"CCK Location: field\_A\_loc"}.

I also added a contextual filter. I selected as contextual filter:

* {Content: Nid}

and I added % to my path so now the pat is /myviewpath/%. This allow me to choose the value:

* {Content: Nid} in the field "Node ID argument to use" of the filter "Location: Distance / Proximity".

So i try to run the view but I get no results when the view is called as mydomain.com/myviewpath/3 where 3 is a A node.

I also tried to do not use the contextual filter (that does not allow me to set the "Node ID argument to use" in the "Location: Distance / Proximity, with the parameters" filter) and running the view mydomain.com/myviewpath/node/3 but in this case I get the list of all B nodes..

What I'm doing wrong setting up this view??

Thanks in advance for your help

# Answer
> 1 votes
Yes, you could set up a view, filtering on Location: Distance / Proximity, and configure what the origin or "starting point" is, eg, the location of the logged in user, a node that has a location, or, in this case, a static lat/long, and then have it display whatever fields in the filtered nodes you want.

# Answer
> 0 votes
Think the best docs are now up https://drupal.org/node/1944648

# Answer
> 0 votes
By doing what you specified the view will show all nodes next to the visited node, as you added a contextual filter. Moreover, **make sure to tick Exclude box in More section from {Content: Nid} field in contextual filter.** This tutorial may be helpful https://www.reinisfischer.com/how-create-drupal-views-distance-filter-using-location-module

---
Tags: 7, views, location
---


# Question
Title: user/login page displays but gives a 404 error on firebug
My Drupal site gives a 404 error in firebug, even though the login form is showing. Also nothing happens when you click Log in-- the page just refreshes and login DOES NOT happen. This only happens in https. There is no error in HTTP and the login is working.

I have installed the secure\_login module hoping it might help, but no change. Basically, it just forced the login page to redirect to https.

I thought maybe the https is not configured correctly, but HTTPS is working fine in all the other pages. My site works in both http and https. The only problem is the login form.

# Answer
> 5 votes
The solution is in your Apache config file. Enable ‘LoadModule rewrite\_module modules/mod\_rewrite.so’ in httpd.conf file and clear the cache and then login again.

# Answer
> 0 votes
Bikashphp's answer above (Enable ‘LoadModule rewrite\_module modules/mod\_rewrite.so’ in httpd.conf file) worked for me, but I had to add an extra step of installing mod\_rewrite. Here are instructions on how to do that:

> In order to use mod\_rewrite you can type the following command in the terminal:
>
> ```
> a2enmod rewrite
>
> ```
>
> Restart apache2 after
>
> ```
> /etc/init.d/apache2 restart
>
> ```
>
> or
>
> ```
> service apache2 restart
>
> ```

From: https://stackoverflow.com/questions/869092/how-to-enable-mod-rewrite-for-apache-2-2

---
Tags: users
---


title: Page doesn't appear in search results

text:
# Question
Title: Page doesn't appear in search results
I created a view (page) which shows a list of nodes of a certain content type. This page doesn't show up when searching the site.

Is this expected behavior? Is there any way to make the page show up in a search?

# Answer
> 1 votes
To answer the first question: Yes, this is the expected behavior. Views pages are not indexed by Drupal core search.

For the second question, Drupal core search is limited. More is possible by using Apache Solr search integration. According to https://www.drupal.org/node/2570521, https://www.drupal.org/project/apachesolr\_nan is an example of a module that may do what you need. But you would need access to a Solr server.

# Answer
> 0 votes
Instead of creating a page view, I've created a block view and added it to an actual page (content). This works in my particular case and allows the site to index the page to show up in a search. It may not be fancy but I don't have to add a module to make it happen.

Thanks to user cilefen who answered my questions and got me here.

---
Tags: 7, views, search
---


title: Change labels of date select fields

text:
# Question
Title: Change labels of date select fields
I'm using the Form API to create a Date of Birth field with lists for month, day and year.

```
$form['dob'] = array(
    '#type' => 'date_select',
    '#title' => t('Date of birth'),
    '#default_value' => '',
    '#date_format' => 'm-d-Y',
    '#date_label_position' => 'within',
    '#date_year_range' => '-100:+0',
    '#required' => TRUE,
);

```

Sine the default value is blank this outputs the following:

How can I alter the labels? Specifically I want to get rid of the '-' characters so it looks more like this

# Answer
> 2 votes
There might be better way to do this, but one method would be to run an `#after_build` function that will alter the first `''` placeholder date label option to your liking. For example:

```
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  $form['dob'] = array(
    '#type' => 'date_select',
    '#title' => t('Date of birth'),
    '#default_value' => '',
    '#date_format' => 'm-d-Y',
    '#date_label_position' => 'within',
    '#date_year_range' => '-100:+0',
    '#required' => TRUE,
  );
  $form['dob']['#after_build'][] = 'MYMODULE_myform_dob_after_build';
}

// Alter the date component option so the first placeholder element has the new label.
function MYMODULE_myform_dob_after_build(&$form, &$form_state) {
  $form['day']['#options'][''] = t('Day');
  $form['month']['#options'][''] = t('Month');
  $form['year']['#options'][''] = t('Year');
  return $form;
}

```

---
Tags: datetime, forms
---


title: Files migration failed

text:
# Question
Title: Files migration failed
I am trying to migrate Drupal 7 site to Drupal 8. Other migration processes work well, but only file migration fails.

I have files in sites/default/files/.

This is my migrate\_plus.migration.upgrade\_d7\_file.yml

```
uuid: c6ddfa39-c76a-4457-ba30-8db364387f45
langcode: en
status: true
dependencies:
  module:
    - file
id: upgrade_d7_file
migration_tags:
  - Drupal 7
label: Files
source:
  plugin: d7_file
process:
  fid: fid
  uid: uid
  filename: filename
  uri: uri
  filemime: filemime
  status: status
  created: timestamp
  changed: timestamp
destination:
  plugin: entity:file
  source_path_property: filepath
  urlencode: true
migration_dependencies:
  required: {  }
  optional: {  }

```

And, I execute it with this drush command:

```
drush8 migrate-import upgrade_d7_file

```

This process returns this error message:

```
Processed 446 items (0 created, 0 updated, 446 failed, 0 ignored) - done with 'upgrade_d7_file'

```

What am I doing wrong here?

# Answer
> 7 votes
First off, when there are failures, check the messages table to see what the specific failures are:

```
$ drush8 mmsg upgrade_d7_file

```

In this case, I'm sure what you'll find is that it couldn't copy the files, because it couldn't find them - your .yml file does not include source\_base\_path, so there's no way for the migration to know where to copy the files from.

I'm guessing when you ran drush migrate-upgrade --configure-only to generate your migrations, you forgot --legacy-root - this value (either the address of your site such as http://www.example.com if you want to scrape the files directly over the web, or an absolute local filepath if you've copied the files onto your D8 server) will be used to set source\_base\_path in your destination configuration.

---
Tags: 8, files, migrations
---


# Question
Title: How do I limit permissions to manage an event?
I'm using the RNG Event module in D8 and have an issue where any registered user can click on an event and has access to the view and event tabs. And then through the event tab they can access the settings, access, conflicts, etc.

They can also click to view other user's registrations and delete them.

How do I limit normal logged in users to only see the event, and to register or delete a registration for only themselves? If they can see the other registrants that's fine, but they shouldn't be able to delete.

I have checked all normal permissions settings and see nothing that could grant their current level of access. The only other thing I see under Content Type \> Event type \> Access Defaults are the three stock rules that also seem to be correct.

This may or may not be connected to the issue I'm having here - Why does the "Registration List" tab not appear for my events for users with adequate privileges?

# Answer
> 1 votes
Per the other thread listed above, Daniel answered:

> Are you saying you have never seen the 'Registration list' tab? If this is the case you need to create that view by enabling rng\_views module. Then go to the event type edit form. An option to create the view will appear.

This worked perfectly, thanks again Daniel!!

---
Tags: rng
---


# Question
Title: Can't re-import a majority of products in CSV file
I have been working on a development site for a long time, so there have been many instances where I have imported, deleted, re-imported, re-imported with tampering, etc. There seems to be a large chunk of products from the CSV file that keep getting skipped during the import, and I can't figure out where there is a record of them in Drupal that could cause them to be "flagged" as already imported.

One possible source of the problem may involve the CSV files. The client is exporting a CSV file of all products on a weekly basis from an incredibly old computer system. The filename is always the same, and I have set up the feed with the File Upload settings set to "Supply path to file or directory directly."

I've used the Commerce Reset module, cleared caches, rebuilt the feeds importers with different machine names - everything I could possibly think of - yet it skips several hundred products that I know I have imported before. Is there something I'm missing, possibly regarding GUIDs, UUIDs, product\_id/entity id?

EDIT:

I should also have mentioned that I am using two feeds to import products - one to add the prices, and one for everything else (it's part of the client's DOS-based system, so no flexibility there). The current process involves running a feed to create the product (add the SKU, title, keywords), then running the price feed, which is set to update only.

Last night, I simply switched the settings on the price feed (add new products, overwrite existing, skip hash check, delete non-existing - the same as the other feed) and ran it. I was able to import all of the products. However, I decided to run the other feed to get the descriptions and keywords, and it would only update the products that it had last imported when it was set to create/overwrite/delete. What is happening here?

# Answer
There is a bug report about Importing Large CSV document (downloaded and processed in the background).

Also, take a look at Feeds large CSV import.

So if your CSV files are too big, parhaps cutting them down into multiple smaller CSV's will likely fix your problem OR You could try using the Drush Feeds sandbox as mentioned in the first comment.
> 0 votes

---
Tags: 7, commerce, feeds
---


# Question
Title: create two different registration form with same fields without using profile2
I have already setup account fields, and I have two roles (A) and (B) I need to create a page with two button links :

* register as (A)
* register as (B)

when the user choose one of these two links, he will go to the registration page and after filling the form, he will be registred and automatically get the role (A) or (B) pursuant the link chosen above

the problem is: how can I pass the info of what choice the user has chosen (first or second link) to the registration form.

I thought to pass it inside the request URI and then get it via `$_GET` but Is there another solution wihtout showing any query to the user in the URL ?

Thanks in advance.

# Answer
Well you can make small form with 2 submit buttons (Register as A, Register as B) and post that data on register form, in this way you can hide it from url

OR

The other way which is more complicated, using ajax, when link is clicked and based on the clicked link you create the $form\_state and set the flag then you call the register from using drupal\_get\_form and you pass the argument

OR

Just create boolean field in user, and put the option (Register as A, Register as B) and make it required to be listed in register from
> 0 votes

# Answer
I will use the Drupal form API to create a module for this. These two forms has to be different and will use the `user_save` function to create new user account and will assign role.

```
$myuserroles[] = 'newrole';
user_save($myuser, array('roles' => $myuserroles));

```
> 0 votes

---
Tags: 7, users
---


# Question
Title: How to add new component type in webform?
I want to add a reset component type to a webform. Is there any contributed module available? if not suggest me how can I achieve this through code.

# Answer
I got answer for my question from this link, Hope this will help somebody who have same requirement. follw this link.
> 2 votes

# Answer
You can add below markup on the webform to create a reset form button:

Component type: **Markup**

Value:

```
<input type="reset" value="Reset" id="reset-button">

```
> 0 votes

---
Tags: 7, entities, webforms
---


# Question
Title: How to translate the search block title?
In Drupal 8.1.1 I am able to translate customs block and basic blocks (block type).

The search block seems not to be translatable. But I need to translate the title of the standard search block. I can not find a way to do it. Words like "Search" are translated in all languages but the search block title gets not translated.

# Answer
> 4 votes
This is configuration translation. You have to enable the module with this name and then go to block layout, configure a block and click on the tab "Translate block":

```
/admin/structure/block/manage/mytheme_search/translate

```

---
Tags: 8, blocks, search
---


# Question
Title: How to set transactional email api key for external app in drupal like mandrill
Like mandril,I have app for routing system transactional mails through that.I got create account in that app and getting api key for my drupal site,But i dont know how to process it (where to add that api key to configure it)on drupal to send mail.please clarify.

# Answer
Assuming you're using the Mandrill module, the API key can be configured at this path:

**/admin/config/services/mandrill**
> 1 votes

# Answer
Send your transactional emails from Drupal using Pepipost, you may use the SMTP Authentication Support module or the Swift Mailer module depending on your needs.

Ref: http://support.pepipost.com/knowledge\_base/topics/drupal
> 0 votes

---
Tags: emails
---


# Question
Title: Limit node.js updates if the view is active
I have a Facebook style news feed view which updates via *node.js* and *rules* when new content is created. This all works fine however if one user is in the process of commenting on a node teaser (comments shown on node teasers on the view) and another user creates a new node, the view then updates causing the unfinished comment to be lost.

My question is: is there a way to restrict the node.js view update for the current user if the view is currently active?

# Answer
I had and just have the same problem with node.js views update. It seems that the module is refreshing every view that's in use.

I managed to get a workaround by styling my news feed with an open comment section. But i think this is only a solution when you do not expect a hughe amount of comments.

In another use case I implemented another workaround with jQuery:

On my page users can create requests and other users are able to answer these request. A request is a node type and an answer is a node type. They are connected through entity reference module and i wanted to have some sort of inbox functionality where every answer to a specific request is shown in a menu on the specific request page. A user could then click on a answer-menu-item and the whole answer is shown under the request. To give it a more chat feeling I implemented the comment form of the specific answer and styled it to look like a chat form.

This is done with two views implemented on that page. The menu functionality is done with jQuery (Click on menu item -\> show related views row of second view). With node.js views refresh I managed to get the chat feeling (When a new comment is added -\> refresh first and second view).

I then ran into the same issue like you described above. Each time a user submitted a new comment both views refreshed but the views returned to the their output states - for example: the user was reading an answer of user G and was commenting on that answer when the view was refreshing because of a new comment on an answer of user Y. The view returned to its output state and was not showing any answer because they were initially hidden to achieve the inbox / menu functionality.

My workaround for that problem is:

```
var content = [the views-row belonging to the menu entry]
$(specific-menu-item).click(function(e){
    $(".my-second-view .views-row").hide();
    $(content).show();
    Cookies.set('latest-viewed-answer', content);
    return false;
    e.preventDefault();
});

$(document).ajaxComplete(function() {
  var latest = Cookies.get('latestmessage');
  $(".my-second-view .views-row").hide();
  $(latest).show();
});

```

To get the Cookie thing working https://github.com/js-cookie/js-cookie

Sorry for my long answer, but i thought that it would be necessary to understand my needs to understand my workaround...

Because this is still a workaround and because I'm asking myself if there will be performance and server issues with our approaches (news feed and chat) I would love to see a solution that is really solving the problem.
> 0 votes

---
Tags: 7, views, comments, nodes, nodejs
---


# Question
Title: How do I send email to a large number of users?
I have a scheduled rule to send a HTML email, using a view to list the email addresses.

I tested this based on a couple of users ; everything worked as expected. When I increased the number of emails to around 1400, I found that half the users received the email, over and over again.

I also noticed that when I manually run cron, the page times out.

I can't see any error messages, but these may have been cleared.

Could anyone explain why this is occurring? I'm confident that everything was working before I increased the number of users.

# Answer
Use the Mail Chimp module to integrate with MailChimp. This is a popular email external delivery service.

> The module makes it easy for website users or visitors to control which of your email lists they want to be on (or off), lets you generate and send MailChimp email campaigns from your site, and lets you and your users view a history of emails they have been sent from MailChimp. More generally, it aspires to makes your email delivery world efficient and to make your user's email receipt and control simple and precise. Thanks to MailChimp's ongoing sponsorship, this module is actively maintained and regularly adding features.

A tested, working solution can be found on on http://azadnegar.com.
> 0 votes

# Answer
The Mandrill module (combined with the Mandrill service) lets you send transactional emails (and, theoretically, bulk emails) very quickly. It has a built-in queue feature which adds outgoing emails to a cron queue.

Note that the Mandrill service requires you to build up a reasonable sender reputation before you can send many emails at the same time - there are hourly limits that increase automatically. And of course it can cost money.

The Queue Mail module is a general-purpose solution to queue outgoing emails, if you don't want to run Mandrill or other modules that have their own queueing.

Regarding cron: Drupal's built-in cron triggers all repeating tasks to run at once, which means it can be very slow for complex sites. Many cron tasks don't need to run that often, and many of them shouldn't run often (for example, the system cron clears caches, which can really slow down the site).

So you can use the Elysia Cron module to manage cron jobs more effectively: it allows you to separate tasks so that the ones that are fast and need to be frequent (such as Mandrill cron) run say every minute, while the ones that are slow (such as system cron) run every week.

The Ultimate Cron module is an alternative to Elysia Cron - I haven't used it recently so I'm not certain that it works well.
> 2 votes

# Answer
Sending e-mails is slow. Always was, always will be. What more, anti-spam techniques deliberately makes it even slower. It is specifically designed that way to discourage mass mail sending in one huge package, because even if mails like that happen to be legitimate, they are huge strain for receiving servers and could potentially work like DoS attack.

Timeout will only log to server's error log. By the very nature it cannot log to Drupal's one, because when it happens Drupal's script is dead and cannot do a thing. That's why you will not see a thing logged in watchdog reports.

One solution is to simply hire others to take the problem. MailChimp is easily integrated with Drupal, and at least for now, free for up to 2000 recipients. I'm sure there are many competitors, too.

Other way is to set up sending server locally. Then be sure it has mass sending prevention methods turned off and accepts connections from localhost only. Use SMTP Authentication Support to push all mails into it. Then script should work much faster, hopefully without timeouts.

Using Batch API to send mails might work, but would require a lot of custom coding and mails could not be triggered by regular users - you don't want regular user to see "your action triggered mass mailing, sending to 451 users", and hope he will wait patiently without closing browser.
> 0 votes

# Answer
If your emails are transactional/triggered in nature,then Pepipost can be a best fit.

To send emails from Drupal using Pepipost, you may use the SMTP Authentication Support module or the Swift Mailer module depending on your needs.

Ref : http://support.pepipost.com/knowledge\_base/topics/drupal
> -1 votes

---
Tags: views, emails, rules
---


# Question
Title: How to show/hide a block at some content types using PHP filter?
I want to show/hide my block at some content types so I'm using PHP filter. My code in block configuration is:

```
<?php
if(arg(0)=='eshop') { return true; }
if(arg(0)=='node' && is_numeric(arg(1)) {
  return false;
}
return false;
?>

```

With this code the block is visible at every page even if it returns false, even if arg(0) is 'node' and arg(1) is 170. But if I use only:

```
<?php
if(arg(0)=='eshop') { return true; }
?>

```

It will show the block corectly only at `/eshop` page.

What is this, a GIANT Drupal bug?

# Answer
> 2 votes
There is another alternative available ... ***which doesn't require the PHP filter to be enabled*** (which you should try to avoid whenever possible) ... Just use the Rules block visibility module. Here is a quote from its project page:

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

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules "***check the path of the current page***" (so that the block is only shown for the page with an URL like `/eshop`).

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?".

# Answer
> 1 votes
Use PHP Code to filter, the content type and specific pages. This code shall work on node pages, although you can use any code to filter accordingly.

```
<?php
if (arg(0) == 'node' && is_numeric(arg(1)) && !arg(2)) {
  $node = node_load(arg(1));
  if ($node->type == 'YOUR_CONTENT_TYPE_HERE') {
    return TRUE;
  }
  elseif (PUT ANOTHER CONDITION HERE (for specific pages)) {
    //return TRUE here also
  }
  else {
   return FALSE;
  }
?>

```

# Answer
> 0 votes
Nope it is not a bug, if you are using `arg()` it will always consider the original path, that means `node/[nid]`

Your `/eshop` is an alias of `node/[nid]` so the Drupal will use original path for `arg()`

If you want to use `/eshop` then use `if($_GET['q'] == 'eshop') { return true; }`

# Answer
> 0 votes
Why use PHP filter when you can configure your block using the UI.

# Answer
> 0 votes
If you want to show your block to particular content type then you can set your Visibility settings by your content type .Please find the screenshot.

---
Tags: blocks
---


# Question
Title: How to setup a Facebook page block for each user?
Is it possible to setup Facebook block for each user? When a user registers or later in specific node he can copy/paste a link in text field that will result in his Facebook page block.

I know how to setup views contextual to show block for each user based on user's id or nid, so that part is covered.

# Answer
I'm presuming you want to do something like a Facebook Likebox embedded iframe (e.g. https://www.facebook.com/plugins/likebox.php?my\_user\_facebook\_page\_details...) with the user supplying his own URL in his user account profile.

If that's the case set up your block view to render your user's URL field with a custom template. Under the Views UI in **Advanced \> Other \> Theme**, the **Information** link will give you a list of template names (e.g. **views-view-field--field-my\_user\_field.tpl.php**) that you can put in your theme's template directory and some boilerplate code (found via the link next to the template names). You can alter the template such that the `$output` is wrapped in a iframe `src` attribute.

Flushing the cache should rebuild everything so that your block's URL field now renders as an iframe on the user page (if you've configured your contextual filter correctly). It probably should be noted that rendering a user-supplied iframe URL is dangerous so you probably should be filtering out non-Facebook URLs.
> 1 votes

# Answer
Here are the steps that I think should help to create such block:

* Define an appropriate text field containing the link within the user profile, and make it optional.
* Use the Views module to create a list of users.
* Format the view as a block (not as a page).
* The only field to be shown is your text field containing the link.
* Add a contextual filter to limit the results to the `uid` of the currently logged in user.
* Since there should only be 1 record selected, there is no need for any sorting.
* Place the block wherever it fits on your page(s).
* If needed, adapt the block visibility settings to fit your needs. Optionally use the Rules Block Visibility module to refine the logic about when to yes/no display the block (eg: if the profile field is empty, then don't show the block).
> 0 votes

---
Tags: 7, views, social-network
---


title: Remove fields from dialog window

text:
# Question
Title: Remove fields from dialog window
How can I remove fields from the CKEditor dialog window? In my case, I need to remove the "Caption" field from the "Table Properties" window. How can I do that?

# Answer
The solution is simple: remove the caption tag from the allowed HTML tags in "/admin/config/content/formats" :-)
> 0 votes

---
Tags: 8, wysiwyg
---


# Question
Title: How to fix a field with unlimited values where the "Add another item" is broken?
I am working on Drupal 7.43.

I have created a few months ago standard fields (text) with unlimited values. Everything was fine.

Today, I can not **add another item**, the Javascript icon is turning and then nothing happens. Surprisingly, it works on a local version. The weirdest thing is when I use a fresh field, created for test, everything works fine and I can have multiple values added.

In recent log messages, I have an AJAX warning : Invalid form POST data. (EDIT : this warning message is not displayed each time I try to add another item.)

I have tried many different things (jQuery Update configuration, new theme, deactivation/reactivation of modules, cache flushing...).

Does anyone know if I could fix my "broken fields" so I can still use them instead of creating new ones and cloning all the values already entered? Thanks in advance.

A similar issue here

EDIT (05/09/16) :

Looking at the Firebug Console, in JSON tab, I have just noticed that 2 lines are missing, compared to my localhost version, where the function works fine. The lines missing :

* Object {command="add\_css"...}
* Object {command="insert", method="prepend", selector="head"...}.

Seems important? Any way to get these lines on the production website?

# Answer
After many different tests, I have found the solution.

All the multi-value core fields using the module "Better Field Descriptions" were broken.

The help text added below by this module seemed to block the new option line to be created or at least displayed. Deactivate the module fixed the problem.

So, if you need a multiple values field and a permission to edit the help texts, be cautious with module interactions.

Thanks for those who tried to help me on this issue.
> 0 votes

---
Tags: javascript, ajax, entities
---