# Question
Title: Problems translating strings for my module
As far I as know, the `t()` function is supposed to collect the strings and allow for their translation at `admin/config/regional/translate/translate`. This is not happening though for my module's string. Despite disabling the module + flushing the cache + enabling back, the string does not show up there.

*I'm aware of the filters and case-sensitivity of the search field.*

Any ideas as per what is going wrong?

# Answer
> 0 votes
The string has to be displayed at least once on the site (as far as i know). If this does not work, try to rename the string you want to replace with a translation and clear the caches again.

---
Tags: i18n-l10n
---


# Question
Title: trouble with a checkbox on the user registration pages
I created an extra checkbox field for the user registration form

This is the field setting page. (*Standaardwaarde* means "Default value.")

In the setting page, the field is unchecked, but it's checked in the registration page. I looked at some older questions regarding this subject, but it still a big questions mark for me.

How can I get the checkbox to be unchecked by default?

# Answer
> 0 votes
Found the answer. The problem was that I selected the wrong field type. I think because it is only one field you need to select a Boolean type. Now it's working!

---
Tags: 7, users
---


# Question
Title: How should I render the tpl of module at theme
I create a module and mymodule.module file like this:

```
function mymodule_menu(){
    $items['mymodule/list']=array(
        'type'=>MENU_CALLBACK,
        'page callback'=>'mymodule_list_view',
    );
    return $items;
}

function mymodule_list_view(){
    theme('list_view');
}

function mymodule_theme($existing, $type, $theme, $path){
    return array(
        'list_view'=>array(
            'template'=>'mymodule_list',
            'type'=>'theme_engins',
        ),
    );
}

```

then I create templates file: mymodule\_list.tpl.php

And I create a theme and create templates file: page--mymodule.tpl.php. Now when I access /mymodule/list, it will use page--mymodule.tpl.php to render the page.

My question is: how should I write page--mymodule.tpl.php to display the content in mymodule\_list.tpl.php?

# Answer
You don't need a customized page template file because you are using a template file for your theme. What you need to do is to fix your code, which should be as the following one.

```
function mymodule_menu() {
  $items['mymodule/list'] = array(
    'type' => MENU_CALLBACK,
    'page callback' => 'mymodule_list_view',
    'access arguments' => array('access content'),
  );

  return $items;
}

function mymodule_list_view() {
  return theme('list_view');
}

function mymodule_theme() {
  return array(
    'list_view' => array(
      'template' => 'list-view',
    ),
  );
}

```

Notice that:

* For the menu callback, you should define the access callback, and the access arguments, or the menu will not be visible to the users (except the user #1). By default, Drupal uses `user_access()` as access callback; in this case, you need to provide the permission string as access arguments.
* The template filename must be equal to the theme name; the only acceptable difference is the underscores replaced by hyphens.
* Your page callback needs to return its output, or print it. In the first case, the rendered page will contain all the output returned from Drupal, such as blocks; in the second case, the rendered page will just contain what your page callback prints.
> 1 votes

---
Tags: 7, theming
---


# Question
Title: string espected but array given in custom pop_date field #default_value
> **Possible Duplicate:**
> Date popup form field doesn’t show the default value correctly

I'm trying to set a default value for my custom date\_popup field. To be precise I'm trying tho set the field to the first day of the current month. But if I can populate the field without errors I can figure out the rest.

At first I was trying to input a string value:

`#default_value = '1/1/2012'`

This results in no errors but also the field will remain empty.

I've looked trough some issues including this one and noticed that I had to use a `date()` as value. But this also results in an empty field using the the following code:

```
'#default_value' => date('d/m/Y'),

```

Which I think should give todays date?

Finally I used the following code:

```
'#default_value' => array('day' => 1, 'month' => date('m'), 'year' => date('Y')),

```

which populates the field but gives me:

> Warning: strlen() expects parameter 1 to be string, array given in date\_default\_date() (line 114 of /home/quickstart/websites/nieuwesite/sites/all/modules/date/date\_api/date\_api\_elements.inc).

Of course I'm trying to build this field in hook\_form(). for reference here is my whole field:

```
$form['click_stats_date_start'] = array(
'#type' => 'date_popup',
'#title' => t('Start date'),
'#label_display' => '',
'#date_format' => 'd/m/Y',
'#date_year_range' => '-1:+0',
'#date_label_position' => 'hidden',
'#default_value' => array('day' => 1, 'month' => date('m'), 'year' => date('Y')),
'#size' => 20,
'#required' => TRUE,
);

```

So my question is how do I populate the date\_popup field on the first load without errors?

# Answer
You are getting the "expects parameter 1 to be string" error because the only value the date popup form element accepts as default value is a string with the format described in date\_popup\_element\_info().

> Set the #type to date\_popup and fill the element #default\_value with a date adjusted to the proper local timezone in datetime format (YYYY-MM-DD HH:MM:SS).

The code you should use is the following one.

```
$form['click_stats_date_start'] = array(
  '#type' => 'date_popup',
  '#title' => t('Start date'),
  '#label_display' => '',
  '#date_format' => 'd/m/Y',
  '#date_year_range' => '-1:+0',
  '#date_label_position' => 'hidden',
  '#default_value' => date('Y-m-d'),
  '#size' => 20,
  '#required' => TRUE,
);

```

If you need to visualize a specific value as default value, then the code should be the following one. (Replace `$saved_timestamp` with the value you need to show.)

```
$form['click_stats_date_start'] = array(
  '#type' => 'date_popup',
  '#title' => t('Start date'),
  '#label_display' => '',
  '#date_format' => 'd/m/Y',
  '#date_year_range' => '-1:+0',
  '#date_label_position' => 'hidden',
  '#default_value' => date('Y-m-d', $saved_timestamp),
  '#size' => 20,
  '#required' => TRUE,
);

```
> 2 votes

# Answer
you need to use date() with mktime(). The thread you referenced has the clue for you.

Here is the working example,

```
  $form['click_stats_date_start'] = array(
    '#type' => 'date_popup',
    '#title' => t('Start date'),
    '#label_display' => '',
    '#date_format' => 'd/m/Y',
    '#date_year_range' => '-1:+0',
    '#date_label_position' => 'hidden',
    '#default_value' => date("Y-m-d", mktime(0, 0, 0, date('m'), 1, date('Y'))),
    '#size' => 20,
    '#required' => TRUE,
  );

```
> 1 votes

---
Tags: forms, datetime
---


# Question
Title: AJAX calls fail when the base URL is set
I have installed the Drupal 7.17 security update, and I am having some issues with my site.

If I comment out the `$base_url ='www.xxx.com';` line in the setting.php file, the AJAX calls work; when I uncomment that line, the AJAX calls fail.

What could be the reason behind this? how can I get my base\_url working again?

# Answer
> 1 votes
Make sure you didn't already include a base URL in your ajax link. For my development site, `http://localhost/project1/ajaxlink`, the following will work perfectly when no base URL has been set.

```
$.ajax({url: 'project1/ajaxlink', ...

```

In case a base URL has been set, the AJAX call is equivalent to the following, which will not work.

```
$.ajax({url: 'project1/project1/ajaxlink', ...

```

---
Tags: 7, ajax, configuration
---


# Question
Title: How to see the results of my first module
I created a module to alter the query executed by a view, but i cannot figure it out how to test it ... I mean where should i see the results ? I've created the following files:

```
my_module.info
my_module.module
my_module.views.inc

```

in the second file i have:

```
function my_module_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'my_module'),
    'template path' => drupal_get_path('module', 'my_module'),
  );
}

```

and in the third one:

```
function my_module_hook_views_query_alter(&$view, &$query)  {
  var_dump($view);
}

```

Where should i be able to see the result of var\_dump ?

# Answer
> 3 votes
hook\_views\_query\_alter() is supposed to alter the query passed as second parameter, or the view object passed as first argument, not to output anything. If you want to debug the hook, you should use code similar to the following one.

```
watchdog('my_module', 'View: @view', array('@view' => print_r($view, TRUE)), WATCHDOG_DEBUG);

```

The name you gave to your hook is wrong: You just need to replace hook with the short name of your module. For a hook like `hook_views_query_alter()`, the function name is not `my_module_hook_views_query_alter()`, but `my_module_views_query_alter()`.

# Answer
> 2 votes
Nowhere probably, you're dumping the var straight out to the buffer which isn't the 'done thing' in Drupal :) (unless you're taking care of the page rendering yourself for whatever reason, but that's a different story)

For debugging, get a copy of the Devel module and use the excellent `dpm()` function like so:

```
function my_module_hook_views_query_alter(&$view, &$query) {
  dpm($view);
}

```

That'll give you a nice output to the message area similar to:

You can navigate through and drill down into expandable variables...all in all it makes debugging simple arrays and objects very easy.

# Answer
> 0 votes
Firstly, your hook name is wrong. It should be `my_module_views_query_alter()` instead of `my_module_hook_views_query_alter()` ( kiamlaluno has mentioned )
Assuming you have a view and its machine name is "my\_view" and its menu path is "example/myview".
The `var_dump` result will be rendered in the page http://yousite.com/example/myview

In the hook, you may alter the query of the view by checking its view name, for example

```
function my_module_views_query_alter(&$view, &$query) {
  var_dump($view);  // this will be displayed in all views pages
  switch($view->name){
    case 'my_view' :    // this is machine name of the view
      // query alter here
      var_dump($view);  // this will be displayed only in this view page, for example, http://yousite.com/example/myview
    break;

    case 'another_view' :

    break;
  }
}

```

---
Tags: views, 7
---


# Question
Title: What is the default behavior of the Drupal 7 cache?
I can't find any specific documentation explaining how the default caching mechanism in Drupal 7 works and when does it clear caches automatically. From my own testing, I can state the following:

* Cache is cleared when any content is added
* Cache is cleared when any content is updated
* Cache is NOT cleared when content is deleted!!! (Check my comment below for update).

Where can I find documentation to approve the above and also learn a little more about this topic? Any other cases where cache is auto cleared?

**Details**: the above results are based on turning on both "Cache pages for anonymous users" and "Cache blocks" and setting "Minimum cache lifetime" and "Expiration of cached pages" to none.

# Answer
To find out all events when page and block cache is cleared - you can search through all modules for using of cache\_clear\_all() function.

Here is brief list of such events in Drupal core.

