# Question
Title: pass php page to page callback with hook_menu
I'm developing a module where I use `hook_menu`.

I know that I can pass to 'page callback' a function that return string with HTML/PHP code.

```
function mymodule_menu(){
    $items = array();

    $items['test'] = array(
        'title' => 'page test',
        'description' => 'my test',
        'page callback' => 'my_page',
        'access arguments' => array('access content'),
        'type' => MENU_NORMAL_ITEM,
        'menu_name' => 'main-menu',
    );

    return $items;
}

function my_page(){
    return '<h1>hello</h1>';
}

```

How can I pass a whole PHP/HTML page as an argument to `'page callback' => '[my_page.php]'` instead of creating a string inside `my_page()` function ?

# Answer
> 7 votes
The value to 'page callback' can only be a function name.

If you must use 'a whole PHP/HTML page' then work around by using the hook\_theme.

```
<?php
function my_example_menu() {
  $items['my/example'] = array(
    'title' => 'My title',
    'page callback' => 'my_example_page', /* callback function */
'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
);

return $items;
}

/**
 * Implements hook_theme
 *
 */
function my_example_theme($existing, $type, $theme, $path) {
  return array(
    'the_html_page' => array(
    'template' => 'the-html-page', /* create file with this name + .tpl.php */
  ),
);
}

function my_example_page(){
  return theme('the_html_page');
}
?>

```

The value of 'template' in hook\_theme() is the name of your file. Create the template file with .tpl.php extension and place it in the same directory as your module. You can put any html that you need in the file.

---
Tags: 7, routes
---


# Question
Title: Fix/force blocks in a region inside a tableDrag
I'm trying to alter/patch/hack `node_level_blocks` (like the admin blocks overview page) so that some users are restricted in choosing regions for certain blocks. For instance the "New Content" view must always be in the Right region. The normal user can change the weight and add more blocks to that region, but they can't remove that block from that region.

What I did (I'm pretty close):

* Form alter the `<select>` to that it contains only 1 option
* Override `Drupal.tableDrag.blocks.onDrag` to fix and improve the standard tableDrag handler and make the row jump back to its forced position

That works, but the user can still drag the block around to regions it doesn't belong. (I don't have a demo online.)

How do I tell tableDrag to NOT let some blocks out of their original regions? I don't understand its 400 options...

# Answer
The checking-magic comes from `Drupal.tableDrag.prototype.row.prototype.isValidSwap` and you can override that to add a custom validation. This solved my problem:

```
// onDomReady: override Drupal.tableDrag.prototype.row.prototype.isValidSwap to add swap-validation.
jQuery(function($) {
  if (Drupal.tableDrag) {
    var _isValidSwap = Drupal.tableDrag.prototype.row.prototype.isValidSwap;
    Drupal.tableDrag.prototype.row.prototype.isValidSwap = function(tr) {
      // Do standard tableDrag validation.
      var valid = _isValidSwap.apply(this, arguments);
      if (!valid) {
        return false;
      }

      // One of us?
      var $select = $('.form-select', this.element),
        loner = $select[0].options.length <= 1;
      if (loner) {
        // Can't swap with non-draggables, since that would mean a boundary.
        if (!$(tr).is('.draggable')) {
          return false;
        }

        // Can't skip over any rows, since that might be a boundary.
        var diff = tr.rowIndex - this.element.rowIndex;
        if (Math.abs(diff) > 1) {
          return false;
        }
      }

      return true;
    };
  }
});

```

All thanks to Mołot of course.
> 1 votes

---
Tags: blocks
---


# Question
Title: Synchronizing Database Configuration Across Environments
I am the sole developer on a Drupal 7 site, and I need advice. I use Git, having a 'master' branch (the published version of the site) and a 'dev' branch (the experimental features for future versions of the site).

Using Capistrano for deployment, I've gotten it fairly easy to deploy the two branches to their respective URLs, but I'm up against this wall where I'm not sure how to merge the 'dev' branch database into the 'master' branch after the new features are ready for production.

With a lot of Drupal's structure stored in the database, like Content Types and Views, what solutions are there for merging database changes from the 'dev' branch's url to the 'master' branch's url? So far, I've been writing down the changes I make and then recreating them on the production site before I merge the dev branch back into the master branch.

# Answer
> 1 votes
You cannot reliably 'merge' database copies. One way or another, everything has to be managed through code.

In Drupal 8 this is handled with the Configuration Initiative, but in D6 and D7 you have to use a tool like the Features module, which provides an interface to create 'features' (which are really exportable content stored in specific modules). You can export things like site configuration, content types, views, etc. into a feature, then push the code from one branch to another, and have that feature's changes "apply" on to the new database.

The Features module has its share of problems, but it does work fairly well for the most part, and is the go-to solution for managing database changes.

In addition to Features, you'll likely also want Strongarm, which lets you use Features to export data from the `variables` database table.

Alternatively, many people use update hooks to handle their database changes; that's a bit more involved and requires a strong understanding of Drupal development.

You may also want to read through these resources:

---
Tags: views, database, deployment
---


title: Page Arguments and Dynamic Pages

text:
# Question
Title: Page Arguments and Dynamic Pages
I am trying to make dynamic pages using hook menu which is going fine but the problem is I want to add page arguments for the states. For example if someone goes to the url and there isnt a state in the url like california for example(site/listings/california) it would show a page not found error, and if found it would list the listings I have looped out in my function.

Any Suggestions?

```
/*
** Hook Menu
*/

function listings_menu() {
    $items = array();

    $items['site/listings/%'] = array(
        'title' => 'City Listings',
        'page callback' => 'business_listings',
        'access arguments' => array('access content'),
        'page arguments' => array('states', 'city_names'),
    );

    return $items;
}

/*
** State Listings
*/

function listing_states($state){
    $state = array(
        'alabama' => t('Alabama'),
        'alaska' => t('Alaska'),
        'arizona' => t('Arizona'),
    //ect.....

    );
    return $state;
}

/*
** Company Listings
*/

function business_listings(){

    $states = listing_states(arg(2));

    $dbquery = db_query("SELECT DISTINCT CityName FROM {zipcodes} WHERE StateName = '".ucfirst(arg(2))."' ORDER BY CityName ASC");

    $cityname = '';
    $cityname .= '<div class="city-wrapper">';
    foreach ($dbquery as $dbrow) {
        $cityname .='<div class="cityname" style="float:left; width:200px;">';
        $cityname .= '<a href="'.arg(2).'/'.strtolower(urlencode($dbrow->CityName)).'">'.$dbrow->CityName.'</a>';
        $cityname .= '</div>';
    }
    $cityname .= '</div>';

    return array('states' => $states, 'city_names' => $cityname);
}

```

# Answer
Update your menu callback to pass the third argument (state) to the page callback:

```
$items['site/listings/%'] = array(
  'title' => 'City Listings',
  'page callback' => 'business_listings',
  'access arguments' => array('access content'),
  'page arguments' => array(2),
);

```

