title: How to add a class to scald images?

text:
# Question
Title: How to add a class to scald images?
I am using the Drupal 7 **Bootstrap** theme and **Scald**. I have figured out how to use contexts but would like it so that when an image is shown it has the `img-responsive` class.

Can this be done by manipulating the render array?

Can anyone point the best way to achieve this?

# Answer
> 3 votes
Putting an extra `<div class="img-responsive">` wrapper around the standard atom markup generated by Scald works (sort of - the legend doesn't look good).

However, I've solved this by just copying the Bootstrap `img-responsive` class, using it as an override for the Scald `dnd-atom-wrapper` class:

```
// Just copy the Bootstrap CSS for img-reponsive.
.dnd-atom-wrapper {
  max-width: 100%;
  display: block;
  height: auto;
}

```

This seems to work for all image atoms in Scald (it may break other types of atoms - I only use Scald atoms for images).

I really want to emulate the complete Bootstrap "thumbnail" concept (including nice borders and captions), but using standard Scald atom css classes, so I ended up with these overrides for the relevant classes (this is the default player - must be slightly adapted to work with the HTML5 player):

```
// CSS fror Scald image atoms
.dnd-atom-wrapper {
  max-width: 100%;
  display: block;
  height: auto;
  background-color: #ffffff;
  border: 1px solid #dddddd;
  border-radius: 4px;
  line-height: 1.42857;
  margin-bottom: 5px;
  padding: 4px;
  transition: border 0.2s ease-in-out 0s;
}
.dnd-legend-wrapper {
  margin: 0;
  text-align: center;
  font-size: 0.8em;
  width: 100%;
}
.dnd-atom-wrapper,
.dnd-drop-wrapper img {
  margin-left: auto;
  margin-right: auto;
  float: none;
  display: block;
}
.dnd-atom-wrapper.atom-align-right {
  @media (min-width: @screen-lg-min) {
    margin-left: 0.7em;
  }
}
.dnd-atom-wrapper.atom-align-left {
  @media (min-width: @screen-lg-min) {
    margin-right: 0.7em;
  }
}
.atom-align-right {
  @media (min-width: @screen-lg-min) {
    float: right !important;
  }
}
.atom-align-left {
  @media (min-width: @screen-lg-min) {
    float: left !important;
  }
}

```

I have this CSS in `less/overrides.less` in my Bootstrap subtheme.

Remember to compile it with *lessc* and clear caches for it to work.

Below you can see it in action. Big screen on the left, small screen on the right.

# Answer
> 1 votes
I finally worked this out. It is still a hack, but it doesn't add a wrapper, and don't require additional CSS. I don't think it *can* be solved "the Drupal way", given the way **Scald** works.

It turns out that markup for **Scald** atoms is already present in the render array and a class added as an attribute to the render array (as you would normally do) will be ignored.

Adding the following to the top of `node.tpl.php` works:

```
$markup = $content['field_scald_atom_ref'][0]['#markup'];
$markup = str_replace('typeof="foaf:Image"',
  'typeof="foaf:Image" class="img-responsive"', $markup);
$content['field_scald_atom_ref'][0]['#markup'] = $markup;

```

What this code snipped does is to hack the markup already generated by **Scald** to include `class="img-responsive"`.

---
Tags: 7, theming, scald
---


# Question
Title: Token to show only first term in Page Title module
I am using Page Title module and patterns to auto create them. One of the tokens for Page Title when creating content is taxonomy term.

Since users can add as many terms in content i would like to limit Page Title to only use first term added by the user.

Is there a way to do this with tokens ?

# Answer
> 3 votes
Delta values for field are available in token

As the description says delta start with 0 try using token as `[node:field-page-title:0]`, remember to replace your field machine name.

---
Tags: tokens
---


# Question
Title: When building a SelectQuery, why can't I use the alias from addExpression() in a condition()?
I'm trying to search for nodes with field values that satisfy a mathematical formula. I can build a SelectQuery that will find all nodes and return the value of the computation for each result using addExpression(), but I cannot seem to accomplish the final step of only returning the correct nodes using condition().

Here is a simplified example:

```
$myquery = db_select('node', 'n');

// Use innerJoin() since node field values are stored in separate tables
$myquery->innerJoin('field_data_field_number_one', 'one', 'n.nid = one.entity_id');
$myquery->innerJoin('field_data_field_number_two', 'two', 'n.nid = two.entity_id');

// Add basic node fields and the two value fields so they will be available in the results
$myquery->fields('n');
$myquery->addField('one', 'field_number_one_value', 'one');
$myquery->addField('two', 'field_number_two_value', 'two');

// Add the computation using addExpression()
// In this example the computation has been reduced to a simple sum
$myquery->addExpression('(one.field_number_one_value + two.field_number_two_value)', 'sumcalc');

// Only return nodes of type desired_type
$myquery->condition('n.type', 'desired_type');

// The query will execute properly without the following line
$myquery->condition('sumcalc', 5, '<');

$prex = $myquery->preExecute();

if ($prex) {
  $qresult = $myquery->execute();
  foreach ($qresult as $qrecord) {
    // Without the erroneous condition above, this line will print each result
    // and each result will contain the value of the calculation added via addExpression()
    dpm($qrecord);
  }
}

```

If I try to execute the code above, I get the following error:

```
PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'sumcalc' in 'where clause'

```

What am I doing wrong here?

# Answer
The MySQL you're trying to build is invalid - you can't refer to an expression field in a `WHERE` clause.

You need a `HAVING` clause for that, which in Drupal-ese is:

```
$myquery->havingCondition('sumcalc', 5, '<');

```
> 2 votes

---
Tags: database
---


title: How to force user to change password?

text:
# Question
Title: How to force user to change password?
I am using Force password change module to give a facility to user to reset the password after their first login. So far, I have installed the module and after creating the user, when I click on edit link, I could see the *force user to change password* check box option. But I am unable to see the same option in add user page (while creating user).

Any suggestions about how to enable same option on add user page?

# Answer
You can navigate to this url `admin/config/people/force_password_change` and check `Force password change on first-time login` option or you can configure based on roles too.

In that case you will get a option in both create and edit user as shown in screenshort.
> 4 votes

---
Tags: users
---


# Question
Title: Including a different jQuery version only on specific page
jQuery update module is including this script.

```
<script type="text/javascript" src="/sites/all/modules/jquery_update/replace/jquery.min.js?6"></script>

```

I need this on every page, except a certain template file which I am using fancy box, and need a later version of jQuery.

I need to exclude jQuery update from putting the above script in the `$scripts` variable ONLY on page-media-photos.tpl.php. How can I achieve this?

# Answer
Here are your options:

* Use jQuery Multi, as mentioned in another answer. It can be configured to load the higher version of jQuery just on that page and just for the fancy box. It won't interfere with Drupal's jQuery or with jquery\_update's jQuery.
* In Drupal 7, you can use hook\_js\_alter(), which will let you swap out jquery\_update's version with whatever you want.
* In Drupal 6 *with jQuery Update*, it provides a hook that lets you alter the JS after it's done doing its thing. You can look at the jQuery Multi 6.x code to see how it uses this hook.
* In Drupal 6 *without jQuery Update*, you can do this using a preprocess\_page hook. The `$scripts` variable will be available there, and you can change it. This can get a bit tricky. You can also see how qmulti does this. jQuery Update also does this in a similar way.

Remember that swapping to a higher jQuery version can break some things in Drupal core and contrib, which is the problem jQuery Multi solves. So if you do this make sure you're not breaking anything. The benefit here is that you just load the jQuery you need, while with jQuery Multi you'll load both.
> 11 votes

# Answer
There is a module jQuery multi. This module allows you to have `multiple versions of jQuery run parallel` on your drupal instance. It provides an `alias` for each instance which you can use for calling that version of jquery.
> 3 votes

# Answer
If you have troubles with jqueryupdate and views admin pages (for example) try to install Dev version of ctools and everything will be OK, just tested myself.
> 3 votes

# Answer
Please find this code may helpful, Place this code in your template.php

```
function MYTHEME_preprocess_page(&$vars) {
  $scripts = drupal_add_js();
  if (in_array('page-media-photos', $vars['template_files'])) {
    unset($scripts['all']['module']['PATH_OF_JS_NEED_TO_REMOVE']);
  }
  $vars['scripts'] = drupal_get_js('header', $scripts);
}

```

PATH\_OF\_JS\_NEED\_TO\_REMOVE give the path of js for ex: sites/all/modules/og/og.js
> 3 votes

# Answer
### Drupal 7

You can call `jquery_update_jquery_replace()` on specific page (e.g. it in `hook_library_alter()`) as demonstrated in here by drupalmoff:

```
<?php
/**
 * Implements hook_module_implements_alter().
 */
function your_module_module_implements_alter(&$implementations, $hook){
  if( $hook == 'library_alter' ){
    $group = $implementations ['your_module'];
    unset($implementations ['your_module']);
    $implementations ['your_module'] = $group;
  }
}

/**
 * Implements hook_library_alter().
 */
function your_module_library_alter(&$javascript, $module) {
  if( $module === 'system' && current_path() == 'path/to/page' ) {
    // Make sure we inject either the minified or uncompressed version as desired.
    $min = variable_get('jquery_update_compression_type', 'min') == 'none' ? '' : '.min';
    $cdn = variable_get('jquery_update_jquery_cdn', 'none');
    $path = drupal_get_path('module', 'jquery_update');

    $version = '1.7';

    jquery_update_jquery_replace($javascript, $cdn, $path, $min, $version);
  }
}
?>

```

### Drupal 6

My solution was to change `JQUERY_UPDATE_REPLACE_PATH` constant before `jquery_update` loads it:

```
<?php
/**
 * Replace jQuery files on specified paths (fix for IE 6&7 - jQuery bug: bugs.jquery.com/ticket/6498)
 */
// if (array_search($_GET['q'], array('my_page')) !== FALSE) {
if (arg(0) == 'node' && arg(1) == '123') {
  define('JQUERY_UPDATE_REPLACE_PATH', 'sites/all/libraries/jquery/1.5.2');
}
?>

```

So it can be added either at very beginning of the .module file (which is loaded before `jquery_update`, or try in settings file.
> 2 votes

---
Tags: 6, javascript
---


# Question
Title: PDOException: SQLSTATE[HY000] [2002] No such file or directory in _registry_check_code()
Drush is running on MAMP, PHP 5.6.6.

Inside `/Volumes/Doxy/htdocs/omegadoen/sites/all/themes/omega`

I run:

```
drush omega-wizard

```

I get:

> # Additional uncaught exception thrown while handling exception.
>
> ## Original
>
> PDOException: SQLSTATE\[HY000\] \[2002\] No such file or directory in drupal\_is\_denied() (line 1917 of /Volumes/Doxy/htdocs/omegadoen/includes/bootstrap.inc).
>
> ## Additional
>
> PDOException: SQLSTATE\[HY000\] \[2002\] No such file or directory in \_registry\_check\_code() (line 3169 of /Volumes/Doxy/htdocs/omegadoen/includes/bootstrap.inc).
>
> ---
>
> Drush command terminated abnormally due to an unrecoverable error. \[error\]

What now?

# Answer
For simplicity check `drush status` with verbose and debug parameters:

```
drush -vd status

```

If you're using different profile, don't forget to include it as `-l http://foo`.

If you still have a problem, it's an issue with bootstrapping your Drupal.

First check your SQL connection if it's working:

```
drush sql-cli

```

If it does not, check your db credentials in your Drupal settings file.

If it does, there is a problem with SQL connection through the socket.

So in MAMP you've to do:

1. Check value of `socket` in my.cnf (menu: *File/Edit Template*), it's usually set as:

```
socket      = /Applications/MAMP/tmp/mysql/mysql.sock

```
2. Double check if your MySQL can find this file:

```
$ mysql_config --socket
/Applications/MAMP/tmp/mysql/mysql.sock

```
3. Double check if your PHP has the right `mysql.sock` set-up:

```
$ php -i | grep mysql.default_socket

```
4. Link the socket into your `/tmp` and see if that helps:

```
sudo ln -s /Applications/MAMP/tmp/mysql /var/mysql

```
5. Test the socket file:

```
mysql --socket=/var/mysql/mysql.sock

```
6. Still the problem? Add the following setting into your `$databases`:

```
$databases['default']['default'] = array(
  // ...
  'unix_socket' => '/var/mysql/mysql.sock',

```

---

### Troubleshooting

* Try: `drush sqlq "SELECT @@version_comment LIMIT 1"`
* Try: `drush ev "Database::getConnection('default', 'default');"`
* Try: `mysql --socket=$(php -r 'echo ini_get("mysql.default_socket");')`
* Check permissions on Unix socket: `stat $(mysql_config --socket)`
* Debug: on OS X with `sudo dtruss -fn mysqld`, on Linux with `strace`
* Debug with XDebug:

+ `echo '<?php xdebug_start_trace("/tmp/foo.log");' > init.php`
    + `drush -c init.php ev 'Database::getConnection("default", "default");'`
    + or set `xdebug.show_exception_trace=1` in your `xdebug.ini`
* Check MySQL settings:

+ `echo '<?php phpinfo();' > init.php`
    + `drush -c init.php ev 'Database::getConnection("default", "default");' | grep mysql`
* Run: `php -r "new PDO('mysql:host=localhost;port=3306;charset=utf8;dbname=dbname', 'root', 'root');"`
* Try to rebuilt your registry
> 26 votes

---
Tags: database, drush
---


# Question
Title: Get an error if I run the pml drush command line
I just started to use Drush and I think I have some miss-configuration somewhere. I use MAMP (on mac) and s/Applications/MAMP/htdocs/subastas is the folder for the Drupal installation.

The error tells me the site has not a configured database, but that is not true since the site is running just fine.

When I try to run the **pml** command I get this error message:

> Dooghouse-iMac:subastas doghouse$ drush pml
>
> `PDO::__construct()`: \[2002\] No such file or directory (trying to \[warning\]
> connect via unix:///var/mysql/mysql.sock) environment.inc:517
> Command pm-list needs a higher bootstrap level to run - you will need \[error\]
> invoke drush from a more functional Drupal environment to run this
> command.
> The drush command 'lml' could not be executed. \[error\]
> Drush was not able to start (bootstrap) the Drupal database. \[error\]
> Hint: This error often occurs when Drush is trying to bootstrap a site that has not been installed or does not have a configured database.
>
> Drush was attempting to connect to:
> Drupal version : 7.9
> Site URI : `http://default`
> Database driver : mysql
> Database hostname : localhost
> Database username : drupal
> Database name : subastas
> Default theme : garland
> Administration theme: garland
> PHP configuration :
> Drush version : 5.2
> Drush configuration:
> Drupal root : /Applications/MAMP/htdocs/subastas
> Site path : sites/default
> Modules path : sites/all/modules
> Themes path : sites/all/themes
> File directory path: sites/default/files
> %paths : Array
>
> You can select another site with a working database setup by specifying the URI to use with the --uri parameter on the command line or `$options['uri']` in your drushrc.php file.

This is the error message shown when using `drush si`:

> My-Name-iMac:drupal-7.14 myname$ drush si --db-url=mysql://root:drupal@localhost:8889/d14
> You are about to CREATE the 'd14' database. Do you want to continue? (y/n): y
> sh: mysql: command not found
> Starting Drupal installation. This takes a few seconds … \[ok\]
> WD php: Warning: `PDO::__construct()`: \[2002\] No such file or directory \[warning\]
> (trying to connect via unix:///var/mysql/mysql.sock) in `DatabaseConnection->__construct()` (line 304 of /Applications/MAMP/htdocs/drupal-7.14/includes/database/database.inc).
> WD php: Exception: In order for Drupal to work, and to continue with \[error\]
> the installation process, you must resolve all issues reported below.
> For more help with configuring your database server, see the installation handbook. If you are unsure what any of this means you should probably contact your hosting provider.Failed to connect to your database server. The server reports the following message: SQLSTATE\[HY000\] \[2002\] No such file or directory. Is the database server running? Does the database exist, and have you entered the correct database name?Have you entered the correct username and password? Have you entered the correct database hostname? in install\_run\_task() (line 417 of /Applications/MAMP/htdocs/drupal-7.14/includes/install.core.inc). WD php: Warning: Cannot modify header information - headers already \[warning\] sent by (output started at /Users/myname/Documents/drush/drush/includes/output.inc:37) in drupal\_send\_headers() (line 1239 of /Applications/MAMP/htdocs/drupal-7.14/includes/bootstrap.inc). Exception:
>
> In order for Drupal to work, and to continue with the installation process, you must resolve all issues reported below. For more help with configuring your database server, see the installation handbook. If you are unsure what any of this means you should probably contact your hosting provider.
>
> Failed to connect to your database server. The server reports the following message: *SQLSTATE\[HY000\] \[2002\] No such file or directory*.* Is the database server running?
> * Does the database exist, and have you entered the correct database name?
> * Have you entered the correct username and password?
> * Have you entered the correct database hostname?
>
> in install\_run\_task() (line 417 of /Applications/MAMP/htdocs/drupal-7.14/includes/install.core.inc).
> Drush command terminated abnormally due to an unrecoverable error. \[error\]

# Answer
> 14 votes
I fixed by running these lines in the terminal.

```
sudo mkdir /var/mysql
sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /var/mysql/mysql.sock

```

# Answer
> 1 votes
Find path to your `mysql.sock` (e.g. run: `mysql_config --socket`), then add extra line (with `unix_socket`) to your `settings.php` file:

```
$databases['default']['default'] = array(
    'driver' => 'mysql',
    'unix_socket' => '/var/mysql/mysql.sock',
    // ... (other options)

```

Where `/var/mysql/mysql.sock` is your full path to your `mysql.sock` file.

---
Tags: drush
---


# Question
Title: Add content type filter on taxonomy page
I am new to drupal, i have created 2 different content types i.e. Online and Offline. I want to add content type filter dropdown on taxonomy page to select any one content type from online/ offline. Can anyone help?

# Answer
> 2 votes
Instead of creating the two different content type i.e. online and offline, you should create vocabulary with two terms and then add "term reference" field to that content type.

# Answer
> 1 votes
You can use the views module to create the taxonomy listing. Within Views you can add an exposed filter, which allows users to select which content to view, Offline or Online.

There are many guides on views, so I wont go into the actual detail of how to configure the view itself.

# Answer
> 0 votes
Create a `taxonomy` by adding `vocabulary` : modes(say). Add terms in it. "*Online*". Add second term : "*Offline*". Now create field in your `entity` \- content type/taxonomy wherever you want and add a field of type `term reference`. Choose `widget` select list. Now choose your vocabulary name from select list. And this way you can achieve the result.

If still having any issue you can ask.

---
Tags: views
---


# Question
Title: Filter Entity reference based on attribute
Here's my situation: I have a "Project" content type. I want to be able to add employees to a project based on their role with a select or multi-select drop down widget with unlimited number of values. So I can add multiple people with different roles.

I would like to be able to choose a Role first - say a "designer" - and then have the drop down for the entity reference only show just the roles for designers.

```
Project
  --> choose Role "designer"
  --> choose designer "John Doe"
  Add next person
  --> choose Role "??"
  --> choose person "??"

```

What are possible ways to do this?

# Answer
> 2 votes
The best way I found offering a very high amount of flexibility is to combine the two following components:

* The Dynamic Dependent Fields (DDF) module takes in charge the relation between the other fields composing your form and your Entity Reference field.

Concretely, it will add a new mode for the entity selection, "*Views: Filter by an entity reference view with dynamic argument*", which allows you to dynamically pass the value of one or several other fields of your edit form as contextual filters to a view.

The magic here is that the values proposed by your Entity Reference is dynamically updated upon modification of the controller fields content (JavaScript).

The only limitations I encountered with this module is that it does not support autocomplete fields as the controlee Entity Reference fields, drop-down lists must be used instead. Moreover, DDF does not take into account programmatically set default values for the controller fields, however I submitted a patch solving this.
* A patch for Entity Reference (currently in RTBC status) adds the possibility to use tokens now as contextual filter for the views and complement very well the above mentioned DDF module.

For instance, this patch allows very easily to exclude the current entity from the Entity Reference available choices.

Associating the two modules let your Entity Reference fields available values to be generated by a View taking into account both tokens and other fields values. Hard to get more flexibility !

# Answer
> 1 votes
you can't use **Hierarchical select** Hierarchical Select module for this purpose because you don't have dependancy like Countyr -\> State -\> City -\> Village etc. so you should create view for your content type and add expose filter manually like :

```
/**
* Implements hook_form_alter().
*/
function my_module_form_alter(&$form, &$form_state, $form_id) {
 if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'my_view_name' && $form_state['view']->current_display == 'my_view_display_name') {
// your stuff here
       if(isset($_POST['project_name'] && !empty($_POST['project_name']))
        {
        }
       ...
        and so on..

 }
}

```

# Answer
> 0 votes
Hierarchical select Module provides input format similar for your requirement.

> **Description**
>
> This module defines the "hierarchical\_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy.
>
> Hierarchical Select has the ability to save the entire lineage of a selection or only the "deepest" selection. You can configure it to force the user to make a selection as deep as possible in the tree, or allow the user to select an item anywhere in the tree. Levels can be labeled, you can configure limit the number of items that can be selected, configure a title for the dropbox, choose a site-wide animation delay, and so on. You can even create new items and levels through Hierarchical Select!

Since hierarchical select will not work another way is by using
Dynamic dependent fields, Entity reference, Role field, Field collection these modules.

Create a Field Collection with role field and user entity reference field and use DDF for filtering user entity reference by roles. Add this Field Collection to your project content type.

---
Tags: entities, users, input-formats
---


title: Block not showing up

text:
# Question
Title: Block not showing up
I am building a fairly simple module, and I am trying to set up a block, but it doesn't appear. I can't figure out what is wrong with my code.

```
function quick_links_block_info() {
  $blocks['quick_links_staff'] = array(
    'info' => t('Quick Links'),
    'status' => 1,
  );
  return $blocks;
}

function quick_links_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'quick_links_staff':
      $block['subject'] = t('Quick Links');
      $block['content'] = quick_links_get_links();
      break;
  }
  return $block;
}

function quick_links_get_links($department = '') {
  return t('Hi');
}

```

# Answer
Your implementation of the block hooks is wrong. Try the below:

```
function quick_links_block_info() {
  $blocks['quick_links_staff'] = array(
    'info' => t('Quick Links'),
    'status' => 1,
  );
  return $blocks;
}

function quick_links_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'quick_links_staff':
      $block['subject'] = t('Quick Links');
      $block['content'] = quick_links_get_links();
      break;
  }
  return $block;
}

function quick_links_get_links($department = '') {
  return t('Hi');
}

```

I've namespaced the block, and changed the status from TRUE to 1, as per the `hook_block_info()` docs. I've also removed the assignment of `$delta`, as this is passed through automatically.

**REFERENCES**

`hook_block_info()`

`hook_block_view()`
> 2 votes

# Answer
I had the same problem, I cleared all caches under performance and my module showed up in blocks.
> 2 votes

# Answer
Use:

```
'status' => 0

```

or

```
'status' => 1,

```

and provide a region like this:

```
'status' => 1,
'region' => 'footer',

```
> 0 votes

# Answer
Uninstall the Module and install the module again and you will be able to see the block that you have created.
> 0 votes

# Answer
Try the following:

* double check your module is loaded properly and there are no typos,
* you're testing it on the right environment:),
* clear all caches (including `memcached`/`redis`) either in *Performance* or by `drush cc all`,
* disable 'Cache blocks' (and other caches) in *Performance*
* restart Apache server (it could be `OPCache`/`XCache`),
* check if Apache user has read access to your module file or folder,
* check logs (e.g. `drush watchdog-show --tail`),
* install `drush_extras` and run: `drush block-show` to see if your block is on the list
* see if the block is loadable either at `/devel/php` or via `drush`:

```
drush ev "var_dump(block_load('foomodule', 'foodelta'));"

```
> 0 votes

---
Tags: blocks
---


# Question
Title: How to clear or update only anonymous cache from module?
I have nodes updating from my module in Drupal 7 and also complicated view with result cached in the module by cache\_set() and cache\_get() functions.

Anonymous users get old info with broken links and other problems after nodes updating in module. Disabling "Cache pages for anonymous users" solves the problem, but how can I update anonymous page cache by the function after update?

I can't just clear all cache because of complicated views cache, it will disable all site for the time.

# Answer
cache\_clear\_all() is what you need.

If you need to clear cache of only one node page:

```
cache_clear_all('http://yoursite.com/node/' . $node->nid, 'cache_page')

```

(first parameter - cache id, it case of cache\_page it is page url).

If you want to clear all pages cache:

```
cache_clear_all('*', 'cache_page', TRUE);

```
> 1 votes

---
Tags: nodes, caching
---


# Question
Title: How to execute VBO list of nodes in Rules on After updating an existing user account event?
I have a VBO of all the unpublished nodes of the user, and I want to publish all of them based on user role change that happens via Rules.

I created a component of rule to list the nodes of that user but since my `Event` is `After updating an existing user account` in my `actions` section, when I add the component, there's no `Node` related parameters to pass so I can publish those nodes.

**Update**: Pierre's answer actually defines the steps that I've already taken, the last part that puzzles me is that how can I add the component to be triggered to an `After updating an existing user account` event where there's no node defined in it.

# Answer
What you actually need to do is similar to what is shown in the video about Using VBO to load list of objects into Rules, starting from about 5:30, up to 11:30. Here is a summary of what is shown in this video (quote from the linked page):

> * You need a view that lists the entities you want to work on in Rules. Note that you don't need a display of the view – and it might even be better not to have one if you don't want the view to be displayed somewhere.
> * However, you need one bulk operations field. The type of bulk operations field determines what entity type will be sent to Rules. Note that you don't need any actions enabled for the field – it is enough that it is present.
> * You need a rule that, as an action, loads entities from a VBO. (This is available under the "Views bulk operations" group.) All view displayes with at least one VBO field will be selectable.
> * The action provides a list of entities, that can be used just like other lists in Rules. Combine with loops, actions and Rules Scheduler to make awesomeness happen.

In your case you want to start from your VBO list of the unpublished nodes of the user. And for each node in the list you want the rules action to be "publish node" (instead of "remove sticky").

You want to pass the userid as a parameter also, similar to what is shown around 7:30 in that video also. I'm assuming your VBO view also requires the userid already.

The Rules component that you create as described above, should then become the action to be performed by a rule that is triggered by the event "After updating an existing account". This is what differs from what is shown in the video, starting from 11:30 (in the video the Rules component is triggered daily, via the Rules Scheduler).

Should you need any other rules "conditions" (eg: only for selected roles), you can add them to the rules component you created.
> 1 votes

---
Tags: 7, rules, views
---


# Question
Title: How do I manually set tnid when migrating nodes?
I need to manually set tnid during migration.

My code:

```
  public function complete($entity, $row) {

    // load the newly created node (just in case entity isn't fully populated).
    $node = node_load($entity->nid);
    $node->tnid = '66';
    $node->title = 'CHANGE THIS !';

    // create the field collection item entity
    $item = entity_create('field_collection_item', $values);

    // attach it to the node loaded above
    $item->setHostEntity('node', $node);

    // save the entity
    $item->save();
  }

```

The node 66 exists and is active, but when I check on translations, the new node isn't associated. Instead the title is changed with "changed this", then the new node is updated.

With Devel I see that the node has tnid 66.

# Answer
> 0 votes
You want to give the node a language, and set the source node in the `translation_source` key:

```
$node->language = 'es';
$node->translation_source = node_load(66);

```

Reference: https://api.drupal.org/api/drupal/modules!translation!translation.module/function/translation\_node\_prepare/7

---
Tags: nodes, migrations, i18n-l10n
---


title: cURL hangs the hook_user_update

text:
# Question
Title: cURL hangs the hook_user_update
I am using a cURL to notify remote site of some updates on my site. I use it with hook\_user\_update() which is used when user data is saved. Problem is that it takes a lot of time to do that (maybe slow remote server). User saving is slow and it takes sometimes a minute or two.

How could I make this work that cURL doesn't hang user update and they are not dependent in this way?

This is the code I am using now

```
/**
 * Implemention of hook_user_update(), Notify OS after updating user account
 */
function os_integration_user_update(&$edit, $account, $category) {
  $query = array(
    'source' => 'web',
    'action' => 'nCustomer',
    'customer_id' => $account->uid,
    );

  $url = url('http://admin.com/synch/index.php', array('query' => $query));

$username = 'admin_os';
$password = 'admin_pass';
$basic = base64_encode($username . ':' . $password);

$headerArr = array();
$headerArr[] = 'Authorization: Basic ' . $basic;

$ch = curl_init( $url ) ;
curl_setopt ($ch, CURLOPT_HTTPHEADER , $headerArr );
curl_setopt( $ch, CURLOPT_HEADER, 1);
// Execute
curl_exec($ch);

// Check if any error occurred
if(!curl_errno($ch))
{
 $info = curl_getinfo($ch);

 echo 'Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url'];
 watchdog('lelo_os_integration_os_error', 'Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url']);
 // other info data http://php.net/manual/en/function.curl-getinfo.php
}

// Close handle
curl_close($ch);
}

```

# Answer
> 0 votes
The HTTPRL project provides you with a non-blocking HTTP client.

```
$url = url('http://admin.com/synch/index.php', array('query' => $query));
$username = 'admin_os';
$password = 'admin_pass';
$basic = base64_encode($username . ':' . $password);

httprl_request($url, array(
  'blocking' => FALSE,
  'headers' => array(
    'Authorization' => 'Basic '.$basic,
    'Host' => $_SERVER['HTTP_HOST']
   ),
));
$request = httprl_send_request();

```

---
Tags: hooks, users
---


# Question
Title: Errors occured while trying to retrieve tweets
I am running drupal 7 and using the following twitter module for twitter feed to display on the front page of a site.

`Twitter Pull 7.x-1.0-rc1 Pull Info from Twitter and Create Contextual Insets`

Recently, start getting the following error message instead of twitter feed

`Errors occured while trying to retrieve tweets. Please check Watchdog log messages.`

I don't have watchdog configured nor see any other error log that lead to anywhere. Please note that I am new to drupal. kindly let me know with detail steps how do I resolve this issue.

I see the following on `/admin/reports/dblog`

```
 Reports
 Status report
 Get a status report about your site's operation and any detected problems.
 Field list
 Overview of fields on all entity types.

```

This was working so I am sure the API keys were setup but I don't know where to look to confirm this.

Good idea to enable database logging. I have enabled the database logging now seeing more detail error message:

`Non-empty list of tweets returned blank space after applying theme function. Most probably you are passing invalid/unregistered theme key or tpl file corresponding to the theme key does not yet exist. Please fix the problem.`

I will check details on sendbox.

# Answer
If you haven't enabled **Database Logging** yet, go ahead and do that on the modules page. Then you should see errors reporting under **admin/reports/dblog**.

Twitter recently dropped their version 1 support, which is what Twitter Pull runs off of. Now you must use the Twitter and oAuth modules to deal with v1.1. Look at this sandbox for a solution. It branched off from Twitter Pull as an alternative to deal with oAuth tokens.

**Updated: Better way to do it**

There's recently a new module that came out that makes it a whole lot easier to embed tweets using the embedded widgets. Try Twitter Block instead, and you'll get up and running a lot faster.
> 2 votes

# Answer
The Twitter v1 API has now been replaced by v1.1 of the API, and as such it requires OAuth for even retrieving tweets. The Twitter Pull module was designed to easily pull tweets without any prior configuration since it used the old version of the API and as such, there are no plans to include OAuth integration, since the Twitter module performs this task now.

However, there is still a necessity for people using Twitter Pull blocks to have a working feed so they don't have to rebuild and redesign their blocks; but it requires Twitter & OAuth module integration now to restore this.

You can find a patch to integrate Twitter & OAuth into Twitter Pull to fix this and it should return your feeds to normal. The instructions are near the top of the thread.

Here's what I did when encountering the same problem:

* Turn off Twitter Pull
* Install and Enable Twitter, Oauth and Autoload.
* Enable Twitter Pull
* Register your application https://dev.twitter.com/apps/new
* Go to admin/settings/twitter/settings and copy in the OAuth settings from your new twitter app
* On the Twitter app settings page and paste in the callback URL displayed at admin/settings/twitter/settings
* On the Twitter app details page, click the “Create my access token” button at the bottom of the screen
* On your site, go to admin/settings/twitter and click “Go to twitter to add an authenticated account”, insert the account login
* Run cron to pull in the latest tweets to store in the database

This should renew your feed. There is no other solution I know of, but at least this method enables you to continue using Twitter Pull and not have to rebuild everything with just Twitter module.
> 1 votes

# Answer
Check logs as possible things can be:
> 0 votes

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


# Question
Title: How to implement an enumerated field using hook_schema()?
I need to have a field in my database that is shall hold a limited set of enumerated values.

The MySQL ENUM type is not one of the predefined Drupal data types.

So how do one implement a field to hold enumerated values using hook\_schema?

I understand that I can do it with a `tiny int`, but how do I map from and to the strings of enumerated values (e.g. "zero", "one", "two", "three") to integers stored in the DB?

# Answer
> 1 votes
If you are using the Form API to accept this data, you can map integers to string values.

You can also store that mapping array in your .module file.

---
Tags: 7, database
---


title: Information of the user in comments

text:
# Question
Title: Information of the user in comments
I want to show the information of the author in his comment. By default it shows the name and the picture, I want to add:

* The number of node and created comments
* The number of obtained userpoints.

What code should I use to achieve this?

# Answer
> 0 votes
As @arpitr wrote in his answer, you should edit the `comment.tpl.php` file in your theme. Use `userpoints_get_current_points()` to display the user's points. You can easily count the number of nodes and comments with a database query:

```
$uid = $comment->uid;
$nodes = db_query("SELECT COUNT(*) FROM node WHERE uid=$uid AND status=1")->fetchField();
$comments= db_query("SELECT COUNT(*) FROM comment WHERE uid=$uid AND status=1")->fetchField();

```

Put these lines in comment.tpl.php too and print them where you want the values to appear.

# Answer
> 1 votes
Each comment runs through comment.tpl.php template, where the php variables are replaced with actual values and from where you get the actual html

Before going to tpl files, execution passes through template\_preproces functions, preprocess function allows you to add new variables or override existing variables which you use on tpl files.

Now in your case it is comment.tpl.php, if you see the file in bartik theme the code

```
  <div class="attribution">

    <?php print $picture; ?>

    <div class="submitted">
      <p class="commenter-name">
        <?php print $author; ?>
      </p>
      <p class="comment-time">
        <?php print $created; ?>
      </p>
      <p class="comment-permalink">
        <?php print $permalink; ?>
      </p>
    </div>
  </div>

```

is responsible to show comment author information. In order to override the html you can simply copy the comment.tpl.php from parent theme to your base theme and start overriding the html. If you want to introduce new variable to the template, then use template\_preprocess\_comment(), for example on your theme template.php

```
function your_theme_preprocess_comment(&$variables) {
  // To Debug what is inside variables already
  dpm($variables);
  // To override exisiting variable
  $variables['author'] = 'my test author';
  // To add any new variable to comment.tpl.php
  $variables['author_comment_count'] = _some_function_fetch_comments_count($user_id);
  $variables['author_nodes_count'] = _some_function_fetch_node_count($user_id);
  $variables['author_user_points'] = _some_function_fetch_user_points($user_id);
}

```

Now you will have three more variables to use on comment.tpl.php as `$author_comment_count`, `$author_node_count`, `$author_user_points`

Use them on template, example

```
<div class="attribution">

    <?php print $picture; ?>

    <div class="submitted">
      <p class="commenter-name">
        <?php print $author; ?>
      </p>
      <p class="comment-time">
        <?php print $created; ?>
      </p>
      <p class="comment-permalink">
        <?php print $permalink; ?>
      </p>
      <p class="comment-count">
        <?php print $author_comment_count; ?>
      </p>
      <p class="node_count">
        <?php print $author_node_count; ?>
      </p>
      <p class="user-points">
        <?php print $author_user_points; ?>
      </p>
    </div>
  </div>

```

---
Tags: 7, theming, comments
---


# Question
Title: Keyword research does not find any keywords under keyword stats
I've installed module `SEO Tools` including all its 'sub modules". One of them being they `Keyword research` module. Now, in order to find keywords I'm supposed to be able to the **Keyword stats** tab from `admin/structure/kwresearch/keyword_report`, enter a keyword and hit *submit*. I don't get any results, I just see "No keywords were found." - even when I submit a keyword like *bike* for example. Why is this? what am I missing?

# Answer
Keyword research is because of Keyword Research Module, which might have installed as suggestion by SEOTools module.

The report you are looking for is supposed to be pull form third party tools, or to be imported from google, which basically will help you deciding what keyword to use on your site.

Watch this demo for better understanding if you have not watched it yet. \- http://getlevelten.com/tools/contentanalysis/keyword-research/drupal/screencast

Please follow the module installation instructions. Module page says

> To get full reporting with integrated keyword statistics you will need to connect to or import from a 3rd party data source. The module will work without a 3rd party data source, still providing tools for organizing site keywords and tagging nodes and providing links to external tools for assessing keyword statistics. Currently the Keyword Research module supports:
>
> ```
> Wordtracker - premium keyword research service with a free demo key that provides up to 15 suggested phrases per API call.
> Google Keyword Tool - a free tool but data must be imported via file download
> WordStream (via WordStream module) - freemium service. Free account provides 200 API calls/mo
> Scribe SEO (via Scribe SEO module) - paid service starting at just $17/mo.
>
> ```
> 0 votes

---
Tags: 7
---


# Question
Title: Advanced search in Multidomain - Multilanguage catalog webpage Drupal 7
I have a quite complex products database. I have migrated most of the content and hierarchy into Drupal taxonomy, content type and relationships scheme. However, I am not sure if I will be able to configure some Advanced search module to look for products according to name of product, category (taxonomy) and other intrincate parameters. Can you advice some module which is easy to configure and write own MySQL search strings?

# Answer
> 1 votes
There are at least two options. You can use the Views module to expose search filters on the products.

If you have access to an Apache Solr search server you can use some of the modules that integrate with Solr for advanced searching.

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


# Question
Title: Reverse proxy causes issue with CSS links and HTTPS
I have multiple Drupal instances behind a F5 load balancer. If I use it as http, that is OK. If I want to use http and https and ofload https on the LB, all CSS and JavaScript links in the https site comes as http and cannot be loaded because of the https security.

# Answer
> 0 votes
* Do you have any css/js aggregation module installed. If so delete the caches under sites directory. You can even try uninstalling the module to debug if that is causing the issue.
* Clear Drupal caches
* Ensure you do not have global $base\_url hard coded to http.

# Answer
> 0 votes
We have used a configuration similar to the one shown on Running Drupal Secure Pages behind a proxy. Have the F5 set a `X_FORWARDED_PROTO = https` header, then configure Apache to set `HTTPS=on` if the header is set.

---
Tags: proxies
---


# Question
Title: Using searchapi module on a drupal multisite installation
We are setting up a Drupal multisite installation, which is going to look like

```
themastersite.edu
themastersite.edu/somethinglikethesubsite1
themastersite.edu/somethinglikethesubsite2 and so long

```

I've read some documentaition around Searchapi module, but I can't find out if there is a possibility to have, in themastersite.edu, a searchapi page that should search in all subsites ?

Any help or link, welcome.

# Answer
> 0 votes
You declared that searchapi is the solution but actually Solr Multisite can do this.

---
Tags: search
---


# Question
Title: How do I rewrite Solr search results to show related entity reference field?
1: I have two node types: "Plants", and "Pests". related using a field in the plants node type called "affecting\_pests".

How do I modify the solr Search result view; in the case of a Pests result, to display " name of pest==\>affected plant " in the results title, and instead of link to pest page, redirect to the parent plant that the pest affects?

# Answer
> 0 votes
Assuming you are using the apachesolr module, implement hook\_apachesolr\_search\_result\_alter() in a custom module. The function you create will receive the $document object that you may modify. You will have to add logic in there to locate and load the appropriate related entity.

---
Tags: entities, search
---


# Question
Title: hook_simplenews_scheduler_edition_node_alter does not work as expected
Using simplenews scheduler 7.x-1.0-beta2. I created a template newsletter and scheduled it to be sent daily.

I created a simple function to insert a dynamic value into the body of the newsletter edition that is created from the source template:

```
function hook_simplenews_scheduler_edition_node_alter($edition_node, $scheduler_node) {
  $edition_node->body['und'][0]['value'] = 'my new value';
}

```

My expectation was that when a newsletter edition is created from my newsletter template ($scheduler\_node), the body of the new edition would say 'my new value'.

What actually happens is that the email sent to the newsletter subscribers says 'my new value', but the body of the newsletter edition node that is physically created still contains the body from the template.

Any suggestions?

# Answer
> 0 votes
```
function hook_simplenews_scheduler_edition_node_alter(&$edition_node, $scheduler_node) {

    $my_arg = '-1day';
    $edition_node->body['und'][0]['value'] = views_embed_view('tracker03', 'page', $my_arg);
    return $edition_node;

}

```

This does the trick.

---
Tags: emails
---


# Question
Title: Where should I install the LESSPHP compiler?
Hello I just bought a premium theme for Drupal. This theme works with the Less css preprocessor module, and I've installed and enabled this module:

The problem is, the site still doesn't look designed, and I get Drupal errors printed to the screen indicating on problems with Less. Thus I went to the themes' suport forum, ran a search and understood I need to download something called "LESSPHP" (A PHP based LESS-CSS comipler I guess) and install it somewhere in my Drupal installment, but I just don't know where and if it even a right step. Moreover, my site also indicated I miss this "LESSPHP" preprocessor at admin/config/development/less:

Where should I install this "LESSPHP" compiler and what else do you think I missed given the errors I see above?

# Answer
> 2 votes
In the Less Processor Module page it says:

> **Requirements**
>
> Libraries API
>
> less.php and unpack it so that 'lessc.inc.php' is located at 'sites/all/libraries/lessphp/lessc.inc.php'.

Which means:

1) you need to **download and enable** the Libraires API module

2) Then you need to download Less.php **\<-- click here to download it**

3) Open the zip file, and grab the `lessc.inc.php` file only

4) Next you'll need to create some folders in your web directory **(create a libraries folder inside the all folder, and a lessphp folder inside the libraries folder)** so it looks like this

