HOWTO: Configure settings using drupal_execute
NB: drupal_execute() cannot be used with install profiles themselves since Drupal is not fully bootstrapped - and forms provided by modules are not available
Do you prefer using code to clicking around with a mouse to configure stuff (you secretly feel superior using code rather than a GUI)? Do you use the same configuration settings on multiple sites and are looking for a faster way to set things up (but feel that an installation profile is overkill)? If you answered yes to either or both of these questions, then this page should be valuable to you.
Note: These examples are somewhat cleaned-up versions of code from the Macro engine component of the Devel module. Please see that module for all available variables.
An easy way to run these snippets is via the execute PHP block that comes with the Devel module.
Some of these examples were generated by using the Devel module's Macro engine.
Blocks
Enable the "Who's online" block at the top of the right sidebar region:
<?php
$block = array(
array(
'module' => 'user',
'delta' => 3,
'weight' => '-10',
'region' => 'right',
),
);
drupal_execute('block_admin_display', $block);
?>// TODO: Create block
// TODO: Set block visibility settings
Forums
Create top container:
<?php
$values = array(
'name' => t('General'),
'description' => t('description'),
);
drupal_execute('forum_form_container', $values);
?>Create a new forum, which will be a child of the previous container:
<?php
$values = array(
'name' => t('Help'),
'description' => t('Get help on using this site'),
);
drupal_execute('forum_form_forum', $values);
?>Now we create the hierarchy:
<?php
$parent = db_result(db_query("SELECT t.tid FROM {term_data} t LEFT JOIN {vocabulary} v ON t.vid = v.vid WHERE t.name = '%s' and v.module = '%s'", t('General'), 'forum'));
$tid = db_result(db_query("SELECT t.tid FROM {term_data} t LEFT JOIN {vocabulary} v ON t.vid = v.vid WHERE t.name = '%s' and v.module = '%s'", t('Help'), 'forum'));
db_query('INSERT INTO {term_hierarchy} (tid, parent) VALUES (%d, %d)', $tid, $parent);
?>Menus
// TODO
Menu items
// TODO
Taxonomy vocabularies
Here is a sample of a script used to create a vocabulary called Pets. All the possible attributes are set. See the chart below the code to see which attributes are required, what kind of values each attribute takes, and a description of what each setting does.
<?php
$values = array(
'name' => t('Pets'),
'nodes' => array('story' => 'story', 'page' => 'page'),
'description' => t('terms in this category might be: dog, cat, turtle,...'),
'help' => t('Select a term that relates to your content.'),
'tags' => 1,
'hierarchy' => 1,
'relations' => 1,
'multiple' => 1,
'required' => 1,
'weight' => -5,
);
drupal_execute('taxonomy_form_vocabulary', $values);
?>
Taxonomy terms
Add the terms Dogs, Cats, and Bunnies to the "Topic" vocabulary:
<?php
$vid = db_result(db_query("SELECT vid FROM {vocabulary} WHERE name = '%s'", t('Topic')));
$terms = array(
t('Cats'),
t('Dogs'),
t('Bunnies'),
);
foreach ($terms as $name) {
drupal_execute('taxonomy_form_term', array('name' => $name), $vid);
}
?>Users and Roles
This example demonstrates adding roles, then using these roles as part of adding a user.
Add the first user called "admin" with the email "admin@example.com" to the new roles "Editor" and "Administrator".
<?php
// Define the required roles, with 'na' being a placeholder for the role id (rid).
$roles = array('Administrator' => 'na', 'Editor' => 'na');
foreach ($roles as $role => $rid) {
$values = array(
'name' => $role,
'op' => 'Add role',
'form_id' => 'user_admin_new_role',
);
drupal_execute($values['form_id'], $values);
// Query the database for the new rid, and replace 'na' with rid.
$roles[$role] = db_result(db_query("SELECT rid FROM {role} WHERE name = '%s'", $role));
}
// Create user, assign roles as appropriate.
$pass = user_password(6);
$name = 'admin';
$mail = 'admin@example.com';
$values = array(
'name' => $name,
'mail' => $mail,
'pass' => $pass,
'init' => $mail,
'roles' => array(
$roles['Editor'] => $roles['Editor'],
$roles['Administrator'] => $roles['Administrator'],
), // replace this array with NULL if you don't want to assign a role.
'status' => 1,
);
user_save(FALSE, $values);
// Print the password to the screen.
drupal_set_message("Initial password for user <em>$name</em> is <strong>$pass</strong>.");
?>Access control
Apply permissions to three roles using slightly different techniques. The three roles are "anonymous" (1), "authenticated" (2) and "Admin" (3)
<?php
// Simple assignment of permissions to role 1 (anonymous).
$values[1] = array(
'access content' => 'access content' ,
'access comments' => 'access comments',
);
// To get more creative, start with a list of all permissions.
$raw_permissions = module_invoke_all('perm');
foreach ($raw_permissions AS $perm) {
// Put array in a format suitable for saving.
$permissions[$perm] = $perm;
}
// Now we can assign all permissions to role 3 (Admin).
$values[3] = $permissions;
// And we can also start by assigning all permissions to role 2 (authenticated)...
$values[2] = $permissions;
// ... but then remove all permissions that have 'admin' in the description.
foreach ($values[2] AS $perm) {
if (stristr($perm, 'admin')) {
$values[2][$perm] = 0; // unset() also works.
}
}
// Finally save the permissions.
drupal_execute('user_admin_perm', $values);
?>| Attachment | Size |
|---|---|
| vocabulary-attributes.png | 48.54 KB |

