# Question
Title: How to Retrieve FID from UUID on Feature Enable
I would like to use features to import/export some content. The content type conains custom field of file, so I am using hook\_uuid\_node\_features\_export\_render\_alter(&$export, $node, $module){..} to add UUID of the file to the export.

```
function MODULE-NAME_uuid_node_features_export_render_alter(&$export, $node, $module){
        if($module == 'MODULE-NAME'){
        $field_instance = field_get_items('node', $node, 'field_elastic_slide');
        foreach($field_instance as $key => $instance){
            $file = file_load($instance['image']);
            $export->field_elastic_slide['und'][$key]['image'] = (array)$file;
            $file = file_load($instance['thumb_image']);
            $export->field_elastic_slide['und'][$key]['thumb_image'] = (array)$file;
        }
    }
}

```

This works well and the UUID along the other file info is written into the file ending .features.uuid\_node.inc part of the export module. So far, so good.

When importing, i would like to use the UUID to look up the FID of file on the Drupal instance import taking place, so i am using:

```
function MODULE-NAME_uuid_node_features_rebuild_alter(&$node, $module){
    if($module == 'MODULE-NAME'){
        $field_instance = field_get_items('node', $node, 'field_elastic_slide');
        foreach($field_instance as $key => $instance){
            $uuid = $instance['image']['uuid'];
            // We have a uuid - we'll try to retrieve fid.
            $file = entity_uuid_load('file',$uuid);//attempt 1
            $slider_img = current($file);

            $fid = uuid_get_serial_id('file', 'fid', $uuid); //attempt 2

            // There is no local image.
            if (empty($fid)) {
                watchdog(WATCHDOG_NOTICE, 'Slider image with uuid: ' . $uuid.' was not found', WATCHDOG_ERROR);
            }
            $node->field_elastic_slide['und'][$key]['image'] = $fid;
...

```

This is not working. Where is the UUID\<-\>FID Map stored for features? How to retrieve the FID at the time of importing(enabling the feature)? Any help is much appriciated

# Answer
I guess i didn't know exactly how the export/import works...perhaps, i still do not, but here is my theory so far. When importing custom fields containing file, we have to save the file in the table file\_managed by ourselves. The feature module will only do the work of importing files for the default field types(file, text,etc) and not for custom fields which is our case.

Here is quick write up http://margotskapacs.com/2014/03/make-custom-field-with-file-exportable-in-drupal-features/
> 0 votes

---
Tags: migrations, entities, features
---


title: Grant a role access to certain content

text:
# Question
Title: Grant a role access to certain content
Is there a way to only grant a role access to certain content? So that every user given that role can access what they need without others being able to, while still being limited from accessing content that only other roles can access?

Also is there a way to automatically grant new roles to users as a result of performing certain actions? Just like how some forums work where you can only start new threads when you've written 10 replies? Only this will be people being able to access a new level of the site when they have say uploaded a file or corresponded with a certain person and that person has given a thumbs up? The latter I suppose could come in form of you being granted a role when a certain level is reached that enables you to give other users roles up to a certain limit?

Cheers, Thor

# Answer
> 0 votes
There are a variety of content access modules, so you might want to look around to find one that best suits your specific needs but a good start is often https://drupal.org/project/content\_access

As for automatic role delegation, there are a variety of ways you can do so, too. Rules is a great place to start https://drupal.org/project/rules but depending on what your requirements are, you might need to write a custom module. There are also a variety of rules-related modules that expand on it's offerings that might help you out. Rules is very capable for many things but sadly, if you have very specific needs it might be a little more complex than point-and-click.

---
Tags: users
---


# Question
Title: Don't show block until after a number of comments
I have created a block and I don't want it to display until there are a number of comments posted on the node because if I just display the block the site will look ugly.

How would I go on to make it that when the node has lets say 6 comments the block or some content will show but when the node has less than 6 comments the block wont show.

# Answer
use php code for your block "Show block on specific pages" fieldset settings, paste next code:

```
<?php
if (arg(0) == 'node') {
  $node = node_load(arg(1));
  if ($node) {
    return $node->comment_count > 5;
  }
}
return FALSE;
?>

```

p.s. Enable PHP filter module, if you not see PHP code option.
> 0 votes

# Answer
If you are making the block using Views, you should be able to do this pretty easily by adding a view filter of "Content: Comment Count" is greater than or equal to "6"

It will then only show the block when it has results that meet your criteria.
> 0 votes

---
Tags: blocks, comments
---


# Question
Title: Put a wrapper div around every second row in drupal view
Hi there I am trying to use a views template override to put a wrapper div around every group of two rows. If the last group only has 1 row ( say if there were 5 rows total ) I want to end the wrapper div.

I found some code for this but it's not working I am getting zero output from this I can see my comment tag but that it.

```
<!-- test row output -->

<?php
$group_nr = 1;                  // first group number
$last_row = count($rows) -1;    // last row
$wrapper  = 2;                  // put a wrapper around every 2 rows
?>
<?php foreach ($rows as $id => $row): ?>
<?php if ($id % $wrapper == 0) {print '<div class="row">'; $i = 0; $group_nr++; } ?>
<?php print $row; ?>
<?php $i++; if ($i == $wrapper || $id == $last_row) print '</div>'; ?>
<?php endforeach; ?>

```

Any idea what I am doing wrong

My template is called views-view--homepage-awards--block-2.tpl.php

I want my output to look like this

```
<div class="row">
  <div>row1</div>
  <div>row2</div>
</div>
<div class="row">
  <div>row3</div>
  <div>row4</div>
</div>
<div class="row">
 <div>row5</div>
</div>

```

Any help would be greatly appreciated.

# Answer
> 4 votes
This should accomplish it:

```
<?php
  $last=count($rows) - 1;
?>
<?php foreach ($rows as $id => $row): ?>
  <?php if (!($id & 1)): // if this an even row id, open the <div> ?>
    <div class="row">
  <?php endif; ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>
  </div>
  <?php if ($id==$last || ($id & 1)): // if this the last or an odd row id, close the <div> ?>
    </div>
  <?php endif; ?>
<?php endforeach; ?>

```

It'll wrap each group of two rows with a `div` with a class of `row` and make sure if it's an odd number that the final `div` is closed.

Now, if you want to remove all the classes from those inner rows that Views inserts, then you just need to clean them up or out of that obvious `if` in the middle.

CAVEAT: If you have done anything with Views pre\_render()ing or other similar hooks that have deleted any of the rows out of the results and not reset the ids to be consecutive, this logic will most probably fail.

---
Tags: views
---


title: Drupal Collaboration for beginners

text:
# Question
Title: Drupal Collaboration for beginners
I am currently working on a team of four people trying to develop a simple news website. We are having a hard time figuring out the best way to collaboration. I've found other threads that suggested using Features module; however, that is outside of our scope at the moment. Can you suggest a simpler way to collaborate?

# Answer
Since you specifically mention the **Features** module in your question, (also mentioned in the upvoted and accepted answer to: How do I manage collaborative development on a Drupal site?) I shall assume you're asking about how to share the database and code under development among team members, and not about tools for team collaboration ("groupware") in general.

First, let me say that I don't think **Features** is the right tool for this task, and shall propose an alternative set of tools.

A prerequisite for team collaboration is to have a staging server for testing out development versions of the project that is separate from your production server. All development code is tested at the staging server, and only pushed to production server when it is stable and ready for deployment. However, the developers doesn't work directly at the staging server. Each developer work at his or her own workstation, using a revision control and source code management (SCM) to coordinate his or her work with the rest of the team.

The SCM system allow team members to work in parallel on different *branches* of the code without interfering with each other. Only the *master* branch is deployed on the staging server for testing purposes.

To mirror the database between production, staging and workstations, there is a module named Backup and migrate that can be used if you're on shared hosting and not managing your own database. If you're managing your own database server, this is the only project on that server, and you use *mysql*, the following pair of commands are handy:

To dump:

```
mysqldump --all-databases --opt -u root -p > DUMP.sql

```

To restore:

```
mysql -u root -p < DUMP.sql

```