Then update your page callback to use the new argument, validate it against the items returned by `listing_states()` (which doesn't look like it needs to accept an argument), and throw a 404 if validation fails:

```
/**
 * State Listings
 */
function listing_states() {
  $states = array(
    'alabama' => t('Alabama'),
    'alaska' => t('Alaska'),
    'arizona' => t('Arizona'),
    // ...
  );

  return $states;
}

/**
 * Company Listings
 */
function business_listings($state) {
  $all_states = listing_states();

  if (!isset($all_states[$state])) {
    drupal_not_found();
  }

  // your other code here
}

```

Additionally, you should really read up on Drupal's coding best practices, as there are numerous issues with your code. Other than formatting, your query is vulnerable to a SQL injection attack, your markup should be in a template file or a theme function, your CSS should be in an external CSS file, and your link should be using the `l()` function (or at least `url()` for the `href` attribute).
> 1 votes

# Answer
I believe you want to change your listings\_menu()

```
function listings_menu() {
    $items = array();

    $items['site/listings/%'] = array(
        'title' => 'City Listings',
        'page callback' => 'business_listings',
        'access arguments' => array('access content'),
        'page arguments' => array(3),
    );

    return $items;
}

```

Then you need to change your listings to accept that argument

```
function business_listings($states){
  $states = listing_states($states);

  $dbquery = db_query("SELECT DISTINCT CityName FROM {zipcodes} WHERE StateName = '".ucfirst(arg(2))."' ORDER BY CityName ASC");

  $cityname = '';
  $cityname .= '<div class="city-wrapper">';
  foreach ($dbquery as $dbrow) {
      $cityname .='<div class="cityname" style="float:left; width:200px;">';
      $cityname .= '<a href="'.arg(2).'/'.strtolower(urlencode($dbrow->CityName)).'">'.$dbrow->CityName.'</a>';
      $cityname .= '</div>';
  }
  $cityname .= '</div>';

  return array('states' => $states, 'city_names' => $cityname);
}

```
> 1 votes

---
Tags: 7
---


# Question
Title: Error when using hook_form_comment_form_alter()
I am using the following function in template.php to modify the comment form to remove the form title and add a default value inside the form:

```
/**
* Implements hook_form_comment_form_alter().
*/
function mytheme_form_comment_form_alter(&$form, &$form_state, $form_id) {

    $form['subject'] = array(
      '#type' => 'textfield',
      '#maxlength' => 255,
      '#attributes' =>array('placeholder' => t('subject')),
      '#required' => FALSE,
    );

    $form['comment_body'] = array(
      '#type' => 'textarea',
      '#maxlength' => 255,
      '#attributes' =>array('placeholder' => t('comment')),
      '#required' => TRUE,
    );

}

```

It does the desired task but it causes an error where the form will submit but the contents entered into the body are not submitted and will not display. The following error gets generated:

```
Notice: Undefined property: stdClass::$comment_body in comment_submit()

```

Am I missing something within the function so the text inputed is actually submitted when saving the form?

# Answer
Turns out the correct way to add the placeholder was:

```
$form['comment_body'][LANGUAGE_NONE][0]['#attributes']['placeholder'] = t( 'comment' );

```
> 0 votes

---
Tags: comments
---


# Question
Title: Using jQuery $.ajax() on my site won't work
This is the first time for me to use the jQuery `$.ajax()` in Drupal. The code is a simple test code but it keeps going to the `error:` section instead of `success:`. Could my url path be wrong? The .js file and the `test-ajax.php` file are in the same folder named "code".

```
    //This is Javascript
    $.ajax({
        url: 'code/test-ajax.php',
        data: 'a=hello&b=world',
        type: 'POST',
        success: function(data){
            alert(data); //Should return "hello, world"
        },
        error: function(){
            alert('FAIL'); //Keep getting "FAIL". It's like it can't find the php file.
        }
    });

```

Nothing fancy inside the file `test-ajax.php`:

```
<?php
$a = $_POST['a'];
$b = $_POST['b'];

echo "$a, $b";
?>

```

**EDIT**: To avoid confusion on the paths (I keep it organized):

* **Main theme files:** `<templatename>/<.info, template.php, style.css, etc.>`
* **Template files:** `<templatename>/templates/*.tpl.php`
* **AJAX files:** `<templatename>/code/<PHP and .JS files>`

# Answer
> -1 votes
Thanks to everyone who's commented (especially @jcisio)! Based on all your answers, I was able to come up with the `THEMEPATH` global variable which stores the complete path to the theme by using `drupal_add_js()`.

```
drupal_add_js( array( 'themepath' => base_path() . path_to_theme() ), 'setting' );

```

Which you can then reference in your .js file as

```
var THEMEPATH; //a global variable
$(function(){
    THEMEPATH = Drupal.settings.themepath; //assign the variable
})

//THEMEPATH has to be assigned on page load and not before or else it won't work

```

So in the end, you simply use it in jQuery as: `THEMEPATH + '/code/test-ajax.php'`. I'm surprised Drupal doesn't have this by default.

# Answer
> 1 votes
In Drupal, JavaScript files are added via the `drupal_add_js()` function or in the theme’s .info file. A simple example of using jQuery in drupal is

```
    <?php
    drupal_add_js('jQuery(document).ready(function () {
   jQuery.ajax({
        url: '/code/test-ajax.php',
        data: {'a':'hello','b':'world'},
        type: 'POST',
        success: function(data){
            alert(data); //Should return "hello, world"
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert(textStatus + errorThrown); //Better diagnostics
        }
    });
    });', 'inline');
    ?>

```

you have to use 'jQuery' instead of $.

# Answer
> 1 votes
Change

```
url: 'code/test-ajax.php',

```

to

```
url: Drupal.settings.basePath + 'sites/all/themes/YOURTHEME/code/test-ajax.php',

```

Anyway, the more Drupal way is to use hook\_menu to register your callback instead of putting a PHP file in your theme folder.

# Answer
> 0 votes
As with all programs, it's impossible to fix an error unless you know what's wrong.

jQuery will pass three parameters (`jqXHR, textStatus, errorThrown`) to the error function to help you determine what your problem is. You may be getting a `404` which means you need to fix your path (or flush your drupal cache to get the `hook_menu()` to be recognized). You may be getting a `500` which means you have a syntax error in your module. Or any of the other numerous problems you can encounter when using AJAX.

The documentation for these parameters is at http://api.jquery.com/jQuery.ajax/

# Answer
> 0 votes
I would write the same code like this:

```
//This is Javascript
    $.ajax({
        url: '/code/test-ajax.php',
        data: {'a':'hello','b':'world'},
        type: 'POST',
        success: function(data){
            alert(data); //Should return "hello, world"
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert(textStatus + errorThrown); //Better diagnostics
        }
    });

```

Note the following:

* URL is absolute (starts with /). If current page URL is node/x, then code/text-ajax.php will be looked up as node/code/text-ajax.php, which is (probably) wrong
* error handler has parameters, which gives your better diagnostics
* data is an object, not an URL string

# Answer
> 0 votes
I already commented on this under the answer given by Mujtaba but here it is as a proper answer.

You do not have to change all $ to jQuery for this to work. As per the Drupal 7 documentation, you just need to wrap your code like this:

```
(function($){
  $(document).ready(function(){
    ...
  });
})(jQuery);

```

Then you can just keep writing your code using $ and it assigns $ to jQuery. It's basically doing the same thing as just writing your code using jQuery instead of the $ but saves you the trouble of find and replace on existing code and saves you characters (and thus file size) when making your code from scratch.

# Answer
> -1 votes
How odd, I got it to work but only by using the complete URL path for the AJAX file.

```
url: 'http://mydomain.com/sites/all/themes/<themename>/code/test-ajax.php',

```

This just doesn't feel right. Is there a *Drupal way* of doing this instead of entering the complete URL path?

---
Tags: 7, ajax
---


# Question
Title: Page visible for authenticated user, not custom role
I have a custom module that has type MENU\_LOCAL\_TASK with path user/%/custom-page.

The page callback is displaying a content and with custom page arguments and access arguments functions, only the author of the content can see that content. So far so good.

I have authenticated users and custom role (editor).

Now my goal is to display the MENU\_LOCAL\_TASK with the page callback content only for the authenticated users, not the editor.

All authenticated users are with role\[3\] and the Editor is with role\[5\]. Because of the role "Editor" is automatically authenticated user I cannot set the custom page to be visible only for the other authenticated users.

On my page.tpl.php I've managed to display links that will be visible only for authenticated user without user with role\[5\] (editor) with this code and its working great.

```
<?php
if(isset($user->roles[3])){
    //visible only for roles[3], the ordinary authenticated users
}

```

How can I do this with my custom module?

I didn't find an examples in hook\_menu for roles.

Hook\_permission() didn't helped, because when I choose the authenticated user in drupal permissions UI, automatically marks the editor role.

I'm using Drupal 7.

# Answer
When declaring items in `hook_menu()`, you can specify a custom `access callback` property. This should be a function that returns `TRUE` if the user has access to the page.

In this function you can have a look at the global `$user` object (ie. the currently logged-in user) and determine whether to grant access or not:

```
/**
 * Implementation of hook_menu()
 */
function hook_menu() {
  $items['user/%/custom-page'] = array(
    'title' => 'Custom Page',
    'type' => MENU_CALLBACK,
    'page callback' => 'your_page_callback',
    'access callback' => 'custom_page_access',
    'access arguments' => array(1),
  );

  return $items;
}

/**
 * Access callback for /user/%/custom-page

 * @param  {[type]} $account [description]
 * @return {[type]}          [description]
 */
function custom_page_access($account) {
  // how do you want to handle role restrictions? if looking at the user
  // whose custom-page is being loaded, use $account, otherwise the global
  // $user object:

  global $user;

  // check that role id 3 IS set, and role id 5 is NOT
  if (isset($user->roles[3]) && !isset($user->roles[5])) {
    return TRUE;
  }

  return FALSE;
}

```

Don't forget to clear the site's cache (to rebuild the menu registry) after making these changes.
> 1 votes

---
Tags: hooks, users
---


# Question
Title: How can I change an image field programatically?
I'm trying to change the image field 'Badge' when an article is situated at the top of a view 'Top 3' after it has been updated. This is my custom module:

```
function top_node_update($node) {
    $top = views_get_view_result('top_3');
    $first = $top[0]->nid;

    if ($first == $node->nid) {
        $node->field_badge[0]['value'] = '/default/files/images/gouden_rozet.png';
        field_attach_update('node', $node);
    }
}

```

Unfortunately, nothing happens when I edit and save an article.

What's going wrong and how can I solve this?

---

**Edit:** Everything seemed perfectly fine after @undersounds answer, because the image fields were correctly changed by my custom module. I used the same piece of code to also edit the images of the second and third node in the view:

```
<?php

function top_node_update($node) {
  $top = views_get_view_result('top_3');
  $first = $top[0]->nid;
  $second = $top[1]->nid;
  $third = $top[2]->nid;

  if ($first == $node->nid) {
    $image = file_get_contents('public://images/gouden rozet.png');
    $file  = file_save_data($image, 'public://images/gouden rozet.png',FILE_EXISTS_REPLACE);
    $node->field_badge[LANGUAGE_NONE]['0']['fid'] = $file->fid;
    field_attach_update('node', $node);
  }

  if ($second == $node->nid) {
    $image = file_get_contents('public://images/zilveren rozet.png');
    $file  = file_save_data($image, 'public://images/zilveren rozet.png',FILE_EXISTS_REPLACE);
    $node->field_badge[LANGUAGE_NONE]['0']['fid'] = $file->fid;
    field_attach_update('node', $node);
  }

  if ($third == $node->nid) {
    $image = file_get_contents('public://images/bronzen rozet.png');
    $file  = file_save_data($image, 'public://images/bronzen rozet.png', FILE_EXISTS_REPLACE);
    $node->field_badge[LANGUAGE_NONE]['0']['fid'] = $file->fid;
    field_attach_update('node', $node);
  }
}

```

I started playing around a bit to see whether everything worked and discovered this: when a certain node has for example the 'bronzen rozet' image and moves to the first row in the view, the image is changed to 'gouden rozet' - as it should be - but the bronzen rozet.png file is also deleted in my images file!

How can I prevent this?

# Answer
```
function top_node_update($node) {
      $top = views_get_view_result('top_3');
      $first = $top[0]->nid;
      $second = $top[1]->nid;
      $third = $top[2]->nid;

  if ($first == $node->nid) {
    $image = file_get_contents('public://images/badges/gouden rozet.png');
    $file  = file_save_data($image, 'public://images/gouden rozet.png',FILE_EXISTS_REPLACE);
    $node->field_badge[LANGUAGE_NONE]['0']['fid'] = $file->fid;
    field_attach_update('node', $node);
  }

  if ($second == $node->nid) {
    $image = file_get_contents('public://images/badges/zilveren rozet.png');
    $file  = file_save_data($image, 'public://images/zilveren rozet.png',FILE_EXISTS_REPLACE);
    $node->field_badge[LANGUAGE_NONE]['0']['fid'] = $file->fid;
    field_attach_update('node', $node);
  }

  if ($third == $node->nid) {
    $image = file_get_contents('public://images/badges/bronzen rozet.png');
    $file  = file_save_data($image, 'public://images/bronzen rozet.png', FILE_EXISTS_REPLACE);
    $node->field_badge[LANGUAGE_NONE]['0']['fid'] = $file->fid;
    field_attach_update('node', $node);
  }
}

```

You should also try to prevent using functionality twice. So instead of the code above you can also write something like:

```
function top_node_update($node) {

  $top = views_get_view_result('top_3');
  $first = $top[0]->nid;
  $second = $top[1]->nid;
  $third = $top[2]->nid;

  if ($first == $node->nid) {
    $img_name = 'gouden rozet.png';
  }

  if ($second == $node->nid) {
    $img_name = 'zilveren rozet.png';
  }

  if ($third == $node->nid) {
    $img_name = 'bronzen rozet.png';
  }

  $image = file_get_contents('public://images/badges/' . $img_name);
  $file  = file_save_data($image, 'public://images/' . $img_name, FILE_EXISTS_REPLACE);
  $node->field_badge[LANGUAGE_NONE]['0']['fid'] = $file->fid;
  field_attach_update('node', $node);

```

}
> 2 votes

---
Tags: 7, media, nodes
---


# Question
Title: Views contextual filter on just ONE of the listed contenttypes
I'm not sure how I can accomplish this but I hope you can tell me. I have a view that lists 2 different contenttypes that has different filters.

