# Question
Title: Query method not triggered in custom filter handler?
I'm using Views 3.

I needed to create a custom *Views filter* that handle dates range. So I looked at example and tried to mimic the behavior and I got some trouble.

It seems that when I extend my own class from `views_handler_filter`, the query method is never invoked, BUT if I extend my class from let's say `views_handler_filter_string` it works.

I must forget something but I'm stuck here.

Here is my code, if someone can take a look and advise me about what happened, I would be very grateful.

Here is my `.views.inc` file :

```
<?php
  class v3d_date_custom_filter extends views_handler_filter {
    var $always_multiple = TRUE;

    function value_form(&$form, &$form_state) {
      //parent::value_form($form, $form_state);
      $form['value']['v3d_date']['period'] = array(
        '#type' => 'select',
        '#title' => 'Period',
        '#options' => array(
          '7_days' => 'Last 7 days',
          'yesterday' => 'Yesterday',
          'today' => 'Today',
          'custom' => 'Custom dates'),
        '#default_value' => 'custom',
        '#attributes' => array("onclick" => "period_click(this);"),
      );

      $form['value']['v3d_date']['start_date'] = array(
        '#type' => 'date_popup',
        '#date_format' => 'Y-m-d',
        '#title' => 'Start date',
        '#size' => 30);

      $form['value']['v3d_date']['end_date'] = array(
        '#type' => 'date_popup',
        '#title' => 'End date',
        '#date_format' => 'Y-m-d',
        '#size' => 30);
      }

   function exposed_validate(&$form, &$form_state) {

     if(is_null($form_state['values']['start_date']) &&
        is_null($form_state['values']['start_date'])) {
        return TRUE;
     }

    /*
     * If we get array for start_date or end_date
     * errors occured, but the date module will handle it.
     */
     if(!is_string($form_state['values']['start_date']) ||
        !is_string($form_state['values']['end_date'])) {
       return TRUE;
     }

     /* Get day, month and year from start_date string */
     if(!preg_match('/(\d+)-(\d+)-(\d+)/',
        $form_state['values']['start_date'],
        $start_date
        )) {
       return TRUE; }

     /* Get day, month and year from end_date string */
     if(!preg_match('/(\d+)-(\d+)-(\d+)/',
        $form_state['values']['end_date'],
        $end_date
     )) {
       return TRUE; }

     /* Create timestamps and compare */
     $start_date = mktime(0,0,0,$start_date[1],$start_date[2],$start_date[3]);
     $end_date = mktime(0,0,0,$end_date[1],$end_date[2],$end_date[3]);

     if($start_date >= $end_date) {
       form_set_error('start_date','Start date must be anterior to end date.');
     }
   }

   function query() {
     die('fdsfds');
     $this->ensure_my_table();
     $field = "$this->table_alias.$this->real_field";
     dsm($this);
   }

 }
?>

```

And my `.module` file

```
<?php
  function custom_filters_views_api() {
    return array(
      'api'=>3,
      'path' => drupal_get_path('module','custom_filters') . '/views',
    );
  }
?>

```

And part of my `views_data` that use my custom filter :

```
<?php

function voice_views_data() {

  $data['v_tp_voice']['date_utc_agent'] = array(
    'title' => t('date_utc_agent'),
    'help' => 'date_utc_agent',
    'field' => array('handler' => 'views_handler_field'),
    'filter' => array('handler' => 'v3d_date_custom_filter'),
    'sort' => array('handler' => 'views_handler_sort')
  );

  return $data;
}

```

# Answer
> 1 votes
As suggested by todinov, you can use Drupal contrib modules Date along with its sub module **Date Views** which will most probably handle any kind of filter in Views. If it doesn't help, you can achieve it through code by implementing hook\_views\_query\_alter.

---
Tags: 7, views
---


# Question
Title: Send E-Mail When User Profile Fields Updated
I am looking to update my brain regarding a set of rules in Drupal 7. What I am wanting to do is:

1. Send e-mail to arbitrary e-mail address (mine) when a user updates any of their user profile fields.
2. I want the updated fields to appear in the e-mail template.
3. It would be helpful to have the old information showing the new updated field information.
4. Avoid sending e-mail when password is reset or changed.

I am probably missing something basic here with data comparison but thought I would seek out some thoughts on this.

# Answer
Just Install Rules Module and set the conditions something like this:

`Event:` **After updating an existing user account**

`Actions:` **Send a HTML Mail** (`$account` variable is available to send updated values through mail)

*Conditions: If needed*
> 6 votes

---
Tags: rules, users
---


# Question
Title: Use computed fields as Apache solr facets
Today I wanted to add a computed field to my facet to make a faceted search using that field but when checking the facets page that field wasn't in the allowed field to make facets. When i realized none of my computed fields was in that list i came to the conclusion that you can't use computed fields as facets.
Looking on google didn't help me confirm my dobuts, there's actually no result that talks about solr facets and computed fields so i decided to ask here:

Can you use computed fields to make facets? If yes, is there something i have ti do (install a module, change a setting...) to enable this since at the moment i can't see them from the available facets?

# Answer
* I think you need to store the `computed field` in **database** in order to make apache solr index it.
* There is *check box* in `computed field` to save it to database: `Store value in database`

Just enable it and see if it works.
> 0 votes

---
Tags: search, entities
---


# Question
Title: Views: how to make an OR condition between filters and contextual filters
I have been able to separate Views filters into groups and apply an OR condition, following this article: http://www.webomelette.com/drupal-views-filters-and-or-logic

I also understand how to use the hook\_views\_query\_alter() to make a few contextual filters act with an OR statement between each contextual filter.

What I can't figure out is this: how do I make the conditional between the REGULAR filters and the CONTEXTUAL filters? After altering the query, this is what I've able to create:

```
WHERE
(
  ( (og_membership_node.gid = '8' )
    AND (node.status = '1')
    AND (node.type IN  ('event'))
    AND (field_data_field_event_type.field_event_type_tid = '12')
  )
  AND(
  ( (node.status = '1')
     AND (node.type IN  ('event'))
     AND (field_data_field_event_type2.field_event_type_tid IN  ('11', '10')) )
  )
)

```

and I want it to be:

```
WHERE
(
  ( (og_membership_node.gid = '8' )
    AND (node.status = '1')
    AND (node.type IN  ('event'))
    AND (field_data_field_event_type.field_event_type_tid = '12')
  )
  OR(
  ( (node.status = '1')
     AND (node.type IN  ('event'))
     AND (field_data_field_event_type2.field_event_type_tid IN  ('11', '10')) )
  )
)

```

To give some background of what I am trying to do: I am using Organic groups, and I want my view to show events, Global, Regional and Chapter events. However, if the event is of type Chapter, I want to only show Chapter events which are in the same group as the page content.

I had manually edited the query to move the regular filters associated with the Chapter filter into the contextual filter group, with this:

```
foreach($query->where[1]['conditions'] as $condition) {
  $query->where[0]['conditions'][] = $condition;
}
unset($query->where[1]);

```

# Answer
There is a module for that (albeit a sandbox module). Download Views arguments in filters. As it is a sandbox module you will have to use git.

With this module you add your contextual filter as a global null contextual filter. Then in your normal filter's section, you refer to your contextual filter via the format %N (%1 etc). In this way you bring your contextual filter down to the normal filter section in views, and you can now apply the conditional clauses there, as well as the other filter logic.
> 2 votes

---
Tags: views
---


# Question
Title: Is there anything inherently wrong with mutually reliant custom modules?
The custom modules on the main site I work on evolve. I try to separate their functions and write multiple modules based on discrete needs but sometimes they grow into each other once written.

Now I have two modules that are inextricably linked to each other to the point where each of their .info files have `dependencies[] = theothermodule` in them to remind future site admins of this fact.

Of course I can undo this and separate the functions out, but thinking about it made me wonder *why* I should do it, and that advice on this topic might be useful here.

# Answer
From wikipedia on "modular programming"

> Modular programming is a software design technique that emphasizes separating the functionality of a program into independent, interchangeable modules

If you have two modules, and they depend on each other, they are no longer *independent*, and in fact, are no longer two modules, but one. At least in theory, that's a bad thing, because you can no longer make changes to one, without changing the other.

Sooner or later, you'll also likely find that this becomes a practical problem, because as the module grows, it becomes increasingly difficult to keep up appearances of an external interface. Both modules are calling functions in both modules, and again, you can no longer change one without also updating the other.
> 3 votes

---
Tags: 7
---


# Question
Title: How do I limit the number of nodes posted by a user to an entity referenced node?
I have created a content type (*Reviews*). I am referencing another content type (*Books*) using the Entity Reference module. How do I limit the number of reviews posted per book to 1 per user? Is there a module for this?

I have already experimented with the node\_limit module but that doesn't work in this particular context. It restricts the user from posting content per content-type but not per node.

# Answer
Try using the the Unique Field module

> This module performs additional validation when a node is created or updated by a user to require that a node's title, author, language, and CCK fields are unique within a given context.

This might help you.
> 1 votes

# Answer
I don't think there is a module for that ("yet", may be). However, this can be done easily with a form alter hook and validation.

```
<?php
function MYMODULE_form_node_form_alter(&$form, &$form_state) {
  if ($form['#node']->type == 'article') {
    $validate = TRUE;
  }
  // You can also use field existence like following:
  if (isset($form['field_name_that_you_want_to_validate'])) {
    $validate = TRUE;
  }

  if (!empty($validate = TRUE;)) {
    $form['#validate'][] = 'MYMODULE_node_validate_only_one_review';
    form_load_include($form_state, 'inc', 'MYMODULE', 'FILE_THAT_CONTAINS_THE_VALIDATE_FUNCTION');
  }
}
?>

```

Then, define the validate function:

```
<?php
function MYMODULE_node_validate_only_one_review($form, &$form_state) {
  if (!empty($form_state['field_name_that_you_want_to_validate'])) {
    $nids = array();
    foreach ($form_state['field_name_that_you_want_to_validate'] as $language => $items) {
      foreach ($items as $delta => $item) {
        if (!empty($item['target_id'])) {
          $nids[$item['target_id']] = array($language, $delta);
        }
      }
    }
    if (!empty($nids)) {
      $query = new EntityFieldQuery();
      $query->entityCondition('entity_type', 'node')
        ->entityCondition('bundle', 'article')
        ->propertyCondition('uid', $GLOBALS['user']->uid)
        ->fieldCondition('field_name_that_you_want_to_validate', 'target_id', $nids);

      $matches = $query->execute();
      if (isset($matches['node'])) {
        foreach ($nids as $nid => $pack) {
          if (isset($matches['node'][$nid])) {
            list($language, $delta) = $pack;
            form_set_error('field_name_that_you_want_to_validate][' . $language . '][' . $delta,
              t('You have already submitted a review for this content.');
            );
          }
        }
      }
    }
  }
}
?>

```