If yours is not the only database on that server, script some version of `mysqldump` (or equivalent if you're not using *mysql*) that dumps your databases only.

Make a policy that it is the database on the production server that is master. The staging server and workstations should be a copy of the production database, not vice versa.

Note that Drupal 7 keeps all its admin setting in the database. This means that mirroring the database between the production site, staging site and workstations will migrate admim settings without **Features**.

Now, for sharing the code:

The standard way for sharing code among the members of a development team is to use SCM system. Drupal happens to be default be managed with such a system named *git*.

*Git* allows the use of local or remote repositories. If the team members are located in the same physical space, you can set up a local repository on your staging server. If they're spread geographically, you can set up a remote repositiory. If you don't mind others having read access at your code under development, you can use a *sandbox* at Drupal.org as a remote repository. You can also use a project area on *GitHub*. *GitHub* is not only a repository, but comes with a some tools for collaboration, and allows both public and private repositories.

Basically, a SCM system allow team members to pull source code and documentation from the respository shared by the team members, and push it back in again after having worked on it. The SCM keeps track of changes and if there is a conflict (i.e. somebody tries to push code that doesn't the contain the changes another team member has committed), it will tell you and also suggest a way to resolve this conflict.

Usually, with some cordial communication about how the tasks are divided among the members of the team, there will be no conflicts. But with the SCM system keeping track of things, conflicts become manageable even if mistakes are made or communication fails.

There exists a lot of tutorials on getting started with and using *git* (GIYF). Two I will recommend are: the *git-scm* website and *Pro Git* by Scott Chacon.
> 1 votes

---
Tags: 7
---


# Question
Title: How do I manage collaborative development?
I work with another developer on a Drupal site. We have struggled to find a good way to work on different parts of the site at the same time without getting in each others way. We've tried working on the same development instance of the site, but we often step on each others toes, or bring down the site with some bad code making it impossible for the other to continue working until it's resolved. So we've moved to separate development instances. But now it's a big pain to merge our work into a single instance of the site. We basically end up redoing everything on a shared copy.

The biggest problem we have now is how do we merge database changes, and how do we include the database in our source control system? The files are easy, just track them all (we use git) and merge our work, resolving conflicts where needed. But this doesn't really work with the database. We can take a SQL dump and include that in our git repository, but we can't really merge the databases. The Features module helps a little, letting us export some of our database work into code which can then be versioned and merged. However, not even close to everything supports Features. So...

* What steps can we take to easily merge our database changes?
* How should we version the database (is putting a dump file in git a good way to do it)?
* Are there any modules available that help with some of these problems?
* Or, are we stuck with working on the same copy of the site? (please so no)

---

Edit: In the comments we discussed what things can't be exported with Features and one of them was Taxonomies. There's another question that deals with that.

# Answer
It is a workflow change but you should get used to working on a fresh dump of the live DB. There are three ways to get changes into the DB.

1. Features. This won't work for everything but will for a lot of things you need.
2. update hooks. When features won't work you can hard code things into an update hook of a module you own.
3. Manual changes. Use sparingly. Some things don't come naturally to features or update hooks and are just much easier to do manually. This is a last resort but sometimes is the only piratical way.

If you can. Several times a day get a fresh dump and test your build, you should have less integration problems.
> 5 votes

# Answer
I answered a similar question and am going to adjust it slightly to answer your question here.

My root suggestion is that you have a development/staging server where code changes are checked out using a Continuous integration system on a frequent basis (e.g., every 5 minutes). Thus, on your local machine, you only work on one feature request/bug report at a time, being sure to clearly delineate this task from others that people might be working on and communicating to your teammates that you are working on it (redmine or other bug tracking is great for this). Then, you commit changes on a regular basis, and they get pulled down to the dev/staging server, as do your teammates. Ideally, you have unit tests built into your continuous integration system (highly recommend luntbuild or QuickBuild for this by the way, but Hudson also works). The CI system or tests can automatically pick up on any conflicts you might have introduced as soon as you check in your code. If you need to make content (non-code) changes, you do so on the dev/staging server.

As to the database portion, I've adopted basically two schools of thought here (a 3rd school of thought, doing database diffs, I won't discuss because the complexity is quite high).

1. Deploy by dropping the production database, and importing a mysqldump of the development database. Optionally, run a regex find/replace beforehand on any hard-coded absolute links which reference the dev URL in the SQL dump. After importing the dev db into prod, automatically run SQL statements (usually via script) afterwards to change any settings that are different for prod than dev (e.g., maybe you have in variables table some connection settings for connecting to external systems that you need to change to point at prod external systems instead of at the dev version).
2. Use the Features module, as mentioned by budda, for admin settings, and use the Node Export module for content export/import in combination with the Delete All module. So workflow is:

use node\_export and features to export nodes/features to files Optionally (and hopefully) version control Load files on prod system Use drush or admin interface to load features Use drush delete-all or admin interface to delete all nodes of the types you want to import Use drush ne-import or the admin interface to import the nodes from the nodes file you exported. One note, I would highly suggest adopting a standard workflow, where content goes one direction only. Either Dev -\> Prod or Prod -\> Dev (I prefer this one).

I've done this, and am doing this on some big systems, with fairly good results, but there will always be many ways to slice this apple, choose whichever way works best for you.
> 4 votes

# Answer
While this is an old question with an accepted answer, I believe that there is still room for another one.

First, let me say up front that I don't think **Features** is the right tool for this task, and shall propose an alternative set of tools.

A prerequisite for team collaboration is to have a staging server for testing out development versions of the project that is separate from your production server. All devlopment code is tested at the staging server, and only pushed to production server when it is stable and ready for deployment. However, the developers doesn't work directly at the staging server. Each developer work at his or her own workstation, using a revision control and source code management (SCM) to coordinate his or her work with the rest of the team.

The SCM system allow team members to work in parallel on different *branches* of the code without interfering with each other. Only the *master* branch is deployed on the staging server for testing purposes.

To mirror the database between production, staging and workstations, there is a module named Backup and migrate that can be used if you're on shared hosting and not managing your own database. If you're managing your own database server, this is the only project on that server, and you use *mysql*, the following pair of commands are handy:

To dump:

```
mysqldump --all-databases --opt -u root -p > DUMP.sql

```

To restore:

```
mysql -u root -p < DUMP.sql

```

If yours is not the only database on that server, script some version of `mysqldump` (or equivalent if you're not using *mysql*) that dumps your databases only.

Make a policy that it is the database on the production server that is master. The staging server and workstations should be a copy of the production database, not vice versa.

Note that Drupal 7 keeps all its admin setting in the database. This means that mirroring the database between the production site, staging site and workstations will migrate admim settings without **Features**.

Now, for sharing the code:

The standard way for sharing code among the members of a development team is to use SCM system. Drupal happens to be default be managed with such a system named *git*.

*Git* allows the use of local or remote repositories. If the team members are located in the same physical space, you can set up a local repository on your staging server. If they're spread geographically, you can set up a remote repositiory. If you don't mind others having read access at your code under development, you can use a *sandbox* at Drupal.org as a remote repository. You can also use a project area on *GitHub*. *GitHub* is not only a repository, but comes with a some tools for collaboration, and allows both public and private repositories.

Basically, a SCM system allow team members to pull source code and documentation from the respository shared by the team members, and push it back in again after having worked on it. The SCM keeps track of changes and if there is a conflict (i.e. somebody tries to push code that doesn't the contain the changes another team member has committed), it will tell you and also suggest a way to resolve this conflict.

Usually, with some cordial communication about how the tasks are divided among the members of the team, there will be no conflicts. But with the SCM system keeping track of things, conflicts become manageable even if mistakes are made or communication fails.

There exists a lot of tutorials on getting started with and using *git* (GIYF). Two I will recommend are: the *git-scm* website and *Pro Git* by Scott Chacon.
> 0 votes

---
Tags: 7
---


# Question
Title: Update user fields programatically resets password
When trying to update user (custom) fields programatically in drupal 7, I get the weird problem that whenever I do, my password is reset, my user is logged out, and I have to reset password to be able to log-in again.

I have tried a few different things, none seem to work, here's my code.

```
global $user;
global $language;
$fullUser = user_load($user->uid);

$updateUserParams = array();

$updateUserParams['language'] = $language->language;
$updateUserParams['field_first_name'][LANGUAGE_NONE][0]['value'] = $form_state['values']['firstName'];
$updateUserParams['field_surname'][LANGUAGE_NONE][0]['value'] = $form_state['values']['lastName'];

$year = $form_state['values']['birthdate']['year'];
$month = $form_state['values']['birthdate']['month'];
$day = $form_state['values']['birthdate']['day'];

$birthdate = date( "Y-m-d", strtotime($year.'-'.$month.'-'.$day));

$updateUserParams['field_birthdate'][LANGUAGE_NONE][0]['value'] = $birthdate;
$updateUserParams['gender'][LANGUAGE_NONE][0]['value'] = $form_state['values']['gender'];
$updateUserParams['field_address']['en'][0]['thoroughfare'] = $form_state['values']['street'];
$updateUserParams['field_address']['en'][0]['postal_code'] = $form_state['values']['postalCode'];
$updateUserParams['field_address']['en'][0]['locality'] = $form_state['values']['city'];
$updateUserParams['field_phone'][LANGUAGE_NONE][0]['value'] = $form_state['values']['phone'];

user_save($user, $updateUserParams);

```

What am I doing wrong?

# Answer
> 0 votes
@Nikit, your answer pushed me in the right direction, however, it wasn't correct.

the problem wasn't that I had the `pass` variable defined in my `$updateUserParams`, as you can see, I do not.

The problem was, that i had the `pass` variable defined in the `$user` I did my `user_save` with. I managed to fix the problem by unsetting the `pass` on my user object. And to be saved, I did the update on the `$fulluser` instead of the `$user` which is a global variable, and could potentially break things.

Here's the working code.

```
    global $user;
    global $language;
    $fullUser = user_load($user->uid);

    $updateUserParams = (array) $fullUser;

    $updateUserParams['language'] = $language->language;
    $updateUserParams['field_first_name'][LANGUAGE_NONE][0]['value'] = $form_state['values']['firstName'];
    $updateUserParams['field_surname'][LANGUAGE_NONE][0]['value'] = $form_state['values']['lastName'];

    $year = $form_state['values']['birthdate']['year'];
    $month = $form_state['values']['birthdate']['month'];
    $day = $form_state['values']['birthdate']['day'];

    $birthdate = date( "Y-m-d", strtotime($year.'-'.$month.'-'.$day));

    $updateUserParams['field_birthdate'][LANGUAGE_NONE][0]['value'] = $birthdate;
    $updateUserParams['gender'][LANGUAGE_NONE][0]['value'] = $form_state['values']['gender'];
    $updateUserParams['field_address']['en'][0]['thoroughfare'] = $form_state['values']['street'];
    $updateUserParams['field_address']['en'][0]['postal_code'] = $form_state['values']['postalCode'];
    $updateUserParams['field_address']['en'][0]['locality'] = $form_state['values']['city'];
    $updateUserParams['field_phone'][LANGUAGE_NONE][0]['value'] = $form_state['values']['phone'];

    unset($fullUser->pass);
    unset($updateUserParams['pass']);

    user_save($fullUser, $updateUserParams);

```

# Answer
> 0 votes
If you look user\_save there special code at the top, that prevent updating password if `pass` not provided on `$updateUserParams`. So please check your other modules or Rules, that possibly resetting password each time, then user\_save called.

---
Tags: entities, users
---


# Question
Title: Add new field to core module by overide drupal 7
I want to add one more field of Sex (male/female)radio button in core Login Form Module. How do i achieve this by override.

# Answer
Adding field into login form is not very difficult. You can do it easily by making a custom module & altering the login form by help of hook\_form\_alter like this.

```
function hook_form_alter(&$form, &$form_state, $form_id) {
  $options = array(0 => t('Male'), 1 => t('Female'));
  if ($form_id == 'user_login_block' || $form_id == 'user_login') {
    $form['gender'] = array(
      '#type' => 'radios',
      '#title' => t('Gender'),
      '#options' => $options,
      '#description' => t('Select your gender'),
    );
  }
  return $form;
}

```

But next things will be tricky: for example, what you have to do with their selected values.
> 0 votes

---
Tags: forms
---


# Question
Title: User relationship module - error strict warning: Only variables should be passed by reference
module name: User Relationships.

module version is: 7.x-1.0-alpha5

whenever i try to add relationship type or edit it give me this error:

```
Strict warning: Only variables should be passed by reference in theme_user_relationship_implications_form_table() (line 103 of C:\wamp\www\drupal\modules\user_relationships\user_relationship_implications\user_relationship_implications.module).
Strict warning: Only variables should be passed by reference in theme_user_relationship_implications_form_table() (line 104 of C:\wamp\www\drupal\modules\user_relationships\user_relationship_implications\user_relationship_implications.module).
Strict warning: Only variables should be passed by reference in theme_user_relationship_implications_form_table() (line 105 of C:\wamp\www\drupal\modules\user_relationships\user_relationship_implications\user_relationship_implications.module).

```

the code in user\_relationship\_implications.module is as follows:

```
function theme_user_relationship_implications_form_table($variables) {
$form = $variables['form'];
$headers = array(t('Relationship Type'), t('Strict'), t('Reverse'));
$rows = array();

foreach ($form['opts'] as $rtid => $elements) {
if (!is_numeric($rtid)) {
  continue;
}
$rows[$rtid] = array(
  drupal_render(array_shift($elements)),
  drupal_render(array_shift($elements)),
  drupal_render(array_shift($elements)),
);
}
return theme('table', array('header' => $headers, 'rows' => $rows));
}

```

in the above code line 103-105 is:

```
drupal_render(array_shift($elements)),
drupal_render(array_shift($elements)),
drupal_render(array_shift($elements)),

```

Can you please help me solve the error and also bring to my knowledge why does this occur?

# Answer
IMHO, this is a bug in the User Relationships module, and should be reported to that module's issue queue.

If you look at the documentation, you see that the template for `drupal_render` is:

```
drupal_render(&$elements)

```

Passing a function call by reference not good coding practice (but it will not have adverse effects if you never use the return value passed by reference).

The following will do the same thing and not produce the warning:

```
$_shift1 = array_shift($elements);
$_shift2 = array_shift($elements);
$_shift3 = array_shift($elements);
$rows[$rtid] = array(
  drupal_render($_shift1),
  drupal_render($_shift2),
  drupal_render($_shift3),
);

```

The module author probably doesn't have PHP-warnings enabled, and never saw the warning.
> 0 votes

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


# Question
Title: how to get individual classes for each menu list items
I am theming my website and used the following code to print my main menu.

```
<?php
 $main_menu = variable_get('menu_main_links_source', 'main-menu');
 $tree = menu_tree($main_menu);
 print render($tree);
?>

```

Now, I need to have individual class name of each list item, so that I can call different background images using css. I would like to have class with name 'menu-497' as shown in screenshot. I couldn't figure out how this is done. Please help.
Old code which used to load individual list class is below. But this code won't load submenu, so I am not using it.

```
<?php print theme('links__system_main_menu', array(
  'links' => $main_menu,
  'attributes' => array(
    'id' => 'topNav',
  ),
)); ?>

```

# Answer
It looks like you need Menu attributes module:

> You should use this module when
>
> * You want to "nofollow" certain menu items to sculpt the flow of PageRank through your site
> * You want to give a menu item an ID so you can easily select it using jQuery
> * You want to add additional classes or styles to a menu item

Alternatively, if you don't mind some coding, see `theme_menu_link()`. Comments in it's documentation already shows how to do it:

> ```
>    function superseven_menu_link(array $variables) {
>      $variables['element']['#attributes']['class'][] = 'menu-' . $variables['element']['#original_link']['mlid'];
>
>      return theme_menu_link($variables);
>    }
>
> ```
> 1 votes

---
Tags: theming, routes
---


title: Simple cycle that pick next free id

text:
# Question
Title: Simple cycle that pick next free id
What I'm trying to do is function working like this:

```
function my_function($id){
   while($id){
      if($id = not free){
          $id=$id+'1';
      } else {
          return $id;
      }
   }
}

```

I'm new to php and drupal generally and can't figure out how to handle this cycle. For instance, 'if statement' should test if the id is already in database. If it is then +1 to id if not return this free id.

I'm using this to check whether the id is free or not:

```
$check_unique_station_id = 'SELECT field_station_id_value FROM {field_data_field_station_id} WHERE field_station_id_value = :input_id LIMIT 1';
if (db_query($check_unique_station_id, array(':input_id'=>$input_id))->fetchField()){

}

```

Any help would be appreciated.

//EDIT

I guess I didn't explain it well. I have custom module and few custom fields. One of them is 'station\_id' which is field for storing number (type) of station. Let's say it is a name of the station expressed in number. Here is an example of values I have in database in field\_station\_id:

1. 22
2. 45
3. 89

Now what I want to do: when user input=22 then check if 22 already exists and if so check if exist 22+1. When input=45 then return 46 etc. Now I see that I explained it really bad. Hope that now you know what I mean.

// EDIT 2 // MY SOLUTION

I came up with this piece of code. However I was just wondering if there is some query function to do it (propably faster). As mentioned by Felix downthere (pick as the right answer) it seems that the only query function founds the maximum number in db and return it. Which is not what I want.

Here is my code:

```
function free_value($occupied_value){

// loads all used values from db
$query_all_occupied_values = 'SELECT field_station_value FROM {field_data_field_station_value} WHERE field_station_value >= :occupied_value ORDER BY field_station_value';
$all_occupied_values = db_query($query_all_occupied_values, array(':occupied_value'=>$occupied_value))->fetchAll();

// count number of rows of used station_values
$number_of_values = count($all_occupied_values)-1;

// finds first closest value which is not occupied in db
for($i=0; $i<=$number_of_values; $i++) {
    if($occupied_value == $all_occupied_values[$i]->field_station_value) {
        $occupied_value = $occupied_value+1;
    } else {
        break;
    }
}

$free_value = $occupied_value;

return $free_value;

```

}

# Answer
This will select the next free ID:

```
$next_free_id = db_query("SELECT MAX(field_name) + 1 FROM table_name")->fetchField();

```
> 2 votes

---
Tags: 7
---


# Question
Title: When using hook_form_alter to modify a content type's node add / edit form, where do I put the #states property?
This is actually a compound question. All in all the question is:

**When using hook\_form\_alter to modify an existing content type's node add / edit form, where do I put the #states property, and, within the definition of the #state array, how do I determine what the value of 'name' should be in ':input\[name="somename"\]'?**

NOTE: If you're very familiar with using #states and modifying node add / edit forms, please skip to the very last of the question where my non-working sample code is listed.

I've created a custom content type and I would like to alter certain node add / edit form elements to show up conditionally based on the values in other fields. To do this, I'd like to use the #states property (Here is a quick intro where I first learned about #states).

Most of the examples and tutorials I find are about creating custom forms. But the same approach does not seem to be working when modifying existing custom content type node add / edit forms.

For example, notice in the link above the following:

```
$form['kids'] = array(
    '#title' => t('How many kids do you have?'),
    '#type' => 'select',
    '#options' => array(0, 1, 2),
  );

  $form['kids_preferences'] = array(
    '#title' => t('Your kids\' preference'),
    '#type' => 'radios',
    '#options' => array('moto' => 'Motorcycles', 'cars' => 'Cars'),
     // Show this field only if the user has kids.
    '#states' => array(
      'visible' => array(
        'input[name="marriage"]' => array('checked' => TRUE),
      ),
      'disabled' => array(
        'select[name="kids"]' => array('value' => '0'),
      ),
    ),
  );

```

One would think then, based on the above (which is the same in all other tutorials and Drupal Docs), that you'd add \['#states'\] = array(etc..) immediately after the first field element key, right?

Looking at the 'disabled' definition, you'd also conclude that you'd use the field key (kids) to reference the value in the 'name=' part of the #states array, correct?

So, after doing dpm($form) I indeed found my field names. According to dpm they were $form\["myfield1"\] and $form\["myfield2"\].

So because $form\['myfield2'\] depends on a value in $form\['myfield1'\], I tried:

```
$form['field_rf_which_state_territory']['#states'] = array(
            'visible' => array(
                ':input[name="myfield1"]' => array('value' => 'Yes')
            ),
        );

```

However, that doesn't work. **Why?**

After doing a lot of digging only, I started to see references to array structures like `$form['myfield1']['und']['0']['#states']`

I don't understand that, but I gave it a shot. Here are the actual data dumps of the two form elements from my content type node add form that I need to interact. (sorry for the long dump)

1) `print_r($form["field_rf_which_state_territory"]);`

```
Array
(
[#type] => container
[#attributes] => Array
    (
        [class] => Array
            (
                [0] => field-type-list-text
                [1] => field-name-field-rf-which-state-territory
                [2] => field-widget-options-select
            )

    )

[#weight] => 15
[#tree] => 1
[#language] => und
[und] => Array
    (
        [#entity] => stdClass Object
            (
                [uid] => 1
                [name] => admin
                [type] => snaped_resource_finder
                [language] => und
                [title] =>
                [status] => 1
                [promote] => 1
                [sticky] => 0
                [created] => 1396239314
                [revision] =>
                [comment] => 2
                [menu] => Array
                    (
                        [link_title] =>
                        [mlid] => 0
                        [plid] => 0
                        [menu_name] => main-menu
                        [weight] => 0
                        [options] => Array
                            (
                            )

                        [module] => menu
                        [expanded] => 0
                        [hidden] => 0
                        [has_children] => 0
                        [customized] => 0
                        [parent_depth_limit] => 8
                    )

            )

        [#entity_type] => node
        [#bundle] => snaped_resource_finder
        [#field_name] => field_rf_which_state_territory
        [#language] => und
        [#field_parents] => Array
            (
            )

        [#columns] => Array
            (
                [0] => value
            )

        [#title] => Which State / Territory
        [#description] =>
        [#required] =>
        [#delta] => 0
        [#type] => select
        [#default_value] => Array
            (
            )

        [#multiple] =>
        [#options] => Array
            (
                [_none] => - None -
                [AL] => Alabama
                [AK] => Alaska
                [AZ] => Arizona
                [AR] => Arkansas
                [CA] => California
                [CO] => Colorado
                [CT] => Connecticut
                [DE] => Delaware
                [DC] => District Of Columbia
                [FL] => Florida
                [GA] => Georgia
                [HI] => Hawaii
                [ID] => Idaho
                [IL] => Illinois
                [IN] => Indiana
                [IA] => Iowa
                [KS] => Kansas
                [KY] => Kentucky
                [LA] => Louisiana
                [ME] => Maine
                [MD] => Maryland
                [MA] => Massachusetts
                [MI] => Michigan
                [MN] => Minnesota
                [MS] => Mississippi
                [MO] => Missouri
                [MT] => Montana
                [NE] => Nebraska
                [NV] => Nevada
                [NH] => New Hampshire
                [NJ] => New Jersey
                [NM] => New Mexico
                [NY] => New York
                [NC] => North Carolina
                [ND] => North Dakota
                [OH] => Ohio
                [OK] => Oklahoma
                [OR] => Oregon
                [PA] => Pennsylvania
                [RI] => Rhode Island
                [SC] => South Carolina
                [SD] => South Dakota
                [TN] => Tennessee
                [TX] => Texas
                [UT] => Utah
                [VT] => Vermont
                [VA] => Virginia
                [WA] => Washington
                [WV] => West Virginia
                [WI] => Wisconsin
                [WY] => Wyoming
            )

        [#value_key] => value
        [#element_validate] => Array
            (
                [0] => options_field_widget_validate
            )

        [#properties] => Array
            (
                [strip_tags] => 1
                [optgroups] => 1
                [empty_option] => option_none
                [filter_xss] =>
            )

        [#after_build] => Array
            (
                [0] => field_form_element_after_build
            )

    )

[#access] => 1
)

```

2) `print_r($form['field_rf_snaped_associated']);`