1. Any content is created or updated (nodes, taxonomy terms, comments, etc)
2. Content permissions are updated.
3. Block is created or updated.
4. Vocabulary created, edited or deleted.
5. Any settings form in admin back-end is submitted (those forms that use system\_settings\_form()).
6. User account is created, updated or canceled.

As you see page and block cache is not cleared automatically when any content is deleted.
> 4 votes

---
Tags: 7, caching, performance, nodes
---


# Question
Title: How to get the list of fields which are referenced to particular vocabulary
As the title say I want to get the list of fields which are referenced to particular vocabulary.

For example field1 and field2 are taxonomy reference fields and the vocabulary associated to them is vocab1, now if I pass vocab1 I should get field1 and field2 as the results.

# Answer
> 1 votes
The vocabulary that a term reference field is associated with is held in the `data` column in the `field_config` table. Unfortunately that's a serialised PHP array so there's no clean way to query it directly.

The Field Info API doesn't seem to have a function to query fields by type so you'll need to implement your own. The basic logic would be to grab a list of fields that have the `taxonomy_term_reference` type, along with their data, then loop through each to determine if it has the correct vocab assigned.

Something like...

```
function MYMODULE_term_reference_fields_by_vocab($vocab) {
  $args = array(':type' => 'taxonomy_term_reference');
  $data = db_query('SELECT field_name, data FROM {field_config} WHERE type = :type', $args)->fetchAllKeyed();

  $field_names = array();
  foreach ($data as $field_name => $info) {
    $info = unserialize($info);

    if ($info['settings']['allowed_values'][0]['vocabulary'] == $vocab->machine_name) {
      $field_names[] = $field_name;
    }
  }

  return $field_names;
}

```

You'll probably want to add a static caching mechanism to that for performance, but it'll work as-is if that's not important.

---
Tags: 7, taxonomy-terms, entities
---


# Question
Title: Using form_set_value with commerce in custom form
I'm trying to change the value of a form within a custom Commerce Pane **during validation** but I get the following error:

> Recoverable fatal error: Argument 2 passed to drupal\_array\_set\_nested\_value() must be an array, string given, called in /var/www/vhosts/innovista.org/httpdocs/includes/form.inc on line 2514 and defined in drupal\_array\_set\_nested\_value() (line 6440 of /var/www/vhosts/innovista.org/httpdocs/includes/common.inc).

As far as I see my code is an array.

```
form_set_value($form_state['values'][$checkout_pane['pane_id']]['donation_amount'], array('und' => array(0 => array('value' => '999'))), $form_state);

```

