# Question
Title: How to make the Rules module block flagged users from sending entityform submissions?
I am trying to create a simple block user functionality on my site. I have a "Block/Unblock User" Flag that other users can block and unblock so they stop getting contact emails from (via entityform)

The entityform is set up like (logged in users):

```
NodeReference: Points to content they are interested in. I use tokens to fill in the authors name, email, etc...
Message: Text message to email field_nodereference:author:mail

```

So I am trying to create a rule (using the Rules module):

```
Event: Before saving a entityform submission

Condition:
NOT User has roles: entityform-unchanged:user is administrator (admins can bypass rule)

Entity is of bundle: Parameter: Entity: [entityform-unchanged], Entity type: Entityform Submission, Entity bundle: Contact Article Creator

Entity has field: Parameter: Entity: [entityform-unchanged], Field: field_nodereferencearticle

User is flagged
Parameter: Flag: Block/Unblock User, user: [entityform-unchanged:user], User on whose behalf to check: [entityform-unchanged:field_nodereferencearticle:author

Actions:

Page Redirect to site:url
Show Message: Warning: Was unable to send messsage. The Recipient has blocked you from contacting them.

```

So the basic premise of this is if a user blocks another user, this rule will preprocess all Contact Article Creator eforms and see if the potential recipient has blocked the user. If so, redirect to the front page with a warning stating the user blocked them.

EDIT 1: However, every eform I submit goes through. I can't get the rule to not submit.

EDIT 2: Here is the actual exported rule.

```
{ "rules_block_user_from_sending_message_if_user_blocked_them" : {
"LABEL" : "Block user from sending message if user blocked them",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "entityform", "flag" ],
"REQUIRES" : [ "rules", "flag", "entityform" ],
"ON" : { "entityform_presave" : [] },
"IF" : [
  { "entity_is_of_bundle" : {
      "entity" : [ "entityform-unchanged" ],
      "type" : "entityform",
      "bundle" : { "value" : {
          "contact_seller" : "contact_seller",
          "contact_seller_anonymous" : "contact_seller_anonymous"
        }
      }
    }
  },
  { "entity_has_field" : { "entity" : [ "entityform-unchanged" ], "field" : "field_listing" } },
  { "flag_flagged_user" : {
      "flag" : "block_unblock_user",
      "user" : [ "entityform-unchanged:user" ],
      "flagging_user" : [ "entityform-unchanged:field-listing:author" ]
    }
  }
],
"DO" : [
  { "redirect" : { "url" : [ "site:url" ] } },
  { "drupal_message" : { "message" : "Was unable to send message. ", "type" : "warning" } }
]

```

} }

# Answer
It seems pretty obvious to me that something in any of your Rules Conditions is not working as you'd expect/want them to work. Which would also explain your "***I can't get the rule to not submit***".

# Basic debugging

You clearly have a combination of Rules Conditions that need some debugging. Rules is great, but sometimes also tough to debug if things don't work as you'd expect. There are some typical facilities to do such debugging, but my **K**eep-**I**t-**Super**-**S**imple technique I often use is my ***BINGO***-trick. A sample of such rule can be found in my answer to "Which Rules condition can be used to email a user when an admin updates their profile?". Stupid, but simple and efficient (I think).

Also, since you have 3 Rules Conditions in a single rule, you should try to see what happens (if you get a "bingo") for each of the individual Rules Conditions. This by simply (temporary) removing 2 out of the 3 Rules Conditions you are using, and verify if they each result in the Rules Action you'd expect (also just a simple Bingo-message should be sufficient).

# Advanced debugging

Something else that will help you find the answer to your question, is to have a look at Rules **debugging** ... Within the Rules **settings**, experiment a bit with the debugging facilities that come with the rules module. At least have a look at the "***Rules Evaluation Log***" (to check that the Rules logic being executed, actually matches what you expect that logic to be).

Depending on what the result of that type of debugging is, you may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value" (in your case of your `node:comments`).

For way more details about these 2 variations, refer to **Rules debugging**, as explained in the answer to "How can I display the value of a variable inside a condition?".
> 0 votes

---
Tags: 7, users, rules, flags, entities
---


# Question
Title: Get the ID / class of the part of the form that has been repainted with an AJAX callback?
I have an AJAX form with a callback that fires some JavaScript when the form is submitted.

I need to know what has been repainted. Can I get the class / ID of the parts of the form that have been changed by submitting the form?

AJAX callback:

```
function _my-module_form_process_callback_js($form, &$form_state) {
  $commands = array();

  $commands[] = array (
    'command' => 'customSomething',
  );

```

JavaScript:

```
  Drupal.ajax.prototype.commands.customSomething = function(ajax, response, status) {

    console.log(ajax);

  };

```

By logging ajax I can see the form ID and class. However I don't belive that the entire form is being repainted. Most of the form is unchanged, its only one fieldset that changes.

# Answer
> 0 votes
I don't know if its the best solution but this works:

```
  Drupal.ajax.prototype.commands.customSomething = function(form) {

    var formId = '#' + form.form.context.id;

  };

```

---
Tags: ajax
---


title: uppercase form textfield

text:
# Question
Title: uppercase form textfield
I want to have a form textfield automatically uppercase the text entered as it is typed in. I was hoping that there was as set-able property that would allow for this but I’m unable to find one.

> $form\['elementName'\] = array( '#type' =\> 'textfield', '#title' =\> $this-\>t('Address'),... )

The searches I have done so far point to the use of ‘Plugins.’ However if there is a simple(er) solution I prefer that. Any ideas appreciated;

# Answer
> 2 votes
> However if there is a simple(er) solution I prefer that.

Sorry, maybe I going too deep, but the most simpler solution that you can use just for display is a CSS solution.

Based in your example:

```
input[name='elementName'] {
  text-transform: uppercase;
}

```

That's it, any char will be uppercase in your textfield. If need store in uppercase, just change case before save.

# Answer
> 0 votes
The easy solution would be to do this in a submit handler before the value is actually saved.

If this is for display purpose - the Drupal way is to not alter what is saved, but alter how it appear on screen.

---
Tags: 8, forms
---


# Question
Title: Is there any way to run hook_form_alter based on a form ’s class instead of it’s ID?
Is there any way to run a hook\_form\_alter based on a form ’s class instead of it’s ID?

I have a class of commerce products and am needing to do form alterations on their add to cart forms. There are too many of them to do this using their form id’s.

Pseudo code might be:

```
function  theme_form_alter(&$form, &$form_state, $form_class) {
    //code goes here
    }

```

# Answer
> 2 votes
No - forms are only referred to by their ID (or 'base ID'), which is essentially the name of the function that defines them, or generally speaking, closely related to it.

So if you have

```
function MYMODULE_some_form($form, &$form_state) {
  // ...
}

```

Then the ID of that form is `MYMODULE_some_form`. It's not related to the HTML ID attribute, in case that's what you're thinking, so there's no `class` equivalent.

# Answer
> 0 votes
For Drupal Commerce, you can always use this hook to get all cart forms without an if statement:

```
<?php
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state, $form_id) {
  $product = $form_state['default_product'];
  $product_wrapper = entity_metadata_wrapper("commerce_product",$product);
}
?>

```

---
Tags: forms
---


# Question
Title: In Drupal 7 Commerce, is there a way to populate an anonymous user's profile billing/shipping address data during checkout?
This is for Commerce Core. Not Kickstart, but it can also apply.

Upon completing checkout with an anonymous user in Drupal Commerce. There is no billing / shipping data populated in the user's profile. What modules or rules are needed to have the user's billing / shipping address profile pre-filled upon successful checkout?

This is after the anonymous user completes a successful checkout and an account is automatically generated for them.

# Answer
> 1 votes
It sounds like you're wanting to set the default billing / shipping customer profiles for the newly created user to be the ones that were just used in checkout. I don't know if there's a Rules action for that, but if not, that sounds like a good feature request for the Commerce Addressbook module. If there is, then you just need to add a checkout completion rule to make it happen.

# Answer
> 1 votes
You can do this with address book module and simple submodule.

1) Install address book as usually.
2) Enable a simple submodule (see above).
3) Create a field\_address in user profile

**Optionaly**:
\- Install Commerce addressbook extra
\- Add a simple js to synchronize a field\_address and commerce\_addressbook fields on registration (and user edit) page.
**All done**.

---
Tags: 7, users, commerce
---


# Question
Title: How to validate and submit a form using AJAX?
I've created a webform using the Form API. I'm using the `#AJAX` field option to add AJAX validation to each field.

Is it possible to validate and submit the form using AJAX without reloading the page. If validation fails I want to show an error message and if validation is successful then I want to show a message (ideally in a lightbox) and reset the form fields.

My code so far:

```
$form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#default_value' => '',
    '#maxlength' => '128',
    '#required' => TRUE,
    '#ajax' => array(
        'callback' => '_validate_name',
        'wrapper' => 'name-error-icon-container',
        'method' => 'html',
        'effect' => 'none',
        'progress' => array(
            'message' => NULL,
        ),
    ),
);

$form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
    '#ajax' => array(
        'callback' => '_handle_form_submit',
        'effect' => 'fade',
    ),
);

```

callback functions look like this:

```
function _validate_name($form, $form_state) {

    if ($form_state['values']['name'] != '') {
    $output = 'OK';
    }
    else {
      $output = 'Enter a value';
    }

   return $output;

}

function _handle_form_submit($form, $form_state) {
}

```

But I'm not sure what should go in the `_handle_form_submit` function to validate and then either return a message or submit form and reset fields?

# Answer
The examples module has an ajax form that you can refer to as well as many others. Here is a link to the ajax form example in the code repository, but I suggest downloading to look at the implementation yourself anyway.
> -2 votes

# Answer
I know this is question has been lying around for a couple of years by now, but I don't feel any of the other answers really get the point of Drupal 7 ajax form submission, so I'll try to explain it.

Since your form should work as well without the ajax as per good practice, your ajax submit handler should do nothing but return the form. Everything else should be in your validation and submit functions.