**There are 4 assumptions:**

* Node type is `article`. Change all instances of `article` with the correct node type machine name.
* Your field name is `field_name_that_you_want_to_validate`. Change it accordingly.
* You are using Entity Reference module for node reference (hence, the `target_id` key. It would be `nid` if you use References module)
* This bounty gave you the hat ;)

**There is 1 fact:**

* I submitted this answer for the hat.

**There is 1 hope:**

* I will get that hat.
> 4 votes

# Answer
The other answers approach the requirement from a validation standpoint. I think it's better from a user experience standpoint (and I think it makes more sense logically) to tackle it earlier - at presentation. That is, don't present the option to review a book if the user has already reviewed it. Only show books that *can be reviewed* by the acting user when giving them the list of books to select for reviewed.

**Summarized approach**:

> Upon creation of a Book Review, limit the list of books available for review to those that have not previously been reviewed by the reviewer.

Given this approach, we want to limit the list of books a user can select when creating a review to those that have not previously been reviewed by the reviewer. Entity Reference allows you to use a View to generate the list of reference-able entities. **So all you need is a view that displays all Books that haven't been referenced by the current user yet.**

More simple (given that we're already excluding entities that aren't books): **Show me all books, but exclude books that have been referenced by this user already.**

**Basic instructions:**