Now, I want to use a contextual filter on just one of the contenttypes.

Is there any way I can accomplish this?

Best regards,

# Answer
That really depends on your specific view configuration. Generally speaking, you can add validation (e.g. what content type to accept as contextual filter) and a fallback behavior (e.g. ignore argument vs. show 404), see screenshot. With these instruments you can achieve pretty much.
> 0 votes

---
Tags: views
---


# Question
Title: Can the themeing and render api be accessed independently?
Are there de-coupled versions of the form rendering and theming APIs that can be used outside of the Drupal framework?

# Answer
> 3 votes
Not in Drupal 7 or earlier. There might be chances for Drupal 8. But in the currently available major versions of Drupal the mentioned components are still strongly integrated in the core system.

---
Tags: theming
---


# Question
Title: Views Module: Related Content by Title Only
How to make a "Related Content View" but **only** by titles.

I know how to do it by taxonomy terms and such I don't want that. I only want it to be related by the terms in the titles of the articles.

For example, lets suppose I have an article with the title: "Stackexchange Drupal Help by Awesomeness People"

I want to make related content View with other articles having title with the words "Stackexchange", "Drupal", "Help", "by", "Awesomeness" and "People"...

I just want related content filtered with the words from titles, to show other articles with this same words. If possible excluding words with less than 5 characters.

I'm trying this for days now, I think this is impossible, or at least I can not do it. Thank you in advance

# Answer
The way I achieved this was by using the **Apache Solr module** https://drupal.org/project/apachesolr

It has a "*More Like This*" feature that makes it easy to show related content, see the documentation for that module.
> 1 votes

---
Tags: views
---


# Question
Title: Is there a way to ask migrated users to complete their profile?
I hope to migrate users in the database (using Drupal 7).

How will I handle the fact that they have no password, and will need to create one before accessing their profile?

Password is currently on the Join Form and these migrated users shouldn't have to go through the Join form.

Also - what do you suggest for mass email?

Thanks!

# Answer
You can take help of Mass Password Reset module.

I had same kind of situation when I made a existing website of D6 into D7 & migrated users from there.
> 0 votes

---
Tags: users, emails, migrations
---


title: all nodes page not found

text:
# Question
Title: all nodes page not found
Drupal 7.26 multi-site , one of my sites is playing up. Error started with no login page until I realised all nodes except home were not found. So I tried putting in code in index.php to see errors but none showed up. Then I dropped the database and reinstalled settings to start with basic drupal install but after importing sql and again drush updating database still pages cannot be found excepting home page. Then went to ?q=user to login as admin and could see all the pages but clicking on any one of them would throw page not found error.

update: this has morphed into new question but was able to regain pages by removing clean-urls so will grant answer and ask new question.

# Answer
It could be because you have enabled clean url but its not working may be because of .htaccess file missing. Just check if there a .htaccess file in your sites first folder. if not copy one from other drupal site. or what you could do is go to yoursite/?q=admin/config/search/clean-urls this page and uncheck enable clean url and save
> 1 votes

---
Tags: 7
---


# Question
Title: Is there any module for picking photos for image field on mobile platforms like iphone
I think this is probably impossible but I wondered if there was any way to provide image upload or equivalent for mobile platforms for drupal.

# Answer
> 2 votes
No, you'll need to write an iphone application to do the photo upload (using a web service).

There is an older post with more info.

With Android phones the regular photo upload works, at least that's what I heard from a couple of users.

# Answer
> 0 votes
With iOS 6 they allowed mobile safari to access your photo library and uplode it directly from your phone to the site.

http://www.mobilexweb.com/blog/iphone-5-ios-6-html5-developers

# Answer
> 0 votes
This can be accomplished with DrupalGap.

---
Tags: theming
---


# Question
Title: Drupal Rest Service - Create node problem
I'm using POSTER add-on (Firefox) to create a node.(REST service). I couldn't able to create node having select/checkbox item. Getting following error in response.

\["An illegal choice has been detected. Please contact the site administrator"\]

How to resolve this? I'm able to create node if post data doesn't contains select/checkbox data. My problem is exactly related to the following link. But I couldn't find solution.

drupal 7 + services 3 - inserting nodes with select fields

If I replace 'und' to 'en' in json format, the node is being created but with null values.

I've found following messages under Recent log messages.

Warning: htmlspecialchars() expects parameter 1 to be string, array given in check\_plain() Warning: Illegal offset type in isset or empty in list\_field\_validate() Illegal choice in LABEL element.

Here 'LABEL' is the label(name) of the filed

# Answer
Yes.. finally I got solution for my problem. Here is the solution.

In JSON format, Here is the correct way to handle LIST type fields

"field\_select\_options":{"und":\["4"\]}

(Initially I tried "field\_select\_options":{"und":\[{"value":"4"}\]} which results error in response.)

Thanks, I got the solution from https://drupal.org/node/1971484
> 0 votes

---
Tags: 8
---


# Question
Title: Created custom entity with Entity Construction Kit but cannot filter in Views by taxonomy
I'm new to D7 but have extensive experience as a site builder in D6.

I created a custom entity type using the Entity Construction Kit(ECK) and then added a bundle with a term reference field using a hierarchical taxonomy and the Simple Hierarchical Select widget. Everything works fine except when I try to build a view to display the fields and filter by the taxonomy terms selected using the SHS widget.

When you start building the view the preselector screen asks what to show; content, users, my custom entity/bundle, etc. If I select my custom entity bundle, taxonomy terms don't show up as available for filtering. If I select content, then my custom entity is not available presumably because content means nodes.

How do I build a view that displays fields from my custom entity and can be filtered using taxonomy? If I create a custom content type instead of an entity, there's no problem filtering by terms, as expected. What am I missing?

Tnx,

Jeff

# Answer
> 0 votes
SHS doesn't work with entities, only nodes. The Hierarchical Select module doesn't support Views exposed filters yet either.

The taxonomy terms didn't show up as filters because I hadn't selected the bundle in the Views preselector screen. I was trying to generalize the view to filter at any level with SHS but no workee.

This forces me to use nodes where entities are more appropriate, or try some other taxonomy scheme to get some useable exposed filter UI, using entities.

Ugh.

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


title: Checking access in Views

text:
# Question
Title: Checking access in Views
I posted a support request on Drupal.org, but I thought I may find a faster answer here.

I am using the User Relationships module to create mutual relationships between two people with the purpose of viewing content. The node access part of UR seems to work fine. I am having trouble with Views, though.

Can anyone explain to me how I would do the following?

* Create a View containing content a user (not current logged in user) has created, filtered by a content type (lets call it Image). This view has a path with an argument like user/%/images.
* When the current user goes to user/%/images, it should show the images for whichever user ID is passed as the argument ONLY IF both users are related/accepted relationship. There is only one relationship type on the website. If there is no relationship, I would like to serve Access Denied, or at the very least, Page Not Found. But 403 makes more sense.

I cannot get this to work.

My goal is to show links to different types of contents users have created, and the viewing user (requester?) needs to have a relationship to view the content. Otherwise they should see nothing at all, or return an access denied error.

# Answer
> 7 votes
What you need is to create a custom views access plugin. I found a blog post that contains the basic information about how to do that here: http://techcp.wordpress.com/2011/01/11/adding-custom-access-plugin-to-views-in-drupal/

You then need at least need to do two specific things:

a) Extend it so that the access callback function receives the second url argument as the argument (in `function get_access_callback()`, change `array()` to `array(1)`).

b) In defined access callback function, check if there is a relationship between the currently logged in users and the uid that gets passed in, by using user\_relationships\_load() (documentation is for D7, but very similar in D6). Something like this (untested):

```
function your_access_callback($uid_viewed) {
  global $user;
  $params = array('between' => array($user->uid, $uid_viewed));
  return (bool) user_relationships_load($params, array('count' => TRUE));
}

```

That should already be enough to make it work four your case. However, this sounds like an interesting improvement to UR in general, for this, two additional things would be necessary.

c) Allow to configure which argument is the user id. Maybe there are also other ways where it could come from (if the view is displayed as a block for example). Not sure how to do that.

d) Allow to configure which relationship type should be checked. Expose a form element for that in the options and then pass the chosen relationship type id to your access callback and in there to `user_relationships_load()`.

# Answer
> 0 votes
Using Views Access Callback together with the Privacy Per User module is supposed to work cleanly and easily.

Sample implementation:

```
function mymodule_views_access_callbacks() {
  return array(
    'mymodule_user_has_access' => t("Check user privacy policy "),
  );
}

// Callback function to determine if a view has access according to the user's privacy polocay.
function mymodule_check_user_privacy_policy($arg1 = NULL) {
  switch (arg(2)) {
    case 'blog':
      if (!privacypu_check_access($arg1,'post_blog_article'))
        return FALSE;
      break;
    case 'friends':
      if (!privacypu_check_access($arg1,'becomefriend'))
        return FALSE;
      break;
  }
  return user_access('access content');
}

```

The only issue is that with my Drupal 7 site the Views Access Callback module is having some kind of strange fatal error with my multi-display views, and the suggested patch doesn't work. Any idea on how to fix it?

---
Tags: 7, views, users
---


# Question
Title: Custom filter disabled after approximatively 45 minutes
I am developping a filter to render equations in nodes as images from LaTeX code using mathtex library ( http://www.forkosh.com/mathtex.html ).

The filter works quite well, my filter is active, the content is filtered, the node is cached using Boost and the HTML file is containing teh filtered HTML code.

BUT : after several minutes (arround 45 minutes) my filter is disabled (not visible in the input format adminpage, see below) despite that the module is still activated in the module page and the content is not filtered anymore. BUT : when I desactivate/reactivate the modules, OR when I delete all caches, the filter is reactivated, the content is filtered again. And approximatively 45 minutes after it's not filtered anymore.

I try to do the same filter but using the Custom Filters module and I had the same behavior.

I supposed that the cron job had an influence, but content become not filtered BEFORE cron is executed (every hours).

Someone has an idea from where does the problem can come from ?

I'm running : Drupal 7.23 using lots of modules : http://sites.uclouvain.be/selt/files/selt-modules.txt

Some captures to illustrate :

Content not filtered, as after approximately 45 minutes :

Content filtered, as after cache flushing or de/reactivation of module :

Administrative page for format "Full HTML" showing activated mathtex filter :

Administrative page for format "Full HTML" not showing filter :

# Answer
After several tests and investigations, the culprit was the distant MySQL server which had a too short wait\_timout. During cache refreshing operations the server used to go away before filters beeing applyed, leading to caching unfiltered pages. Using a MySQL server with no wait\_timeout has solved this problem, without changing any setting elsewhere.
> 1 votes

# Answer
Suggestions to debug:

1. Simplify the setup -- limit your installation to a simple, fresh drupal with only your filter module. No unknown influences, to pinpoint the flaw.
2. If you suspect cron -- turn it off and wait 60 minutes.

But this is individual support. No other user might ever benefit from your very individual problem. It is not a good fit for a public question on stackexchange.
> 0 votes

---
Tags: caching, cron, input-formats
---


# Question
Title: How to remove contents type drupal advanced search page
When Drupal does a search, and returns no results, an advanced search form is displayed. The form contains a list of content types. There are a couple of content types on our site, but these should be hidden from the user, e.g the end user shouldn't see "contentType", "newType".

I don't want to limit the results, just restrict the user's ability to filter the results using the types.

I've tried looking at the search templates, but couldn't find a reference to the fields.

Any ideas on where I find the correct type or turn off this field?

# Answer
Advanced Search field can be disabled in Permissions settings (it should be disabled by default).

If you rather want to leave Advanced Search, but limit to specific content types, you can 1) Use Custom Search module, as advised by @Lance or 2) Dig through `modules\search\*.*` directory to see which function controls the content type of the Advanced Search options, after which you can use your own module to override the settings.
> 2 votes