```
function ex_form($form, $form_state) {
  $form['name'] = array(
    '#type' => 'textfield',
     '#title' => t('Name'),
     '#default_value' => '',
     '#maxlength' => '128',
     '#required' => TRUE,
  );

  $form['submit'] = array(
   '#type' => 'submit',
   '#value' => 'Submit',
   '#ajax' => array(
     'callback' => 'ex_form_ajax_handler',
     'effect' => 'fade',
   ),
  );
}

function ex_form_submit(&$form, &$form_state) {
  // Submit logic - runs when validation is ok
  // You can alter the form here to be just a markup field if you want.
}

function ex_form_validate(&$form, &$form_state) {
  // Validation logic - invalidate using form_set_error() or form_error()
}

function ex_form_ajax_handler(&$form, &$form_state) {
  return $form;
}

```
> 13 votes

# Answer
I think the post by maxtorete on October 17, 2011 seems to give a fuller example using both `form_validate()` and `form_submit()`

(I haven't tested it yet.)

Also Joshua Stewardson's answer over at stack overflow has a nice working example:

```
function dr_search_test_form($form, &$fstate) {

  $form['wrapper'] = [
    '#markup' => '<div id="test-ajax"></div>',
  ];

  $form['name'] = [
    '#type'     => 'textfield',
    '#required' => TRUE,
    '#title'    => 'Name',
  ];

  $form['submit'] = [
    '#type'  => 'submit',
    '#value' => 'Send',
    '#ajax'  => [
      'callback' => 'dr_search_test_form_callback',
      'wrapper'  => 'test-ajax',
      'effect'   => 'fade',
    ],
  ];

  return $form;
}

function dr_search_test_form_callback($form, &$fstate) {

  return '<div id="test-ajax">Wrapper Div</div>';
}

function dr_search_test_form_validate($form, &$fstate) {

  form_set_error('name', 'Some error to display.');
}

```

Joshua makes the point that **validation error messages replace the `#ajax['wrapper']` element completely so your callback needs to resupply this element again as you replace it.**
> 3 votes

# Answer
In general, validation and form submission handling should happen in the usual \_validate() and \_submit() callbacks. The idea is that forms should still work without ajax.

Pretty much the only thing the #ajax callbacks should do is return the part of the form that should be replaced, according to the defined wrapper.
> 2 votes

# Answer
There are two ways

1)

```
function abc_form_validate(&$form, &$form_state) {
  // Validation logic - invalidate using form_set_error() or form_error()
}

function abc_form_ajax_handler(&$form, &$form_state) {
  return $form;
}

```

2) Example module http://cgit.drupalcode.org/examples/tree/ajax\_example/ajax\_example.module?id=refs/heads;id2=7.x-1.x#l402
> 0 votes

# Answer
In my case, using a `submit` type caused the form to always submit, so I changed it to a `button` with `#ajax` specified. Then, I had to do my validation in the ajax callback.

I was making a ctools pane; I don't know if that plays into it.

```
function mymodule_form($form, &$form_state) {
  ...
  $form['button'] = array(
    '#type' => 'button',
    '#value' => t('Subscribe'),
    '#ajax' => array(
      'callback' => '_mymodule_ajax',
    ),
  );
  return $form;
}

function _mymodule_ajax($form, &$form_state) {
  if ( ! valid_email_address($form_state['values']['email']) ) {
    form_set_error($form, t('Please enter a valid email address.'));
  } else {
    $form = array(
      '#markup' => t('You have subscribed.'),
    );
  }
  return $form;
}

```
> 0 votes

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


# Question
Title: How to return a missing field as null with db_select union?
I have a db\_select union of two tables where some of the columns are different. I would like to select a column that is only in one of the tables. The standard SQL way of doing this seems to set the column as null for the table where the field missing. Is there a way of doing this with db\_select? db\_query?

Standard SQL way:

```
select id, name, date, null as userid, 'A' as recordtype from table1
union all
select id, name, null /*as date*/, userid, 'B' as recordtype from table2

```

What I'm trying to do:

```
$table_one = db_select('t_one', 'to')->fields('to', array('ID', 'NAME'));
$table_two = db_select('t_two', 'tw')->fields('tw', array('ID', 'NAME', 'new_field_not_in_first_table'));
$s_query = Database::getConnection()
        ->select($table_one->union($table_two), 't')
        ->fields('t', array('ID', 'NAME', 'new_field_not_in_first_table'));

```

I tried adding `'NULL as new_field_not_in_first_table'` in the first table but no luck. Thanks for your time!

# Answer
I used the addField function to explicitely declare the NULL aliased columns for the UNION. It worked! Check the following snippet:

```
$table_one = db_select('users', 't_o');
$table_one->addField('t_o', 'uid', 'id');
$table_one->addField('t_o', 'name');
$table_one->addField(NULL, 'null', 'weight');
$table_one->addField('t_o','mail');

$table_two = db_select('taxonomy_term_data"', 'tw');
$table_two->addfield('tw', 'tid', 'id');
$table_two->addfield('tw', 'name');
$table_two->addfield('tw', 'weight');
$table_two->addField(NULL, 'null', 'mail');

$s_query = db_select($table_one->union($table_two), 't')
    ->fields('t', array('id', 'name', 'weight', 'mail'));

```

And this generates this kind of SQL:

```
SELECT t.id AS id, t.name AS name, t.weight AS weight, t.mail AS mail
FROM
  (SELECT t_o.uid AS id, t_o.name AS name, null AS weight, t_o.mail AS mail
   FROM {users} t_o
   UNION
   SELECT tw.tid AS id, tw.name AS name, tw.weight AS weight, null AS mail
   FROM {taxonomy_term_data} tw)

```

Hope this solves your problem!
> 0 votes

---
Tags: database
---


# Question
Title: TWIG if/else to filter through templates
I am trying to write a TWIG else/if statement that loops through four different templates based on the number of customers are chosen from a list. So if a designer chooses 1 customer a certain template is used to create that view, and if they choose 3 customers a different template is used.

```
{% if content.field_featured_customers|length == 1 %}
{% include "node--customer--featured-full.hmtl.twig" with content.field_featured_customers %}
{% elseif content.field_featured_customers|length == 2 %}
{% include "node--customer--featured-split.html.twig" with content.field_featured_customers %}
{% elseif content.field_featured_customers|length == 3 %}
{% include "node--customer--featured-3block.html.twig" with content.field_featured_customers %}
{% else %}
{% include "node--customer--featured-carousel.html.twig" with content.field_featured_customers %}
{% endif %}

```

This is what I have tried so far, but nothing is rendered. I have created templates for all of the different views I am trying to display. Here is an example for the featured-full.html.twig

```
<div class="row">
<div class="columns small-12 medium-4">
{{ content.field_logo }}
</div>
<div class="small-12 medium-8">
<h3>{{ content.field_comapny_name }}</h3>
<p>{{ content.field_description }}</p>
<a class="button" href="#">Learn More</a>
</div>
</div>

```

Am I doing something wrong in the if/else statement, do I need to create different views, or is there something in the theme that I need to include?

# Answer
> 0 votes
If not rendered at all, for sure, Twig not found your template file.

There is a var that store the base dir of your theme, just use it to define where is your template file.

**Twig file:**

```
{% include "#{directory}/templates/node/node--customer--featured-full.hmtl.twig" %}

```

---
Tags: views, theming, forms
---


# Question
Title: I lost permission to access admin/content for user 1
I uninstalled several contributed modules of my site and suddenly I lost the permission to access admin/content for user 1.

As far as I know this is not related to any contributed module.

When I try to access this page **admin/content** I get a message "**You are not authorized to visit this page.**".

How can I trace this? I run cron, clear caches and even run sites/all/modules/registry\_rebuild/registry\_rebuild.php to rebuild registry.

Is **Drupal7** using the **Commerce Kickstart distribution** (I disabled all commerce modules)

**Update1:** I just rebuild permission at: admin/reports/status/rebuild but problem persit.

Also there are these error messages:

```
Notice: Trying to get property of non-object in user_access() (line 808 of /home/temporal-13/www/modules/user/user.module).
Notice: Trying to get property of non-object in user_access() (line 820 of /home/temporal-13/www/modules/user/user.module).
Notice: Trying to get property of non-object in user_access() (line 821 of /home/temporal-13/www/modules/user/user.module).
Notice: Trying to get property of non-object in user_access() (line 827 of /home/temporal-13/www/modules/user/user.module).
Notice: Trying to get property of non-object in user_access() (line 830 of /home/temporal-13/www/modules/user/user.module).

```

# Answer
Solved: the problem was the module: admin\_views I just disabled it and the problem was gone.
> 4 votes

# Answer
I have run into this before, and it is when you have corrupt menu router information. Chances are there is a contributed module improperly running `hook_menu_alter`. Disable additional contributed modules you have added to your site, one by one, to identify the offending module.

> Is Drupal7 using the Commerce Kickstart distribution (I disabled all commerce modules)

Well, that can be problematic. You have altered a Drupal Commerce distribution and disabled the Drupal Commerce modules. Commerce Kickstart 2 makes modifications to the menu for the admin toolbar menu.

Re-enable the Drupal Commerce modules, or use a different distribution, or not one at all.
> 1 votes

# Answer
In a situation like this I would enable the Devel module to provide me with the menu item so that I can ascertain what is controlling the access.

1. Install and enable Developer
2. Go to `example.dev/devel/menu/item?path=admin/content`
3. From the returned array check the value of 'access callback' to see which function is responsible for granting access.
> 1 votes

# Answer
I am not certain, but it looks like you may have lost access to the admin account? If so, try following the directions in the following Drupal Community Doc about recovering the administrator password: https://www.drupal.org/node/44164