1. **Create a new view**. It will need a display type of "Entity Reference". But for now, I suggest giving it a Page display so you can test.
2. **Join the referenc*ed* and referenc*ing* entities**: Add a reference to `Entity Reference: Referencing` entity (note Referenc**ing**, not Referenc**ed**)
3. **Only return Articles** \- Under filter criteria, create a filter for `Content Type = Article`
4. **Filter based on user** \- Under Contextual Filters, create a Contextual Filter for `Content: Author uid:`
    1. **When the filter value is *not* in the URL**: Provide default value = User ID from logged in user
    2. **Negate the expression** \- Under "More", select "Exclude" (Exclude essentially negates the filter \[and might be inappropriately misnamed as such\] - we want to return all referenced nodes that *weren't* created by the current user).
5. **Verify, add view display, and profit** \- At this point you should be able to visit the URL of the view you created as different users. There you can verify that the only Book nodes that are displayed are those that have not been reviewed by the current user (or those not reviewed at all). Once you've tested and verified it's working, add a display to the view of type "Entity Reference". Then back in your Review content type, set the Entity Reference field's Mode to "Views" and select the view you just created.
> 4 votes

# Answer
You can use Node Review module for review functionality to nodes.

I you want it in the way you are using then I think you need to use `hook_node_validate` to validate node before saving.

```
function hook_node_validate($node, $form, &$form_state) {
  if ($node->type == 'review') {
    // check if review node exists for the selected referenced field value display for same uid.
  }
}

```
> 1 votes

---
Tags: nodes, users
---


# Question
Title: How to link Views Bulk Operations and Bibliography modules in a home-made search engine?
I am using Bilbiography module to manage scientific publications on a website. The default search engine is nice but I would like to add a Views Bulk Operations function so users can choose specific nodes (tick the boxes on each line) and then export them to End Note or Bibtex, etc., like Bibliography does (export links at the top right). Has anyone built a thing like this before in a View? I would appreciate to have a few tips on this. Thanks in advance.

# Answer
See this sandbox module that add export functionality for all results in a view as a footer / header: https://www.drupal.org/sandbox/szeidler/2394975
> 0 votes

---
Tags: views, importing-exporting
---


# Question
Title: Translate website with prefix URL when everything is on domain
The website I'm working on has multiple languages and the detection is based on domain name.

I want to add another language, available only to developers, but do not have a domain name for it now. So I would like to know if it is possible for ONE language to be found via prefix, an example structure would be:

Thanks.

# Answer
> 1 votes
# No

Not with the core code.

# Avaliable solutions

1. Language Domains would allow you to create alternative domain prefixes, like ru.example.com and www.example.com leading to different languages.
2. Domain Locale \- this one I never used, but it promises to *"customize language sets per domain"*

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


# Question
Title: Running code only once when building a form
I have built a form using the field API. The function hook\_field\_widget\_form gets called for every field. I have a bit of code that populates a select box but it is being called for every field in the form - see the first 10 lines of the code below.

```
function mango_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

  $library = libraries_detect('d3_custom_scripts');
  if($library) {
    $libs = libraries_get_libraries();
    $custom_scripts_path = $libs['d3_custom_scripts'];
    $files = file_scan_directory($custom_scripts_path, '/.*\.js$/');
    $custom_script_list[''] = t('Please select');
    foreach ($files as $file => $info) {
      $custom_script_list[$info->filename] = $info->filename;
    }
  }
  dpm($items[$delta]);
  $item =& $items[$delta];
  $element += array(
    '#type' => 'fieldset',
  );

  $element['enabled'] = array(
    '#title' => t('Enabled'),
    '#type' => 'checkbox',
    '#default_value' => isset($item['enabled']) ? $item['enabled'] : '',
  );

  $element['custom_script'] = array(
    '#title' => t('Attach script'),
    '#type' => 'select',
    '#options' => $custom_script_list,
    '#default_value' => isset($item['custom_script']) ? $item['custom_script'] : '',
  );
  return $element;
}

```

Is there a ay to only run the code once and pass in the variables into the hook\_field\_widget\_form function so I can avoid calling the same code over and over when I only really need to call it once? Many thanks.

# Answer
> 0 votes
Use built-in caching!

At the beginning of your function, test if results are already prepared in cache:

```
function mango_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  // Construct cache id. Let's start with function name, as it should eb unique
  $cid = __FUNCTION__;
  // Now let's add a fast hash of everything important. Seems only $items matter
  $cid .= '-' . hash('adler32', serialize($items));
  // Oh, and language, too!
  $cid .= '-' . $langcode;

  // Do we have results for this set of parameters?
  if( $result = cache_get($cid)  ) {
    // We do, return it.
    return $result->data;
  }

```

At the end of your function, just before you return value, save it to cache:

```
  cache_set($cid, $element);

```

That's all. It will not prevent your function from being called, but it will prevent actual computation in it. Just be sure to choose cache id carefully. It must be fast to compute, but avoid collisions well.

---
Tags: 7, entities, hooks
---


# Question
Title: How to insert HTML that includes an ampersand>
I've created a custom block, and I'm trying to get this custom block to output a specific piece of HTML. The HTML needs to be different on every page, because it needs to include the page's URL in it. For instance, if the page is http://www.businesskorea.co.kr/article/7789/content-business-marginalized-samsung-reorganizes-media-solution-center-owing-poor, then the block should output:

```
<img src="http://cp.news.search.daum.net/api/publish.json?nurl={http%3A%2F%2Fwww.businesskorea.co.kr%2Farticle%2F7789%2Fcontent-business-marginalized-samsung-reorganizes-media-solution-center-owing-poor}&xml_url={http%3A%2F%2Fwww.businesskorea.co.kr%2Farticle%2F7789%2Fcontent-business-marginalized-samsung-reorganizes-media-solution-center-owing-poor%3Fformat%3Dxml}&channel=business" style="display:none;">

```

This is to be compatible with daum.net's news publishing functionality. The code that I've written up for this custom block looks like this:

```
<?php

/**
* Implements hook_block_info().
*/

function bkcustom_block_info() {
  $blocks = array();
  $blocks['bkcustom_daum_json_block'] = array(
    'info' => t('BKCustom Daum JSON'),
  );
  return $blocks;
}

/**
* Implements hook_block_view().
*/

function bkcustom_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'bkcustom_daum_json_block':
      $block['subject'] = '';
      $block['content'] = BKCUSTOM_DAUM_JSON_BLOCK_CONTENT();
      break;
  }
  return $block;
}

function BKCUSTOM_DAUM_JSON_BLOCK_CONTENT() {
  $path_alias = drupal_get_path_alias($_GET["q"]);

  $encoded_path_alias = urlencode($path_alias);

  $output = t("<img src=\"http://cp.news.search.daum.net/api/publish.json?nurl={http%3A%2F%2Fwww.businesskorea.co.kr%2F" . $encoded_path_alias . "}&xml_url={http%3A%2F%2Fwww.businesskorea.co.kr%2F" . $encoded_path_alias . "%3Fformat%3Dxml}&channel=business\" style=\"display:none;\" />");

  return $output;
}

```

Which outputs almost, but not quite, what I need. The output changes ampersands to `&`, and somehow deletes the final forward slash (/) at the end of the IMG tag. The output looks like this:

```
<img src="http://cp.news.search.daum.net/api/publish.json?nurl={http%3A%2F%2Fwww.businesskorea.co.kr%2Farticle%2F7789%2Fcontent-business-marginalized-samsung-reorganizes-media-solution-center-owing-poor}&xml_url={http%3A%2F%2Fwww.businesskorea.co.kr%2Farticle%2F7789%2Fcontent-business-marginalized-samsung-reorganizes-media-solution-center-owing-poor%3Fformat%3Dxml}&channel=business" style="display:none;">

```

The most frustrating part of this exercise is that if I delete the opening and closing brackets, \<\>, the code works perfectly and prints out each character exactly as I need it to. That's how I tested to see if it would work. But when I introduce opening and closing brackets, the code changes and the JSON query or whatever the crap this is fails.

How can I preserve the & and / characters?

# Answer
> 0 votes
I ended up solving this problem by abandoning the custom module idea and doing the work in the theme layer - in node.tpl.php. I should have done that from the beginning I guess.

# Answer
> 0 votes
`t` function is for texts, not for HTML, so it is perfectly allowed to fail. Also, you should not use dynamic strings in `t`'s first argument at all, it is meant to be static.

Whenever possible, you should use renderable arrays. In your specific case this seems a bit difficult, so first thing to, if you are willing to settle for quick and dirty, do would be just forget `t` and output tag directly.

---
Tags: blocks
---


# Question
Title: How to pass Javascript variable with form on submit?
I want to pass a variable created with Javascript to $form\_state so that I can use this variable in the form\_submit function.

In an ajaxified form I can use:

```
Drupal.ajax[ajax_el].options.data._my_vars = JSON.stringify(js_object);

```

But how can I accomplish it in a non ajax form? Is there another possibility than using a hidden field? It might be possible to pass it to a field with `#access => FALSE`?

I would welcome every advice. Many thanks!

Daniel

# Answer
Create a field for that variable, like this:

```
$form['_my_vars'] = array('#type' => 'hidden', '#default_value' => $_my_vars);

```

Whenever you are changing variable, update field's value.

**Do not** use

```
'#access' => FALSE

```

The Form API Reference clarifies it:

> when FALSE, the element is not rendered and the user submitted value is not taken into consideration.
> 2 votes

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


# Question
Title: IP white address not accepting my current IP
It says "*Enter the list of allowed IP addresses below*

> Warning: If you don't enter your current IP address into the list, you will immediately be locked out of the system upon save, and will not be able to access the system until you are in a location with an allowed IP address."

So I am trying to white list all Australian IP and ban all other with this simple module called Restrict IP but when I go to input my current IP which by the way is dynamic so I don't see how that will help if it keeps changing. Anyway I found a list of IP in Australia from **here** and have input them all but when I got to save configuration it says is not a valid IP address.

Actually does this module only blacklist IP trying to login the site or does it blacklist viewing as well? I only want to blacklist login and register all IP outside of Australia.

# Answer
The Restrict IP module clearly states:

> This module allows administrators to restrict access to the site to an administrator defined set of IP addresses. **Anyone trying to access the site from an IP address not in the list of allowed IP addresses will be redirected to an access denied page** with the message "Your address is not in the list of allowed IP addresses".

Emphasis mine. So it restricts access to the *site*, not the login form.

If you're adding a valid IP address, and the module is saying it's not a valid IP, you've found a bug and need to report it to the issue queue on Drupal.org.

If you're serious about restricting people by geographic region you'll need to come up with something better than IP address, which is not reliable for such things.
> 2 votes

# Answer
You could give a try to IP Ranges Module which is actively maintained

> Type can be either "blacklist" or "whitelist", where blacklisted IP's are denied from the site, and whitelisted are allowed.
>
> Whitelists always override blacklists.

* Restrict IP allows you to enter whitelists. All other IP's are banned. Unlike IP Ranges, it does not actually restrict access to the page, but rather unsets all the regions.
* It also may serve pages even to banned IP:s if the requested page can be retrieved from cache.
> 2 votes

# Answer
Site you linked provides ranges with last byte `.0` and `.255` at their ends. Generally, `.255` is reserved for broadcasts, and `.0` for network ID, so modules may rightly not consider it a valid IP addresses.

This may lead to all kinds of unexpected behaviour, especially when the module you are using is still in unstable version. Release Candidates should be pretty stable, but they can be expected to have some minor issues still unsolved, especially with data that shouldn't be entered in the first place.
> 2 votes

---
Tags: users
---


# Question
Title: adding data attribute to option value in Drupal 6
I have a form, like this:

```
        $form['my_case_type_list']=array(
            '#type'=>'select',
            '#title' => 'Issue Type',
            '#options' => $my_list,
            '#multiple' => false,
            '#attributes'=>array('size'=>1),
            '#weight'=>2,
        );

```

where $my\_list is an array, like this:

```
$array[0] = 'string 1'
$array[1] = 'string 2'
$array[2] = 'string 3'

```

This renders a dropdown list with the array key as the option value and the array value as the option text. I want to use a multi-dimensional array to also provide each option with a data id. An array like this:

```
$return_array[0] = array('name' =>'string 1', 'description'=>'description for string 1');
$return_array[1] = array('name' =>'string 2', 'description'=>'description for string 2');
$return_array[2] = array('name' =>'string 3', 'description'=>'description for string 3');

```

and have the description field be used, in the option value, as a data attribute. So, it would be rendered like this:

```
<select name="my_case_type_list" size="1" class="form-select" id="edit-my-case-type-list">
    <option data-desc='description for string 1' value="0">String 1</option>
    <option data-desc='description for string 2'  value="1">String 2</option>
    <option data-desc='description for string 3'  value="2">String 3</option>
</select>

```

Is this even possible? Can you assign a multi-dim array to a form? When I do, it just create option groups and each dimension of the array becomes an option.

thanks jason

# Answer
This has been asked previously for Drupal 7 and there is no great answer so it's unlikely to be possible in Drupal 6 the answer seems to be implementing a custom theme\_select
> 0 votes

---
Tags: webforms, forms
---


# Question
Title: How to display list of nodes in responsive grid?
What module should I use to implement this?

Each item has photo, taxonomy, title, description. And it has a horizontal mouse hover movement. Could you kindly recommend drupal modules to implement this grid?

# Answer
Views Responsive Grid provide basics of functionality you need:

> Views Responsive Grid provides a views plugin for displaying content in a responsive(mobile friendly) grid layout. Rather than trying to force the standard Views grid display to work for mobile this provides the same functionality, but in DIVs instead of tables. Provided is also the ability to specify a horizontal or vertical grid layout which will properly stack the content on a mobile display.

The rest is fine tuning and theming.
> 4 votes

# Answer
You can use Views Fluid Grid module, it offers the option to add separate css classes. If this grid doesn't fit your requirements then check the other option in @Molot comment.

> The plugin settings form provides options to define the width and height of the elements in the grid. But it also provides advanced layout options implemented in separate CSS classes that allow you to define item margins, alignment and a couple of CSS3 properties (box-shadow and border-radius).
> 3 votes

---
Tags: 7, theming
---


# Question
Title: How to integrate Views with apache solr search?
In my site I am implementing zip code based search, for that I created one view of user profile and add one expose filter to it which is exposing result on postal zip code entered by user. Now I am thinking that exposed filter integrate with Apache solr.

Help me out for which module I have to use for it and how I configure it?

List of modules I have used in my project:

1. addressfield
2. geofield
3. geocoder
4. geophp
5. apachesolr
6. facetapi
7. profile2

# Answer
The module you want is the aptly named Apache Solr Views which will allow you to construct views from the SOLR index. Configuration is pretty simple. It's kind of a drop-in module. You'll choose to create an "Apache SOLR view". From the project page:

> Create a view from admin/structure/views/add and choose Apachesolr search. All of the fields indexed in solr should be available as views fields/filters/sort. Configure the view as needed and save it

Hope that helps you. Good luck!
> 4 votes

---
Tags: views, search
---


# Question
Title: Create an e-mail reminder depending on a date field in a custom content type
I have created a custom content in which there is a date field and an e-mail field I would like to add an automatic email reminder that is triggered on that date and sent to the email specified in the custom field.

What is the correct procedure to do so?

# Answer
> 1 votes
I followed the following instructions to achieve what I wanted to do.

> Create a Rules component of type 'Action Set' and call it 'Send Notification'. Add a Variable of 'Entity: Node', give it a label and machine name of 'node'.
>
> Add an action to the loop (note: add it to the loop and not the component) of 'System: Send Mail'.
>
> Add a new rule and call it 'On new event', to react on 'Node: After saving new content'. Restrict it to the custom content type.
>
> Add an action to this rule, 'Rules schduler: schedule component evaluation', and select the 'send notification' component you created earlier.
>
> Set the evaluation date to node:field-event-date.
>
> Add an offset: -1 days (optional)
>
> Add an identifier of 'node-\[node:nid\]-event' and note its pattern as you will be using it to delete events.
>
> Select the Node as 'node'

Source: Send reminder to referenced users day before event date in cck date field

---
Tags: rules, emails, notifications
---


title: Problem with date_timezone_set()

text:
# Question
Title: Problem with date_timezone_set()
I've managed to get my webform fields to display in views via this tutorial. The tutorial uses the Webform My SQL views and data modules.

Webmform My SQL views: 7.x -1.0 Data: 7.x-1.0 alpha

System: Plesk 10.3 CentOS 5.8 Apache 2.2.3 Php 5.1.6

I can successfully create my view that allows me to choose the webform fields I want to display, however, when i try to add the "Webform views request time off 272: Submitted" date field, I get this:

> Warning: date\_timezone\_set() expects parameter 1 to be DateTime, boolean given in format\_date() (line 1909 of /var/www/vhosts/mydomain.com/intranet/includes/common.inc).

> Warning: date\_format() expects parameter 1 to be DateTime, boolean given in format\_date() (line 1919 of /var/www/vhosts/mydomain.com/intranet/includes/common.inc).

As a result, this field displays no values.

I've done a search on that issue and while I did find some topics, I'm not sure how they apply to my situation. Unfortunately, this site is for our intranet so I cannot post a link.

The goal in this view is to show the submission fields and include a filter control that I can expose to the user that uses the submission date as the criteria for a date range.

I had the "Date" module activated, then deactivated which didn't resolve the issue.

Any help would be greatly appreciated.

# Answer
> 0 votes
I ran into the very same 2 errors but in the context of of sub-theme preprocess function when using the format\_date() function as follows.

```
$vars['timestamp'] = format_date($dc_file_items[0]['timestamp'], 'custom', 'd M, Y');

```

After searching in many directions (including installing the Date module - not required), I came to realize that `$dc_file_items[0]['timestamp']` was returning a **string** and not an **integer**. Adding `intval()` around it made the errors disappear. In the end, the code above should look like this.

```
$vars['timestamp'] = format_date(intval($dc_file_items[0]['timestamp']), 'custom', 'd M, Y');

```

Hope this helps.

# Answer
> 0 votes
As its said date\_timezone\_set() expects parameter 1 to be DateTime type so you have to send the DateTime value to the variable or you have to apply this patch to get rid of warning.

And always "Expects parameter xxx to be "xxxtype" error is data type casting problem ". to solve this you have to send data in that data type format or you have to handle it in the core file by applying this patch.
https://www.drupal.org/node/518816 https://www.drupal.org/files/issues/518816-5.date\_format\_date\_warnings.patch

believe it helps you

---
Tags: views, webforms
---


title: How to add a link to an image in a view

text:
# Question
Title: How to add a link to an image in a view
I have a view that is showing a single image, and I need the image to link to a specific URL, but when I try using Rewrite Results on the field it will still show the image but doesn't add the link.

I have tried both "Rewrite the output of this field" putting in `<a href="http://example.com">[field_file]</a>` and "Output this field as a link" putting http://example.com in the field and neither of those ways worked.

How can I rewrite the field to have the link on the image?

# Answer
> 4 votes
You can use the image url formatter module to output the path to the image. Then do like you tried before to Rewrite Results and add the markup.

```
<a href="http://www.example.com"><img src="[field_file]" /></a>

```

# Answer
> 0 votes
1. global $base\_path;

get the base path (if you globally declared in settings.php)

2. $profile\_pic= !empty($data-\>\_field\_data\['uid'\]\['entity'\]-\>field\_profile\_pic) ? $data-\>\_field\_data\['uid'\]\['entity'\]-\>field\_profile\_pic : "";

Get the image field url from $data.

3. $Logo = file\_create\_url($profile\_pic\['und'\]\[0\]\['uri'\]);

Get the URI of that image value if the image is present store that URI

$link\_path = "path to where the link has to go on clicking the image"; print the image under a link

```
<a href="<?php print $link_path;?>"><img alt="profile picture" src='<?php print $Logo.'?'.time();?>' width="126" height= "173"></a>

```

here the time is to avoid cache problem with image in drupal it will retrive the latest image from the server.

hope this helps

---
Tags: views
---


# Question
Title: How to get the path to theme in Views for linking an Image
When creating a view, I rewrote the output in "Rewrite Results". There I have an HTML with a link to an icon in the theme folder.

```
<ul class="stats vertical">
       <li><a href="#"><img src="sites/all/themes/my_theme/images/my_icon.png">[field_output]</a></li>
       <li><a href="#"><img src="sites/all/themes/my_theme/images/my_icon.png_orange.png">[field_text_output]</a></li>
</ul>

```

As you can see that I am hard-coding the path to my icons. This works if this View Page is accessed from home page. But when this View page is accessed from some 2nd or 3rd level page, the icons are not shown.

Is there any way I can get a relative path to my theme within Views?

Thanks.

# Answer
> 1 votes
I will encourage you to rethink your hardcoding approach and instead implement your icons as CSS background images, using views to apply the desired classes to your field elements. This approach will allow you to avoid the options I am about to suggest :)