```
sites/all/libraries/lessphp/

```

5) **Upload** the `lessc.inc.php` file to the `lessphp` folder.

---
Tags: theming
---


# Question
Title: Field in custom node tpl - Simple issue that this newb can't figure out
I have been trying to learn the ins and outs of hooks and basic theming in Drupal.

I currently have a template file for one of my content type (`node--opportunities.tpl.p`hp). Everything has been going great theming with this except for a field collection that I am now stuck on. I know there are a multiple ways of theming a field collection and this is the worse. But I can't figure it out when the array is perfectly right in front of me.

`field_services` is the field name. When I `dsm($content)` on the node you can see it perfectly. So I'm using a foreach to loop through the items, pull them out and load them. Then print their values with my markup. But it will not render. Even when I 'dsm' the final array, it shows me my fields perfectly. But when I try to render them, nothing happens.

Can anyone help me understand what I am doing wrong? I am more interested in why my investigative attempts to print the values of this array are fruitless than I am interested in actually theming the field collection.

```
    hide($content['field_services']);
    //horizontal radios
    print '<div class="ec-controls">';
      print render($content['field_opportunity_type']);
    print '</div>';

    //if (!empty($content['field_services'])) {

        print '<div class="ec-collection">';

         foreach ($content['field_services']['#items'] as $entity_uri) {

          $a_field_collection_item = entity_load('field_collection_item',                 $entity_uri);

            foreach ($a_field_collection_item as $a_field_collection_item_object ) {

              dsm($a_field_collection_item_object);

              print render($a_field_collection_item->field_service);
              print render($a_field_collection_item_object->field_service_multiplier);
              print render($a_field_collection_item_object->field_extend_service_total);

              //print render($a_field_collection_item_object->field_service['und'][0]);
              //$...->field_service['und'][0]['entity']->field_unit_price
              //->field_service['und'][0]
            }
        }
        print '</div>' . "\n";
    //}

```