```
Array
(
[#type] => container
[#attributes] => Array
    (
        [class] => Array
            (
                [0] => field-type-list-text
                [1] => field-name-field-rf-snaped-associated
                [2] => field-widget-options-buttons
            )

    )

[#weight] => 14
[#tree] => 1
[#language] => und
[und] => Array
    (
        [#entity] => stdClass Object
            (
                [uid] => 1
                [name] => admin
                [type] => snaped_resource_finder
                [language] => und
                [title] =>
                [status] => 1
                [promote] => 1
                [sticky] => 0
                [created] => 1396239314
                [revision] =>
                [comment] => 2
                [menu] => Array
                    (
                        [link_title] =>
                        [mlid] => 0
                        [plid] => 0
                        [menu_name] => main-menu
                        [weight] => 0
                        [options] => Array
                            (
                            )

                        [module] => menu
                        [expanded] => 0
                        [hidden] => 0
                        [has_children] => 0
                        [customized] => 0
                        [parent_depth_limit] => 8
                    )

            )

        [#entity_type] => node
        [#bundle] => snaped_resource_finder
        [#field_name] => field_rf_snaped_associated
        [#language] => und
        [#field_parents] => Array
            (
            )

        [#columns] => Array
            (
                [0] => value
            )

        [#title] => Is this material associated with a SNAP-Ed program?
        [#description] =>
        [#required] => 1
        [#delta] => 0
        [#type] => radios
        [#default_value] =>
        [#options] => Array
            (
                [Yes] => Yes
                [No] => No
            )

        [#value_key] => value
        [#element_validate] => Array
            (
                [0] => options_field_widget_validate
            )

        [#properties] => Array
            (
                [filter_xss] => 1
                [strip_tags] =>
                [empty_option] =>
                [optgroups] =>
            )

        [#after_build] => Array
            (
                [0] => field_form_element_after_build
            )

    )

[#access] => 1
)

```