I was personally able to do the first way that's listed there, which is using Drupal Console. Of course, to do that you need command line access to your server, like SSH through PuTTY. If you don't have command line access, then the page about resetting with a sql query has a solution for you about halfway down the page that is under the section header, "Reset using a PHP-file". (Or just go directly to the corresponding page: https://www.drupal.org/node/1556488.)
> 0 votes

---
Tags: commerce, users
---


# Question
Title: getpreventdefault is deprecated - Caroussel stopped working
I have a caroussel slide made with a view and it was working fine until today. The block (with a view inside) just dissappeared from the front page.

I aggregated js files in the performance page... maybe that was it. But now I uncheked the option and cleared the cache many times and is still not working.

I'm getting this error from the console: Use of getPreventDefault() is deprecated

Does it has something to do with it?

Jquery update is 1.10

# Answer
try to use Jquery version 1.7.1, or 1.8

If this doesn't work you can try that function this way:

```
$(document).on('click', function (e) {
    if (e.originalEvent.defaultPrevented) return;
    // continue
});

```

If everything was working before, maybe is some other js script added and it is getting the error but the console is not showing it properly
> 0 votes

---
Tags: javascript
---


# Question
Title: How to get Drush to use alternative php.ini
I'm trying to get Drush up and running on my webserver via SSH. I'm new to working with SSH so hopefully someone can help me work this out. When checking Drush's status it mentions that the **disable\_functions** are not empty.

So I copied the webservers php.ini to the .drush file but it still uses the php.ini from the webserver and not from my .drush folder.

I tried finding a solution online but can't get this to work. A couple of thigs I tried are:

* Using a drush.ini file. If I add this I is found by drush and shown in my **drush status**. But it doesn't solve the disable\_functions problem. It also shows the webserver php.ini file. So it's the php.ini first and then the drush.ini.
* I added export PHP\_INI="/path/to/.drush/php.ini" to my .bashrc file and when I run echo PHP\_INI it shows the right path but it doesn't solve my problem. I also did the **source ~/.bashrc** to reload the .bashrc. But this didn't help.

This is the complete **drush status**:

```
The following restricted PHP modes have non-empty values:            [error]
disable_functions. This configuration is incompatible with drush.
Please check your configuration settings in
/opt/alt/php56/etc/php.ini or in your drush.ini file; see
examples/example.drush.ini for details.
exec() has been disabled for security reasons preflight.inc:380      [warning]
exec() has been disabled for security reasons preflight.inc:425        [warning]
exec() has been disabled for security reasons preflight.inc:380        [warning]
exec() has been disabled for security reasons preflight.inc:380        [warning]
 PHP configuration      :  /opt/alt/php56/etc/php.ini
 PHP OS                 :  Linux
 Drush script           :  /home/bin/drush
 Drush version          :  8.0.3
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :

```

Hopefully someone can help me getting this Drush installation to work. Thanks in advance.

Zeb

# Answer
Looks like you are using the Drush Phar, which does not support php.ini selection. You must either:

1. Configure your webserver php-cli php.ini correctly (may not be an option if /opt/alt/php56/etc/php.ini is not writable)

* or -
2. Install Drush via Composer per the installation instructions
> 1 votes

---
Tags: drush
---


# Question
Title: Show node in view based on dropdown in seperated content type
I have two content types. One content type is 'sport' and a other content type is 'teacher'. I collected the content type 'teacher' with views and I display the fields in a block (this is important for my site set-up).

My content type 'sport' is seperated from the content type 'teacher' (this is also important for my site set-up). My content type ‘sport’ is the content type where my block ‘teacher’ is showing up.

My page is look like this:

If I create a new sport like basketball, the information of soccer changes into the information about basketball and the teacher should be Rob (choose from a dropdown when creating a page from content type 'sport').

# Answer
> 0 votes
I found a solution.

I followed the following steps:

* I have created an entity reference (in the content type sport)
* I have created a view with relationship to the entity reference
* I have created a contextual filter, content Nid with the relationship I created before to the entity reference field.

Everything works now!

---
Tags: views
---


# Question
Title: How can users set their own price for their products?
This question is a followup question to my prior question ...

Consider authenticated users of site are "STOREs". Any store (= user) should be able to set the product's price in their profile. So that product A sells at 200$ for Store B and sells at 150$ for Store C. How can I do it? I want Stores can set their price in their profile.

# Answer
> 0 votes
Assuming that you are using the Flag module (as I suggested in my answer to your prior question to "How authenticated users can choose favorite products and show them in their profile?", you could implement an extra (price) field when you define a flag. Such field can then be used to store the Product's price.

So if a user (= Store) then flags a product (to indicated "This store sells this product"), such user could use the extra field to actually indicate the price for that store.

Refer to the community documentation about Attaching fields to flags for more details about this.

---
Tags: 7, commerce
---


title: Load nodes into div using AJAX

text:
# Question
Title: Load nodes into div using AJAX
* I've created a views block that loads all nodes of a certain content type.
* I've added the *Content: Has taxonomy term ID* contextual filter

This works great. In the preview area if I change the value in the "preview with contextual filters" input field it changes the nodes that load below according to which taxonomy term ID I input.

How can I have this same functionality on a normal Drupal page?

I will have a list of links on the page with an href value of the taxonomy term ID. When I click a link, I need it to load all nodes that have been associated with that particular taxonomy term into an empty div using AJAX.

I've read somewhere on here that if the nodes just contain some basic text then using a pure AJAX solution might not be the best but rather accomplish the same thing using views.

# Answer
> 1 votes
Here is the javascript I ended up using to load a views block using AJAX and pass in a contextual filter from the href value of given link on page.

```
function getInfo(args) {

  $.ajax({
    url: Drupal.settings.basePath + 'views/ajax',
    type: 'post',
    data: {
      view_name: 'agent_lookup',
      view_display_id: 'agent_lookup_block', //your display id
      view_args: args,
    },
    dataType: 'json',
    success: function (response) {
        if (response[1] !== undefined) {
        var viewHtml = response[1].data;
        $('#ajax-target').html(viewHtml);
        //Drupal.attachBehaviors(); //check if you need this.
      }

    },
        error: function(data) {
         alert('An error occured!');
        }
  });
}

$('.ajax_button').once().click(function(e){
    e.preventDefault();
    var the_id = $(this).attr('href');
    noSlashes = the_id.replace(/\//g,'');
    getInfo(noSlashes);
});

```

# Answer
> 0 votes
Sounds like removing the contextual filter and instead exposing the taxonomy term filter in your view could be what you need.

Or for a more complicated solution, this could work well.

http://www.stevepolitodesign.com/blog/load-content-drupal-ajax-without-coding

---
Tags: views, ajax
---


title: Add Encryption to Images

text:
# Question
Title: Add Encryption to Images
Is there a way to add encryption to images once they are uploaded on the website and stored on the server?

# Answer
> 2 votes
Encrypted Files module sounds like exactly what you're looking for. From the project page:

> Say you want users of your site to be able to upload and download documents, but you also want these documents to be protected in case someone breaks into your server. This module allows Drupal to encrypt files that users upload and decrypt files for download, keeping the unencrypted versions of files from ever being stored on disk. It does this by creating a custom file stream wrapper that Drupal can read from and write to and a new download method that sits alongside the regular public and private methods. So you can make Encrypted Files the default download method, or only use it as the download method for specific file-type fields.

---
Tags: 7, media, security
---


# Question
Title: Give flagged products in search API a higher search score?
I have a product catalog running on Search API and Search API SOLR Search. Now I was hoping that when a customer flags a product (with the flag module), there would be a way to boost the search score of that particular product. So that when it is flagged as `favorite` it will float to the top, but only for that specific user.

How to alter Search API search scores so flagged items will have a higher score?

# Answer
**TLDR;** Use the Boost Query (bq) parameter

```
function mymodule_search_api_solr_query_alter(array &$call_args, SearchApiQueryInterface $query) {
  $call_args['params']['bq'][] = 'im_field_product$flag_favorite_user:"' . $uid . '"^10';
}

```

---

There are several things at play that made this question difficult to solve.

At first I was looking at `hook_search_api_query_alter()` which I didn't understand, only to find out later (thanks to LeDrupaliste) there is also a `hook_search_api_solr_query_alter()`.

Then there was the challenge to sort the results based on the flag. I wanted to return all relevant content, but have favorite (flagged) products returned first. Mostly on the shop landing page (empty search query). So I needed to sort the results, giving the results with the matching flag and user higher priority. Too bad flag's integration with Search API exposes it as a multi-value field and SOLR is not capable to sort on mutli-value fields.

So in the end the client and I came to agree that we only display flagged products on the empty query page, which was implemented like this:

```
function mymodule_search_api_solr_query_alter(array &$call_args, SearchApiQueryInterface $query) {
  if (empty($call_args['query'])) {
    $call_args['query'] = 'im_field_product$flag_favorite_user:7^20 OR *:*';
  }
}

```

If the query is empty, query for the indexed flag field `im_field_product$flag_favorite_user` where the value matches the users uid `7` in this case and boost the score `20` times to ensure high relevance. To prevent the query from hiding all other results, also include all other non-empty fields `*:*`.

It is not yet exactly what I wanted, but it is very close. Now I only need to find a way to append this a regular search. Returning all items matching the keywords, but with the favorite onces on top.

```
$call_args['query'] = 'im_field_product$flag_favorite_user:7^20 OR ' . $call_args['query'];

```

Above returns the flagged items always first even if no field matches the rest of the query. Undesirable as it provides irrelevant search results. (i get a yellow product even though I search for a red one)

```
$call_args['query'] = 'im_field_product$flag_favorite_user:7^20 AND ' . $call_args['query'];

```

Above returns only results if the product is flagged and contains the correct query fields. No other products matching the query will be returned. (only red products that are marked favorite are returned)

```
$call_args['query'] = 'im_field_product$flag_favorite_user:7^20 ' . $call_args['query'];

```

Same as with `AND`.

I will update the answer once I've found a way to do this properly.

ps. I've found the field name through the SOLR web interface, but Search API SOLR probably provides it somehow.

**UPDATE**

In the end I solved it like this:

```
if (empty($call_args['query'])) {
  $call_args['query'] .= 'im_field_product$flag_favorite_user:' . $uid . '^9 OR *';
}
else {
  $call_args['query'] .= ' AND (im_field_product$flag_favorite_user:' . $uid . '^9 OR *)';
}

```

It adds a single filter to the query if no query exists, showing all products, but giving priority to the flagged ones. If there is an existing query, we use the AND clause to again select all products and give priority to the flagged ones, but also match it against the existing query so it honors the provided search terms. It is important to match everything (`*`) in the AND clause otherwise only flagged products are shown.

**UPDATE2**

I just discovered the Boost Query parameter.

> The bq parameter specifies an additional, optional, query clause that will be added to the user's main query to influence the score.

So the code has been updated to:

```
function mymodule_search_api_solr_query_alter(array &$call_args, SearchApiQueryInterface $query) {
  global $user;
  $uid = $user->uid;

  $call_args['params']['bq'][] = 'im_field_product$flag_favorite_user:"' . $uid . '"^10';
}

```
> 2 votes

# Answer
You could have a view that shows flagged nodes by user and a view attachment for the index filtering out nodes that the user has flagged.
> 3 votes

# Answer
Sounds to me like you would need to add this flag to the index. Given that bit of knowledge, it was only about 5 minutes to find this Drupal issue:

Search API: Flag module integration

Which does have a reasonable snippet of code that helps bring out to the index a count of "flags" per node.

```
<?php
/**
 * Get the flag count for a given node.
 */
function mymodule_get_count($entity, $options, $name, $entity_type, &$info) {
  // Requiring type node since we're relying on $entity->nid,
  // but this could be used for user objects too.
  if ($entity_type == 'node') {
    $query = db_select('flag_counts' ,'fc');
    $query->fields('fc', array('count'));
    $query->condition('fc.fid', $info['data']['flag']->fid);
    $query->condition('fc.content_type', 'node');
    $query->condition('fc.content_id', $entity->nid);
    $count = $query->execute()->fetchColumn();
  }
  return !empty($count) ? $count : 0;
}

/**
* Implements hook_entity_property_info_alter().
*/
function mymodule_entity_property_info_alter(&$info) {
  if (isset($info['node']['bundles'])) {
    // For each content type.
    foreach ($info['node']['bundles'] as $bundle_type => $bundle) {
      // Find all applicable flags for this content type.
      $flags = flag_get_flags('node', $bundle_type);
      // For each applicable flag.
      foreach ($flags as $fid => $flag) {
        $info['node']['bundles'][$bundle_type]['properties']['flag_' . $flag->name . '_count'] = array(
          'label' => t('@title Flag Count', array('@title' => $flag->title)),
          'description' => t('The total number of @title flags for this node.', array('@title' => $flag->title)),
          'type' => 'integer',
          'getter callback' => 'mymodule_get_count',
          'computed' => TRUE,
          'data' => array('flag' => $flag),
        );
      }
    }
  }
}
?>

```

But this isn't what you would need. You would need a module like commerce\_search\_api that provides a referenced entity index (commerce uses a product reference field, similar to the way flag references content entities on flag entities). So, your best bet is to:

1. Start with the commerce\_search\_api module
2. Modify the module for flag
3. Then you should be able to add the user of the flag to your index

> Note: I believe Flag is the reverse relationship which might pose an additional challenge to making a modified module do what you need to do.
> 1 votes

# Answer
You can try hook\_search\_api\_solr\_search\_results\_alter (or hook\_search\_api\_solr\_multi\_search\_results\_alter if you are doing multi index search)

I can't test for now if changing score here alters the results order but you can use your own sort function if necessary (with usort)
> 0 votes

---
Tags: flags, search
---


title: How to add Flag to a rendered View

text:
# Question
Title: How to add Flag to a rendered View
I've set up the default Flag (bookmark) and have added the proper links to my node.tpl.php pages so that the flags show up properly. Is there any way to add the same link to a rendered view (page?) I tried using views-view.tpl.php and adding the following code:

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

But that doesn't work because the rendered view is not a node, of course. What I'm trying to do is allow users to bookmark a rendered page view just like they can do with any other node.

# Answer
> 2 votes
> Just a single flag for the rendered page view that displays all articles (i.e., a way to bookmark the "read all news" page.)

ok then doing it the way you were doing it, is the way to go.

`$node->nid` alone won't return the nid, you need to to use menu\_get\_object() function

```
<?php

if ($node = menu_get_object()) {
  // Get the nid
  $nid = $node->nid;

print flag_create_link('bookmarks', $nid);

}

?>

```

**Note 1:** If you're using a page view, the above won't work since it cannot fetch an nid since page view's don't have node id's. In order to get it to work, you can create a block view, and then create a node where you insert your block view. Then since the node has a nid, it's able to fetch the node id.

**Note 2:** You can ignore all the comments below, as they were due to using a page view (see note1)

---
Tags: views, flags
---


title: Increase security on logon

text:
# Question
Title: Increase security on logon
I am using Logintoboggan module but by chance by playing around with Wireshark packet sniffing tools I can see all login details and passwords when users login/register on my site!

Is there a way to encrypt login details and/ or add extra security to this module - Are there better secure modules out there?

# Answer
> 1 votes
### Secure Login

> For sites that are available via both HTTP and HTTPS, Secure Login module ensures that the user login and other forms are submitted securely via HTTPS, thus preventing passwords and other private user data from being transmitted in the clear. Secure Login module locks down not just the user/login page but also any page containing the user login block, and any other forms that you configure to be secured.
>
> For Drupal 7 and 8, Secure Login module enforces secure authenticated session cookies, thus preventing session hijacking. For previous versions of Drupal, PHP's session.cookie\_secure flag must be enabled on the HTTPS site to enforce secure session cookies.

### Login Security

> With Login Security module, a site administrator may protect and restrict access by adding access control features to the login forms (default login form in /user and the block called "login form block"). Enabling this module, a site administrator may
>
> limit the number of invalid login attempts before blocking accounts, or deny access by IP address, temporarily or permanently. A set of notifications by email or Nagios may help the site administrator to know when something is happening with the login form of their site:
>
> password and account guessing, bruteforce login attempts or just unexpected behaviour with the login operation.

---
Tags: 7, users, security, authentication-authorization
---


title: Wrap <div> inside <a> tag

text:
# Question
Title: Wrap <div> inside <a> tag
This is valid HTML5. Yet Drupal 7 seems to ignore it.

This is what is entered into the node (using FULL HTML and no WYSIWG)

```
<a style="display:block; height: 50px; width: 200px" href="http://somewhere.com">
  <div class="xyz">My div contents</div>
</a>

```

And this is what the garbage rendered:

```
<p><a style="display:block; height: 50px; width: 200px" href="http://somewhere.com"></a></p>
<div class="xyz">My div contents</div>
<p></p>

```

Any success in beating Drupal into submission when it comes to respecting valid HTML5?

# Answer
> Any success in beating Drupal into submission when it comes to respecting valid HTML5?
> 2 votes

---
Tags: nodes, input-formats
---


title: My login form seems to have disappeared

text:
# Question
Title: My login form seems to have disappeared
I'm developing a custom theme and even though I have placed the "user login" block in a region, I can't find it and now I'm locked out.

My site is on Drupal 8.

# Answer
The login block is "a" way to get logged in. Another solution to get loged in is to navigate to an URL like `/user/login`.

So try that, and see what happens then. Of course, if you get logged in, hurry to move that disappeared block to some region that for sure you now is OK. To QA test it, use another browser before logging out again ...
> 1 votes

# Answer
Phew!!. After hours of almost going crazy, I finally solved this by removing the custom theme from the theme directory. The default theme presented me with a login form and I'm back in. Thanks guys for help.
> 1 votes

---
Tags: blocks, 8, users
---


title: Alternative views on content type

text:
# Question
Title: Alternative views on content type
How do you allow a content type to publish an option that changes views options of that page?

I have created 2 views slideshows block with different settings - I want the user to choose how to view the images on any page of a certain content type BUT DONT WANT TO SAVE THE PAGES TWICE - the images must be shown programmatically depending on which view option is chosen.

I saw this tutorial on rendering views via a tpl.php file...

I do not know how to create and where to place this tpl.php file -- Could this be implemented as a module instead? What do you place in the $args function - are there any useful examples?

# Answer
Add a new field to your content type:

* Name: **Pick a view**
* Type: **boolean**
* Widget: \[doesn't matter\]

Then add this code to your block or node or page tpl.php file.

```
<?php

if ($node = menu_get_object()) {
  // Get the nid
  $nid = $node->nid;

$node = node_load($nid);
$wrapper = entity_metadata_wrapper('node', $node);
$field_value = $wrapper->field_pick_a_view->value();

if ($field_value == 1) {
  print views_embed_view('my_view', 'block_1');
  } else {
  print views_embed_view('my_view', 'block_2');
  }
}

?>

```
* replace **view\_name** with your view name
* replace **block\_1** or **block\_2** with your machine name

So if your field is check-marked, it prints view 1. If it's not checked-marked, it prints view 2.
> 3 votes

---
Tags: 7, views, nodes
---


title: How do I add JS libraries in DrupalGap

text:
# Question
Title: How do I add JS libraries in DrupalGap
I am hoping to add Slick Library within my DrupalGap but when I try to use it, I am unable to.

The library is added normally within index.html but when one my node page (which has the HTML in it) tries to use it, it doesn't work.

Any idea how to do this correctly.

# Answer
Including the Slick carousel `.js` file in the `index.html` file is correct.

You can use the brand the new `hook_entity_view_alter` to attach a `pageshow` handler to the node's page:

In the `pageshow` handler is when you'd initialize the carousel. The `pageshow` event fires after page is shown to the user. There are a few other hooks you could use to have a chance to place the `pageshow` event on a node's page within the app:

The `hook_entity_view_alter` is the most powerful and is brand new, so you need the latest `bin/drupalgap.min.js` file and the latest `jdrupal.min.js` file to run it. But that is the hook I'd recommend using
> 1 votes

---
Tags: javascript
---


# Question
Title: How to delay the execution of a rule for 5 minutes?
I'm using the module "Facebook Autopost" to post Drupal content on Facebook. When a new node is created, a link to this node is posted on a Facebook page. Facebook's scraper picks up the link and tries to scrape this.

This is configured in a rule. Currently, it looks like this:
https://i.stack.imgur.com/nZCe6.jpg

When a new node is created, the rule is executed. The link gets posted on the Facebook page, but the scraper seems to get a 404. It appears the rule is executed too fast, BEFORE the actual node is created.

Is there a way to delay the execution of the actions so the node is actually created already?

# Answer
> Is there a way to delay the execution of the actions so the node is actually created already?

Yes, you need to enable the Rules Shecheduler module (comes with rules).

Then Create a Rule Component that will do your action.

Then create a rule with action of schedule component. (set it to 5 mins)

For example, see Rules Conditions being evaluated after schedule time elapsed?

Attention:

> Be aware that the actual trigger will only happen the next time your Cron job runs. So if you say "after 5 mins", and the next Cron job runs in say about an hour, then it'll only be after about an hour. If that's not acceptable (as was the case in this question), then you'd have to run your cron job like every 5, 10 or 15 minutes.

So I suggest using Ultimate Cron, that way you can target, so that only your rule cron job runs every 5 or x mins, instead of running every single cron job.

In other words, it allows you to run different catagories/module cron jobs at different times. While you could run less crucial jobs, like Update Manager, only once a day (every 24 hours).
> 2 votes

---
Tags: 7, rules
---


# Question
Title: Can I use fewer modules for implementing my newsletter?
I came across a Drupal 7 site that uses the following modules to send a newsletter to users (6000 users subscribed): Simplenews, Mail system, Mime mail, simplenews rules, variable email, HTML mail, and Rules.

Would using only the Newsletter and Webform modules be sufficient?

If I move to a more minimalist solution, how could I save all the 6000 subscribed users?

# Answer
> 4 votes
I think that with 6000+ emails to send you need to use an external mailer like MailChip or MailUp. Remember that these services have the correct infrastructure to support massive send email and dashboard report.

We have written a module for 1 of our clients that permits to create NewsLetters in Drupal and send it via MailUP for example.

However 7 modules to send an email are not a big number because in Drupal each module exec a single work:

* Simplenews is the module that manages the newsletter (user subscribe, unsubscribe, check, etc etc).
* Mimemail, htmlmail and Mail system permits to create correct HTML email and send it in correct way. And in this case you can reuse all for the internal mail (wellcome, lost password, etc.).
* Rules manage "the" rules of sending email (in this case).

In other systems you have a big module that manages all but not so good like single modules for single works. And in many cases the big module is not compatible with other modules. In Drupal I have found only very few cases where a module is not compatible with other modules.

# Answer
> 1 votes
The MailChimp module is very minimalist, giving you a very good ecosystem !

You call sync all your leads (users) to a normal mailchimplist.

Here's a tutorial: How-To Article: MailChimp Module for Drupal.

# Answer
> 1 votes
Have a look at my answer to the question about "How to eMail a file uploaded to a Webform to a sysadmin using the Rules module?".

It explains how to use the Rules module for sending an eMail. To do so, it uses the Mail System and Mime Mail modules ... only!

With some commonly used Rules techniques (like Rules Scheduler, Rules components, etc), it should be pretty forward to make that work for your case also. Possibly you may want to add the Webform Rules modules also to further improve your implementation.

---
Tags: 7, emails
---


title: Customizing Output of Views Block

text:
# Question
Title: Customizing Output of Views Block
I'm trying to figure out how to alter the output of a Views Block. The first image shows the situation that I'm stuck in, which obviously looks horrible, and the bottom two images are of what I would like to see, as well as the likely div plan. This is my first time working on this type of issue, so if someone has an idea of where to go, or if there is a module available for me to work with. I'm just looking for the cleanest way of getting to the output goal. Thanks!

# Answer
In Style settings you can add a class to your fields.

To achieve your look, move the picture above the title.

Then add css class to your picture field.

Then add the following css code to your theme's .css file `.pictureclass { float: left; }`

---

# BONUS INFO

In Format Settings, you can add classes to your rows

In css class, you can add a class to your entire view
> 1 votes

# Answer
Probably best to use a Format for the display of 'Unformatted list' instead of HTML List.

In your view hide all your fields by setting 'Exclude from display'.

Add a 'Global: Custom text' field and use it to write your html that includes your fields via Replacement Pattern Tokens.

Structure your html and CSS according to this post which explains the use of the CSS property of overflow very well.

CSS: Clearing Floats with Overflow

> Demo 2: Overflow:auto can also be used to prevent content from wrapping around the floated element. Let's say you are designing a comment list. You would, most likely, have an avatar floating on the left and the comment to the right. To prevent the comment from wrapping around the avatar just add overflow:hidden to the comment container. The advantage of using overflow here is that I don't have to set a float or width to the comment container. The container automatically aligns after the floated avatar image.
> 0 votes

---
Tags: views, blocks
---


title: add class to fields on login block

text:
# Question
Title: add class to fields on login block
I am using drupal 7 and would like to customise my login form block.

```
function theme_form_alter(&$form, &$form_state, $form_id) {

```

if ($form\_id == "user\_login\_block") { $form\['links'\] = Null; // Remove Request New Password and other links from Block form //$form\['links'\]\['#markup'\] = t('Forgotten Password?') . ' ' . t('Forgotten Password?') . ''; // Remove Request New Password from Block form //$form\['links'\]\['#markup'\] = ' ' . t('Register') . '' . ' ' . t('Forgotten Password?') . ''; // Remove Request New Password from Block form

```
    $form['#prefix'] = '<div class="nano-ui">';
    $form['#suffix'] = '</div>';

    $form['name']['#attributes']['class'][]= array("nui-input");

    $form['name']['#title'] = Null; // Change text on form
    $form['name']['#attributes'] = array('placeholder' => t('username'));
    $form['pass']['#title'] = Null;
    $form['pass']['#attributes'] = array('placeholder' => t('password'));

}

```

}

In the above code the following line does not seem to have any effect on my field :

```
$form['name']['#attributes']['class'][]= array("nui-input");

```

# Answer
> 2 votes
This is what will work

```
    $form['#prefix'] = '<div class="nano-ui">';
    $form['#suffix'] = '</div>';

   $form['name']['#title'] = Null; // Change text on form
    $form['name']['#attributes'] = array('placeholder' => t('username'));
    $form['pass']['#title'] = Null;
    $form['pass']['#attributes'] = array('placeholder' => t('password'));

    $form['name']['#attributes']['class'][] = 'nui-input';

```

Here is the reference : How do I use hook\_form\_alter() to add CSS classes to a custom input field in user\_register\_form?

---
Tags: theming, blocks
---


# Question
Title: How to display number of results that would show in a contextually filtered view
I have a view which has some contextual filters (not exposed) which limit the view results so they are only shown to the page author. I would like to show other users how many (total) results there are in the view. I thought I could do that with a Global Results Summary under No Results Behavior, but that only shows results AFTER the contextual filter has been applied.

Any ideas?

# Answer
Add an Attachment to the View. You can control the Access and change the filters.
> 0 votes

---
Tags: views
---


# Question
Title: Advance Search form $form is not the same when invoked a second time?
I Want the users to have an expanded advance search form if no results are returned from a search. The advance search form on the search page always defaults to collapsed.

I found that I can check whether I have results in two different ways: theme or module, depending on the hook I want to use, I chose module because it fires earlier than the theme's.

I also can effect the advanced search form's attributes (whether it's collapsed, or maybe display other data inside of the advanced search form, etc) with drupal's `hook_FORMID_form_alter()` with `MYTHEME_form_search_form_alter`'s first call. The issue I have is `MYTHEME_form_search_form_alter()` gets called before results are returned.

So I can alter the advance search form first, then I can check if we returned any results from the search... which doesn't help me, because I need it to be vice versa - If I know I have no results then I know to expand the advanced search form's collapsible form.

My quick solution was to invoke `drupal_get_form()` with `drupal_get_form("search_form", "no_results");` inside of my module's preprocess search hook `MYMODULE_search_preprocess_search_results(&$variables)` and just pass in the variable `"no_results".` This (as most of you probably know) will invoke `hook_form_search_form_alter` again, where I can edit the advance search form now and I will alter the advance search form only if my variable `"no_results"` comes through.

Here is my crux though! Even though I am invoking that theme hook again and checking for the variable, when I go to edit the `$form`'s `"advanced"` entry... its gone now. So it's clearly there when theme's hook is called, and I can indeed effect the arrays, but if I try to effect the advanced array when I invoke the theme's hook (inside of my module's hook) it's not there. Where would I invoke this theme's hook if not on the module layer? Hell, the theme's preprocess hook is fired AFTER the module's and has proven to be the same circumstance, seems in either of the two ways of checking my results I cannot invoke the form\_alter hook and get the exact same form back.

This is before I check results when THEME's alter hook is first being called:

This is after I check results in my module's hook and invoke the THEME's alter hook once more:

You can see my new variable denoting that we have no result (in this case it's LarryU) under the action key, but there is no advanced key. I tried just remaking it but it doesn't to the form.

# Answer
> 1 votes
As I understood from your question you need to add additional style when no results found.

The file **search-block-form.tpl.php** in search module folder is responsible about displaying the form you could copy it to your theme folder and alter the markup as you need (You have to clear cache in order to flush theme registry).

Also take a look at the two files **search-result.tpl.php** and **search-results.tpl.php** the same could be done depending on your needs and use case.

For more clarification about theme suggestions read

---
Tags: hooks
---


# Question
Title: How to put links in a menu programmatically?
I'm using Drupal 7, and modules such as Service links and Flag.

I would like to put the links proposed by these modules (share or flag) in a menu (main menu or other).

Anybody know the way to follow?

# Answer
> -1 votes
Your question is relatively vague, but to answer the title, here's the code you need to use:

```
$link = array(
  'link_title' => t('Your link'),
  'link_path' => 'your-path',
  // Enter the name of the menu where you want this link to appear.
  'menu_name' => 'main-menu',
  'weight' => 0,
);
menu_link_save($link);

```

---
Tags: 7, theming, navigation
---


# Question
Title: How to implement validation of field values?
I'll soon be involved in a project that requires this, I haven't started yet. I have some experience with Drupal but I'm not that much of a programmer.

Here's how it goes:

* Create a content type with field 1,2,3.
* The user A **adds** a new node, filling those fields.
* The user B can go through those fields and do some kind of "OK" in each one. This OK will only trigger something else that will show a cross or a check mark instead, it won't have any interference with the field, which will not be changed.
* The user A1 adds a new node, and the user B has to go all the way again.

I'm asking your opinion on possible options to accomplish this. I understand that maybe I'll have to write some code...

Here's the draw that illustrates this:

# Answer
You could use the Flag module for this. Excerpt from its project page (bold markup added here):

> ... Flag is a flexible flagging system that is completely customizable by the administrator. Using this module, the site administrator can provide any number of flags for nodes, comments, users, and any other type of entity. Some possibilities include bookmarks, marking important, friends, or flag as offensive. With extensive views integration, you can create custom lists of popular content or keep tabs on important content.
>
> **Flags may be** per-user, meaning that each user can mark an item individually, or **global, meaning that the item is either marked or it is not marked, and any user who changes that changes it for everyone.**
>
> In this way, additional flags (similar to published and sticky) can be put on nodes, or other items, and dealt with by the system however the administration likes.

If you're not familiar with the Flag module, checkout the set of 8 video tutorials about the flag module. Refer to Flag's Community documentation for (way) more details.

Specific to your 3 fields here, you'd need 2 flags for each field X (x=1, 2, 3) (so 3\*2=6 flags in total) whereas you'd add these flags to the nodes where these fields are used:

* 1 flag to indicate `Field X is Valid`.
* 1 flag to indicate `Field X is Not Valid`.

And if you'd then use either of the options I described in my answer to "How to add a custom icon or symbol to a flag link?", you can even make its look and feel match with your requirements.

Optionally also using some CSS magic to align 2 of these flags next to the field X that they are related to (as suggested in a comment below this answer, merci!).

But wait, there is even more: by using all sorts of integrations with the Rules module, you could also implement things like:

* "Send an eMail" to User B whenever User A does something that waits approval/review from User B.
* "Send an eMail" to User A about the result (approve or reject) from User B.
* Implement any kind of validations between those fields, such as "If field 1 has value P, then field 3 is not allowed to have a value of Z".

There are tons of other enhancements you could implement (potentially even causing User B to no longer be needed, since Rules becomes the validation engine ...).
> 0 votes

---
Tags: entities
---


# Question
Title: How use settings.local.php with Acquia Cloud
I try to setup my `.gitignore` file. My **local repo** is a clone from my Drupal 8 distro from Acquia Cloud.

(I want to theme my template locally and then, step by step I want to push it to `Dev` on Acquia Cloud.)

So regarding handeling `settings.php`, whether or not to ignore `settings.php` and whether or not use `settings.local.php`:

If I look in my current `settings.php` is see this:

```
// On Acquia Cloud, this include file configures Drupal to use the correct
// database in each site environment (Dev, Stage, or Prod). To use this
// settings.php for development on your local workstation, set $db_url
// (Drupal 5 or 6) or $databases (Drupal 7 or 8) as described in comments above.

```

I am confused and don't know anymore how to setup my `.gitignore` file with all this information and whether or not use `settings.local.php`. Please can somebody advice my what I have to do exactly, so it's setup correctly from the beginning.

# Answer
> 0 votes
The default `.gitignore` file that ships with your Acquia Cloud git repository is fine as it is. See https://drupal.stackexchange.com/a/193251/23961

I also advised against adding `settings.php` to your `.gitignore` file here.

Using `settings.local.php` is optional. Details about the file are available in the file or the online Drupal documentation as described already here.

---
Tags: 8, version-control, acquia-dev-desktop, acquia-cloud
---


title: Addressfield change max size of column

text:
# Question
Title: Addressfield change max size of column
I'm working with the addressfield module. I need to change the thoroughfare column to have a max length of 960 (or make it a text instead of varchar) instead of the default 255.

However I'm not sure how I should do it.

I've created an empty module with a hook\_schema\_alter()

```
function hook_schema_alter(&$schema) {
  $schema['addressfield']['thoroughfare'] = array(
    'description' => 'The thoroughfare of this address. (i.e. Street address)',
    'type' => 'text',
    'default' => '',
    'not null' => FALSE,
  );
  return $schema;
}

```

However I suspect that the part "$schema\['addressfield'\]\['thoroughfare'\]" is not correct. Nothing is changed when I install the module with this hook.

How to change it? In the original addressfield it returns only columns in the schema hook, it's not really linked to a schema itself?

# Answer
> 0 votes
**That** approach won't affect the column type or size as I get you need to make it store more chars.

**You** could do **hook\_update\_N()** that execute a sql query to change the field type and size.

**Then** yo have to change field settings **see**

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


# Question
Title: node:url token not returning clean (alias) URL
This is a follow-up question of: How to delay the execution of a rule for 5 minutes?

When not delaying the action, the `node:url` token does not return the alias URL, but the URL with the token ID: `...node/id`. I assumed this is because this URL is simply not available yet. I have to use the clean URL, because otherwise a scraper would get a HTTP status code 302 and is unable to scrape the page correctly.

I'm using the Pathauto module to create the URL's automatically.

However, when using the sheduler, I'm still not getting the clean URL. These are my current settings:

The marked token in the screenshot should return the clean URL, but it returns the unclean `/node/id` one. I've already tried to change the token to `[entity-fetched:url:path]`, but this seems to return an invalid URL (or no URL at all, is it possible to debug this?).

Why can't I get the clean URL using tokens in rules?

The weird thing is... if I edit a node instead of creating a new one, `node:url` **does** return the clean URL, but not when using the sheduler.

EDIT:

```
{ "rules_publish_to_fb" : {
    "LABEL" : "Publish to fb",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler", "fb_autopost_entity" ],
    "ON" : { "node_insert" : [], "node_update" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : {
              "event" : "event",
              "inspiration_theme" : "inspiration_theme",
              "news_item" : "news_item"
            }
          }
        }
      },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_facebook_message" } },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_facebook_published" } },
      { "NOT data_is_empty" : { "data" : [ "node:field-facebook-message" ] } },
      { "data_is" : { "data" : [ "node:status" ], "value" : "1" } }
    ],
    "DO" : [
      { "schedule" : {
          "component" : "rules_facebook",
          "date" : "+2 minutes",
          "param_node" : [ "node" ]
        }
      }
}

```

And

```
{ "rules_facebook" : {
    "LABEL" : "facebook",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "fb_autopost_entity" ],
    "USES VARIABLES" : { "node" : { "label" : "node", "type" : "node" } },
    "ACTION SET" : [
      { "entity_fetch" : {
          "USING" : { "type" : "node", "id" : [ "node:nid" ] },
          "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
        }
      },
      { "entity_create" : {
          "USING" : {
            "type" : "facebook_publication",
            "param_type" : "link",
            "param_user" : [ "site:current-user" ]
          },
          "PROVIDE" : { "entity_created" : { "facebook_link" : "Facebook link" } }
        }
      },
      { "data_set" : {
          "data" : [ "facebook-link:field-facebook-message" ],
          "value" : "[node:field-facebook-message]"
        }
      },
      { "data_set" : {
          "data" : [ "facebook-link:field-facebook-link" ],
          "value" : "[entity_fetched:url]"
        }
      },
      { "publish_to_facebook" : {
          "USING" : { "publication" : [ "facebook-link" ], "pages" : "1247812435236072" },
          "PROVIDE" : { "facebook_publication_id" : { "facebook_publication_id" : "Facebook publication returned ID" } }
        }
      },
      { "drupal_message" : { "message" : "[entity_fetched:url]" } }
    ]
  }
}

```

# Answer
> 1 votes
# Option 1 (a): Try another token

Check what result you get by using either of these tokens:

* `[site:current-page:url]`.
* `[node:node-path]`.
* `[node:node-url]`.

# Option 1 (b): Pass the URL as an extra parameter

Inspired by the answer to the question "Send node path alias to user", you might be more lucky to get access to the correct value of your URL (or either of the tokens I suggested above) if you just pass that value to your Rules Component as an extra parameter (so on top of the "node" parm you already have). And of course use the value of that parameter in your Rules Component instead.

The reason why I think you may be more lucky, is that you already have that "`node_is_of_type`"-condition. So because of that, and similar to the answer in the above mentioned question, it should be available in your first rule in which you schedule the Rules Component.

# Option 2: Perform Rules debugging

If Option 1 doesn't help, then I'd recommend you to do some further debugging of your actual rule, as detailed below (and in the order specified).

### Basic debugging

Rules is great, but sometimes also tough to debug if things don't work as you'd expect. There are some typical facilities to do such debugging, but my **K**eep-**I**t-**Super**-**S**imple technique I often use is my ***BINGO***-trick. A sample of such rule can be found in my answer to "Which Rules condition can be used to email a user when an admin updates their profile?". Stupid, but simple and efficient (I think).

### Debugging using Rules settings

Something else that might help to find the answer to your question, is to have a look at Rules **debugging** ... Within the Rules **settings**, experiment a bit with the debugging facilities that come with the rules module. At least have a look at the "***Rules Evaluation Log***" (to check that the Rules logic being executed, actually matches what you expect that logic to be).

### Debugging using the Devel module

Depending on what the result of that type of debugging is, you may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value".

### Video tutorial about Rules debugging

Refer to the (great!) video "Debugging rules configuration" for way more details about the last 2 variations.

---
Tags: 7, rules, tokens, path-aliases
---


# Question
Title: Avoid duplicate ID for a field that appears multiple times on the same form
I'm having a problem with duplicate ID's for a custom field widget.

The scenario: I have an order form, that contains 2 field collections "pick-up" & "delivery". Both these collections contain the same field "field\_delivery\_profile" which is a customer profile reference field with a custom field widget. In the hook\_field\_widget\_form regardless of whether I assign the element an id or not, the ID is the same for both occurrences of the field in the form.

One thing is the breaking W3C standard but the most crucial one for me right now, is that I need to check both fields value change through JS and have to be able at least predict the IDs. Is there maybe a way to get the parent field-collection (that's containing the field) information for assigning a better id?

Best,

Alari

# Answer
> 0 votes
Drupal has a helper function for that:

`drupal_html_id()`:

> Prepares a string for use as a valid HTML ID and guarantees uniqueness.

---
Tags: entities
---


title: Adding css classes to taxonomy terms

text:
# Question
Title: Adding css classes to taxonomy terms
I am trying to have all my taxonomy terms to look different from each other.

Is there a way for me add specific CSS classes to differing taxonomy terms?

# Answer
> 1 votes
Already the **page-taxonomy-term-TERM\_ID** is present on the body tag.

To add more classes you can use `hook_preprocess_html()` and add the `$vars['classes_array']` to add the css classes you want for the terms.

# Answer
> 0 votes
Are you talking about taxonomy pages? If so you can target each one of them with the default body class "page-taxonomy-term-X" where X is the taxonomy id.

If you want a different class, I suggest you to use the context module

# Answer
> 0 votes
If you want add class to term in everywhere I suggest customize taxonomy template with taxonomy-term.tpl.php. This will allow you to customize the output of your term page.

also if you want to add class to it in views result use Field Formatter CSS Class module is what you're looking for.

> Adds a formatter for text/list/taxonomy fields to render as CSS classes on nodes.
>
> The Field formatter CSS class module allows you to set any text/list/option/taxonomy field to render as CSS class on the node. This enables the node author to select predefined CSS styling per node.

# Answer
> 0 votes
you can add new filed

admin/structure/taxonomy/{vocabulary}/fields

then use this filed with custom template

using normal theme suggestions and overwrites or

**Note** this code related to another issue \[*How to render node using custom view mode*\]

```
<?php
/**
 * Implements hook_entity_info_alter().
  add new view info [name , label]
 */
function {ModuleName}_entity_info_alter(&$entity_info) {
  $entity_info['node']['view modes']['{ViewName}'] = array(
    'label' => t('{ViewName Label}'),
    'custom settings' => TRUE,
  );
}

/**
 * Implements hook_theme_registry_alter().
  register templates path so drupal could find this view name template
  and you could add this template inside your module
 */
function {ModuleName}_theme_registry_alter(&$theme_registry) {
    // Defined path to the current module.
  $module_path = drupal_get_path('module', '{ModuleName}');
  // Find all .tpl.php files in this module's folder recursively.
  $template_file_objects = drupal_find_theme_templates($theme_registry, '.tpl.php', $module_path);
  // Iterate through all found template file objects.
  foreach ($template_file_objects as $key => $template_file_object) {
      // If the template has not already been overridden by a theme.
      if (!isset($theme_registry[$key]['theme path']) || !preg_match('#/themes/#', $theme_registry[$key]['theme path'])) {
          // Alter the theme path and template elements.
          $theme_registry[$key]['theme path'] = $module_path;
          $theme_registry[$key] = array_merge($theme_registry[$key], $template_file_object);
          $theme_registry[$key]['type'] = 'module';
      }
  }
}

/**
 * Implements hook_preprocess_node().
  use our custom view as theme suggestions while rendering this a node who use this view mode
 */
function {ModuleName}_preprocess_node(&$variables) {
  if($variables['view_mode'] == '{ViewName}') {
    $variables['theme_hook_suggestions'][] = 'node__' . $variables['type'] . '__{ViewName}';
  }
}

```

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


# Question
Title: restrict shipping of particluar item for paticular shipping zone
Is there a module available to restrict the shipping of the particular product for particular shipping zone(country)? so that the message would appear and cancel the checkout.

# Answer
1. Add a field in variant for shipping restriction countries
2. Add a rule in with event Collecting shipping rates for an order
3. Add a php condition to get the line items details from $commerce\_order
4. Check shipping restricted countries with shipping address countries in your php function
5. Remove the product by commerce\_cart\_order\_product\_line\_item\_delete()
6. Add an action to show the msg on site
> 1 votes

# Answer
I'm fairly certain there isn't a module that does this. You can build this with rules, but the effect will be very rudimentary.

Create a rule reacting to `order` updates:

1. Checks for a particular product included in the order.
2. Checks to see if a shipping address condition is met.
3. For your action, display a system message.
4. Set the status of the order to `cart` or perhaps `checkout:shipping`.

That way you wouldn't be able to advance past the shipping status without having it fulfilled.

Not knowing your situation, cancelling an order is a bit extreme, but you could forward the user to a webform, change the status of the order to some new, internal value for review, or even just remove the product from the cart so that the customer can continue.
> 1 votes

---
Tags: commerce
---


title: Clear views cache on specific node

text:
# Question
Title: Clear views cache on specific node
I want to clear the cache of specific node's view. In my database in cache\_views\_data table I found the cid of my view and the format is like "views\_name:display:hash" but I cannot find this hash where is reffering to.

# Answer
> 0 votes
Here's how you can clear cache of specific view:

```
cache_clear_all('ctools_export:views_view:' . $NAME_OF_YOUR_VIEW, 'cache_views', TRUE);
cache_clear_all($NAME_OF_YOUR_VIEW, 'cache_views_data', TRUE);

```

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


title: Fetch discount start date and end date

text:
# Question
Title: Fetch discount start date and end date
I have a discount 'women's day'. I have set start and end date as 8March 8AM to 8 March 8PM for this discount. In my coupon validation function, I want to check if the current time is in between 'women's day' discount start and end time or not. So I basically need a start and end time of discount.

# Answer
> 1 votes
I think you don’t want to allow a coupons for specific time period, if discount is activated for specific period

1. Add a rule with event Redeem a coupon
2. Add a condition Data comparison to check site:current-date \> start date (value)
3. Add a condition Data comparison to check site:current-date \< end date (value)
4. Add an action to remove all the coupon 5 Add an action to show msg on site

# Answer
> 1 votes
I don't understand why do you need that..

From your question I can assume you have both the discount module and coupons module..

If using discount in general, you don't need to apply a coupon, and the discount will be applied with rules only on the dates that you put in on the default discount creation form.

The same goes for coupon creation, when creating a coupon, you can set coupon criteria as date range and that will also be applied by default in coupon validation.

# Answer
> 1 votes
You should be able to load the discount by using:

```
$discount = entity_load('commerce_discount', YOUR_DISCOUNT_ID);

```

To see what's available to you, install Devel and use the `dpm()` function:

```
$discount = entity_load('commerce_discount', YOUR_DISCOUNT_ID);
dpm($discount);

```

You can run this from the `/devel/php` page.

---
Tags: commerce
---


# Question
Title: How to create a shortcut to IMCE File Browser?
The File Browser link is different for each user, e.g.:

```
http://example.com/user/1/imce
http://example.com/user/10/imce

```

How can I create a shortcut to the File Browser which is good for all users?

# Answer
Use me aliases module.

It turns:

```
http://example.com/user/10/imce

```

to:

```
http://example.com/user/me/imce

```
> 1 votes

# Answer
For the current user /imce path should work:

```
http://example.com/imce

```
> 1 votes

# Answer
This is default page provided by IMCE module, you can create your own menu callback which will call same page callback which is used by "user/\[UID\]/imce". To do this you can use hook\_menu. Once you've done that, if required you can remove access to default page using hook\_menu\_alter.

Here is example of how you can achieve this:

```
function MODULENAME_menu() {
  $items['custom-imce'] = array(
    'title' => 'File browser',
    'page callback' => 'MODULENAMW_imce_user_page',
    'access callback' => 'MODULENAMW_imce_user_page_access',
  );

  return $items;
}

function MODULENAMW_imce_user_page() {
  global $user;

  if (!empty($user->uid)) {
    module_load_include('inc', 'imce', 'inc/imce.page');
    imce_user_page($user);
  }
  else {
    drupal_set_message(t('Please login to access this page.'), 'warning');
    drupal_goto('');
  }
}

function MODULENAMW_imce_user_page_access() {
  global $user;

  if (!empty($user->uid)) {
    return imce_user_page_access($user);
  }

  return FALSE;
}

```
> 0 votes

---
Tags: 7
---


# Question
Title: Limit row items to 1 as per the GROUP BY result in Views 3.x
I'm trying to limit row items to 1 as per the GROUP BY result in Views 3.x, below is the view which I've created but I'm missing the key part from that, below is the exported code of my view.

```
$view = new view();
$view->name = 'position';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Position';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Position';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['grouping'] = array(
  0 => array(
    'field' => 'field_home_page_anchor_position',
    'rendered' => 1,
    'rendered_strip' => 0,
  ),
);
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
  'field_home_page_anchor_position' => 'field_home_page_anchor_position',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'field_home_page_anchor_position' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: Home Page Anchor Position */
$handler->display->display_options['fields']['field_home_page_anchor_position']['id'] = 'field_home_page_anchor_position';
$handler->display->display_options['fields']['field_home_page_anchor_position']['table'] = 'field_data_field_home_page_anchor_position';
$handler->display->display_options['fields']['field_home_page_anchor_position']['field'] = 'field_home_page_anchor_position';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Sort criterion: Content: Home Page Anchor Position (field_home_page_anchor_position) */
$handler->display->display_options['sorts']['field_home_page_anchor_position_value']['id'] = 'field_home_page_anchor_position_value';
$handler->display->display_options['sorts']['field_home_page_anchor_position_value']['table'] = 'field_data_field_home_page_anchor_position';
$handler->display->display_options['sorts']['field_home_page_anchor_position_value']['field'] = 'field_home_page_anchor_position_value';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'news_story' => 'news_story',
);
/* Filter criterion: Content: Home Page Anchor Position (field_home_page_anchor_position) */
$handler->display->display_options['filters']['field_home_page_anchor_position_value']['id'] = 'field_home_page_anchor_position_value';
$handler->display->display_options['filters']['field_home_page_anchor_position_value']['table'] = 'field_data_field_home_page_anchor_position';
$handler->display->display_options['filters']['field_home_page_anchor_position_value']['field'] = 'field_home_page_anchor_position_value';
$handler->display->display_options['filters']['field_home_page_anchor_position_value']['operator'] = 'not empty';
$handler->display->display_options['filters']['field_home_page_anchor_position_value']['value'] = array(
  'min' => '',
  'max' => '',
  'value' => '',
);

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');
$translatables['position'] = array(
  t('Master'),
  t('Position'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Home Page Anchor Position'),
  t('Block'),
);

```

SQL query generated by View is:

```
SELECT node.title AS node_title, node.nid AS nid, node.created AS node_created, field_data_field_home_page_anchor_position.field_home_page_anchor_position_value AS field_data_field_home_page_anchor_position_field_home_page_a, 'node' AS field_data_field_home_page_anchor_position_node_entity_type
FROM
{node} node
LEFT JOIN {field_data_field_home_page_anchor_position} field_data_field_home_page_anchor_position ON node.nid = field_data_field_home_page_anchor_position.entity_id AND (field_data_field_home_page_anchor_position.entity_type = 'node' AND field_data_field_home_page_anchor_position.deleted = '0')
WHERE (( (node.status = '1') AND (node.type IN  ('news_story')) AND (field_data_field_home_page_anchor_position.field_home_page_anchor_position_value IS NOT NULL ) ))
ORDER BY node_created DESC, field_data_field_home_page_anchor_position_field_home_page_a ASC

```

# Answer
> 0 votes
Don't know if I understood the question, but if you want to group the results in views, in the view edit page, in **Advanced** \>\> **Other** \>\> **Use aggregation** you can select the *Aggregate* option for the display. After that, each filed will have an *Aggregation settings* link for your to select the aggregation options you need to generate the *group by* part of your SQL query.

---
Tags: views
---


# Question
Title: How to add classes to every menu block placed within in a specific region?
How do I add classes to menus but only when they appear within a certain region? Is there a way to do this in a theme?

# Answer
> 1 votes
you can augment the variables collection available to any twig file by tweaking the appropriate preprocess ... for example ... if you create the following function within your $THEME$.theme file:

```
function $THEME$_preprocess_block(&$variables) {
  $block_id = $variables['elements']['#id'];
  $block = \Drupal\block\Entity\Block::load($block_id);
  $variables['region'] = $block->getRegion();
}

```

you can then access the newly defined **region** variable from within:

```
{{ region }}

```

you could then add your desired classes to menus but only when they appear within a certain regions:

```
{% set classes = 'menu' ~ ((region == 'header') ? ' menu-header') %}
{% block content %}
    <nav {{ content_attributes.addClass(classes) }}>
        {{ content }}
    </nav>
{% endblock %}

```

that would add the class **menu** to all blocks and additionally would add the class **menu-header** to any block within the header region

hope that helps!

---
Tags: 8, theming
---


title: Price is 0 then show "On Request" text

text:
# Question
Title: Price is 0 then show "On Request" text
I have to show "On request" if price is 0, I have used **Commerce Extra Price Formatters** and it allow us to do so,but I need currency converter block also and if I go through **Commerce Extra Price Formatters** then it will not convert currency, So if there is any other alternative to show text without using any module then pls suggest..

# Answer
There's actually quite a nice module for this also:

https://www.drupal.org/project/commerce\_free\_price\_formatter

The beauty of it is, that is works as a price formatter and you can use it on specific displays, product types or views as you desire :)

And this module only changes the name of 0 price to what you want, and the formatter settings have a fallback formatter choice, where you can chose your current default formatter for all the times when the price isn't 0
> 0 votes

# Answer
Add this to your (template) .tpl.php file

```
<?php

if ($node = menu_get_object()) {
  // Get the nid
  $nid = $node->nid;

$node = node_load($nid);
$wrapper = entity_metadata_wrapper('node', $node);
$field_value = $wrapper->field_price->value();

if ($field_value == 0) {
  print 'On Request';
  } else {
  print $field_value;
  }
}

?>

```

Not sure if the machine name of price is `field_price`.

If the machine name is just `price` then use `$field_value = $wrapper->price->value();` instead.
> 0 votes

---
Tags: commerce
---


title: Hook that runs on admin pages

text:
# Question
Title: Hook that runs on admin pages
I'm trying to find a D7 hook that runs on admin pages (admin/people/create to be exact). I've tried many hooks, but none of them seem to be firing on admin pages. What is the best way to detect if user is on admin/people/create?

Thanks

# Answer
> 3 votes
In case other people have the same question for D7, you can always use `hook_page_alter()`. It will be invoked on all pages. Here's an example:

```
function YOUR_MODULE_page_alter(&$page) {
  // Check if the user is on /admin/people/create.
  if (current_path() == 'admin/people/create') {
    // Do whatever you want.
  }
}

```

However, do bear in mind that:

1. This code needs to be in a custom module in order to be invoked everywhere.
If you add this to your front end theme, it will not be executed unless you are using the front end theme for managing the site as well.
2. This way you can recognize if the user on that page, but you will not be able to alter the form. To alter the form, check out @Weboide's answer - you'll have to use `hook_form_alter()`.

# Answer
> 0 votes
You could hook into the different forms that `user_admin()` uses.

There is:

* user\_register\_form (for creating users)
* user\_multiple\_cancel\_confirm (for cancelling accounts)
* user\_filter\_form (searching for users)
* user\_admin\_account (also searching for users, but to do a mass update)

For example, to see when they're creating a user, using a hook like this could work:

```
function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id)
{
  // do your thing.
  if(user_access('administer users'))
    // then an admin is creating the account
}

```

---
Tags: hooks
---


# Question
Title: Replace YouTube URL with player in nodes and comments?
Is there a module or something similar I can use to replace a YouTube URL with the actual video in a node and also in comments?

I've found a few that work for the node, but what about in comments as well?

# Answer
Use the Googtube module for this. It will provide you with an additional input format, which you can use wherever you want.

From the project page:

> Googtube allows users to embed Youtube, Vimeo and Google Videos in a simple way without tags. When users post a url to videos the link is automatically converted to a video witch is actually embed code.
> 0 votes

---
Tags: files
---


# Question
Title: Cannot find image properties when uploading
I'm building an LXC based on an existing and working well website. I've checked that all settings where the same. However, when I want to save a content after having uploaded an image on my LXC, I get the following error:

> PDOException: SQLSTATE\[HY000\]: General error: 1366 Incorrect integer value.

I have thoroughly searched the web all the day to read every close topic but none gave me a suitable answer.

The fact is when the *Field SQL Storage* module try to get the properties of my image; it is unable to find its parameters, so the width and height properties are empty and the SQL query is crashing.

Why Drupal can't read my image properties and store them in database?

# Answer
I finally found the answer. There was missing packages in my server configuration...I needed to install those :

```
aptitude install php-apc php-pear php5-curl php5-gd php5-mcrypt

```
> 0 votes

---
Tags: files, media
---


# Question
Title: Enable/ Disable elements under 'edit' depending on role
I want some users to have access to certain items under the 'edit' tab but hide others...

I know you can allow a role to 'edit' or not 'edit' a published node content type but that enables and disables the whole of the edit tab!

# Answer
As I understand your question, you need the Field Permissions module. From the project page:

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

This will allow you to grant permission for editing certain fields to a specific user role.
> 0 votes

---
Tags: 7, nodes, users
---


title: How do I add custom theme settings?

text:
# Question
Title: How do I add custom theme settings?
In my theme I have link to social network. So, I would like to have field in theme settings where administrator can put link what would be use in all place where is **{{link-social-network}}**.

```
<a href="{{link-social-network}}" class="btn-social btn-outline"><i class="fa fa-fw fa-facebook"></i></a>

```

I also read that theme settings default values can not be set in a theme's info.yml files.

The theme's **config/install/THEME.settings.yml** file should have that information.

# Answer
> 14 votes
You can create new file and call it as `theme-settings.php` and add the following to it or even add this to THEME\_NAME.theme file.

```
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Theme\ThemeSettings;
use Drupal\system\Form\ThemeSettingsForm;
use Drupal\Core\Form;

function THEME_NAME_form_system_theme_settings_alter(&$form, Drupal\Core\Form\FormStateInterface $form_state) {
  $form['THEME_NAME_settings']['social_icon']['social_url'] = array(
    '#type' => 'textfield',
    '#title' => t('Social Link'),
    '#default_value' => theme_get_setting('social_url', 'THEME_NAME'),
  );
}

```

Then you need to add the following to `THEME_NAME.theme` file.

```
function THEME_NAME_preprocess_page(&$variables) {
  $variables['social_url'] = theme_get_setting('social_url','THEME_NAME');
}

```

Then you can use it in the `twig` file.

```
<a href="{{ social_url }}" class="btn-social btn-outline"><i class="fa fa-fw fa-facebook"></i></a>

```

To have a default value for the social url, you can include it in your `config/install/THEME.settings.yml`

Hope it helps!

# Answer
> 4 votes
Additional to Suresh's answer: If you want to have all theme settings available in your twig template, use the following function:

```
use Drupal\Core\Cache\CacheableMetadata;
function _THEME_extend_variables(&$variables){
  // Add cachability metadata.
  $theme_name = \Drupal::theme()->getActiveTheme()->getName();
  $theme_settings = \Drupal::config($theme_name . '.settings');
  CacheableMetadata::createFromRenderArray($variables)
    ->addCacheableDependency($theme_settings)
    ->applyTo($variables);
  // Union all theme setting variables to the twig template variables.
  $variables += $theme_settings->getOriginal();
}

```

and call it when ever you need to extend `$variables`:

```
function THEME_preprocess_page(&$variables) {
  // extend twig variables with theme settings
  _THEME_extend_variables($variables);
  // do fancy stuff
}

```

This is more or less copy pasted from basic theme.

---
Tags: 8, forms
---


# Question
Title: How to make the commerce_kickstart distribution fully multilingual?
I just downloaded and installed the Commerce Kickstart 7.x-2.0-rc1 distribution.

Now I'm in the process of making it fully multilingual. I have no problem with the products.

But I don't know how the make multilingual the Search blocks (Facet) which you can see in the left sidebar in this demo. I already enable the taxonomy\_translation module, then I'm able to translate the terms used by the facet. But if I switch languages the facet shows all terms regardless the language the term is in. I also enabled the facetapi\_i18n but I see no changes at all.

Any suggestions about how to do this?

# Answer
You'll want to look at these two different resources:

Configure entity translation for Drupal Commerce

and

Search API Entity Translation
> 0 votes

---
Tags: i18n-l10n, search, commerce
---


# Question
Title: Can I prevent Administrators from Updating Modules?
So I had an issue yesterday where a module was updated on one of my sites that I wasn't ready for it to be updated on. It caused some issues, but I was eventually able to get the previous version back from my test server and it is working normally again.

My guess is that someone with administrative rights (but not User-1) was able to update the module from the web interface. Is there a way to prevent anyone from updating modules except User-1?

# Answer
Uncheck the permissions "administer software updates" from roles, and they should no longer have access to this screen in the admin.

At the same time, it is advised to use drush or other methods of applying updates, as the admin screen is pretty not great for this.
> 4 votes

---
Tags: updating
---


# Question
Title: Unable to render title field on node template
For my content type - Article I have a template

```
node--article.tpl.php

```

I currently render other fields such as the body text just fine. However the title cannot be displayed. I'm using

```
print render($content['title']);
print render($content['body']);

```

But only the title is displayed. To make sure I'm using the right machine name, I looked at the content type configuration.

Is there something missing? Or is there something special I have to do to to the 'title' field?

# Answer
I was able to print the title using

```
print $title;

```
> 0 votes

---
Tags: theming
---