I've also tried these as suggested with no luck. Here is also a printscreen of the `dpm`:

DPM PS http://ecteam.net/Untitled.png

```
    dpm($a_field_collection_item_object);

    print 'test';
    print $a_field_collection_item->field_service['und'][0];
    print $a_field_collection_item->field_service['und'][0]['entity']->title;
    print $a_field_collection_item->field_service['und'][0]['target_id'];
    print $a_field_collection_item->field_service_multiplier['und'][0]['value'];
    print $a_field_collection_item->field_service_multiplier['und'][0]['value'];
    print $a_field_collection_item->field_extend_service_total['und'][0]['value'];

```

**Note**: `field_services` is the parent field collection, `field_service` is the individual field that contains the service title that I am trying to render from it.

# Answer
> 1 votes
Arpitr was correct but I was also referencing the wrong variable.

The foreach loops states foreach ($a\_field\_collection\_item as $a\_field\_collection\_item\_object ) {

I guess I just wasnt paying attention. I used this:

```
    print render($a_field_collection_item->field_service);

```

but I should have used this:

```
    print render($a_field_collection_item_object ->field_service);

```

**Final solution for how to theme a field collection in a node template**

My content is called opportunities. So in my node--opportunities.tpl.php I put:

```
    if (!empty($content['MY_FIELD_COLLECTION'])) {
      hide($content['MY_FIELD_COLLECTION']);

      print '<div class="ec-collection">';

      foreach ($content['MY_FIELD_COLLECTION']['#items'] as $entity_uri) {

        $a_field_collection_item = entity_load('field_collection_item', $entity_uri);

            foreach ($a_field_collection_item as $a_field_collection_item_object ) {

                print $a_field_collection_item_object->field_service['und'][0]['entity']->title;
                print $a_field_collection_item_object->field_service_multiplier['und'][0]['value'];
                print $a_field_collection_item_object->field_extend_service_total['und'][0]['value'];

            }
    }
   print '</div>' . "\n";
   }

```

# Answer
> 0 votes
You do not need to call render function. render() is for renderable arrays.

In your case change from

```
print render($a_field_collection_item->field_service);

```

to

```
print $a_field_collection_item->field_service['und'][0]['value'];

```

similarly for others fields, do a `dpm($a_field_collection_item);` to ensure you pick the right keys for arrays.

For example if service is text field then to fetch you will use print `$a_field_collection_item->field_service['und'][0]['value'];` if its entity reference field than print `$a_field_collection_item->field_service['und'][0]['target_id'];`

---
Tags: theming, entities
---


title: database access to databases

text:
# Question
Title: database access to databases
I have a drupal with many external databases. I do the same things in all databases but I want to limit the access to the database basing on the role the logged-in user has.

I mean:

* The administration user has access to all databases
* Employee has access to db1 and db2
* Worker has access to db1

How can I control database access per role?

# Answer
If you mean controlling which database Drupal uses for its own database tables (e.g. the table containing all the registered users, the active sessions, the nodes created), then it is not possible. There is no way to tell Drupal which database use basing on the user's roles.

If you are asking about your own module, then it is possible, but your module needs to handle this on its own because Drupal doesn't have my specific functions to handle your use case, except the following ones:

* `user_has_role()` checks the user account passed as argument (or the currently logged-in user) has the role passed as argument
* `db_set_active()` set the database used from the successive database API calls using one of the keys set in the settings.php file

Rather than using `db_set_active()`, I would use `$options['target']` which can be used from any Drupal function necessary to query the database.
> 1 votes

---
Tags: users, database
---


# Question
Title: View for selecting an image associated with a node's child node?
I am trying to compose a certain view. I have a content type lesson that contains exercise content types. Exercises reference a lesson nid through an entity reference field. Exercises have images. For a given lesson node, I am trying to build a view that returns the images associated with a lesson's exercises, and then choose one at random.

I couldn't figure out how to make Views return such a result set. And if someone can just explain this in SQL terms, irrespective of view, there is a fiddle: http://sqlfiddle.com/#!9/dbf63

Regards

# Answer
> 1 votes
Haven't figured out how to make Views return what I want but it seems this works, where I would pass the query the lesson node. But I really want to understand how to make Views produce the desired result!

```
SELECT *
FROM file f
INNER JOIN tab t on t.field_tab_fid = f.fid
INNER JOIN lesson l ON l.entity_id = t.entity_id
WHERE l.field_lesson_target_id = 672

```

http://sqlfiddle.com/#!9/dbf63/4

# Answer
> 0 votes
The problem seems to be back-referencing missing on lesson to exercise content type. You can try any of the two ways.

1. Create view on exercise content type, add relationship on entity reference field to lesson, so that you will get lesson content types fields as well, now in your views you will have option to show field from any of two content types exercise or lesson(using relationship). But problem will comes with lessons who are not referenced by any exercise, those will not be listed.
2. Setup a back referencing field on lesson content type, which automatically creates reference of exercise content type on lesson node when user creates referencing on exercise node. There is module Corresponding Entity Relationship which does the same.

---
Tags: views
---


# Question
Title: Filter under condition based on value checkbox of current user profile
I use Views 3.x and Views PHP module.

**The task.** Make Views filtering criteria that would make two different actions, depending on status of checkbox (`TRUE` or `FALSE`) of current user's profile.

**Description**. Logic diagram:

```
IF checkbox current user == TRUE
THEN display taxonomy terms, tid == New
ELSE display taxonomy terms, tid == array('New', 'Archive', 'Old', ...) // 50+ taxonomy terms

```

Please help me.

# Answer
As you can already display the taxonomy terms from the `ELSE` part of your logic diagram in a View, it is quite easy to achieve what you want with a template file for your View. Find the suitable template here and adapt the code underneath, where I assume that you use views-view-field--YOUR\_VIEW-YOUR\_BOULEAN\_FIELD.tpl.php:

```
global $user;
if ($user->field_YOUR_BOULEAN_FIELD['und'][0]['value'] == 1) {
  $output = taxonomy_term_load($tid)->name;
}

```

The variable `$tid` for `taxonomy_term_load()` should be the tid of your taxonomy term *New*.
> 0 votes

---
Tags: views, input-formats
---


title: Two forms using one submit button

text:
# Question
Title: Two forms using one submit button
I want to merge 2 forms together (user register form and node registration form). Should I use multiform module to achieve this or create new form using form API?

# Answer
> 1 votes
**Option 1:**

Think of one form as Node Form with more fields that you can reuse on user entity as well.

Now on node save you have flexible node api to hook in and create user. As an example

1. hook\_node\_presave($node)
2. hook\_node\_insert($node)
3. hook\_node\_update($node)

You can use any of the above, most suitable would be node\_insert I think as you would like to create user only when new nodes is created. Inside the hook you will get the user submitted values inside $node object, all you have to do is create user programmatically from it. Which basically is building a user object and mapping of fields and finally do a user\_save() on your user object.

Here is an example of how you can create user programmatically

**Option 2:**

Form does not need to be node form, you can have a custom form as well using form api, in that case you will not need any of the node hooks instead process would be just like user\_save() you will do node\_save(). So inside your custom form submit handler you will be creating a node(how to create node programmatically) and a user(how to create user programmatically)

---
Tags: forms
---


# Question
Title: How do I add taxonomy to my custom entity?
I am working with a custom entity and I would like to be able to add taxonomy to the entity. The drupal 8 entity documentation is lacking.

I have tried reading Node.php and term.php entitiy files but I don't understand how any sort of taxonomy is linked to any other entity though this.

Do I need to change something in my entity definition to allow taxonomy to be added? Or is there a way to access the taxonomy entity?

Edit: I am working on the same pattern to add this to the install file of my module

```
'category' => array(
                'type' => 'varchar',
                'not null' => TRUE,
                'default' => '',
                'description' => 'The section front  to appear on',
            ),

```

this is the exception that I get trying to install the module

```
exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error [error]
or access violation: 1064 You have an error in your SQL syntax; check
the manual that corresponds to your MySQL server version for the
right syntax to use near 'NOT NULL DEFAULT '' COMMENT 'The section
front  to appear on',

```

# Answer
For custom entities, I would suggest to work with @ContentEntityType and baseFieldDefinitions() method, instead of creating the table on .install file.

You can see more details on why take this path in When to use BaseFieldDefinition instead of hook\_schema an on this implementation.

A taxonomy field is now on D8 only an entity reference field, and you can have an example on how to use it at the field "voted\_entity\_id" at https://github.com/pedrorocha-net/votingapi/blob/8.x-1.x/src/Entity/Vote.php
> 1 votes

# Answer
As Clive said, you use an entity reference field for that, just like articles have a tags reference field to terms.

If you want to define it in code, it's really the same as the node.uid field, which is an entity reference to a user. Or the user.roles field, which is a multivalue reference to user roles. Entities reference others using an entity reference field, it's always the same pattern.
> 2 votes

---
Tags: taxonomy-terms, entities, 8
---


title: Drupal 8 Custom Entities from a UI?

text:
# Question
Title: Drupal 8 Custom Entities from a UI?
Does anyone know away to create custom entities from Drupal 8 UI that is not ECK? I try it out using ECK and still a little bit buggy.

# Answer
Each entity needs a lot of classes for access, forms, storage, listing, viewing, etc... so you would have to create a module with default classes that would be somehow generic and you would have to handle the discovery of these new entity types since D8 uses annotations. Overall a quite a lot of work.

The same goes for config entities but that would be easier since they do not need that much handling compared to content entities.
> 2 votes

# Answer
I don't think it's possible right now and the way to go is wait for ECK port to be more stable.

It's a lot of work to do and ECK maintainers probably are the ones closer to do this.

The other approach is to use Drupal Console, that is really easy to use.

Drupal 8 is not yet too friendly for site builders, in my opinion, as things are not stable. However, for developers, it's already awesome.
> 2 votes

# Answer
I think Drupal console assists with entities scaffolding. It's not an admin UI, but easier than coding from scratch.
> 0 votes

# Answer
Creating a custom entity with a few keystrokes is just one of the things Drupal Console does. In fact when creating a content entity, it gets its own table in the database and instant REST capabilities.
> 0 votes

---
Tags: entities, 8
---


# Question
Title: How to launch a Rule when X nodes were created in X days time?
I'm currently awarding medals to the users on my website by using the Goals and Rules modules: a medal awarding Rule fires when a Goal is completed. However, I'd like to get rid of the Goals module, because it is no longer maintained at the time of writing and it doesn't fully provide the functionalities that I need.

The Goals module has a nice feature, though: it is possible to record tasks that were completed *within a certain period*. I would like to keep this functionality, because some of my medals are granted to users who created X nodes in X days time.

Therefore, I had the idea to add a condition to my medal awarding Rules that checks whether the user created, say, 5 nodes in 10 days time. Is it possible to do this?

# Answer
I've written the following function in my custom module in order to count the amount of published nodes of a certain user in the last period:

```
function MYMODULE_count_nodes($uid, $days) {
  $seconds = $days*24*60*60;
  $period = REQUEST_TIME - $seconds;
  $count = db_query("SELECT COUNT(*) FROM node WHERE uid=$uid AND status=1 AND created >= $periode")->fetchField();
  return $count;
}

```

Afterwards, I've created a Rule where the condition evaluates this code:

```
$count= MYMODULE_count_nodes($uid, 10);
return $count == 5;

```

Mind that the variable `$uid` isn't always provided directly in the Rule. In my case I used `$uid = $flagged_node->uid;`
> 0 votes

# Answer
I don't think rules by itself has the capability to do that - unless you get very deeply embedded into components, and by then it's almost the same as programming.

You probably need to write a custom module with a cron hook that checks how many nodes were created in the last 10 days. Do you want to know how many nodes were created at all, or just by a particular user? Either way that seems the best way to do it.
> 1 votes

---
Tags: 7, rules
---


# Question
Title: How to replace a Token in the PHP evaluation of a Rule?
I'm trying to grant Userpoints to users with a Rule. The Rule first calculates two integer values 'New value' and 'Old value'. Debugging these numbers shows that there's no problem with them. Naturally, I tried awarding the points with an action "Grant points to a user" and I'm using the following code in the PHP evaluation:

```
if ($value > 5) {
  return 0;
}
else {
  return token_replace('[new-value]');
}

```

where the default `$value` is *old-value*. As the `[new-value]` token is available in the data selectors of the 'Points' section of the action, I suppose that one can use it in the PHP evaluation too. Therefore, after reading Token Replacements, I thought my code should work, but it doesn't: the Userpoints aren't granted to the user.

There's definitively something wrong with the Token, because the Rule is executed correctly when I use `1` instead of `token_replace('[new-value]')`.

What am I doing wrong and how can I solve this?

# Answer
I still don't know what went wrong, but I've solved the problem in an alternative way. Everything works fine when you follow the steps underneath.

1. Save the integers *Old value* and *New value* as variables.
2. Add a third variable *Result*. Thanks to step 1, one can use `$old_value` and `$new_value` in the PHP evalution of this variable. I've used this code:

```
if ($old_value > 5) {
  return 0;
}
else {
  return $new_value;
}

```
3. Convert *Value* to an integer *Final value*.
4. Award *Final value* Userpoints to the user of your choice.
> 0 votes

---
Tags: 7, rules, tokens
---


# Question
Title: How to fallback to default language when listing nodes in a view if no translation is available
I have a list of projects, mostly in english, but some are translated in French.

When i visit the French version of my website, how can I list all projects that are translated in French and if no translation is available for a specific node, display the english counterpart.

Is that something possible in the view UI ? Or I'm guessing with a hook\_query\_alter.

Thanks,

# Answer
> 0 votes
Try the Alternative Language Module. There a lot of sub modules, but the base one will give you the functionality you are looking for.

> Allows a language to specify an alternative language. If a node translation for a specific language does not exist, Drupal will try to load the translation for the alternative language before throwing a 404.
>
> This module is useful if you have multiple languages and only one language is typically translated. Rather than create all of the other translations and maintain those, the non-translated languages can load the node from the alternative language.
>
> For example, you have the following language configuration:
>
> * / - US English - default
> * /en-ca - Canada English - alternative language is US English
> * /fr-ca - Canada French
>
> There is a node /contact, you will get three URL's:
>
> * /contact - US English
> * /en-ca/contact - Canada English
> * /fr-ca/nous-joindre - Canada French
>
> There are only two versions of the node, US English and CA French. The CA English uses it's alternative language and loads the US English version so all three pages work and the URL's are correct.

---
Tags: views, i18n-l10n
---


# Question
Title: Hooking a JS script at node submission to alter data submitted
I am building a website in which a lot of the text comes from Word docs. The problem is that when you copy from a Word doc to WYSIWYG editor, the resulting HTML and CSS is horrible.

I want to implement a JS script that will run whenever a node (Drupal's basic page) is created or updated, to clean and optimize the data.

I've seen that I must create a custom module and use a hook. Looking through the list of Drupal 7's hooks, I've noticed `hook_node_submit()` which seems perfect but in it's documentation (here) is written:

> This hook is intended for adjusting non-field-related properties.

So:

1. Do I have any other method simpler than module?
2. What is the correct hook I should use?

# Answer
You can look into either https://www.drupal.org/project/sanitizable or https://www.drupal.org/project/pasteformat both does the job.

and if you are looking hook based solution, i would suggest you `hook_node_presave` worth looking their documentation.
> 2 votes

# Answer
Give a try for Paste Format module. Module page says

> Paste Format allows you to clean-up the text you copy/paste into your content from other web pages, MS documents, e-mail clients, etc.

There is another module as Sanitizable. Module page says

> The Sanitize module allows administrators to configure a text format to be applied to formatted text before storage. This is useful to ensure clean and valid data in the database.

The major difference among two seems to the time even sanitization happens. Looks like paste format will do the time you will paste the text, which will help in showing the data which actually goes to database while the other module does it before node save, so user sees the unprocessed data before save.
> 1 votes

---
Tags: nodes, hooks, javascript
---


# Question
Title: How to make link unchangeable when using Pathauto?
Link for each node is made with Pathauto based on several fields. Those fields are required so when user makes the node first time, link is generated.

I would like to leave these links unchangeable if user changes something later in those fields (which is needed).

I consider this would be better solution then auto301 each link as this would cause thousands of them later on which is bad for SEO.

How to make link that is created first time by Pathauto unchangable even if the user changes fields that are part of pathauto tokens ?

# Answer
This is an option in the pathauto settings (**Configuration » Search and metadata » URL aliases » Settings**) under **Update action**. Set it to *Do nothing. Leave the old alias intact.* and pathauto will not update the path alias after its initial creation.
> 1 votes

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


title: Contact form on maintenance mode page

text:
# Question
Title: Contact form on maintenance mode page
I'm using Drupal 7 and I wanted users to be able to contact me via email whilst I'm still working on the website. So my plan was to use 'create a contact form', as I don't want to expose my email address.

However whenever I try to add an `input` element in the maintenance mode message it is completely ignored in the output. I think that this is because the message uses the filtered HTML file as I do have other bits of HTML the message that are rendering just fine, but I can't see any option to change which filter is used.

Is there a way to change the filter to full HTML or is there a better a option?

# Answer
If you are comfortable with Custom coding, you can try following route

On your theme template.php implement template\_preprocess\_maintenace(), this will help you introducing new variables to maintenance page tpl file, something like below

```
function yourtheme_name_preprocess_maintenance_page(&$vars) {
  if (function_exists('_your_form_builder_funtion')) {
    $vars['your_custom_form'] = drupal_render(drupal_get_form('_your_form_builder_function'));
  }
}

```

Now copy the maintenance-page.tpl.php in your custom theme templates folder and on the template file, you can use the variable like any other being already used. So somewhere on your maintenance-page.tpl.php add following

```
  <div class="contact-form">
    <?php print $your_custom_form; ?>
  </div>

```
> 0 votes

---
Tags: 7, emails, maintenance-mode
---


# Question
Title: How to notify a user who's mentioned in a comment?
I'm using the Message module to notify users when someone commented on one of their nodes. I'd like to extend this mechanism and also let users know when they're mentioned (e.g. *@user*) in a comment.

I tried setting up the following Rule:

* **Event:** After saving a new comment.
* **Condition:** Text comparison: comment contains `@`.
* **Action:** Create a new entity: message.

I should now determine whether the text after `@` is a user and, if so, store it to use it in the action. The problem is that I don't know how to do that. Another tricky constatation is that the username can contain spaces. After asking How to prevent users from being registered when their username contains a space?, I've made sure that usernames never contain spaces.

Is it possible to solve my problem by working on with Rules or is there another solution (coding, I suppose)?

# Answer
First, let me remind you that this solution will only work when usernames don't contain spaces. Our main goal is to get an array of the uid's of the users that were mentioned in a comment and then use this array to notify the users with a Message. In my code, one can mention a user by using *@user*, but the `@`-sign can be replaced by every desired character.

1. Write a function `MYMODULE_users_in_comment($text, $array)` that returns an array with all the words after a `@`-sign. Useful links to do this are:
2. Write a function `MYMODULE_uid_users_in_comment($text)` that replaces every valid username in the output of the previous function with that user's uid. Use `user_load_by_name()` for this and read Delete an element from an array to delete invalid 'usernames'.
3. Implement `MYMODULE_comment_insert()` and `MYMODULE_comment_update()`: loop over the elements of `MYMODULE_uid_users_in_comment($comment)` in order to create a Message for every user. You can find more information about how to create Messages programmatically here and in the message\_example.module file of the Message module.

Of course, in the final step, you can use the array of uid's for other notifying tools as well (e.g. email).
> 1 votes

# Answer
You can do it this way:

1. Copy the function `function mentions_get_mentions($text)` from mention module repo, It's defined on line 359.
2. Unfortunately I can't say if the regex from *mention* module actually works for user's with space in their name, and the function doc comment is not helpful either. So you could use your own regex

# What kind of regex?

```
#\s?@([a-zA-Z0-9 ])+(?|[^a-zA-Z0-9 ]|$)#

```

### How did I do it?

```
#                  : Identifies beginning of the RegEx pattern.
(?|^|[^a-zA-Z0-9]) : match any non-username chars or beginning of subject string.
@  : A plain @ char is needed.
([a-zA-Z0-9 ])+    : match any username char after a "@" including whitespace.
(?|$|[^a-zA-Z0-9]) : match any non-username chars or ending of subject string.
#                  : Identifies ending of the RegEx pattern.

```

Now all you have to do is to write a custom rule, pass it a text variable, and get list of user entities (or uid's) back. You could make sure users who matched through regex actually exists in database too.

# A few more notes

* A ? in regex causes the group **NOT** to appear in matched groups. Useful when you need to define a *group* but don't need it in the array of matched strings.
* ^|\[^a-zA-Z0-9\] means beginning of subject string or (the | is or) any char which is **NOT** (said by ^ in \[\]) in ranges a-z, A-Z and 0-9.

# Does this regex have bugs? yes

* The returned user name(s) from regex can have an space at the end of their name, you could trim each name. *It will be easier than to fix it in the regex pattern IMO*.
* It displays a funny character in my shell when matching an string with unicode characters in them. preg\_match supports such multi-byte characters though, and the u flag dis not work.

But again first check the function from mentions.

References:

Mentions module
PHP preg\_match doc
Writing custom rules for drupal, Rules DEV doc
Writing custom rules, A blog tutorial

one more thing I couldn't find in google right now: there is a module for rules which provides text tools, I think it had regex matching and you wont need a custom module.

# What is this "Regex" you're talking about all the time anyway?

RegEx stands for Regular Expression. It's a search pattern and is extremely very powerfull. While itself can be complicated (sometimes), many task which usually take a lot of time and effort to be done, such as parsing a text, can be done using regex in one line!
In this case we are looking for usernames in a paragraph in order to turn them into links. First we describe what a username looks like (the text patterns of username): *any* part of text which begins with letter, followed by a sequence of more letters *and* numbers.
Then we write it as a RegEx (What I've done here) and later extract usernames by passing both text and RegEx pattern to preg\_match function and taking usernames array back (the function is preg\_match).
If I want to talk about all the benefits it wont fit in here, so I suggest you a little search on duckduckgo. It's a handy tool to have, a powerful one try to learn it :)
> 1 votes

---
Tags: 7, comments
---


# Question
Title: Is the "www" in the database for the site confguration?
I have recently helped launch a site and there are some cross domain issues between "www.website.com" and "website.com"

I was chatting with Cloudways tech support and he mentioned that if I remove the "www" from the database for my site settings I wouldn't be having the issue.

What I ended up doing was modifying the `.htaccess` to redirect to "www.website.com" for now, but I still have the question: Is the "www" for the domain name in site information stored in the database? If so, would you really want to edit that?

# Answer
No its not there in database.

It depends on global $base\_url variable.

How drupal define this variable is based on super global $\_SERVER\['HOST'\] variable, which is basically depends on how the request was sent with/without www.

But you can override global $base\_url in your settings.php $base\_url = 'http://yoursite.com'
> 3 votes

---
Tags: database, subsites
---


title: drush only runs with sudo

text:
# Question
Title: drush only runs with sudo
When I run `drush` without `sudo` I get the header plus: `drush` is designed to run via the command line. Drush with `sudo` works as intended.

I have read that: You do not need root-level permissions to use Drush: it'll work as long as the user invoking it has direct access to the Drupal installation directory.

This does not seem to be true in this case. Even when I `su` to the exact user that owns the Drupal installation, I still cannot run Drush without the error message.

```
drwxr-xr-x 10 ouruser www-data     4096 May 18  2012 html

```

Is there something incorrect about permissions or is there another problem going on?

# Answer
> 1 votes
Greggles comment is most likely correct. Check your php path my going to the phpinfo path in the reports section. The URL is `admin/reports/status/php`.

# Answer
> 0 votes
As per Greg comment:

> Sounds like are using a different PHP with `sudo` than without. Check `$PATH` in both environments. You should be using php-cli with Drush; looks like you are using php-cgi without `sudo`. Fix your `$PATH` in the non-sudo environment so that the same php executable is selected as is in the `sudo` case.

---
Tags: drush
---


title: Get Drupal username

text:
# Question
Title: Get Drupal username
On my website I use the module PayPal Donations. When you donate money, the module get various info from PayPal using IPN callbacks. In a block, I show a list of people who have donated money. However, instead of using the username that is delivered by PayPal, I want to use the username from Drupal.

Unfortunately, my attempt to use the Drupal username does not work. *Drupal doesn't write anything in the username field.*

This is what I tried:

I've found the following code:

```
global $user;
print $user->name;

```

This works beautifully and displays the username of the current logged in user.

So I wanted to use some of this code to replace the first name and last name (which comes from PayPal) with the Drupal username.

This code adds add the first and last name from PayPal to the database.

```
$entity->field_paypal_donator_name[LANGUAGE_NONE][0]['value'] = $_POST['first_name'] . " " . $_POST['last_name'];

```

In the top of the document, I've written `global $user;` and I've replaced

```
$entity->field_paypal_donator_name[LANGUAGE_NONE][0]['value'] = $_POST['first_name'] . " " . $_POST['last_name'];

```

with

```
$entity->field_paypal_donator_name[LANGUAGE_NONE][0]['value'] = $user->name;

```

The full code is the following one.

```
/**
 * @file
 * Handling the PayPal IPN callbacks
 */

/**
 * IPN callback function().
 */

  global $user;

function paypal_donations__ipn_callback() {
  $paypal_host = variable_get('paypal_donations_service_url', 'www.sandbox.paypal.com');
  header("Content-type: text/html");
  header("Expires: Wed, 29 Jan 1975 04:15:00 GMT");
  header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  header("Cache-Control: no-cache, must-revalidate");
  header("Pragma: no-cache");

  // Read the post from PayPal system and add 'cmd'.
  $req = 'cmd=_notify-validate';

  foreach ($_POST as $key => $value) {
    $value = urlencode(stripslashes($value));
    $req .= "&$key=$value";
  }

  $header = '';

  // Post back to PayPal system to validate.
  $header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
  $header .= "Host: " . $paypal_host . "\r\n";
  $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
  $header .= "Content-Length: " . strlen($req) . "\r\n\r\n";

  $fp = fsockopen('ssl://' . $paypal_host, 443, $errno, $errstr, 30);

  if (!$fp) {
    watchdog('paypal', 'HTTP error');
  }
  else {
    fwrite($fp, $header . $req);
    watchdog('paypal', $header . $req);

    while (!feof($fp)) {
      $res = fgets($fp, 1024);
      if (strcmp($res, "VERIFIED") == 0) {
        global $user;

        if (!empty($_POST['txn_id'])) {

          if ($_POST['txn_type'] == 'web_accept') {
            $donation_type = 'single';
          }
          elseif ($_POST['txn_type'] == 'subscr_payment') {
            $donation_type = 'recurring';
          }

          $entity = new stdClass();
          $entity->field_paypal_transaction_id[LANGUAGE_NONE][0]['value'] = $_POST['txn_id'];
          $entity->field_paypal_donator_email[LANGUAGE_NONE][0]['value'] = $_POST['payer_email'];
          $entity->field_paypal_donations_amount[LANGUAGE_NONE][0]['value'] = $_POST['mc_gross'];
          $entity->field_paypal_donator_name[LANGUAGE_NONE][0]['value'] = $user->name; // my attempt to use the Drupal username instead of the PayPal first name.
          //$entity->field_paypal_donator_name[LANGUAGE_NONE][0]['value'] = $_POST['first_name'] . " " . $_POST['last_name']; // original line
          $entity->field_paypal_donator_country[LANGUAGE_NONE][0]['value'] = $_POST['address_country'];
          $entity->field_paypal_donations_type[LANGUAGE_NONE][0]['value'] = $donation_type;
          $entity->created = time();

          entity_save('paypal_donations_item', $entity);

          module_invoke_all("paypal_donations_made", $entity, $_POST);
          watchdog('paypal', 'Paypal payment received with transaction id @txn_id.', array('@txn_id' => $_POST['txn_id']), WATCHDOG_NOTICE);

          drupal_mail('paypal_donations', 'payer_confirmation', $_POST['payer_email'], user_preferred_language($user), array(
            'first_name' => $_POST['first_name'],
            'amount' => $_POST['mc_gross'],
            'donation_type' => $donation_type,
          ));

          drupal_mail('paypal_donations', 'admin_confirmation', $_POST['receiver_email'], user_preferred_language($user), array(
            'name' => $_POST['first_name'] . " " . $_POST['last_name'],
            'amount' => $_POST['mc_gross'],
          ));
          }
        }
      }
    fclose ($fp);
  }

  die();
}

```

(The altered line is 11 \[added global $user;\] and line 64 \[where I try to use $user-\>name; to get the Drupal username\].)

I'm no expert in PHP and this is my (poorly?) attempt to use the Drupal username instead of the first and last name coming from PayPal.

Can anyone tell my why it doesn't work?

# Answer
The global `$user` object is loaded based on the user's *session*, which is identified by looking up the value of their session cookie in (usually) the database. However, the PayPal IPN request is not made by the user: it comes directly from PayPal's servers to yours; so it doesn't contain the user's session cookie.

Not sure what's the best way to fix that. Ideally the module would record the user ID and associate it with the transaction ID, and look that up to find the correct user object. If it doesn't, you may want to file a bug report. Note that the module seems to *expect* the `$user` object to be correctly populated, as it attempts to use it for localisation of notification emails - which apparently isn't working either - so this probably really is a bug.
> 1 votes

# Answer
Have you tried declaring your variable from inside of your callback ?

```
function paypal_donations__ipn_callback() {
  global $user;
  $paypal_host = variable_get('paypal_donations_service_url','www.sandbox.paypal.com');
  header("Content-type: text/html");
}

```
> 0 votes

# Answer
I think you might have missed adding those property to the custom Entity defined by paypal\_donations module.

In order to add the field visit 'admin/structure/paypal\_donations/manage/fields' and add a text field to hold value for user name and make sure machine name of the field should be same as you are using in the code, currently you are using machine name as 'field\_paypal\_donator\_name'.
> 0 votes

---
Tags: users
---


# Question
Title: Rules data comparison: compare node field with a group
How to use rules to compare a field from the node with a specific Organic Group?

I am using rules event after saving new content of type X. Now I need to specify if in the field field\_group the value is a specific group.

I am able to get the field of the node, but have no clue how to be able to compare it with a group I want.

# Answer
> 1 votes
**Ok, lets assume that your group name is called "Pokemon"**

1) Under Conditions, click on Add Condition.

2) In the drop down, select TEXT COMPARISON

3) Click on the Blue Link that says (DATA SELECTORS)

4) Look for your field, if you named it "group", then look for node:field-group