I've been using `$checkout_pane['pane_id'] . '][donation_amount'` with `form_set_error()`, and it works fine. I can't understand why argument 2 is not working.

I have tried setting #parents as this question suggests: Using form\_set\_value() in Drupal 7

In the following way:

```
$form_state['values'][$checkout_pane['pane_id']]['donation_amount']['#parents'] = array( 'values',$checkout_pane['pane_id'], 'donation_amount');

```

But this produces an extra error:

> Notice: Array to string conversion in donation\_checkout\_pane\_pane\_checkout\_form\_validate() (line 186 of /var/www/vhosts/innovista.org/httpdocs/sites/all/modules/donation\_checkout\_pane/donation\_checkout\_pane.module).

Do you have any idea?

# Answer
The code executed from form\_set\_value() is the following one.

```
function form_set_value($element, $value, &$form_state) {
  drupal_array_set_nested_value($form_state['values'], $element['#parents'], $value, TRUE);
}

```

`$checkout_pane['pane_id'] . '][donation_amount'` is a string, even if `$checkout_pane['pane_id']` is an array; this is because the string concatenation operator cast an array into a string.
If `$element` is a string, then `$element['#parents']` is a string made of one character, similarly to what happens with `$string[0]`, when `$string` is set to `'long string with many characters that are added just to make the string longer'`.

That explains the error about the second argument.

With form\_set\_error(), `$checkout_pane['pane_id'] . '][donation_amount'` works because the function is expecting a string as first argument, and the format of that string is exactly the format of the string you are passing.

The first argument of form\_set\_value() is a form API array for the form element for which you want to set the value. That is not the content of `$form_state['values']`. As that is the code for a form validation handler, it should be similar to the following one.

```
function mymodule_form_validate(&$form, &$form_state) {
  // …
  $form[$checkout_pane['pane_id']]['donation_amount']['#parents'] = array($checkout_pane['pane_id'], 'donation_amount');
  form_set_value($form[$checkout_pane['pane_id']]['donation_amount'], '999', $form_state);
}

```

You still need to verify the content of `$checkout_pane['pane_id']` is effectively the parent of the element you want to change. For that, you can install the Devel module, and print the structure of `$form` using `dpm($form);`.

As for the answer given in the other question, I can say it is based on the description present in form\_set\_value() for the `$element` parameter.

> The form element that should have its value updated; in most cases you can just pass in the element from the $form array, although the only component that is actually used is '#parents'. If constructing yourself, set `$element['#parents']` to be an array giving the path through the form array's keys to the element whose value you want to update. For instance, if you want to update the value of `$form['elem1']['elem2']`, which should be stored in `$form_state['values']['elem1']['elem2']`, you would set `$element['#parents'] = array('elem1','elem2');`.
> 0 votes

---
Tags: 7, forms, commerce
---


title: Drupal Translations

text:
# Question
Title: Drupal Translations
I'm downloading .po files from http://localize.drupal.org/translate/downloads which is great for Drupal Core translations, but I'm wondering if it's possible to download a .po file which could update custom text/menu items/etc?

# Answer
If you install the i18n module you can both export and import custom translations for your site which sit outside of any other module translation. The module groups translations by source including the Built-in interface, Blocks, CCK, Content types, Menus and Taxonomy depending on which submodules you enable.
> 0 votes

---
Tags: i18n-l10n, importing-exporting
---


# Question
Title: How to display image height and width in pixels?
I have image size, but I can't find any field for image height and with in Views.

I need to display orginal image height and weight, something like: Resolution: 800px x 600px.

# Answer
Have you created an image style for the image (what used to be ImageCache in Drupal 6 now in Core)? Configuration -\> Media -\> Image Styles

If not perhaps you should because this will give you much more control over the size of an image without having to worry about theming the size directly. Set up a preset for the image display in question and you can choose the size it should be generated at for a particular use.
> 0 votes

---
Tags: 7, views, media
---


# Question
Title: How to add a field widget for multiple file upload?
Is there a module that provides a multiple file upload (Drag and Drop) widget? If there isn't, how can I build one? Will it require a special setup for the server stack (LAMP)?

# Answer
Multiupload FileField Widget

This is what you want. It enables the HTML5 standard for uploading multiple files. Use a normal file field but use this widget. Now one can select several files when browsing for files to upload. This works for never web browser but not IE8.
> 2 votes

# Answer
jQuery File Upload module is in Dev, but it looks exactly like what you want.

Here's a demo of how jQuery File Upload works: http://blueimp.github.com/jQuery-File-Upload/
> 1 votes

# Answer
Hey you can use the PLuplaod module in drupal 7. http://drupal.org/project/plupload .. it support for HTML5, flash and HTML4 also easy to use.
> 0 votes

---
Tags: 7, files, entities
---


# Question
Title: Are custom content types a good way to model the classic entity relationship model?
I have several content types which will store thousands of records each one. Those content types will be related to each other as in a classic *1..N* or *N..M* **relationships** I would like to query those content types taking this relationship into account.

I have searched for this on d.o but I am puzzled with the big quantity of modules available. For instance is `entity` and `entity reference` any good for this ?

What is the best way to model the classic entity-relationship model of the database systems ? Also, will I be able to tune the database (mainly create new indexes) to increase the performance of the queries ? I am asking this because I will need to tune the database because of the big amount of data, so this is something to take into account at the time of considering different approaches to the modeling decision.

# Answer
> 4 votes
In Drupal 7, you'll want the Entity module as it extends the core Entity API to do lots of useful things, and a lot of contributed modules depend on it.

To create relationships between entities (a "node reference" relationship, if you will) you'll want the Entity Reference module. Another more radical approach is the Relation module which provides two-way relationships – this is in early development stages and is a bit more complicated. I would recommend the Entity Reference module, as even though the initial relationship is 1-way, it's simple enough to find the referencing-entity on a referenced-entity when needed.

Regarding your question about tuning the database – the relationships are not setup as foreign keys or anything like that, as Drupal handles your database constraints in code and not within the database schema itself. That's a whole other conversation. The tables that contain fields for a specific node type, including the table that includes a reference to another node ID, are just joined with the node table on "entity\_id". There are pros and cons to this – if you're a traditional database admin type, this may seem problematic, but it's the job of the CMS to maintain integrity in this model. I don't think you'll find ways to tune the database via new indexes, although you could certainly try. Thousands of nodes is not a lot of data and you should see Drupal 7 – in a properly tuned environment, with queries and views that do not contain extraneous joins – performs quite speedily.

My 2 cents.

---
Tags: 7, entities
---


# Question
Title: How to manage contextual filters for a simple date-based view
I'm building a simple view to show content of X type, filtered by date. I want this view to be available via URLs like:

* /events/2012 - *Show all content for this year only*
* /events/2012/11 - *Show all content for this year and month only*
* /events/2012/11/28 - *Show all content for this exact day only*

These URLs form part of this section's hierarchy so the patterns are non-negotiable.

The date I'm filtering on is a date field provided by the Date module, and has an optional end date.

I've tried setting the path of the view to `/events/%/%/%`, and have added three contextual filters for the date field. The granularity for each of the filters is set correctly to the respective date part for that filter.

However, none of that works; I either get all event content, regardless of year, for the year filter, or no content at all if I include the other filters.

There are several related questions (none with answers as it happens):

But nothing that covers exactly what I'm looking to do.

How do I tame these contextual filters, **without resorting to the PHP filter which is simply not an option**? I can't believe that there's no way to do this just with the UI, it seems like one of the most obvious use-cases.

**UPDATE**

I tried using a filter with a granularity of month, and changed the argument to `2012-11`...and it worked.

So I think the answer is simply that the date filter handlers don't work as I expected.

# Answer
> 3 votes
Here is the one approach,

* First create a custom call back for /events
* Remove the date contextual filters from your view
* Add only one filter(not contextual filter) to your view for that date field, accept the default values and save the view
* Then use the following code in your custom callback to execute the view

```
function get_events($year = '', $month = '', $day = '')
{
  // Display ID of the view.
  $display_id = 'default';
  // get the view object.
  $view = views_get_view('events_views'); //Replace with your view name
  $filter = $view->get_item($display_id, 'filter', 'field_event_date_value');
  if ($year) {
    $filter['value']['value'] = $year;
    $filter['granularity'] = 'year';
  }
  if ($year && $month) {
    $filter['value']['value'] = $year . '-' . $month;
    $filter['granularity'] = 'month';
  }
  if ($year && $month && $day) {
    $filter['value']['value'] = $year . '-' . $month . '-' . $day;
    $filter['granularity'] = 'day';
  }
  $view->set_item($display_id, 'filter', 'field_event_date_value', $filter);
  // If you have any other arguments read from the URL and pass it here as part of args array
  $result = $view->execute_display($display_id, $args);
}

```

Hope you are aware of how to pass arguments to the view programatically. This is what we are using for complex date filters in views which lacks lot of support for date functionality, however we haven't tried with granularity. This is un tested and not optimized. Modify it according to your need.

---
Tags: views
---


# Question
Title: Module to separate the links of menus by language?
A few days ago I found a module to separate the links of menus by language. Given a localized menu then you get the links separated by languages. Very useful I think.

But now I can't remember its name. Does anyone know it?

# Answer
I found it, it's a sandbox project though: http://drupal.org/sandbox/TimBrandin/1835360
> 1 votes

---
Tags: 7, routes
---


# Question
Title: Can Pressflow 7 be a drop-in replacement for Drupal 7?
The Pressflow site mentions that it is used by many ***Drupal 6*** sites, and in the FAQ, in answer to the question "What's the deal with Pressflow 7?" says

> Pressflow 6 made significant improvements to Drupal core in scalability and performance and most of these features have been contributed back to Drupal 7 core. Until well understood performance patches are created for Drupal 7 Pressflow development will be slow. Additionally, as Drupal 8 matures, significant enhancements will likely be backported to Pressflow 7.

That sounds to me like a very indirect way of implying that there are lots of problems with Pressflow 7 that cause people to avoid using it, but stated in a way that no one would understand unless they're already aware of the problems. The answer seems like more of an explanation (indirect and implied) of *why* there are problems, than really an explanation of *what the situation is* with Pressflow 7.

So, can anyone tell me in plain English what the situation is? Is there some reason I wouldn't want to replace a normal Drupal 7 site with Pressflow 7? Or some reason it is simply impossible? (Or is the problem simply that Pressflow 7 has not been optimized to the same degree that Pressflow 6 has?)

# Answer
It's not that there are problems with Pressflow 7, but that there are no significant benefits to it at this time. This is stated in the lines above your quote:

> If your project is built on Drupal 7 you might not need to use Pressflow at this time because the key enhancements from Pressflow 6 were added to Drupal 7.

You could use Pressflow 7 as a replacement, but why bother if there are no advantages? (I haven't actually used Pressflow 7 because of this).
> 4 votes

# Answer
Pressflow is a Drupal fork. Pressflow 6's code is different from Drupal 6, and it is more performant. (Pressflow 6 is used on Drupal.org, as far as I know.)
What the quoted text means is that, since some of the code used from Pressflow 6 became part of Drupal 7 (thanks to the patches offered from the team who develops Pressflow), the development of Pressflow 7 is slowing down. Once the development of Drupal 8 is more stable, the code of Drupal 8 will be possibly back-ported to Pressflow 7.

At the actual state, Pressflow 7 is more performant of Drupal 6, but it is similar to Drupal 7.
> 2 votes

---
Tags: 7
---


# Question
Title: What is the correct ways to add themes to a profile within an Aegir install
I have Aegir installed with a two platforms. I'm interested in adding some additional themes/modules to the platform. Normally I might do this through Drush, but when I log into the server, I am logged in as Root not as Aegir (I don't believe you can log in a Aegir).

What is the best approach to adding themes and or modules? Should I simply upload via FTP and then make sure that I change ownership of the files?

# Answer
> 2 votes
I figured out a work around, actually it is quite simple. First ssh in as root. Then switch users su - aegir. Now drush will work. then simply use the drush command with the @sitename, so for instance `drush @sitename.com dl themename`. now this downloads to sites/all/modules, if you want you can move it to sites/sitname/modules. Either way it's a pretty fast workflow.

# Answer
> 0 votes
There are some good beginner tutorials here. http://friendlydrupal.com/aegir

since you are able to log in as root then you can also create the aegir user at the bash prompt like this:

```
ln -s /var/aegir/config/apache.conf /etc/apache2/conf.d/aegir.conf
useradd -r -U -d /var/aegir -m -G www-data aegir
echo 'aegir ALL=NOPASSWD: /usr/sbin/apache2ctl'>> /etc/sudoers

```

this is assuming you are on an Ubuntu distro and that you have installed aegir properly. Other helpful links; http://vimeo.com/17131725, http://vimeo.com/groups/webdesigntuts/videos/9127281 and of course, http://community.aegirproject.org

I also found this which might be ideal for the situation:

> Primarily, I had to generate the key file as Aegir user and move the key file over from the first server, where it was generated, to the second server, where it would be used, as a conventional (i.e., non-system account) user (that is assumed to have FTP capability at the second server). This can be accomplished as follows: Steps to be run from the first server:

* Start by being logged in as the conventional user
* Become Aegir user: "sudo su -s /bin/bash - aegir"
* Create key file: "ssh-keygen -t dsa" \[when prompted for text, just hit return\]. This produces, among other things, a public key file named "id\_dsa.pub". This file will be copied to the other server.
* Copy id\_dsa.pub to a location that is accessible to the conventional user account: "cp .ssh/id\_dsa.pub /\[accessible\_location\]/." + "chmod 777 /\[accessible\_location\]/id\_dsa.pub" (remember to remove this temporary file later)
* Return to being the conventional user by exiting out of "su"
* FTP the file from \[accessible\_location\] to the second server \[again, this assumes that a FTP capability exists between the first and second server, and that the conventional user is able to use that capability on both machines\]

> At the second server:

* Become the Aegir user (as above)
* Copy the file to the .ssh directory, under Aegir user's home directory, as the file "authorized\_keys" (e.g., /var/aegir/.ssh/authorized\_keys). Note: if this file already exists, you want to concatenate id\_dsa.pub on to the existing authorized\_keys file. Last, I had to set the file permissions just right on the second server:
* change the permissions on this file to 600 (i.e., chmod 600 authorized\_keys) When I tried this before, I left the permissions on authorized\_keys as 777 during debug. I now understand that passwordless login WON'T WORK with this permissions set to 777. Obviously, we would not leave them at 777 in a permanent solution anyway, but I was surprised that this issue was a show-stopper during debug/installation.”

I found this at http://groups.drupal.org/node/89684

---
Tags: drush, aegir
---


title: Edit one field across multiple nodes

text:
# Question
Title: Edit one field across multiple nodes
Is there a way to edit a single field (for example: publication date) across a few dozen nodes?

I added a field called "Publication date" to an existing content type, and now I need to add a date to a whole lot of them. I'd love to have a table display showing the node title, and the field in question next to it in an editable column.

# Answer
I would use Views Bulk Operations. Build a view that shows the nodes you want, then add the display style to be "views bulk operations", adding the option to update a field. Then, when you view this view, you'll see a table of all of the items you want along with checkboxes and a dropdown to mass-update the fields of your choosing.
> 2 votes

# Answer
The editable fields module (http://drupal.org/project/editablefields) works well with views. So you could build a view with node title and this pub date field making the pub date editable.
> 3 votes

---
Tags: entities
---


# Question
Title: Can I just change Drupal's default timezone to test to see if some scheduled rules will fire?
I need to test to see if some scheduled rules will fire as expected. I cannot change the server time, as I do not have access to do this. However, if I change Drupal's default timezone can I expedite the process? If not is there another way to do this.

Note: I cannot just shorten the schedules rules as they are hardcoded in a contrib module.

# Answer
I am 95% certain that drupal is using the server's system time so changing the timezone will have no effect as far as rules are concerned.

Alternatively, you could (temporarily) hack the contrib module to test whatever you need to test and when you're sure things are working, restore the original module when done.
> 3 votes

---
Tags: rules, datetime
---


title: Taxonomy view per vocabulary

text:
# Question
Title: Taxonomy view per vocabulary
I want to create different view pages for different vocabulary types.

For each vocabulary I created a view and assigned a filter to limit to one vocabulary; as a page path I'm using `taxonomy/term/%` (on every view). It seems like only one view is working. For all others no details displayed (just an empty page is showing up).

Is this a valid approach? What can I do to display different taxonomy term pages for each vocabulary?

Also, the solution tvi doesn't work.

# Answer
The best solution that I have been is the Taxonomy Display module. It Can handle each view, no matter its URL! it's very powerful!

> The taxonomy display module allows administrative configurable term display pages. This allows administrators to override the default presentation of taxonomy term pages per vocabulary through the taxonomy term page's manage display form.
> 4 votes

# Answer
Panels: enable prepared taxonomy term page, clone it for each your required vocabulary and add "Selection rules" for these.
> 2 votes

# Answer
Use Taxonomy Views Integrator module:

How do you use it:

1. Enable TVI module (requires taxonomy and views)
2. Set permissions regarding TVI administration
3. \[optional\] Define a new view, clone taxonomy/term/\* view, or you may use a view from code.
4. After you know what view you want to use on a vocab or term, simply visit the term or vocabulary edit page that the view should be applied to, select the view that you wish to use using the drop-down select list, select the view plugin, and save your changes.
> 2 votes

# Answer
You can create special template taxonomy-term.tpl per each vocabulary. You can specify the vocabulary here.

> vocabulary-\[vocabulary-name\]: The vocabulary to which the term belongs to. For example, if the term is a "Tag" it would result in "vocabulary-tag".
> 1 votes

# Answer
You can create separate template file for specific vocabulary, For vocabulary of term 2 you can create tpl file like

page--taxonomy-vocabulary-2.tpl.php

And in template.php file you have to add following code:

```
if (arg(0) == 'taxonomy' && arg(1) == 'term') {
  $term = taxonomy_term_load(arg(2));
  $vars['theme_hook_suggestions'][] = 'page__taxonomy_vocabulary_' . $term->vid;
}

```
> 0 votes

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


# Question
Title: Views, Grouping by various levels of granularity in a date field?
I'd like to group a nodes in a view by date, but more specifically, I'd like Grouping field Nr.1 to be year and Grouping field Nr.2 to be the month.

Possible?

## At current the test view looks like this:

## I'd like it to look more like this

## 2015

November

* ibh Persto Torqueo Vel

October

* Commoveo Macto Premo Vel

September

* Ad Adipiscing Meus Nutus Tego Torqueo

## 2012

December

* Antehabeo Decet Pala Populus

April

* Quadrum Si Suscipit

# Answer
Well I think I got it.

## **Step 1: Add two new date formats**

I set up two new date formats: Month only and Year only

---

## **Step 2: Query the date date field twice under the new formats**

Add the Publication Date field twice in these newly created formats

---

## **Step 3: Apply the proper grouping to the view**

Here's how I grouped it....

---

## **And finally, the results**

Below, albeit poorly formatted, I have two two years of 2015 and 2014 with sub divided months.

(For some reason, what ever the last grouped field is encapulated in . I tried playing with the formatting but no luck. However, I've worked out my logic here.)
> 0 votes

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


# Question
Title: How to make a calendar tab for every user showing user's events?
I followed the tutorial Calendars for Organic Groups - A simple tutorial for D6, and successfully created a calendar for every group in my site showing its events. I also managed to show the calendar as a tab in every group homepage using the path `node/%/calendar`.

Now I want to create a second calendar page, shown as a tab in every user profile page, which will provide the user information about all the events that are registered in the groups the user is a member of. I created a second view, and configured it to show all the events of the site.

How can I limit this view to only show the events from all the groups? How can I add its page as a tab in every user profile? Is there a way to limit the access to this tab to only the user that owns the profile?

# Answer
Clone the default view "OG all user group content" provided by Organic Groups. Filter content type based on events and thats it. This displays all the events from all the groups the user is subscribed to.

You can also change the display style to calendar and add a bunch of other settings.
> 1 votes

---
Tags: 6, users, organic-groups, datetime
---


# Question
Title: how to delete width and height attributes from image field for particular nodes
I would like to strip width and height attributes from image fields for a few specific nodes.

I tried `hook_preprocess_image($vars)` but $vars don't have enough information. From the documentation, `theme_image()` won't have that information, either. I can't figure out the node from the path, because the node is used in a block. Using CSS `width:auto !important;` does not work, at least with Firefox 16 (and I've read IE 8 has problems with it, too). Any ideas?

# Answer
You could implement hook\_field\_attach\_view\_alter(), which allows modules to alter the rendering array for the entity. Using the following code, I found the array structure for the image field attached to the nodes I was watching.

```
function code_testing_field_attach_view_alter(&$output, &$context) {
  if ($context['entity_type'] == 'node' && !empty($output['field_image'])) {
    $image = $output['field_image'];
    unset($image['#object']);
    watchdog('code_testing', 'Image: @image', array('@image' => var_export($image, TRUE)), WATCHDOG_DEBUG);
  }
}

```

In my case, the array had the following structure.

```
array (
  '#theme' => 'field', '#weight' => '2', '#title' => 'Image',
  '#access' => true, '#label_display' => 'hidden', '#view_mode' => 'full',
  '#language' => 'und', '#field_name' => 'field_image', '#field_type' => 'image',
  '#field_translatable' => '0', '#entity_type' => 'node', '#bundle' => 'article',
  '#items' => array(
    0 => array(
      'fid' => '129', 'alt' => '', 'title' => 'title',
      'width' => '235', 'height' => '568', 'uid' => '1',
      'filename' => 'imagefield_rGEXAF.png',
      'uri' => 'public://field/image/imagefield_rGEXAF.png',
      'filemime' => 'image/png', 'filesize' => '1372', 'status' => '1',
       'timestamp' => '1354109930'
    )
  ),
  '#formatter' => 'image',
  0 => array(
    '#theme' => 'image_formatter',
    '#item' => array(
      'fid' => '129', 'alt' => '',
      'title' => 'title',
      'width' => '235', 'height' => '568', 'uid' => '1',
      'filename' => 'imagefield_rGEXAF.png',
      'uri' => 'public://field/image/imagefield_rGEXAF.png',
      'filemime' => 'image/png', 'filesize' => '1372', 'status' => '1',
      'timestamp' => '1354109930'
    ),
    '#image_style' => 'large', '#path' => ''
  )
)

```

The code you should write in your module is similar to the following one:

```
function mymodule_testing_field_attach_view_alter(&$output, &$context) {
  if ($context['entity_type'] == 'node' && !empty($output['field_image'])) {
    // You can check the node ID with context['entity']->nid, and the content type
    // with context['entity']->type.

    unset($output['field_image'][0]['#item']['height']);
    unset($output['field_image'][0]['#item']['width']);
  }
}

```
> 2 votes

# Answer
You may be able to accomplish this with view modes.

Make some new image styles for these particular images. Implement a `theme_image_style()`, which checks for this new style name and unsets width and height as needed.

If you install/enable Entity View Modes you can create new view modes for your nodes. Clone what you have for node/teaser to your additional layouts. For the images, change the display settings to use your new styles.

Next is the part I am not sure what the best solution is. One way to use the view mode is to use a Panel page for each individual node. When you add the content, you can set the view mode to one of your new ones. Otherwise, I would try @PierreBuyle's solution at Using a different view mode with a node. This essentially overrides the menu page for node/nid to add some additional intermediate logic to set the view mode.
> 3 votes

---
Tags: 7, hooks, media
---


title: Adding button to toolbar for non-admin

text:
# Question
Title: Adding button to toolbar for non-admin
Im trying to add a button to the toolbar for my module. Now I know I can just it in the menu and blah blah but I want it to make it when the module is activated. I think im on the right track using hook\_menu however it doesn't exactly specify the callback to do this.

This is what I have so far....

```
function mysite_form_menu() {
$items = array();
$items['admin/config/mysite_form/ads'] = array(
    'title' => 'mysite Ad\'s',
    'description' => 'Allows administrators to adjust ads.',
    'page callback' => 'ads_page_callback',
    'access callback' => 'current_user_hide_tabs',
    'page arguments' => array('ads'),
    'access arguments' => array('administer editor mysite settings'),
    'file' => 'thank_you_ads.inc',
    'file path' => drupal_get_path('module', 'mysite_form'),
);
}
function current_user_hide_tabs() {
  global $user;

  if (isset($user->roles['3']) || isset($user->roles['5'])) :
  return true;
  else :
  return false;
  endif;

}

```

This is a image of the toolbar I am talking about so there is not any confusion.

# Answer
The buttons on the toolbar are automatically added when the module is enabled, as long as the menu items defined from the module with `hook_menu()` are sub-menus of the admin menu defined from the System module.

The function that renders the toolbar is toolbar\_view(), which contains the following code.

```
  // Retrieve the admin menu from the database.
  $links = toolbar_menu_navigation_links(toolbar_get_menu_tree());
  $build['toolbar_menu'] = array(
    '#theme' => 'links__toolbar_menu',
    '#links' => $links,
    '#attributes' => array('id' => 'toolbar-menu'),
    '#heading' => array(
      'text' => t('Administrative toolbar'),
      'level' => 'h2',
      'class' => 'element-invisible',
    ),
  );

```

toolbar\_menu\_navigation\_links() excludes the hidden menu items, and the ones to which the user doesn't have access.

`toolbar_view()` is called from `toolbar_pre_render()`, which is the pre-render function added from toolbar\_page\_build() to `$page['page_top']['toolbar']`. Once the module is disabled, the menu items should not be anymore visible on the toolbar. The Toolbar module doesn't use any cache; I would expect the change to be immediately visible.

To appear on the toolbar, the menu item needs to be a direct sub-menu of admin. Differently, as in your case, it will not appear in the toolbar.

To test it, I added the following code in a module I use to test code.

```
/**
 * Implements hook_menu().
 */
function code_testing_menu() {
  $items['admin/mysite_form'] = array(
    'title' => 'My site form',
    'description' => 'Set custom settings for a site',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('code_testing_mysite_form'),
    'access callback' => 'code_testing_mysite_access',
  );

  return $items;
}

function code_testing_mysite_form($form, &$form_state) {
  $form['code_testing_switch_lights'] = array(
    '#type' => 'checkbox',
    '#title' => t('Switch lights on.'),
    '#default_value' => variable_get('code_testing_switch_lights', TRUE),
  );

  return $form;
}

function code_testing_mysite_access() {
  return user_access('administer site');
}

```

What I obtained is visible in the following screenshots.

Once the module is disabled, the toolbar doesn't contain anymore the menu.

I would rather not put a menu item directly, under admin, if not in particular cases. If the menu item just shows a form for a module's settings, I would not show it in the toolbar. If, vice versa, the module would show a page of links like the Advanced help does, then I could consider adding the menu item directly under admin.

In the other cases, I would consider adding links through the Shortcut module. This would mean adding code in `hook_enable()` that:

* Creates a new shortcut set to use for the users with a specific role
* Sets the new shortcut set as default for those users

In `hook_disable()`, the code should:

* Change back to the old shortcut set

Once the module is uninstalled, it should remove the shortcut set it created.

As alternative, the module could add a new link to the shortcut set used from user with a specific role.

The functions that such code would use are the following ones:

Playing with the Shortcut module, and manually adding a link to a menu item defined in `hook_menu()` from a module that I then disable, I noticed the link is automatically removed from the shortcut set once the module is disabled. Even after re-enabling the module, the link is not anymore shown as part of the shortcut set.

The second screenshot shows the shortcut content after the module is disabled.

After I re-enable the module (which defines the "My site form" menu callback I shown before), this is what appears as content of the shortcut set. I didn't save the shortcut set, since the other screenshot.
> 1 votes

---
Tags: 7, routes, toolbar
---


# Question
Title: 7 - How to create a view using ApacheSolr?
How am I able to create a view using ApacheSolr as base in Drupal 7?

All I can see when creating a new View, is ApacheSolr localhost server which doesn't give me the fields that I need, found few links online but none of them helped! very confused!

I am using :

* Apache 7.x-1.0-rc4
* Drupal 7
* Views 7.x-3.5
* Apache Solr Search Integration 7.x-1.0-beta1

# Answer
> 3 votes
The various answers here do not mention the apachesolr\_views module, which has the advantage of working directly with Apache Solr Search Integration. The Search API Solr module requires a distinct setup, and if you want to use both integrations simultaneously, it's more complicated. If you already have Apache Solr Search Integration working for you, I suggest taking the simpler approach. You'll then get views right out of the box.

# Answer
> 4 votes
I add a full response.

If you want a full integration with Solr and Views you should use Search api with Search Api Solr (there several modules that work with Search Api, see the Search Api page).

You will be able to:

There are many usefule modules that work with Search Api: autocompletation, indexing files, create index on file taxonomies and users, spellcheck, sorts, ranges, saved searches etc.

Every day I use Search Api at work, for views and for default search, I think is the best solution.

# Answer
> 0 votes
You should switch to the Search API module.

> This module provides a framework for easily creating searches on any entity known to Drupal, using any kind of search engine.

The Views capabilities are excellent.

# Answer
> 0 votes
I'm not sure I totally understand the nature of the question, but creating a view in 7 with Apache Solr works great for me. You have to first create an index and then when you go to create the new view the name of that index should show up in the list, ie "Show \[ name of index \] sorted by..." . From there you can create a table view or whatever. If you are using Facet API then you can define facets on that index, which automatically creates blocks and you move those blocks into a region and have them only show up at the path that corresponds with the view you created.

---
Tags: views, search
---


title: how to make a search form

text:
# Question
Title: how to make a search form
I would like to make a search form for my site so that users can use a series of drop down menus and click to search and it will create a view with listings that fit the criteria of the search.

Its for a property/real-estate website so I want the user to be able to select how many bedrooms, price range, and location. Then, they will get a list or properties that are in the location selected with the number of bedrooms specified etc. I spent a while searching and all I could find is how to customize a single Drupal search field in the header.

# Answer
You add some filter criteria, and expose them to the users who see the view. The filter criteria can be any of the filter criteria implemented by the Views module, but there is one that you are probably interested to add it for a search view: *Search: Search Terms.*

>

>

You could also add a filter for selecting the user who posted the node, and the date when the node was posted.

>

>

At the end, the view page would appear similar to the following one.

>
> 4 votes

---
Tags: views, 7, forms
---


title: How to Alter Views Result in Drupal 7

text:
# Question
Title: How to Alter Views Result in Drupal 7
i've several list of products display on a Drupal block. I get the list of products using views module. Then, i've several pages dedicated for each product. Before the list of products display on a block, i need to check if the page for the product exist of not. if exist, i need to display the product as list, but if not exist, i don't want to display it as link.

Example:

I have pages:

Product/A for product A

Product/C for product C

I have products:

A

B

C

D

So, views result that display on the block, should be:

A -\> as link

B -\> not a link

C -\> as link

D -\> not a link

How can I achieve that?

# Answer
> 3 votes
The only way I can think is to use a views field template file to be overridden.

Copy the template **sites/all/modules/views/theme/views-view-field.tpl.php** to your current enabled theme folder. Assuming that you have a block view "product-listing", you could rename it to **views-view-field--product-listing--block.tpl.php**.

Rescan template files in your view theming information. The file **views-view-field--product-listing--block.tpl.php** just created should be highlighted with bold. Now, you have an active custom field template for your block view.

Then, you can edit the template as you need. Here is a sample code:

```
<?php
 $alias = drupal_get_path_alias('node/'.$row->nid);
 if(drupal_valid_path($alias)){
     $url = url($alias);
?>
    <a href="<?php print $url; ?>"><?php print $row->node_title; ?></a>
<?php
}else{
?>
    <span><?php print $row->node_title; ?></span>
<?php
}

```

You can check if a page ( or path ) exists or not by using drupal\_valid\_path().

---
Tags: 7, views, hooks
---


# Question
Title: Getting JQuery Masonry to work with Drupal 7 Views
I want to do this without porting the fluid grid module to 7 from 6. I can't for the life of me get a view page of images to work with Masonry.

Does anyone has experience with this and know how to get it working with just masonry.js and not a module?

Thanks

# Answer
> 6 votes
There's actually a Masonry module now

> Makes the jQuery Masonry plugin available to Drupal as a library.

# Answer
> 1 votes
i just took a short look at masonry .., you can add the masonry.js to your theme, and add a custom .js with a drupal.behavoir containing your masonry code - but this will be used on every page. the

you can do the same in a custom module for dedicated includes; only when your view is displayed.

---
Tags: 7, javascript
---


# Question
Title: How to use Migrate module to import Videos?
I have a bunch of blog posts from an old site, some of which have .flv videos. I'm using the Migrate module to migrate all of these blog posts and the videos are the only piece left. I'm using the Video module for the embedded videos in my blog posts.

How do I use the Migrate module to import those videos into drupal?

# Answer
> 1 votes
I had to migrate a few thousand flv and mp4 videos. I ended up just migrating the file name into a field, uploading the videos files to s3 and then using a custom node.tpl.php to render the player:

```
<?php
  //display legacy videos
  $mediaid = $content['field_mediaid']['#items'][0]['value'];
  if ($mediaid != '') {
      $video2 = '<a href="http://mydomain.s3.amazonaws.com/videos/ka/'.$mediaid.'.mp4" id="player" class="flowplayer"></a>';
              flowplayer_add('#player', array(
                'clip' => array(
                  'autoPlay' => TRUE
                ),
              ));
        print $video2;
 }
 //hide the mediaid field from display
 hide($content['field_mediaid']);
?>

```

Not very elegant but it got the job done. I used migrate 7.x-2.2 back then, maybe 2.5 has better video and/or file import features.

---
Tags: 7, files, migrations
---


title: Drupal 7: how to build a form system

text:
# Question
Title: Drupal 7: how to build a form system
* I want to build something like:
* We have 2 type of users: staff and student.
* Student logins into a drupal site, then a collection of forms presented to the student
* Form type 1: Student selects a form then fill in all fields. After hitting the submit button, data will be saved as a node.
* Form type 2: Similar as form type 1, except the same student visits the same form, s/he will see the previous data s/he entered.
* Very similar situation for staff.
* I wonder what are the basic steps I need to take.

# Answer
I can't give the complete solution, Yet I will try to relate things what you have asked to things what we have in Drupal,

1. Form type 1 =\> Any Node type (say Article)
2. Form type 2 =\> Any Node type (say blog)
3. Student =\> Drupal User (has a profile of student, use profiles2 module )
4. Teacher =\> Drupal User (has a profile of Teacher, use profiles2 module )

User Permissions for Node creation, Node edit by its own author. Views to display the forms and user redirection module to get something you want.
> 0 votes

---
Tags: 7, nodes, forms, entities
---


# Question
Title: Alter render (array) of a field in a View?
How do I alter the rendering of a field in a View?
Where can I access the render array before the html is generated for output?

For example, if I have an image field included in my view, where can I add to the attributes of the image before the image is rendered using `theme_image`? Assuming that the field is eventually still rendered using `theme_image`.

I want to add attributes **to the image tag** and NOT the surrounding `divs` that Views inserts into the markup.

EDIT based on answer by Jimajamma:

Editing the `$view->result` as suggested is causing the View to crash. Page doesn't render correctly anymore:

```
function MYMODULE_views_pre_render(&$view) {
   if ($view->name=='viewyouarelookingfor') {
      foreach($view->result as $row) {
         $row['field_body'][0]['rendered']['#markupe'] = '<p>Test!</p>'; // causes View to crash
      }
   }
 }

```

# Answer
> 9 votes
I'd take a look at the `views_pre_render(&$view);` hook. There, in your module, you can do stuff like:

```
 function MYMODULE_views_pre_render(&$view) {

   if ($view->name=='viewyouarelookingfor') {

      // do whatever you want

   }

 }

```

and do whatever you want meaning you have access to $view-\>result which is an array of all the raw data making up each row. Throw in a `drupal_set_message('<pre>' . print_r($view->result, true) . '</pre>');` or its equivalent to take a peek at that and you should be able to work all kinds of magic.

If this doesn't work to your needs, you can still render the field any way you like from a view template for that row or field itself.

# Answer
> 2 votes
Also, you need to make sure that you use the array key `'#markup'` and not `'#markupe'`.

---
Tags: views, entities, hooks, theming
---


# Question
Title: Automatically downloading libraries for a module
I have a small module on drupal.org. Among a few other things, my module adds support for a third-party PHP library to Drupal. Users are expected to download the module to .../libraries/ and the module provides helper functions, etc.

A few days ago I had a feature request come in. Essentially, a user is asking for a way to automagically download the PHP library to .../libraries/ for use by the module.

Before I stamp this request as denied, I was curious whether there is a decent method to do this, and if there are any existing modules that already to this (so I can look at them for inspiration).

# Answer
> 2 votes
Views Infinite Scroll provides a Drush command to do it, so I'd start there- it sounds like a pretty simple option!

> Instead of downloading jquery.autopager manually, drush could be used to download the plugin in /js directory or sites/all/libraries if libraries module is enabled.
>
> Drush command: `drush dl-autopager`

The Drush include is here, but this is the important bit:

```
function views_infinite_scroll_drush_autopager_download() {
     if(module_exists('libraries')) {
       $path = 'sites/all/libraries/autopager';

       // Create the path if it does not exist.
       if (!is_dir($path)) {
         drush_op('mkdir', $path);
         drush_log(dt('Directory @path was created', array('@path' => $path)), 'notice');
       }
     }
     else {
       $path = drupal_get_path('module', 'views_infinite_scroll') . '/js';
     }
     drush_op('chdir', $path);
     // Download the plugin.
     if (drush_shell_exec('wget http://jquery-autopager.googlecode.com/files/jquery.autopager-1.0.0.js')) {
       drush_log(dt('jquery.autopager-1.0.0.js has been downloaded to @path', array('@path' => $path)), 'success');
     }
     else {
       drush_log(dt('Drush was unable to download jquery.autopager-1.0.0.js to @path', array('@path' => $path)), 'error');
     }
   }

```

# Answer
> 7 votes
You can use drush make to do this, but that will only work if the person downloading the module is using drush make.

In your modulename.make file:

```
libraries[foolib][download][type] = "get"
libraries[foolib][download][url] = "http://path.to/file/or/tarball.gz

```

This is only advisable if you are grabbing libraries. Adding dependent modules here currently can cause version conflicts (although many modules supply this info via a modulename.make.example file).

---
Tags: theming
---


# Question
Title: Where to check for node value constraints on services data receive
I have a REST service to create nodes. On data receive, `node.create` is executed, but before actually creating the node I need to check some constraints like *node type* and other node values.

Is there any I can use?

# Answer
> 0 votes
To have more control on the node creation you need to write up your own service for nodes using `hook_services_resources()`. By default you can control only the access for creating a particular node using permissions.

If you need to control node creation via node values, you need to go with your own services.

---
Tags: 7, hooks, services
---


# Question
Title: Open a pop-up/modal window after add/edit node to share
I'm using Social Share to generate share links on my nodes but I want the user to be prompted to share after adding and/or editing a node. Is there any possibility of creating a pop-up/modal window that contains those links after the add/edit window has been submitted?

# Answer
without coding, you could setup a message in rules and show it with Better Messages or similar (there is a link to a wiki on the project page) or you could acheive the popup with some coding and the hidden gems of ctools (see the examples in ctools)
> 1 votes

---
Tags: nodes
---


# Question
Title: E_DEPRECATED and E_NOTICE errors showing in dblog / syslog despite disabling in php.ini
I'm still getting a lot of PHP Deprecation and Notice messages in my logs despite having these values turned off in php.ini. According to `admin/config/development/logging` I should only be displaying errors and warning if that is relevant. Is there some other way that Drupal might override my php.ini settings?

# Answer
> 6 votes
In drupal\_environment\_initialize(), Drupal changes the report level with the following code.

```
// Enforce E_ALL, but allow users to set levels not part of E_ALL.
error_reporting(E_ALL | error_reporting());

```

The value of `E_ALL` changes basing on the PHP version, and it is:

```
--------------------------------------------------------------------------------
PHP   | Value expressed using the other constants                              |
-------------------------------------------------------------------------------|
Before| E_WARNING | E_PARSE | E_NOTICE | E_CORE_ERROR | E_CORE_WARNING         |
5.2.x | E_COMPILE_ERROR | E_COMPILE_WARNING | E_USER_ERROR | E_USER_WARNING    |
      | E_USER_NOTICE                                                          |
-------------------------------------------------------------------------------|
5.2.x | E_WARNING | E_PARSE | E_NOTICE | E_CORE_ERROR | E_CORE_WARNING         |
      | E_COMPILE_ERROR | E_COMPILE_WARNING | E_USER_ERROR | E_USER_WARNING    |
      | E_USER_NOTICE | E_RECOVERABLE_ERROR                                    |
-------------------------------------------------------------------------------|
5.3.x | E_WARNING | E_PARSE | E_NOTICE | E_CORE_ERROR | E_CORE_WARNING         |
      | E_COMPILE_ERROR | E_COMPILE_WARNING | E_USER_ERROR | E_USER_WARNING    |
      | E_USER_NOTICE | E_RECOVERABLE_ERROR | E_DEPRECATED | E_USER_DEPRECATED |
-------------------------------------------------------------------------------|
5.4.x | E_WARNING | E_PARSE | E_NOTICE | E_CORE_ERROR | E_CORE_WARNING         |
      | E_COMPILE_ERROR | E_COMPILE_WARNING | E_USER_ERROR | E_USER_WARNING    |
      | E_USER_NOTICE | E_STRICT | E_RECOVERABLE_ERROR | E_DEPRECATED          |
      | E_USER_DEPRECATED                                                      |
--------------------------------------------------------------------------------

```

With all the PHP versions, `error_reporting(E_ALL | error_reporting())` causes any warning to be raised; since PHP 5.3, it causes any deprecation message to be raised too.

`drupal_environment_initialize()` is the only place where Drupal sets the error level. A custom settings.php file could change it with `ini_set('error_reporting')`. Since settings.php is included after `drupal_environment_initialize()` is executed, that file could restrict the error level, or expand it; this means that with PHP 5.3, settings.php could cause `E_STRICT` errors to be raised too.

```
function _drupal_bootstrap_configuration() {
  // Set the Drupal custom error handler.
  set_error_handler('_drupal_error_handler');
  set_exception_handler('_drupal_exception_handler');

  drupal_environment_initialize();
  // Start a page timer:
  timer_start('page');
  // Initialize the configuration, including variables from settings.php.
  drupal_settings_initialize();
}

```

About the error levels, the PHP documentation has the following notes:

> In PHP 5 a new error level `E_STRICT` is available. Prior to PHP 5.4.0 `E_STRICT` was not included within `E_ALL`, so you would have to explicitly enable this kind of error level in PHP \< 5.4.0. Enabling E\_STRICT during development has some benefits. STRICT messages provide suggestions that can help ensure the best interoperability and forward compatibility of your code. These messages may include things such as calling non-static methods statically, defining properties in a compatible class definition while defined in a used trait, and prior to PHP 5.3 some deprecated features would issue `E_STRICT` errors such as assigning objects by reference upon instantiation.

If you are using PHP 5.4, that would explain why Drupal is recording `E_STRICT` errors, since Drupal adds `E_ALL` to the error level.

---
Tags: 7
---


# Question
Title: Is there a way to show the Google Analytics panel inside a drupal site?
I'm using the Google Analytics module to track the visits.

Is there a way to show the Google Analytics panel inside the Drupal site?

# Answer
Google analytics reports Provide you a default report page. You can use the Query hooks to make your own query and show it as a block or panel.

They provide common queries like visits, Top pages viewed etc.
> 0 votes

---
Tags: nodes, google-analytics, log-messages
---


# Question
Title: Dynamic Payment Method required Input Field for Ubercart Checkout
I have a site running with Drupal 7.12 and Ubercart 3.0. I am creating a custom payment module which is used to pay by mobile phone. The workflow is:

1. User enters his mobile phone number in the checkout page
2. When he clicks on "verify phone number" he gets an SMS with a PIN which he has to enter in another input field.

The PIN field is a required field, but only if this specific payment option is chosen.

I know that i can add additional information by returning an instructions array in my callback method, like this:

```
function uc_my_payment_method($op, &$order) {
    switch ($op) {
        case 'cart-details':
            $build['instructions'] = array(
                '#markup' => t('Your mobile phone') . ': ' .
                     /* some markup for the new input fields */
                    '<br />'
            );
            return $build;
    }
}

```

But i am stuck at the form elements. Can you help me? Do you need additional information?

# Answer
It's a bit late but just for reference for anyone finding this page as a search result: From what I found out by experimenting, you are right that you need to return an element. Actually what I had to do in my case was to use the following code:

```
$form = array();
$form['mobile_phone'] = array(
  '#type' => 'textfield',
  '#title' => t('Mobile phone'),
  '#description' => t('Enter your mobile phone number here and a PIN will get sent to you.'),
);
return $form;
```

You just build a normal form and it gets drupal\_rendered when needed.
> 3 votes

---
Tags: 7, forms, ubercart
---


# Question
Title: How to hide field from entity display view programmatically?
I am adding field inside module.install file to specified entity. I want to hide this field from display. How can I do that?

# Answer
> 6 votes
Anyway found solution, example of field instance:

```
field_create_instance(array(
    'field_name' => FIELD_GALLERY_VIEW_FIELD_NAME,
    'entity_type' => 'node',
    'bundle' => 'article',
    'label' => t('Choose gallery View'),
    'description' => t('Gallery view type for display gallery field collection'),
    'widget' => array(
        'type' => 'OPTIONS_SELECT',
        'weight' => 0,
        'settings' => array('size' => 50),
    ),
    'display' => array(
        'default' => array(
            'label' => 'hidden',
            'settings' => array(),
            'weight' => 1,
            'type' => 'hidden'
        ),
        'teaser' => array(
            'label' => 'hidden',
            'settings' => array(),
            'type' => 'hidden',
        ),
    ),
    'required' => TRUE,
));

```

---
Tags: 7, entities
---


title: Auto submit the user registration form

text:
# Question
Title: Auto submit the user registration form
I am customizing the user registration in the template file. I want to auto submit the registration form using Drupal code, or JavaScript code.

Does anyone know how I should achieve this?

# Answer
Based on your question, I would recommend you use the devel module to auto-generate random users.

OR if you really want to auto-submit the user form (or any form) then attach JavaScript to the page that does so via #attached in a hook\_form\_alter or via drupal\_add\_js() or simply in your theme via a .js file included in your .info file.

The javascript would be as Eugene Fidelin has posted above – `$('#user-register-form').submit();`or potentially by extending the Drupal.behaviors object, which is recommended for a number of reasons I won't get into here:

```
(function ($) {

  Drupal.behaviors.myModule = {
    attach: function (context) {
      $('#user-register-form').submit();
    }
  };

})(jQuery);

```
> 1 votes

# Answer
To submit user register form use following code:

```
$('#user-register-form').submit();

```
> 0 votes

---
Tags: forms
---


title: XML Sitemap stopped working

text:
# Question
Title: XML Sitemap stopped working
I don\`t know exactly when but it seems to me after upgrade of some modules and core, sitemap stopped working. Using latest Drupal 7.17 and XML Sitemap 7.x-2.0-rc1

You can see it with some kind of error here http://www.testtest.detect.by/sitemap.xml (Use Firefox to get it displayed)

How could i know what\`s the problem?

Thanks in advance!

# Answer
> 1 votes
Your sitemap seems to work. When viewing the source of your sitemap, the XML needed for crawlers is displayed.

If you're talking about the blank page you get to see when viewing it in your browser: see if you've enabled the "include stylesheet for humans" option in the configuration of the module.

# Answer
> 0 votes
The error Firefox shows is for the sitemap.xsl file.

> XML Parsing Error: not well-formed
> Location: http://www.testtest.detect.by/sitemap.xsl
> Line Number 1, Column 2:
> `<?xml version="1.0" encoding="UTF-8"?>`
> -^

I tried validating the file with the Nu Markup Validation Service, and it shown the following error:

> Fatal Error: required character (found ) (expected `<`)
> At line 1, column 2
>
> `<?xml version=`

The problem is caused by a space before `<?xml version="1.0" encoding="UTF-8"?>`.

The first lines of sitemap.xsl are the following ones.

```
 <?xml version="1.0" encoding="UTF-8"?>

<!-- Copyright (c) 2010  Dave Reid <http://drupal.org/user/53892>

     This file is free software: you may copy, redistribute and/or modify it
     under the terms of the GNU General Public License as published by the
     Free Software Foundation, either version 2 of the License, or (at your
     option) any later version.

     This file is distributed in the hope that it will be useful, but
     WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     General Public License for more details.

     You should have received a copy of the GNU General Public License
     along with this program.  If not, see <http://www.gnu.org/licenses/>.

     This file incorporates work covered by the following copyright and
     permission notice:

     Google Sitmaps Stylesheets (GSStylesheets)
     Project Home: http://sourceforge.net/projects/gstoolbox
     Copyright (c) 2005 Baccou Bonneville SARL (http://www.baccoubonneville.com)
     License http://www.gnu.org/copyleft/lesser.html GNU/LGPL -->

```

That space is not present in the file that is used to create the output for http://www.testtest.detect.by/sitemap.xsl, though.

---
Tags: 7, xml-sitemap
---


# Question
Title: Wrapping a rendered file from Media with a link
This is a question related to How to set Media Styles in Media 7.1.2 / Media 7.2.X?.

I am using Media 1.2 in a Drupal 7 site to add some fields to images (caption, credit, etc).

If I have an image field set up to display as a **Rendered file** with a particular view mode, eg

I have my display set up the way I want to show the proper fields for this view mode. In the file display, eg

is there a way to wrap the image in a link to the media/fid page? I am not seeing how to do this from the UI, and Theme Developer isn't giving me any useful info for which theme functions and preprocess/process functions are being invoked between the one for the whole image field (as far as the content type is concerned) and the image itself (the actual \<img/\> element).

At this point, I do not want to switch to Field Collection, but would entertain switching to Media 2.x if that is my only option.

# Answer
As you mentioned, Media renders fields via Drupal's field display formatter mechanism. Your custom module will work, but there is one for this: Linked Field
> 1 votes

# Answer
OK, here is the working code.

The Media module implements `hook_file_formatter_info()` to set up a callback for rendering images.

As is the Drupal way there is a `hook_file_formatter_info_alter()` to change the default behavior. So, I took the default callback from file\_entity.module and cloned it into a custom module. I then wired this up with the alter. My custom callback has some additional logic to check for an image style, and then wrap the element with a link.

The only real quirk is that the default implementation of `theme_link()` assumes it is a leaf element, so you need to render out the image element first.

As a side note, this is also how you would get alt/title text onto the images, which is missing by default.

```
function MYMODULE_file_formatter_info_alter(&$info) {
  if (!empty($info['file_image'])) {
    $info['file_image']['view callback'] = 'MYMODULE_file_formatter_file_image_view';
  }
}

function MYMODULE_file_formatter_file_image_view($file, $display, $langcode) {
  // Prevent PHP notices when trying to read empty files.
  // @see http://drupal.org/node/681042
  if (!$file->filesize) {
    return;
  }

  // Do not bother proceeding if this file does not have an image mime type.
  if (strpos($file->filemime, 'image/') !== 0) {
    return;
  }

  if (file_entity_file_is_local($file) && $image = image_load($file->uri)) {
    if (!empty($display['settings']['image_style'])) {
      $element = array(
        '#theme' => 'image_style',
        '#style_name' => $display['settings']['image_style'],
        '#path' => $file->uri,
        '#width' => $image->info['width'],
        '#height' => $image->info['height'],
      );
      if ($display['settings']['image_style'] == 'MYSTYLE') {
        $element = array(
          '#theme' => 'link',
          '#text' => drupal_render($element),
          '#path' => 'media/' . $file->fid,
          '#options' => array(
            'attributes' => array(),
            'html' => TRUE,
          ),
        );
      }
      else {
      }
    }
    else {
      $element = array(
        '#theme' => 'image',
        '#path' => $file->uri,
        '#width' => $image->info['width'],
        '#height' => $image->info['height'],
      );
    }
    return $element;
  }
}

```
> 4 votes

---
Tags: theming, media
---


title: Poll module for blogs

text:
# Question
Title: Poll module for blogs
I have a blog that needs a poll attached to it. I've looked at a few modules, but they seem to be buggy.

Any suggestions on a good poll module or methodology?

# Answer
I've been using the Advanced Poll module, and it seems to handle what I need. It lets you display the poll as a block, but doesn't have an option to get rid of the author info. It looks like the best one so far.
> 0 votes

---
Tags: 7, polls
---


# Question
Title: Drupal 7, Rules, Convert text to date and set a date field
I've some string like "11/28/2012" and i want use to populate a date field in my nodes/entity. In rules i use "set a value", select the date field and add php code:

$mydate = field\_get\_items(($entity\_type, $entity, 'field\_textdate');

$value = date('m-d-Y', $mydate);

return $value;

But when i execute the rules, i get 46.397 ms Unable to modify data "node:field-datone": Invalid data value given. Be sure it matches the required data type and format. 57.754 ms Unable to evaluate action data\_set.

How can i do?

# Answer
field\_get\_items() returns an array of items – try `strtotime('m-d-Y', $mydate[0]['value']);`. Also, it looks like you have an extra `(` on your field\_get\_items call:

`field_get_items((`

I would recommend installing the devel module, then you can add this code anywhere you'd like and get the results printed in your messages area for quick debugging and to see what data is available to you and how it's nested:

```
$mydate = field_get_items($entity_type, $entity, 'field_textdate');
dpm($mydate);

```
> 2 votes

---
Tags: rules, datetime
---


# Question
Title: D7 Views 3: Filter by relationship based on nid and uid
I have a content type 'contest' that users submit guesses on. The guesses are entities that have `uid` and `nid` properties (and of course their own primary key, `gid`) to record the user and the contest to which they belong.

How can I display only contests on which a given user has submitted guesses? A similar problem might be how to return only nodes of a certain type that a given user has commented on.

By using this within `hook_views_data` and setting the query to distinct (which I'd also prefer not to have to do) within the Views UI, I was able to confine the results to nodes that have guesses whose `nid` property match - but I can't figure out how to confine the results to nodes with guess entities whose `nid` AND `uid` properties match:

```
$data['node']['nid'] = array(
    'relationship' => array(
        'handler'        => 'views_handler_relationship',
        'base'           => 'entity_guess',
        'base field'     => 'nid',
        'title'          => t('Has guesses'),
        'label'          => t('contests with guesses'),
    ),
);

```

Thanks so much!

# Answer
I ended up achieving the result that I wanted with hook\_views\_query\_alter:

```
function site_views_query_alter (& $view, & $query)
{
  if ('block_3' == $view->current_display) {
    $account        = SiteUser::loadByID(arg(1), TRUE);
    $query->where[] = array(
      'conditions' => array(
        array(
          'field'    => 'node.nid',
          // Return just the IDs
          'value'    => SiteContest::getContestsPlayedBy($account, TRUE),
          'operator' => 'in',
        ),
      ),
      'args'       => array(),
      'type'       => 'AND',
    );
  }
}

```
> 0 votes

---
Tags: 7, views
---


title: No imagecache actions available

text:
# Question
Title: No imagecache actions available
I have imagecache, imageapi and imageapigd enabled on my drupal 6 site. When I visit imagecache presets no actions (crop / resize et al) are available. This all seemed to work fne with the same configuration on my MAMP home box, however, this fails in production. Some other info:

```
PHP Version: 5.2.17
GD Support  enabled
GD Version  bundled (2.0.34 compatible)
FreeType Support    enabled
FreeType Linkage    with freetype
FreeType Version    2.3.11
GIF Read Support    enabled
GIF Create Support  enabled
JPG Support enabled
PNG Support enabled
WBMP Support    enabled
XBM Support enabled

```

I'm stumped - any help is greatly appreciated..

# Answer
> 2 votes
Did you happen to be using one of the latest 6.x-2.x-dev versions of imagecache?

I spent an entire day trying to figure this one out (because unfortunately this was the only relevant page that came up in a google search). Once I finally decided to try the 6.x-2.0-rc1 version, everything seemed to work fine.

---
Tags: 6, media
---


# Question
Title: How to register Field Handler class with Migrate module
I'm trying to use the migrate module to import some video fields. I'm assuming that I'll need to write an extension to the `MigrateFileFieldHandler`. I set up a shell class based on what I saw in the `MigrateImageFieldHandler` (which is a subclass of `MigrateFileFieldHandler`), however my class doesn't seem to get loaded.

My guess is that I need to register my Field Handler somewhere, somehow, but I can't find any instructions or examples anywhere. I know that I register Migrations in the `hook_migrate_api` but I can't find how or where I need to register Field Handlers.

# Answer
From this blog post it looks like you register the field type from within your custom class: http://openconcept.ca/blog/mmallett/migrating-data-using-drupals-migrate-module

as such:

```
class MigrateCUSTOMFIELDNAMEFieldHandler extends MigrateFieldHandler {
  public function __construct() {
    $this->registerTypes(array('email'));
  }
// more stuff in your class ...

```

Without such information migrate usually just silently ignores the field, or try to work with it in any way. The same rule for an improperly named/implemented Migration class -- you just don't see it in `drush ms`.

**EDIT:**

From the blog post, actually from MigrateExtras README:

> The Migrate Extras module provides extensions to Migrate (http://drupal.org/project/migrate) to support various contributed modules. The ideal place to implement migration support for a contributed module is in that module. That way, the migration support is always self-consistent with the current module implementation - it's not practical for the migrate\_extras module to keep up with changes to all other contrib modules. Support for contributed modules may be added to migrate\_extras for two reasons - if the module's maintainer does not accept a patch providing migration support, or as an intermediate step before submitting such a patch to the other module.
>
> In cases where modules supported by migrate\_extras end up implementing the support themselves, you could at least temporarily end up with redundant implementations. The extra implementation may be disabled at admin/content/migrate/configure.

Anyway, if you then look at: http://drupalcode.org/project/migrate\_extras.git/blob/9843c3b2c003e8bd19bb370e6eb6b2264f13eca1:/migrate\_extras.migrate.inc

They declare their migrate API integration thus:

```
/*
 * Implementation of hook_migrate_api().
 */
function migrate_extras_migrate_api() {
  $api = array(
    'api' => 2,
    'destination handlers' => array(
      'MigratePathautoHandler',
      'MigrateExtrasNodeFlagHandler',
      'MigrateExtrasUserFlagHandler',
    ),
    'field handlers' => array(
      'MigrateAddressFieldHandler',
      'MigrateCckPhoneHandler',
      'MigrateGeoFieldHandler',
      'MigrateIntervalFieldHandler',
      'MigrateNameHandler',
      'MigrateMediaFieldHandler',
    )
  );
  return $api;
}

```

You probably want to list your FieldHanlder in a similar fashion (but with your class name). You probably also want to add it to the `files[]` array of your module so it is autoloaded and Migrate sees it.

Your new FieldHanlder should be listed at admin/content/migrate/configure

... if you read the blog post provided, it explains this oddity of FieldHandlers ...
> 1 votes

---
Tags: 7, files, migrations
---


# Question
Title: Can't hide fields in user registration form at new menu path
I have a menu path which rendered User Registration Form. The problem is I did hide fields like "Email", "password" and "status" by setting #access to `FALSE`. It is not working.

When I have done the same thing in `hook_form_alter()`, it does work.

This is my code.

```
/**
 * Implements hook_menu().
 */
function MY_MODULE_menu() {
  $items['admin/author/create'] = array(
    'title' => t('Author'),
    'page callback' => 'MY_MODULE_author_form',
    'type' => MENU_CALLBACK,
    'access callback' => TRUE,
  );

  return $items;
}

/**
 * Author form.
 */
function MY_MODULE_author_form() {
  drupal_set_title('Create Author');

  // Getting User Register Form
  $form = drupal_get_form('user_register_form');

  // Change Username to Author Name
  $form['account']['name']['#title'] = 'Author Name';

  // Exclude User Registeration Elements
  $form['account']['mail']['#access'] = FALSE;
  $form['account']['pass']['#access'] = FALSE;
  $form['account']['status']['#access'] = FALSE;

  // The path to which the form will be submitted.
  $form['#action'] = url('admin/people/create');

  return $form;
}

```

I think I can alter the form in `MY_MODULE_author_form()`.

Is there anything wrong with my code?

# Answer
Follow Drupal's standards and change your hook\_menu:

```
/**
 * Implements hook_menu().
 */
function MY_MODULE_menu() {
  $items['admin/author/create'] = array(
    'title' => t('Author'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('MY_MODULE_author_form'),
    'type' => MENU_CALLBACK,
    'access callback' => TRUE,
  );

  return $items;
}

```
> 0 votes

# Answer
As Mohammad mentioned, you could set `drupal_get_form` as `page callback` in your `hook_menu`.
You would not need to create your own page arguments. You just need to set it to `user_registration_form`. It will render user registration form at your new menu path.

Assuming you have implemented `hook_form_alter`, you can alter user registration form upon the different path.
I think you don't need `$form['#action']`. User registration form will be submitted as usual.

```
/*
 * Implementation of hook_menu()
 */
function MY_MODULE_menu() {
    $items['admin/author/create'] = array(
        'title' => t('Author'),
        'page callback' => 'drupal_get_form',
        'page arguments' => array('user_register_form'),
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM,
        'weight' => 0,
    );
    return $items;
}

/**
 * Implementation of hook_form_alter
 * Override form structure
*/
function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'user_register_form'){
        elseif($_GET['q'] == 'admin/author/create') {
            # user registration form invoked by your new menu path
            # change your fields as your need here
        }
        if($_GET['q'] == 'admin/people/create') {
            # user registraion form when logged in as administrator
            # change your fields as your need here
        }
        elseif($_GET['q'] == 'user/register') {
            # user registration form for anonymous user
            # change your fields as your need here
        }
    }
}

```
> 0 votes

---
Tags: 7, users
---


# Question
Title: Will forcing validation on a node save result in security issues or data integrity loss?
I have a content type containing lots of required and conditional fields. Because it can take a bit of time to properly create these nodes, and not all information will always be available to the end-user, I've implemented the ability for the user to "Save as Draft" while on this node's edit form.

Here's my form alter:

```
function mymodule_form_node_form_alter(&$form, &$form_state) {
  if ($form['#bundle'] == 'content_type') {
    // If node already exists and is not published, show "Draft" markup.
    if (isset($form['#node']->nid) && $form['#node']->status == 0) {
      $form['draft_markup']['#markup'] = '<div id="node-draft">Draft</div>';
    }

    // Add a new validate function to disable error checking on required fields.
    if (empty($form['#validate'])) {
      $form['#validate'] = array();
    }
    array_unshift($form['#validate'], 'mymodule_save_draft_validate');

    // Add 'Save as Draft' button
    $form['actions']['draft'] = array(
      '#type' => 'submit',
      '#class' => 'form-submit',
      '#value' => t('Save as Draft'),
      '#weight' => '0',
      '#submit' => array('mymodule_save_draft_submit'),
    );

    // Change submit button's text.
    $form['actions']['submit']['#value'] = t('Save & Publish');
  }
}

```

Custom validate function – the magic lies in `&drupal_static('form_set_error', NULL, TRUE)`, where TRUE resets the static `form_set_error` variable:

```
function mymodule_save_draft_validate($form, &$form_state) {
  if ($form_state['triggering_element']['#value'] == $form['actions']['draft']['#value']) {
    // Set as unpublished.
    $form_state['values']['status'] = 0;

    // Force validation.
    $errors = &drupal_static('form_set_error', NULL, TRUE);
  } else {
    // Set as published.
    $form_state['values']['status'] = 1;
  }
}

```

Custom submit function – `drupal_get_messages()` stops "required" field errors from displaying when a user saves as draft, while a user doing the normal 'submit' will see the errors:

```
function mymodule_save_draft_submit($form, &$form_state) {
  drupal_get_messages();
  node_form_submit($form, $form_state);
}

```

Outside of obviously missing field data (which I'm not worried about since status = 0 and I can filter to never display unpublished nodes to the public) does anything stand out as dangerous here for a long-term, production site? Maybe the answer is simply "no", but forcing validation via `&drupal_static('form_set_error', NULL, TRUE)` makes me wonder if I'm opening the door to bigger security vulnerabilities. Because fields still run their validation, I am unable to get data to save that shouldn't be saved (i.e. if I try and put PHP code in a number input, the integer "0" is saved into the database - cool). Looking for a bit of peer review here...

# Answer
> 1 votes
Looking at Drupal code, I don't see any possible security flaw; there could be any, depending on the code executed from third-party modules.
For sure, I am expecting many errors raised for form fields that are added to the node edit form and whose content is not validated. None of the modules I know (and which alter the node edit form) validate the user input in the validation, and in the submission handlers they add.

Unconditionally removing any error message is not what I would do. I would rather let the users know when the node they are editing has been already changed from another user, which is the error message returned from node\_validate().

```
  if (isset($node->nid) && (node_last_changed($node->nid) > $node->changed)) {
    form_set_error('changed', t('The content on this page has either been modified by another user, or you have already submitted modifications using this form. As a result, your changes cannot be saved.'));
  }

```

I would also let the users know there is already a translation for a node in a language, which is the error message given from translation\_node\_validate().

```
if (isset($translations[$langcode]) && $translations[$langcode]->nid != $node->nid) {
  form_set_error('language', t('There is already a translation in this language.'));
}

```

Using `drupal_static('form_set_error', NULL, TRUE)` (you could simply use `drupal_static_reset('form_set_error')`), you are resetting all the form errors for any form present in the page. See How do I make form\_set\_error() affect the submitted form only?

If I were to implement that code, I would write it as follows. I don't think that avoiding the validation errors are seen from the users causes anything good.

```
function mymodule_form_node_form_alter(&$form, &$form_state) {
  if ($form['#bundle'] == 'content_type') {
    // If node already exists and is not published, show "Draft" markup.
    if (!empty($form['#node']->nid) && $form['#node']->status == 0) {
      $form['draft_markup']['#markup'] = '<div id="node-draft">Draft</div>';
    }

    // Add 'Save as Draft' button
    $form['actions']['draft'] = array(
      '#type' => 'submit',
      '#class' => 'form-submit',
      '#value' => t('Save as Draft'),
      '#weight' => 0,
      '#validate' => array('mymodule_save_draft_validate'),
      // Change the following line to contain the name of the fields that
      // needs to be validated. As it is, it avoids any form field is validated,
      // when this button is clicked.
      'limit_validation_errors' => array(),
      '#submit' => array('mymodule_save_draft_submit'),
    );

    // Change submit button's text.
    $form['actions']['submit']['#value'] = t('Save & Publish');
  }
}

function mymodule_save_draft_validate($form, &$form_state) {
  $form_state['values']['status'] = 0;
}

function mymodule_save_draft_submit($form, &$form_state) {
  // …
}

```

---
Tags: 7, forms, security
---


# Question
Title: Duplicating Database For Local Development
I've recently started putting some Drupal installations in to source control. Editing modules and the like is pretty easy since they're obviously just text files. I run in to issues with the database though.

My current idea is to run a cron job to pull in database from the live server every night to keep things up to date.

The current method is to just drop the local db and then mysqldump the live one on to my local machine.

I'm pretty sure doing it the way I currently am could cause me to lose things like content types and fields if I make new ones on the local machine and then the 'outdated' live db gets pulled in.

What is the best way to approach this situation?

# Answer
I haven't used this (but read about it today on this site).

Seriously look at the Configuration module. I have used Features and have seen their warts.

Since I'm not using Configuration myself yet, I am using Features + Git to check in the database on every-ish commit.

EDIT:

A small overview of how i'm using Features+Git+Drush. I try to use Features to store my configuration in a Features based module, but many modules still dont fully support code export properly. This becomes problematic. Even when using a custom install profile and hook\_install or hook\_update its a pain to try and create an initial configuration of a module that doesnt support code export properly.

So, try to grab all the configuration using Features. Then I use `drush sql-dump` with a site specific `drushrc.php` that sets a `common` key to basically ignore all cache tables.

Then when I feel I have "captured" most of the Feature into code. I use drush sql-dump to grab a snapshot of the development DB and make a commit of the website.

At some point I have a snapshot to push to a production website. Then I can use Drush from there to keep dev/prod in sync with eachother.

I want to try out Configuration next.
> 0 votes

# Answer
It's important to understand the differences between the data of your site and the structure. You probably don't need all the data (new nodes, user information...) updated every day in your development site, What you need is to upload the new structural changes to your live site once you reach a stable point in your development.

I've been using a combination of git + features to develop my sites and keep them in sync between develop and live enviroments. With Features you can upload the structural changes to your live site without overwriting the database. When you reach a stable point in your development site you prepare a feature with the changes (content type, image style, views... whatever), save it to code and upload to your live site with the source control program.

Then only sometimes, when the content difference really is important I download the database to my local site, usually with drush.
> 2 votes

# Answer
If you have control of both servers you just use drush on a cron from the main server or the testing server. This details how to http://drupal.org/node/670460. It's the reverse process but it should apply. Take the steps put it into a php or .sh file and have cron do it at will.

There's a couple modules that do a similar things but not as nice as drush will. A direct sync from your databases will be heavy but probably faster and without the disk write and reed making it a bit faster especially if your doing it often.
> 0 votes

---
Tags: database, version-control
---