# Answer
You can use hook\_form\_alter to change the form to your needs. In your case just go and unset the GUI elements you don't want to show up from the $form array.

If you don't know the form ID just implement an empty hook\_form\_alter and use dpm() to print the form IDs. You need the devel module and the "Access developer information" permissino to see the output of dpm().
> 1 votes

# Answer
Try the Custom Search Module. With this you can specify which role can search which content types and some other nice features.
> 1 votes

---
Tags: search
---


# Question
Title: How to add nodes inside admin area, e.g. for admin documentation
I have an admin theme set. When I create a page in my custom module with an `admin/...` path it is rendered with the admin theme.

I've set up a node type for documentation and I'd like these to be inside the admin area. I've set the default menu to *Management* and I've given the page an alias that begins with `admin/` but it's rendered in the normal (non-admin) theme.

How can I add nodes that will be considered part of the admin area, and rendered with the admin theme?

# Answer
This can be done using Administration theme module:

> The Administration theme module allows you to use this theme on more pages like :
>
> * batch processing pages
> * devel node load and render pages
> * coder code review pages
> * **pages you define yourself** in the provided textarea

Emphasis mine.
> 1 votes

---
Tags: nodes, theming
---


# Question
Title: Is it necessary to learn php in order to use drupal to manage my site?
I am planning on using Drupal to manage a website. Should I learn PHP because I understand Drupal is built on PHP language?

I don't know PHP and I am not planning to learn it, but I have decided to use Drupal as my CMS, will I still efficiently manage my geospatial data handling site?

# Answer
No, it's not "necessary". Drupal core has a UI to perform its basic functions, as do most contributed modules.

Beyond that, it's totally up to ***you*** to say whether you need to learn PHP, based on the level of customisation ***you*** need in your site

If all the functionality you'll ever need can be provided through the UI of whatever modules you decide to use, then no, you won't need to learn PHP. If all of that functionality *isn't* provided "out-of-the-box", then yes, you'll need to learn PHP.

As with anything, your mileage will vary. The only possible way to answer this question properly is for you to get stuck in and try it out for yourself.
> 4 votes

---
Tags: 7
---


# Question
Title: What files will Drupal poll for hooks by default?
I tried implementing `hook_menu()` in an `foo.admin.inc` file for reasons that aren't important, and discovered that hooks are not checked in said file. However, in the past, I have seen include files with hooks defined in them (e.g. rules.inc), so I was wondering what the default core rule is for this, and how one can specify files outside of the defaults. Does extending where hooks can be checked have a nice Drupal way of doing this, or have module developers used PHP to achieve this end?

# Answer
> What files will Drupal poll for hooks by default?

There's no "polling" happening really, at the core, this is what happens:

```
function module_hook($module, $hook) {
  return function_exists($module .'_'. $hook);
}

```

And this is simply called with `$module` being the name of each enabled module. So essentially, if the hook is declared in any file that is loaded, PHP will find it, and the function above will return `TRUE`.

If one, for one reason or another, wants to declare hooks elsewhere, it is possible to explicitly tell Drupal to load up other modules by using hook\_hook\_info. The documentation says:

> Normally hooks do not need to be explicitly defined. However, by declaring a hook explicitly, a module may define a "group" for it. Modules that implement a hook may then place their implementation in either $module.module or in $module.$group.inc. If the hook is located in $module.$group.inc, then that file will be automatically loaded when needed. In general, hooks that are rarely invoked and/or are very large should be placed in a separate include file, while hooks that are very short or very frequently called should be left in the main module file so that they are always available.

Another low tech option, or the only option in D6, looks like this:

\[module\].module:

```
function module_menu() {
  require_once "module.menu.inc";
  return _module_menu();
}

```

\[module\].menu.inc:

```
function _module_menu() {
  return array();
}

```

If hook module is large, this moves the majority of the code outside of the module, requiring less RAM on most page loads to run the module. As above, this makes little sense if the module is invoked on (nearly) every page load.
> 1 votes

# Answer
An include file will be scanned if the hook is within a group. For example, the rules module defines a group called 'rules' and so Drupal will scan the file foo.rules.inc for implementations of rules hooks.

The hook where groups are defined is hook\_hook\_info. See: https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook\_hook\_info/7

Also, look at the function module\_implements that finds modules implementing a hook: https://api.drupal.org/api/drupal/includes!module.inc/function/module\_implements/7
> 1 votes

---
Tags: 7, hooks
---


title: Computed dependent field

text:
# Question
Title: Computed dependent field
I have a node type (actually entityform type) with a term reference field. The terms has a description field (a long text with a HTML markup). I need to display the description of a selected term on a node edit form. Is it possible to show a description immediately after user selects new term from a list?

# Answer
It seems that it's very easy to implement a computed dependent field. Suppose there is a term reference (field\_section) on an edit form with YOUR\_FORM\_ID.

```
function YOUR_MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == YOUR_FORM_ID) {

    // Add an AJAX behaviour to field_section:
    // After you will select a new term on the edit form,
    // YOUR_MODULE_NAME_form_alter and
    // _YOUR_MODULE_NAME_form_section_callback will be called.
    $form['field_section'][LANGUAGE_NONE]['#ajax'] = array(
      'event' => 'change',
      'callback' => '_YOUR_MODULE_NAME_form_section_callback',
      'wrapper' => 'nomination-desc-wrapper',
      'method' => 'replace',
      'effect' => 'fade'
    );

    // Add a wrapper for our computed dependent field.
    // At the begining it will be invisible
    $form['nomination_desc_container'] = array(
      '#type' => 'hidden',
      '#weight' => 2,
      '#attributes' => array('id' => array('nomination-desc-wrapper')),
    );

    // Add a computed dependent field. It will be shown as a text
    $form['nomination_desc_container']['nomination_desc'] = array(
      '#type' => 'item',
    );

    // This code will be executed during form creation and
    // during each AJAX-call
    if (isset($form_state['values']['field_section'])) {

      // Find taxonomy term
      $tid = $form_state['values']['field_section'][LANGUAGE_NONE][0]['tid'];
      $term = taxonomy_term_load($tid);

      // Show it's description
      $form['nomination_desc_container']['nomination_desc']['#markup'] = $term->description;

      // Display description wrapper
      $form['nomination_desc_container']['#type'] = 'container';
    }
  }
}

// Just return new wrapper body
function _YOUR_MODULE_NAME_form_section_callback($form, &$form_state) {
  return $form['nomination_desc_container'];
}

```
> 0 votes

---
Tags: entities
---


title: hook_views_query_alter all condition

text:
# Question
Title: hook_views_query_alter all condition
I have an exposed filter that shows products which have multiple entity references. The user should be able to pick some number of entities and the view should show entities containing all those references. In my mind that should mean changing the `in` operator on the where clause to an `all` operator.

```
function hook_views_query_alter(&$view, &$query) {
  if ($view->vid == 7) {
    dpm ($query);
    if (isset($query->where[1]['conditions'][2]['operator'])) {
      $query->where[1]['conditions'][2]['operator'] = 'all';
    }
    dpm ($query);
  }
}

```

However this seems to have no effect. the operator is changed from the first `dpm` to the second and it does break if I enter some other value in the `all` does not change the results. Do I have the wrong operator? Or am I going about this all wrong?

\[edit\] According to Payou the function should look like

```
function falk_products_query_products_alter($query) {
  $conditions = &$query->conditions();
  $conditions2 = &$conditions[0]['field']->conditions();
  $conditions3 = &$conditions2[0]['field']->conditions();
  $my_query = &$conditions2[0]['field'];
  $my_conditions = &$my_query->conditions();
  dpm ($my_query->conditions());

  if (isset($my_conditions[2])) {
    foreach ($my_conditions[2]['value'] as $target) {
      $my_query->condition($my_conditions[2]['field'], array($target), 'in');
    }
  }
  dpm ($my_query->conditions());
}

```

Which at the dpm's give me arrays that look good to me but dont work if more than one value is input.

# Answer
Altering a query like this is really not recommended.

First of all, you should use SelectQuery methods provided by "$query" variable. You can get an array of query conditions by using "SelectQuery::conditions()" method.

Be careful, if you want to alter this array get the array like the following snippet :

```
$conditions =& $query->conditions();
//Now you can use and alter your query conditions.

```

Some others tips related to your code :

**1) You can tag your query in Views UI**

Add a tag to your Views Query :

With this trick you can define a special hook for altering all query who use this tag. This hook is "hook\_query\_TAG\_alter"

Now you can use this code :

```
function YOUR_MODULE_query_my_tag_alter($query) {
  $conditions =& $query->conditions();
  //This condition is useless now
  //if ($view->vid == 7) {
  //Check conditions and do your updates

  //}
}

```

**2) Careful to the module weight**

When you alter something, other modules can do it too... This order is determined by the module weight saved in the "system" table.

By using your own tags on your query, other modules should not know about this tag and should not alter your query.

You can change your module weight but this is not the thread of this post

**Links**

SelectQuery Api

SelectQuery::conditions() method

Query Alteration recommandations by Drupal

hook\_query\_TAG\_alter

Change Module Weight
> 1 votes

---
Tags: views, database
---


# Question
Title: Store data from a specific content type in a different database?
Was not able to find a previously asked question. But is it possible and or worthwhile?

Background: setting up a new feature that will host a lot of data. Want to separate it from the rest of the site so if something happens to that data the rest of the site, users e.g will not be touched.

# Answer
> 0 votes
This is not possible without a lot of custom code. Primarily because Drupal stores field content in separate database tables. There is not the one single table that holds the content of all nodes of a specific content type. And fields are also re-usable across different content types. You would need to create your own storage engine.