Option 1: Copy one of the following files found in the views module `theme` folder into your theme's `templates` folder: `views-view-field.tpl.php`, `views-view-fields.tpl.php` and rename it according to your needs using the Views template files documentation \- and in your case you may want to look at `views-view-list.tpl.php`. Then code your img tag into this field template logic, constructing your img src with PHP using the $base\_url variable. Clear the cache.

Option 2: Install Views PHP and add a Global:PHP field and construct your img src with PHP using the $base\_url variable.

# Answer
> 1 votes
Yes we can make no need to go for tpl and all

```
 function MODULE_init(){
    /*define the theme path for Image and JS folder*/
    $ThemeImgPath = drupal_get_path('theme', 'themename');//for getting the theme path
    if($ThemeImgPath) {
             define("THEMEIMAGEPATH", base_path().$ThemeImgPath . "/images/"); //for getting the path to images folder in the theme
             define("THEMEJSPATH", base_path().$ThemeImgPath . "/js/");//to get the js folder path in the themes
               define("THEMEPATH", base_path().$ThemeImgPath);
         }
    }

```

define this in any of the custom module init() and use it any where in your project in views, themes, modules etc.

use THEMEIMAGEPATH - to get the image path in themes,

THEMEJSPATH - to get the js path in themes,

THEMEPATH to ge the theme path.

---
Tags: views, uri
---


# Question
Title: How can I make Search Terms in a View to look fo into the edited Summary?
I have a View of a type of content, and it has a Search Terms contextual filter. It searches perfectly (after indexing the content and running cron), but when I have a node which has the summary edited (not the default trimmed body text), the search does not return any result. How can I include the edited version of the Summary in the search?

# Answer
> 0 votes
I have discovered how to get it work: just selecting in the Manage Display --\> Search Indexing, Body Summary or trimmed. Isn't it confussing? It seems that it will search only in the summary, while it searches in both Summary and Body. And now it works with edited Summaries.

---
Tags: views, search
---


# Question
Title: hook_services_request_postprocess_alter() does not identify the requested resource
According to the Services API in Drupal 7, we can use hook\_services\_request\_postprocess\_alter() to alter drupal's REST response before returning it to the user. This is useful if you want to alter the structure of an array, or strip out data we don't want returned to the API user. However, I don't see any way to identify what resource is being requested explicitly.

The Hooks passes: ($controller, $args, &$result);

The controller has semi-identifiable information, such as the callback which was fired, or the file where this resource exists. For instance, when firing a node INDEX request, we'd see:

```
[help] => List all nodes
[file] => Array
    (
        [type] => inc
        [module] => services
        [name] => resources/node_resource
    )

[callback] => _node_resource_index
[args] => Array
    (
        [0] => Array
            (
                [name] => page
                [optional] => 1
                [type] => int
                [description] => The zero-based index of the page to get, defaults to 0.
                [default value] => 0
                [source] => Array
                    (
                        [param] => page
                    )

            )

```

Etc. However, there is nothing standard here across services which would tell us: "This is a node INDEX request, using the NODE endpoint."

To be clear, we're referring to node in the resource sense, such as my\_host/my\_endpoint/node.json. **Meaning, which of our endpoint's resources is being requested here, and what (if any) method/operation are we performing.**

I was hoping there was something standard within this hook to identify this information, as opposed to relying on more external data, such as the GET or POST variables.

Anyone have insight into this?

---

\[edit\]:

hook\_services\_request\_preprocess\_alter() is passed an $options array, which contains the endpoint resource and method. I need access to this information in the postprocess hook mentioned above, but don't see any clean, Drupal-way to do that. this is what I am looking for.

The array looks as follows:

```
Array(
  [version] => ,
  [resource] => node,
  [method] => 1.json
);

```

# Answer
> 0 votes
if you take a look to $args array, you can find your node type, for example I have a content type "video", my $args are like this:

```
Array
(
    [0] => 2
    [1] => *
    [2] => Array
        (
            [type] => video
            [uid] => 92
        )

    [3] => 2
)

```