The first thing I noticed is that for each of those `[#type] => container` That's confusing. Drupal 7 form field API doesn't has very little to say about 'container' and I'm not sure how that plays into how this all works or not.

I also noticed that \[#attributes\]\[class\] is a field name. I tried adding that as the :input\[name=\] value, but that didn't work either. Additionally, I tried to inspect element of the html form and use field\_rf\_snaped\_associated\[und\] that was part of the HTML. But, no go either.

And, the one and final confusing point are some tutorials show `input[name...]` and other show `:input[name...].` But, whether I add or omit the colon, it makes no difference. Ultimately, here is the code I ended up with that I can't get to work.

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

// determine if we're on the correct form
if ($form_id == "snaped_resource_finder_node_form") {

    //dpm($form);
    //print_r($form["field_rf_which_state_territory"]);
    //print_r($form['field_rf_snaped_associated']);

    $form['field_rf_which_state_territory']['und']['0']['#states'] = array(
        'visible' => array(
            ':input[name="field_rf_snaped_associated[und]"]' => array('value' => 'Yes')
        ),
    );
}
}

```

So, how would I write that so field\_rf\_which\_state\_territory only shows up when 'Yes' is selected in the field\_rf\_snaped\_associated field?

EDIT: Screenshot showing dpm output of that field

# Answer
I think you need:

```
$form['field_rf_which_state_territory']['und']['0']['value']['#states'] = array(
        'visible' => array(
            ':input[name="field_rf_snaped_associated[und]"]' => array('value' => 'Yes')
        ),

```

When looking though the $form array you need to make sure that you are adding the #states array at the same level that the #type element appears.
> 2 votes

---
Tags: javascript
---


# Question
Title: Advice on CSV import with taxonomy for data sanitaztion
i have a situation where users will be uploading csv files of the same format/columns but the data is not consistent...for example in the "state" field, one office might use "NC" and another might use "North Carolina". another might have "N. Carolina". misspellings are common too in some fields.

**how do i let them upload this data but sanitize it at the same time so that i know that "NC" == "North Carolina" == "N. Carolina"...etc?**

my thought is to use a vocabulary for each column and force the user to map any data that doesn't match up before the csv is processed and nodes are created.

so i'm thinking the process would be as follows:

1. user uploads csv
2. user gets a form/table showing the data they uploaded along with a vocab drop down for each cell that needs to match up to a term. (each cell in the state column would have a drop down)
3. user manually maps any data that did not match up to a term.
4. user hits "process csv" and nodes are created.

so if i uploaded a csv that had "Nrth Car." in the state column...i would have to select "North Carolina" from the drop down before the csv can be processed.

\*would also be cool if i could store these variations as synonyms so that next time they upload a csv they won't have to map the same variations again. ("Nrth Car." would automatically be mapped to "North Carolina" the second time around.)

thoughts?

# Answer
Store the list of states as a taxonomy and add a text field to the taxonomy called aliases. This would be an text field with unlimited values.

Now when checking if a term exists you can use:

```
function taxonomy_load_term_check_aliases($name, $vid) {

    // load term by name (not using taxonomy_get_term_by_name() as I want to pass in vid, not machine name)
    $tid = db_query('SELECT tid FROM taxonomy_term_data WHERE vid = :vid AND `name` = :name', array(':name'=>$name, ':vid'=>$vid))->fetchField();

    // no match - see if an alias exists
    if(!$tid) {
        $bundle = db_query('SELECT machine_name FROM taxonomy_vocabulary WHERE vid=:vid', array(':vid'=>$vid))->fetchField();
        $tid = db_query('SELECT entity_id FROM field_data_field_aliases WHERE field_aliases_value = :name AND bundle=:bundle',
            array(':name' => $name, ':bundle'=>$bundle))->fetchField();
    }

    $term = taxonomy_term_load($tid);

    return $term;
}

```

If you can't find a match then add an additional alias. As you list of aliases builds up it will become more and more automated.
> 0 votes

---
Tags: taxonomy-terms, importing-exporting
---


# Question
Title: Display all nodes posted on a certain month and day between 1990 and 2014
I want to display all nodes created on lets say, March 30 (between 1990 to 2014). Views contextual filters seems to display nodes posted on March 30 this year, how do i make the contextual filters include content posted on March 30 between lets say 1990 till 2014?

# Answer
> 1 votes
The custom module method is:

```
$nodes = node_load_multiple(db_query("SELECT nid
    FROM node
    WHERE MONTH(FROM_UNIXTIME(created)) = 3 AND DAY(FROM_UNIXTIME(created)) = 30 AND
    YEAR(FROM_UNIXTIME(created)) BETWEEN 1990 AND 2014")->fetchCol());

```

As far as I'm aware this isn't possible using the views UI so you would have to use hook\_views\_query\_alter to get this working using views.

---
Tags: 7, views, datetime
---


# Question
Title: How to dynamic select options each webforms seperately?
Currently I have a table of records webform (The node identifier of a webform) and a list of users, Associated with the webform table nid The group has kept a list of users webform's (The node identifier of a webform).

The purpose is to be in accordance with a different view webform to fill a single page, you can automatically bring out the webfrom belong to fill a single page to view a list of users group, the following screen embedded in it, and you want to automate the dynamic select options each webforms seperately, That each webform node page has a list of dynamic select options users group.

If the user fills again webform view to fill a single page, select a person of a certain list of users, and finally to be able to produce the data stored. To record the value webfrom submit sid and webform nid and selected personnel.

How do I make it?

# Answer
> 0 votes
I don't entirely understand your question, but I believe that you want to customize a webform based on the user currently logged in.

To do this you can use hook\_form\_alter.

All webform have an ID that starts webform\_client\_form\_ so you check check for this, and then make any modification as necessary.

E.g:

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

    //drupal_set_message("Form ID is : " . $form_id);

    if(substr($form_id, 0, 20)=='webform_client_form_') {

        global $user;

        // make changes to form here

    }
}

```

---
Tags: 7
---


# Question
Title: How can I encrypt the username and email address in the database, to protect against emails being stolen from a compromised database (D7)
Is there a way to encrypt the following user fields in the database so that they cannot be retrieved from a compromised database?

* Username
* Email address

A solution to encrypt the whole database would also be great.

# Answer
> 8 votes
If you want encrypt it, it means you need to decrypt it. So it means that the algorithm that encrypt and decrypt are available somewhere in your application or drupal files.

I guess if the user that has access to your database he has also access to your files, or at least I guess he can have access easily.

And in that case, encrypted datas are useless.

The most important its to hash the password with algorithms like SHA1 and use a salt or private key, thing that Drupal 7 is doing.

This is just my point of view, but if you want do it what you can use this module http://drupal.org/project/aes and with some user hooks, such as hook\_user\_presave() and hook\_user\_load().

The trick in this case it's that your module should be the last one before saving save the data and be the first one that decrypt data.

# Answer
> 1 votes
Database encryption will help you to encrypt the email: drupal.org/project/dbee.

Looking into this same module you could try to encrypt also the user name.

# Answer
> 0 votes
The easiest (but not cheapest) way to encrypt the whole DB would be to use an Oracle DB (with this module) with Transparent Database Encryption.

---
Tags: users
---


title: Encrypt username

text:
# Question
Title: Encrypt username
How do I go about encrypting "username" so that it is not saved in plain text format in database. I was looking for a module that does this, but couldn't find one.

Would adding logic (`hook_user_presave()` and `hook_user_load()`) as described in How can you encrypt the username and email address in the database, to protect against emails being stolen from a compromised database (D7) be sufficient? The accepted answer says:

> This is just my point of view, but if you want do it what you can use this module http://drupal.org/project/aes and with some user hooks, such as `hook_user_presave()` and `hook_user_load()`.

# Answer
I think it may be easier to store an arbitrary string or number (maybe the UID) as the username, and then store the actual (encrypted) username in a custom field.

This would mean writing a custom login script that uses your custom table, however it means you won't have to start changing stuff in the users module.
> 0 votes

---
Tags: 7
---


# Question
Title: bulk node creation based on number of files uploaded
Is there a module that enables the ability to automatically create nodes based on the number of files to be uploaded

# Answer
> 1 votes
Nodes? Nope, except for possibly rules or some other generic tools. On the other hand, you can try File entity:

> File entity provides interfaces for managing files. It also extends the core file entity, allowing files to be fieldable, grouped into types, viewed (using display modes) and formatted using field formatters. File entity integrates with a number of modules, exposing files to Views, Entity API, Token and more.

It claims to integrate with Plupload, so it should be possible to use the two for bulk creation of file entities. Just not nodes, but node is only a kind of entity, and with module that adds fields to it, what's the difference, really?

---
Tags: 7, nodes
---


# Question
Title: Search order by publish date or custom field
I wan't to order my search result first by publish date (or my custom date field), and then by relevance. Recently posted on Content ranking are not working. How to do this?

# Answer
I assume you are using the core Search module. For this kind of functionality I prefer using the excellent Search API module. There are other modules as well such as Solr but with increased complexity.

The core search module indexes only node title and body. Using the module not only allows you to index other fields but also to present the results in any fashion by creating a custom view with the Views module.

In order to use Search API, you need a backend such as the Search API DB module. This needs to be installed and activated along with Search API as well.

In order to create a custom page of results:

* Create a search server in Search API configuration
* Create an index with all relevant fields THAT you are going to use in the view (next) as well
* Create a new view of type index
* Add an exposed filter 'Fulltext Search' if you wish
* Add any fields you wish to present, usually the rendered entity field (teaser)
* Sort by any field you prefer to.
> 3 votes

# Answer
Did you try the solution from this answer?

```
    function mymodule_preprocess_search_results(&$variables) {
        $variables['search_results'] = '';
        $output_results = '';
        $output = '';

        // loop through results, group by department
        $departments = array();
        foreach ($variables['results'] as $result) {
                $departments[$result['node']->field_department[$result['node']->language][0]['value']][] = $result;
        }
        ksort($departments);

        foreach ($departments as $department => $departmentResults) {
            $value = "";
            foreach ($departmentResults as $key => $result) {
                $value .= theme('search_result', array('result' => $result, 'module' => $variables['module']));
            }

            $output_results .=  '<div id="tabs"><h3>' . $department . '</h3>';
            $output_results .=  $value;
            $output_results .=  '</div>';
        }

        $output .= '</ul>';
        $output .= $output_results;
        $output .= '</div>';

        $variables['search_results'] = $output;
    }

```
> 2 votes

---
Tags: entities, search
---


title: HTML Special characters in preprocess

text:
# Question
Title: HTML Special characters in preprocess
I'm trying to add a bullet to a string in `_preprocess_node()` and am running into problems. I am using Drupal 7.

My code is as such:

```
if($node->type == 'contact_page'){
    $vars['content']['field_fax']['#title'] = t("F •");
    $vars['content']['field_phone']['#title'] = t("P •");
  }

```

I get the literal string instead of the bullet. I've tried a bunch of things, but nothing seems to work. Am I missing something?

# Answer
try:

```
t("F !bullet", array("!bullet" => "•"));
t("P !bullet", array("!bullet" => "•"));

```

Drupal escapes any characters passed through t() function so you need to use variables like this:

* @variable: Escaped to HTML using check\_plain(). Use this as the default choice for anything displayed on a page on the site.
* %variable: Escaped to HTML and formatted using drupal\_placeholder(), which makes it display as *emphasized* text.
* !variable: Inserted as is, with no sanitization or formatting. Only use this for text that has already been prepared for HTML display (for example, user-supplied text that has already been run through check\_plain() previously, or is expected to contain some limited HTML tags and has already been run through filter\_xss() previously).
> 3 votes

# Answer
Had the same issue and after hours of searching I finally found something that works. Try decode\_entities

```
if($node->type == 'contact_page'){
    $vars['content']['field_fax']['#title'] = decode_entities("F •");
    $vars['content']['field_phone']['#title'] = decode_entities("P •");
}

```
> 1 votes

---
Tags: 7, theming
---


# Question
Title: How To Embed a video in a body field like facebook does
Do you know please?

Instead of having to click on a button to embed a video.

Is there a module that hides the embed code in the body field

http://www.youtube.com/watch?v=-cUWFLBZU5I&list=PL15BE2E8313A4E809&feature=share

So when you add the youtube link

```
<iframe width="560" height="315" src="VIDEO LINK" frameborder="0" allowfullscreen></iframe>

```

It fill in the src link

Many Thanks for your help

# Answer
If I understand you correctly I think that you can use the Video Filter module.

Video Filter allows you to put something like this in the body:

```
[video:http://www.youtube.com/watch?v=PCLx4fRHmCk]

```

Here you can see a post about this module:

How to Embed Videos using Video Filter in Drupal 7
> 4 votes

---
Tags: files
---


# Question
Title: How do I hide text format options in node view with in place editing?
I am using drupal 7 version with in place editing module editablefields I was able to hide the text format options in edit mode with simplify module but in node view mode are still there.

Please, do you have any module or custom module with hooks that I could use or do? !

# Answer
> 2 votes
You can find multiple questions/answers to this problem in this site... One of the most recommeded approach is using `hook_form_alter` hook: example:

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

  // dpm($form);
  // dpm($form_id);

  if($form_id == 'MY_NODE_FORM_ID') {
    $form['#after_build'][] = 'custom_my_node_form_after_build';
  }
}

function custom_my_node_form_after_build($form) {
  // dpm($form);
  // Find the right field's format option with dpm() function

  $form['MY_FIELD']['und']['0']['format']['#access'] = FALSE;
  return $form;
}

```

# Answer
> 0 votes
You can disable text formats from this page admin/config/content/formats

# Answer
> 0 votes
As mentioned above you can do this task by various way....

1. See the screenshot of display setting and make it plain.
2. Use hook\_node\_view or template\_preprocess\_page or template\_preprocess\_node\_page and just unset the format key of an array $var.

---
Tags: input-formats
---


# Question
Title: How to assign "Edit" permission per Webform?
On Drupal 7, how can I assign the "Edit" permission per webform, beside using "Permissions per Webform"?

# Answer
It actually can be done by "Enable per content node access control settings", which is under "Structure \> Content types \> Edit Webform \> Access Control".
> 1 votes

---
Tags: webforms
---


title: behaviours.js syntax (Leaflet Map)

text:
# Question
Title: behaviours.js syntax (Leaflet Map)
An answer is given here to a problem concerning Leaflet Maps

My question: How would I adapt this code (yellow border here) to the syntax of my-theme/my-theme.behaviours.js ?

I think it would begin:

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

```

or maybe

```
Drupal.behaviors.some_name_here = {
attach: function() {

```

# Answer
This should do the trick:

```
(function($) {
    Drupal.behaviors.leafletMap = {
        attach: function(context, settings) {

            $('body').once(function(){
                $(this).on('shown','#link3', function() {
                    L.Util.requestAnimFrame(map.invalidateSize,map,!1,map._container);
                });

            });

        }
    };

})(jQuery);

```

I've used .once() as you only want to bind this behavior once and the attach function will run on page load and every subsequent ajax request.

I found this blog post very useful on Drupal behaviors.
> 1 votes

---
Tags: javascript
---


# Question
Title: What's wrong with my plupload implementation?
For reasons that are out of scope here I should not send packets over 32 MB, so my php.ini looks like this:

```
; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize = 500M

; Maximum number of files that can be uploaded via a single request
max_file_uploads = 20

; Maximum size of POST data that PHP will accept.
; Its value may be 0 to disable the limit. It is ignored if POST data reading
; is disabled through enable_post_data_reading.
; http://php.net/post-max-size
post_max_size = 32M

```

I know plupload can do this, so I "only" needed to integrate it with Drupal. For this I installed Plupload integration module. Thanks to Clive I found this bug report:

> Right now you need to spesify a max file size larger than the max post size as plupload is stil honoring the setting.

I'm not particularly happy with `upload_max_filesize = 500M` but I guess for now I can live and work with it.

I tried custom code first:

```
  'DownloadFile' => array(
    //'#type' => 'managed_file',
    '#type' => 'plupload',
    '#title' => t("Download"),
    '#title_display' => 'invisible',

    '#upload_validators' => array(
      'file_validate_extensions' => array(),
      'file_validate_size' => array(variable_get('my_max_file_size', 300 * 1024 * 1024)),
    ),
    '#upload_location' => 'public://mymodule/download',
    '#default_value' => $item->fid,
    '#required' => TRUE,
    '#plupload_settings' => array(
      'runtimes' => 'html5',
      'chunk_size' => '10mb',
    ),
  ),

```

It was showing 300MB under the Form API field all right. Sadly, everything over 20MB gave me:

> Error: File too large: Some\_182MB\_file.zip

So I thought I'm doing something wrong and decided to try ready-made solution. I went for FileField Sources Plupload \- I see 32 MB on the node add form, but **182 MB file uploaded all right.**

So what's wrong with my implementation? I practically copied example from official documentation so I would expect it to work.

# Answer
When using Plupload integration module in custom code, you need to set up size twice. Preferably to the same value. First place you do it is the usual:

```
'#upload_validators' => array(
  'file_validate_size' => array(variable_get('my_max_file_size', 300 * 1024 * 1024)),
),

```

This handles display and post-upload verification.

Second place is `#plupload_settings`:

```
'#plupload_settings' => array(
  'runtimes' => 'html5',
  'chunk_size' => '10mb',
  'max_file_size' => variable_get('my_max_file_size', 300 * 1024 * 1024) . 'b',
),

```

This is what actually goes to the plupload JavaScript.
> 2 votes

---
Tags: files
---


# Question
Title: Validate a group of fields so that form can only be submitted if 0 or 2+ fields have been completed
In Drupal 7 I need to validate several cck fields so that the node can only be saved if 0 or two or more fields have been completed. So if only one of the fields is completed validation would fail with an error message like 'Please submit two or more years worth of data, or no data at all'.

I know that I can useField Group and Field Group Multiple To set up groups of fields. I can see that Field Validation provides basic validation options, including checking that a minimum of 1 of several fields have been completed. But as far as I can see it does not have the capacity to achieve what I need it to do.

Could you please suggest how to go about forcing a user to either complete 2+ fields or none at all?

Thanks

# Answer
I solved this the right way by installing field validation with the field validation extras submodule enabled and creating a validator to extend it.

Inside field\_validation/field\_validation\_extras/plugins/validator I created field\_validation\_zeroortwoplusofseveral\_validator.inc with the following code inside it:

```
<?php
/**
 * @file
 * Field validation some of several validator.
 *
 */
$plugin = array(
  'label' => t('Require ZERO or two or more of several fields'),
  'description' => t('Forces the user complete zero or two or more several fields.'),
  'handler' => array(
    'class' => 'field_validation_zeroortwoplusofseveral_validator',
  ),
);

class field_validation_zeroortwoplusofseveral_validator extends field_validation_validator {

  /**
   * Validate field.
   */
  public function validate() {
    $flag = FALSE;
$group_name = $this->rule->settings['data'];

$required_fields = $this->rule->settings['required_fields'];
if (!is_numeric($required_fields) || $required_fields < 0) {
  return TRUE;
}

$field_values = $this->get_field_column_value($this->items, $this->rule->col);
$field_values = count(array_flip($field_values));

if ($field_values >= $required_fields) {
  $flag = TRUE;
}
if ($field_values == 0) {
  $flag = TRUE;
}

if (!$flag) {
  ctools_include('export');
  $other_group_rules = ctools_export_load_object('field_validation_rule', 'conditions', array('entity_type' => $this->rule->entity_type, 'bundle' => $this->rule->bundle, 'validator' => $this->rule->validator));
  foreach ($other_group_rules as $other_group_rule) {
    // Skip when do not have the same group name, rule is disabled, equal to current rule.
    if ($other_group_rule->settings['data'] != $group_name || !empty($other_group_rule->disabled) || $other_group_rule->name == $this->rule->name ) {
      continue;
    }
    $other_items = isset($this->entity->{$other_group_rule->field_name}[$this->langcode]) ? $this->entity->{$other_group_rule->field_name}[$this->langcode] : array();
    $other_field_values = $this->get_field_column_value($other_items, $other_group_rule->col);
    $field_values += count(array_flip($other_field_values));
    if ($field_values >= $required_fields) {
      $flag = TRUE;
      break;
    }
  }
}

    if (!$flag) {
      $this->set_error();
    }
    $break = TRUE;
    return $break;
  }

  /**
   * Provide settings option
   */
  function settings_form(&$form, &$form_state) {
    $default_settings = $this->get_default_settings($form, $form_state);
    //print debug($default_settings);
    $form['settings']['data'] = array(
      '#title' => t('Group name'),
      '#description' => t("Specify the group name for those fields, it should be the same across those fields. Validation rules with the same group name work together."),
      '#type' => 'textfield',
      '#default_value' => isset($default_settings['data']) ? $default_settings['data'] : '',
    );
    $form['settings']['required_fields'] = array(
      '#title' => t('Required fields number'),
      '#description' => t("Specify the minimum number of fields that must have a value, it should be the same across fields of the same group. Validation rules with the same group name work together."),
      '#type' => 'textfield',
      '#default_value' => isset($default_settings['required_fields']) ? $default_settings['required_fields'] : '',
    );
    parent::settings_form($form, $form_state);
  }

  /**
   * helper function to get field values
   */
  function get_field_column_value($items, $column ='value') {
    $field_values = array();
    foreach ($items as $delta => $item) {
      if (isset($item[$column]) && $item[$column] !='') {
        $field_values[] = $item[$column];
      }
    }
    return $field_values;
  }

}

```
> 0 votes

# Answer
First I assume this must be for Drupal 6 since you are describing CCK fields? I would suggest creating a small custom module, and implementing hook\_validate.

You can then check how many fields have been entered by your user to see if it passes your requirements described above.

If the validation fails you can then display the error to the logged in user with form\_set\_error

**EDIT**:

Since you're using Drupal 7, you can use hook\_node\_validate within a custom module.
> 0 votes

---
Tags: 7, forms
---


title: Find out what entity type an entity is?

text:
# Question
Title: Find out what entity type an entity is?
How can I find out what entity type an entity is, when all I know is the entity ID?

Or is there a way I could list all the entity types on my website (or even via database)?

# Answer
> 0 votes
**You can't.**

Different entities use the same ID.

E.g. you can have a user with ID 42, and a node with ID 42, **and** a taxonomy term with ID 42. So just knowing the ID is 42 is not enough to know what type of entity the ID belongs to.

This is why entity\_load takes both the entity type and the ID as arguments.

To list all entities use entity\_get\_info().

---
Tags: 7, entities
---


title: how to customize user profile page

text:
# Question
Title: how to customize user profile page
I want to customize user profile page as per my own way. I have created one file named as page--user.tpl.php, but after making changes in this file during user logged in, the changes reflects on sign up(register page) without logged in. But i only wants to change the look and feel of individual user's page.

Please help me.

Thanks

# Answer
> 1 votes
You've simply used the wrong template. page--user.tpl.php affects "user pages" like, as you've discovered, the user login.

The template you want to create and modify is **user-profile.tpl.php** https://api.drupal.org/api/drupal/modules%21user%21user-profile.tpl.php/7

---
Tags: theming, users
---


title: Change Drupal's default styling

text:
# Question
Title: Change Drupal's default styling
I'm starting to build a new Drupal site with the core theme "Stark" (Almost no styling) but I can't seem to find where the default body background(grey) is coming from so I can change it. (I'm good with CSS).

# Answer
> 1 votes
stark.css doesn't contain any background colour, so you can set one yourself. you don't need to remove anything first.

---
Tags: theming
---


title: xautoload classes in subfolders

text:
# Question
Title: xautoload classes in subfolders
I have issues autoloading classes found in subfolders of my module with xautoload.

my module is called myentity

Here is my hook\_entity\_info

```
function myentity_entity_info() {
    $return['myentity'] = array(
        'label' => t('My entity'),
// The entity class and controller class extend the classes provided by the
// Entity API
        'entity class' => 'Drupal/myentity/class/MyEntity',
        'controller class' => 'Drupal/myentity/controller/MyEntityController',
        'base table' => 'myentity',
        'fieldable' => TRUE,
        'entity keys' => array(
            'id' => 'me_id',
            ),
        'bundles' => array(
        'myentity' => array(
            'label' => 'myentity',
        // Information below is used by the Field UI - they "attach" themselves here and lets us
        // do the standard field management that all the core entities enjoy.
            'admin' => array(
                'path' => 'admin/structure/myentity/manage',
                'access arguments' => array('administer myentity'),
                ),
            ),
        ),
    'label callback' => 'entity_class_label',
    'uri callback' => 'entity_class_uri',
    'module' => 'myentity',
    'view modes' => array(
        'full' => array(
            'label' => t('Default'),
            'custom settings' => FALSE,
        ),
        'teaser' => array(
            'label' => t('Teaser'),
            'custom settings' => FALSE,
        ),
    ),
    'metatags' => TRUE,
);

return $return;
}

```

My class and controller are found in

```
sites\all\modules\myentity\lib\Drupal\class\MyEntity.php

```

with the following content

```
<?php

namespace Drupal\myentity\class\MyEntity;

/**
 * The class used for model entities
 */
class MyEntity extends Entity {

    public function __construct($values = array()) {
        parent::__construct($values, 'myentity');
    }

    protected function defaultLabel() {
        return $this->name;
    }

    protected function defaultUri() {
        return array('path' => 'myentity/' . $this->identifier());
    }

}

```

and

```
sites\all\modules\myentity\lib\Drupal\controller\MyEntityController.php

```

# Answer
> 2 votes
Bugs bugs bugs.

```
    'entity class' => 'Drupal/myentity/class/MyEntity',
    'controller class' => 'Drupal/myentity/controller/MyEntityController',

```

This should be

```
    'entity class' => 'Drupal\myentity\class\MyEntity',
    'controller class' => 'Drupal\myentity\controller\MyEntityController',

```

And:

```
namespace Drupal\myentity\class\MyEntity;

```

This should be

```
namespace Drupal\myentity\class;

```

(and btw, is "class" really a valid namespace part? Won't PHP complain?)

And:

```
sites\all\modules\myentity\lib\Drupal\controller\MyEntityController.php

```

This should be:

```
sites\all\modules\myentity\lib\Drupal\myentity\controller\MyEntityController.php

```

EDIT: One more:

```
class MyEntity extends Entity {

```

should be

```
class MyEntity extends \Entity {

```

Because class Entity is in root namespace.

---
Tags: 7
---


# Question
Title: Modifying destination directory for imagefield file migrating D6->D7
I'm working on a D6-\>D7 site migration, and I'm having problems trying to figure out how to do a couple things with the migration of some of the files. An added wrinkle in this migration is that I'm moving the storage of the files from the local server to Amazon S3 using the S3FS module (which is really slick, BTW). The source D6 blog content type has two image fields - field\_mainphoto and field\_thumbailphoto. I would like to combine these fields into one multi-value image field in the blog content type in the D7 site titled field\_images. The file storage locations for the two fields are `main_photos/[site-date-yyyy]/[site-date-month]` and `thumbnail_photos/[site-date-yyyy]/[site-date-month]`. The new field\_images will have a storage location of images/\[site-date-yyyy\]/\[site-date-month\]. Therefore, what I need to do is twofold:

1. Change the destination directory from main\_photos/ and thumbnail\_photos/ to images/.
2. Combine the data from these two image fields into one image field.

In the interest of asking one question per post, this one is limited to the first one. I've been looking through all of the documentation, and the shortest and easiest way would be to implement an override of the prepare() method, and modify $entity-\>destination\_dir. The only thing I don't like is that it's modifying a string. Do I need to go as far as overriding MigrateDestinationFile or MigrateFileUri, or is there a simpler way to do this?

Thanks.

# Answer
To avoid future situations like this, here is what I came up with:

```
  public function prepare($entity, stdClass $row) {
    // Change the destination directory for the field_mainphoto and
    // field_thumbmailphoto files to be /images.
    foreach (array('main_photos', 'thumbnail_photos', 'video_thumbnails') as $dir) {
      if (substr($entity->destination_file, 1, strlen($dir)) == $dir) {
        $entity->destination_file = str_replace($dir,'images', $entity->destination_file);
      }
    }
  }

```
> 1 votes

---
Tags: migrations
---


# Question
Title: How should I let some users to download from Private folder
I stored the names of some users in one table and they should be able to download certain files from private folder(not other users). As i see i have to use hook\_file\_download

In the page of that hook it is said:

> If the user does not have permission to access the file, return -1. If the user has permission, return an array with the appropriate headers.

I don't understand which array should be returned exactly! my file in private folder is mp4 file and user has to see save page.
some users file\_create\_url() but i don't know how to use it inside hook\_file\_download. can u give me one example code?

## thanks in advanced for your help

edit: I found this code here:

```
  if ($can_access_file) {
    $headers = file_get_content_headers($file);
    return $headers;
  }

```

I don't know exactly how to provide with $file! here is file\_get\_content\_headers help

# Answer
> 0 votes
my problem solved by the help of friends here
this is the my final code:

```
function my_module_file_download($uri) {

  // Get the file record based on the URI. If not in the database just return.
  $files = file_load_multiple(array(), array('uri' => $uri));
  if (count($files)) {
    foreach ($files as $item) {
      // Since some database servers sometimes use a case-insensitive comparison
      // by default, double check that the filename is an exact match.
      if ($item->uri === $uri) {
        $file = $item;
        break;
      }
    }
  }

  if (!isset($file)) {
    return;
  }

  // Put your permission check code here.

  // When done perform the following code
  if ($can_access_file) {
    $headers = file_get_content_headers($file);
    return $headers;
  }
  return -1;
}

```

my mistake was copying files to private folder directly! that was why the above code did not work! I created a custom content with to fields: file and taxonomy! it uploads the files to private folder and at the same time adds file name to "file\_managed" table! Thank you all for helping me understand my mistakes :) i appreciate that

# Answer
> 1 votes
What field type serve the link for the download ? Maybe the module behind this type already implement this hook ?
For example, File module or Image module already implement this hook\_file\_download.

In case of File module, it allow you to alter the permission to access to the file.

```
// Allow other modules to alter the returned grants/denies.
    drupal_alter('file_download_access', $grants, $field_item, $entity_type, $entity);

```

You just have to implement the hook\_file\_download\_access\_alter. By the way, there is this other hook (hook\_file\_download\_acces) you can may be try to hook.

Finally, if no one of this hooks can help you, so may be you have to use this hook\_file\_download. But I don't really know what is expecting as headers, but you can look at the hook in the Image module.

There, it get headers from others modules (may be you can just use this trick) :

```
// Check the permissions of the original to grant access to this image.
  $headers = module_invoke_all('file_download', $original_uri);

```

And just after that, it make its own headers :

```
return array(

      // Send headers describing the image's size, and MIME-type...
      'Content-Type' => $info['mime_type'],
      'Content-Length' => $info['file_size'],
      // By not explicitly setting them here, this uses normal Drupal // Expires, Cache-Control and ETag headers to prevent proxy or // browser caching of private images.
    );

```

Hoping that help :)

# Answer
> 1 votes
All is in the code you have found :) Just before the :

```
if ($can_access_file) { }

```

You have this code :

```
$files = file_load_multiple(array(), array('uri' => $uri));
if (count($files)) {
  foreach ($files as $item) {
    // Since some database servers sometimes use a case-insensitive comparison
    // by default, double check that the filename is an exact match.

    if ($item->uri === $uri) {
      $file = $item;
      break;
    }
  }
}

if (!isset($file)) {
  return;
}

```

You see the $file ? $file is returned in the first line :

```
$files = file_load_multiple(array(), array('uri' => $uri));

```

In fact, the file\_load\_multiple can return you more than one file. But not really used like that (with just one URI). So, the $files contain just your $file.

So, if Drupal don't find your file, count($files) will return 0 and you don't go through the if(). But normally, count($files) will return 1, for the file matching with the URI :

```
if (count($files)) {
  foreach ($files as $item) {
    // Since some database servers sometimes use a case-insensitive comparison
    // by default, double check that the filename is an exact match.

    if ($item->uri === $uri) {
      $file = $item;
      break;
    }
  }
}

```

The first time when Drupal will enter in the foreach, the $item-\>uri will be the same as $uri. So it's your file, and you stock all informations in $file :

```
$file = $item;

```

And it's like that you have provide your $file. By the way, the code above come from the implementation of hook\_file\_download in the File module.

# Answer
> 0 votes
You seems to have most of it in place already. To get the `$file` object, you call `file_load`:

```
$file = file_load($fid);

```

The argument (`$fid`) is the file id that is stored in the table `{file_managed}`.

Note that the file will only appear in the table `{file_managed}` if the file is uploaded to the site with the use of Drupal. If you've put the file in the private folder by some other means (e.g. you've used *ftp* or just copied the file into that folder), then the file is not managed by Drupal and can not be accessed through the Drupal API.

