title: Search filter result score

text:
# Question
Title: Search filter result score
I'm seeing an interesting anomaly (?) I'm trying to get to the bottom of. I've set up a view with an exposed filter Search: Search Terms. I am trying to mimic the result set offered by standard drupal search module, but am finding interesting results based on the score.

When I search for "term1" (no quotes) in both standard site search, and within the view:

* result set is similar, but not the same.
* actual score returned for items in sitewide search, and views search are different.

So I guess, my question really is "where is the search modules' results score coming from, and how can I recreate it within a view?"

I should add I am not using any special search modules at all, just core search module.

**Core search sql, as viewed from devel:**

```
SELECT i.type AS type, i.sid AS sid, SUM((45.0578814438 * i.score * t.count)) AS calculated_score
FROM search_index i
INNER JOIN node n ON n.nid = i.sid
INNER JOIN search_total t ON i.word = t.word
INNER JOIN search_dataset d ON i.sid = d.sid AND i.type = d.type
WHERE (n.status = :db_condition_placeholder_0) AND( (i.word = :db_condition_placeholder_1) )AND (i.type = :db_condition_placeholder_2) AND( (d.data LIKE :db_condition_placeholder_3 ESCAPE '\\') ) GROUP BY i.type, i.sid
HAVING (COUNT(*) >= :matches)
ORDER BY calculated_score DESC
LIMIT 10 OFFSET 0

```

**From the created view:**

```
SELECT node.title AS node_title, node.nid AS nid, node.type AS node_type, SUM(search_index.score * search_total.count) AS score, 'node' AS field_data_body_node_entity_type, 'search_test:page' AS view_name
FROM
{node} node
LEFT JOIN {search_index} search_index ON node.nid = search_index.sid
LEFT JOIN {search_total} search_total ON search_index.word = search_total.word
WHERE (( (node.status = '1') AND( (search_index.type = 'node') AND( (search_index.word = 'test') ))))
GROUP BY search_index.sid, score, node_title, nid, node_type, field_data_body_node_entity_type, view_name
HAVING (( (COUNT(*) >= '1') ))
ORDER BY score DESC
LIMIT 10 OFFSET 0

```

# Answer
There are a few things affecting the difference in results. I'm sure you noticed the queries differ slightly.

* The first and core issue is that the `search` module's main table is `search_index`, so each row is built around entries in that table and then joined outward to get more information. Your `view` is built around the `node` table and joined the other direction to search index.
* The core search uses inner joins to get node data, which will be more limiting in its result sets (see this answer.)
* The `search_dataset` table isn't joined from the Views search (see this answer for an explanation of why.)
* Core search multiplies the search scores by relevance, which shouldn't affect their ranking, but looks confusing. See line 496-500 of `search.extender.inc`.

I know I only answered the first half of your question, but I hope this helps. I'm not sure it's possible to get a View to exactly mirror your search results without considerable customization.
> 0 votes

---
Tags: views
---


title: How to get header.php drupal 7

text:
# Question
Title: How to get header.php drupal 7
I have the next files .tpl.php in my drupal7:

* page-front.tpl.php
* page.tpl.php
* page-taxonomy.tpl.php

I want include a header.php and footer.php with the follow way but is not working:

```
<?php include_once($theme_path.'/include/header.php');?>

```

How can I get common files from a tpl.php?

# Answer
Use `drupal_get_path()`, e.g.

```
<?php include_once drupal_get_path('theme', 'MYTHEME') . '/include/header.php'; ?>

```

`include_once` isn't a function so no need for parentheses.
> 0 votes

---
Tags: theming
---


title: Performance effect on field length

text:
# Question
Title: Performance effect on field length
When we are adding a text field to a content type the default length is 255. I am curious to know the performance effect of the field types and the length have for it.

Is there a preferred order of fields and length based on performance? so that we can chose our fields accordingly.

# Answer
> 1 votes
Going over 255 means that field can not easily be indexed and thus if you filter on it in views or in a query it will be slow. As long as you stay below this limit all is well.

---
Tags: entities, performance
---


# Question
Title: Custom fivestar widget does not display custom icons
I am struggling to get my custom widget for the Fivestar module to work. The only time when I can see my new star icons is when I change the options in *manage display* for the field in *content type*. Otherwise, the default stars are shown (in the dimension that I state in the css).

I created the widget following the tutorial number 17. I kept the same names, just changed the size of the stars. Here is my code for the .module:

```
function my_stars_fivestar_widgets() {
  // Letting Fivestar know about my custom stars.
  $widgets = array(
    drupal_get_path('module', 'my_stars') . '/my_stars.css' => 'my_stars',
   );
 return $widgets;
}

```

And here is the css:

```
/* Static View-only Star Version */
.fivestar-my_stars div.fivestar-widget-static .star {
  width: 28px;
  height: 28px;
  background-image: url(my_stars.png) no-repeat 0 0;
}
.fivestar-my_stars div.fivestar-widget-static .star span.on {
  background-image: url(my_stars.png) no-repeat 0 -56px;
}

.fivestar-my_stars div.fivestar-widget-static .star span.off {
  background-image: url(my_stars.png) no-repeat 0 0;
}

/* Javascript Star Version */
.fivestar-my_stars div.fivestar-widget .cancel,
.fivestar-my_stars div.fivestar-widget .star {
  width: 28px;
  height: 28px;
}
.fivestar-my_stars div.fivestar-widget .cancel,
.fivestar-my_stars div.fivestar-widget .cancel a {
  background: url(cancel.png) no-repeat 0 0;
}

.fivestar-my_stars div.fivestar-widget .star,
.fivestar-my_stars div.fivestar-widget .star a {
  background: url(my_stars.png) no-repeat 0 0;
}

.fivestar-my_stars div.fivestar-widget div.on a {
   background-position: 0 -28px;
}
.fivestar-my_stars div.fivestar-widget div.hover a,
.fivestar-my_stars div.rating div a:hover {
 background-position: 0 -56px;
}

```

I am using Drupal `7.38`, fivestar 7.x-2.1, Voting API 7.x-2.12, and Halfstar 7.x-1.1 is installed but deactivated at the moment.

# Answer
Without seeing your file structure it is difficult to discern your problem. But I suspect the hook is having issues with the path to your css. I have found a really nice tutorial to do this, it setups a widgets folder in your custom module and uses file\_scan\_directory to scan all custom star folders in that folder.

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

Be mindful that there is a slight error in the code as it is outdated, in the foreach, you need to use $file-\>uri instead of $file-\>filename for the array key.

---

`foreach ($files as $file) {
 if (strpos($file->filename, '-rtl.css') === FALSE) {
 $widgets[$file->uri] = drupal_ucfirst($file->name);
 }
 }`
> 1 votes

---
Tags: 7, rating
---


title: Reversing a number

text:
# Question
Title: Reversing a number
I am trying to use a form field to add a number to itself, reversed. Such as number input into field 15729 which would be added to 92751 and the result displayed. Any clue how to do this?

# Answer
You could try Computed field to use PHP to calculate the reverse of the number.