Then $args\[2\] has the content type (because I set it like a parameter in my resource: http://site.local/api/v1/node?parameters\[type\]=video&parameters\[uid\]=92&pagesize=2&page=2

---
Tags: 7, services
---


# Question
Title: How to use #element_validate and #value_callback in Drupal 8
I have followed the official Form API Documentation, but this code don't work for me on Drupal 8:

```
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['upload'] = array(
      '#title' => t('Upload Images'),
      '#type' => 'managed_file',
      '#upload_location' => 'public://image_example_images/',
      '#element_validate' => array('file_generic_settings_max_filesize'),
    );
    return $form;
  }

  private function file_generic_settings_max_filesize($element, &$form_state) {
    form_error($element, 'This is an error.');
  }

```

I have trying to remplace form\_error() by $form\_state-\>setErrorByName() but same problem, the file is uploaded and the validation is not called.

Have you a solution please ? The documentation of #element\_validate is outdated ?

My objective: Upload a lot of images, use a custom validation and insert all images thumbnails inside a `<div class="preview"></div>` with a field for name each images.

Example: (After upload, display thumbnails and title field for name all each images)

Else, after upload, for display Thumbnails and other field (title and description) for each image, I need to use #value\_callback, #process, #attached (manage field/display with js after upload) or an other option please ?

Thanks.

# Answer
> 12 votes
To use an instance method for `#element_validate`/`#value_callback` etc you need a callable. e.g.

```
$form['upload'] = array(
  '#title' => t('Upload Images'),
  '#type' => 'managed_file',
  '#upload_location' => 'public://image_example_images/',
  '#element_validate' => array(
    array($this, 'file_generic_settings_max_filesize'),
  ),
);

```

You'll need to mark `file_generic_settings_max_filesize()` (which if you were being a stickler for standards should really be named `fileGenericSettingsMaxFilesize`) as `public` to accommodate, as your class won't be invoking the method.

Documentation for this is ongoing, the change notice is here.

---
Tags: 8, forms
---


# Question
Title: URL paths in optimized CSS sometimes are https instead of http
The expanded URLs inside my optimized CSS files are sometimes getting generated with https instead of http. This appears to happen randomly. Doing a cache clear, recreates the optimized CSS and usually the URLS are correctly expanded using http.

The source CSS files have relative paths in them, for example:

```
@font-face {
  font-family: "my-custom";
  src: url("../fonts/my-custom/my-custom_47f454dc1e054575ab6c2a63cbc17e46.eot");

```

In the optimized CSS this gets expanded to a full URL:

```
@font-face
{ font-family: "my-custom"; font-style: normal; font-weight: normal; src: url("http://i.cdn.my.com/drp/.../assets/fonts/my-custom/my-custom_47f454dc1e054575ab6c2a63cbc17e46.eot?#iefix") format("embedded-opentype"),

```

Then, seemly randonly it will be:

```
@font-face
{ font-family: "my-custom"; font-style: normal; font-weight: normal; src: url("https://i.cdn.my.com/drp/.../assets/fonts/my-custom/my-custom_47f454dc1e054575ab6c2a63cbc17e46.eot?#iefix") format("embedded-opentype"),

```

I have CDN enabled on the site, so that might be a factor. But again why is the behavior seemingly random?

Any suggestions on where to start looking in settings, hooks that affect CSS optimization behavior, known bugs with CSS optimization, etc. would be appreciated.

# Answer
> 0 votes
I don't think the behaviour is random.

These files are regenerated periodically, and the regeneration is mainly going to be triggered by visits to pages. I would guess that the urls in the CSS files get http when the page that triggered the regeneration has http, and https when the page that triggered the regeneration has https.

Prepending the URLs in CSS with the full protocol and domain is **not** a stock Drupal behaviour, so something in your setup is doing it–probably whatever module you're using to set up the CDN. You don't mention which module you're using for this, so it's difficult to say. I would begin by looking in the module settings.

It's also possible that your CDN service itself rewrites the urls in CSS files. Cloudflare, for example doesn't do this, but does have configurable options that rewrite certain files (such as, e.g., minifying css, js, or html).

# Answer
> 0 votes
The Advanced CSS/JS Aggregation module should sort out the http/https issue inside your css files, as long as `$GLOBALS['is_https']` is set correctly; that variable is set inside of drupal\_settings\_initialize() so it should work. Give it a try.

If it's not working after using AdvAgg try adding this to your settings.php file

```
// Set https to on if it should be.
if ( (isset($_SERVER["HTTPS"]) && strtolower($_SERVER["HTTPS"]) === "on")
  || (isset($_SERVER["HTTP_X_FORWARDED_PROTO"]) && strtolower($_SERVER["HTTP_X_FORWARDED_PROTO"]) === "https")
  || (isset($_SERVER["HTTP_HTTPS"]) && strtolower($_SERVER["HTTP_HTTPS"]) === "on")
  ) {
  $_SERVER["HTTPS"] = "on";
}

```

---
Tags: 7, theming
---


title: Drush module version

text:
# Question
Title: Drush module version
Is there a way for drush to print out what module version for a module that is currently enabled?

I'm not looking for trying to find what version of drush is.

I end up doing it the janky way:

`drush dl mymodule --select` and then seeing which version is installed.

Or `drush pm-list | grep mymodule`

# Answer
For Drupal 7 and earlier, try using `drush pm-info module`. It may give you what you want.

For Drupal 8 and later, the `pm` commands are mostly deprecated. To get module information, you would use `composer show drupal/module`.
> 22 votes

# Answer
You can use the shortcut:

```
drush pmi [module]

```
> 8 votes

# Answer
This will give you a list of all the *currently enabled*, *contrib*(i.e., non-core), modules on your site along with the exact version number:

```
drush pm-list --type=module --no-core --status=enabled

```
> 6 votes

---
Tags: drush
---


title: How are node IDs generated?

text:
# Question
Title: How are node IDs generated?
How are node IDs generated? Is there a field in the database, like "last node ID", that's incremented each time a new node is created? What is the data type, and are there limitations, such as a maximum value?

# Answer
`{nid}` is an auto\_increment field in the table `{node}` \- As all of the nodes are sourced from that one table it's able to keep its serialization. This is part of why UUID is such an important initiative in Drupal 8. It's not straightforward to maintain portability of content across environments for this reason.

The type is `int(10)` also known as unsigned so you're only limited by the data type limit of your preferred database and the disk space on your database server to store all those nodes. If it's MySQL that's 0 up to 4294967295.
> 3 votes

---
Tags: nodes
---


# Question
Title: Views: no results text not showing when contextual filter is set & no results returned
I have the following setup:

1. Block view
2. Contextual filter: Author UID -\> Provide default value -\> User ID from logged in user.
3. Fields: various
4. Filters: various
5. No results behaviour: text

I want the user to see a list of nodes that they have created. If no nodes are found, I want the No results text to show. Currently, it's all working fine if nodes are found. However, if no results are found, the entire view is hidden. Is this standard behaviour? How do I make it display the No results text?

# Answer
I just had a similar issue, I had a block view showing the current category:

1. Block view
2. Contextual Filter - Taxonomy term: Term ID - Provide default value (term id from url)
3. fields
4. filters
5. No results - Global text field

Like you, because the contextual filter was set to provide default value I never saw the no results text.

### SOLUTION

Edit the contextual filter and scroll down to the bottom, under

> "When the filter value IS available or a default is provided"

1. Check Specify validation criteria.
2. Leave validator as default.
3. Change "Action to take if filter value does not validate" to "display contents of No result found".

Bingo, on the *Overview* page with no term passed I get the no results found text, and when I go to a category page it picks up the term and displays the correct content.
> 7 votes

# Answer
Ok, my bad here. I was using a template override and had removed the line printing $empty. Which would explain why it was showing up in the preview, but not in the rendered block.
> 0 votes

---
Tags: 7, views
---


# Question
Title: How do I go to Checkout Page without product in cart?
I am using Commerce Donate and configured it to show donation form on checkout page. That is what actually I need. Donation form, contact info and payment form on same page.

But we cannot go to the checkout page without having some product in cart.

How can I do that?

# Answer
You can add the following code to a custom module:

```
/**
 * Implements hook_menu_alter().
 */
function YOURMODULE_menu_alter(&$items) {
  // Alter the default checkout callback to allow checkout without products.
  $items['checkout']['page callback'] = 'YOURMODULE_checkout_router';
}

/**
 * Implements hook_commerce_checkout_order_can_checkout().
 */
function YOURMODULE_commerce_checkout_order_can_checkout($order) {
  return TRUE;
}

/**
 * Displays the checkout form and create the user a cart if none exist.
 */
function YOURMODULE_checkout_router() {
  global $user;
  // Load the shopping cart order.
  if (!($order = commerce_cart_order_load($user->uid))) {
    $order = commerce_cart_order_new();
  }
  drupal_goto('checkout/' . $order->order_id);
}

```
> 2 votes

---
Tags: commerce
---


# Question
Title: Weird node edit form behavior with feeds imported nodes
got a weird situation going on. I imported a bunch of nodes from a csv file using the feeds module to a particular content type. This conent type have different type of field like address field, entity reference, and a lot of long text.

All records from the file are imported and I can see all the nodes properly. But when I go in edit mode, All the text fields are empty. Title, address, dates and links fields are ok, but all text are empty. The data is in the database as well as showing on the node, but not in the edit mode.

This is of course causing me problems as when you have to edit, you"loose" all the text. I have a multilingual site...but all those node are set to english...and it's working. The only thing I saw was the fields table didn't seem to get the language value from the node set by the feeds. But I updated it manually in the table and it's not helping anyway.

Th encoding of the csv is utf-8..and I use \n as line break....it's an export of mysql.

Any idea why it's doing this? What I am doing something wrong? Is there a special trick to apply to prevent this...it's driving me crazy..

Thanks

# Answer
Ok,I found the problem. Seems like feeds does not support languages. So in order to make it work, you need to manually update the language of the field in both the data and the revision table for the node you imported using feeds. Once both table are done, the data appears in the edit form.
> 0 votes

---
Tags: 7, nodes, feeds
---


title: Sort nodes based on referenced node

text:
# Question
Title: Sort nodes based on referenced node
Im pretty new with advanced views and references module (Drupal 7). Im seeking for some help.

I would like to sort nodes based on node post date of the nodes that references it. So I have node type A and node type B that can reference node type A (A-one, B-many). I would like to sort type A nodes based on which has the latest Type B node.

Almost like journals that can have posts and I would like to see a list of the journals that have the newest posts.

Any idea how to approach this correctly, I seem to struggle and get some odd results.

**Update:** I would like to sort the journals by the newest post in them. Right now it sorts by the first post in journal. Any idea how to set this? (obviously setting the sort criteria on the sort field to ascending doesnt work, because it will just flip the list of journals...)

# Answer
> 2 votes
You have B that references A (single value entity reference field).

Construct your view as follows:

View of content (nodes) filtered by type A

Relationship: Entity Reference: **Referencing** entity (A bridge to the Content entity that is **referencing** Content via YOUR\_ENTITY\_REFERENCE\_FIELD.). ISSUE - are you making this required? If you do then some A's that are not referenced will not show up. If you leave it as not required then unreferenced nodes will show up in the list either first or last, depending on whether sort is ASC or DESC.

Sort Criteria: Content: Post date, and set the relationship to the relationship added.

And that is it. To test your view you might want to add the field: Post Date, and set the relationship to the relationship added. This will show the post date of the referencing node so you can easily see if it works or not.

You might also want to add a second sort criteria.

---
Tags: nodes, views
---


title: drupal_static_reset causing errors

text:
# Question
Title: drupal_static_reset causing errors
I have developed a custom template for a node where I wanted to essentially show the node in a blank white page. I created a file called node--results.tpl.php and page--node--results.tpl.php that removed just about everything except a few divs. In my module, I have function called `results_view_preprocess_node` that adds the custom javascripts and css files I needed and removed.

```
function results_view_preprocess_node(&$variables) {

  if ($variables['view_mode'] == 'full') {
    $node = &$variables['node'];
    if ($node->type == 'results') {
      //remove all other CSS files
      drupal_static_reset('drupal_add_css');

      $path = drupal_get_path('module','results_view');
      drupal_add_css($path . '/css/styles.css');
      drupal_add_css('sites/all/libraries/jquery/jquery-ui-1.10.4.custom/css/smoothness/jquery-ui-1.10.4.custom.min.css');
      drupal_add_js('/sites/all/libraries/jquery/jquery-ui-1.10.4.custom/js/jquery-ui-1.10.4.custom.min.js');

      $id = $variables['nid'];
      drupal_add_js(
        'meetdir="/files/results/' . $id .'";',
        array(
          'type' => 'inline',
          'scope' => 'header',
          'weight' => 5,
          'group' => JS_LIBRARY,
        )
      );

      drupal_add_js(
        array(
          'results_view' => array(
            'path' => drupal_get_path('module','results_view'),
          ),
        ),
        'setting'
       );
      drupal_add_js(
        $path . '/js/advancedResults.js',
        array(
         'type' => 'file',
         'scope' => 'header',
         'group' => JS_LIBRARY,
        )
      );
      drupal_add_js(
        $path . '/js/filter.js',
        array(
          'type' => 'file',
          'scope' => 'header',
          'group' => JS_LIBRARY,
        )
      );

      //drupal_set_message('<pre>' . print_r($variables,true) . '</pre>','warning');
    }

  }
}

```

I've noticed that when I load a node of this type, I get a large number of warnings and have narrowed it down to `drupal_static_reset('drupal_add_css');`. **When I comment this line out, I don't get the warnings**, but then I don't get a clean page.

```
Notice: Undefined index: group in drupal_sort_css_js() (line 3129 of /mysites/html/development/drupal/includes/common.inc).
Notice: Undefined index: group in drupal_sort_css_js() (line 3129 of /mysites/html/development/drupal/includes/common.inc).
Notice: Undefined index: group in drupal_sort_css_js() (line 3132 of /mysites/html/development/drupal/includes/common.inc).
Notice: Undefined index: every_page in drupal_sort_css_js() (line 3139 of /mysites/html/development/drupal/includes/common.inc).
Notice: Undefined index: every_page in drupal_sort_css_js() (line 3142 of /mysites/html/development/drupal/includes/common.inc).
Notice: Undefined index: weight in drupal_sort_css_js() (line 3146 of /mysites/html/development/drupal/includes/common.inc).
Notice: Undefined index: weight in drupal_sort_css_js() (line 3149 of /mysites/html/development/drupal/includes/common.inc).
Warning: uasort(): Array was modified by the user comparison function in drupal_get_css() (line 3063 of /mysites/html/development/drupal/includes/common.inc).
Notice: Undefined index: type in drupal_get_css() (line 3080 of /mysites/html/development/drupal/includes/common.inc).
Warning: ksort() expects parameter 1 to be array, null given in drupal_group_css() (line 3206 of /mysites/html/development/drupal/includes/common.inc).
Notice: Undefined index: type in drupal_group_css() (line 3218 of /mysites/html/development/drupal/includes/common.inc).
Notice: Undefined variable: group_keys in drupal_group_css() (line 3238 of /mysites/html/development/drupal/includes/common.inc).
Notice: Undefined index: type in drupal_aggregate_css() (line 3279 of /mysites/html/development/drupal/includes/common.inc).
Notice: Undefined index: type in drupal_pre_render_styles() (line 3399 of /mysites/html/development/drupal/includes/common.inc).

```

As far as I have been able to tell, this is the technique you're supposed to use to create a separate template for a node, but obviously, I'm missing something. What do I need to do to fix this?

**EDIT** Looking at the rendered HTML, both CSS files I add using `drupal_add_css` are linked like this:

```
<style type="text/css" media="all">
   @import url("http://www.oregonswimming.org/sites/all/modules/results_view/css/styles.css?ngdwh6");
   @import url("http://www.example.com/sites/all/libraries/jquery/jquery-ui-1.10.4.custom/css/smoothness/jquery-ui-1.10.4.custom.min.css?ngdwh6");
   @import url("http://www.example.com/modules/shortcut/shortcut.css?ngdwh6");
   @import url("http://www.example.com/modules/toolbar/toolbar.css?ngdwh6");
 </style>

```

# Answer
> 0 votes
I ended up removing `drupal_static_reset('drupal_add_css');` from my code and overriding all the drupal css styles in my own CSS file. It's a pain but the only way I can find to get rid of all the errors.

# Answer
> 0 votes
Well, if group, page, weight etc are missing or undefined, try this :

```
$file = drupal_get_path('module','results_view') . '/css/styles.css';
drupal_add_css($file, array(
    'type' => 'file',
    'group' => CSS_DEFAULT,
    'every_page' => TRUE,
    'weight' => 0),
    );

```

Maybe following a `drupal_static_reset('drupal_add_css');` calls to `drupal_add_css` need these attributes. Perhaps the functions defaults get reset as well.

---
Tags: 7, theming
---


# Question
Title: How i can use entity_metadata_wrapper for new database entry and update data in Drupal 7
How i can use entity\_metadata\_wrapper for database entry and update data in Drupal 7

I am using below code to save entry in database but not finding logic to update existing entry

```
    $node = new stdClass();
    $node->type = "event";
    $node->uid = $user_id;
    $entity_wrapper = entity_metadata_wrapper('node',$node);
    $entity_wrapper->title->set($row->title);
    $entity_wrapper->body->set($row->description);
    $entity_wrapper->status->set(0);
    $entity_wrapper->promote->set(0);
    $entity_wrapper->comment->set(0);
    $entity_wrapper->field_eventbrite->set($row->eid);
    $entity_wrapper->field_venue->set($row->name);
    $entity_wrapper->field_eventbrite_city->set($row->city);
    $entity_wrapper->field_privacy->set($row->privacy);
    $entity_wrapper->field_repeats->set($row->repeats);
    $entity_wrapper->field_date_period->set(array(
        'value' => str_replace(' ', 'T',$row->start_date),
        'value2' => str_replace(' ', 'T', $row->end_date),
    ));
    $entity_wrapper->field_eventbrite_url->set(array(
        'url' => $row->url,
    ));
    $entity_wrapper->save();

```

Please help. Please let me know if require more information is needed.Thanks..

# Answer
> 2 votes
Its simple

```
// $nid - nid of node you want to udate
$node = node_load($nid);
$entity_wrapper = entity_metadata_wrapper('node',$node);
...
$entity_wrapper->field_eventbrite->set($row->eid);
$entity_wrapper->field_venue->set($row->name);
$entity_wrapper->save();

```

---
Tags: hooks, entities, 7
---


title: Drupal 8 multilingual node edit

text:
# Question
Title: Drupal 8 multilingual node edit
I have a multilingual setup, and the content translation works well and smooth.

But when I try to edit a node on the other language - I have the same link from the content admin menu, which renders the default language form. I.e. I have /node/21/edit both for En and De versions.

For the test I've try to alter the node object on the form build step (couldn't found a correct hook, so just try it in the FormController::getContentResult() ) - no luck:

```
$translated = $form_object->getEntity()->getTranslation('de');
$form_object->setEntity($translated);

```

form object states the active language as 'de', but the rendered form still has en version fields.

Also the form has native language switcher (Languages), which in my mind should do language switching, but for me it shows only English and does nothing.

# Answer
The entity passed in the `$form_object` is simply ignored, as the whole `$form_object` thing - it is used only to determine the `form id`. You may add entity to the form\_state, but with the original drupal form generation it is ignored too.

To set the node edit translation you need to set `$form_state->set('langcode', $langcode);`

The full thing emulating drupal's node edit form looks like so:

```
public function customEdit($type = 'node', $id, $langcode) {
    $request = \Drupal::request();
    $entity = Node::load($id);
    $form_object = \Drupal::entityManager()->getFormObject('node', 'edit')->setEntity($entity);

    // Add the form and form_state to trick the getArguments method of the
    // controller resolver.
    $form_state = new FormState();
    $request->attributes->set('form', array());
    $request->attributes->set('form_state', $form_state);

    $args = \Drupal::service('controller_resolver')->getArguments($request, array($form_object, 'buildForm'));

    $request->attributes->remove('form');
    $request->attributes->remove('form_state');

    // Remove $form and $form_state from the arguments, and re-index them.
    unset($args[0], $args[1]);
    $form_state->addBuildInfo('args', array_values($args));

    $form_state->set('langcode', $langcode);

    $render_array = \Drupal::service('form_builder')->buildForm($form_object, $form_state);

    return $render_array;
  }

```

The answer is actual for the Drupal 8 beta 2, I'm sure the ability to edit different language node versions would be fixed before release.
> 2 votes

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


title: How Encrypt module actually works?

text:
# Question
Title: How Encrypt module actually works?
I installed the Drupal Encrypt module and enabled it. However, I wonder how this module actually works. Does it encrypt all the submissions from the browser that the user/admin key in like 1) Login 2) Add/update node 3) Contact form/webform and decrypted again in the server before saving to the database ? Any tool to test this process? I'm looking a way to protect all the submissions or update over the internet which may be captured or exposed especially in the public area when using those free Wi-Fi. Please advise.

# Answer
The Encrypt module:

> provides an application programming interface (API) for performing two-way data encryption. It allows modules to encrypt data such that it can be decrypted using the same key that was used to encrypt the data. This is useful for **storing sensitive information**.

Emphasis mine. That's its purpose, to provide an API that other modules can use to encrypt data before it's stored in the database (or elsewhere I guess).

As an API module, it provides no functionality unless you make explicit use of it; either by installing one of the modules listed that uses it, or by writing a custom module that does so. The emphasis is on you (or the writer of a contrib module) to actually do something useful with this module:

> It is up to the module calling encrypt() to manage and store the encrypted data.

The important thing to understand is that it doesn't (and couldn't) protect users from having their data sniffed over a public network. For that you'll need to use HTTPS, no exceptions. All this module does is offer an encryption/decryption service for your server-side app.
> 3 votes

---
Tags: security
---


# Question
Title: How to import translated strings having dynamic variables?
**Short:** How can I import .po file having dynamic variables in strings like follows

```
$message = t('Hi @firstname, please follow @sitelink or mail me at @email ', $var);

```

**Indetail:**

I've written a custom module to send mail notification to users. In that module `$message` string has dynamic variables like follows (sample)

```
$var = array('@firstname' => $username, '@sitelink' => $GLOBALS['base_url'], @email => $email);
$message = t('Hi @firstname, please follow @sitelink or mail me at @email ', $var);

```

How can I import `$message` string to my site.

I could translate all the static strings to Spanish of other custom modules like follows.

```
#: mycustom.module
msgid "Are you sure to approve"
msgstr "¿estás seguro de aprobar"

```

But how can I write the same for Dynamic variables. Right now Spanish Users are getting their mail in English?

Note: I'm just using Drupal core *Locale* module.

# Answer
There are two way to achieve this

Add string in a your .po file like follows

```
msgid "Hi @firstname, please follow @sitelink or mail me at @email"
msgstr "Hola @firstname, por favor, siga @sitelink o envía un email al @email"

```

and import that .po file by going

> Administration » Configuration » Regional and language » Translate interface » Import

If you want to change individual translated strings go to

> Home » Administration » Configuration » Regional and language » Translate interface » Translate

You can find list of strings there each having edit link beside. So you change the individuals like follows.

Hope this helps someone.
> 0 votes

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


# Question
Title: Inform user with account creation email, for existing users to
Is there a way(It doesn't matter if passwords need to be recreated/generated) to send all the users an email about there account being added to the website after they are already added?

# Answer
I'd be really interested in this idea too. I'm making a website to contain and extend an existing registry and it would be great to set the whole thing up with all the members' details and then just send out a mass email containing each user's username and generated password when everything's put together...

I haven't tested it yet, but it could potentially be done:

1. Set up your users, ensuring 'Notify User' is unchecked and Status is 'Blocked'. If you already have active users, block them (make sure no email goes out, check `admin/config/people/accounts`)
2. When you're ready to notify the users, go to `admin/people` and check all the blocked users, then user Bulk Options to Activate them (if there's a huge amount of users you might want to do a group at a time to save the server a bit...)
3. Individual emails should be sent out containing a 'one-time login', see `admin/config/people/accounts` and scroll down to E-mails and choose 'Account Activation' for the email which goes out.

I will give it a shot and let you know if it worked.
> 1 votes

# Answer
The Account Reminder module could probably handle this requirement. Available for D6 and D7. Offers the ability to schedule the email to a given number of days after the account was set up and, as you might guess from the name it is designed to remind users who have not logged in to their account to log in. Can also be configured to send several reminders every X days.
> 1 votes

# Answer
Maybe there is a module for that but I don't know it. But I would use `hook_user_insert` in a custom module and intercept each user creation. In this hook\_user\_insert I would invoke `drupal_mail`
> 0 votes

# Answer
Mass Messaging will allow you to do that.

> This module allows you to send mass messages to users. To compose and select recipients the Views module is used. This allows complex selection queries setup by a administrator. The mapping of the view fields and the subject, recipient, message body and the attachments is done in the view. To send a message the view plus the arguments of the view are put into a queue. The cron does then send the messages in the background.
> 0 votes

---
Tags: users, emails
---


# Question
Title: Multiple forms for one content type using one module
I want to create the following functionality:

Multiple interrelated forms needed

* Form 1,
* Form 1 detail and
* Form 1 user detail

But the user can fill in the forms only in order.. I mean when the first form is not inserted then the detail and user detail form aren't available to the user.. and additionally I want to relate those forms also..

Is this possible with just one content type? Any ideas how I can achieve this in Drupal 7?

# Answer
You can use drupal Webfroms for this purpose.

Webform is the module for making surveys in Drupal. After a submission, users may be sent an e-mail "receipt" as well as sending a notification to administrators. Results can be exported into Excel or other spreadsheet applications. Webform also provides some basic statistical review and has and extensive API for expanding its features.

Some good examples could be contests, personalized contact forms, or petitions. Each of these could have a customized form for end-users to fill out. If you need to build a lot of customized, one-off forms, Webform is a more suitable solution than creating content types and using CCK or Field module.

here is the way you can create a multi step form which solves your purpose
> 2 votes

---
Tags: 7, webforms, nodes
---


title: Filter content by own content or admin