Wouldn't an intelligent backup strategy be enough to assure data security in your case?

---
Tags: nodes, database
---


# Question
Title: Commerce/Rules - Multiply the price by a custom field value
In my Drupal Commerce store, I have a field called **Commission**.

The Commission is input as a percentage (i.e. its not a fixed global value).

I need the final price to be updated so it incorporates the commission. I then need VAT to be added to the commission (but not the original price). The user should be able to see the full price (with commission and commission-VAT) before they add a product to cart.

I thought Rules would be perfect for this situation, especially as it has an action called *"Multiply the unit price by some amount"*. However, this action doesn't seem to accept values from custom fields, even if you bring them into scope in the conditions area of the Rule.

I have watched Randy Fey's excellent tutorials on the Rules and Commercial modules, and I have tried to adapt them to my use case. However, I can't get it to work.

Could some one give me some pointers. Thanks!

# Answer
I found the solution to this, so I thought I would post it to help anyone else out who is struggling:

1) Before you can call your field under actions, you have to bring it "into scope" under conditions. Select "Entity has field". Under data selectors choose "commerce-product (saved commerce product).

2) For some reason, it seems impossible to use the "Multiple the Unit Amount by" option, as no matter what data selector you use, you will get an error. Instead select "Calculate a value"

3) Under "Input Value 1" select "commerce-product:commerce-price:amount".

4) Select which calculation to use. In my use case, I used multiply (\*).

5) Under "Input Value 2" click the "switch to data selection button". You can now select your custom field. It will be located under "commerce-product: (saved commerce product)"

6) Under "Provided variables" give the result of the calculation a name. Choose a good name, as you will be using it later on.

7) Now create a new action called "Set a data value".

8) For the data select pick "commerce-product:commerce-price:amount"

9) Finally, under value, click the "switch to data selection button". You can now select the variable you created in step 6.

This is everything you need to change the price based on the value of a custom field.

Notes: 1) For the event, I used "Before saving a commerce product" 2) I would recommend creating a custom field called "base price", where the user can enter the price before calculations. The rule is applied every time a product is saved, so the commerce price field will keep on changing each time the product is saved. If you use a base price field, you can avoid this problem.
> 6 votes

# Answer
Though this is an old question, I came across the same problem as bench. I finally solved it by using the following conditions:

```
Entity has field -> Entity: [commerce-line-item] -> Field: commerce_product
Entity has field -> Entity: [commerce-line-item:commerce-product] -> Field: field_your_custom_field

```

So you have to do it in two steps. Wished someone told me that 2 hours ago..;-)
> 2 votes

# Answer
for 1): 'Under data selectors choose "commerce-product (saved commerce product)."'

Under data selectors i can only add "commerce-line-item..." ?? And also there is a block "field" - "The name of the field to check for." ??
> 0 votes

---
Tags: rules, commerce
---


# Question
Title: Drupal commerce: there is a way to apply discount to products with some taxonomies elements?
I would like to know if there is a way to apply discount to products with some taxonomies values, something similar to "bulk views operations" Or another way where a non developer or not a site-builder it's able to create new discounts.

Thanks

Oskar

# Answer
> 1 votes
The biggest issue here is that in your taxonomy term comparisons, Rules is going to be looking for taxonomy term IDs. In core Rules, there is no way to show a select list or something similar in the Rules UI for selecting a taxonomy term. There may be a contributed module that adds this functionality; I didn't look.

If you know a term ID, you can use a different condition based on whether the term reference field is single or multi value:

* Single value: Data comparison
* Multi value: List contains item

Since you're going for usefulness to non-developers / site builders, I'll assume you need something better than that. It appears you might be using Commerce Discount, but I don't know if that's why you've added the tag or not. It offers a simplified interface for building product pricing rules and depends on the http://drupal.org/project/inline\_conditions module, which includes a simplified taxonomy term check for product entities.

---
Tags: taxonomy-terms, commerce
---


# Question
Title: How to achieve order fulfillment in drupal commerce like ubercart?
I'm new to drupal commerce. I would like to know how to achieve Order fulfillment in drupal commerce like ubercart. I'm using UPS,FedEx & USPS for shipping. I had seen package options in each shipping methods configuration. I'm confused to handle shipment process for orders. Is there shipment requirements has send automatically to respective shipping service(UPS,FedEx & USPS) after creating an order?

Please help me to get clear about handle order shipment process in drupal commerce.

# Answer
> 1 votes
Have you tried https://drupal.org/project/commerce\_delivery at all? That appears to be used in conjunction with https://drupal.org/project/commerce\_physical\_fields and its dependent Physical Fields module.

---
Tags: commerce
---


# Question
Title: Accessing all VIEW data in a preprocess hook
I have the following hook method:

```
hook_preprocess_views_view_unformatted(&$vars)

```

I can obtain the VIEW like so:

```
$view = $vars['view'];

```

When I dump this result I can see a complex structure with all the data I need...the VIEW can be iterated via:

```
foreach ($view->result as $index => $record)

```

Each records data (node details) is navigable via the following path:

```
$record->_field_data['nid']['entity']->field_XXX

```

I am uneasy accessing these details with the second property in this chain as usually "underscore" represents private...maybe it is just the OO purist in mean telling me it's bad practice and I am defeating OCP. :)

Ultimately I need the ability to iterate my custom fields and this seems to be the only way I can achieve that -- is there not a API which would encapsulate this access for me?

I assumed the $view object itself would have an API to provide traversing methods or at least result iteration, but it doesn't appear that way.

# Answer
> 7 votes
The `result` array in the Views object contains the row information so yes, if you need to access the results, this is the way to do it.

For example, including:

```
function YOURMODULE_preprocess_views_view(&$variables) {

  $view=$variables['view'];
  drupal_set_message('<pre>' . print_r($view->result, TRUE) . '</pre>');

}

```

and then a quick View that just returns node objects would look like this:

and a View that returns fields (in this case just titles) would look like this:

and then when you actually include custom fields, you get that big `_field_data` array, eg:

but you should also see it in a more top level area of the results as well:

Also, a quick look at views\_get\_view\_result() might shed some more "this is how we do it" confirmation/information on Views results. Also What is the hook to preprocess a view and Changing values in preprocess view function talk about other options available to you in the Views API.

---
Tags: views, hooks
---


# Question
Title: Add role to user after joining organic group with rules
I'm trying to add a user role to a user who has become a member of a group. The workflow is like this:

* User requests to join group.
* Request is approved by group administrator.
* User is a member of the group.
* User gets an additional role.

I've tried to make a rule which would be able to do this, but although all the settings seem correct after joining the group the user doesn't get the additional role. See below a screenshot of my rule settings:

# Answer
> 2 votes
Now your Rule runs after user requests membership. But you should run it after OG membership was approved.
I prepared Rule which adds role “member” after membership was approved or if it was added by admin (auto-approved). Here is export (`4` is id of my drupal role “member”):

```
{ "rules_after_add_user_to_group" : {
    "LABEL" : "After add user to group",
    "PLUGIN" : "reaction rule",
    "TAGS" : [ "test" ],
    "REQUIRES" : [ "rules", "og" ],
    "ON" : [ "og_user_insert", "og_user_approved" ],
    "IF" : [ { "data_is" : { "data" : [ "og-membership:state" ], "value" : "1" } } ],
    "DO" : [
      { "user_add_role" : { "account" : [ "account" ], "roles" : { "value" : { "4" : "4" } } } }
    ]
  }
}

```

Screenshot:

**Tip:** you can enable Rules debug (page `admin/config/workflow/rules/settings`) to see when your rules are executed.

# Answer
> 2 votes
I have the same issue (that why I started a bounty).

I solved it this way.

I added a function to a custom module. You can simple create your own module by making a new folder in /sites/all/modules with two files:

yourname\_module.info -\>\>

```
name = "Custom Functions"
description = "Allows execution of custom code for the website"
core = 7.x
package = "yourname_customs"
version = 7.x-1.x

```

yourname.module

```
<?php
function yourname_add_role_to_user($uid, $role_name) {

    $user = user_load($uid);

    if ($user === false || !isset($user->uid) || !is_array($user->roles)) {
        //Display an ugly error when user is not set correctly
        exit('$user is not set correctly <pre>' . print_r($user, true) . "</pre>");
    }

    //Get the user roles
    $roles = user_roles(TRUE);
    $rid = array_search($role_name, $roles);

    if ($rid != FALSE) {
        $new_role[$rid] = $role_name;

        // Add new role to existing roles.
        $all_roles = $user->roles + $new_role;

        //Delete all user roles from DB
        db_delete('users_roles')
                ->condition('uid', $user->uid)
                ->execute();

        //Insert all user roles in DB
        $query = db_insert('users_roles')->fields(array('uid', 'rid'));
        foreach (array_keys($all_roles) as $rid) {
            if (!in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) {
                $query->values(array(
                    'uid' => $user->uid,
                    'rid' => $rid,
                ));
            }
        }
        $query->execute();
    } else {

        //Display an ugly error wen role not found
        exit("Could not find role " . htmlspecialchars($role_name) . "<br/>
              Vald roles: <pre>" . print_r($roles, true) . "</pre>");
    }
}

```

Then goto your modules and enable "Custom Functions".

Make sure you have module custom php code enabled.

Then instead of action add user to role in rules, add: run custom php code and enter:

```
yourname_add_role_to_user($account->uid, "Members");
header("Location: /admin/people");
exit;

```

This adds the user to the role, and stops the script. If you don't stop the script, the role is not saved. And I needed to add a module because `user_save` does not work when executed in `custom php code`.

So, I know it is very ugly, but it works for me.

# Answer
> 0 votes
Which version of OG do you run ?

This is a know bug that have been fixed with Organic Group 2.4+ (see bug page).

If you are already running a 2.3 or lower version of OG the updgrate should be straightforward. If you are running OG 1.x, you can find more details on the update process from OG 1.5 to 2.4+

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


# Question
Title: How to change a fields text_format for admin users, and show a plain_text for anonymous users?
When a node with body text format as **plain\_text** is posted by anonymous user , how do I change it to **full\_html** when being edited by admin or authenticated user?

Is there anyway I can edit body fields text\_format on the go? like through preprocessing or form hooks?

I also have cases where some of the nodes when edited by admin comes with "enable/disable richtext", and for some nodes, it does not show up.

# Answer
I'm afraid what I assume you are trying to accomplish just isn't available to you because Drupal saves the text entered in a field unfiltered/as is; it then filters it when it is actually displayed or rendered.

So, if you enter for example:

```
<b>Hello world</b> <some html tag>blah blah blah</end some html tag>

```

in a text field, that exact content will be saved.

Then, when the entity is displayed, Drupal will look at the text format and if it's plain\_text, it will output