---
Tags: 7, files
---


# Question
Title: I want download window appear instead of showing my mp4 file
I upload some mp4 files to my private folder and some users can access those files. this is my code for letting them download my mp4 files:

```
function my_module_file_download($uri) {

  // Get the file record based on the URI. If not in the database just return.
  $files = file_load_multiple(array(), array('uri' => $uri));
  if (count($files)) {
    foreach ($files as $item) {
      // Since some database servers sometimes use a case-insensitive comparison
      // by default, double check that the filename is an exact match.
      if ($item->uri === $uri) {
        $file = $item;
        break;
      }
    }
  }

  if (!isset($file)) {
    return;
  }

  // Put your permission check code here.

  // When done perform the following code
  if ($can_access_file) {
    $headers = file_get_content_headers($file);
    return $headers;
  }
  return -1;
}

```

**my problem:** once my user clicks on the link of the file google chrome starts showing the file! although they can right click on the link of the file and download that, but i want the download window appear from beginning! maybe one solution is to zip the file but what about mp4 without zipping?

# Answer
> 0 votes
You can do this using htaccess, Open your .htaccess file and add the following...

```
<FilesMatch "\.(mp4)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</FilesMatch>

```

This should force the browser to do a left click download, rather than play the content. You can do it for multiple files types as well. After the mp4 just add |mp3, so it would look like `<FilesMatch “.(?i:(mp4|mp3|pdf))$”>`