text:
# Question
Title: Filter content by own content or admin
So I have an entity reference field on a node, the widget is a select-box.

I want so that an user can choose one of their own authored nodes as a reference OR if an admin is logged in, they can choose any content. So admins should be able to bypass this restriction (with a permission, role or something).

I tried building a view based on this, but the contextual filter seems to be the problem. I can't really do any either/or kind of thing with contextual filter.

# Answer
> 1 votes
## Background

> So I have an entity reference field on a node, the widget is a select-box.

You (Risse) have already done this, but to make this clear for other users, this involves adding an entity reference field to a content type and in the field settings changing from the default 'Simple..' to 'Views..':

Now the select list used to choose a referenced entity (in this case a node), will use views to create the select list, allowing us to customise the nodes listed. In the example above I have created a view (and added an 'Entity Reference' display) and called it entity\_reference\_select.

> I want so that an user can choose one of their own authored nodes as a reference OR if an admin is logged in, they can choose any content. So admins should be able to bypass this restriction (with a permission, role or something).

It is easy enough to list only nodes by the current author using the filter "Content: Author uid" in the view (as per @molot above). Unfortunately this does allow us to differentiate the results for admin users.

An appropriate response might initially seen to involve an OR statement in the views filters to allow admin user to see all nodes in the select list, and other users to only see their own nodes. Unfortunately there are two issues with this:

* There is no way to create a views **Relationship** to the current user in order to evaluate the current user's roles in the filters section
* An OR conditional in the filters will **remove** options, not add them, so would remove non authored nodes from an admin role user anyway

## Solution

Provide a default value for a contextual filter which is defined by PHP. This means we can specify which user(author) we are going to filter the results by, which would be the current user (fetched from the global $user object) unless the current user has the 'administrator' role, in which case we list nodes authored by **all** users.

---
Tags: views, entities
---


# Question
Title: Is it possible to build a complete web site with Drupal 7 without using contributed modules or Hooks?
Is it a good programming practice to add your own hooks in a template.tpl.php or is it best practice to make all the changes possible into a custom module?

# Answer
It depends on the site's requirements. If you want to create a site only for content listing, you can simply change in template files to make it as per design. But you must keep your theme in `sites/all/themes` directory.

But generally the requirements are not so simple. The modules are contributed to make the better user experience. If you are asking this question for the better performance of site, then you should maintain your site with drupal standard.

The things to keep in mind :

1. Use contributed module rather than writing custom module.
2. In some case if you have to write custom module, then use drupal functions and API rather than core PHP functions.
3. Always keep your site (drupal/modules) updated with security releases.
> 2 votes

---
Tags: 7, hooks
---


# Question
Title: Custom submit button callback overrides default callback?
I am trying to accomplish the following functionality:

I have a profile2 registration form to which I have added a custom form element (just a submit button) using `hook_form_alter()`.

The submit button has a `#submit` property set to a `custom_callback` function.

For debugging purposes, the callback function just displays a

```
drupal_set_message('hello world');

```

The general idea is that the button is used to gather information from a webservice (in the callback function) and then fill the form with the returned values.

The user can then check the values and submit the user registration form.

When I click the custom submit button, it fires the custom callback. But when I click the user register form submit button, it also fires the custom callback?

I have checked the dpm of $form and the `#submit` properties are as follows:

```
$form['#submit'][0] == de default (correct) user registration callback
$form['custom']['#submit'][0] == de custom submit handler

```

So, any clues on why the default submit handler no longer works?

**EDIT:**

My form alter implementation looks like this (just add an image button)

```
   $form['custom'] = array(
    '#name' => 'custom',
    '#type' => 'image_button',
    '#src' => drupal_get_path('module', 'custom') . '/logo.png',
    '#value' => t('get data'),
    '#prefix' => '<div class="button-wrapper">',
    '#attributes' => array('alt' => t('get data')),
    '#suffix' => '</div>',
    //'#weight' => -99,
    '#submit' => array('custom_callback'),
  );

```

Thanks in advance!

# Answer
> 2 votes
Problem seems to be custom form element. Change it to :

```
$form['custom'] = array(
    '#name' => 'custom',
    '#type' => 'submit',
    '#value' => t('get data'),
    '#prefix' => '<div class="button-wrapper">',
    '#attributes' => array('alt' => t('get data')),
    '#suffix' => '</div>',
    '#submit' => array('custom_callback'),
  );

```

---
Tags: forms
---


# Question
Title: Fetch data from database and show in custom module's form
I used the following code in my module to build a form :

```
$form['promo_type'] = array(
  '#type' => 'select',
  '#title' => 'Promotion Type',
  '#options' => array(t('Digital Coupon')),
);

```

I want the `option` data as dynamic, fetch from database. How can I do that?

# Answer
Use db\_select to fetch data from database. Create an array of values :

```
$result = db_select('table', 't_alias')->fields('t_alias', array('id', 'title'))->execute()->fetchAll();
$options = array();
foreach ($result as $value) {
  $options[$value->id] = $value->title;
}

$form['promo_type'] = array(
  '#type' => 'select',
  '#title' => 'Promotion Type',
  '#id' => 'promo_type',
  '#options' => $options,
  '#required' => TRUE,
);

```
> 4 votes

---
Tags: forms, database
---


# Question
Title: how to send notification to seller when payment is received
I want the system to send an email notification to the author of the product when the payment is received on their product. I have tried to run the module mp\_tokens this scenario but I do not find the token \[order-seller-email\] there. please help how to create a token for this issue

# Answer
> 2 votes
Assuming author of product is also seller, You can do this with a rule using loop and author:mail. Try importing this rule and see how it works

```
{ "rules_e_mail_seller_checkout_notification" : {
"LABEL" : "E-mail seller checkout notification",
"PLUGIN" : "reaction rule",
"REQUIRES" : [ "rules", "uc_cart" ],
"ON" : [ "uc_checkout_complete" ],
"DO" : [
  { "LOOP" : {
      "USING" : { "list" : [ "order:products" ] },
      "ITEM" : { "list_item" : "Current list item" },
      "DO" : [
        { "mail" : {
            "to" : "[list-item:node:author:mail]\u000D\u000A",
            "subject" : "OrderID: [list-item:order-id] Product: [list-item:title]",
            "message" : "Order: [list-item:order-id]\u000D\u000ANid: [list-item:nid]\u000D\u000ATitle: [list-item:title]\u000D\u000AQty: [list-item:qty]\u000D\u000APrice: [list-item:cost]\u000D\u000ASeller: [list-item:node:author]",
            "language" : [ "" ]
          }
        }
      ]
    }
  }
]

```

} }

source - https://www.drupal.org/node/1830962

# Answer
> 1 votes
One option is to use Ubercart Rules to add integration with Rules, and then configure a reaction rule to send an e-mail when payment completes.

# Answer
> 1 votes
You could use rules for this, Check this http://www.drupalcommerce.org/user-guide/checkout-completion-rules

---
Tags: 7, ubercart, tokens
---


title: Views and Taxonomy Filtering

text:
# Question
Title: Views and Taxonomy Filtering
I have a question regarding filtering in Views.

**My setup:**

• I have a content-type, for example: Cars
• I have a few different taxonomy term fields attached to that node, something like: Car brand, Car color, Car type, with the following terms:

* Vocabulary: Car brand
    + Term:Car Brand A
    + Term: Car Brand B
    + Term:Car Brand C
* Vocabulary: Car color
    + Term: Blue
    + Term: Red
    + Term: Black
* Vocabulary: Car type
    + Term: Two seater
    + Term: SUV
    + Term: Sedan

I have a View that displays all the available cars, and I used Better Exposed Filters to display a block that displays those taxonomy fields as filters. Now: this is were I get stuck.

Say for example, that 'Car Brand A' only only sells Blue and Black Sedans. What I would like is that the color option 'red' and car types 'SUV' and 'Two seater' are hidden as selectable option, and re-added if a user selects other brands. How do I do that?

I really hope you can help me with this! :)

# Answer
If I understand your question correctly, you need the functionality of the Views Selective Filter module.

Although I haven't used this module myself, I've written a similar Views handler in a custom module. This filter handler removes all options from select lists that don't provide any results (due to other selected values). If the Views Selective Filter doesn't provide the desired functionality, I can create a sandbox project of my code.
> 2 votes

# Answer
View's default expose filter didn't give such functionality. You may need the Search API module.

I have seen it in Commerce Kickstart package but didn't use it from fresh setup.
> 0 votes

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


title: Add Font Awesome to Webform Placeholder

text:
# Question
Title: Add Font Awesome to Webform Placeholder
I am currently using Webform 7.x-4.2 and am looking to add a Font Awesome icon inside the placeholder. I did try modifying the settings.php with the following line:

```
$conf['webform_allowed_tags'] = array('a', 'em', 'strong', 'code', 'img', 'i');

```

My understanding was that this would allow me to use an 'i' tag on my webforms but it is not working for a placeholder. It does work if I use the tag in place of my label but then when a user gets a confirmation email with a submission summary the label shows the 'i' tag (ex. )

Is there a way to use Font Awesome in a placeholder?

Thanks for any assistance.

# Answer
> 1 votes
After reading question again I was way off. I am not sure if there is an easy cut and dry way to do this but I did find a workaround with hook\_preprocess\_webform\_element. The code is pretty rough but should point the way to suit your needs.

Example:

```
function MY_MODULE_preprocess_webform_element(&$variables) {
 $icons = array(
  'fa-adn' => '',
  'fa-align-right' => '',
 );
 if (isset($variables['element']['#attributes']['placeholder']) && array_search($variables['element']['#attributes']['placeholder'], array_keys($icons)) !== FALSE) {
  $icon = $variables['element']['#attributes']['placeholder'];
  $search_string = implode('|', array_keys($icons));
  $variables['element']['#children'] = preg_replace('/^(<input .*placeholder=")(' . $search_string . ')(".*\/>)$/', '$1' . $icons[$icon] . '$3', $variables['element']['#children']);
 }
}

```

This will allow the editor to put the fa icon name in the placeholder text field on the edit form.

You can find the codes for the fa icons here.

**EDIT:** I forgot to add that you would have to change the font-family for the element and then remove it when the placeholder disappears if you are not using FA for your sites font.

**Edit2:** Per comment you can add a wrapper class to the textfield when editing the component then use CSS to have an icon permanently in front of the textfield.

```
.textfield-wrapper::before {
  position: relative;
  font-family: FontAwesome;
  margin-left: 5px;
  content: '\f061';
 }

```

**Note:** If you want the icon 'inside' the text field you can add the appropriate top, left positioning and z-index to this CSS.

---
Tags: webforms
---