```
Hello world blah blah blah

```

but if the text format is full html it will output (with minor exceptions)

```
<b>Hello world</b> <some html tag>blah blah blah</end some html tag>

```

but once again, in both instances whatever the user inputs will be stored in the database.

Of course, you could create a field that toggles some sort of "display the body with full html after an admin has verified its contents" that would be looked at and if set, display the entity with that field using full html, but until set, would just display it in plain text.
> 0 votes

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


# Question
Title: After disabling and uninstalling memcached module, I get this PDOException and WSOD?
I´ve cloned my production site in a local Xampp installation. My site has Memcached installed (in the server and I´ve got the drupal memcache module installed).

But I´ve got this error at my local site:

> You must enable the PECL memcached or memcache extension to use memcache.inc

(this is repeated at least 30 times, so that line is printed about 30 times at the top of every page).

Now, I´ve disable and unninstalled memcache at my local installation, and the error is still there.

I´ve tried after that deleting the additional settings added to my settings config file:

> $conf\['cache\_backends'\]\[\] = 'sites/all/modules/memcache/memcache.inc'; $conf\['cache\_default\_class'\] = 'MemCacheDrupal'; $conf\['memcache\_key\_prefix'\] = 'memcache\_sitio'; $conf\['cache\_class\_cache\_form'\] = 'DrupalDatabaseCache';

But if I do eliminate those lines (after I´ve uninstalled -not only disabled- memcached module), I get WSOD and this error:

> Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE\[HY000\]: General error: 2006 MySQL server has gone away' in C:\Users\Vic\Desktop\XAMPP\htdocs\drupal\includes\database\database.inc:2139 Stack trace: #0 C:\Users\Vic\Desktop\XAMPP\htdocs\drupal\includes\database\database.inc(2139): PDOStatement-\>execute(Array) #1 C:\Users\Vic\Desktop\XAMPP\htdocs\drupal\includes\database\database.inc(664): DatabaseStatementBase-\>execute(Array, Array) #2 C:\Users\Vic\Desktop\XAMPP\htdocs\drupal\includes\database\database.inc(2318): DatabaseConnection-\>query('SELECT expire, ...', Array, Array) #3 C:\Users\Vic\Desktop\XAMPP\htdocs\drupal\includes\lock.inc(167): db\_query('SELECT expire, ...', Array) #4 C:\Users\Vic\Desktop\XAMPP\htdocs\drupal\includes\lock.inc(146): lock\_may\_be\_available('schema:runtime:...') #5 C:\Users\Vic\Desktop\XAMPP\htdocs\drupal\includes\bootstrap.inc(405): lock\_acquire('schema:runtime:...') #6 C:\Users\Victoria in C:\Users\Vic\Desktop\XAMPP\htdocs\drupal\includes\database\database.inc on line 2139

Please note that I´ve deleted all cache, tried disabling (and enabling) all performance options, and I´ve run run cron more than once.

What should I do? Thanks!

# Answer
Each time I saw the "Mysql server has gone away" error, it was caused by the max\_allowed\_packet setting (in the my.ini setting file) that was too small.
> 2 votes

# Answer
Found the solution!! It´s here: http://stannesi.blogspot.com.ar/2011/11/how-to-install-memcache-on-xampp.html

In a nutshell: My Xampp php didn´t have any memcache extension, so, I have to add it:

After all the extensions declared in my php.ini file, I´ve added this:

```
extension=php_memcache.dll
[Memcache]
memcache.allow_failover = 1
memcache.max_failover_attempts=20
memcache.chunk_size =8192
memcache.default_port = 11211

```

After that I have to download the php\_memcache extension (php\_memcache.dll) and put it inside php/ext folder, in my Xampp installation.

And that was it!!

Hope this helps out someone, somewhere :)
> 1 votes

---
Tags: caching, installation
---


# Question
Title: Make autocomplete window appear above accordion pane
I have created a node add form using the field group module to put the form in a jQuery accordion.

I have a auto-complete field that is at the bottom of one pane so the div that appears that lets users choose from the auto-complete options is behind the pane below it as it has overflow: hidden. Here is an image of the problem:

I've fixed this behavior by changing 2 lines in autocomplete.js in the populatePopup function:

```
//var position = $input.position();
// changes to:
var position = $input.offset();

// and

//$input.before(this.popup);
// changes to:
$('body').append(this.popup);

```

As the auto-complete div is now appended to the body it appears above everything else.

This is great but the problem is I don't want to start hacking Drupal core js files.

I could copy the whole autocomplete.js to a new file and then replace the whole thing, but really I just want to override the populatePopup function.

Is it possible to do this?

(I've tried copying the populatePopup function into my own js file but I get the error Drupal.jsAC is undefined.)

# Answer
> 1 votes
Doh - I was so close.

The answer is to simply copy the function you want to override to your own custom JS file but make sure to **wrap it in a document ready function!**

---
Tags: javascript, ajax, navigation
---


# Question
Title: drupal_get_path() not working in subdirectories of my site
So I'm using drupal\_get\_path() within a block to reference an image in my themes//images directory.

And this works. At the root and all first level pages. example.com, example.com/about, etc.

However, if I am on a page such as example.com/about/csa:

Instead of continuing to output the filepath as /sites/all/... it outputs the file as //sites/all/...

This only happens when I'm in a subdirectory of the site.

Does anyone know why this might happen?

EDIT:

```
<?php $src = drupal_get_path('theme', $GLOBALS['theme']) . '/images/carrots.png';
echo '<img src=' . $src . ' alt="carrot background image" >'
?>

```

# Answer
> 5 votes
Its because drupal\_get\_path returns relative path.

Try this:

```
<?php
  global $base_path;
  $src = $base_path . drupal_get_path('theme', $GLOBALS['theme']) . '/imag/carrots.png';
  echo '<img src=' . $src . ' alt="carrot background image" >'
?>

```

**Edit with url function:**

```
<?php
  $src = url(drupal_get_path('theme', $GLOBALS['theme']) . '/imag/carrots.png');
  echo '<img src=' . $src . ' alt="carrot background image" >'
?>

```

---
Tags: blocks
---


title: Using built in jQuery UI in my theme

text:
# Question
Title: Using built in jQuery UI in my theme
Every page of my theme will need to use jquery UI. I know it's included with Drupal 7, but I can't really decipher Drupal's way-too-technical documentation. It looks like the only way to do it is with the template.php file. But since I don't understand that file, I'm trying to avoid doing it that way.

Is there another way, or should I just try the template.php file?

# Answer
Adding JS to a page is really not that hard, even though you need to use php.

For normal JS files, you could do something like this

```
drupal_add_js($path_to_js)

```

Drupal has however registered jQuery UI into libraries making it easier to add both JS and CSS files for certain jQuery UI plugins. This can be done using

```
drupal_add_library($module, $library);

```

All the jQuery UI plugins exist in the system module, so you could do

```
drupal_add_library('system', 'ui');

```

or

```
drupal_add_library('system', 'ui.accordion');

```

Some of these plugins have dependencies because they use other plugins. Drupal handles this very cleverly and will included the components needed.

You can see the full list of jQuery plugins here. This is formatted as a PHP array, but generally the naming convention is ui.PLUGIN-NAME.

If you need to add the JS on every page you could simply add a preprocess page hook and add them there. This would look something like this in the template.php file.

```
function NAME_OF_THEME_preprocess_page(&$variables) {
  drupal_add_library('system', 'ui');
  drupal_add_library('system', 'ui.accordion');
  drupal_add_library('system', 'effects.highlight');
}

```
> 36 votes

# Answer
have you tried the date\_popup module? works good with the form API
> 4 votes

# Answer
1. Refactor your hard-coded form in the .tpl file into a Form API implementation. Like @LSU\_JBob said, there is no reason why you should be creating a form without using FAPI. I recommend you read the Form API Quickstart Guide, and bookmark the Form API reference page.
2. Once you have your form built and you are able to submit values to it, process it, etc., download and read the code in the Date contrib module. Date is used to provide the kind of date popup you want to create, but for CCK in D6 and Core Fields in D7. Although you are not looking to work with fields, the Date module uses JQuery UI to accomplish what you are trying to do. This module should give you a solid example.
> 4 votes

# Answer
Thanks `googletorp` for answering this.

Just to add, if things are still not very clear related to enabling **UI plugins**.

Please note that when you will mention: `drupal_add_library('system', 'ui');`
This will NOT enable all the ui plugins automatically.

You can find list of available jquery ui plugins in drupal 7 here: `/misc/ui/`

To enable a perticular plugin, forexample: `jquery.ui.slider.min.js`, you need to add this line:

```
drupal_add_library('system', 'ui.slider');

```

Hope this is useful.
> 3 votes

# Answer
I had this problem recently. Someone gave me their custom module to force JQuery UI to load on every page. You can recreate it simply. First, install jquery\_update and make sure it's working. Then, create & enable this module:

Make a folder in path/to/modules named 'jquery\_force'.

Inside, add two files:

**jquery\_force.info**:

```
name = JQuery UI Force
description = Forces JQuery UI to always load
dependencies[] = jquery_update
package = User Interface
core = 7.x
files[] = jquery_force.module

```

**jquery\_force.module**:

```
<?php
/**
 * @file jquery_force.module
 * TODO: Enter file description here.
 */

/**
 * Implements hook_init().
 */
function jquery_force_init() {
    drupal_add_library('system', 'ui');
}

```
> 2 votes

# Answer
Adding a preprocess hook in the `template.php` file did not work for me.

I simply put `drupal_add_library('system', 'ui');` into the `template.php` file by itself, works.
> 2 votes

---
Tags: 7, theming, javascript
---


# Question
Title: Redirect all pages to a form unless the user has filled out some information (Drupal 7)
I need to bring up some sort of dialog or form to collect user information when they first login. Is there anyway that the user can be redirected to a form that they must fill out before they can proceed when they first login?

I need to do this because we need to collect information from users who have already created accounts and will not have entered the information that we are adding to the user node.

EDIT: I really want to force the user to fill out this form if they have not, so what I am really looking for is a way to redirect all pages on the Drupal site to this form unless they have filled it out.

# Answer
> 0 votes
This should do it. although there might be a module that already does this as well.

https://api.drupal.org/api/drupal/modules!user!user.api.php/function/hook\_user\_login/7

---
Tags: 7, users
---


# Question
Title: How to detect if field support multi values?
It seems that field\_info\_instance doesn't return such info...

# Answer
> 4 votes
I believe the 'cardinality' is stored at the field (base) and not the field instance. You should be able to use field\_info\_field to retrieve that information.

---
Tags: 7, entities
---


title: Mac to Windows Database issue

text:
# Question
Title: Mac to Windows Database issue
I've been developing a Drupal site for over a year on my MacBook. The production server that the Drupal site will run on is Windows Server 2008 R2. As I try and load the SQL file from my MacBook, I'm getting this error from my MySQL client: "This file contains mixed linebreaks. They have been converted to Windows linebreaks." Then the import crashes. Can anyone share some tips with me on how to sucessfully migrate the Drupal database to Windows w/o carrying over assorted character/encoding problems?

Also-because the Drupal URL of the site on Windows is something other than "localhost", I end up having to edit the exported SQL file(s) either in TextMate (on Mac) or in Notepad++ (on Windows) to change the URLs. Could this also be contributing to the problem? I have also noticed in Sequel Pro that in the "field\_data\_body" table that there are hard returns everywhere. Is this normal?

Sorry if this is a dumb question, but I'm at my wits end and on a tight deadline. Thanks so much,

Jason

--Added on 2/9/14--

Here's some additional details related to my original question.

1. First, I realized that the Mac version of my database contains Windows line breaks (\r\n) and not OSX line breaks (\n). If my production MySQL server runs on Windows, should I even bother to try and convert the incorrect line breaks on my mac development site?
2. Importing using Backup & Migrate doesn't usually work from my Mac to my Windows server because the Windows server usually crashes. So I have to start the site off on Windows by importing the schema and data files separately. Schema imports fine, but the data file import encounters SQL errors from these issues: apostrophies in block of text (i.e., Drupal's, site's); brackets (i.e., 'Your membership request was approved for '\[og\_membership:group:label\]' in an insert statement), anyplace where % or @ occurs.