> Computed Field is a very powerful field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views. (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of fields. So start cooking up your PHP based values!

(heres a snippet from, http://www.phpmoot.com/php-reverse-number/ on how to reverse a number in php - there are lots of different ways to do, just google it)

```
<?php
$num=65410205; // 65410205
$revnum=0;
do{
 $revnum=($revnum *10)+($num % 10);
 $num=(int)($num / 10 );
}while($num>0);
echo $revnum;  // 50201456
?>

```

Then add the two fields together with a Computed field.

Edit: didn't see your tag for javascript, you can use this https://stackoverflow.com/questions/6351825/reverse-decimal-digits-in-javascript#answer-6351965 to reverse the number, then simple JS logic to output the values in the textboxes you want... but using JS for this is not a drupal solution it's pure JS which is slightly off-topic.
> 2 votes

---
Tags: entities
---


# Question
Title: how to fetch user related tables from live sever with drush sql-sync
If you have a live server where some people have registered to your iste and you push new content from your dev,server regularly. What is the best workflow to fetch user related data from the server before you sql-sync and r sync an updated site to the live server with drush?

# Answer
It is not recommended to push your database from dev to live. Instead, push just the code from dev -\> stage -\> live, and pull the database in the other direction.

There are a number of solutions for moving content from dev or staging to live. One option is the content staging module; other people use feeds to import new data.
> 0 votes

---
Tags: drush
---


# Question
Title: How does the private files folder need to be configured exactly?
In `settings.php` I specified as `/home/username/myfiles`

Under Config \> File System it shows the path, but when I add a file field to content, it does not show private upload as an option. I am wondering if it is because of how I specified the path? The path exists, and is writable. So I am confused.

Any ideas?

# Answer
> 3 votes
Ahhhh, just needed to clear cache...

---
Tags: 8, files
---


# Question
Title: How to secure access to a Forena data block?
I have set up an external database source using the Forena reports module and the PDO driver. This data source has its data security method set to "Use Drupal permissions". The only other option is "Match values provided by a data block".

There is a matching Drupal permission for the data source in admin/people/permissions labelled "Access MyDB data". (Machine name "access my\_db data"). The "Access MyDB data" permission has only been granted to a couple of roles.

What I have tried: I put a line in my .sql file for the data blocks built on this source:

```
--ACCESS=access my_db data

```

This prevents anyone from getting any results from the report based on this data block, even the Drupal administrator.

I removed the above line in the .sql file. This allows any logged in user to access the report. It does not respect the permission "Access MyDB data".

How do I set this up so that the access to this data block (and therefore the reports using it) is limited to only those who have the "access my\_db data" permission?

# Answer
Quote from the documentation that comes with Forena, about Data Block Security:

> Data Blocks Security is a technique used to secure a selected data block. It is an additional (but optional) security layer on top of the Drupal permission "**access repository name data**" right (whereas "repository name" is the name of the data block's repository). Using this technique it is possible to enforce additional Drupal permissions such as:
>
> * access content
> * access administration pages
> * administer content
> * administer users
> * administer permissions
> * ... (the (Drupal permissions) sky is the limit)
>
> Data Blocks Security is actually implemented by means of a comment containing **ACCESS=some\_permission**. It is added near the top of a data block which indicates the Drupal permission required to access the data retrieved by the data block. Its format depends on the format of the Data Block (which can be either in SQL format or in XML format), as further detailed below.

From the scenario in the question here, it appears to me that there is no need for adding such comment with **ACCESS=some\_permission**, instead it should be sufficient to only use the **access repository name data** for those "couple of roles" that should have access to the data in the report.

Note the **data in the report** I wrote here: it is well possible that users who do not have the required permission for the data blocks, do have access to such "reports" anyhow. However: those reports, by design, do not show any data of the data blocks they do not have access to.

Nevertheless, I wonder if there is anything (like a bug?) that may be related to the "`my_db`" part of your issue. Therefor I'd recommend to also experiment with (eg) the "Drupal" reports: only grant access to these reports to "Admin" role, and then run a similar testcase. How do your results look like in that scenario? As a variation, can you (temporarily) rename "`my_db`" to "`mydb`", to check what results you then get?
> 1 votes

---
Tags: 7, log-messages, forena
---


# Question
Title: After installing composer: "The drush command X could not be found"
**Edit: re-wrote intro paragraph to highlight the installation of composer - I suspect composer may have broken drush.**

I want to test out elastic search with D7. I used drush to install a fresh D7 install, then views, elasticsearch\_connector, libraries. At that point Watchdog indicated that I was missing the elasticsearch-php library.

I tried to follow Elasticsearch's instructions on getting this library and installed composer:

```
/sites/mysite $ curl -sS https://getcomposer.org/installer | php
#!/usr/bin/env php
All settings correct for using Composer
Downloading...

Composer successfully installed to: /sites/aarp/composer.phar
Use it: php composer.phar
/sites/mysite $ sudo mv composer.phar /usr/local/

```

I added an alias for composer to my `~/.profile`. I have not been able to use any drush commands since (see below). I have since discovered that composer can be used to install drush so now I suspect this is the root of my trouble.

```
/sites/mysite $ drush en composer_manager -y
composer_manager was not found.                                                                                [warning]
The following projects provide some or all of the extensions not found:                                                                                [ok]
composer_manager
Would you like to download them? (y/n): y
cProject composer_manager (7.x-1.7) downloaded to sites/all/modules/composer_manager.                                                                                [success]
dThe following extensions will be enabled: composer_manager
Do you really want to continue? (y/n): y
composer_manager was enabled successfully.                                                                                [ok]
One or more extensions have dependencies managed by Composer.
Update packages managed by Composer? (y/n): y
Download and install the Drush Composer extension? (y/n): y
Directory /Users/mmutrux/.drush exists, but is not writable. Please check directory permissions.                                                                       [error]
Project composer (8.x-1.x-dev) could not be downloaded to /Users/mmutrux/.drush/composer.                                                                              [error]
The drush command 'composer' could not be found.                                                                                [error]
/sites/mysite $ chgrp _www /Users/m
macadmin/ mmutrux/
/sites/mysite $ chgrp _www /Users/mmutrux/.drush/
chgrp: you are not a member of group _www
/sites/mysite $ chgrp _www /Users/mmutrux/.drush/
/sites/mysite $ chmod 777 /Users/mmutrux/.drush/
chmod: Unable to change file mode on /Users/mmutrux/.drush/: Operation not permitted
/sites/mysite $ sudo chmod 777 /Users/mmutrux/.drush/
Password:
/sites/mysite $ drush en composer_manager -y
The drush command 'en composer_manager' could not be found.  Run `drush cache-clear drush` to clear the commandfile cache if you have installed new extensions.        [error]
/sites/mysite $ drush cache-clear drush
The drush command 'cache-clear drush' could not be found.  Run `drush cache-clear drush` to clear the commandfile cache if you have installed new extensions.          [error]

```

Where'd my drush go??

**Edit: added in response to comments**

```
/sites/mysite $ which drush
/opt/local/bin/drush
/sites/mysite $ drush --version
The drush command 'version' could not be found.  Run `drush cache-clear drush` to clear the commandfile cache if you have installed new extensions.                    [error]
/sites/mysite $ sudo drush --version
The drush command 'version' could not be found.  Run `drush cache-clear drush` to clear the commandfile cache if you have installed new extensions.                    [error]
/sites/mysite $ drush --version -v
Initialized Drupal 7.35-dev root directory at /sites/aarp                                                                                [notice]
Initialized Drupal site default at sites/default                                                                                [notice]
The drush command 'version' could not be found.  Run `drush cache-clear drush` to clear the commandfile cache if you have installed new extensions.                    [error]

```

# Answer
> 1 votes
I'm not sure if this will help anyone but if you do ever run into this issue:

This seemed to be a permissions issue from the beginning, so in chat we:

* Removed the old drush and composer instances.
* Installed Composer
* Downloaded Drush from Github
* Installed dependencies via Composer

Once we had a fresh copy of drush it seems that drush now worked just fine. We had some small issues that came from the machine that was being used.

# Answer
> 9 votes
Being inspired by comment by Free Radical, it works for me even without removing .composer directory:

1. `drush cc all` *outside* the Drupal root directory
2. `drush cc all` *inside* the Drupal root directory

# Answer
> 1 votes
I was bitten by the same problem after trying to install Composer Manager for D7 using this command:

```
drush en composer_manager -y

```

The installation crashed, and after that, drush responded “The drush command X could not be found” for *every* X, including `cc` and `version`.

This is what I did to get it working again:

1. Removed a directory named `.composer` that had been created in my home directory.
2. Did `drush cc all` *outside* of the Drupal root (this now works).
3. Did navigate to the Drupal root, and did `drush cc all` again (this now works).

I haven't done any testing to see if *all* these steps are necessary - just posting it in case it helps someone who wants to recover from this without reinstalling *drush*.

# Answer
> 1 votes
For me, using Drupal in a Docker image with Bowline I hit the same problem, but the `drush cc all` method didn't work, and I didn't want to trash Bowline's composer installations.

But taking the hints from above, I found that manually deleting the `./.drush/cache` directory in my project root (same level as Bowline's `bin`) fixed drush. I hope that helps someone with the same circumstances.

# Answer
> 0 votes
A one-liner approach...

```
pushd $HOME && drush cc drush && popd

```

---
Tags: 7, drush, composer
---


# Question
Title: Flex Slider issues after upgrading Drupal to v7.39
I've been researching this issue for a week to no avail. Perhaps someone has some suggestions? Upgraded a site from Drupal 7.34 to 7.39 rather seamlessly. Also updated all modules that were down level. All seemed OK. But then the flex slider just stopped displaying. I've checked all I could in the various display and definitions pages and all looks fine. I've tried different browsers and even a different server instance with on luck. I'm just hoping someone who may have experienced this anomalie can shet some light on what to look for next?

# Answer
> 1 votes
Don't know why but in the `admin/config/development/performance` section I unchecked the compress javascript option, saved the page and suddenly my flex-slider images returned. Strange though, isn't it?

Anyway - solved.

---
Tags: javascript
---


# Question
Title: How to change timezone format for user/site settings?
I want to change the user configurable timezone format on the regional settings and user settings form.

For example, it displays as `Asia/Kolkata: Friday, October 9, 2015 - 17:24 +0530` I want to display it as `Asia/Kolkata`. I have used following code but not working.

```
function my_modue_form_system_regional_settings_alter(&$form, &$form_state, $form_id) {
dpm(timezone_identifiers_list());
dpm($form);
$form['timezone']['date_default_timezone']['#options'] = timezone_identifiers_list();
}

```

Is it possible to do this?

# Answer
Yes, you're close. The problem with the above code is that it doesn't set the correct key values in `#options`; thus upon saving, the `date_default_timezone` variable will be set to some numeric key instead of an accepted PHP timezone string that is expected for the variable.

Do something like this to set the correct key:

```
function token_form_system_regional_settings_alter(&$form, &$form_state, $form_id) {
  $options = array();
  foreach(timezone_identifiers_list() as $timezone) {
    //$options[$timezone] sets the value for date_default_timezone select
    //$timezone set the display for select
    $options[$timezone] = $timezone;
  }
  $form['timezone']['date_default_timezone']['#options'] = $options;
}

```
> 1 votes

---
Tags: 7, forms, datetime
---


# Question
Title: Isotope and Views Load More error - Javascript breaks on some Ajax calls
I've created a view with Views Isotope and Views Load More contributed modules.

The objective is to have a Isitope grid that we can zoom in/out on items.

After long time to get it working I got a strange bug:

1. When I load the page it works fine.
2. When I click on load more first time the grid breaks.
3. When I click on load more second time the grid works fine.
4. When I click on load more third time the grid breaks.
5. And so on...

See it working here.

This is my javascript:

```
(function ($) {
Drupal.behaviors.skeletonthemeCustomBehavior = {

attach: function (context, settings) {

  // $grid.isotope('destroy');

  var $grid = $('#isotope-container').isotope();

  $grid.isotope({
    masonry: {
      columnWidth: 10
    }
  });

$grid.on( 'click', '.isotope-element', function() {
  if ($( this ).hasClass( 'gigante' )) {
    $( this ).toggleClass('gigante');
  } else {
    // change size of item by toggling gigante class
    $( '.isotope-element' ).removeClass( 'gigante' );
    $( this ).toggleClass('gigante');
  }
  $grid.isotope('layout');
});

$('#destroy').bind( 'click' ,function(e) {
  event.preventDefault(e);
  $grid.isotope( 'destroy' );
});

  $('.relayout').bind( 'click' ,function(e) {
    event.preventDefault(e);
    var $grid = $('#isotope-container').isotope();
    $grid.isotope({
      masonry: {
        columnWidth: 10
      }
    });
    $grid.isotope('reloadItems');
  });

  $( document ).ajaxComplete(function() {
    var $grid = $('#isotope-container').isotope();
    $grid.isotope({
      masonry: {
        columnWidth: 10
      }
    });
    $grid.isotope('reloadItems');
  });
}

};
})(jQuery);

```

# Answer
I did noticed that after the 1st load more, you can't zoom in, then after the 2nd load more zoom works, and after the 3rd load more zoom doesn't work again.

**I believe it's your code. You need to add the zoom in/out part again inside the** `ajaxComplete function`

```
(function ($) {
Drupal.behaviors.skeletonthemeCustomBehavior = {

attach: function (context, settings) {

  // $grid.isotope('destroy');

  var $grid = $('#isotope-container').isotope();

  $grid.isotope({
    masonry: {
      columnWidth: 10
    }
  });

$grid.on( 'click', '.isotope-element', function() {
  if ($( this ).hasClass( 'gigante' )) {
    $( this ).toggleClass('gigante');
  } else {
    // change size of item by toggling gigante class
    $( '.isotope-element' ).removeClass( 'gigante' );
    $( this ).toggleClass('gigante');
  }
  $grid.isotope('layout');
});

$('#destroy').bind( 'click' ,function(e) {
  event.preventDefault(e);
  $grid.isotope( 'destroy' );
});

  $('.relayout').bind( 'click' ,function(e) {
    event.preventDefault(e);
    var $grid = $('#isotope-container').isotope();
    $grid.isotope({
      masonry: {
        columnWidth: 10
      }
    });
    $grid.isotope('reloadItems');
  });

  $( document ).ajaxComplete(function() {
    var $grid = $('#isotope-container').isotope();
    $grid.isotope({
      masonry: {
        columnWidth: 10
      }
    });
    $grid.isotope('reloadItems');
    // adding the zoom in/out after ajax complete
       $grid.on( 'click', '.isotope-element', function() {
       if ($( this ).hasClass( 'gigante' )) {
       $( this ).toggleClass('gigante');
       } else {
       // change size of item by toggling gigante class
       $( '.isotope-element' ).removeClass( 'gigante' );
       $( this ).toggleClass('gigante');
       }
       $grid.isotope('layout');
       });
  });
}

};
})(jQuery);

```
> 2 votes

# Answer
It works fine for me. (your site) However if you want to prevent default behaviour you can indeed call `e.preventDefault();` You just might want to try omitting the parameter.

**new answer, now I understand the question better:**

1) Drupal has an old version of jQuery by default with enough code that breaks. An easy solution without breaking modules that depend on the old version is adding a new version og jQuery with `drupal_add_js()` and then write

```
var nQuery = $.noConflict(true); //or any name you want
nQuery('#divID').click();//and use it like the $

```

2) jQuery selectors don't work on elements that are generated (bij XHR /ajax for example) But if you use the `.on` (a delegate) it does work:

```
$(document).on('click', '.relayout', function () {
    //show big pic
});

```

3) combining those:

```
 nQuery(document).on('click', '.relayout', function () {
        //show big pic
 });

```
> 1 votes

---
Tags: views, javascript, ajax
---


# Question
Title: How to implement multiple approvals with emails?
I am currently using the Webform module, but I can't find a way to make a workflow that works for what I am trying to do.

Please let me know if I am approaching this incorrectly, or if I should be using a different module.

This is basically how I want the steps to work:

1. User fills out a Webform and submits it. (one of the fields in the form is his/her supervisor's email). The form then enters a state called "Pending"
2. The form is sent to the entered Supervisor's email.
3. If the Supervisor wants to approve it, he/she will change the state to "Approved". If he/she feels that more approval from someone higher up is required, then he/she can change the state to "More Approval" needed and then enter the email of their supervisor.
4. If the Supervisor's Supervisor likes it, then he/she can change the state to "Approved"
5. When the state is at approved, HR is notified.

Is doing something like this possible? If so, how can it be done?

# Answer
> 1 votes
Instead of using the Webform module for this, I would use a custom content type for this, with the fields similar to what your webform is using. And instead of submitting a webform, a node of this custom content type is to be created.

This content type should have these fields:

* A field to reflect the "state" (Pending or Approved, maybe also a state like "Escalated"?), say you name this field like `field_approval_status`.
* An "entity reference" field to select the Supervisor.

With the above setup, you could use the Rules module to notify the Supervisor, using a rule that is similar to the rule included in my answer to "How to send an email via a Rules action using a field key?", and which looks like so:

```
{ "rules_notify_reviewer_about_outstanding_approval" : {
    "LABEL" : "Notify reviewer about outstanding approval",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--blog" : { "bundle" : "blog" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_blog_reviewer" } }
    ],
    "DO" : [
      { "mail" : {
          "to" : "[node:field-blog-reviewer]",
          "subject" : "Blog Post waiting your approval",
          "message" : "[node:author] has submitted a new Blog post waiting your approval.\r\n\r\nYou can review it at: [node:edit-url].",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

If the supervisor then wants to forward it to another supervisor, all that's needed is to edit the node and change the selected supervisor to another one.

You may want to add some extra logic and/or permissions related to such `field_approval_status` field, i.e. to ensure that when such node is created, the author cannot set it to "Approved" right away (only to "Pending"?). That's something you could do using the Rules module (to validate/enforce that), or you might want to use the Field Permissions module for that.

**Note**:

To avoid that creating nodes is too intimidating for most users, you want to look at the Simplify module also, which helps to de-clutter forms. Here is a quote from its project page:

> Simplify allows particular fields to be hidden from the user interface. This helps to de-clutter forms and present a more user-friendly experience to content editors.

---
Tags: webforms, emails, workflows
---


# Question
Title: Multilingual redirects don't work from node url
Drupal 7, node translation method being used. Having an issue with translated content url aliases right now. Aliases work, language prefixes in urls work, but using the node/# url does not redirect to the node's alias if not in the default language. English is set to the default language.

**Example:**

English version: node/1 if being viewed goes to its alias, /alias.

French version: node/2 if being viewed does NOT go to its alias, /fr/french-alias, node is viewed correctly at node/2. If you view /fr/french-alias you see the node correctly as well. So you can view the French version of the node two ways when I really want only /fr/french-alias to work and if you go to node/2, I want it to redirect to its alias.

It's like the site is having the issue of applying the language prefix in the url to redirect with. How do I correct this?

# Answer
**tl;dr:** The Global Redirect module with the option *Language Path Checking* enabled may allow you to enforce redirects for all users.

Node translation can be quite mindboggling. Aliases are stored per language, but that language is determined by the current path language.

With English being your site's default language, if you visit `/node/2` instead of `/fr/node/2` Drupal will look up the *English* alias for `node/2`. Likewise if you visit `/fr/node/1`, you won't get redirected since Drupal is looking up the French alias (which does not exist).

The Translation Redirect module (part of the Internationalization project) solves this, but with one gotcha:

> Note that, by design, translation redirection does not work for the homepage or for authenticated users.

*(Link added by me.)*

As irritating as this may sound at first: Redirecting editors to a node's language prefix brings with it a host of problems that aren't obvious at first, but can render parts of the backend unusable.

Depending on your translation workflow you may want to consider using the Entity Translation module instead.
> 1 votes

---
Tags: i18n-l10n, path-aliases, redirection
---


# Question
Title: logging of access to images in image field
If someone hot links an image attached to a node via the image field, does Drupal add a log entry?

I was thinking along the lines of creating a mechanism where I can use images in Drupal nodes to track who reads emails, much like Mailchimp does. If I embed an image hosted by Drupal, would the log show the node as accessed, when an image from the image field was embedded in an email?

# Answer
Take a look at the Mail Tracking module.

Drupal can only register requests for public files that aren't present yet (e.g. image derivatives that have not yet been created). Otherwise the file will be served directly by the web server.
> 0 votes

---
Tags: media
---


title: Media 7.x-1 Library tab empty

text:
# Question
Title: Media 7.x-1 Library tab empty
All of the sudden my media library tab becomes empty. I check the permissions and everything seems to be fine.

# Answer
It looks like when I updated the jquery update module I checked both administrative and default version to use jquery 1.7. There is a known issue here jQuery Update 7.x-2.4 makes Media 7.x-1.4's Library tab empty. When I changed the administrative pages to use 1.5 everything was ok again.
> 9 votes

# Answer
**chane Alternate jQuery version for administrative pages**
> 1 votes

---
Tags: 7, media
---


# Question
Title: How to input internal CSS to content items with CKeditor
Sometimes I don't have time to input css in the stylesheet, so I would like to simply add it directly to the article.

Since content items don't seem to have any tags when viewing source, the tags get stripped.

How can I get this done, for example:

```
<html>
<head>
<style>

h1   {color:blue}

</style>
</head>
<body>

<h1>This is a heading</h1>

</body>
</html>

```

I have tried to add it inline, and it shows up when editing before saving, but not showing up on front end, only in back end.

# Answer
If you are using Filter HTML go to:

/admin/config/content/formats/filtered\_html

add the `<style>` tag to the limit allowed html tags

**If the above does not do it**, depending on which one you are using (filter or full html) You need to go to

/admin/config/content/ckeditor/edit/Advanced (for Filter HTML)

/admin/config/content/ckeditor/edit/Full (for Full HTML)

Then under Advanced Content Filter, select disabled.
> 1 votes

---
Tags: theming, wysiwyg
---


# Question
Title: How to fix the PDOException shown after upgrading to Drupal 7
I upgraded Drupal 6 to Drupal 7.

The following updates returned messages:

> node module
>
> Update #7006
>
> taxonomy module
>
> Update #7005
>
> search module
>
> Update #7000

***I updated the schema\_version column of the system table for module above to higher number.***

After all the pending update has finished running.

My front page website show error:

> PDOException: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'base.format' in 'field list': SELECT base.tid AS tid, base.vid AS vid, base.name AS name, base.description AS description, base.format AS format, base.weight AS weight, v.machine\_name AS vocabulary\_machine\_name FROM {taxonomy\_term\_data} base INNER JOIN {taxonomy\_vocabulary} v ON base.vid = v.vid WHERE (base.tid IN (:db\_condition\_placeholder\_0)) ; Array ( \[:db\_condition\_placeholder\_0\] =\> 6 ) in DrupalDefaultEntityController-\>load() (line 198 of /home/domains/site.com/public\_html/includes/entity.inc).

How do I fix it?

# Answer
If you manually edited the *schema\_version* column, you practically avoided Drupal would execute the necessary updates, and add the necessary fields in the database tables. That is why you get that error message.
How many updates you blocked depends on the number you set for *schema\_version*; if you set it (for example) to 8000, then you avoided Drupal would execute all the updates.

To fix it, you can only restore the values *schema\_version* had and run again update.php. This is not 100% error free: In some cases, executing the same update twice could cause an error that would stop the update process. It would be much better if you would restore the database from a backup you have from before manually editing the system table; in that way, you would be sure that executing update.php would not cause any runtime exception that would interrupt the update process.
The only alternative I see is executing the updates that were not executed, but you should have to track which updates were not executed or were executed but stopped because some error. It is also difficult because some updates need to be executed in a specific order; see `system_update_dependencies()` that defines the order for some of the updates for the System module, or `node_update_dependencies()` that does the same for the Node module. In short, you should write code similar to the one used by Drupal to update modules, adapting it to your case.
> 3 votes

---
Tags: database
---


# Question
Title: Groups audience list shows NONE in Organic Group module
In my drupal site i have implemented the Organic Group module for user group management

1. Here I have created a number of groups like grp1, grp2 ... .
2. I have a custom content type as **Opinion** that has a field **Groups audience** with FIELD TYPE **Entity Reference** so that user can able to post the content type and choose group from **GROUPS AUDIENCE** to which group the post should belong

The issue is when i am adding **Opinion** by admin dashboard the groups are showing in the list **GROUPS AUDIENCE** as grp1, grp2 ... and posted to that required group

But when the authenticated user want to post that the **GROUPS AUDIENCE** shows **NONE** , by which after posting the content it is visible in Home page but not showing the corresponding group page

I have gone through this link

Also given the full permission to the Role that assigned to the user . Any guidance will help me a lot.

Thanks

# Answer
> 0 votes
I just changed the following to get my work Admin -\> structure -\> content type -\> custom content type(i.e. Opinion) -\> manage fields -\> changed the WIDGET name to Select list of the field name having FIELD TYPE as Entity Reference

---
Tags: commerce, organic-groups
---


title: How to expose grouping in Views?

text:
# Question
Title: How to expose grouping in Views?
I have a **view**, where I **use grouping** to display publications by year. Format: HTML List -\> Settings -\> Grouping field Nr.1: Year

This is what I get:

Is there a possibility, to **expose this grouping** to the website user? So that the user can group for example by publications type or author? So the same functionality like exposing filters?

# Answer
> 0 votes
kiamlaluno gave the perfect hint. Without actually using any additional modules, you can just use tabbing for multiple views, each with different grouping. Thats how you do it:

1. Create a new view as a page
2. Page settings -\> Menu -\> Path -\> e.g. /publications
3. No Menu link

4. Add a new page to the view with the same credentials like the one above (in my case grouping by field\_year) - IMPORTANT
5. Page settings -\> Menu -\> Path -\> e.g. /publications/by-year (keep the root path)
6. Page settings -\> Menu -\> Default menu tab
7. Parent menu item -\> Default menu item

8. Add a new page to the view with different credentials (in my case grouping by field\_type)
9. Page settings -\> Menu -\> Path -\> e.g. /publications/by-type (keep the root path)
10. Page settings -\> Menu -\> Menu tab

Finally there are three pages:

In the frontend it will look like this:

I hope this steps help you a bit. In this way, you can create as many views as you like.

Thanks to the community again.

---
Tags: 7, views
---


# Question
Title: How to call different fields from different content in same view?
I have content type Say "A" and for that i want to create view, in this view i want to add a field which is from different content type say "B", reason is here in the B content type i have fee category and assigning the rent value for each category, and this node of content type is referring in a content type A with entity reference, something like this in screen shot. as of now i created view for content type A,and added the field of content type B, but the values add in the content B are not displaying in the view of content A

# Answer
To get the values of "*cage rent per day*" from B to A's view, you must add a relation in content A view with the "*Fee category*" field.

Then normally you should select in the "*cage rent per day*" field settings in view A, the relation you've just added.

However, the idea is to have some reference to content B in view A to access B's fields values. And this is possible with relations .
> 1 votes

# Answer
Relationship is what you're looking for. I found this on Google - Drupal Views relationships and entity reference
> 0 votes

---
Tags: views
---


# Question
Title: Error: Syntax error, unrecognized expression: <div id="ctools-modal">
I want to display a form in CTool modal dialog, but failing badly.

When I click link to show modal form, ajax request is started:

POST http://drupal.dev/my\_mod/arg1/ajax/arg3

and returns:

```
Error: Syntax error, unrecognized expression: <div id="ctools-modal">
<div class="ctools-modal-dialog">      <div class="modal-content">
<div class="modal-header">          <button type="button"
class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 id="modal-title" class="modal-title"> </h4>        </div>
<div id="modal-content" class="modal-body">        </div>      </div>
</div>  </div>

```

I tried to click different link, but gets an error:

> TypeError: Drupal.CTools.Modal.modal is undefined

Code:

```
function my_mod_menu() {
  return array(
    'my_mod/%/%ctools_js/%' => array(
      'title' => 'Entity Modal Edit',
      'page arguments' => array(1,3),
      'page callback' => 'my_mod_modal_page_callback',
      'access callback' => 'my_mod_modal_access_callback',
      'access arguments' => array(1,2,3),
      'type' => MENU_CALLBACK,
    ),
  );
}

function my_mod_modal_page_callback($entity_type, $id) {
  ctools_include('modal');
  ctools_include('ajax');
  ctools_modal_add_js();

  $form_state['user'] = user_load($id);
  $output = ctools_modal_form_wrapper('my_mod_form', $form_state);
  ctools_modal_render('Edit', $output);
  exit;
}

```

I'm creating my edit link in custom views\_field\_handler:

```
class my_mod_handler_field_links extends views_handler_field {

  function init(&$view, &$options) {
    parent::init($view, $options);

    if (! isset(self::$some_property)) {
      ctools_include('modal');
      ctools_include('ajax');
      ctools_modal_add_js
    }
  }

  function render($values) {

    $edit_link = array(
      'href' => 'my_mod_ctools/some_value1/nojs/some_other_value',
      'title' => t('edit'),
      'attributes' => array('class' => array('mymod-ctools-links', 'ctools-use-modal', 'use-ajax')),
    );

    $links[] = $edit_link;

    $build = array(
      '#prefix' => '<div class="mymod-ctools-links-wrapper">',
      '#suffix' => '</div>',
      '#theme' => 'links',
      '#links' => $links,
    return drupal_render($build);
  }

  function query() {}

}

```

# Answer
> 1 votes
I had using jQuery 1.9. I changed it to 2.1 and the problem is solved (jquery\_update module)

---
Tags: 7, views, ajax, chaos-tool-suite
---


# Question
Title: How to display an individual list of user created nodes?
I'm having a block on the front page with a list of users displaying their profile fields like: picture, full name, e-mail etc. I achieved this by simply creating a User View in Views displaying it as a block.

Now I want to add an extra option to it that gives a list of the user's created node articles. So that their articles (per user) will be visible as a list and displayed like the profile fields.

I've tried several ways but all to no avail. The following approaches got me close:

* Made a relationship "User: Representative node" and added a Node Title field to the View with this relationship. The way this relationship works is what I actually want, I think. The thing is: it obtains a SINGLE representative node for each user but I want to obtain ALL the nodes for each user.
* Made a seperate user View (block) with relationship "User: Content authored" and contextual filter "Content: Author uid". Having the Node Title as a field again. I tinkered a bit with the contextual filter and setting it with "User ID from logged in user" gets me a nice list of nodes of the logged in user. But that's not what I want, I want to show all content of each user separately. Providing a default value "User ID from URL" gives me nothing. Probably because the block is on the frontpage.

Can anybody tell me what's the solution, or just give some ideas? I'm on it for days now and I'm out of ideas.

# Answer
The simple "non-coding" version would be:

1. install Views Field View module
2. create a separate node view with a contextual filter that filters by node author
3. in your first/initial view, add the "uid" as a hidden field
4. in the same first/initial view, add a "views field" that is displaying the view created at point 2
5. in this "views filed" settings add the uid field as an argument
> 2 votes

---
Tags: users, views
---


title: How to show comments in teaser?

text:
# Question
Title: How to show comments in teaser?
As the title says, I'm looking for a way to show the node comments in teaser. Anybody knows how to do?

# Answer
You can use the EVA module, it provides a Views display plugin that allows the output of a View to be attached to the content of any Drupal entity, in your case the teaser.

"Entity Views Attach: Use Views Almost Anywhere" contains a great tutorial about it.
> 1 votes

---
Tags: comments, 7, nodes
---


# Question
Title: How to create an "All" link in a taxonomy menu (block)?
I have a taxonomy vocabulary and terms as follow:

Food:
-Meat
-Veggies
-Fruit
-Dairy

I want to create a menu of taxonomy terms that look like this:

-All
-Meat
-Veggies
-Fruit
-Dairy

... when you are on the "Food" page.

I have tried the Taxonomy Menu and Taxonomy Menu Block modules, but none give me the option to have an "All" link. That's a bit daft innit?

How can you show the user posts/nodes of all terms?

Any other solutions?

# Answer
> 0 votes
My opinion:

You can create a new term called `all` and add it to all your related nodes.

Or, You may use Views to create a page to show all nodes, and add that to your menu.

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


# Question
Title: How to create a query about users in a Drupal Commons group including their location (State)?
I need to create a MySQL query that will allow me to view the users in a specific Drupal Commons group and include their USA State location. I would like to be able to export this to a CSV file.

Any help with this would be appreciated.

# Answer
To create such query (and report) you may want to look at the Forena module. You would use its report writing features (such as its WYSIWYG report writer and/or it's query builder) to first create a report that fits your needs. The result of it could be a tabular output and/or graph. After the report content matches the specifications, you could save it as (e.g.) a CSV file.

Here is a quote from one of the Forena community docu pages, i.e. Reasons for considering Forena:

> Reports created by Forena (combined with SVGGraph and mPDF) can be saved (exported) as PDF documents with embedded graphs. Other supported formats for saving a report are CSV, XLS, DOC, HTML, etc.

# Similar samples

1. Refer to this online example in the Forena demo site for a report that is fairly similar to the kind of (tabular) report you could (easily) create:

* Using Forena's **Query builder** you would create the required SQL statement (if you'd rather want to write the SQL with your favorite SQL editor that's another option).
    * Using forena's **WYSIWYG report writer** you would develop your custom report (if you'd rather want to write that report with your favorite XHTML editor that's another option).

Some more details about the sample report mentioned above:

* Use the "Parameters" pulldown option, to select any other state.
    * Note the **PDF** hyperlink: using that link, you'll get a PDF version of that report. When creating such report, you could as well ask for other (or additional) report export formats, one of them is **CSV** (or XLS, DOC, HTML, ...). This is how the CSV equivalent version of that sample report looks like.
2. The Master Summary with drill down sample report demonstrates how you can also "link" various reports together (while it also shows some of the charting features of Forena). Click on either any of those bars in the chart, or on the total-hyperlink in tabular report below the chart. Doing so will bring you to the report "for the selected state" (= the first sample report mentioned above).

# Direct access to data blocks

All *data blocks* are accessible directly via their url also, provided you have permission to access that block. Here are a few samples of that, for the sample report located at `/reports/sample.states`:

# More info about supported export formats

Refer to my answer to "How to add a link to the CSV download to my module page, for a report created with Forena?" for more details about supported export formats.

# Video tutorials

The Forena Video demos and tutorials contain quite some links to live demos. They should help a lot to get you started.

Disclosure: I'm a co-maintainer of Forena.
> 1 votes

---
Tags: users, 7
---


# Question
Title: Filter between first and last day of the current month in any year
I have a date field in my view and when I try to filter between the *first* and the *last* day of the month there is no result in my view preview.

Here is my settings. This filter is because I need to compare the *born date* from all the registered users and print only those who have the value between first and last day of the month.

Here are the screen shoots of my views settings:

**First here is my date field settings:**

**Then the filter settings:**

And finally set the filter option to get the result between first and last day of the month:

This is what I've tried till now without success. Can someone help me in this? I don't want to use a module for this. I only need this filter works.

# Answer
> 3 votes
I had a similar requirement a while ago. What I did was to create a small module with a hook\_views\_query\_alter(). You need to write a bit of code, but I think is more elegant and easier to maintain than adding PHP code inside contextual filters in the views UI.

Try the following:

In your .module file

```
function MODULE_views_api() {
  return array(
    'api' => 3,
  );
}

```

In module.views.inc

```
//make sure you use your date field table and field name bellow
function MODULE_views_query_alter(&$view, &$query) {
    if ($view->name == 'date_test') { // replace this with your view name

        //this line removes the year from your date field
        $formula = "DATE_FORMAT(field_data_field_date.field_date_value, '%m-%d')";

        //join the field table
        $join = new views_join();
        $join->table = 'field_data_field_date';
        $join->field = 'entity_id';
        $join->left_table = 'node';
        $join->left_field = 'nid';
        $join->type = 'left';

        //add the join the the view query
        $query->add_relationship('field_data_field_date', $join, 'node');

        $first = date('m-d', strtotime('first day of this month'));
        $last = date('m-d', strtotime('last day of this month'));

        //add the field without the year
        $query->add_field(NULL, $formula, 'date_no_year');

        //add the where clauses
        $query->add_where(0, "$formula >= '$first'", array(), 'formula');
        $query->add_where(0, "$formula <= '$last'", array(), 'formula');
    }
}

```

# Answer
> 4 votes
Long story short: Use Views Partial Date. The image below demos some of its features (click the image if you don't see the animation).

**Why it can't be done with Views**

Views by itself can only handle Unix timestamps. Even when a relative date is used, Views' date filter uses strotime() internally to convert the relative date to a timestamp before adding the filter condition to the query.

**Why it can't be done with Date Views**

Date Views is a complex beast that provides a multitude of features surrounding date calculations, including support for multiple DB backends.
Theoretically Date Views could implement incomplete dates, but since it also supports relative dates and various input widgets (like Date Popup), the additional validation and logic would be extremely hard to maintain.

**What we can do about it**

At this point we've established that either an additional module or custom code of some form is required.
With that in mind I created Views Partial Date and will be expanding this answer in the following days to describe the approach I took.

# Answer
> 1 votes
Ok try this.

1. Add contextual filter "node id"
2. allow multiple values
3. add this php code as default value, when no filter value is in url:

---

```
$results = db_query("SELECT entity_id FROM field_data_field_FIELDNAME
WHERE DATE_FORMAT(field_FIELDNAME_value,'%m') = DATE_FORMAT(NOW(),'%m')
AND entity_type = 'node' AND bundle = 'NODE_TYPE'");
$ids = array();
foreach ($results as $result) {
  $ids[] = $result->entity_id;
}
return implode(',',$ids);

```

Related to this.

# Answer
> 1 votes
This article will help you (which is on drupal.org as well). Once you are configured with this, you will be able to filter the content between exactly two dates.

So you need to add a default start date as 1st of particular of month and end date as nextmonth - 1.

This needs to be done through default views settings or one can add small javascript which added default value to that particular fields.

# Answer
> 0 votes
Try these two options:

> first day of this month
>
> last day of this month

Putting those values into this strtotime() tester provides the appropriate dates.

# Answer
> 0 votes
The SQL syntax that you want to achieve is relatively straightforward using the SQL MONTH() function:

```
SELECT *
FROM field_data_field_fecha_nacimiento
WHERE MONTH(field_fecha_nacimiento_value) = 8; // August

```

However, there is no way for Views to create that kind of SQL expression without some kind of additional module.

# Answer
> 0 votes
I haven't tested this, but wouldn't it work if you choose "month" as granularity and then use a single date (the relative "now", or a specific date) as filter value?

# Answer
> 0 votes
why are you making them to write custom modules for this ?

This is **pretty simple** for: `First day of current month you need to add` "**first day of**" & `for Last day of current month same way` "**last day of**"

Read the documentation from PHP.NET carefully.

Here I am attaching screenshot of my view's date filter for relative dates.

---
Tags: entities, views, datetime
---


# Question
Title: How to fix the fatal error due to cached data while migrating?
I was trying to migrate my site from one computer to another. I have imported .sql file from database from my first database (unfortunately forgot to clear cache) and created a new database in the second and exported the data. Then i have tried to point the settings.php's database array to the newly created database in the second computer but when i tried to access the page, i get a white screen with the following error

> Fatal error: require\_once(): Failed opening required '/var/www/html/sites/pullup.local/modules/remote\_stream\_wrapper/remote\_stream\_wrapper.inc' (include\_path='.:/usr/share/php:/usr/share/pear') in /var/www/html/includes/bootstrap.inc on line 3186

Where **sites/pullup.local** was my site folder in the first computer which is not present here. Then i tried to remove all the entries in the database starting with "cache". Even after clearing all the entries in the cache tables i am getting same error and I am not understanding that from where old folder path coming.

I also tried to remove the database entry from settings.php then it is working normal as the web installation page coming up. So I think something caches the old folder in the database (DRUPAL\_ROOT variable value is cached).

How can I fix the problem?

# Answer
> 0 votes
Drupal uses code registry to load the files containing a class or an interface. While the code registry is cached in cache\_bootstrap, it is contained in the *registry* and *registry\_file* database tables.

To rebuild it, I would edit those database tables to change the path shown in the *filename* row to match the new site's path. Other methods that require bootstrapping Drupal would probably not work, since any class Drupal would use would not be found, causing a PHP exception, and stopping the bootstrap, with the effect that Drupal would not run the necessary code.

---
Tags: 7, caching, migrations
---


# Question
Title: Is it possible to redirect users when page caching is enabled?
I use simple redirect user inside `template.php` with the following code:

```
if ( isset($_GET['abc']) && $_GET['abc'] == 1 ) {
  drupal_goto('mypage');
}

```

Is it possible to redirect to the page even with caching turned on? It seems that if the page that I want to redirect from is already cached, the template.php file does not fire.

# Answer
Usually no. Not like that.

Caching systems are created to serve content with as minimal as possible PHP execution. If you use varnish, nginx or similar cache, or Boost module, you ay even not have any PHP executed at all. And even if some parts of PHP are executed, theming layer is usually omitted, because logic shouldn't be there - and if logic shouldn't be there, then that's exactly the part that is (or should be) safe to cache.

So first, try to move logic from template to some module, and second - learn about the caching system you are using, and how to add exceptions to it (if just moving the logic does not fix it for you already).
> 0 votes

---
Tags: 6, caching
---


title: Load a panels display in code

text:
# Question
Title: Load a panels display in code
To load a Panel display from the database we can use `panels_load_display($did)`

However, the `$did` value is an autoincrement value from the database. It is not present in exported Panel page displays (e.g features export).

I thought perhaps we could use `ctools_export_object_load` to load the exported panels display.

However, I found that it only returns a result if the display is in the `panels_display` table in the database, and returns empty empty for exported code storage displays.

e.g:

```
// Attempt to load Panels display
ctools_include('export');
$uuid = '49c15c71-d5d1-d574-b539-0149f912f925';
$display  = ctools_export_load_object('panels_display', 'conditions', array('uuid' => $uuid ));
var_export($display); // empty array if not in DB.

```

How can we load a Panel display in code when that display is exported in features and using code-based storage?

# Answer
After trying various approaches such as:

```
$page = ctools_export_load_object('page_manager_pages', 'names', array('app'));
var_export($page);
// And also
$handler = ctools_export_load_object('page_manager_handlers', 'names', array('page_app__panel_context_7d7ea5ec-d257-43aa-bfe6-a0c25623111d'));
var_export($handler);

```

I found I couldn't reliably load the panel display when it was in both code and stored in the db.

Maybe there's another way but in the maze of ctools, panels and page manager, I ended up with a simpler solution.

**Minipanels**!

Compared to page displays, it's much easier to load and render minipanels programmatically:

```
$minipanel_name = 'minipanel_machine_name';
// This loads the minipanel, both from DB or from code export.
$minipanel = panels_mini_load($minipanel_name);
// Render the minipanel display
if (empty($minipanel) || empty($minipanel->display)) {
  watchdog('module', 'Unable to load minipanel: !name', array('!name' => $minipanel_name));
}else if (!empty($minipanel->display)) {
  $display = $minipanel->display;
  // Pass data as dynamic args to panel display
  // This is optional, but used for this case.
  $display->args = array('data' => $data);
  $output = panels_render_display($display);
}

```
> 1 votes

# Answer
The relationship between tables and their exported datasets is declared via the `export` key in a table's schema definition. We can see that key both for `page_manager_pages` and `panels_display`.

ctools also allows the definition of a default hook. If non was provided it will fall back to `default_{table}`.

When loading a ctools exportable via `ctools_export_load_object()` ctools will first query the table for objects, then invoke the default hook to retrieve any objects stored in code.

When page manager pages are exported, `panels_display` objects are not declared separately under their own hook, but are wrapped in `hook_default_page_manager_pages()`.
In order to retrieve them by their UUID they would have to be declared within `hook_default_panels_display()`.
> 1 votes

---
Tags: 7, panels, chaos-tool-suite
---


# Question
Title: Drupal 8 Installation Is Just Plain HTML
I just installed Drupal 8 in a subdirectory. I pushed all of the files to the directory, I installed Drupal with a minimal setup and and edited my .htaccess file to make Drupal work with my subdirectory. Now, it displays my website, but without any CSS or Javascript. It's just plain HTML text. How can I fix this problem?

# Answer
> 1 votes
Wow. I just solved the problem. I didn't realize that by default on a Minimal installation that the Stark theme, which is simply a plain HTML theme, was enabled by default. I switched the theme and now it works fine.

---
Tags: 8, installation
---


# Question
Title: How to share a D8 configuration without the UUID limitation?
How can I share a Drupal 8 configuration (content type, custom view/menu/block, etc.) with another website without the UUID limitation?

Each site has a unique UUID, and refuses to work with the configuration file of another website. It's a big problem that doesn't allow users to share their configuration with the world.

# Answer
> 2 votes
The best way is to use the features module which is pretty stable and useful. You can even bundle specific configs and install them later on any website as a module (thus not needing to install the module there).

# Answer
> 0 votes
The Configuration Development module allows you to export configuration that can be shared/re-installed by stripping out the UUID for you. Unlike features, you have to manually manage the config you want to export by listing them in your module info yml file.

---
Tags: 8
---


# Question
Title: Is there a way to run a shell script on a custom cron?
I'm new to all this so maybe this isn't the best solution, but I've created a shell script cache warmer.

```
wget --quiet http://www.example.com/custom-sitemap.xml --output-document - |
egrep -o "http://www.example.com/[^<]+" | wget --delete-after -i -

```

I can also do this with drush commands too using the cache warmer module.

I need to figure out how to run these commands every couple of hours.

My understanding was that I could create a custom cron job with Elysia cron that ran the script on my server, but now I am confused if this is possible / how to implement.

When I go to the script section and write the following:

```
*/15 * * * * custom_cron

```

I am told it it is an invalid line.

Can you make custom timed cron jobs then use the elysia cron API to make a module call my shell script?

Thanks!

# Answer
> 1 votes
I believe you can edit the crontab or by talking to hosting provider you will be able to edit the crontab file.

In case, if you have to do it in custom module using Elysia Cron API, I assume you can do it following way :

```
function example_cronapi($op, $job = NULL) {
  $items['example_shell_cron'] = array(
    'description' => 'Send mail with news',
    'rule' => '0 */4 * * *', // Every 4 hours
  );
  return $items;
}

function example_shell_cron() {
  shell_exec ('wget --quiet http://www.example.com/custom-sitemap.xml --output-document - |
egrep -o "http://www.example.com/[^<]+" | wget --delete-after -i -');
}

```

# Answer
> 1 votes
The documentation under Linux for crontab is found in a manual page:

```
man 5 crontab

```

The `5` is important to indicate the section you want to see (section 1 shows you the command line documentation.)

Cron runs from `/` in most cases, so it won't find a script as you specified it. You have two solutions: make sure it can run from a specific user, which should be the case for root, or place the script somewhere under /var/... or /etc/... Then change the crontab script to use a full path:

```
*/15 * * * * /home/my_user_name/custom_cron

```

Using crontab you can also defined variables. Also remember that you do not have the full environment loaded. Your script needs to do that if you need a full environment.

Another way, assuming you don't need to run it every 15 minutes, is to place the script under a cron directory in /etc. In my case I use cron.hourly.

This means no setup in crontab, just copy the script under that directory, probably with a filename that makes sense such as:

```
/etc/cron.hourly/drupal.sh

```

That .sh file must be executable (have the `x` flag set) as in `chmod 755 /etc/cron.hourly/drupal.sh`.

---
Tags: 7, caching, cron
---


# Question
Title: Allow non-members of an OG to post group content
I'm building a website with the use of Organic Groups module. I need to allow all registered users (not only group members) to have permission to post nodes of a certain content type to any group. However I failed to achieve this behaviour as well as finding helpful info online. Can anyone please advise me on how to make this? Are any additional modules needed?

# Answer
You need the OG permissions overview menu (`admin/config/group/permissions`). You can find there permissions to let non-members post content.
> 0 votes

---
Tags: organic-groups, users
---


# Question
Title: drupal jquery mobile datepicker cannot select year
I'm using drupal 7 with jquery.mobile-1.4.5.

I had created a form with date field, using Inline Datepicker

```
  $form['body']['dob'] = array(
    '#type' => 'textfield',
    '#title' => 'Date of Birth',
    '#attributes' => array('data-role'=>'date', 'id'=>'dob'),
  );

```

The Inline Datepicker is showing exactly like the demo in http://demos.jquerymobile.com/1.4.1/datepicker/

However, I would like to have a inline datepicker, with a dropdown menu for user to select year in calendar. Eg: https://jqueryui.com/datepicker/#dropdown-month-year

I had tried adding in below function but it doesn't work.

```
$(function() {
    $( "#dob" ).datepicker({
      changeMonth: true,
      changeYear: true
    });
  });

```

Is there any way I can allow user select year in the inline datepicker?

# Answer
> 0 votes
You can use Date module which has several options regarding to your requirement. You can use date functionalities in your custom form.

For example,

```
$form['body']['dob'] = array(
  '#type' => 'date',
  '#title' => 'Date of Birth',
);

```

will have options to select date, month and year.

If `#type => 'date_popup'`, it will popup with calendar which allows user to select date.

Check this link for more info date example

---
Tags: 7
---


# Question
Title: How do I run drush migrate for specific path site
I want to use drush to run the migrate command to upgrade my drupal version 6 to 7 using Data Export Import module.

I have two site in different path.

**How do I run drush migrate for the Testing website below.** Drupal version is 6.

> Main website
>
> /domains/site.com/public\_html
>
> Testing website
>
> /domains/site.com/public\_html/testsite

# Answer
> 1 votes
To use Drush to more effectively migrate sites from one VPS to another, to manage more than one site and to synchronize easily between them. It assumes that you are running your own cloud server, have Drush on it, and have already installed a Drupal site.

**Drush Aliases**

Drush aliases are a simple set of configuration that allows you to reference Drupal sites from anywhere in your server's folder structure by using a shortcut of the following format @site. Before being able to use these shortcuts though, you'll need to configure the respective alias. To do this, and if you don't have one already, create a file called aliases.drushrc.php in the .drush folder that resides in your server's root folder:

```
nano /root/.drush/aliases.drushrc.php

```

Here, you have to create a php opening tag, `<?php`, for the file and below copy the following array declaration:

```
$aliases['site1'] = array(
 'root' => '/var/www/drupal_folder',
 'uri' => '88.88.88.88/drupal_folder',
);

```

Save the file, exit, and the alias is set. To test it out, navigate to a folder that is outside of your Drupal site and run the following command:

```
drush @site1 status

```

Now you should get the regular status information about the site you just referenced in the alias. And you can use this shortcut also with other commands.

**Migrating sites**

Now that you know how to reference sites, we can look at migrating (copying) a site from one folder to another using Drush. Let's say you want to move @site1 from /var/www/drupal\_folder to /var/www/drupal\_folder2.

First, you need to create a new alias for this future installation. For this, like always, edit the aliases.drushrc.php file:

```
nano /root/.drush/aliases.drushrc.php

```

Here, you need to create below two aliases, both with the same format. Just copy-paste the old one and make the appropriate changes:

```
$aliases['site2'] = array(
 'root' => '/var/www/drupal_folder2',
 'uri' => '88.88.88.88/drupal_folder2',
 );

```

Save the file and exit. If you run drush @site2 status, it will not work because obviously the folder not only does not contain a Drupal installation, but it doesn't even exist. So let's create it:

```
mkdir /var/www/drupal_folder2

```

In order to prepare for the new Drupal installation, you'll need to create a new database as well. So login to your MySQL through your preferred way and create a new database, making a note of the access username and password. If you are unsure how to do this, read the tutorial that shows how to deploy a Drupal site with Drush.

Now that your database is set up, you can proceed to migrate the site. To copy all the codebase from the first folder to the other, run the following command:

```
drush core-rsync @site1 @site2 --include-conf

```

Now, edit this newly copied settings.php file in the drupal\_folder2 copy and change the database information to reflect the new database you just created.

```
nano /var/www/drupal_folder2/sites/default/settings.php

```

In this file, you need to make changes to the following block of code to reflect your own database information:

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'your_db',
      'username' => 'your_username',
      'password' => 'your_password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

```

Save the file and exit. Now you can also migrate the database using Drush because it knows that the site in the drupal\_folder2 now uses this database, even if it's currently empty. All you need to do is run the following command:

```
drush sql-sync @site1 @site2 --create-db

```

This will drop the tables in the database associated with **@site2** (the one that is currently empty) due to the --create-db option and insert the ones from the database associated with **@site1** \- your original Drupal installation. So now you have 2 exact replicas of the same site.

You may run into the following error message (with the applicable credentials):

```
ERROR 1044 (42000) at line 1: Access denied for user 'your_username'@'localhost' to database 'your_db'

```

If this is the case, make sure that your user has the required privileges.

Log into MySQL `(mysql -u root -p).`

Grant the following privileges:

```
grant all privileges on your_db.* to your_username@localhost with grant option;
grant reload  on *.* to druser2@localhost;
flush privileges;

```

**Synchronizing Drupal Sites**

Now that you have a duplicate of your original site (@site2), you can use it for development work. If you make codebase modifications to it, you can use the core-rsync command to sync the files with the original (@site1):

```
drush core-rsync @site2 @site1

```

Obviously, you would not want to copy the settings.php file again, which prevents making database changes again. Next, to sync the database as well, run the same sql-sync command:

```
drush sql-sync @site2 @site1 --create-db

```

In most cases, it's recommended that the receiving database is emptied before the copy (using the --create-db option) to avoid conflicting configuration saved in the database that will then cause problems.

**Remote sites**

```
nano /root/.drush/aliases.drushrc.php

```

And let's create a new alias for a site on a remote server. Copy the following code below and replace appropriately with your information:

```
$aliases['site3'] = array(
   'root' => '/var/www/drupal_folder3',
   'uri' => '99.99.99.99/drupal_folder3',
   'remote-host' => '99.99.99.99'
 );

```

So, what does this mean? The site with the alias @site3 is located in the folder drupal\_folder3 on the remote server and has that URI pointing to it on the remote server. This is to be expected. Additionally, you have to specify the remote host (which is the IP address of the remote host). Given that you have set up SSH keys, you will not be required to enter a password unless of course you have a password protecting your private SSH key itself, which I recommend if you are creating keys between two remote hosts (none being your personal computer).

And that's it. Now when you run the commands we've be talking about, you can perform the same actions remotely, as well as migrating and keeping sites synchronized. But just to test out the alias, run:

```
drush @site3 status

```

---
Tags: drush
---


title: How can I enable clean URLs?

text:
# Question
Title: How can I enable clean URLs?
I installed Drupal 7 on Wamp Server. I can't find any checkbox or link to enable clean URLs; I see only the *Run the Clean URL Test* button.

How can I enable clean URLs?

# Answer
The settings for the clean URLs are at admin/config/search/clean-urls.
That page shows the "Enable clean URLs" checkbox only when it is possible to enable them; when the server is not configured to support them, that page shows the following message:

> Clean URLs cannot be enabled. If you are directed to this page or to a *Page not found (404)* error after testing for clean URLs, see the online handbook.

On an Apache server, and with the default settings used from Drupal, clean URLs work if:

* The mod\_rewrite module is enabled for the server
* The following directives are present in the Apache configuration file

```
AllowOverride All
AccessFileName .htaccess

```
> 13 votes

# Answer
Enable the `mod_rewrite` module then restart the wampserver.

I think you can enable the `mod_rewrite` from the quick launch icon. Right click and view open the apache modules menu and make sure the `mod_rewrite` is enabled.

**UPDATE:**

Open the file `httpd.conf` inside apache installation folder and edit the following line:

```
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
#   Options FileInfo AuthConfig Limit
#
AllowOverride None

```

To be:

```
AllowOverride All

```
> 7 votes

# Answer
How I solved my problem:

Clean URLS:

1. Enable the `mod_rewrite` with this command:

```
a2enmod rewrite

```
2. Then under /etc/apache2/sites-available edit the “default” file and replace `Override None` with `Override All`. This needs to be changed twice.
3. Restart Apache
> 4 votes

# Answer
Please enable rewrite\_module for apache using wampserver interface.

To access it click on the green "w" icon in systray, go to apache \> apache modules \> click on rewrite\_module.

your wampserver icon should turn red and then orange and green. If not try restarting wampserver. When the icon is green visit the apache modules again and ensure that rewrite\_module is checked.

enabling rewrite\_module is essentially turning on mod\_rewrite, but dont know why wampserver calls it so. Hopefully it solves your issue with clean urls, you can verify its fixed by running the test again.
> 3 votes

# Answer
For cleaning URL open **Terminal** -\> Type the command **vim /etc/apache2/sites-enabled/000-default**

It would open the 000-default file there you would see

```
<VirtualHost *:80>
ServerAdmin webmaster@localhost

DocumentRoot /var/www
<Directory />
    Options FollowSymLinks
    AllowOverride none
</Directory>
<Directory /var/www/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
</Directory>

ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory "/usr/lib/cgi-bin">
    AllowOverride None
    Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
    Order allow,deny
    Allow from all
</Directory>

ErrorLog ${APACHE_LOG_DIR}/error.log

# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn

CustomLog ${APACHE_LOG_DIR}/access.log combined

Alias /doc/ "/usr/share/doc/"
<Directory "/usr/share/doc/">
    Options Indexes MultiViews FollowSymLinks
    AllowOverride None
    Order deny,allow
    Deny from all
    Allow from 127.0.0.0/255.0.0.0 ::1/128
</Directory>

</VirtualHost>

```

So select the entire code and put this in place of the code in 000-default file.

```
<VirtualHost *:80>
ServerAdmin webmaster@localhost

DocumentRoot /var/www
<Directory />
    Options FollowSymLinks
    AllowOverride All
</Directory>
<Directory /var/www/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
</Directory>

ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory "/usr/lib/cgi-bin">
    AllowOverride None
    Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
    Order allow,deny
    Allow from all
</Directory>

ErrorLog ${APACHE_LOG_DIR}/error.log

# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn

CustomLog ${APACHE_LOG_DIR}/access.log combined

Alias /doc/ "/usr/share/doc/"
<Directory "/usr/share/doc/">
    Options Indexes MultiViews FollowSymLinks
    AllowOverride None
    Order deny,allow
    Deny from all
    Allow from 127.0.0.0/255.0.0.0 ::1/128
</Directory>

</VirtualHost>

```

Now restart the aparche server using

```
sudo service apache2 restart

```
> 1 votes

# Answer
You can use this by `.htaccess` file

First find this line of code in `.htaccess` file

```
#RewriteBase /

```

and replace it with following line of code:

```
RewriteBase /~yoursitename/yoursitename

```

Remove `#` from the code. Here `yoursitename` is the folder name after domain name like `example.com/~yoursitename/yoursitename`.
> 1 votes

# Answer
We need to uncomment or add the line:

```
LoadModule rewrite_module modules/mod_rewrite.so

```

to enable `mod_rewrite` Apache module.
> 0 votes

---
Tags: 7, uri
---


# Question
Title: How to add different field values in views?
I have two contents *A* and *B*. I have created a view for A, I need a one of field value from *B* in my *A view*.

I have referred some tutorials, they are suggesting relationship by using entity reference field.

Actually in my content *B* there is no any *entity reference* fields. In content *B* I have only two fields one is *title* and other one is *plain text*. How can I overcome this? Thanks in advance.

# Answer
> 0 votes
create a block view of content B By overiding fields and render a content of block in A's view page.

# Answer
> 0 votes
Field of content B is displaying in the field list of view, after finding that you can easily add in the view. You can select the filter option of content type too.

---
Tags: views, entities
---


title: Lat/long gets reset after updating

text:
# Question
Title: Lat/long gets reset after updating
At the moment I'm having some struggles with the location module in Drupal, well I'm not really sure that it's the location module that is causing the problems.

The best I can explain it with a little code. There is a module which connects to a backoffice and gets venues with lat / longitudes.

I do the following:

```
    dpm($node->field_address[LANGUAGE_NONE][0]);
    node_save($node);
    dpm($node->field_address[LANGUAGE_NONE][0]);

```

Before updating the node the values are in the object

```
    array(6) {
      ["street"]=>
      string(16) "Street 1"
      ["city"]=>
      string(7) "Middle earth"
      ["postal_code"]=>
      string(7) "12345"
      ["latitude"]=>
      string(8) "52.000"
      ["longitude"]=>
      string(7) "4.000"
      ["location_settings"]=>
      array(1) {
        ["form"]=>
        array(1) {
          ["fields"]=>
          array(2) {
            ["latitude"]=>
            array(1) {
              ["default"]=>
              string(8) "52.000"
            }
            ["longitude"]=>
            array(1) {
              ["default"]=>
              string(7) "4.000"
            }
          }
        }
      }
    }

```

After saving the node the lat / long is reset to int(0). The lat / long in the location settings is still in tact.

I've search a long time to debug this, i was thinking maybe there's a hook that resets the value, but I just can't find it. I'm fairly new to Drupal so any help will be appreciated :)

Thanks!

# Answer
Found the solution.

The lat/long came from a different source and when the location module tried updating the lat/long I got NULL/NULL, because I was on the max amount of requests to google.

Solution was to set the 'source' column in the location table to 1, so the module thinks the value is overruled by the user. The lat/long doesn't get updated / reset to null anymore.
> 1 votes

---
Tags: 7, location
---


title: alter password reset url

text:
# Question
Title: alter password reset url
I'm trying to alter the password reset link (user/password) to my own language specific URL, but I can't find how I can do this.

How can I change it?

# Answer
Drupal has different way to understand which language should be used to show the current page. By default, Drupal shows the pages in the language set in admin/config/regional/language; other detection methods are disabled. (See the settings on admin/config/regional/language/configure.)

>

If you want to use a different language, and since you are asking for a page that is normally used from anonymous users, you would need to enable the *Browser* method that will select the language for the pages basing on the browser settings and the HTTP headers the browser uses when seeing a page.
The *Session* method uses a session variable (which means the user already visited one of the pages on your site), or a request parameter; it could be the right method if you know the user already visited your site at least one, with cookies enabled for your site.
> 0 votes

# Answer
Render **user\_pass** form in your custom url. **drupal\_render(drupal\_get\_form('user\_pass'));**

OR

In template.php

```
function mymodule_theme(){
// custom user-password.tpl.php
    $items['user_pass'] = array(
        'arguments' => array('form' => NULL),
        'render element' => 'form',
        'template' => 'templates/user-pass',
    );
    return $items;
}

```

In user-pass.tpl.php:

```
php global $base_url;

div class="forgotPassword"

# Forgot Password

php
    print drupal_render($form['form_build_id']);
    print drupal_render($form['form_id']);
    print drupal_render($form['name']);
    print drupal_render($form['actions']);
?
/div

```
> 0 votes

---
Tags: 7, users
---


# Question
Title: How to create more than 1 block with different .tpl (theme) file in a single module?
How to create more than one block with different **`.tpl`** (theme) file in single module in Drupal 7?

Suppose I have a module name **mymodule**, I want to create two blocks in this module name as **myblock1** and **myblock2** and these two block should be associated with different tpl file like `block1.tpl.php` and `block2.tpl.php.` and both blocks have **same content**.

Any help?

# Answer
> 2 votes
Block code from custom template is here

```
 /**
 * Implements hook_theme().
 */
function my_custom_block_theme() {

    $theme = array();

    $theme = array(
        'my_custom_block_output' => array(
            'variables' => array('items' => array()),
            'path' => drupal_get_path('module', 'my_custom_block') . '/templates',
            'template' => 'block--my-custom-block'
        ),
        'my_custom_header_block_output' => array(
            'variables' => array('items' => array()),
            'path' => drupal_get_path('module', 'my_custom_block') . '/templates',
            'template' => 'block--my-custom-header-block'
        ),
);

    return $theme;
}

/**
 * Implements hook_block_info().
 */
function my_custom_block_block_info() {

    $blocks['my_custom_block_output_block'] = array(
        'info' => t('Custom one'),
        'cache' => DRUPAL_CACHE_PER_ROLE,
    );

    $blocks['my_custom_home_block_output_block'] = array(
        'info' => t('Custom two'),
        'cache' => DRUPAL_CACHE_PER_ROLE,
    );
  return $blocks;
}

**
 * Implements hook_block_view().
 */
function my_custom_block_block_view($delta = '') {
    $block = array();
    switch ($delta) {
        case 'my_custom_block_output_block':
            $block['subject'] = t('Block one');
            $block['content'] = _my_custom_block_block_content();
            break;
        case 'my_custom_home_block_output_block':
            $block['subject'] = t('Block 2');
            $block['content'] = _my_custom_home_block_block_content();
            break;
 }
    return $block;
}

/**
 * Callback implemented by hook_block_view().
 */
function _my_custom_block_block_content() {
    //Your custom values for output in $items
    $items = get_data();
 $output = theme('my_custom_block_output', array('items' => $items));
return $output;

}
function _my_custom_home_block_block_content() {
   //Your custom values for output in $items
   $items = get_data();
 $output = theme('my_custom_header_block_output', array('items' => $items));
return $output;

}

 //Data to be output
 function get_data(){
     //Your custom code
    }

```

Template file(.tpl) should be in "template" directory Eg :

```
template/block--my-custom-block.tpl.php
template/block--my-custom-header-block

```

---
Tags: 7, blocks
---


title: How to use RefreshView event properly?

text:
# Question
Title: How to use RefreshView event properly?
I'm editing views rows via ajax request. After request I expected refresh of this view.

I've added custom ajax command:

```
  Drupal.ajax.prototype.commands.refresh_view = function(ajax, response, status) {
        var selector = Drupal.settings.my_module.refresh_selector;
        $(selector).triggerHandler('RefreshView');
    };

```

but nothing happends. I'm debugging this and have sure that selector is ok. Maybe this issue is because that Drupal.views.instances is empty?

What am I missing?

# Answer
Solution is dead simple. 'Use Ajax' option in View settings must be enabled.
> 2 votes

---
Tags: 7, views, ajax
---


# Question
Title: How to select a random user from a list of users that have flagged a content?
I'm trying to make some kind of contest site, in which users can publish random old stuff, which will be raffled later between the users that have marked that content. I crated a specific content type for this, let's call it "kiwi", with a winner field. Then created a flag for that content, so, every content created has the button saying "I want this", when you click, you are kind of "subscribed" to that content. I want to create a rule, which chooses a random user from the list of user that have flagged the content.

I've been struggling with this for a lot of time, I don't have any more ideas on how to solve this.

Thank you very much

# Answer
> 1 votes
Well I finally did it. The modules used were:

* Rules
* Flags
* Views
* Views rules (This one was the key, allows to execute a view inside a rule, even as loops.)

Two thins were done, first, a component which would be executed every hour, and second, inside that component, every hour, a winner would be chosen for every content that had a contest date matching the hour.

## Creating scheduled component

1. Create a rule set component, which receives a parameter of type date.
2. Add a rule action **schedule component evaluation**, in this component created, and set as the value, the component you are editing, this will program this component to be executed one hour after it is executed.
3. Save everything, and go to Settings \> Rules \> Components and press "execute", with the value "now".
4. Component now is being executed every hour.

## Selecting random winner

1. Install all the modules listed above.
2. Create a simple component that receives a user, and a node as parameters, then add the conditions you need, and finally add an action which sets the winner field inside the node as the user given.
3. Create a view and add a "Rule" display, this will be like the first query.
4. Lets call it "Select content programmed for now", and filter it by a given date, then add the fields that will display, "nid" is the most important.
5. Change the section "edit field info", inside "Rules settings", setting the type of the output, choose "Node" type for the nid (this gives the reference to the node instead of a number).
6. Create another view, called "choose random winner", make it receive a "nid" and return the list of flagged user "uid", sort it with a global random criteria, and set max results with 1.
7. Repeat 4 for this view, but with "User" type.
8. Go to the component which executes every hour, add a view loop action in your rule.
9. Select the view that filters the content for the current date.
10. Add a view loop inside that loop, with the new rule.
11. Add an action containing the component created at the beginning with the parameters you now have available.

---
Tags: rules, flags
---


# Question
Title: How do I replace part of a webform component label with a variable token?
I have webform component labels like this:

Did \[your pet\] have any illnesses?

and I want to replace \[your pet\] with a variable token?

Do I need to write a custom module or can I do this by editing one of the theme .tpl files?

Tried this code as suggested:

```
<?php

/*
 * Implementation of hook_form_alter()
 */

drupal_set_message(t('Outwith the hook'), 'warning'); // display outwith the hook

function wit_bootstrap_form_alter(&$form, &$form_state, $form_id) {

drupal_set_message(t('Inside the hook'), 'warning'); // display within the hook

 // target my form / my field
  if ($form_id == "webform_client_form_1") {
    // target my form / my field

    if ($form['neutered']['#title']) {
        $title = $form['neutered']['#title'];
        $token_val = 'freelo';//get_tokenised_value(); // Which ever way you handle that...
        $title = str_replace('[your pet]', $token_val, $title);
        $form['neutered']['#title'] = $title;
    }
  }
}

```

# Answer
> 0 votes
hook\_form\_alter() should allow you to so.

Within your theme you should be able to do something like :

```
/*
 * Implementation of hook_form_alter()
 */
function my_theme_form_alter(&$form, &$form_state, $form_id){
  // target my form / my field
  if ($form_id == "my_form") {
    if ( $form['my_field']['#title'] ) {
      $title =  $form['my_field']['#title'];
      $token_val = get_tokenised_value(); // Which ever way you handle that...
      $title = str_replace('[your pet]', $token_val, $title);
      $form['my_field']['#title'] = $title;
    }
  }
}

```

Also check the forms api reference to see what things you can set / alter on forms.

---
Tags: webforms, forms
---


# Question
Title: Making Twitter 1.1 API requests on site with OAuth and Twitter modules
I've setup a Twitter app and placed the appropriate Consumer Key and Consumer Secret strings in the settings of *admin/config/services/twitter/settings*.

I'm able to make twitter 1 api requests just fine, such as `drupal_http_request('https://api.twitter.com/1/statuses/oembed.json?id=507185938620219395');` Using api.twitter.com/1.1, however, causes a `215 Bad Authentication` error.

Obviously I'm not passing the necessary data to authenticate myself, but how do I go about doing that? All my google searching comes up with Drupal situations utilizing modules which do everything from the UI, or code examples which use php libraries such as Twitteroauth.

I should add that I am running a localserver test site and have setup my app's callback as both http://127.0.0.1:8000/twitter/oauth or the domain name I have setup in etc/hosts on my linux server. Neither seem to help, but both are accepted just fine in the twitter settings.

Lastly, I have been getting the following Notice on *admin/config/services/twitter*:

> Notice: Trying to get property of non-object in user\_access() (line 808 of /var/www/twitcher/modules/user/user.module). (as well as lines 820, 821, 827 and 830)

I only began seeing this 2 days ago, and have been unable to figure out exactly what is causing this (I've seen other threads about the same notice, usually relating to Administrative Views, but nothing on the Twitter module).

What is preventing authorization here?

# Answer
> 1 votes
Perhaps not a Drupal solution, but I thought I would update to say that I have settled on using Twitter-API-PHP found here https://github.com/J7mbo/twitter-api-php

---
Tags: social-network, authentication-authorization
---


# Question
Title: Data export import module node id different after imported
I using Data export import module in my new Drupal 7.

I imported Drupal 6 database into Drupal 7 site.

But unfortunately the node id for the same article is different.

How do I fix this?

# Answer
> 3 votes
You can use UUID module, some quote from module page :

> This module provides an API for adding universally unique identifiers (UUID) to Drupal objects, most notably entities. Features in Drupal 7 version Automatic UUID generation
>
> UUIDs will be generated for all core entities. An API is provided for other modules to enable support for custom entities. UUID API for entities, properties and fields
>
> With this unified API you can load entities with entity\_uuid\_load() so that all supported properties and fields are made with UUID references. You can also save entities formatted this way with entity\_uuid\_save() (depends on Entity API). Export entities to use as default/demo content
>
> The integration with Features module provides the ability to export UUID enabled entities with intact dependencies and references to other entities. This functionality depends on Deploy module 7.x-2.0-alpha1 (soon to be released) and is probably the most robust way for installation profiles and distributions to provide demo content!

The problem is that Drupal uses serial ids for the content (nodes), so if we have the same site installed different places, the id for the same content most likely will be different. (fx in one environment the node id might be 137, while it on another might be 153) This makes it very hard to track changes on the same content in different environments. The idea with UUIDs is to create a id that is the same on all environments.

---
Tags: importing-exporting
---


# Question
Title: How to render entity reference data in field template?
I have a **field collection** with adding multiple items. In each item there is an **entity reference field** with multi-selection of contents. I can render entity reference content by **target\_id** using `node_load` in an **entity\_reference field template**. But it is getting only first value of each item.

How can I render all contents of each item from **field collection**? Is there another way to fetch?

# Answer
> 0 votes
Paste the below code `template.php`;

```
function mytheme_preprocess_node(&$variables) {
  if(isset($variables['node']))   {
    switch ($variables['node']->type) {
      case "value":
        $var_abc = $variables['node']->field_abc;

        foreach ($var_abc['und'] as $key => $value) {
          $variables['abc_fields'][] = $value;
        }
      break;
    }
  }
}

```

Paste the below code to create separate node tpl for that specific content type;

```
<?php
foreach($variables['abc_fields'] as $key => $value) {

  $var_authorvalue = $value['node']->field_author;
  //echo "<pre>";
  //print_r($var_authorvalue['und'][0]['value']);
  $var_fields = $value['node'];
  print render($var_fields->title)."<br/>";
  print render($var_authorvalue['und'][0]['value'])."<br/>";

}
?>

```

OR

Check How can I print a field from a referenced entity in my theme?

---
Tags: theming, entities
---