# Question
Title: How to delete file using drupal_form_submit?
I'm using rest services with a custom resource on node update, i want to build the correct variable node structure to delete one of the files on a file image multiple fields. I removed the file element from the `form_state['values']` but isn't working. I know i can do it manually but is it possible altering `form_state['values]` ?

# Answer
You can use this code in your form submit function

```
$file ='public://not_imported_longanswer.csv';
$path = $base_url . '/sites/default/files/not_imported_longanswer.csv';
if (file_exists($file)) {
    file_delete($path);
}

```
> 0 votes

---
Tags: forms, files, services
---


title: View page is taking lot of time to load

text:
# Question
Title: View page is taking lot of time to load
I have developed an application using Drupal 7, where I have created views and it has lots of data. Now its taking lot of time to load the page and all users are complaining about this issue.

Can anyone please help me to resolve this performance issue? I will be very thankful if someone answer to my question.

Thanks in advance.

# Answer
### Install and use Views Litepager

> Though this pager may appear similar to View's "Mini Pager" option, it is functionally different in a very important way. **The Views Litepager module solves a problem of scalability for sites with large amounts of content.** Drupal's core pagination system creates a pager navigation that shows exactly how many pages of content exist for the content list. This requires that a COUNT query be executed based on the query used to generate the list.

### Enable Caching

### In Drupal Performance settings

Enable aggregate css and js.
> 1 votes

---
Tags: 7, views, performance
---


# Question
Title: How to login into Drupal 8 using the REST API?
Ok i've spent my whole afternoon trying to get this running:

* Setup a freshly installed Drupal 8
* Activate the WebServices (HAL, HTTP Basic Auth, Restful Webservices, Serialization)
* Install REST UI Module
* Activate the REST Module for e.g. /user/{user} under Configuration -\> Web-Services -\> REST (i'm activating GET/POST with json and basic\_auth)
* Fix the permissions so all "authenticated user" can access the Restful Webservices for User content

I basically followed this tutorial to get there: https://drupalize.me/blog/201401/introduction-restful-web-services-drupal-8

Then i go forward and create a POST call looking like this:

```
GET http://{my-host}/user/testing

// with following headers obj
{
  'Authorization': 'Basic dGVzdGluZzptYXN0ZXI=',
  'Content-Type': 'application/json'
}

```

Well, the user "testing" really exists, i've checked this like 100 times. The Basic Authorization user i'm giving him (i obfuscated the data here since it is still plain text base64) - believe me, it is a correct credential too, even from the admin user.

The path is correct too with /user/{user} - but he is *always* returning a 404 Not Found ...? Why?

Well what i try to achieve is a login trough a REST API call - so i can login with an existing drupal user from an external system (auth0). As far is i understood from the docs this should all be possible with the /user/{user} endpoint - but i'm totally unsure because i couldn't find any working examples for it.

# Answer
`'Content-Type': 'application/json'` **needs to be** `'Content-Type': 'application/hal+json'` in order for it to work.

I recommend you watch these video tutorials

Learn Drupal 8 - REST API Part1

Learn Drupal 8 - REST API Part2

The login is covered in part 2, but part 1 is very informative and part 2 will make more sense if you watch part 1.

Although, the video tutorial uses the Google Chrome Postman add-on, your code needs to do the same.

1. Have a header with the *Content Type* and *Authorization* values
2. > `GET http://{my-host}/user/testing`

Your URL to POST, GET, or PATCH shouldn't be your user page, unless you want to work with the user fields. The URL needs to have the entity you are working with.

For example: See the url's used in the video tuts.

You can even use Postman to generate your code

**HTTP Generation**

```
PATCH /node/1 HTTP/1.1
Host: forexample.com
Content-Type: application/hal+json
Authorization: Basic Q2FtaWxvOmNvY29saXNa
Cache-Control: no-cache // delete
Postman-Token: 3803eeac-0dc2-5c09-05e1-40d15d5b9820 // delete

{
"title": [
{
"value": "The title changed, WOOOHOOO!!!"
}
],
"type": [
{
"target_id": "article"
}
],
"_links": {
"type": {
"href": "http://forexample.com/rest/type/node/article"
}
}
}

```

**PHPV1 generation**

```
<?php

HttpRequest::methodRegister('PATCH');
$request = new HttpRequest();
$request->setUrl('http://forexample.com/node/1');
$request->setMethod(HttpRequest::HTTP_METH_PATCH);

$request->setHeaders(array(
  'postman-token' => '9656f5e8-13a5-0e2b-23cb-5ac03af59b5b', // remove this line
  'cache-control' => 'no-cache', // remove this line
  'authorization' => 'Basic Q2FtaWxvOmNvY29saXNa',
  'content-type' => 'application/hal+json'
));

$request->setBody('{
"title": [
{
"value": "The title changed, WOOOHOOO!!!"
}
],
"type": [
{
"target_id": "article"
}
],
"_links": {
"type": {
"href": "http://forexample.com/rest/type/node/article"
}
}
}');

try {
  $response = $request->send();

  echo $response->getBody();
} catch (HttpException $ex) {
  echo $ex;
}

```

You can also generate for other languages like Python, jQuery, PHP Curl to name a few.
> 0 votes

---
Tags: 8
---


title: Counterup JS to work

text:
# Question
Title: Counterup JS to work
According to Counter Js**Include**

```
<script src="http://cdnjs.cloudflare.com/ajax/libs/waypoints/2.0.3/waypoints.min.js"></script>
<script src="jquery.counterup.min.js"></script>

```

(I've defined the library in the theme.libraries.yml and attached the library in the theme.info.yml and it shows in the header)

```
statcounter:
 version: 8.x-1.0
js:
 scripts/jquery.counterup.min.js: { minified: true }
dependencies:
 - core/jquery

```

**HTML**

```
<span class="counter">1,234,567.00</span>
<span>$</span><span class="counter">1.99</span>
<span class="counter">12345</span>

```

(Have added this in a block in the front page and the markup is displayed)

**jQuery**

```
$('.counter').counterUp(); **or with extra parameters**
$('.counter').counterUp({
delay: 10,
time: 1000
});

```

(Have placed the jquery in a separate custom js; and defined it in the theme, the js is loaded and no errors till now)

```
   custom:
    version: 8.x-1.0
   js:
    scripts/custom.js: {}

```

I want to attach the last bit of jquery to the theme and make the counter work...Any ideas how to get it to work? Thanks.

# Answer
> 2 votes
Make sure all files are present !

The drupal way for custom js in your theme is a behavoir, so your js file should look like this:

```
    (function ($) {
      Drupal.behaviors.myThemeBehavior = {
        attach: function (context, settings) {
           $(context).find('.counter').once('myThemeCounter').counterUp({
             delay: 10,
             time: 1000
           });
        }
      };
    })(jQuery);

```

This will ensure the script is executed after the DOM is loaded and only will run once.

---
Tags: theming, 8
---


# Question
Title: How to call functions from another module in hook_language_negotiation_info()?
I am writing a new custom module which is dependent on geoip module. I'm trying to add another language negotiation in the language detection configurations which would trigger a callback function defined in the module. Now How do I call the function defined in geoip.module file? I tried calling the function directly and after a module\_load\_include and both do not work.

```
/**
 * Implement hook_language_negotiation_info
 */
function my_module_language_negotiation_info() {
  return array(
      'geoip_language_provider' => array(
          'callbacks' => array(
              'language' => '_my_module_language_callback',
          ),
          'file' => drupal_get_path( 'module', 'my_module' ) . '/my_module.module',
          'weight' => -4,
          'name' => t( 'My Module GeoIP Negotiation Provider' ),
          'description'=> t( 'This redirects the user to correct language based on their IP.' ),
          'cache' => 0,
      ),
  );
}

function _my_module_language_callback() {
  module_load_include( 'module', 'geoip' );

  //Returns array of languages based on country code. Eg. array( 'CN' => 'zh-hans',)
  $languages = _my_module_language_mapping();
  $country_code = geoip_country_code();
  $default_langcode = language_default( 'language' );

  if( !isset( $languages[$country_code] ) ) {
    watchdog( 'geoip_language', 'The country code is not in the language mapping.' );
    return $default_langcode;
  }

  return $languages[$country_code];
}

```

# Answer
Not sure if this is the correct reason for this behaviour or not but it seems like the language negotiation process runs before the modules and the themes are bootstrapped in Drupal which would explain why the function is not available by default.

Changed the module\_load\_include to actually include the file directly by calling drupal\_get\_filename and requiring the file and it worked.

```
function _my_module_language_callback() {
  $geoip_file = drupal_get_filename('module', 'geoip');
  if( file_exists( $geoip_file ) ) {
    require_once DRUPAL_ROOT . DIRECTORY_SEPARATOR . $geoip_file;
  }

  $languages = _my_module_language_mapping();
  if( function_exists( 'geoip_country_code' ) ) {
    $country_code = geoip_country_code();
  }
  $default_langcode = language_default( 'language' );

  if( !isset( $country_code ) ) {
    watchdog( 'geoip_language', 'Country Code could not be identified by IP.' );
    return $default_langcode;
  }

  if( !isset( $languages[$country_code] ) ) {
    watchdog( 'geoip_language', 'The country code is not in the language mapping.' );
    return $default_langcode;
  }

  return $languages[$country_code];
}

```
> 1 votes

# Answer
First you have to read the module documentation to see if It provide a way to use It's own functions and instructions on how to use them. Also, you have to check if the function you're calling is in that module or in another file (for example, an inc file). If the function is in an inc file you can call it with something like:

```
module_load_include('inc', 'geoip');
// this cals geoip.inc

```

or like

```
module_load_include('inc', 'geoip.field');
// this cals geoip.field.inc

```
> 0 votes

# Answer
Your language negotiation callback is called from `drupal_bootstrap()` before Drupal is completely bootstrapped; as such not all the enabled modules are loaded. In fact, it is called during the `DRUPAL_BOOTSTRAP_LANGUAGE` phase, which is right before the `DRUPAL_BOOTSTRAP_FULL` phase.
You just need to use `drupal_load()` to load the module file as `drupal_load('module', 'geoip')`.

Keep in mind that your language negotiation callback is also called from authorize.php, via `drupal_initialize_language()`, the same function used from `drupal_bootstrap()`. If you are going to load that module in your language negotiation callback, be sure it works also when autorize.php is used from Drupal, which means when installing a module from the user interface, for example.
> 0 votes

---
Tags: 7, hooks, i18n-l10n
---


# Question
Title: Is there way to export block layout settings?
I created a custom theme and I was wondering if there is way to export my block layout settings (location and order of each block). This way will be easier to apply my theme in a different site.

I'm using the Features module to keep on track of my custom blocks and block types.

# Answer
This question is about D8, for which you can use an approach as suggested in the comment from Ivan Jaros, i.e.:

> ... enable config core module and export the blocks (they are basically just instances of blocks) via `admin/config/development/configuration/single/export` and put them into your theme's config/install directory.

What not everybody may know, is that this kind of block related facilities that are new in D8, is actually because of the Bean module which has been included with Drupal 8 core (refer to this issue for more information).

This implies that a similar question for D7 can be resolved also by using the Bean module. Here is a quote about its project page:

> Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

This module also works great in combination with the UUID and UUID Features Integration modules. And after you become familiar with the Bean module, you might find other cases in your site where you also want to use this module (which somehow compensates the fact that you need to add another module).

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.

This module only started as of D7 (because of the "entities" of course that were only introduced in D7), and already has over 22K reported installs. Those who don't use it yet (in D7) should definitely start looking at it in preparation of some day upgrading to D8.
> 1 votes

---
Tags: blocks, 8, features, theming
---


# Question
Title: multiple values of several fields grouped together
I am using drupal 7 as a backend, in which I have a content type called conferences, and each conference has several events. I do not want to create another content type for events and would want to add them to the same content type as each event has only two fields the date and the venue. How can I achieve this using UI as CMS ? and then later be able to make API's to send the same. Please suggest modules to achieve the same

# Answer
> 1 votes
You should look at `field_collection` module. It allows you to create a field, and add fields to that field (behind the scenes it's using entities).

A typical use case, is if you want user to enter multiple sets of data, like fx

* name
* image
* url

To achieve this, you would create a field\_collection field on the node or what you want this on and set the cardinality to the limit. Then on the field collection you would add the name, image and url fields. It's also possible to configure some fields to be required and other to be optional.

---
Tags: 7
---


title: What does "dynamic permissions" mean?

text:
# Question
Title: What does "dynamic permissions" mean?
What does *dynamic permission* mean, in Drupal 8?
When should I use this?

# Answer
In Drupal 8, the permissions a module defines are defined in a .permissions.yml file (such as the user.permissions.yml file used from the User module), which doesn't contain PHP code. As such, those are static permissions because they don't depend from any runtime condition, such as the node bundles defined from modules, the user roles present in the site, or the input filters implemented by modules.

Dynamic permissions are those permissions that depends from runtime conditions. For example, the Node module defines a set of permissions for each node bundle defined from modules. They cannot be statically set because the number and the type of node bundles can change from site to site.

In this case, Drupal allows to define in the .permissions.yml file a list of methods that return a list of extra permissions. This is what done, for example, in node.permissions.yml and filter.permissions.yml, where you find the following line.

```
permission_callbacks:
  - Drupal\filter\FilterPermissions::permissions

```

If you look at the code for `Drupal\filter\FilterPermissions::permissions()`, you will see how easy defining new dynamic permissions is: Return an array containing the *title* and *description* keys, keyed by the permission name.

```
  foreach ($formats as $format) {
    if ($permission = $format->getPermissionName()) {
      $permissions[$permission] = [
        'title' => $this->t('Use the <a href=":url">@label</a> text format', [':url' => $format->url(), '@label' => $format->label()]),
        'description' => [
          '#prefix' => '<em>',
          '#markup' => $this->t('Warning: This permission may have security implications depending on how the text format is configured.'),
          '#suffix' => '</em>'
        ],
      ];
    }
  }

```
> 3 votes

# Answer
I consider it generating permissions based on some data within your site.

For instance, I wanted to create permissions based on terms or vocabularies for roles, in regards to if they could use the functionality a contrib module I maintain provides:

http://kevinquillen.com/drupal/2016/02/21/dynamic-permissions-in-drupal-8

If you look at the NodePermissions class, it does something similar.
> 4 votes

---
Tags: 8, users
---


# Question
Title: How to disable auto submit on value change in date_popup form?
Is there a quick way how to disable auto submit on value change in date\_popup forms?

Thanks.

# Answer
Add 'event' =\> 'submit' in #ajax' =\> array()
> 1 votes

---
Tags: datetime
---


title: Search API highlight

text:
# Question
Title: Search API highlight
using the search API module I highlighted the search text. Key words take the whole width of the block, how to insert them in the text? my current setup is:

Highlighting prefix : `<p class="views-highlight">`
Highlighting suffix : `</p>`

CSS: `.views-highlight {color: black; background-color: yellow;}`

my search results

# Answer
> 0 votes
You should not be wrapping your keywords in **p** tags. **P** is a block-level element, and that is why it stretches 100% width of your container.

Use **mark**, **span** or any other inline-level element instead.

---
Tags: views, search
---


# Question
Title: How to add jQuery Datepicker option which accepts a function as an argument
I have added a date\_popup field to a form :

```
$form['arrival_date'] = [
  '#type'                => 'date_popup',
  '#title'               => t('Arrival date'),
  '#date_format'         => 'd/m/Y',
  '#date_year_range'     => '0:+1',
  '#date_label_position' => 'none',
  '#default_value'       => '',
  '#size'                => '10',
];

```

I want to add an option to run a function using the onClose option so my js is :

```
(function ($) {

  Drupal.behaviors.ios2 = {
    attach: function (context, settings) {
      $('#edit-arrival-date-datepicker-popup-1').datepicker('option', {
        onClose: function (date) {
          // date will have the new date or empty string if no date
          // has been selected.
          alert(date);
          // Do something
        }
      });
    }
  };

})(jQuery);

```

However the onClose event never executes. If I remove the 'option' argument thus :

```
$('#edit-arrival-date-datepicker-popup-1').datepicker({

```

it does work, but my suspicion is that it is replacing the datepicker with a new one, rather than altering the existing options.

# Answer
> 0 votes
You have to ommit the 'option' parameter, the following modified version of your code worked for me:

```
(function ($) {

  Drupal.behaviors.ios2 = {
    attach: function (context, settings) {
      $('#edit-arrival-date-datepicker-popup-1').datepicker({
        onClose: function (date) {
          // date will have the new date or empty string if no date
          // has been selected.
          alert(date);
          // Do something
        }
      });
    }
  };

})(jQuery);

```

---
Tags: javascript, datetime
---


title: Theme CSS won't load in a D8 theme

text:
# Question
Title: Theme CSS won't load in a D8 theme
I'm creating a new D8 theme and am having trouble making Drupal load the CSS that is a part of my theme. I have disabled cache and am sure I'm getting the up-to-date output.

Here's my **mytheme.info.yml:**

```
name: Mytheme
type: theme
description: 'This is a description.'
core: 8.x

libraries:
  - mytheme/global-styling

libraries-override:
  system/base: false

regions:
  header: Header
  content: Content  # the content region is required
  menu_primary: 'Menu - Primary'
  menu_secondary: 'Menu - Secondary'
  footer: Footer

```

Here's **mytheme.libraries.yml**

```
global-styling:
  version: 1.0
  css:
    theme:
      css/global.css: {}

```

and this is the top of my **html.html.twig** file:

```
<!doctype html>
 <html lang="en">
 <head>
   <title>{{ head_title }}</title>
   <head-placeholder token="{{ placeholder_token|raw }}">
   <css-placeholder token="{{ placeholder_token|raw }}">
   <js-placeholder token="{{ placeholder_token|raw }}">
   {{ page.head }}
   {{ page.styles }}
   {{ page.scripts }}
</head>
...

```

The content in the YAML files is not tabbed, spaces are used.

I already spent several hours trying to figure out what's wrong and why the global.css is not being linked in the header of the html page, but I have no idea. I'll be gratefull for any help.

EDIT: I found out that my CSS do load when I use this:

```
{{ attach_library('mytheme/global-styling') }}

```

but I thought the point of referring to global-styling inside mytheme.info.yml was that I don't have to do that. Did I understand that correctly?

# Answer
Try this. I am using this in my base theme, and it works:

```
global-styling:
  version: VERSION
  css:
    base:
      css/YOURCSSFILE.css: {}

```
> 0 votes

---
Tags: theming
---


title: Drush make and multisite

text:
# Question
Title: Drush make and multisite
I am building a multisite and each sub-site may have its own contrib modules.

For example: sites/all/modules/contrib/entity sites/site1/modules/contrib/views sites/site2/modules/contrib/services

I build a makefile for the shared modules:

```
api = 2
core = 7.x
projects[entity][] = ""

```

And one makefile per subsite which includes the global makefile:

```
includes[] = "make.yml"
projects[views][] = ""

```

The inclusion works properly but I can't get the modules being downloaded in different directories.

I try to run the drush make command with *--contrib-destination=sites* option, add *defaults\[projects\]\[subdir\] = all/modules/contrib* in the global makefile and to specify a subdir for each sub-sites's specific module *projects\[views\]\[subdir\] = "sites1/modules/contrib"*. No luck, the modules are downloaded in *sites/modules/all/modules/contrib* and *sites/modules/site1/modules/contrib* instead.

Is there any way to get it working? I now think to add some custom code to a script to run after the drush make command to move specific modules to proper directory.

Thanks,

# Answer
> 2 votes
By checking the drush code itself, we discovered the possibility to add contrib\_destination on specific project level.

```
projects[views][] = ""
projects[views][contrib_destination] = "sites/site1"

```

However, as it would had quite a lot of lines to the makefile (we must add the contrib\_destination line to all modules used by site1 only) we decided to not use the includes feature and to keep to separate makefiles.

To build our docroot, we then have one "global" makefile to prepare the sites/all modules and another ones for each subsites (sites/site1). Then we launch the drush make command for each makefile (using a shell wrapper to handle it).

This is not perfect and would probably be easier to have something build-in (I don't know what would be the best syntax for that).

---
Tags: drush, multi-sites
---


title: add a webform in a product checkout

text:
# Question
Title: add a webform in a product checkout
I would add a webform in the checkout step of a particular product. I need this feature because sometimes the products that i offer needs more information and sometimes the information that i need are different, so the webform that i should show could be change.

I would show the webform during the checkout, i don't want to have a webform that redirect to checkout (commerce webform module i think)

# Answer
> 0 votes
If you're needing product-related information, Commerce Custom Product would be the way to go. If you're needing order level information, then you can create order-level fields and expose during checkout using Commerce Fieldgroup Panes.

Finally, this post on drupalcommerce.org seems to elude to getting a webform to work within a custom pane.

# Answer
> 1 votes
As per my understanding of your question you should follow below steps:

1. Create a form using Webform and then in Webform \>\> Advance settings mark that webform as "Available as block".
2. Now you can see that webform as a block in Blocks page.
3. In block configuration you can set the option to display that block on specific page.

Let me know when you implement it.

---
Tags: forms, commerce, webforms
---


# Question
Title: Why are my custom fees disappearing from my orders?
I've set up my shop so that I am able to create an entire order programmatically. Line items register fine. However, I can't get fees to stick through the ordering process. I'm using the following code:

```
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$fee = 'machine_name_of_fee';
commerce_fees_apply($order_wrapper, $fee, 500, 'USD');
commerce_order_save($order);

```

I then push the order through to checkout so that I can manage it on the backend:

```
commerce_order_status_update($order, 'checkout_checkout');

```

I get no errors, but when I check the order in the admin backend, there are no fees that show up. I've double checked that the machine name is correct, and have even confirmed that the commerce fees module returns as 'empty' if the machine name doesn't exist. This leads me to believe that the fees are indeed being added, but that they are being removed at some point after a checkout stage. Is there a specific stage where fees have to be added in order to stick to and affect the order total? Am I implementing commerce\_fees\_apply() incorrectly?

# Answer
> 1 votes
You need to apply commerce fees after "checkout\_checkout" status and also move order to next status i assume "checkout\_review".

commerce\_fees\_apply() is a rule callback and you are calling it directly from your code.This function first removes all fee type line item and then adds add the same and expects values from rules config.

I tried this and it worked.

```
module_load_include('inc','commerce_fees','commerce_fees.rules');
$order = commerce_order_load(3);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$fee = 'test';
commerce_fees_apply($order_wrapper, $fee, 500, 'USD');
commerce_order_save($order);
commerce_order_status_update($order, 'checkout_review');

```

But curious to know why you are writing code for this.You can easily achieve this using rules.

# Answer
> 1 votes
```
function commerce_fees_commerce_cart_order_refresh($order_wrapper) {
$line_item_ids = array();

foreach ($order_wrapper->commerce_line_items as $delta =>   $line_item_wrapper) {
// If the line item is a fee remove it.
if ($line_item_wrapper->getBundle() == 'fee') {
  // Delete the line item, and remove it from the order.
  $line_item_ids[] = $line_item_wrapper->line_item_id->value();
  $order_wrapper->commerce_line_items->offsetUnset($delta);
}

```

}

```
// If we found any fee type line items...
if (!empty($line_item_ids)) {
// Then delete the line items.
commerce_line_item_delete_multiple($line_item_ids);
}

rules_invoke_event('commerce_fees_order', $order_wrapper);
}

```

This code is responsible for removing fee type line item on page refresh.So hook\_commerce\_cart\_order\_refresh is called on every page load and commerce fees module is using this hook to remove all existing fees attached to an order and applying the same using rules\_invoke\_event function.

---
Tags: commerce
---


title: Drag & drop files into drupal site?

text:
# Question
Title: Drag & drop files into drupal site?
Does anyone know of a module that allows to drag files from users computer into a target area in site (like in gmail or wordpress)? ideally this would work with Image and other modules to insert the file "correctly" into drupal, save uploader info and allow adding meta data for file (like in the wordpress media area).

# Answer
You might want to give the Plup Module a try. It allows you to modify your content types with a plup field for drag and drop uploads.
> 2 votes

# Answer
I've tried several solutions using the Media module with Plupload with drag and drop capability, but I have never gotten them to work the way I want. I don't like the way Media handles files and even though I can bulk upload them into the Media area, when I want to connect them to an individual node, I still have to select them individually with an awkward media browser. Not a fan.

However, I have been VERY pleased with Multiupload Imagefield Widget (requires: Multiupload Filefield Widget). It works with a standard Image field, no need to change your content structure or do anything weird. All you need to do is edit the Widget Type on your Image field and change it from Image to Multiupload.

It will let you use the standard Image field upload, but you'll be able to select multiple images at once and upload them all with one click.
> 3 votes

# Answer
Since October 2013, the dragndrop\_upload module has become available. (*Completely different* from dragndrop\_uploads recommended already.) At the current time, it seems to be the most sophisticated solution to me. Worked flawlessly for me, and can be styled very nicely.

Another alternative is dragdropfile. Did not test it though.
> 2 votes

# Answer
Questions a little old now but ..

http://drupal.org/project/dragndrop\_uploads gives you the ability to drop onto a node body textarea. I've not used it so dont know how well it works. Weather it provides all the functionality your after I dont know, but it seems to be the best option out there

Another thing - while no way near as 'snazzy' and not really what you after, just thought I'd mention you can also drag files onto the 'choose file' button. I am pretty sure this works on all sites providing you have a decent browser, and that is not just a Drupal thing.
> 1 votes

# Answer
For Drupal 8, there's an initiative to get this functionality into core. See File Field design update for details. Let's combine all of our efforts over there.
> 0 votes

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


# Question
Title: Sort content in a view by taxonomy term and use terms as headlines in drupal 8
Say I have a content type `books` and a taxonomy vocabolary `book categorys` i.e.

```
book categorys:
 - Novel
 - Short Story

```

Now, what I would like to display in a view is:

**Novel**

* Novel 1
* Novel 2

**Short Story**

* Short Story 1
* Short Story 2

I sure can make one block for each taxonomy term and filter by term, but I also create regulary new ones so that is not an good option.

# Answer
> 3 votes
To do this you need a **Taxonomy term** view with a **Content using field\_xxx** relationship.

Here are the steps needed:

1. Create a new view with **Show: Taxonomy terms of type: Book category** (or whatever your vocabulary is called).
2. Under **Advanced** settings add a Relationship of type **Content using field\_bookcategory**
3. Under **Fields**, Add a Content Title field to the view. A relationship to your field\_bookcategory should be automatically selected at this point.
4. You now need to group your results by taxonomy term. Do this under under **Format: Settings** and set **Grouping field Nr. 1** to **Taxonomy term: Name**
5. Lastly, you'll want to hide the term name in the results, since you're already displaying it in the group heading. To do this set the **Taxonomy term: Name** field to **Exclude from display**

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


# Question
Title: Drupal 7 Simple Ajax Module returning 404
I am trying to do a simple Ajax call in drupal 7. But i get a 404 not found. I tried with another drupal install and it worked.

Here is the list of the installed modules :

CKEDITOR, ctools, entity, field\_collection, field\_group, pathauto, references, token, wysiwyg

And here is the code :

```
function bookmark_ajax_menu() {

  $items['ajax-bookmark'] = array(
    'page callback' => 'bookmark_ajax_add_article',
    'access callback' => 'user_access',
    'type' => MENU_CALLBACK,

  );

  return $items;
}

/**
 *
 * AJAX FUNCTION FOR ADD ARTICLE
 */

function bookmark_ajax_add_article(){
   global $user;
           $user_name = $user->name;

   drupal_json_output($user_name);

}

function bookmark_ajax_init(){
    drupal_add_library('system','drupal.ajax');
    drupal_add_js(drupal_get_path('module', 'bookmark_ajax') . '/bookmark_ajax.js', array('scope' => 'footer'));
}

(function ($) {
  Drupal.behaviors.bookmark_ajax = {
    attach:function (context) {

      // If the site name is present set it to the username.
      $('document').ready(function(){
           $('body').load(Drupal.settings.basePath+'ajax-bookmark');
      });

    }
  };
})(jQuery);

```

# Answer
The first arg to `user_access` is mandatory, so you need to provide it in `hook_menu` via `access arguments`. The default for `access callback` is already `user_access` as it happens, so you can omit that:

```
$items['ajax-bookmark'] = array(
  'page callback' => 'bookmark_ajax_add_article',
  'access arguments' => array('access content'), // Or whatever permission makes sense.
  'type' => MENU_CALLBACK,
);

```

After you clear caches the page should be accessible.

Incidentally, you don't need to use `jQuery.ready` when you're inside a Drupal behavior `attach` method, as those are only ever invoked on DOM ready anyway.
> 0 votes

---
Tags: ajax
---


# Question
Title: Drush not seeing drushrc.php configuration file
I've got a new Red Hat 6.3 server running and Drush installed with a Drupal instance running.

Drush is installed via Pear and here's the output of "drush *sitename* status" in the Drupal install:

```
 Drupal version                  :  7.23
 Site URI                        :  http://<hostname>.org
 Database driver                 :  mysql
 Database username               :  <mysqluser>
 Database name                   :  <databasename>
 Database                        :  Connected
 Drupal bootstrap                :  Successful
 Drupal user                     :  Anonymous
 Default theme                   :  <themename>
 Administration theme            :  seven
 PHP executable                  :  /usr/bin/php
 PHP configuration               :  /etc/php.ini
 PHP OS                          :  Linux
 Drush version                   :  6.1.0
 Drush configuration             :
 Drush alias files               :/home/<username>/.drush/dev.aliases.drushrc.ph
                                p
                                /home/<username>/.drush/prod.aliases.drushrc.p
                                hp
 Drupal root                     :  /var/www/<sitename>
 Site path                       :  sites/default
 File directory path             :  sites/default/files
 Private file directory path     :  sites/default/files/private
 Temporary file directory path   :  /tmp

```

I have a drushrc.php files in sites/all/drush and but it's not registering, hence the blank entry in "Drush configuration" above. Whenever I run any drush commands on these sites, it just outputs the contents of the drushrc.php file.

I have the exact same codebase running on my local server (Kubuntu 13.04 with the same version of Drush) and it is recognizing the drushrc.php file so I'm assuming that it's not the file itself.

Drush, including all aliases, is working exactly as expected except for the screen output of the drushrc.php file mentioned above.

Here's the output of "drush -d status" running outside the Drupal install:

```
    Bootstrap to phase 0. [0.01 sec, 3.78 MB]                            [bootstrap]
    Drush bootstrap phase : _drush_bootstrap_drush() [0.01 sec, 3.98 MB] [bootstrap]
    Cache HIT cid: 6.1.0-commandfiles-0-068c4f324233e194887820ad3c8ded3a      [debug]
    [0.02 sec, 3.99 MB]
    Bootstrap to phase 0. [0.09 sec, 9.16 MB]                             [bootstrap]
    Found command: core-status (commandfile=core) [0.13 sec, 9.16 MB]     [bootstrap]
    Loading outputformat engine. [0.21 sec, 9.2 MB]                          [notice]
    Calling hook drush_core_status [0.21 sec, 9.25 MB]                        [debug]
    Returned from hook drush_core_status [0.21 sec, 9.25 MB]                  [debug]
    PHP executable        :  /usr/bin/php
    PHP configuration     :  /etc/php.ini
    PHP OS                :  Linux
    Drush version         :  6.1.0
    Drush configuration   :
    Drush alias files     :  /home/<username>/.drush/dev.aliases.drushrc.php
                              /home/<username>/.drush/prod.aliases.drushrc.php
    Command dispatch complete [0.21 sec, 9.29 MB]                            [notice]
    Peak memory usage was 11.19 MB [0.22 sec, 9.29 MB]                       [memory]

```

Any advice welcome.

# Answer
> Whenever I run any drush commands on these sites, it just outputs the contents of the drushrc.php file.

Make sure your `sites/all/drush/drushrc.php` has an opening `<?php` tag at the head of the file.

Also, you'll need to clear drush's cache when you add new site aliases.

```
drush cc drush

```
> 6 votes

# Answer
If you installed drush via composer:

`$ cp ~/.composer/vendor/drush/drush/examples/example.drushrc.php ~/.drush/drushrc.php
$ drush cc drush
$ drush status`

You should notice:

`Drush configuration : /home/<username>/.drush/drushrc.php`
> 3 votes

---
Tags: drush
---


title: Unique domain for each organic group

text:
# Question
Title: Unique domain for each organic group
Im trying to make it that each OG has its own URL eg. www.group1.com, www.group2.co.uk etc There was a module to do this apparently but not for D7. You'd think it streight foreward but it isnt. Probably due to path module. Everything I try gives me permission errors. Im using D7 and Cpanel. Any help would be really appreciated. Thanks Steve

# Answer
You can accomplish this with the Rules module, and the Domain Rules module.

> Adding Rules module actions related to Domain Access module. Allowing automation of different actions needed to create/modify/delete domains.
>
> First version includes:
>
> * rules\_action\_create\_domain - create new domain using given arguments
> * rules\_action\_delete\_domain - delete existing domain
> * rules\_action\_set\_user\_defaults\_domain - set a given role access to a given domain
> * rules\_action\_set\_node\_domain - set domain to a node
> * rules\_action\_set\_domain\_theme - set a theme to a given domain
> 4 votes

# Answer
I created GitHub project that provides a OG sub-module called OG Domain Access which does exactly this. It also allows you to override CSS/JS/Template suggestions per domain group. At the core of the module, hook\_node\_grants\_alter is used to prevent access to content that does not belong to the domain the user is logged into.
> 1 votes

# Answer
You could use the Subdomain module in its "one subdomain per organic group" mode, and then additionally provide DNS CNAME aliases from your domains to these subdomains that were assigned to the Organic Groups.
> 0 votes

---
Tags: organic-groups
---


# Question
Title: Manage 2 separate page cache for the same URI
We have a multilingual website build with Drupal 7.

We have a IP detection for detect Chinese users. Chinese laws do not allow the use of certain JS librairies. In our case, for one page, we use Google Map for all the users in the world, and we replace the library with Baidu Map for Chinese IP.

The problem is that if the first user is Chinese, then Drupal will cache the page with BaiduMap. Anonymous users from all the world will then have the page with Baidu Map even if there aren't Chinese (since it is the same URI).

We can detect if the IP is Chinese or not. So, how can we handle 2 separate page cache according to the user IP and then call the right cached page ?

# Answer
> 2 votes
This assumes that the theme is changing.

Settings.php file:

```
// Check if cookie is set.
if (!empty($_COOKIE['custom_theme'])) {
  // Add theme name to page cache id.
  $_SERVER['REQUEST_URI'] .= '#' . $_COOKIE['custom_theme'];
  // Set Theme.
  $conf['theme_default'] = $_COOKIE['custom_theme'];
}
// Disable page cache if cookie not set so hook_init code can set the cookie.
else {
  $conf['cache'] = CACHE_DISABLED;
}

```

hook\_init():

```
  // If no cookie is set set a cookie with the value of theme_default.
  if (empty($_COOKIE['custom_theme'])) {
    $temp = empty($custom_theme) ? variable_get('theme_default') : $custom_theme;
    setcookie('custom_theme', $temp, time() + 60*60*24*30, ini_get('session.cookie_path'), ini_get('session.cookie_domain'));
  }

```

---
Tags: caching, i18n-l10n
---


title: Generate form from XML

text:
# Question
Title: Generate form from XML
I have a standard form structure with fieldsets etc. I'm trying to populate my form into various nodes. This means that the same form will be displayed on more than one nodes. For every node, the form's fields will be enabled or disabled. This depends from XML files where it is described which fields will be enabled or disabled. This is a complex problem where i don't know how to start searching.

# Answer
> 0 votes
I'm not sure about D8, but for a D7 site I would read the XML file within a hook\_form\_alter() function, and use this to select enabled or disabled each form element depending on the rules set forth within the XML.

Of course as lovely, or convoluted as that sounds, it's a pretty nasty performance hit to show a form so caching would be important here.

I hope I understood your question correctly.

---
Tags: forms
---


# Question
Title: What is the alternative of hook_custom_theme in Drupal 8?
I need to change the theme based in custom criteria.

Some nodes should be displayed with one particular theme and others with the admin theme.

In D7 I could simply use the pathauto module and set the node url to **admin/\[node-title\]**. It works in D7 because all url starting in admin will use the admin theme in D7.

An alternative way to do the same thing would be to use the **hook\_custom\_theme()** function in D7. I did not find any similar function in D8.

# Answer
That is a service now. See `\Drupal\user\Theme\AdminNegotiator` for an example, which is registered as a tagged service:

```
theme.negotiator.admin_theme:
  class: Drupal\user\Theme\AdminNegotiator
  arguments: ['@current_user', '@config.factory', '@entity.manager', '@router.admin_context']
  tags:
    - { name: theme_negotiator, priority: -40 }

```
> 3 votes

---
Tags: theming, 8
---


# Question
Title: How do I get Search API to index rendered content including referenced nodes?
We are building av website in Drupal 8 where the content is divided into 3 content types;

* Basic Page, the scaffold for all visual pages like "About, Features etc."
* Content Block 1, for a layout with one text field and one image
* Content Block 2, for a layout with one text filed and two images

Nodes on Content Block 1 and 2 are referenced in on Basic Page nodes to enable different designs for each Page. This is done using a view block on Basic Pages.

Now, to the question:

Is there a way to set Search API to index only nodes on Basic Page, rendered with the content of referenced Content Block nodes?

I also need to exclude Content Block nodes from being indexed and showing up as nodes in the results, but that I have a grip on.

I hope my question is clear enough. Please comment otherwise and I will be happy to elaborate.

Thanks!

# Answer
> 1 votes
You should be able to traverse through the reference fields on the Search API Add Fields page. Then you want to add all the referenced text fields, so they become part of the main node. However, it is possible that Search API currently has some limitations there, it didn't show configurable fields for me when I tried something similar a few days ago. I'm sure that will eventually be fixed, though. There might be issues already.

PS: You might want to check out Paragraphs. It's a similar concept, with a much better editing experience, you can have different types of embedded content elements and edit it all in the same form. We're working on Search API integration right now and will also look into the problem mentioned above.

---
Tags: 8, search
---


# Question
Title: How to alter $form_state before render a form?
I want to render a **Custom Form** from a **Controller** class. So i've written the code like this

```
class MyController extends ControllerBase {

  public function content() {

    $form = \Drupal::formBuilder()->getForm('Drupal\MyModule\Form\CustomForm');
    return $form;
  }
}

```

but i want to put some values in $form\_state i.e. set #default\_values.
But here **$form** is a **renderable array**, not an **object** so there is no **$form\_state** object. So, what to set default values ?

# Answer
An edit form for what exactly?

getForm() accepts arguments. All additional arguments are passed to the buildForm() method of your form. So you pass whatever you are editing in, and when building the form, you get the current value and set it as #default\_value of the form elements.

If you are editing entities, then you should consider using an entity form. I'm maintaining the \_entityform\_block module, which has the following build() method in it's block, you could do something similar in a controller:

```
$values = array();
// Specify selected bundle if the entity has bundles.
if (\Drupal::entityTypeManager()->getDefinition($this->configuration['entity_type'])->hasKey('bundle')) {
  $bundle_key = \Drupal::entityTypeManager()->getDefinition($this->configuration['entity_type'])->getKey('bundle');
  $values = array($bundle_key => $this->configuration['bundle']);
}

$entity = \Drupal::entityTypeManager()
  ->getStorage($this->configuration['entity_type'])
  ->create($values);

if ($entity instanceof EntityOwnerInterface) {
  $entity->setOwnerId(\Drupal::currentUser()->id());
}

$form = \Drupal::entityTypeManager()
  ->getFormObject($this->configuration['entity_type'], 'default')
  ->setEntity($entity);
return \Drupal::formBuilder()->getForm($form);

```
> 4 votes

# Answer
I think you should use the same hook\_form\_alter as in D7. No need to alter the form in controller. FormBuilder::getForm returns renderable form array, not a Form API array.
> 1 votes

---
Tags: forms, 8
---


# Question
Title: Is it possible to make summary mandatory?
For a given content type is it possible to make creating a summary mandatory?

# Answer
**Short Answer**

Yes, you can require the summary field be populated before it can be sumbitted.

**Details**

Implement hook\_form\_FORM\_ID\_alter() in a custom module.

```
hook_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
   $form['body'][LANGUAGE_NONE][0]['summary']['#required'] = TRUE;
}

```

This assumes that you are taking the standard "body" field and requiring that it's summary be entered before submission.
> 3 votes

# Answer
I come after battle but you can have a look to the summary settings module : https://www.drupal.org/project/summary\_settings
> 3 votes

# Answer
Based on Citricguy's answer...

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function summary_required_form_form_id_alter(&$form) {
  // Make the field required.
  $form['body'][LANGUAGE_NONE][0]['summary']['#required'] = TRUE;
  // Remove the class from the wrapper class that triggers
  // the hiding of the summary input.
  $form['body'][LANGUAGE_NONE][0]['summary']['#prefix'] = "<div>";
  // Amend the help text.
  $form['body'][LANGUAGE_NONE][0]['summary']['#description'] = "Enter a short summary";
}

```
> 1 votes

# Answer
I was looking to do the same thing on Drupal 8 and after reading through this post and looking at the new documentation I was able to accomplish it.

I used `drupal_set_message($form_id)` to get my form ID. Then I used `hook_form_FORM_ID_alter`.

```
function hook_form_FORM_ID_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  $form['body']['widget'][0]['summary'] = array(
    '#type' => 'textarea',
    '#title' => t("Summary"),
    '#rows' => 3,
    '#attached' => array('library' => array('text/drupal.text')),
    '#description' => t("Enter trimmed value of full text."),
    '#attributes' => array('class' => array('js-text-summary', 'text-summary')),
    '#weight' => -10,
    '#required' => true,
  );

}

```

I'm fairly new to Drupal so I don't know if this is the correct way or if there's a easier solution. But this worked for me.
> 1 votes

# Answer
You could create a separate field on the content type for a summary, and enforce a minimum length so that the user is required to enter something. You probably then want to hide the trimmed output of the main body from the teaser view, and show the separate summary field only in teaser view.
> 0 votes

# Answer
Another solution would be to use the field\_validation module. You can assign a validation rule to the Body and select the 'Summary' column, and check the length of the entered value for example.
> 0 votes

---
Tags: 7
---


# Question
Title: Change image style during hook_node_view()
I'd like to programmatically change an image style during hook\_node\_view(), and I thought this would be relatively straightforward like so:

```
/**
 * Implements hook_node_view()
 */
function example_node_view($node, $view_mode, $langcode) {

  if (example_ok()) {
    $node->content['field_image'][0]['#image_style'] = 'new_image_style';
  }

}

```

Unfortunately this does not work. I'm aware of the picture and breakpoints modules, and am in fact using them, however there are sometimes when a dynamic decision needs to be made that these modules don't cover.

# Answer
> 3 votes
I hate to answer my own question, *but* this answer pointed me in the right direction. Here's the hook that worked in this case:

```
/**
 * Implements hook_preprocess_HOOK().
 */
function example_preprocess_image_style(&$variables) {
  if (example_ok()) {
    $variables['style_name'] = 'new_image_style';
  }
}

function example_ok() {
  global $user;
  // If the logged in user is bob, everything is ok.
  if ($user->uid && $user->name == 'bob') {
    return TRUE;
  }
  return FALSE;
}

```

---
Tags: 7, media
---


# Question
Title: What is significance of confirmation page before deleting a node?
I want to know what exactly usage of node confirm delete page except to avoid miss configuration.

# Answer
This is no t exactly Drupal specific, but I'll answer them anyway because one could miss a few reasons. Correct me if I'm missing any.

* It prevents accidentally clicking the delete button and actually deleting it.
* It provides security against CSRF attacks. If the node is deleted as soon as the node/xyz/delete page is loaded, an attacker can make an administrator open that URL, and the node will be deleted without his intention.

+ Because the specifications say so. http://www.rfc-base.org/txt/rfc-2616.txt GET requests should not make any *change* in data, so the request must be either a POST or a DELETE. Since Drupal forms only support GET and POST, we use the latter.
> 1 votes

---
Tags: hooks
---


title: Content types - custom view

text:
# Question
Title: Content types - custom view
I know there is option to preview content type after save. But i want to customise that preview by my css..i want to use image i upload to content type as background and put text on it from content as well. I am learning about modules/themes but i dont know the right way to do this. Opinion of someone experienced would be nice. Thanks a lot!

# Answer
> 0 votes
You need to use tokens and custom CSS in the view. Takes a little fiddling to get it perfect, because Drupal throws in a bit of it's XHTML.

---
Tags: views, theming
---


# Question
Title: How to debug: How Can I see the form arrays with its components (fields) in a loaded page?
I would like to changing a title of a button in a form, and I would like to have a tool for debug, like devel or another, so I can see in real time, after a page is loaded, what is the structure in forms, subcomponents, name of every field.

So I know how could add a line to the code in my custom module to change the title of a form button.

How would you do it? Steps, method, tools, please share.

Note: These are my first steps in programming modules, changing simple things for now.

Thanks for your suggestions!

# Answer
Debugging in Drupal can be a bit frustrating when you first start out but you'll get the hang of it quickly :)

Debug is a really convenient Drupal function to output your form array (or any array/object) from any custom module/template.

In the case of your form, you can invoke hook\_form\_alter in you custom module to call the debug of your form. (You can find the form ID by looking at the page code and replacing the - with \_. For example "user-login-form" would be "user\_login\_form" here)

```
 function YOUR_MODULE_NAME_form_alter(&$form, $form_state, $form_id) {
   if($form_id == 'your_form_id') {
     debug($form,'form',TRUE);
   }
 }

```

Then (after clearing caches) once you visit the page with the form, Drupal will output the $form array as an entry in your watchdog log (admin/reports/dblog).
> 1 votes

---
Tags: 7, commerce
---


# Question
Title: Send email to webform submissions when new content is created
I have a webform on my site, which collects names and email addresses, for the purposes of receiving content updates. When a new piece of content of a specific content type is added, I want to be able to send the email addresses collected in that webform a message, letting them know that new content has been added.

I've been able to set up rules to send a notification to one specific email address. However, I am struggling with sending to the email values collected in the webform.

I've added the Webform Rules module, and have PHP Filter turned on. However, I'm unable to send. Any help, or PHP code to accomplish what I'm looking to accomplish would be greatly appreciated!

Thanks in advance!!

# Answer
> 0 votes
how about direct get data from database? If you add hidden field and the default value will be \[current-page:query:sid\]. Use php code to get the data. Example: $raw = db\_query("SELECT AGE.data AS age FROM webform\_submissions S LEFT JOIN webform\_submitted\_data A ON A.sid=S.sid AND A.cid=1 LEFT JOIN webform\_submitted\_data AGE ON AGE.sid=A.sid AND AGE.cid=2 where \[current-page:query:sid\] = A.sid)-\>fetchAll();

I dun know I have not tried to code yet. Hope its can help you.

---
Tags: 7, rules, webforms
---


# Question
Title: How change Drupal Context with a button?
Context is great for delivering content to the right part of my site in the right circumstances, in the right order and to the right user.

I'd like to be able to add the ability for a user to toggle Context using a link I create - a button - to cause certain blocks to appear, disappear or be be re-arranged - via Context.

I have researched and experimented for hours and can't find a solution.

In what ways I can I change Context with the press of a button?

# Answer
> 0 votes
### Context Flag

> This module provides integration between the Context and Flag (3.0+ only for the moment, if there is interest in it support for 2.0 may be added later) modules.
>
> When enabled it creates new Context conditions which can be triggered based on the value of one or more Flags applied to nodes, currently active users, or user profile pages.

---
Tags: 7
---


title: Body field in colorbox

text:
# Question
Title: Body field in colorbox
Is it possible to have body trimmed to lets say 150 chars with read more link, and when you click read more, full body field opens in colorbox ?

# Answer
> 1 votes
If you have Colorbox installed, you can install Colorbox Node & Overlay which will let you create a colorbox node link with a `colorbox-node` class (e.g. `<a class="colorbox-node" href="/my/node/path">My Node</a>`).

In your theme's node preprocess function, you can add that class to the read more link:

```
/**
 * Implements hook_preprocess_node() in your theme's template.php
 */
function MYTHEME_preprocess_node(&$variables) {
  if ($variables['view_mode'] == 'teaser') {
    $variables['content']['links']['node']['#links']['node-readmore']['attributes']['class'] = 'colorbox-node';
  }
}

```

You'll need to adjust your theme's stylesheet rules to hide the non-body fields (and other styling as necessary), but it will work.

---
Tags: 7, javascript
---


title: Subscription Membership

text:
# Question
Title: Subscription Membership
User will key in particular info such as Name, contact and email. User will choose membership package such as one month, 6 months or one year Activation email will send to the user. User will click on the link and redirect to paypal. User will key in their payment info. User will receive ID and password.

May I know how to create this logic into my website?

# Answer
https://www.drupal.org/project/moneysuite use this module

1)Enable membership suite submodule of moneysuite and also enable payment gateway (**paypal**).

2)goto admin/people/permissions/roles,create a unique role say(**premium membership**).

3)go to admin/config/people/accounts/fields,then add field to your registration page **"contact"**

4)then go to admin/structure/ms\_products/ms\_membership,there create membership plans ,you can show membership plans(one month, 6 months or one year)on user registration page and also assign the role which was previously created (**premium membership**)

5)after doing complete checkout process,user will get unique (**premium membership**) role who brought membership plans.

6)then create a page which can see only (**premium membership**)roles by setting permissions ,where User will receive ID and password.

Atlast I want to say i cant explain the entire process here above are the basic steps which are required to create any membership site.
> 2 votes

---
Tags: 7
---


# Question
Title: What's the difference between enabling Node View (and adding a variant) and creating a new Panel page?
To learn more about Panels, I've been repeatedly traipsing through screencasts by Shane Thomas and Johann Falk. Right now I find myself confused about the distinction between: enabling a copy of node\_view so one can add a variant for a content type, and, creating a new panel page for that content type.

Code Karate's screencast series is directed to learning about Panels, but #129 takes a side-step into creating a copy of node\_view Page (through Page Manager) to create a variant, selecting by content type. I wonder why Page manager is being used for a tutorial about Panels.

I want a page for a specific content type, but I would like to use a Panel page to get there. How do I do this?

I'm also not clear on what invokes a Panel.

Note: I've read this question/answer by @Letharion about the difference between Page manager and Panels which is a bit too high-level for me at this stage.

# Answer
**Page Manager** allows you to intercept existing paths or create new paths in the system.

As the **node view path** already exists, and you want to change the way it operates depending on some conditions (bundle for instance) you need to enable a copy of node view path in **Page Manager**, instead of creating a new one (as it already exists you cannot create a new one as it will conflict)

**EXAMPLE**: For all nodes of bundle type **Article**, when the user attempts to view such an article, you want to perform some **ACTION**. So you override the node view path, create a variant that filters on bundle of Article, then perform some **ACTION**.

The **ACTION** is pluggable. You can do a redirect for instance. So when the user attempts to view an Article you intercept that, look at some **context** on the specific article (lets say there is an Entity Reference field to a Basic Page), then redirect to that Page.

**Panels** has a plugin component for **Page Manager**. So when your condition to view an Article for instance is satisfied in Page Manager (via your variant), you can select that **Panels** take over the rendering of the page.

The beauty of **Page Manager** is that it intercepts the requested page and then makes all kinds of **context** on that page available, such that you can make decisions (via created variants) on what to do, and when you for instance make the decision to pass the rendering over to **Panels**, you have all the **context** available to you. You can even load more context if you wish. On a node you have limited author information available such as the Users uid, but with Page Manager you can request that it pulls in the User entity to make other fields available such as email etc. You can continue to bring in related context in this fashion: think about the case of a node that has an entity relationship to another type of node that has an author (User) that has a taxonomy reference etc. Access to more context is very helpful. Think of the difficulty with a Views Block. It only has access to the menu object's key (node id etc) and url parameters. But in Panels (via Page Manager) you can embed a View Content Pane and pass as much context to it as needed.

**SO in essence**, the Page Manager - Panel relationship is merely the way by which you decide what paths and what conditions on that paths must be satisfied in order for Panels to take over the rendering with access to lots of context.
> 1 votes

---
Tags: 7, panels
---


# Question
Title: Can we remove template.php from active theme folder?
If we remove template.php file from active theme folder will it work ? Will it follow default theme's template.php ?

Please help with this question.

# Answer
Here is explained the template.php function:

https://www.drupal.org/node/1728096

If you remove the template.php many things on the theme will stop working, specially all the things that make the template different (or useful).

But if you're using a subtheme you can remove the template.php in it since your subtheme will use the original theme template.php (As long as you don't have your own hooks and functions in that subtheme template.php).
> 1 votes

---
Tags: theming
---


title: Separate 403 path per role?

text:
# Question
Title: Separate 403 path per role?
On `admin/config/system/site-information`, one can specify "Error pages" for 403 (No access) and 404 (Page not found).

It would make a lot of sense to specify different pages here, depending if you are logged in or not.

Currently my idea is to show my custom login + registration page for anonymous users, but something else (not sure yet) for logged-in users.

Is there any solution for this in contrib?

# Answer
> 1 votes
There are 2 options to do so, without any custom code involved, as detailed below.

# Option 1: Use the CustomError module

The CustomError module allows the site admin to create custom error pages for HTTP status codes 403 (access denied) and 404 (not found), without creating nodes for each of them. Some more details about its features (from its project page):

> * Configurable page title and descriptions.
> * There are no author and date/time headers as with normal nodes.
> * Any HTML formatted text can be be put in the page body.
> * The error pages are themable.
> * Users who are not logged in and try to access an area that requires login will be redirected to the page they were trying to access after they login.
> * Allows custom redirects for 404s.

You'll probably be interested mostly in the part about "*Users who are not logged in and try to access an area that requires login will be redirected to the page they were trying to access after they login.*".

For D8 there is a 8.x-1.x-dev version for this module available also, more details about it can be found in Issue # 2219227.

# Option 2: Use the Rules module

Assume the path of the "Default 403" page is set to `no_access` (via admin). Then create a rule using the Rules module, with as **Event** something like "After visiting node `no_access`". So that the entire rule would look something like so:

* **Events:** After visiting node `no_access`
* **Conditions:**

1. *User has role(s)* \- `Parameter: User: [site:current-user], Roles: anonymous user`
    2. *NOT Text comparison* \- `Parameter: Text: [site:current-page:url], Matching text: user/login`
* **Actions:** *Page redirect* \- `Parameter: URL: user/login`

Should you want to do so, you could even add another **Action** to also display some (informational) message in the Drupal message area, with something like "You tried to visit a page for which login is required ...".

The above rule is for role anonymous. Create a similar rule for each other role you want to handle in the same way. Using the Conditional rules module you could even merge them in a single rule.

True, it might require you to enable an extra contributed module (Rules). But, as indicated by its growing popularity also, that module is probably already enabled in mostly any site (similar to the Views module), because there are dozens of use-cases for this module.

For D8 there is a 8.x-3.x-alfa version for this module available also.

# Answer
> 1 votes
You can work with panels as suggested in the above comment.

Without panels nor any contrib module you can show blocks limited to roles on the specified error node. Review the blocks settings.

Maybe you need multiblock to place blocks several times.

---
Tags: 7, users
---


# Question
Title: IP-numbers not found in database table ip2country
I am trying to hide a certain field in the product nodes for all visitors from other countries. I have installed the ip2country module and I am using this code snippet to fetch the language code in my module:

```
$ip = ip_address();
$country_code = get_country($ip);
dsm($ip . " " . $country_code);

```

The IP address is showing but not the country code. I am testing this on a web server and the IP printed by the dsm seems OK. I have also copied and renamed the ip2country\_get\_country($ip\_address) function from the ip2 country module to experiment with different solutions in my own module:

```
function get_country($ip_address) {
  $ipl = ip2long($ip_address);
  if (is_long($ip_address)) {
    $ipl = $ip_address;
  }
dsm($ipl);
  // Locate IP within range.
  $sql    = "SELECT country FROM {ip2country}
             WHERE (:start >= ip_range_first AND :end <= ip_range_last) LIMIT 1";
  $result = db_query($sql, array(':start' => $ipl, ':end' => $ipl))->fetchField();

  return $result;
}

```

The thing is that the long ip produced by the get\_country() function (`$ipl = ip2long($ip_address)`) is ten numbers, and as far as I can see in the database table no numbers for my country (Sweden) is made up of ten numbers... So it's not strange that the db query does not return the expected result ('SE'). There must be something obvious I am missing here... ? I have experimented with SQL queries directly in phpMyAdmin and I can confirm that the IP number is not to be found in any of the ranges given.

# Answer
> 0 votes
The comment from AyeshK led me to the right answer. I found this in the php manual:

> As pointed out by others, this function's return value is not consistent on 32 and 64-bit platforms.
>
> Your best bet for consistent behavior across 32/64-bit platforms (and Windows) is the lowest common denominator: force the return value of ip2long() into a signed 32-bit integer, e.g.:
>
> ```
> var_dump(unpack('l', pack('l', ip2long('255.255.255.0'))));
>
> ```

And so I changed this row `$ipl = ip2long($ip_address);` into this `$ipl = unpack('l', pack('l', ip2long($ip_address)));` and now it works!

But if there is a better solution, please let me know.

---
Tags: 7, theming
---


title: Change quote to « »

text:
# Question
Title: Change quote to « »
I'm using Drupal 7. A lot of text are using quotes like "text" or «text». I want that for all older text on the site as well as for new text there will be one type of quotes used: «text».

Can you help me with that? Maybe some text filter or module can do this? Tnx for advice.

# Answer
You can try this module:

Custom filter

> This module allows you to create content filter using regular expressions. Instead of creating a new module for each filter you need, now you can easily create and organize your own filters. Your filter will appear in the input format configuration page.

**Pattern:** `/([^\"]*)\"([^\"]*)\"([^\"]*)/i`

**PHP Code:** do not tick

**Replacement Pattern:** `$1«$2»$3`

REMEMBER to flush the cache!

ALSO note that this pattern could wreak havoc with tag attributes. So you will have to expand it to exclude quotes surrounding attributes. But that is a question for stackexchange.com.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: PDF with print module and wkhtmltopdf - how to install?
I try to generate pdf with the print module and have tried it with the PDF generators MPDF and DOMPDF. Unfortunately, the results are of no use, which is why I want to try wkhtmltopdf. I read good things about it.

Unfortunately, the installation guide is outdated. For instance, I read that you don't need a x server anymore since 3 years.

*What I've done so far:*

* I have downloaded the latest version for Windows.
* As described in the instructions I put the executable in the directory sites / all / libraries.
* After I renamed the cryptic file names wkhtmltox-0.12.1.2\_msvc2013-win32.exe in wkhtmltopdf, it was recognized in the print module settings.
* When I try to generate a PDF on my local installation, a confirmation dialog appears where I have to give permission and then I have to install the executable. After installation a error message occurs (the problem is known, so I will not thematize it further).

My first problem is that I do not know how the .exe needs to be used properly. Whenever I want to generate a PDF, I have to install the program (via "Allow" - "Terms of Conditions" agree and then "Install below C: // Program Files / Files") to continue. There is something wrong. Does anyone of you see the mistake in my procedure?

Or can someone give me an advise how to make wkhtmltopdf work with the print module on a localhost (WIN7 and XAMPP), please?

# Answer
> * I have downloaded the latest version for Windows.
> * As described in the instructions I put the executable in the directory sites / all / libraries.
> * After I renamed the cryptic file names wkhtmltox-0.12.1.2\_msvc2013-win32.exe in wkhtmltopdf, it was recognized in the print module settings.

The executable you've downloaded is the installer, not the wkhtmltopdf executable. You need to **install** it to the `sites/all/libraries`.
> 1 votes

# Answer
You can use the PHP WK HTML to PDF module

> This module is a Drupal Library implementation for the PHPWkHtmlToPdf wrapper and as a result is extremely small because it uses WkHtmlToPdf to do the heavy work.
> 0 votes

---
Tags: installation
---


# Question
Title: Node edit form shows cached or previous title while editing node, after updating node?
When I update a node the revision show changes in values when we see diff but after updating node when I edit node again in node edit from it shows old value ie: cached value.

When I flush all cache then the updated value start appearing in node edit form.

In site no page cache is enabled, no block cache is enabled. But we are using **memcache**

This does not happens always but starts happening when cache not cleared for few hours but after clearing cache it starts working.

Please suggest what kind of cache is effecting values while editing node titles.

I am using modules as well Title and entity\_translation

In my views there is no cache and I am using template file for views nid in which I fetch titles like below which also shows cached version :

```
$link = node_load($nid);
$link->title_field['en'][0]['value']  // English value title
$link->title_field['fr'][0]['value']  // French value of title

```

Should I try like this to get rid of cache:

```
$link = node_load($nid,null,true); // setting true

```

Please suggest, I have been trying and searching from long time but not able to find solution. It seems like problems with memcache.

**Minimum cache lifetime = none**

**EDIT:** seems kind of some similar problem Need to flush cache after node translation

**TRIED SOLUTION and this is of no help :**

```
function custom_module_node_update($node) {
  $nodeurl = url('node/'. $node->nid);
  cache_clear_all($nodeurl, 'cache_page');
  cache_clear_all("field:node:$node->nid", 'cache_field');
}

```

I am not sure this will help in this case or not or while updating translation of node. Please suggest! Thanks!

# Answer
I have switched to below for cache and removed memcached completely. All problems solved with this.

https://www.drupal.org/project/redis

https://www.drupal.org/project/entitycache

Thanks!
> 0 votes

---
Tags: 7, nodes, caching
---


# Question
Title: How to implement responsive social sharing button with counters?
I'm looking to implement some social sharing buttons on my website.

Requirements are

* responsive
* counters

I like the looks of the Ridiculously Responsive Social Share Buttons module, but they don't have counters.

Any ideas about how to implement this in a Drupal, maybe using some jQuery library?

# Answer
> 0 votes
Try any one of this following

1) Social Share Counter

> This module is clearly inspired by the share buttons used by Mashable.
>
> This module gives the share counts for only Facebook,Twitter and more which has some excellent features in more elegant manner. If you have a website, then you definitely need this module.

2) Social Share statistics

> This module is developed to track the share statistics of social media clicks. So when a registered drupal user shares any content to social media, this module saves the uid, nid and the share count for FB/twitter/GPlus in the database for the record.
>
> There is a 'Shares' tab on the user profile page where the user can get the list of content shared on different social networks (facebook, twitter).
>
> This module only tracks shares that are made using the share buttons that the module provides. If you share the nodes with some other mechanism (say directly copy paste the link to Facebook, Twitter, etc. or use some other module), those actions / shares do not count.

# Answer
> 0 votes
# Option 1: Social Stats

Have a look at the Social Stats module. Some details about it (from its project page):

> This is a statistics module. It provides data from various social media sites. The data which is saved per node. It includes data from:
>
> * Facebook : likes count, shares count, comments count & total count.
> * Twitter : tweets count.
> * LinkedIn : share count.
> * Google Plus : plus one count, share count & total count
> * Total Share Count : total across all available social networks
>
> It does not actually provide sharing widgets for the social networking sites. They have to be added manually, or using other modules. List of the modules recommended to use along with Social Stats are:

# Option 2: Rules

A completely different approach is to use the Rules module, as detailed in my answer to "How to show the number of times a page has been shared by all services total?".

---
Tags: theming
---


# Question
Title: Add flag counter in views Module(Search API index)
I want to add flag counter of content in views field. Authenticated users can flag(bookmark) contents. I want to know how many users flaged a content, And I want to add this in views field(display the number of times a node is flagged by a certain flag by Users).

Notice; I'm using "Search API Index" in content part of views

How can I do it?

---

**UPDATE Question after using Vicky8888 method**;

I added below code in global php field of views

```
   <?php
   $flag = flag_get_flag('bookmarks');
   if ($flag) {
  print "Number of Flags:";
  print $flag->get_count($node->nid);
      }
    ?>

```

this code work in tpl.php file of content type, But It's showing "0" in views. I got several errors in picture too.

after that I using JS code of Vicky8888.

```
Drupal.behaviors.your-theme = {

 attach: function (context, settings) {

 //add your available class below
    jQuery('.view-id-top_users.view-display-id-page .views-field-php .flag-link-toggle').click(function(){

        jQuery(document).ajaxComplete(function() {
         location.reload();
        });
       });
      }
       };

```

I cleared "your-theme" and added "adaptivetheme", and cleared classes and added ".view-content .views-field.views-field-php .field-content .flag-link-toggle".

after that I using this code in separate file and added

```
scripts[]=scripts/extracode.js

```

in adaptivetheme.info file.

I cleared cache and run cron too. but It didn't work too.

# Answer
> 0 votes
Use these two modules drupal like and flag simultaneously

Go to /admin/structure/flags create flag ,and configure it properly.

Go to your view add **Global: PHP field**

```
 <?php
print flag_create_link('bookmarks',$node->nid);

 $counts = flag_get_counts('node', $node->nid);
if(isset($counts['bookmarks'])){
 echo $counts['bookmarks'] .' Likes';
 }else{
      echo"no user flaged a content";
     }

 ?>

```

**And at last put this code in your themes js file**

```
Drupal.behaviors.your-theme = {

 attach: function (context, settings) {

 //add your available class below
    jQuery('.view-id-top_users.view-display-id-page .views-field-php .flag-link-toggle').click(function(){

        jQuery(document).ajaxComplete(function() {
         location.reload();
        });
       });
      }
       };

```

**To add the flag link in your content type use code:**

```
   <?php
    global $user ,$base_url;
    if(!$user->uid) {
   $flag_link = flag_flag_link($flag, $action, $content_id);

   $flag_url = $flag_link['href'];
    if(isset($flag_link['query']['token'])) {

    $flag_url .= '?'.$flag_link['query']['token'];
}

?>

  <a href="<?php echo $base_url;?>/user/login?destination=<?php echo      current_path();?>">MY-LINK</a>

```

---
Tags: views, search, flags
---


# Question
Title: Make form to show multiple field widgets with predefined values
I have a node form with multivalue field (cardinality unlimited). I need to show user 3 widgets if this field with predefined value (like shown at screenshot).

At screenshots I show the current form, and its desired look.

How can I achieve this result?

# Answer
> 2 votes
You will probably need to build a custom module that calls hook\_form\_alter() or hook\_form\_FORM\_ID\_alter() and insert your required pre-filled values before the form is rendered.

Your function should look something like this:

```
<?php

/*
 * Implements hook_form_FORM_ID_alter(&$form, &$form_state, $form_id)
 */
function mymodule_form_node_form_alter(&$form, &$form_state, $form_id){
    // Install devel module and uncomment below to see the variables in the form printed on the screen
    // dpm($form_state);

    // Once you know where to put the variables you can add new values to the field array like this
    $form_state['values']['field_something_important'][] = 'First thing';
    $form_state['values']['field_something_important'][] = 'Second thing';
    $form_state['values']['field_something_important'][] = 'Third thing';
}

```

Note that the actual location to put the values will be different, and might be a few levels deeper into `$form_state`.

As always when making modules:

* Replace the 'hook' part of a function name with the module name (case sensitive)
* Make sure you have the right form id in the hook
* Clear your cache so Drupal can find the hook

# Answer
> 1 votes
Ok, I have updated this answer with a solution. I am not 100% that this is what you wanted but hopefully it will get you close.

```
function hook_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
  // test array
  $items = array(
    'item1',
    'item2',
    'item3',
  );
  // Make sure the fields are in their original or blank state.
  if (!isset($form_state['build_info']['args'][0]->field_YOUR_FIELD[LANGUAGE_NONE][0]['value']) && !isset($form_state['default_fields'])) {
    for ($i = 0, $count = count($items); $i < $count; $i++) {
    // First field is already in form.
      if ($i > 0) {
        $form['field_YOUR_FIELD'][LANGUAGE_NONE][$i] = $form['field_YOUR_FIELD'][LANGUAGE_NONE][0];
      }

      // Set form values
      $form['field_YOUR_FIELD'][LANGUAGE_NONE][$i]['value']['#default_value'] = $items[$i];
      $form['field_YOUR_FIELD'][LANGUAGE_NONE][$i]['value']['#value'] = $items[$i];

      // Set row weight
     $form['field_YOUR_FIELD'][LANGUAGE_NONE][$i]['_weight'] = array(
      '#type' => 'weight',
      '#title' => t('Weight for row ' . ($i + 1)),
      '#title_display' => 'invisible',
      '#delta' => $i,
      '#default_value' => $i,
      '#weight' => 100,
     );
    }
    $form_state['default_fields'] = 1;
    $form_state['field']['field_YOUR_FIELD'][LANGUAGE_NONE]['items_count'] = count($items) - 1;
  }
 }

```

This solution probably has some superfluous code. I will try to get some time t edit later. As Darvanen stated your structure and language etc. may be different.

# Answer
> 0 votes
If you'd like to populate values into existing field, try Prepopulate module.

This allows you to pass the values from the URL simulating the user input.

> It allows fields in most forms to be pre-populated from the $\_REQUEST variable.

You can also use Rules with Forms Support to do populate values on certain condition.

---
Tags: entities
---


# Question
Title: How to limit users to posting 1 node per a day?
I am making a diary website, where users can make a daily diary entry. A node acts as a diary page, so naturally I need to limit the user to make 1 node per a day. How can I do this?

---

Steps I have tried

**Using Node Limit**

This contains an option for 1 node per a day. But in fact, it is 1 node per 24 hours. So if my user makes a diary entry at 3:00pm, they have to wait until 3:00pm the next day until making the next one. Because it is diary, it would be better if the limit reset at Midnight every day, but there doesn't seem to be a way of doing this.

**Using Rules**

The problem with Rules is that you have to fire off the rule on Node Creation. This creates a usability issue, as my user will finish their (unallowed second) diary entry before being told that it is not allowed.

# Answer
Check the answer here: Denying access to node form edit. Deny access to user by checking whether he has created a node the specific day.

```
function MYMODULE_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;

  if ($type == 'my_type' && ($op == 'create' || $op == 'update')) {
    my_module_check_if_user_has_published_content_today($account);
    if ($account->something == 'something') { // allow access
      return NODE_ACCESS_ALLOW;
    }
    else {
      return NODE_ACCESS_DENY;
    }
  }
// Return the default ignore value if your module doesn't need to get involved in this decision
  return NODE_ACCESS_IGNORE;
}

```

You should implement the select query that loads all nodes for the specific user on the specific day. You need to join node and user tables. Every node has a UTC value of the creation date. You can check if there is a node that was created after 00:00:01 and 23:59:59 in the specific day.
> 2 votes

# Answer
You could implement this using the Rules module, together with the Flag module, as further detailed below ...

# Step 1 - Content type

Create a dedicated content type to be used for these diary entries (nodes), let's call this type ***Diary*** (with machine name `diary`). So to add a diary entry, one will use a path like `node/add/diary`.

# Step 2 - Flag

Create a flag, using the Flag module. Let's call (label) it ***DailyDiaryCompleted***.

# Step 3 - Rule to disallow multiple nodes on the same day

Create a rule, which is triggered when a user wants to start adding a new diary entry, so using a `node/add/diary` path. Refer to my answer to "How to limit adding content of a specific content type to paid memberships only?" for a rule that you could use as an example. Read on for more details about this rule.

### Rules Event

Use Rules Event "Drupal is initializing".

### Rules Conditions

1. a condition related to "`site:current-page:url`", to check if it matches `node/add/diary`.
2. a condition to check if "this user" has **already** been flagged yet with the ***DailyDiaryCompleted*** flag

### Rules Actions

Set a drupal error message, to indicate they already create such diary node "today" (to stop them from **starting** the creation of such new node).

# Step 4 - Rule to mark daily diary completed

Create a rule, which is triggered after saving a new node of type ***Diary***. The Rules Action is to flag this user with the ***DailyDiaryCompleted*** flag.

# Step 5 - Rule for daily housekeeping

Create a rule, to **list** all users that have been flagged with the ***DailyDiaryCompleted***, and for each of them, perform an unflag of that flag.

# Step 6 - Daily housekeeping

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

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

The way I understand/Read this (haven't experimented with it yet though) is like so:

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

So by scheduling the rule (from the previous step, i.e. "Rule for daily housekeeping") shortly after your midnight, all the flagged users from the previous day will be able to create a new ***diary*** node again "the next day".
> 2 votes

# Answer
You can disable the node form and provide a helpful message if a diary entry was already submitted today. You can also use a presave hook to perform the same check in case the node can be submitted without a form (for example, using a web service).

```
<?php

/**
 * Implements hook_form_alter().
 *
 * Perform alterations before a form is rendered.
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'MYNODE_node_form':
      // Disable the node form if the user submitted an entry today.
      if (MYMODULE_user_submitted_today()) {
        $form['#disabled'] = TRUE;
        drupal_set_message(t('You already submitted a diary entry for today.'), 'status');
      }
      break;
  }
}

/**
 * Implements hook_node_presave().
 */
function MYMODULE_node_presave($node) {
  if (MYMODULE_user_submitted_today($node->uid)) {
    drupal_set_message(t('You already submitted a diary entry for today.'), 'status');
    throw new Exception('Node save aborted. Entry for today already submitted.');
  }
}

/**
 * Checks if a user submitted a diary entry today.
 */
function MYMODULE_user_submitted_today($uid = NULL) {
  if (!$uid) {
    global $user;
    $account = $user;
    $uid = $account->uid;
  }

  // Get the timestamp for the user's latest diary entry.
  $sql = 'SELECT n.created
    FROM {node} n
    WHERE n.type = :type
    AND n.uid = :uid
    ORDER BY n.created DESC
    LIMIT 1';
  $last_created = db_query($sql, array(
    ':type' => 'diary',
    ':uid' => $uid,
  ));

  if (date('z-Y', $last_created) == date('z-Y')) {
    return TRUE;
  }
  return FALSE;
}

```
> 1 votes

---
Tags: users, nodes
---


title: Drupal mail send to multiple recipents

text:
# Question
Title: Drupal mail send to multiple recipents
I want to send the mail to multiple recipents with varying body content each user will have different content . This is the code I used for sending, but I cannot send to multiple users.

```
 $to = 'abc@gmail.com,test@gmail.com';
  drupal_mail('mimemail', 'testing', $to, language_default(), $params, $from = NULL, $send = TRUE);

```

# Answer
This code might be of some help .

```
$to = array('one@email.com', 'two@email.com', 'three@email.com');
        foreach ($to as $key => $mail) {
          if ($mail = 'one@email.com') {
            $to = 'one@email.com';
           $params = array('body' => 'abc');
          }
          elseif ($mail = 'two@email.com') {
            $to = 'two@email.com';
            $params = array('body' => 'def');
          }
          elseif ($mail = 'three@email.com') {
            $to = 'three@email.com';
             $params = array('body' => 'ghi');
          }
          drupal_mail('$module_name', $key, $to, language_default(), $params, $from = NULL, $send = TRUE);
        }

```
> 0 votes

---
Tags: 7, emails
---


title: SMTP server per role

text:
# Question
Title: SMTP server per role
Mails must be sent to certain roles from certain domains. Is it possible to setup SMTP server per role? (through rules or by coding)

# Answer
MTA's can usually handle complex routing, such as handling multiple domains. Your specific rub will be the connection and routing to the MTA with the appropriate credentials to send the email.

You will need to setup a custom SMTP table where each role can setup their details, then within rules (or a custom module) create the logic to connect to the MTA with the appropriate credentials.

I hope this helps, or at least provides a gateway to an exact answer.
> 0 votes

---
Tags: rules, emails
---


title: Alter Drupal search URL

text:
# Question
Title: Alter Drupal search URL
I have a third-party vender that provides particular information for us when queried.

Basically, we need to change the URL of the search results page so that their supplied javascript can contact their site and return results from searching the same term.

So if I searched for polar bears the resulting path would normally look like this http://foo.com/search/node/polar%20bears

I need to append to the path like this http://foo.com/search/node/polar%20bears?scq=polar%20bears or http://foo.com/search/node/polar%20bears?scq=polar bears

How would I accomplish this?

# Answer
> 1 votes
When you want to alter the behavior of an existing form, `hook_form_alter()` is a useful tool here. Here you want to alter the existing form so that the redirected URL has an extra query parameter. By looking at the submission handler we can see that the search form uses `drupal_redirect_form()` to go to the **/search/node/SEARCH\_TERM** path.

We can add an extra submission handler to this search form so that it modifies the redirect path with the extra query parameter.

Here's an example MYMODULE that would do as such for the search block form.

```
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  // Add an extra submission handler the search block form.
  if ($form_id == 'search_block_form') {
    $form['#submit'][] = 'MYMODULE_search_box_form_submit';
  }
}

/**
 * search_block_form submission handler
 */
function MYMODULE_search_box_form_submit($form, &$form_state) {
  $form_state['redirect'] = array($form_state['redirect'], array(
    'query' => array(
      'scq' => $form_state['values']['search_block_form'],
    )
  ));
}

```

# Answer
> 0 votes
I just wanted to share my final code. It is similar to the answer given by Shawn Conn, but revised a bit to use the correct array elements.

```
    <?php

/**
 * @file
 * Adds a submit handler to the default search, then appends the redirect path to allow for third-party
 * javascript to gather search data based on the $_GET['scq'] variable value
 */

/**
 * Implements hook_form_alter().
 */
function My_module_form_alter(&$form, &$form_state, $form_id) {
    // Add an extra submission handler to the form with matching $form_id
    if ($form_id == 'search_block_form' || $form_id == 'search_form') {
        $form['#submit'][] = 'My_module_search_box_form_submit';
    }
}

/**
 * search_block_form submission handler
 */
function My_module_search_box_form_submit($form, &$form_state) {
    // Get the $form_id
    $form_id = $form['#form_id'];

    // Gather the terms used in the search from the appropriate search
    if ($form_id == 'search_form') {
        $terms = $form_state['input']['keys'];
    }
    elseif ($form_id == 'search_block_form') {
        $terms = $form_state['values'][$form_id];
    }

    // Build the correct redirect path, appending the third-party variable (scq) with $terms as the value
    $form_state['redirect'] = array(
        $form_state['redirect'],
        array(
        'query' => array(
            'scq' => $terms,
        )
    ));
}

```

---
Tags: search
---


title: Is node:nid missing?

text:
# Question
Title: Is node:nid missing?
I installed Drupal 8.1.0 and created a view, but I don't have the option of choosing the node ID (as a contextual filter, for example) but I can select the content ID. If it isn't the same thing, why would the node ID be missing as an option?

# Answer
Content Id is the node id in Contextual filters for Drupal 8 views.
> 1 votes

---
Tags: views, 8
---


# Question
Title: How to overridden command via hook_drush_command_alter?
I'd like to override command using `hook_drush_command_alter` before run as below:

```
/**
 * Implementation of hook_drush_command_alter().
 */
function policy_drush_command_alter(&$command) {
  if ($command['command'] == 'features-revert-all') {
    $command['command'] = 'custom-features-revert-all';
    $command['command-hook'] = 'custom-features-revert-all';
  }
}

```

However it doesn't work (it's calling the old command). I'm doing it right? Is it possible using this hook?

# Answer
> 3 votes
The command\_alter hook is not super friendly / obvious when it comes to complete command replacement, as this hook was only designed to make minor alterations to the command. It is all the same possible to replace one command with another, but the process is a bit obtuse, as you need to reset some variables that Drush has already initialized.

This should do the trick:

```
/**
 * Implements hook_drush_command_alter
 */
function policy_drush_command_alter(&$command) {
  if (($command['command'] == 'features-revert-all') && (drush_drupal_major_version() >= 8)) {
    $command['command'] = 'custom-features-revert-all';
    $command['command-hook'] = 'custom-features-revert-all';
    $command['primary function'] = FALSE;
    $command['arguments'] = array(); // Adjust this only as needed
    drush_set_command($command);
  }
}

```

Note that this example removes any arguments the user may have passed to the command; I included this just to demonstrate how to alter the arguments, in case this is needed. Remove the assignment to `$command['arguments']` if you'd like the original args passed through.

---
Tags: hooks, drush
---


# Question
Title: Build a grid with time slots in multiple rooms
I need to build a grid for one day (Feb. 27) that allows users to reserve time-slots. There are 12 1/2 slots with a limit of 8 bookings for each slot (in 8 different rooms). The users are authenticated...this is not open to the public.

I'm guessing this is possible with Calendar module and Jquery without having to install another module. Any ideas?

---

Drupal 7

# Answer
> 0 votes
The bat module - https://www.drupal.org/project/bat would work for this use case without any custom code required.

---
Tags: entities
---


# Question
Title: How to add extra option to the existing drush command?
I'm trying to add extra option to the existing command as below:

```
/**
 * Implements hook_drush_command_alter().
 */
function MYMODULE_drush_command_alter(&$command) {
  if ($command['command'] == 'features-revert-all') {
    $command['options']['cleanup'] = dt("Remove non-existing components from the database after revert.");
  }
}

```

However it seems it doesn't work as expected and `drush fra --cleanup` fails.

Then the `help` command doesn't show this option either.

What's the proper way of adding such option, so drush can understand it and can be available for further parsing via `drush_get_option`?

# Answer
> 2 votes
This is done with `drush_help_alter` rather than `drush_command_alter`. See the example Drush policy file, reproduced in part below:

```
function policy_drush_help_alter(&$command) {
  if ($command['command'] == 'updatedb') {
    $command['options']['token'] = 'Per site policy, you must specify a token in the --token option for all commands.';
  }
}

```

---
Tags: hooks, drush
---


# Question
Title: Display delete confirmations in a modal window
How do I display delete confirmation form in a modal window? I have a view which displays submissions of an entity form. Each one has a 'delete' link for the admin to remove a particular submission, but clicking it goes to a new delete confirmation page (`entityform/[nid]/delete`). How can I display this confirmation page in a modal overlay, like the edit forms?

I tried the overlay\_path module but it tried to display a styled page in the overlay and it looked terrible with my current theme

# Answer
> 2 votes
You can use https://drupal.org/project/ctools\_automodal and then use menu\_alter to use following code and see if it helps.

```
function modulename_menu_alter(&$items) {
    $items['entityform/%entityform/delete']['modal'] = TRUE;
}

```

Be sure to clear cache.

# Answer
> 0 votes
Module **Modal operaitons** do this. https://www.drupal.org/project/modal It is no readme, but here is example. This link was open node view in modal window.

```
//As Example:
<a href="/modal/node/NID/nojs" class="ctools-use-modal">View</a>

```

Or this my code for delete node (for **Views PHP**)

```
<a href="<?php global $base_url; echo $base_url; ?>/modal/node/<?php echo $row->nid; ?>/delete/nojs" class="ctools-use-modal">Delete</a>

```

---
Tags: javascript, entities
---


# Question
Title: Fluch cache on all sites in multisite platform
Is there a way to clear cache on all sites in platform by using platform alias? For example, `drush @platform_name cc all` ? (its multisite setup via aegir).

The problem I am facing with is, when I run that command or the one with @sites, I get a message

> Could not find a Drupal settings.php file at sites/default/settings.php.

So, I then copied default.settings.php as settings.php (which is by default fully commented out) in sites/default, and then it says

> Drush was not able to start (bootstrap) the Drupal database.

Which is obvious, as default doesn't have database (Aegir creates all sites in platform as separately and never touches default).

I also tried to delete default folder but Drush is telling me it needs to have settings.php there (even after I cleared drush cache). Drush in question is 8.1.0.

# Answer
> 0 votes
An easy way is via the views bulk operations. When you select some or all sites you can expand the operations menu at the top, where you should find 'Site: Flush\_cache'. It's part of the hosting\_tasks\_extra module (which is included by default now)

Note that you currently do have to enable the operation in the sites view. See https://www.drupal.org/node/2715945

---
Tags: drush, multi-sites, aegir
---