---
Tags: 7, files
---


# Question
Title: Is it to possible add placeholder text for link fields?
Been trying to add placeholder text for my link fields.

Using hook\_form\_alter to add the attributes. It works fine with text fields

```
$form['field_first_name']['und'][0]['value']['#attributes']['placeholder'] = t( 'Your First Name' );

```

But not able to get it work with link fields

```
$form ['field_twitter_link']['und'][0]['#attributes']['value']['placeholder'] = t( 'Your Twitter profile link' );

```

# Answer
> 3 votes
You could do something like this in

```
function mytheme_form_alter(&$form, &$form_state, $form_id){
  $form['#after_build'][] = 'mytheme_after_build';
}

function mytheme_after_build(&$form, &$form_state){
  $form['field_twitter_link']['und'][0]['url']['#attributes']['placeholder']=t('my new');
  return $form;
}

```

Taken from here https://drupal.org/node/1002560

---
Tags: 7
---


title: Content type export broken in PHP 5.4

text:
# Question
Title: Content type export broken in PHP 5.4
I am trying to upgrade my server from PHP 5.3 to 5.4. When accessing the Content Type export form in CCK with D6 the form does not display.

This issue is on first display of the form, not just on submit (as I have seen other questions online).

Here is the bad form.

Here is the correct form (on PHP 5.3).