I've tried putting a backslash before the offending characters in some tables, but don't want to do this for the whole data file. Is there something I'm doing wrong when exporting SQL files on my Mac that is causing these problems?

One thing I just remembered is that I had to uninstall and then reinstall MAMP on my Mac two weeks ago. Before this, I never encountered these type of import errors, on my Mac at least. I checked my MySQL config. file and the only difference is that I declared InnoDB as the default storage engine. I did not have this in my previous MAMP installation.

Thanks for any assistance.

Jason

# Answer
> 0 votes
First, I would suggest using the Backup and Migrate module to move Drupal databases between hosts. That may solve your line breaks issues, and YMMV, but loading Drupal dbs via other MySQL methods can cause other issues.

Second, have you tried setting the $base\_url config variable on your production server? You shouldn't have to change URLs in the SQL files. It's a best practice to use relative paths in content. There are modules/filters that will convert them to absolute paths on the fly.

Cheers!

---
Tags: migrations, database
---


# Question
Title: Extra sorting criterium in case of ex aequo with Views
My articles have a 'Ranking' field, which contains an integer. I have a view that sorts articles depending on this value: the article with the highest score is a the top. Now, when two articles have the same amount of points, I'd like the most recently posted article to get the highest ranking.

For example. Let's say I have 3 articles:

* 'Article A' (5 points - posted on 30/12)
* 'Article B' (5 points - posted on 21/12)
* 'Article C' (6 points - posted on 20/12).

The ranking should be:

1. 'Article C'
2. 'Article A'
3. 'Article B'

How can I do this?

# Answer
> 0 votes
Add a new sort criteria, Posting date, set it to descending and make sure the order of your sort criterias are correct, first points, then date.

---
Tags: views, 7
---


# Question
Title: Multisite domain not working without symlink
I used to have to work with my own custom `*.conf` file in order to get my multi-site to work off a non root install of drupal but now have moved it to root ,I don't need that file anymore as system reads the `.htaccess`.

So while my subdomains work fine in `sites` folder, my other domain name in `sites` folder refuses to work without symlink. Which I always thought was only necessary in tandem with `*.conf` file for *virtualDocument* hosts.

So my question is --

Why won't my other domain work like other sites in sites folder?

Why must it have a symlink to work?

And why do other sites have clean-urls working along with main install site but not other domain name?

My set up is

> mainsite.com/sites/
>
> ```
>                   subdomain.mainsite.com
>                   subdomain2.mainsite.com
>                   otherdomain.com
>
> ```

If I symlink `otherdomain.com` while in `www` folder:

`ln -s /var/www/html/ /var/www/html/otherdomain.com`

It works but without clean-urls

# Answer
I have the answer now.

The symlink is necessary so two separate domains can share the one IP along with your server's records. Obviously the subdomains share the same name and so are fine just listed in sites directory. The symlink links the other domain or any number of domains to the same html folder where the root installation of drupal resides.

The clean urls for the symlink multi-site domain on my Centos 6.4 linux system running httpd require the default `httpd.conf` file in `etc/httpd/conf` to change `AllowOverride` NONE to All for directories. Then the service must be restarted for changes to take effect `service httpd restart`
> 0 votes

---
Tags: multi-sites, .htaccess
---


title: What's the meaning of "theme()"?

text:
# Question
Title: What's the meaning of "theme()"?
I am new to drupal, I read some introductory tutorial.

I notice there is some theme() function in template files.

Like this:

```
<?php print theme('uc_price',array('price'=>$price)); ?>

```

It will generate some html source code:

```
<span class="uc-price" data-thmr="thmr_45">$59.85</span>

```

Is it **theme()** function is only to generate the html source? If this is the case, why I need use **theme()** function? I Think just only write html source manually.

I use Zen base-theme, Does **theme()** is one of zen's native function?

Please tell me the real usage of **"theme()"**.

# Answer
Your understanding about theme is right. It is for wrapping data with html elements. Advantage is that you can seperate view part and logic part. There are also default theme which you can use out of box
> 0 votes

---
Tags: theming, nodes
---


title: Adding custom text to each user profile

text:
# Question
Title: Adding custom text to each user profile
In D7 i want to let admin add custom text(description) to each user profile and add point to users .
for example the user profile must be like this :

> John
> Description : You'r not good at speaking
> point : 12
>
> Joe
> Description : You'r perfect
> point : 20

Thx

# Answer
> 0 votes
Use field permissions module.

Add fields for these info & restrict the permissions for them to admin only.

---
Tags: users
---


title: How to add extra css in style.css file?

text:
# Question
Title: How to add extra css in style.css file?
I want to add extra css for my images (I just want to set `float:left` to them).

I've checked where I need to add my CSS i.e.`<div class="field field-name-field-gallery field-type-image field-label-above">`.

So should I directly add this class name in `style.css` file or should it go somewhere else?

# Answer
Yes, if style.css is a CSS file that's loaded into your page (either by a module or, more likely, your theme) then that's probably a good place for your custom styles.

If you'd rather have your own file for custom styles though, you can just create a file (e.g. custom.css) in your theme folder, and add a line like this to the theme's .info file:

```
stylesheets[all][] = custom.css

```

Once you clear Drupal's caches you should see the new stylesheet included in all pages using that theme.
> 2 votes

# Answer
I believe you should write this to group them together (replaceing the spaces in the class to dots): field.field-name-field-gallery.field-type-image.field-label-above
> 0 votes

---
Tags: theming
---


# Question
Title: Mobile switch more than is mobile is not mobile
D7 I am using mobile switch with panels to display different views for different devices, but the only options I see are is mobile or is not mobile. On bigger devices like tablets I would like to display something other than what I would show on mobile phone. Is there any way I can get more option in mobile switch?

# Answer
People on tablets prefer to browse the Desktop version.

From this page: https://developers.google.com/webmasters/smartphone-sites/tablets:

> If your website has different pages to serve desktop and smartphone users and does not have tablet-specific pages, **in our experience tablet users usually expect to see your desktop site rather than the site's smartphone pages**.

Mobile switch does not work with caching on.

So I'm using the php code from this site: http://detectmobilebrowsers.com/

Also see : https://stackoverflow.com/questions/11381673/javascript-solution-to-detect-mobile-browser.

So if you want more control, you need to write your own module giving the flexibility you need.
> 0 votes

# Answer
The Mobile Detect module has a ctool submodule that provides a selection plugin.

If you install/enable the module, you can add a **Selection** rule for your panel variant, and then choose device types.

The two basic ones are isMobile and isTablet, and you will also get all of the additional rules that your version of Mobile\_Detect.php provides. The project page and README have more information.

Disclosure: I am the author of Mobile Detect.
> 0 votes

---
Tags: views, panels, theming
---


# Question
Title: Image generation in progress. Try again shortly. (503 service unavailable)
I have two exact copies of the same code installed in the same server running a common AMP stack (I am using bitnami). One copy is named as 'dev' and another one is 'prod'.

Only they have their own database & files (which are clones as well).

In dev, Image styles work just fine. I do `drush if` \- it deletes the styles and creates when viewed.

But in prod, drupal throws `503 service unavailable` with a `Image generation in progress. Try again shortly.` content on the first hit (or until the image is generated).

Of-course that comes from `image.module` line 858, when drupal finds a `lock`. And somehow setting `image_allow_insecure_derivatives` to TRUE might solve this issue.

What I don't understand is why its happening! And whats the remedy?

Thanks!

# Answer
> 1 votes
I managed to fix it!

It was a server configuration issue (PageSpeed (bitnami) to be specific).

I `tail -f`ed the access log and saw

```
xxx.my.ip.xxx - - .... "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.102 Safari/537.36"

xxx.server.ip.xxx - - .... "Serf/1.1.0 mod_pagespeed/1.6.29.2-"

```

Figured out definitely something is wrong with server (why is it hitting twice!).

Disabled and it worked fine

```
# Include conf/pagespeed.conf
# Include conf/pagespeed_libraries.conf

```

This issue was not happening in the dev site maybe because I have apache basic http authentication enabled (hence pagespeed was not caching it, just guessing).

---
Tags: 7, media
---


# Question
Title: Creating a rule for changing user role when related profile is filed
I have created 2 profiles with using profile2 for users lets name them A and B. All users will have role authenticated when they subscribe and will have to fill profile A. Then after completing subscription they can become "Pro" user by filling profile B fields. Now I want to change the user role when he fills this profile to "Pro". I was thinking about doing this with rules but couldn't make it up until now. What is the best way to do this?

# Answer
Here is the solution:

1. Add an action for "After Creating a new profile"
2. Add data comparison for profile2:type
3. Check to see if it is equal to \[Profile Type\]
4. Then add an action to change the user role. And here is the export of the rule:

{ "rules\_become\_pro\_new\_profile" : { "LABEL" : "Become Pro new profile", "PLUGIN" : "reaction rule", "OWNER" : "rules", "REQUIRES" : \[ "rules", "profile2" \], "ON" : { "profile2\_insert" : \[\] }, "IF" : \[ { "data\_is" : { "data" : \[ "profile2:type" \], "value" : "pro" } } \], "DO" : \[ { "user\_add\_role" : { "account" : \[ "profile2:user" \], "roles" : { "value" : { "5" : "5" } } } } \] } }
> 0 votes