# Question
Title: How to change end date automatically after changing start date?
I would like to be able to automatically change the value of the end date to be the same as the start date after changing the start date.

Ex: right after changing the start date to 12-12-12, the end date would be the same.

Here's what I did so far:

Added the following code in a custom module (form\_modif) :

```
$form['#attached']['js'][] = drupal_get_path('module', 'form_modif') . '/custom_alter.js';

```

Witch seems fine, I can see that the script is added in the code source of the page

The JS file's code is :

```
(function ($) {
  Drupal.behaviors.form_modif = {
    attach: function(context, settings) {
      $('.field_date_1').change(function(){
        $field_date1 = $(.FIELD_DATE_2').val();
        $('.field_date_2').val($field_date1);
      });
    }
  };
});(jQuery);

```

And that's where my problem seems to be, I'm not very good in JS, could someone help me with that?

Here's the HTML code of thoses fields if that can help:

Start date field:

```
<input class="date-clear form-text hasDatepicker date-popup-init" type="text" id="edit-field-date-und-0-value-datepicker-popup-0" name="field_date[und][0][value][date]" value="31/01/2014" size="20" maxlength="30">

```

End date field:

```
<input class="date-clear form-text hasDatepicker date-popup-init" type="text" id="edit-field-date-und-0-value2-datepicker-popup-0" name="field_date[und][0][value2][date]" value="31/01/2014" size="20" maxlength="30">

```

# Answer
I did it the way pretty much mentioned in question with some corrections.

My code with javascript file is

```
// Change the end date value to same as that of start date.
Drupal.behaviors.form_modif = {
  attach: function (context, settings) {
        $('input#edit-field-event-date-und-0-value-datepicker-popup-0').change(function(){
        var field_date1 = $('input#edit-field-event-date-und-0-value-datepicker-popup-0').val();
        $('input#edit-field-event-date-und-0-value2-datepicker-popup-0').val(field_date1);
    });
  }
};

```

}(jQuery));
> 1 votes

# Answer
As Kari stated, your selectors looks odd comparing to the HTML you provided.

When you're doing this in jQuery : `$('.field_date_1')` that means you want to select all DOM elements with the class "field\_date\_1". As we can see in your HTML, there is no such class for your elements.

What you have for both class elements is : `date-clear form-text hasDatepicker date-popup-init`. As they are the same for both input, you can't distinguish them using class.

You need to find another way of selecting your elements. I would advise you to take a look at some jQuery tutorials, like this one, so you can find the right way to select your inputs.

For example, you could try `$('input').first()` to select the first input of **your page**, or `$('.my-form-element input').first()` to select the first input inside the DOM element with the class "my-form-element", etc.
> 0 votes

---
Tags: javascript, datetime
---


# Question
Title: How can I list the users who are associated with a given Profile2 profile using Views?
I have a site that has an Organization content type. Each organization has an associated Profile2 profile that contains a reference to a Taxonomy vocabulary depicting the hierarchy of the organization. When users register, they are presented with the given Profile2 profile associated with the organization they belong to.

I am creating a report in Views that needs to display the following:

* Organization
    + Hierarchy
        - User

I can establish a relationship between the organization and the Profile2 profile, and the profile and the taxonomy. However, I cannot find a way to establish a relationship between a given Profile2 profile and the users who are associated with that profile. Does anyone know if I should be able to establish this relationship, or is it going to require some custom Views code?

Or, if anyone has a better suggestion on how to create this hierarchy, I'm open to suggestions.

Thanks!

# Answer
As I understand it, several 'profile types' with different fields and questions relevant to various 'organizations' in your company.

Here's a suggestion to create a view which shows a list of the details in all profiles grouped by 'organization field' and sorted by the various 'hierarchy fields'.

The key to making this work is that the different profile types have a couple of fields in common eg. organization, first name, surname etc. Assuming each profile type uses the same 'field\_organization', 'field\_first\_name', 'field\_surname' we can use table view and grouping. If we need to display profiles with different fields, then add the fields and select another view type such as list view instead.

You may be able to do this even if only field\_organization is in common in all the profiles (with list format instead of table format. Even if the profiles have other fields which don't match, they can be combined into the same report using 'list view' instead of table view.

* Create a new view.
* Either: Show 'Profiles' of type 'profile type for particular organization'
* Or: Show 'Profiles' of type 'All'
* Create as a block and/or page as required. This will show a list of profile ids.
* (optional) In view editor, add a relationship "Profile: User uid" This will give you access to the person's username and email. Add fields as required eg. mail from user, username from user,
* Add fields fields "Organization"
* Add each of the "Hierarchy" fields
* (optional) add field "Profile: type"

If the fields are shared and appear in more than one profile type, you should see "Appears in: profile2:org\_1, profile2:org\_2, profile:org\_head\_office etc. as you select the field to be added.

To group by organization as you outlined, avoid 'grouping and aggregation', and instead select 'Format: HTML list". In the 'format settings' use the 'Grouping field Nr.1 ' to 'Organization'.

Caveat \- if someone has more than one profile, they will appear more than once in this list.

If there is just one 'hierarchy' taxonomy reused in all the profiles, then you might be able to add this as 'Grouping field Nr. 2' instead of relying on sorting.

With luck you should end up with a list such as:

# Organisation Unit 1:

* Firstname Surname Heirachy position1
* Firstname Surname Heirachy position2
* Firstname Surname Heirachy position3

Organisation Unit 2

* Firstname Surname Heirachy position1
* Firstname Surname Heirachy position2
> 1 votes

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


title: Protocol Relative URLs in Drupal 6

text:
# Question
Title: Protocol Relative URLs in Drupal 6
I'm trying to avoid serving pages that load css and js resources through URLs that specify either http or https.

Because Drupal is specifying http:// for the href for all the CSS and JS files. Caching server varnish, caching the JS & CSS files twice (through http & https).

Instead of

```
<link type="text/css" rel="stylesheet" href="http://www.example.com/sites/default/files/css/css_pbm0lsQQJ7A7WCCIMgxLho6mI_kBNgznNUWmTWcnfoE.css" media="all" />

```

I'd like to serve

```
<link type="text/css" rel="stylesheet" href="//www.example.com/sites/default/files/css/css_pbm0lsQQJ7A7WCCIMgxLho6mI_kBNgznNUWmTWcnfoE.css" media="all" />

```

Trying to achieve this in Drupal 6 sites through a module.

# Answer
Issue is fixed now. Implemented module\_preprocess() (in custom module)

```
function module_name_preprocess(&$vars) {
    foreach (array('head', 'styles', 'scripts') as $replace) {
    if (!isset($vars[$replace])) {
        continue;
    }

    $vars[$replace] = preg_replace('/(src|href|@import )(url\(|=)(")http(s?):/', '$1$2$3', $vars[$replace]);
}

```

}
> 1 votes

---
Tags: 6
---


# Question
Title: Hide Certain Values from an Apache Solr Facet
I have some Apache Solr facet blocks i'd like to filter certain values from. For example if a facet contains the values:

Filter by letter:
\- a (6)
\- b (4)
\- c (2)

I want to hide the facet "c" so visitors won't be able to use it as a filter. Is it possible? i'm ok with editing/creating modules and also it would be okay a solution that uses CSS to hide the row from view (which was my first thought but then i realized there isn't a unique identifier for facet values)

# Answer
I kept looking for a solution on the internet after posting this question and i have discovered this module: https://www.drupal.org/project/facetapi\_bonus which does exactly what i need
> 1 votes

---
Tags: search
---


# Question
Title: How do I prevent CKEditor 4 from stripping Google AdSense asynchronous tags?
For whatever reason, CKEditor 4 is stripping Google AdSense asynchronous tags from my Full HTML text format.

What starts as this (placeholders substituted for IDs):

```
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js">
</script>
<!-- Top Banner -->
<ins class="adsbygoogle"
    style="display:inline-block;width:728px;height:90px"
    data-ad-client="ca-pub-XXXXX"
    data-ad-slot="XXXXX"></ins>
<script>
    (adsbygoogle = window.adsbygoogle || []).push({});
</script>

```

Ends up as this:

```
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js">
</script>
<!-- Top Banner -->
<script>
    (adsbygoogle = window.adsbygoogle || []).push({});
</script>

```

Again, this is in the Full HTML text format and I'm able to get the *ins* tag through without attributes, but not with attributes, even though other tags have no problems getting their attributes through to save.

For what it's worth, I do have the following set on the CKEditor profile:

```
config.allowedContent = true;

```

**UPDATE**

CKEditor is only stripping the *ins* tag (and attributes) when it's an empty tag as given by AdSense. If I add anything – a non-breaking space, even – CKEditor is preserving the *ins* tag and attributes.

Per tenken's suggestion, I added the following line to my config, but it didn't help.

```
config.protectedSource.push( /<ins class=\"adsbygoogle\" style=\".*\" data-ad-client=\".*\" data-ad-slot=\".*\"\><\/ins\>/g );

```

# Answer
> 2 votes
Have you read this blogpost (not by me) Drupal WYSYWG Module Custom CkEditor Configuration by Philip Norton.

Your `<script>` tags are not being stripped out, but the funky `<ins>` tag is. From that blog post you should be able to add a `protectedSource` to the AFC rules so that those elements are not stripped. This is untested but deriving from the blogpost:

```
// Allow Google Adsense <ins> tags, I'm being more specific
// than allowing any raw <ins> tag here. This may be too specific, but
// play with it.
config.protectedSource.push( /<ins class=\"adsbygoogle\"\>.*?<\/ins\>/g );

```

In order for this configuration to work you may have to install the WYSIWYG module (or append to your own ckeditor javascript profile directly).

# Answer
> 0 votes
This is from: http://margotskapacs.com/2014/08/taking-ckeditor-a-apart/

There is defined list of tags that is going to be removed if empty(see dtd.js and $removeEmpty). To ensure the certain empty tag are not being removed, add attribute ‘data-cke-survive’:

or pass the following to the CKEditor configuration file:

CKEDITOR.dtd.$removeEmpty\['span'\] = 0; CKEDITOR.dtd.$removeEmpty\['TAG-NAME'\] = 0;

This make the empty tags to not being removed NOTE: If you working with the production CKEditor.js, you will have to alter section starting “CKEDITOR.dtd” as following:

CKEDITOR.dtd=function(){var a=CKEDITOR.tools.extend,e=function(a,d){for(var \[...\] span:0//set the TAG:0 .. You will have to grep the CKEditor.js file for section starting “CKEDITOR.dtd” and then change value from 1 to 0 for each tags you like to not be removed if empty(see above example for ‘span’ tag)

---
Tags: 7, wysiwyg, input-formats
---