then highlight it, copy and paste it under Data Selector\*

7) Under Matching Text put **Pokemon**

8) click SAVE

*Note: obviously, replace Pokemon with your actual group name.*

---
Tags: rules, organic-groups
---


# Question
Title: Permissions to create a database with drush command?
If I use this line to install a drupal site it only runs fine if the 'mydb' database already exist.

If the database doesn't exist I get an error. Is there other drush command to make an installation when the database doesn't exist?

```
drush si --db-url=mysql://root:root@localhost:8889/mydb

```

I don't think is a user permission since the **root** user has all privileges enabled. Look the picture. I use MAMP (the free version)

I this other capture you can see the connection parameters:

# Answer
> 3 votes
I don't think Drush has an option for this built into the `site-install` method but you might find something under the `sql-sync` method, which I think has an option to create a database.

I don't know if it's appropriate for your situation but you might want to look at the Drupal Quickstart: Pre-made Development environment; it has a bunch of custom Drush commands included, one of which will set up an entire site (vhost file, database, file permissions, etc.) in one line:

```
drush quickstart-create all --domain=example1.dev

```

I've copied this command out and hacked it to pieces, and now I can install a fully configured Drupal site on my local Mac machine with a single terminal line:

```
drush isosc --domain=example.dev

```

I would thoroughly recommend doing this; I couldn't live without it now