I don't have any errors being thrown to the error\_log or watchdog, and I am using Pressflow 6.26.

# Answer
> 1 votes
Line 623 of modules/cck/modules/content\_copy/content\_copy.module needs to be changed from:

```
function template_preprocess_content_copy_export_form($vars) {

```

to

```
function template_preprocess_content_copy_export_form(&$vars) {

```

https://drupal.org/node/2230081

---
Tags: nodes, entities, importing-exporting, 6
---


title: Two URL aliases for one node in menu

text:
# Question
Title: Two URL aliases for one node in menu
In my case I do not care about crawler penalty.

I have multilingual site with menu. I use Path module for URL aliases. The URL aliases are language-specific.

I need to create two menu items with different URL aliases but both links have to render the same content node. I need to do it only for one particular node with known node id, so any hardcoded/hack solution is welcomed.

**UPDATE:**
I'm just thinking about such hack solution: I can create some new fake node, set the proper url alias and add menu item for this node. When Drupal is about rendering of this fake node then I'd interrupt the rendering in the code and just render the desired known node.

Is it possible? If so, how can I achieve this?

# Answer
It sounds like you're looking for NodeSymlinks:

> NodeSymlinks allows you to display the same content to users at multiple locations in the Drupal menu system with unique URL path, unique navigation breadcrumb and without the SEO penalty that usually occurs with multiple copies of the same content.
>
> This is useful when you want to have the same page reachable though multiple menu items, each with its own URL, menu trail and breadcrumb path.
> 2 votes

---
Tags: routes, i18n-l10n, uri
---


title: Field edit limit for users

text:
# Question
Title: Field edit limit for users
I need to set a limit on the number of times a field can be edited.

use case: the name of the user (field\_name\_user) can only be edited once or twice.

I tried node edit limit and field permissions but neither won't fit the task. Is ther any other module out there or a way to achieve this?

# Answer
> 2 votes
I think you can achieve this using an entity field, in this case the user entity, and some PHP Code.

Add a Field that counts the numebr of editions. Then, alter the entity edit form (in this case again, the user edit form) and:

1. Hide the field (with #access FALSE, for example).
2. Add your custom submit handler to the entity edit form.
3. If the field value is minor than the max edit count allow to edit then increment the field value in a custom submit handler.
4. If the field value is equal to the max edit count then deny the edition (deny the edit form, hide the field or whatever you want and fit your needs).

Also don't forget to hide the field when the entity is shown (check the entity display settings page).

---
Tags: 7
---


# Question
Title: How can I set the energy settings for the Radioactivity module?
I saw in this screencast (from 4m 20s) that a lot of cool features were available to set the energy settings in Drupal 6. One could for example give specific scores when nodes were viewed or evaluated with Fivestar.

Is this possible in Drupal 7 too? I can't find any documentation about it...

# Answer
All those cool features are still there, you just need to set up a "Decay profile". You can do this at /admin/structure/radioactivity.

Once you've got the profile setup (with the "Advanced" method by the sounds of what you're looking for), you can edit the Radioactivity field on the entity, and choose that profile. When the entity is viewed, the tracking will kick in automatically.

To respond to events such as fivestar ratings, you need to use the Rules module as everything's been decoupled for flexbility.
> 5 votes

---
Tags: 7
---


# Question
Title: Git flow feature in branch on stage server
I am testing out a git feature and pushed the branch to the staging server to show the client. Because it is a drupal feature, I think I need to revert the feature on the branch on the stage server.

My question is if I am in feature/branch and I revert the drupal feature to allow the updates to show up. When I checkout develop will that whipe away the revert I did on the feature/branch?

Thanks

# Answer
> 2 votes
If you switch from the feature branch back to develop, it won't wipe them out because the changes are stored in the database, and you should see an **overridden** status on the feature. Once you switch back to develop, you can perform a feature-revert again to change the settings back.

Either way, I would backup the database, either using Backup & Migrate, or directly on the server, just in case anything goes wrong.

---
Tags: features
---


# Question
Title: How to prevent users from changing Workbench Access Section
I have different authors set up with rights to edit different pages of my site (using Workbench Access), and an unfortunate side effect of this is that, when editing a page, they can also assign it to a different Workbench Access Section.

This would, for instance, allow them to accidentally lock themselves out of a page, or allow someone else to gain editing rights to it. This is definitely not a good thing.

I don't see anything in the permissions that would allow me to fix this, but here are my settings in case some are somehow relevant, despite appearing otherwise.

How can I fix this? How can I prevent access to this field?

# Answer
Users can only assign a node to a workbench access section if their user or role has permissions to do so? But perhaps it gets tricky with assigning permissions to the different transitions too.

Anyway, you can lock the workbench access field on node edits, so they can't lock themselves out if you like:

```
<?php
function MODULENAME_form_node_form_alter(&$form, &$form_state, $form_id) {
  // Make sure this node type actually has workflow_access stuff setup.
  if (isset($form_state['node']->type) && variable_get('workbench_access_node_type_' . $form_state['node']->type, 1) == 0) {
    return;
  }
  // Once the page has been created, don't allow changing the workbench area again.
  if (preg_match("/^node\/([0-9]+)\/edit/", current_path())) {
    $form['workbench_access']['#disabled'] = TRUE;
  }
}

```
> 1 votes

---
Tags: 7, workbench
---


# Question
Title: Display two Views blocks with equal height
I have created two Views Blocks "NEWS" and "BLOG", which resides side by side on my front page.

Both the views have 20 contents **(but can be any number)** in it and a pager. How do I display contents in views block, so that the both views end up with equal height regardless of number of contents displayed.

# Answer
Try using the equal heights module

> This module implements a jQuery Equal Heights plugin that can equalize the height of the elements of the specified class.
>
> To use it, give the elements the same class, then go to the administration interface and add this class (separate multiple classes by a space). By default, it sets the height to the height of the tallest element but you can also specify minimum and maximum height.

To use the just give both the blocks the same class and add the admin name in the admin interface of the module and then js will do the rest.
> 2 votes

# Answer
Installing module to achieve small task is bit too much in my opinion. I would rather apply equal heights JS library https://github.com/mattbanks/jQuery.equalHeights and following script to the main JS file.

```
$('.yourelements').equalHeights();

```

This function will calculate the tallest container of the N-containers and apply in-line css height attribute to all the containers to match equal heights. So you don't have to set height as you can't predict the actual height.
> 1 votes

# Answer
Get the css ID of blocks using Firebug write css like

```
#block-search-form, #block-system-navigation {
    height: 200px;
}

```
> 0 votes

# Answer
If you don't want to use a Module or Plugin I completed this with Jquery. Your views need to have the same class and the below simply looks at each of them, decides which one is higher and sets both their height to the highest value.

```
  function equalHeight() {
   var height = 0;
   var $items = $('.item-blocks');
   $items.each(function() {
    if($(this).height() > height) {
      height = $(this).height();
    }
  });

  $items.css('height', height);
 }

```
> 0 votes

---
Tags: views, blocks
---


title: Alternate node/add page

text:
# Question
Title: Alternate node/add page
I would like to create an alternate node/add page, which can be accessed by a url path, so that I can have an alternate add node page for users while admins can see a different add node page.

This are my current selection rules:

This panel will be selected if Current path is "test", and NOT (Logged in user has role "anonymous user").

I get a 404 error when I access "test". I've tried adding the Node being edited is type "Test". selection rule but it doesn't work either.

# Answer
> 0 votes
Due to talking from comments, there answer that help:

You can't alternate node/add/{node\_type} via Test.
You can **create alias Test for node/add/{node\_type}** or you can write custom function, that call node/add/{node\_type} form via drupal\_get\_form with some node preparements function.
After this you can apply Panels and so on
First answer was incorrect:
Enable **Page manager** module (part of CTools), then goto admin/structure/pages and add 'Add custom page', set path to *test*, save it. Now you can use your Panels that fire for Test page.

# Answer
> 0 votes
You could be more specific about what you meant by add node page. Did you mean node/add page? If thats the case, then I would suggest you use Menu Item Visibility to hide the default add node link and make it visible to only your admin role(s), then create a block containing the add node-type links (eg node/add/article etc) and descriptions the way you want other users to see it, place this block inside your panel page (/test), and create a menu item that links to /test, making this only visible to non-admin users.

Drawback for this is that each time you add a new content type for non-admin users, you have to manually add a link for it to this block

**Edit:** Alternatively, since you want to achieve this using rules, you can install the Rules Bonus Pack module (You need Rules module for this), the sub-module you want to enable is the "Miscellaneous", then Create Event "Page variant is rendered" Condition "Logged in user has role (your role), Action "Page Redirect" here you add the page "test" without the quotes (dont add a leading slash as in /test). Then you can do whatever you want on that page. Hope this helps.

# Answer
> 0 votes
Finally solved it! Though with a very simple and dirty solution.

1. I created a variant for my node add/edit page with the following selection rules:

This panel will be selected if Node being edited is type "Test", and NOT (Logged in user has role "admin").
2. Then I made a URL alias for node/add/test for "test"

Thank you all for your time spent helping me. I thought of it while following your instructions.

---
Tags: panels
---


# Question
Title: Edit display of commerce kickstart shopping cart
How can I display the output of a view in a menu?

I made a views that displays the information I want correctly but I don't know how to display the as a block in a menu. I've tried Menu attach blocks and Menu Views but couldn't get it to work.

Is there another option?

# Answer
> 2 votes
Solved with the Menu Minipanels module. Here is a quote from its project page:

> A system for building "megamenu" -style dropdown menus using Mini Panels, which provides tremendous flexibility in what can be displayed.

The project page also points to an interesting Click-by-click beginner's tutorial

---
Tags: views, commerce, routes
---


# Question
Title: How to setup gmap maps on nodes (using location fields)
I use the gmap and the location to show maps in nodes by adding the **location field** to the node content type.

Let's say I have 2 content types: **Pubs** and **Restaurants** Each one of them have a location field which allows me to show a map for the nodes. So far so god.

My problem is that I see no way to setup the map (zoom, marker, ...) in a different way for each one of the content types.

Let's say I want to set the zoom for Pubs' maps to 12 and the zoom for restaurants' maps to 10.

The only way I see to setup the maps is in admin/config/services/gmap, but these setting affects maps in all nodes of all content types.

I need to customize maps for each content type.

# Answer
> 2 votes
Using OpenLayers instead of Gmap you can set up different maps for different fields. It's more complicated, but with more options.

# Answer
> 0 votes
You can try Geolocation module. It allows you to add a location field (you can then easily select a location using Google Maps in node editing screen) in any content type.

The module then allows you to display the location on a node in various styles (including Google Maps).

---
Tags: google-maps
---


# Question
Title: Error 'Cannot redeclare ctools_menu_add_tab()' after migrating website
After our hosting provider has migrated our website to a new server this fatal error occurs when accessing the site:

> **Fatal error**: Cannot redeclare ctools\_menu\_add\_tab() (previously declared in /www/htdocs/mysite/drupal/sites/all/modules/ctools/includes/menu.inc:42) in **/www/htdocs/mysite/drupal/sites/all/modules/ckeditor/ctools/includes/menu.inc** on line **49**

Now the mother of all questions: How can I fix this? :(

We're using Drupal 6 and – although I haven't checked it yet – all files and databases *should* have been copied correctly by our hosting provider.

# Answer
> 1 votes
You have ctools installed twice, in:

* sites/all/modules/ctools
* sites/all/modules/ckeditor/ctools

Obviously the second path must have been mistake. If you can acces your page, disable ctools and then remove second instance. If you can't, try to do it using drush. If that fails, too, consider re-migration, this time properly. If all else fails, you may try to simply remove second instance and call update.php to perform some cleanup.

---
Tags: 6, routes, migrations, wysiwyg, chaos-tool-suite
---


# Question
Title: How can I defined regions like default admin theme (Seven)?
For example, visit admin/structure/block/manage/search/form/configure config search block, in "Region settings", can see Seven (administration theme) "Dashboard(sidebar)" selected, but I find Seven Theme's file, there is no region defined as "Dashboard(sidebar)".

So how can I do the same thing as Seven Theme?

# Answer
That functionality doesn't come from a theme, it's provided by the core Dashboard module.

The short answer to your question is: copy what the Dashboard module does. To actually do it will require a fair bit of development.

The regions are defined in `dashboard_dashboard_regions()`, and are eventually added to the page by `dashboard_page_build()`. The whole process bypasses the usual workflow of defining regions in the theme file.

I'm guessing it's been done like this so that the Dashboard can be used by any admin theme, not just the Seven theme included with core.
> 1 votes

---
Tags: theming
---