# Answer
This is doable with Rules:

* Create rule that reacts on two events: 'After updating an existing profile' and 'After saving a new profile' - both are necessary because at some point, users might not have the profile created yet.
* Add conditions to see if all fields are filled in (use "Data comparison", "Data value is empty" or "Text comparison" conditions and their negations based on what type of fields you have)
* If all the conditions are met, give the role to the user with action "Add user role".

Btw. you do not have to worry if the user already has this role, it will not cause any unwanted behaviour if it is assigned several times.
> 0 votes

---
Tags: rules, users
---


# Question
Title: delete a specific element within field collection programmatically
This is driving me crazy it just sounds simple, but I cannot find the answer.

I have a field collection in a content type called `field_collection_mine` how you now while creating the node you can add elements to the field collection.

I have tried this:

```
$wrapper = entity_metadata_wrapper($entity_type, $entity);
$wrapper->field_collection_mine = array();
entity_save('field_collection_item',$wrapper);

```

The code above delete all the elements within the field collection, but that is now what I want!! I just want to delete for example the last element. E.g:

* Field Collection mine
* Element1
* Element2
* Element3

How can I for example delete just the element 3? The above code deletes all the elements, so `field_collection_mine` is left empty.

# Answer
Finally I could achieve what I wanted. What I did was this:

In my case I wanted to delete the last item within the field collection.

Take a look to this code, for beginners: **remember that you must have the `$entity` already loaded**, e.g.

```
// Remove the field value
unset($entity->field_salida_mercanc_a[LANGUAGE_NONE][count($entity->field_salida_mercanc_a[LANGUAGE_NONE])-1]);

// Reset the array to zero-based sequential keys
$entity->field_salida_mercanc_a[LANGUAGE_NONE] = array_values($entity->field_salida_mercanc_a[LANGUAGE_NONE]);

// Save the entity
entity_save($entity_type, $entity);

```

Thats all! The other way is:

```
// Get the node wapper
$wrapper = entity_metadata_wrapper($entity_type, $entity);
// Get the last position of the array items, thanks to the ->value() statement you can get the complete Array properties.
$field_collection_item_value = $wrapper->field_collection_mine[count($wrapper->field_collection_mine->value())-1]->value();
// Do not use 'unset' to delete the item due to is not the correct way, I use the entity_delete_multiple provided by the entity API
entity_delete_multiple('field_collection_item', array($field_collection_item_value->item_id));

```

The way above is good using `entity_metadata_wrapper` function, but with that way there is a complex bug that I do not know how to solve it, you can check it at #1880312 and after apply the patch in #9 you get the next issue.
> 1 votes

# Answer
You need to grab the id of the field collection and wrap itself in an entity wrapper. Use the save method in the wrapper to do this instead of the `entity_save` function. E.g.

```
 $wrapper = entity_metadata_wrapper('field_collection_item', $entity);
 $wrapper->field_specific_field_collection_item->set("");

```

or:

```
$wrapper->field_specific_field_collection_item = array();
$wrapper->save();

```
> 1 votes

---
Tags: 7, entities
---


title: Multipage registration form with Ctools

text:
# Question
Title: Multipage registration form with Ctools
I'm trying to follow the tutorial on multipage user registrations at http://www.grasmash.com/article/building-multistep-registration-form-drupal-7-using-ctools, but I'm doing something wrong. As it's written, if I put `function hook_form_user_register_alter(&$form, &form_state) {`, it throws me a `Parse error: syntax error, unexpected T_STRING, expecting T_VARIABLE` error; however, if I change the `&form_state` to `&$form_state`, it doesn't complain.

HOWEVER

It seems as if this form isn't replacing the existing form. There's a button added to the registration form *Create new account* (the standard Drupal *continue* button is still there). The rest of the standard Drupal form is still the same (just username and password fields).

Thanks for your help

# Answer
try this

```
function grasmash_form_user_register_alter(&$form, &$form_state, $form_id) {
  $form['#submit'] = array(
    'user_register_submit',
    'ctools_wizard_submit',
  );
}

```
> 0 votes

# Answer
from your question, it is obvious you had a typo in the function header. Php variable name must start with $ but you typed & f o r m _ s t a t e instead of & $f o r m _ s t a t e

The & only instruct that the $f o r m _ s t a t e be passed by reference.
> 0 votes

---
Tags: forms, users, chaos-tool-suite
---


# Question
Title: How to change value of a field in hook_node_view
In `hook_node_view()` I want to rewrite some fields' values. The `$node` parameter is not referenced, so how can I rewrite a value?

# Answer
Take a look at the API documentation for hook\_node\_view, specifically the comments at the end of the page -\> Has anyone been able to successfully modify a node object?. There's talk of using hook\_node\_load as a solution as well as many of the hooks that are field specific. Note the comments at the bottom of the hook\_node\_load API page that explains why $nodes is not called by reference but is still changed when changes are made to the variable within the hook re: OOP -\> http://php.net/manual/en/language.oop5.references.php.
> 3 votes

# Answer
Clear the cache or visit the Modules page to get the hook picked up after you've added it to your module. Then something like this will work.

```
function my_module_node_view($node, $view_mode, $langcode) {
  switch($node->type) {
    case 'foo':
      $node->content['field_my_field'][0]['#markup'] = 'Changed!';
    break;
  }
}

```
> 3 votes

# Answer
You can do that by implementing template\_preprocess\_field(&$variables, $hook) in your template.php

```
function THEMENAME_preprocess_field(&$variables, $hook) {
  if ($node = menu_get_object()) {
    if ($node->type == 'car') {
      if($variables['element']['#field_name'] == 'field_price') {
        $variables['items']['0']['#markup'] = $new_value; //new value;
      }
    }
  }
}

```

Check here: http://tassaf.moriamedia.com/change-field-value-in-node-view/
> 1 votes

---
Tags: 7, nodes, hooks
---


# Question
Title: How to edit a node programatically after it has been created?
My articles have a field 'Ranking' and I'd like to give a value to this field after a node has been created. The value depends on the node's ranking in a view called 'Top 3'. I tried the following in my custom module 'Top', but it doesn't work.

```
function top_node_insert($node) {
  $top = views_get_view_result('top_3');

  $found = false;
  foreach($top as $key => $value) {
    if ($value->nid == $node->nid) {
        $found = true;
        break;
    }
  }

  if ($found) $ranking = $key + 1;
  $node->field_hoogste_ranking[LANGUAGE_NONE][0]['value'] = $ranking;
}

```

What did I do wrong and what's the correct version?

# Answer
If you look at the Node API Hooks description here, you will see that hook\_node\_insert is called after field\_attach\_insert. That means that at the point hook\_node\_insert is called the fields for the node are already written to the database. If you keep your code in top\_node\_insert, then add field\_attach\_update('node', $node) to update the fields with the new data. It might look something like this:

```
function top_node_insert($node) {
  $top = views_get_view_result('top_3');

  $found = false;
  foreach($top as $key => $value) {
    if ($value->nid == $node->nid) {
        $found = true;
        break;
    }
  }

  if ($found) {
    $ranking = $key + 1;
    $node->field_hoogste_ranking[LANGUAGE_NONE][0]['value'] = $ranking;
    field_attach_update('node', $node);
  }
}

```

Alternatively, you can try and use hook\_node\_presave.
> 4 votes

# Answer
You have to use hook\_node\_presave()

if you use hook\_node\_insert() then the value will not be saved in $node object
> 1 votes

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


# Question
Title: Should I call my function in Drupal custom modules?
I've been trying to implement a redirect to user register page if an anonymous user tries to access a specific page. I used the following code in my custom module.

```
function myregistration_init(){
  global $user;
  if ($user->uid == 0  && $_GET['q'] == 'order_translaton' ) {
    drupal_goto('user/register');
  }
}

```

However, this code did not work until I wrote myregistration\_init() after the function body. I know that in Drupal modules function works automatically without the need to call it. For instance, the following code works without function call:

```
function myregistration_form_user_register_form_alter(&$form,&$form_state){
$form['#submit'][] = 'myregistration_submit';
function myregistration_submit(&$form,&$form_state) {
$form_state['redirect']= 'order_translaton';
}
}

```

Please explain how all this works in Drupal modules.

# Answer
Do not get confused with drupal hooks and functions.

**Drupal Hooks:**

They allow you to interact with core functionality without hacking it. In our custom module we implement hooks which are invoked by drupal at the event the hook is exposed for automatically. So consider the hook\_init(), so when drupal is initialized the system will look inside each contributed, custom module if any of the module has implemented hook\_init(), and if so, drupal will invoke functionality written inside the hook implementation for every single module in the order of their module weight.Basically all we do is implement the hook in custom module and **clear the caches** (clearing the caches is important step as drupal caches all hook implementations so that it doesn't have to look inside every enabled module files to find if there is a matching hook implementation in order to be executed, but since a new hook is added to system we have to clear the cache so that drupal can rebuild information about implemented hooks.), we never explicitly call the hooks, as they are invoked by drupal system itself. So hooks are kind of functions invoked by drupal itself.

**functions:**

Set of code which gets executed when called explicitly.

About your code

```
  /**
    * Implements hook_init()
    */
    function myregistration_init(){
      global $user;
      if ($user->uid == 0  && $_GET['q'] == 'order_translaton' ) {
        drupal_goto('user/register');
      }
    }

```

About your code:

```
function myregistration_form_user_register_form_alter(&$form,&$form_state){
  $form['#submit'][] = 'myregistration_submit';
  function myregistration_submit(&$form,&$form_state) {
    $form_state['redirect']= 'order_translaton';
  }
}

```

I am not sure why this code is working, it should be rather like following.

```
/**
  * Implements hook_form_alter()
  */
function myregistration_form_user_register_form_alter(&$form,&$form_state){
  $form['#submit'][] = 'myregistration_submit';
}

/**
  * Custom submit hanlder.
  */
function myregistration_submit(&$form,&$form_state) {
  $form_state['redirect']= 'order_translaton';
}

```

Both hook implementation codes above should work, but you might need to clear your caches after implementing the code. But do not call it explicitly anywhere in code.
> 4 votes

# Answer
What is that page.. is it a node? if yes then you need to implement hook\_node\_view()

and inside it you need to check if it's the node you want to restrict access to it.. and check if the user is anonymous then redirect him where you want

```
function YOURMODULE_node_view($node, $view_mode) {
  if ($node->type=="YOURTYPE"){
    if ($view_mode == 'full'){
      global $user;
      if (!$user->uid) {
        drupal_goto('user/register');
      }
    }
  }
}

```

If You want to do that another way.. which will help in case the page is not a node then you need to do that check in your theme

```
function THEMENAME_preprocess_page(&$variables, $hook) {}

```
> 0 votes

---
Tags: 7, users, redirection
---