# Answer
> 1 votes
`drush site-install \
 standard --account-name=admin \
--account-pass=admin \
 --db-url=mysql://YourMySQLUser:RandomPassword@localhost/YourMySQLDatabase`

This command create a completed installation (included db).

# Answer
> 0 votes
Looks like you have problem with your system variables. Enter "mysql" in cmd and check if it works correctly.

If it works then you would have some other issue. If doesn't then make it work by pasting your mysql.exe path usually "C:\xampp\mysql\bin" into PATH system environment variable.

---
Tags: drush
---


title: .trigger("click") not firing

text:
# Question
Title: .trigger("click") not firing
I'm trying to automatically launch a dialog box containing an iframe if the user's cursor gets within 25 pixels of the top of the browser window.

In the code, a simulated click of a hidden button should open a dialog box which then loads an iframe containing information inside of a hidden div. However, the code doesn't seem to be executing. What am I doing wrong?

I'm working with Drupal 7. I'm sure there's a far more elegant way of accomplishing my goal, but bear with me right now.

```
<?php
drupal_add_js('https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js','external');
drupal_add_js('https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js','external');
drupal_add_js('jQuery(document).ready(function() {
    jQuery(document).mousemove(function(e) {
      if (e.pageY<=25) {
     jQuery("dialog_trigger").trigger("click");
        jQuery("#dialog_trigger").click(function()
        {

        jQuery("#dialog").dialog("open");
      });
    }
    });
});
    jQuery("#dialog").dialog({
        autoOpen: true,
        position: "center",
        title: "         ",
        draggable: true,
        width: 800,
        height: 700,
        resizable: false,
        modal: true,
    });', 'inline');
?>

<div id="dialog" style="display:none;" title="Dialog Title">
    <iframe frameborder="0" scrolling="yes" width="700" height="650" src="http://google.about.com/b/2013/04/01/google-nose.htm" style="padding-left:50px;> </iframe>
</div>

```