Changing theme on install
For Drupal 6, here's a drupal_execute code snippet to change theme on install (replace 'theme_name' with the name of your theme, such as 'bluemarine'):
<?phprequire_once(drupal_get_path('module', 'system').'/system.admin.inc');
$form_state = array(
'values' => array(
'status' => array('theme_name' => 'theme_name'),
'theme_default' => 'theme_name',
'op' => 'Save configuration',
),
);
drupal_execute('system_themes_form', $form_state);
?>
The require_once at the beginning is necessary as Drupal 6 has optional file inclusion within modules to make things run faster.
The following also works and is far shorter to write:
variable_set('theme_default', 'theme_name');... however, it only sets a default theme and doesn't actually 'enable' the theme (though it does seem to work all the same). Also, doing things through drupal_execute makes more sense in the long run as then all the code that needs to get run on submitting the form gets run.
Jake
---
School and university yearbooks
A bit of context and more instructions would go a long way...
Note: I'm willing to create the documentation suggestions I'm proposing, let me know if the help is desired.
This page could really use an iintroduction to provide some context. I think this page is suggesting methods, functionality by functionality, that would be helpful in speeding up the configuration of a site, kind of a small scale alternative to an installation profile. Yes? That should be written out.
Presumably these snippets would be run from Devel's php execute block. That should be stated explicitly.
You wrote:
That statement, possibly inadvertently, calls into question the reliability of the Macro engine in the Devel module. What exactly are you saying? A clearer comparison of what these snippets do as compared with the Devel Macro engine would help.
A listing of potential values for variables and what they mean would be very helpful. The devel module's variable list shows available variables and their values, but it doesn't show you what the different values mean. For example, I can infer from the taxonomy vocabularies example above that 'tags' => 1 sets the vocabulary to accept free tags. But where is the reference page that will list what other possible values there are for this setting and what they mean?
I think with some more verbose instructions these methods could be used by people who don't know PHP. I'm willing to help do that. Let me know.
Shai
content2zero.com
Adding fuller example and documentation to go with it
Improving on the script for adding a taxonomy vocabulary, here is a fuller example:
<?php$values = array(
'name' => t('Pets'),
'nodes' => array('story' => 'story', 'page' => 'page'),
'description' => t('terms in this category might be: dog, cat, turtle...'),
'help' => t('Select a term that relates to your content.'),
'tags' => 1,
// the syntax for this line is wrong, please help: 'hierarchy' => array(t('single') => t('single')),
'relations' => 1,
'multiple' => 1,
'required' => 1,
'weight' => -5,
);
drupal_execute('taxonomy_form_vocabulary', $values);
?>
Now here is better documentation on how this script works and what the different values can be, whether the attribute (is that the right word) is required and what it does. This documentation would work much better in a table, but table tags aren't permitted here. Any ideas on how better to present it?
Attribute | possible values | required (yes or no) | description
name | unique text inside of t function | yes | Name of the vocabulary
nodes | content type names inside array | yes | Content types whose nodes can be associated with terms in this vocabulary
description | text inside of t function | No | Used to describe vocabulary. May be used by contrib modules | not used by Drupal core other than to show up on the edit vocabulary page
help | text inside of t function | No | Shows up on node edit pages to give instructions to the user on how to use vocabulary
tags | 1 | no | turns on free tagging for vocabulary
multiple | 1 | no | allows user to select more than one term for this category
relations | 1 | no | turns on ability for related terms for vocabulary
weight | integers between -10 and 10 | no | sets weighting for use on node edit page in ordering vocabularies when more then one vocabulary is used
content2zero.com
Correction for name attribute
Actually, the name for the vocabulary does not have to be unique. Drupal allows two vocabularies to have the same name.content2zero.com
Using drupal_execute to create or add a new user
The above function adds a user using user_save. If you want to use drupal_execute to do this, I've found the following works for me:
<?php$values['name'] = 'test-user';
$values['mail'] = 'testuser@example.com';
// Automatically generate password
$random_password = user_password();
$values['pass']['pass1'] = $random_password;
$values['pass']['pass2'] = $random_password;
$values['roles'] = array(5 => 5); // my member role
$values['notify'] = 1; // So the user gets a welcome message with password
drupal_execute('user_register', $values);
// This is just an example of error handling - you probably want to do this better
if (form_get_errors()) {
echo "Errors encountered!<br />";
print_r(form_get_errors());
}
else {
echo 'Success';
}
?>
In this way you can programmatically create a new user using drupal_execute and not user_save.
Charles
www.parkroad.co.za/blog
Role assignment may be tricky
I was using more or less your technique, but I found that the roles I was trying to assign automatically kept getting tossed, I think because the form was being executed anonymously in my case.
What I wound up doing was also implementing hook_user(), catching the 'insert' op and manually inserting the role there.
For D6?
Anyone up for refactoring this so it covers Drupal 6.x? There aren't many changes. Main one is documented here:
http://drupal.org/node/201739
And I blogged it here in simpler terms:
http://www.drupaler.co.uk/blog/drupalexecute-gotcha-drupal-6x/61
=)
--
http://www.drupaler.co.uk/
Creating a cck node in Drupal 6
Here is some example code to create a cck node in drupal 6 using drupal_execute. The format of the array items for $form_state['values'] can be found by inspecting the html code of your form.
global $user;
$evaluation = array();
$evaluation['type'] = 'hra_evaluation'; //cck node type
$form_state = array();
module_load_include('inc', 'node', 'node.pages');
$form_state['values']['field_evaluation_type']['value'] = $evaluation_type; //normal text field
$form_state['values']['field_employee_reference']['nid']['nid'] = $employee->nid; //node reference
$form_state['values']['field_manager']['uid']['uid'] = $employee->field_manager[0]['uid']; //user reference
$form_state['values']['name'] = $user->name;
$form_state['values']['op'] = t('Save'); //required
drupal_execute('hra_evaluation_node_form', $form_state, (object)$evaluation);
Creating a cck node in Drupal 6
Note that for the node reference and user reference CCK field examples given by diricia to work, the widget type for that field should be set to 'select list' and not 'autocomplete'.
If you prefer to leave it set to autocomplete then you need to pass the name of the referenced field (username or page title) instead of the id of this object, as illustrated in the code.
I found this out the long way.
Here's an example of adding
Here's an example of adding a term to a taxonomy with D6:
<?php
module_load_include('inc', 'taxonomy', 'taxonomy.admin');
// get the vocabulary ID (you could just check what it is in advance as well)
$vid = db_result(db_query("SELECT vid FROM {vocabulary} WHERE name = '%s'", 'MyVocabulary'));
$vocab = taxonomy_vocabulary_load($vid);
$form_state = array();
$form_state['values']['op'] = t('Save');
$form_state['values']['name'] = 'Cats';
drupal_execute('taxonomy_form_term', $form_state, $vocab );
?>
When using drupal_execute() to add roles in hook_install()
Some interesting notes, observations, & a solution to a problem with drupal_execute() not working within hook_install(): http://drupal.org/node/283261