# Answer
Never mind. I figured it out:

```
<?php
drupal_add_js('http://code.jquery.com/jquery-1.9.1.js','external');
drupal_add_js('http://code.jquery.com/ui/1.10.1/jquery-ui.js','external');
drupal_add_js('jQuery(document).ready(function() {

jQuery(document).mousemove(function(e) {

if (e.pageY<=5) {
        jQuery("#dialog").dialog("open");
}
});

    jQuery("#dialog").dialog({
        autoOpen: false,
        position: "center",
        title: "         ",
        draggable: true,
        width: 850,
        height: 700,
        resizable: false,
        modal: true,
    });

});', 'inline');
?>

<button id="dialog_trigger" style="display:none;">Open The Dialog</button>
<div id="dialog" style="display:none;" title="Dialog Title">
    <iframe frameborder="0" scrolling="yes" width="800" height="650" src="http://www.google.com" style="padding-left:25px;"> </iframe>
</div>

```
> 2 votes

---
Tags: javascript
---


# Question
Title: Fast way to make all menu-links "Show as expanded"?
Is there a way to automatically make all menu-links in all menus whatsoever "Show as expanded"?

I have about 4 menus that contain many links and it's not serious to pass one by one and click "show as expanded".

Is there a module or a script that will do that automatically? Thanks,

# Answer
Try using menu block and create block what level you want to trail you menu. You can also use menu expanded as per your requirement. Menu expanded is not well maintained.
> 1 votes

---
Tags: routes
---


# Question
Title: How to render a ctools content type programmatically?
I have a ctools plugin aka. content-type aka. panel pane. How does one render it programmatically ?

# Answer
`ctools_content_render()` is the solution.
> 4 votes

# Answer
There is a great and simple example on how to do this in the `ctools_ajax_sample` module (in the CTools suite).

As it has been pointed out, the key is to use the function `ctools_content_render()`.

The example shows how to populate the arguments of the function, although you obviously have to customize it according to your needs.

This thread in Drupal Groups gives more insight on how to load the right context.

File `ctools/ctools_ajax_sample/ctools_ajax_sample.module`

```
function ctools_ajax_simple_form() {
  ctools_include('content');
  ctools_include('context');
  $node = node_load(1);
  $context = ctools_context_create('node', $node);
  $context = array('context_node_1' => $context);
  return ctools_content_render('node_comment_form', 'node_comment_form', ctools_ajax_simple_form_pane(), array(), array(), $context);
}

function ctools_ajax_simple_form_pane() {
  $configuration = array(
    'anon_links' => 0,
    'context' => 'context_node_1',
    'override_title' => 0,
    'override_title_text' => '',
  );
  return $configuration;
}

```
> 3 votes

# Answer
If you load the required file, all you really need to do, is to call the render function (`hook_content_type_render`) which will return a standard class object, much like `hook_block_view` does.
All you need from there is a theme function, unless you just want to render the raw output directly.

In code it could look something like this:

```
function render_ctools_content($subtype, $conf, $panel_args, $context, $function, $file, $theme = TRUE) {
  require_once $file;
  $pane = new stdClass();
  if (function_exists($function)) {
    $pane = $function($subtype, $conf, $panel_args, $context); // hook_content_type_render
  }
  if ($theme) {
    return theme('module_ctools_content', array('pane' => $pane));
  }
  return $pane->content;
}

```
> 2 votes

# Answer
I was able to pull a panelized page in panopoly using the following code:

```
module_load_include('inc', 'page_manager', 'plugins/tasks/node_view');
$node = node_load($nid);
$render = page_manager_node_view_page($node);
echo drupal_render($render);

```
> 0 votes

---
Tags: chaos-tool-suite
---