title: How to manage ajax in nested forms?

text:
# Question
Title: How to manage ajax in nested forms?
As implied in this question, I'm adding a list of similar child forms to my parent form with the following code:

```
foreach ($form_state['items'] as $key => $item) {

    $existing = NULL;
    if (isset($form['item_holder'][$key])) {
        $existing = $form['item_holder'][$key];
    }

    $state = NULL;
    if (isset($form_state['item_holder'][$key])) {
        $state = $form_state['item_holder'][$key];
    }

    $el = item_form_edit($existing, $state, $item);

    $form['item_holder'][$key] = $el;
}

```

I am calling the form function directly because drupal\_get\_form() was causing errors due to confusion about which form was being submitted.

My child form type has ajax callbacks that return parts of it $form object. But the child's callback function is receiving the parent form's object and causing an error trying to return parts of the child form.

How do I sort out ajax calls between parent and child $form contexts? Do I need to go back and add the child forms with drupal\_get\_form()? If so, how do I avoid confusing which form has been submitted?

# Answer
> 0 votes
It turns out Drupal will distinguish ajax for subforms automatically if you work within the system - which I was not.

Instead of calling the form builder function directly *(bad)*, I use drupal\_get\_form() so the code above becomes:

```
foreach ($form_state['items'] as $key => $item) {

    $form['item_holder'][$key] = drupal_get_form('item_form_edit', $item);

}

```

I was previously loading the subitem's code with module\_load\_include(). I now load the sub-item's code with form\_load\_include() which should make a cached version of this form load correctly.

Since I am building a list of similar subforms, the subform needs to make sure it gets a unique wrapper:

```
function item_form_edit($form, &$form_state, $edit = NULL) {

    $id_string = 'sub-item-form';
    $unique_id = drupal_html_id($id_string);

    $form['#prefix'] = '<div id="' . $unique_id . '">';
    $form['#suffix'] = '</div>';

    ...

    return $form;
}

```

Now, an AJAX element on the subform can replace that subform with

```
    '#ajax' => array(
        'wrapper' => $unique_id,
        'callback' => 'subform_callback',
        ...

```

In this example, the entire subform is being replaced by the callback:

```
function subform_callback($form, &$form_state) {
    return $form;
}

```

My subform builder function is in a separate file, so hook\_init() needs to make Drupal aware of the subform code during AJAX requests:

```
if ($_GET['q'] == 'system/ajax' || strstr($_GET['q'], 'file/ajax/')) {
    if (preg_match('/item_form_edit/', $_POST['form_id'])) {
        module_load_include('inc', 'mymodule', 'file_with_item_form');
    }
}

```

---
Tags: forms, ajax
---


title: Aegir Drush Drupal 6

text:
# Question
Title: Aegir Drush Drupal 6
I am using the Hosting module through Aegir. I created a module with some extra fields such as "site\_name," "fields," and "description," which was done successfully. I want to use these fields on a newly created website. I am using this code in the new site:

```
function silverpack_config_menu() {
  // Create additional primary menu items
  $items = array(
    array('link_path' => '<front>', 'link_title' => t('Home'), 'weight' => 0),
    array('link_path' => 'node/2', 'link_title' =>t(drush_get_option('site_name')), 'weight' => 6),
    array('link_path' => 'node/3', 'link_title' => t('Contact'), 'weight' => 8),
     array('link_path' => 'node/4', 'link_title' => t('Contact US'), 'weight' => 10),
     array('link_path' => 'node/5', 'link_title' => t('Terms & Conditions'), 'weight' => 10),
     );

  foreach ($items as $item) {
    $item += array(
      'mlid' => 0,
      'module' => 'menu',
      'has_children' => 0,
      'options' => array(
        'attributes' => array(
          'title' => '',
        ),
      ),
      'customized' => 1,
      'original_item' => array(
        'link_title' => '',
        'mlid' => 0,
        'plid' => 0,
        'menu_name' => 'primary-links',
        'weight' => 1,
        'link_path' => '',
        'options' => array(),
        'module' => 'menu',
        'expanded' => 0,
        'hidden' => 0,
        'has_children' => 0,
      ),
      'description' => '',
      'expanded' => 0,
      'parent' => 'primary-links:0',
      'hidden' => 0,
      'plid' => 0,
      'menu_name' => 'primary-links',
    );
    menu_link_save($item);
  }

}

```

Here, I want to use `drush_get_option('site_name')`. "site\_name" is one of the fields I use in Aegir's Hosting module.

Does anybody have an idea on how to do this?

# Answer
I see that you have not returned the `$items` array before exiting `hook_menu`. I assume it is a typo, but just incase it is not, you need to insert `return $items;` before the end of the function.

You need to check whether or not Drupal is able to fetch the value returned by `drush_get_option()`.

Can you check in your hook\_init(), the value of `drush_get_option()`?

Something like the following code should work.

```
function silverpack_config_init(){
  $test_sitename = drush_get_option('site_name');
  dsm($test_sitename);// Install Devel Module to use dsm()
}

```

Clear the cache, and refresh twice to see if you receive anything back from Drupal. If it is not returning anything, that means either "site\_name" is not registered in your database table, or drush is not getting the context properly.
> 0 votes

---
Tags: 6, drush
---


# Question
Title: How do I programatically add a Node to an Organic Group in Drupal 7?
This question and the documentation would suggest that the og\_group function is the way to achieve this; however, calling og\_group thus:

```
$values = array('entity_type' => 'node', 'entity' => $node);
og_group($gid, $values);
node_save($node);

```

Does not update the group\_audience field on the node.

I'm referring to 7.x-1.3 of the og module; currently the only stable release on D7.

How can I go about programmatically adding a node to a group?

Thanks in advance.

# Answer
> 1 votes
I don't think it's likely that the below is the preferred way to do this, however:

```
$node->group_audience[$node->language][] = array(
                                           'gid' => $gid,
                                           'created' => REQUEST_TIME,
                                           'state' => OG_STATE_ACTIVE);
$new_node = node_save($node);

```

Appears to update the node field and create the necessary entries in OG's tables unlike a call to og\_group.

I'm open to a solution more in line with best practices but for now this may work.

# Answer
> 1 votes
Try og\_set\_association() its listed under their API section of og.module

I have done this in the past with D7, but I believe the API I used has changed since then.

# Answer
> 0 votes
No, you use og\_group() and pass $values as the third parameter that define your group content node, basically:

```
$values = array('entity_type' => 'node', 'entity' => $nid);
// Then call og_group telling it about your node.
og_group('group_content', $a_group_gid, $values);

```

The code you mention sets up defaults for og\_group() to work on Users by default, as a convenience, you just tell og\_group() to subsribe nodes of whatever NIDs.

The documentation says:

> $values: Array with the information to pass along, until it is processed in the field handlers.
>
> "entity\_type": Optional; The entity type (e.g. "node" or "user"). Defaults to 'user'
>
> "entity": Optional; The entity object or entity Id to set the association. Defaults to the current user if the $entity\_type property is set to 'user'.
>
> "field\_name": The name of the field, the membership should be registered in. If no value given, a first field with the correct membership type will be used. If no field found, an execpetion will be thrown.

---
Tags: 7, organic-groups
---


# Question
Title: Custom module embedding existing node form
I have the following content types:

* event
* signup

I'm dealing with my\_singnup module, for which I wish to:

1. allow user to add signup content (same as core node/add/signup)
2. using signup/event/%eventid path (it is simple link expose in every event)
3. presenting (while adding) some information from event in left side and node/add/signup form on the right side
4. preventing signup/event without argument to run

The code I have already wrote is the following.

```
function my_singnup_menu() {
   $items = array();
   $items['signup/event'] = array(
     'title' => 'Sorry, no such event.',
     'page callback' => 'There is no event id in path.',
     'type' => MENU_CALLBACK,
     'access callback' => TRUE // for now
   );

   $items['signup/event/%eventid'] = array(
     'title' => 'Signing up for event',
     'title callback' => 'my_signup_title',
     'title arguments' => array(2),
     'page callback' => 'my_singnup',
     'page arguments' => array(2),
     'type' => MENU_CALLBACK,
     'access callback' => TRUE // for now
   );
   return $items;
}

function my_signup_title($node) {
  if ($node->type == 'event') {
  drupal_set_title(t('Signing up for event '.$node->title));
  }
  if ($node->type <> 'event') {
  drupal_set_title(t('Id in path is not event id.'));
  }
  return t('Signing up for event');
}

function my_signup($node = FALSE) {
   if($node) {
     if($node->type == 'event') {
       module_load_include('inc', 'node', 'node.pages'); //Added
       global $user; //Added
       $new_node = new stdClass; //Added
       $new_node->type = 'signup'; //Added - here was bug
       $new_node->language = LANGUAGE_NONE; //localization
       $new_node->user = $user->uid; //Added
       $new_node->name = (isset($user->name) ? $user->name : ''); //Added
       $form = drupal_get_form('signup_node_form', $new_node); //here was my big trouble
       return $form;
     }
   }
   return drupal_not_found();
}

function my_signup_theme($existing, $type, $theme, $path) {
  return array(
    'signup_node_form' => array(
      'render element' => 'form',
      'template' => 'signup-node-form',
      'path' => drupal_get_path('module', 'my_signup'),
    ),
  );
}

```

Right now, I see some form under event/signup/999 (thats good), but there is no custom groups and fields like in core default node/add/signup. I was so happy to see it that I forget to check it looks the same. I see only core vertical tabs such as Menu, Book, Version, Adress, Comments, and there is no custom fields and groups in it. It is strange.

# Answer
> 1 votes
`node_form()` is in node.pages.inc which isn't included by default. Just add a call like this to the beginning of your `my_signup()` function:

```
module_load_include('inc', 'node', 'node.pages');

```

When you call `drupal_get_form()` with a specific type (like `signup_node_form`) the node module internally translates that to `node_form()`. This happens in `node_forms()` which is in the node.module file, and as such is always included.

However node.pages.inc is only included when specifically requested by a module/menu callback etc. so to use `node_form()` you'll need to include the file manually.

You also need to pass a node object to the function with the required content type assigned like the following code:

```
$new_node = new stdClass;
$new_node->type = 'signup';
$new_node->language = LANGUAGE_NONE;
$form = drupal_get_form('signup_node_form', $new_node);

```

---
Tags: 7, forms, routes
---


# Question
Title: Grant temporary permission during function call on registration page
I am geocoding an address supplied by an anon user on the registration page through ajax and then displaying the point on a map for them. I don't want to have this geocoding permission open to anon users though and just want to make an exception for it in my ajax function. I remember seeing something like this on my past Drupal travels but can't find it for the life of me now. Can someone point me in the right direction?

# Answer
> 0 votes
What you want is not possible. Drupal does its best to prevent cross site request forgery, but same site request forgery is not even an established term.

Any candidate for a solution can be circumvented by a script that automates downloading and parsing the registration form, creating the appropriate HTTP request for the AJAX call and sending it to the server.

---
Tags: 7, users
---


# Question
Title: How to insert the node comments form into quicktabs?
Im trying to insert node comments inside the quicktab, I can use views to list the comments and make the tab with it, but how to add the "Add comment" form to it ?

# Answer
Here is a recipe for adding comments to a quicktab: http://www.katbailey.net/blog/go-forth-and-tabbify-quicktabs-30-drupal-7
> 2 votes

---
Tags: 7, views, comments, blocks
---


title: form submission not working

text:
# Question
Title: form submission not working
I am just starting out making my module and already running into 2 problems, I believe this is being cause because the form is in a block but I am not entirely sure. This is what I have in my .module file, as you can see I have the function to output the drupal message upon submission however it simply does not do anything. I also get this error when I have the variables in my function.

```
Notice: Undefined variable: form in zillow_block_view() (line 33

```

and

```
Deprecated function: Call-time pass-by-reference has been deprecated in drupal_load() (line 933 of C:\xampp\htdocs\drupal\includes\bootstrap.inc).

```

function zillow\_block\_info(){ $blocks\['zillow\_block'\] = array( 'info' =\> t('Zillow Block'), ); return $blocks; }

```
function zillow_block_view($delta = ''){
    $block = array();
        switch ($delta){
    case 'zillow_block';
        $block['subject'] = t('Zillow Block');
        $block['content'] = zillow_form($form, &$zinfo);
    break;
    }
    return $block;
}

function zillow_form($form, &$zinfo){

    $form['description'] = array(
        '#type' => 'item',
        '#title' => t('Get your mortgage rates'),
    );
    $form['rates'] = array(
        '#type' => 'fieldset',
        '#title' => t('Mortgage Rates'),
        '#collapsiable' => TRUE,
        '#collapsed' => FALSE,
    );
    $form['rates']['street'] = array(
        '#type' => 'textfield',
        '#title' => t('Street Address'),
        '#default_value' => 'Street Address',
    );
    $form['rates']['city'] = array(
        '#type' => 'textfield',
        '#title' => t('City'),
        '#default_value' => 'City',
    );
    $form['rates']['zip'] = array(
        '#type' => 'textfield',
        '#title' => t('Zip Code'),
        '#required' => TRUE,
        '#default_value' => "Zip Code",
        '#description' => 'Please enter your zip code',
        '#size' => 5,
        '#maxlength' => 5,
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
    );
    return $form;
}

function zillow_submit_info($form, &$zinfo){
        drupal_set_message('this is the info the form has submitted. zipcode=@zipcode',
        array('@zipcode'=>$zinfo['values']['zip']));
    }

```

any help is appreciated.

# Answer
Do not call form builder functions directly. Retrieve the form with

```
$block['content'] = drupal_get_form('zillow_form');

```

drupal\_get\_form() is the entry point into much of the magic that the Forms API does, like building, validating, invoking submit callbacks and (in Drupal 6) rendering. If you do not call it, you have to replicate much of what drupal\_get\_form() does in your own code, which is not a good idea.

Also, as Joe Beuckman noted, the submit callback should be called `zillow_form_submit`.
> 2 votes

# Answer
This line is using the deprecated pass-by-reference:

```
    $block['content'] = zillow_form($form, &$zinfo);

```

You can fix that with no ampersand:

```
    $block['content'] = zillow_form($form, $zinfo);

```

And I think your submit function should be named zillow\_form\_submit instead of zillow\_submit\_info.
> 2 votes

---
Tags: forms
---


title: Re-order file attachments

text:
# Question
Title: Re-order file attachments
I am using tcpdf to generate a PDF. The PDF generation adds images that have been uploaded. The order of the images matters. After I upload files in Drupal 6 using the upload module, Drupal 6 randomly orders the images (or attachments).

The uploaded images are draggable. But when I drag them to re-order and hit save, the order goes back to what Drupal thinks is best.

How can I change this behaviour to let Drupal recognise my re-ordering?

Thanks

# Answer
> 0 votes
It looks like your re-ordering script is buggy. Make sure it saves the state of the ordering. There should be something in your re-ordering script that tracks the order. Make sure it works. This can be fixed if you have access to the re-ordering script.

---
Tags: files
---


# Question
Title: Choose theme depending on the USER_AGENT
How do I use the mobile theme if the `$_SERVER['HTTP_USER_AGENT']` is mobile, and use the desktop theme if it is desktop?

# Answer
I would suggest you to use browsecap module to detect what browser users use and switchtheme module to switch to correct theme depending on the browser they use.
> 3 votes

# Answer
The mobile tools module also integrates with the browscap module as well as the wufrl module, though I recommend starting with browscap instead of wufrl. Wufrl is more complicated to set up and also not open source anymore.

Mobile tools gives you some handy options like choosing different themes for iPhone vs. Android vs Nokia, Panels module integration, special (optional) permissions for mobile users, and other options. You can also force mobile users to use the mobile theme or let them choose between mobile and desktop a la the switchtheme module.
> 3 votes

---
Tags: 6
---


# Question
Title: How would I wrap (or hard-code) HTML into a block title?
So I see this in the `block.tpl.php`:

```
/**
* @file
* Default theme implementation to display a block.
*
* Available variables:
* - $block->subject: Block title.
* - $content: Block content.
* - $block->module: Module that generated the block.
* - $block->delta: An ID for the block, unique within each module.
* - $block->region: The block region embedding the current block.
* - $classes: String of classes that can be used to style contextually through
*   CSS. It can be manipulated through the variable $classes_array from
*   preprocess functions. The default values can be one or more of the
*   following:
*   - block: The current template type, i.e., "theming hook".
*   - block-[module]: The module generating the block. For example, the user
*     module is responsible for handling the default user navigation block. In
*     that case the class would be 'block-user'.
* - $title_prefix (array): An array containing additional output populated by
*   modules, intended to be displayed in front of the main title tag that
*   appears in the template.
* - $title_suffix (array): An array containing additional output populated by
*   modules, intended to be displayed after the main title tag that appears in
*   the template.
*

```

I'm trying to set the `$title_prefix` & `$title_suffix` in my `hook_block_view` without much luck...

Here is the working version of what I have:

```
/**
* Implements hook_block_view().
*/
function activities_block_view($delta = '') {
 switch ($delta) {
   case 'find_activities_small':
     $block['subject'] = t('Find Activities');
     $block['content'] = drupal_get_form('find_activities_form');
     return $block;
     break;
 }
}

```

# Answer
Core (modules/block/block.tpl.php) and other themes I checked output the title\_prefix with:

```
<?php print render($title_prefix); ?>

```

Therefore, the format of $title\_prefix is any renderable array. You can override theme\_preprocess\_block() function in template.php to supply values. For example,

```
function mytheme_preprocess_block(&$variables) {
  $variables['title_prefix'] = array(
    '#type' => 'markup',
    '#markup' => '<span>My title prefix</span>',
  );
}

```
> 2 votes

# Answer
1. You can hard code in block template: "Drupal 7 Template Suggestions", so determine what module/delta/region appropriate for you.
2. Other way is using theme preprocessor.
> 3 votes

# Answer
Why insert more html when you can simply use css with a class insert through the Block Class module? Here is an excerpt about it from the module's project page:

> ... allows users to add classes to any block through the block's configuration interface. By adding a very short snippet of PHP to a theme's block.tpl.php file, classes can be added to the parent `<div class="block ...">` element of a block. Hooray for more powerful block theming!
> 0 votes

---
Tags: blocks, theming
---


# Question
Title: How to display one block among two block in Drupal?
I have two block (like Block1 and Block2) and I have to display one block among two. Condition is Block1 will be display into the whole site if Block2 is not present there. Block2 will be displayed into specific pages which is controlled dynamically, i.e. when user create content in future they can control the Block2 display. So I need to display Block1 where Block2 is not present.

I am using Durpal 7.

Note: I have tried with default block visibility but this is not worked for me either.

# Answer
This sounds like you're going to need to use something like Context to toggle the display of each of the two blocks depending on the context of the page.

See this tutorial for more info on how that works.
> 1 votes

# Answer
Assuming you want these blocks displayed in the same place on your page and you are creating these blocks yourself in a module, eg, they aren't somehow standard blocks from one or more other modules, you could do all of this in the display logic of one block:

```
if ( the user is on a path/page that the content of block2 should be displayed ) &&
   ( the user has created whatever content you mentioned ) {
      $content=what should be in block 2;
} else {
  $content=what should be in block 1;
}

```

That's pseudo code obviously as I don't know what paths you need to check against (eg, $\_GET\['q'\]) for block 2, nor do I know what you need to check against viz the future content you mentioned that will allow block 2 to be finally displayed, let alone what html (or renderable array that will eventually be rendered) you want in either of the blocks.

Regardless, all of the above would be put in the block\_view() hook of your module along with a corresponding block\_info() hook.

Now, if they are somehow standard blocks from another module, you could hack around with $block = module\_invoke('other\_module', 'block\_view', 'other\_modules\_block\_name\_or\_delta'); and then setting your $content appropriately.
> 0 votes

---
Tags: 7, blocks
---


# Question
Title: Domain administrator role that can only see users of that domain
Is it possible to define a "Domain Administrator" that would only be able to see the users (in the People interface) assigned to the same domain as itself? I've got a few Domain Access modules installed, but I still can't seem to figure this out.

# Answer
Have you tried the Domain Admin module? Looks like there's a bit of stuff in there. It's a shame that a few of the features listed are currently missing for Drupal 7 though.

> Domain Admin adds more granular permissions to the Domain Access module and several of its sub-modules.
>
> Currently the module allows the site admin to delegate the following tasks:
>
> * Access the domain overview page - delegated user will only be able to see the domains assigned to him/her (not there in D7 yet)
> * Editing of domain record, domain settings and domain theme
> * Administer primary and secondary menus (also navigation in D6)
> * Translate interface into the domain language (wont be ported to D7 - use i10n\_client instead)
> * View, edit and delete all unpublished/own unpublished nodes on domain (needs to be tested in D7)
> * Administer book outline/ rearrange child pages of nodes on domain (requires book module)
> * View webform results on domain (requires webform module)
> 1 votes

---
Tags: users, domain-access
---


# Question
Title: FileField Permissions- How can I allow users to upload a file without giving them the ability to remove files that have been uploaded?
I want to be able to upload a file into an article but without the ability to remove other files uploaded from other users to the same article.

Is it possible?

I tried the Field Permissions module; I can edit, but I cannot upload.

# Answer
> 0 votes
Try to add a second file field via the field UI; to set the permissions for a single field you could use hook\_field\_access().

---
Tags: entities, users, files
---


# Question
Title: Best way to break up node edit forms smaller, more manageable forms?
It's pretty common to end up with massive node edit forms once content types start accumulating fields. Collapsable fieldsets and vertical tabs help the UI, but it can still be overwhelming.

**Example**: Say I have a local business site, and it involves a content type called 'business' which has lots of fields. One very significant field is the business's location. Rather than having location as just another fieldset in the large node edit screen, I'd like to break out the location-related items (address fields, google map, etc.) into a separate editing screen.

Multi-step forms are not ideal in this case. Is there a straightforward way to break a single node edit form into distinct forms?

# Answer
I use the field group module to simplify things. This allows you to easily make collapsible groups of collapsible field sets, use horizontal and other types of tabs, and split a single form into multiple pages.

With the field group module, you can also easily add a css class to any group of fields, which makes it straightforward to theme that specific field (change the background color, increase text size, etc.) for emphasis.
> 2 votes

# Answer
You could also do your custom module hooking the node form, and arranging it based on permissions or something.
> 0 votes

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


title: Migrating Content Fields in Drupal 7

text:
# Question
Title: Migrating Content Fields in Drupal 7
I have quite a few content types, and when I set it up I didn't think ahead and created an image field for each content type rather than one image field type. Is there a way to add a common image field type and mass-convert the content types to use that one field? Or do I have to manually migrate all of the currently populated fields?

# Answer
> 1 votes
The Migrate module will help you to export all your image fields, and import them into one unified field; then, you can delete your obsolete fields.

---
Tags: entities, nodes
---


title: hooks call order and hooks dependency

text:
# Question
Title: hooks call order and hooks dependency
I try to implement `hook_menu()` in a module and the code inside of this hook depends on another hook implemented in the same module Example:

```
function mymodule_menu() {
   $streamwrapper = file_stream_wrapper_get_instance_by_scheme('myscheme');
   if($streamwrapper !== false) {
      $directory = $streamwrapper->getDirectoryPath();
       .....
   }
}

```

and another hook function in the same (mymodule) module

```
function mymodule_stream_wrappers() {
  retunr array( 'myscheme' => array(...)
}

```

Apparently, `hook_stream_wrappers()` is called after `hook_menu()`, and `file_stream_wrapper_get_instance_by_scheme()` returns `false` during module installation process.

So, the whole idea works because Drupla will call `hook_menu` eventually and by that time stream wrapper will be in place and ready, but it seems too unreliable, IMHO.

Anyway, **is it possible to control hooks order somehow**? Or is there a better way to achieve desired result - retrieve stream wrapper in hook\_menu after is has been known by the system?

# Answer
Your problem is actually the opposite of what you're thinking. A call to `file_stream_wrapper_get_instance_by_scheme` triggers hook\_stream\_wrappers() if it hasn't been called already.

However, the problem is that the stream wrapper hook *was* already called before your module was enabled and the information from that is statically cached. So you need to clear the static cache to get your own stream wrapper:

```
drupal_static_reset('file_get_stream_wrappers');

```
> 3 votes

# Answer
According the documentation, the function `file_stream_wrapper_get_instance_by_scheme` call another function that call the hook `hook_stream_wrappers`.

Logically your code should work.

I see here that you've a mistake in your `return`

```
function mymodule_stream_wrappers() {
  retunr array( 'myscheme' => array(...)
}

```

it may the cause of your problem.
> 0 votes

---
Tags: routes, hooks, stream-wrappers
---


title: Creating line items in Ubercart 3

text:
# Question
Title: Creating line items in Ubercart 3
I have to build a module to add custom charges along with the order, e.g., gift wrapping charges.

I am using Drupal 7.

# Answer
I've done exactly this before; I'll dump the code I used. Hopefully, it'll give you an idea.

```
/**
 * Implements hook_menu().
 */
function uc_giftwrap_menu() {
  $items['admin/store/settings/giftwrap'] = array(
    'title' => 'Gift Wrapping',
    'access arguments' => array('administer gift wrap'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('uc_giftwrap_admin_form')
  );

  return $items;
}

/**
 * Implements hook_permission().
 */
function uc_giftwrap_permission() {
  return array(
    'administer gift wrap' => array(
      'title' => 'Administer Gift Wrap Settings'
    )
  );
}

/**
 * Form builder for the gift wrap settings.
 */
function uc_giftwrap_admin_form($form, &$form_state) {
  $form['uc_giftwrap_cost'] = array(
    '#type' => 'textfield',
    '#title' => t('Gift Wrap Cost'),
    '#description' => t('Total cost of gift wrapping for an order.'),
    '#default_value' => round(variable_get('uc_giftwrap_cost', '0.00'), 2),
    '#field_prefix' => '£',
    '#size' => 10
  );

  return system_settings_form($form);
}

/**
 * Implements hook_uc_checkout_pane().
 */
function uc_giftwrap_uc_checkout_pane() {
  $panes['gift_wrap'] = array(
    'callback' => 'uc_giftwrap_uc_checkout_pane_callback',
    'title' => 'Gift Wrapping',
    'desc' => 'Provide gift wrapping options for the checkout.',
    'weight' => 5
  );

  return $panes;
}

/**
 * Callback for the checkout pane.
 */
function uc_giftwrap_uc_checkout_pane_callback($op, $order, $form = NULL, &$form_state = NULL) {
  if ($op == 'view') {
    $description = t('Please check this box if you wish your order to be gift wrapped.');

    $contents['gift_wrap'] = array(
      '#type' => 'checkbox',
      '#title' => t('Add Gift Wrapping') . ' (' . uc_currency_format(variable_get('uc_giftwrap_cost', 0)) . ')',
      '#default_value' => isset($_SESSION['uc_giftwrap_checkout']) ? 1 : 0,
      '#ajax' => array(
        'callback' => 'uc_giftwrap_update_line_items',
        'effect' => 'slide'
      )
    );

    return array('description' => $description, 'contents' => $contents);
  }
  else if ($op == 'process') {
    if ($form_state['values']['panes']['gift_wrap']['gift_wrap'] == 1) {
      if (!isset($_SESSION['uc_giftwrap_checkout'])) {
        uc_order_line_item_add($order->order_id, 'gift_wrap', 'Gift Wrapping', variable_get('uc_giftwrap_cost', 0));
        $id = db_query('SELECT MAX(line_item_id) FROM {uc_order_line_items}')->fetchField();
        $_SESSION['uc_giftwrap_checkout'] = $id;
      }
    }
    else {
      if (isset($_SESSION['uc_giftwrap_checkout'])) {
        uc_order_delete_line_item($_SESSION['uc_giftwrap_checkout']);
        unset($_SESSION['uc_giftwrap_checkout']);
      }
    }
  }
}

/**
 * AJAX callback for the checkout form (allows instant updating of total when gift wrap option is chosen).
 */
function uc_giftwrap_update_line_items($form, $form_state) {
  $commands = array();
  if (isset($form['panes']['payment']['line_items'])) {
    $commands[] = ajax_command_replace('#line-items-div', drupal_render($form['panes']['payment']['line_items']));
    $commands[] = ajax_command_prepend('#line-items-div', theme('status_messages'));
  }

  return array('#type' => 'ajax', '#commands' => $commands);
}

/**
 * Implements hook_uc_line_item().
 */
function uc_giftwrap_uc_line_item() {
  $items[] = array(
    'id' => 'gift_wrap',
    'title' => t('Gift Wrapping'),
    'weight' => 2,
    'default' => FALSE,
    'stored' => TRUE,
    'add_list' => TRUE,
    'calculated' => TRUE,
    'callback' => 'uc_giftwrap_uc_line_item_gift_wrap',
    'display_only' => FALSE
  );

  return $items;
}

/**
 * Callback for line item type.
 */
function uc_giftwrap_uc_line_item_gift_wrap($op, $arg1) {
  // Required callback for hook_uc_line_item()
}

/**
 * Implements hook_uc_checkout_complete().
 */
function uc_giftwrap_uc_checkout_complete($order, $account) {
  if (isset($_SESSION['uc_giftwrap_checkout'])) {
    unset($_SESSION['uc_giftwrap_checkout']);
  }
}

```
> 6 votes

---
Tags: ubercart
---


# Question
Title: Why this callback doesn't show all node form?
This question is related to: Custom module embedding existing node form

After dealing with returning existing node form via custom module (my\_singnup module achieved with the big help of Clive) returning form has no custom field groups and custom fields.

```
function my_signup($node = FALSE) {
   if($node) {
     if($node->type == 'event') {
       module_load_include('inc', 'node', 'node.pages');
       global $user;
       $new_node = new stdClass;
       $new_node->type = 'signup_node_form';
       $new_node->language = LANGUAGE_NONE;
       $new_node->user = $user->uid;
       $new_node->name = (isset($user->name) ? $user->name : '');
       $form = drupal_get_form('signup_node_form', $new_node);
       return $form;
     }
   }
   return drupal_not_found();
}

```

signup\_node\_form was build via field UI (create new content type) and looks great when core node/add/signup. It has vertical tabs, validation etc.

I was expecting to get the same with mentioned code. Unfortunately it's not working. I'm getting just Drupal stuff vertical tab (Menu, Book, Version, Adress, Comments...) without my custom groups and fields.

# Answer
The following line in your code is wrong.

```
$new_node->type = 'signup_node_form'

```

What you are setting as node type is really the form ID, not the content type ID. If you look at the code of node\_add(), you will notice the executed code is the following one.

```
  $types = node_type_get_types();
  $node = (object) array(
    'uid' => $user->uid,
    'name' => (isset($user->name) ? $user->name : ''),
    'type' => $type,
    'language' => LANGUAGE_NONE,
  );
  drupal_set_title(t('Create @name', array('@name' => $types[$type]->name)), PASS_THROUGH);
  $output = drupal_get_form($type . '_node_form', $node);

```

`$type` is the parameter the function gets.
If you look at the content type IDs used in Drupal, none of them contains the string "\_node\_form"; differently, `node_add()` would call `drupal_get_form()` passing something similar to "story\_node\_form\_node\_form" as form ID. As the modules that add fields to the node edit form check the content type of the node, it is probable they don't add fields for a content type they don't know. That is plausible, as differently it would mean that a taxonomy term field, for example, would be added to nodes for which it was not supposed to be added.
> 1 votes

---
Tags: 7, forms, routes
---


title: drupal_goto overlay page

text:
# Question
Title: drupal_goto overlay page
I'm using drupal\_goto to redirect users on login. Administrators and 'other' are redirected to the dashboard. All works fine but I want to redirect to the dashboard in an administrative overlay. (Path = #overlay=nl/admin/dashboard)
Chrome and Firefox alter the # to %23 so I get a page not found error.

Can this be done?

Here is the function:

```
/**
 * Implements hook_user_login().
 */
function myModule_user_login(&$edit, $account) {
  $user_roles = array_intersect(array('other', 'administrator'), array_values($account->roles));
  if (!empty($user_roles)) {
    drupal_goto('admin/dashboard');
  } else {
    drupal_goto('');
  }
}

```

# Answer
You need to pass a `fragment` to `drupal_goto()` as an option like so:

```
$options = array('fragment' => 'nl/admin/overlay');
drupal_goto('some-url', $options);

```

Reference for this can be found on the `url()` docs page (the docs page for `drupal_goto()` actually refers you to there as well).
> 2 votes

---
Tags: 7, users
---


# Question
Title: Ajax drop down list problem with callback
I need a little help here. In a custom module, I add a little form where you type your zip code, press a button and a drop down list populates (via ajax) with the stores that are close to that zip code so you can choose one of them. The problem is when you click on that button the callback is made but the zip code field remains empty, seems like I missing something that can bring the zipcode value to that part when the refreshes. some ideas?? thank you

```
    function mymodule_form($form, &$form_state) {

       $form['zip_code'] = array(
        '#type' => 'textfield',
        '#title' => 'zip code',
        '#size' => 5,
        '#maxlength' => 5,
        '#required' => TRUE
      );

      $form['button'] = array(
        '#type' => 'button',
        '#value' => 'find stores',
        "#limit_validation_errors" => array(),
        "#name" => 'mybutton',
        '#ajax' => array(
          'callback' => 'reload',
          'wrapper' => 'stores-div',
          'method' => 'replace',
          'effect' => 'fade'
        )
      );
      $form['select_str'] = array(
        '#prefix' => '<div id="stores-div">',
        '#suffix' => '</div>'
      );
      if(isset($form_state['values']['zip_code'])) {
        $arr = find_store($form_state['values']['zip_code']); //here is my main problem, $form_state['values']['zip_code']is always empty even after the callback
      } else {
        $arr[99999] = 'theres none';
      }
      $form['select_str']['stores'] = array(
        '#type' => 'select',
        '#title' => 'stores near you:',
        '#options' => $arr,
        '#required' => TRUE
      );
      $form['submit_button'] = array(
        '#type' => 'submit',
        '#value' => t('Send!'),
      );
      return $form;
    }
    function find_store($zc) {
        $fields = array(
                'zc'=>urlencode($zc),
            );
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,"http://somepage.php");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
        $result=curl_exec ($ch);
        curl_close($ch);
        $arr = array();
        if($result!='none') {
            $explode=explode(',',$result);
            foreach($explode as $value) {
                $stores = explode('|',$value);
                $arr[$stores[0]] = $stores[1];

        }

    } else {
        $arr[99999] ='theres none';
    }
    return $arr;

}
function reload($form, &$form_state) {
  return $form['select_str'];
}

```

# Answer
> -1 votes
The values will be passed to the callback function `reload` instead of the original form function, therefore you should rebuild the form in your callback function - `reload` and pass back the element:

```
function reload($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
  $form = drupal_rebuild_form('mymodule_form', $form_state, $form);
  return $form['select_str'];
}

```

---
Tags: ajax
---


# Question
Title: Having problems with file_copy in Drupal 7
In my particular situation I am trying to use Drupal's API to import a bunch of files from my computer into a local Drupal installation. Seems like a smart idea. So I have the following function:

```
  function create_picture_file($filepath, $public_place) {
    global $pic_basepath;
    $filepath = "$pic_basepath/$filepath";
    $file = new stdClass();
    $file->filename = basename($filepath);
    $file->filepath = $filepath;
    $file->filemime = file_get_mimetype($filepath);
    $file->filesize = filesize($filepath);
    $file->uid = 1;
    $file->status = FILE_STATUS_PERMANENT;
    $file->uri = $filepath;
    $file->display = 1;
    $file->description = '';
    print_r($file);
    $file = file_copy($file,"public://$public_place",FILE_EXISTS_REPLACE);
    print_r($file);
    return $file;
  }

```

You'll notice the two `print_r` statements towards the bottom. The first one prints the following:

```
stdClass Object
(
    [filename] => Arctic_HE0302_Central_bathy.jpg
    [filepath] => /home/lpeabody/unclos_data/pics/Arctic_HE0302_Central_bathy.jpg
    [filemime] => image/jpeg
    [filesize] => 516130
    [uid] => 1
    [status] => 1
    [uri] => /home/lpeabody/unclos_data/pics/Arctic_HE0302_Central_bathy.jpg
    [display] => 1
    [description] =>
)

```

Which looks good. The second one, however, print's absolutely nothing. Any pointers or tips as to what I'm doing wrong maybe?

**UPDATE** So the public file directory to which this image is being saved in is `region_images`. When this directory exists, nothing get's printed by the second `print_r` statement. When I remove the directory and all of it's associated style directories, the second `print_r` statement prints. However, it prints the following:

```
stdClass Object
(
    [filename] => region_images
    [filepath] => /home/lpeabody/unclos_data/pics/Arctic_HE0302_Central_bathy.jpg
    [filemime] => image/jpeg
    [filesize] => 516130
    [uid] => 1
    [status] => 1
    [uri] => public://region_images
    [display] => 1
    [description] =>
    [fid] => 2595
    [timestamp] => 1331828075
)

```

Which is wrong, as `[filename]` should be `Arctic_HE0302_Central_bathy.jpg`. Hopefully this can help shed some light on the situation.

# Answer
> 1 votes
Use `"public://$public_place/$file->filename"` as `$destination` parameter for `file_copy()`.

---
Tags: 7, files, debugging
---


# Question
Title: How to assign uid in "users" table with imported users?
I am using Drupal 7.

I am using the Migrate module to migrate a list of users from an external user database table into the Drupal "users" table. The problem is that the Drupal "users" table has a numerical "uid" field, which does not exist in my external database users table.

Could someone please tell me of a way to assign a unique uid to the users table everytime I map a row using Migrate?

For example, right now I have, in the "users" database:

```
0
1 root ...
//external users start here
2 user1 ...
3 user2 ...
4 user3 ...

```

Essentially I have would like to start at 2 and continue for each user I migrate over to the "users" table.

More specifically, how I would modify/add a line to the following so that the code can auto generate unique ID's starting from 2? Would the following code be a viable option? If so, where would be the appropriate place to update $counter?

```
$counter = 2;
$this->addFieldMapping('uid', '$counter');

```

Thanks.

EDIT:

If I were to use the following SQL statement to do the user migration, would it be a good idea? If it is also a viable option, how might be able to create unique "uid" for insertion into the "users" table?

```
INSERT INTO users (uid, name, mail,pass,...) SELECT uid, oldusername, email, md5(clear_password),... FROM old_users_table;

```

Thanks.

# Answer
Inserting data directly into Drupal tables is generally a bad idea (until you are familiar enough with the database schema to know what you're doing). For programmatically inserting users there are functions like user\_save() and drupal\_form\_submit() that you can use.

As for generating the unique `uid`: if you can't just provide incremental values in the data insertion loop then you might be able to use the following code instead (copied from user\_save() function):

```
$account->uid = db_next_id(db_query('SELECT MAX(uid) FROM {users}')->fetchField());

```

I'm not familiar with the Migrate module so I don't have more specific advice to offer currently, but the above info and links should be helpful.
> 2 votes

---
Tags: users, migrations, entities
---


# Question
Title: How to automatically generate a random url for a views rss feed?
I have an administrative RSS feed generated by views in a feature that needs to generate a random/unique URL so that non-admins can't easily stumble upon it. I know that after installing the feature, the user can easily manually create the URL, but this will override the feature and put it in the DB, making updates troublesome. Thoughts?

# Answer
> 1 votes
Just configure the menu path for the page/feed display of your view to include a "random" token. You can set them to be whatever you want.

Users will require the token to trigger the menu item and therefore view. You can rotate the token by simply updating the view (though it's a manual process).

If you need to automate rotating the token, you could build a module that hook\_menu\_alter's access callbacks (yourmodule\_access) onto the desired paths that checks the token (variable\_get) that a hook\_cron periodically updates (variable\_set) and mails out to appropriate admins (users with some role). This has added benefit that it's not limited to use with Views. Though that's a bit complex for providing obscurity.

Also, many RSS readers support HTTP basic auth (via adding username:password@hostname to the feed URL), so you could install a contrib module that adds support for logging in via HTTP Basic.

---
Tags: 7, views, feeds
---


title: Link for switch language

text:
# Question
Title: Link for switch language
How do I make a link to switch the language, without using any modules? When users click on a language I want to switch language and redirect them to the same page not to front page.

# Answer
> 2 votes
I assume you are already using the Internationalization (i18n) module. i18n provides the Language Switcher block, which contains links to switch among all enabled languages. When the user chooses one of the links in it, he is redirected to the corresponding page rendered in the newly-selected language.

Note that the block is only shown if at least two languages are enabled and language negotiation is set to something other than None.

---
Tags: 6, i18n-l10n
---


title: Form timing out with drupal_set_message

text:
# Question
Title: Form timing out with drupal_set_message
I am getting some type of timing out error and not sure how to fix it or even where to begin, the error looks something like this http://pastebin.com/M8Wz4KEY

```
/**
 * Block info
 */

function zillow_block_info(){
    $blocks['zillow_block'] = array(
        'info' => t('Zillow Block'),
    );
    return $blocks;
}

function zillow_block_view($delta = ''){
    $block = array();
        switch ($delta){
    case 'zillow_block';
        $block['subject'] = t('Zillow Block');
        $block['content'] = drupal_get_form('zillow_form');
    break;
    }
    return $block;
}

/**
 * Form Info
 */

function zillow_form($form, &$zinfo){

    $form['description'] = array(
        '#type' => 'item',
        '#title' => t('Get your mortgage rates'),
    );
    $form['rates'] = array(
        '#type' => 'fieldset',
        '#title' => t('Mortgage Rates'),
        '#collapsiable' => TRUE,
        '#collapsed' => FALSE,
    );

    $form['rates']['state'] = array(
        '#type' => ('select'),
        '#title' => t('Choose One'),
        '#options' => array(
            'CA' => t('California'),
        ),
        '#required' => TRUE

    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
    );
    return $form;
}

/**
 * Api info
 */

function zillow_api_info($form, &$zinfo){
    $state_value = $zinfo['values']['state'];
    $zillow_id = 'Xx-xxxxxxxx-xxxxxx';
    $xml = file_get_contents('http://www.zillow.com/webservice/GetRateSummary.htm?zws-id='.$zillow_id.'&'.$state_value.'');

    foreach($xml->response->today->rate as $todays_rates){
        print $todays_rates;
        '</br>';
    }

    foreach($xml->response->lastWeek->rate as $lastWeeks_rates){
        print $lastWeeks_rates;
        '</br>';
    }

    return zillow_api_info();
}

/**
 * Submit Info
 */

function zillow_form_submit($form, &$zinfo){
        drupal_set_message(t('this is the info the form has submitted. zip=@zipcode, states=@states, todaysrates=@todaysrates',
        array('@states' => $zinfo['values']['state'], '@todaysrates' => zillow_api_info())));
    }

```

# Answer
> 1 votes
There's an infinite loop in your code...

The function `zillow_api_info()` returns a call to itself, which will result in an infinite recursion from which PHP can't escape. As you're calling this function during the call to `drupal_set_message()` I'd guess that's why you're getting the timeout.

FYI You're not passing the `@zipcode` replacement to the `t()` function, it shouldn't cause an error but it might be a bug :)

---
Tags: 7, forms
---


# Question
Title: How to compare date from table with variable using db_query?
I am trying to retrieve all records from a specific date, given the variable `$date`. I am using db\_select and -\>condition (due to a lot of joins).

I like to do something like:

```
->condition("`tableName`.`field_date_value` )", $date)

```

That doesn't return anything. Perhaps due to different time because `field_date_value` has a time set and $date hasn't. I looked into using a SQL functions like `DATEDIFF`, but it doesn't work for me.

How do I do this?

# Answer
You are going to need to insure that the format of your `$date` variable is formatted exactly the same as the format of the date value in your database (`field_date_value`). For example, if your database is storing its date values in `unixtime`, then your `$date` variable needs to be unixtime. If your `field_date_value` field is storing `mm:dd:yy hh:mm:ss`, then your `$date` variable needs to reflect this same format accordingly. Refer to `date()` to formate your `$date` variable the appropriate way.

Once you've formatted your `$date` variable to the same formate of your sql data, you can run a condition method like this:

```
->condition("tablename.field_date_value", $date, ">=")

```

This will query for everything equal to or greater than the specified `$date` value.
> 2 votes

# Answer
Depending on how your `$date` variable is set, you might want to try MySQL function curdate(). It returns only the date of a datetime column which can then be compared.
> 0 votes

---
Tags: database
---


title: Page view printed in a block

text:
# Question
Title: Page view printed in a block
I have created a page view, and I want to put in a block. I am not looking for a block view.

# Answer
> 1 votes
Try using the panels module. Although it will require some learning, you can use the Panels module to "override" the way nodes are displayed (you can choose from all nodes or overriding specific content types, specific user roles, etc.)

Using this approach, you can make a "page" view display as a block. In fact, with Panels, you can basically use any content in Drupal as a "block." This power does come with some complexity but it should allow you to do what you want with some experimenting.

---
Tags: views
---


title: custom menu/sub-menu output

text:
# Question
Title: custom menu/sub-menu output
what would i have to do to change the menu output structure for my theme?

this is the current structure:

```
<ul class="menu">                                //menu
  <li><a href="">Home</a></li>
  <li>
    <a href="">Other Stuff</a>
    <ul class="menu">                            // sub-menu
      <li><a href="">Sub-Page 1</a></li>
      <li><a href="">Sub-Page 1</a></li>
    </ul>
  </li>
</ul>

```

what i would like to get is something like that:

```
<ul class="menu">
    <li><a href="#">Home</a></li>
    <li>
        <a href="#" class="drop">Other Stuff</a>  // the 'drop' class is for the styling of a menu item with child-items
        <div class="dropdown_1column">
            <div class="col_1">
            <a href="">Sub-Page 1</a>
            <a href="">Sub-Page 2</a>
            </div>
        </div>
    </li>
</ul>

```

# Answer
> 1 votes
Do you know of the nice menus module? Nice menus will allow you to make dropdown menus without writing any code on your own. You can also find instructions for customizing the Nice menus CSS here.

Nice menus has almost 60,000 installs as of this writing, indicating that it is likely to be supported well into the future compared to modules that aren't so popular.

---
Tags: routes, theming
---


title: Override default php settings

text:
# Question
Title: Override default php settings
I am having difficulties in overriding the default PHP settings within my Drupal installation. I do not want Drupal to display E\_NOTICE messages. So I wanted to override the default PHP error\_reporting setting from `E_ALL` to `E_ALL & ~E_NOTICE` or from 2047 to 2039 (the corresponding error reporting values).

I added the line `ini_set('error_reporting', 2039);` in both sites/default/settings.php and sites/default/default.settings.php, but still when I go the status report page and view the PHP info file, I see the error reporting setting of PHP is still set to 2047. What am I doing wrong here? How to override the php setting?

PS: I even tried adding the line `php_value error_reporting 2039` to Drupal's .htaccess file, but there is no effect.

# Answer
> 2 votes
You will have to add

```
error_reporting(E_ALL ^ E_NOTICE);

```

to the *settings.php* file. Here's more.

---
Tags: configuration
---


title: Views not saving after upgrading

text:
# Question
Title: Views not saving after upgrading
I am upgrading my website from Drupal 6 to Drupal 7. In the Views module, when I attempt to save a view I now get the following error:

```
PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column
'human_name' in 'field list': UPDATE {views_view} SET
name=:db_update_placeholder_0, description=:db_update_placeholder_1,
tag=:db_update_placeholder_2, base_table=:db_update_placeholder_3,
human_name=:db_update_placeholder_4, core=:db_update_placeholder_5
WHERE (vid = :db_condition_placeholder_0) ; Array (
[:db_update_placeholder_0] => Last_update [:db_update_placeholder_1]
=> last update [:db_update_placeholder_2] => [:db_update_placeholder_3] => node [:db_update_placeholder_4] =>
[:db_update_placeholder_5] => 0 [:db_condition_placeholder_0] => 11 )
in views_db_object->save_row() (line 2092 of
/home/yektafil/domains/dl.yektafile.info/public_html/sites/all/modules/views/includes/view.inc).

```

Does anyone know what's causing this?

# Answer
The message states that views is missing a database column (human\_name) it is expecting to exist. New fields in core or contributed modules are often added by an update process.

It looks as if you need to run update.php, because it was not run after upgrading core or the views module itself. Alternatively, if you have drush enabled, you can run 'drush updb' from a shell.
> 1 votes

---
Tags: 7, views, upgrading
---


# Question
Title: Drupal method to retrieve all existing roles and all users of a specified role
I wish to retrieve the list of all users that belong to a particular role.

The query is to know:

* if there's any drupal method that provides list of all available roles created under *Admin \>\> User Management* (admin/user/roles) similar to retrieving all node types using node\_get\_types method.
* if there's a drupal method to get list of all users who belong to a particular role.

Though I could get this done by querying the `role` table and using the result with `user_roles` table, I felt that there might be some in-built method in drupal which must enable me to achieve the desired result which i might've missed out searching.

I'm aware that it's not ideal to check user permission related stuff with roles and rather user permissions instead from this post.

It'd be great if I could get a definite answer for my above mentioned queries.

# Answer
> 5 votes
You can use the `user_roles()` function to get a list of the roles in the system. You can even pass in specific conditions, for example if you want to get only the roles that contain a certain permission.

As far as getting a list of users by role, there is no such function, unfortunately; you'll have to write a small helper function yourself. I usually use something like this:

```
function users_by_role($role_id) {
  $sql = 'SELECT uid FROM {users_roles} WHERE rid = %d';
  $q = db_query($sql, $role_id);
  $uids = array();
  while ($row = db_fetch_array($q)) {
    $uids[] = $row['uid'];
  }

  return $uids;
}

```

That'll give you the user ids for a given role, after that you can use `user_load()` to get the user object for each, or simply add a join to the above query and include the data you need directly.

# Answer
> 3 votes
user\_roles() returns an array of roles. There is no function that returns all users of a particular role.

# Answer
> 1 votes
You can use Views to query a list of users, and filter them by Roles.

Or you can specify an Argument of `User: Roles` on the view. Then use `user_roles()` in a custom module to grab a list of all roles. Loop through the roles array, and inside the loop use `views_embed_view('my_users_view', 'display_id', $roleid)` passing the role id to this function as a third argument.

---
Tags: 6, users
---


title: users list as a node view

text:
# Question
Title: users list as a node view
I want to create a content type in which one of the field is a list of all users in drupal.I know I can add a node reference field but that reference is showing only normal node view but not user view.Is there a way to add list of all users in a content type?

# Answer
> 0 votes
You can create a Users view, using a module called Views. It's not exactly "content" (node) but Views can create Page displays which can be placed on the menu.

---
Tags: views, users
---


title: How to customize a content type css?

text:
# Question
Title: How to customize a content type css?
I have a pdf sharing site with a content type which called PDF. This content type has many fileds (such as author, description, rating, etc). These fields display in simple rows but I want to change either their form and css. for example I want to show Rating number much bigger (and in other color) on the top of each post. what can I do?
*Am I able to define new css classes for these fields?*

# Answer
create a new template file and add any classes you want. Here's a good introduction to D7 templates.

your template should be named like this: `node--node_type.tpl.php`. In your case, I think it should be `node--pdf.tpl.php`. You can use `node.tpl.php` as a starting point
> 2 votes

# Answer
One more way is to use a node preprocess hook in your template.php. It might look something like

```
YOURTHEME_preprocess_node(&$var){
 if($var['type'] == 'PDF'){
   drupal_add_css(...);
  }
}

```

refer this for details
> 2 votes

---
Tags: 7, entities, nodes, theming
---


# Question
Title: Move only jQuery UI Tabs load in footer in Drupal 7
I need jQuery UI Tabs to load after Token renders values. I see the simple method being to move jQuery UI Tabs script to the page footer. Please show me how to do this.

# Answer
Try using the following code.

```
drupal_add_js(drupal_get_path('theme', 'youthemename').'/js/jquery.easing.1.3.js', array('type' => 'file', 'scope' => 'footer'));

```
> 2 votes

---
Tags: javascript
---


# Question
Title: Javascript calander to pick contents on a particular date
Is there any module available in drupal which can be used to pick a date and afterwards contents from a particular content type can be displayed ?

# Answer
You can get this sort of functionality with the very powerful FullCalendar module. It provides extensions to Views enabling you to build complex calendars displaying content, users, and basically anything else a View can display.
> 0 votes

---
Tags: 7
---


title: How do I install this module?

text:
# Question
Title: How do I install this module?
I tried to install the Wysiwyg module, but it doesn't work. I copied the folder to `/sites/all/`, but how do I enable it?

The instructions say:

> You need to install and configure an editor library also. Please see this link for instructions.

# Answer
The module files are searched in specific directories, as evident in the drupal\_system\_listing() code. The directories where Drupal looks for modules are the following:

* profiles/$profile/modules, where `$profile` is the name of the currently enabled profile
* sites/all/modules
* $config/modules, where `$config` is the name of the directory containing the settings.php file currently used

If you copied the files in sites/all, then the module is not found because it is not in a directory where the modules are looked for; that would explain why you cannot enable the module.

The first step reported in the instructions is clearly the following one:

> Download, extract, and place Wysiwyg module in the modules folder **like any other Drupal module**.

(The emphasis is mine.)

The part you are quoting is not about the module, but the editor library that module should use.
Once you installed and enabled the module, you will be able to visit its configuration page (admin/config/content/wysiwyg), which will give you a list of libraries that module supports. Once you verify which one is compatible with your server, and you choose the one you want to use, you download the installation file following the link given in that page, and extract its content in sites/all/libraries/. Keep in mind the following notes give in the documentation page you linked.

* If the editor comes in a wrapper folder that equals its short-name, then you can put the entire wrapper folder straight into Wysiwyg's folder: /sites/all/libraries/\[editorname\]. Make sure that the resulting structure is NOT like /sites/all/libraries/\[editorname\]/\[editorname\] unless the settings page indicates otherwise.
* If the editor comes in a wrapper folder with additional characters (e.g. version number), then you can put the entire wrapper folder into the sites/all/libraries folder, but need to rename it to its short-name: /sites/all/libraries/\[editorname\]. Make sure that the resulting structure is NOT like /sites/all/libraries/\[editorname\]/\[editorname-version\].
* If the editor comes without a wrapper folder, then you need to create the editor's short-name folder yourself and copy the editor library files into that folder: /sites/all/libraries/\[editorname\].

If you correctly followed the instructions given from the module and its documentation, on admin/config/content/wysiwyg you will see that the editor library you copied will be reported as *installed*. If you don't see that, it means you copied the editor files in the wrong directory, or there are other errors (e.g. the version you installed is not compatible with the module).
> 5 votes

# Answer
Move the module to `sites/all/modules/`. Then you can activate it under `index.php?q=admin/build/modules` (Drupal 6) or `index.php?q=admin/modules` (Drupal 7).
> 0 votes

---
Tags: wysiwyg
---


title: Blocks page and Themekey module

text:
# Question
Title: Blocks page and Themekey module
I am referring to this page.

I need to use the administration theme on this page, but this is blocked by default.

At the moment I have to go to the theme page, change to my admin theme, and then change back when I have made the changes I need.

Is there anyway I can set this up using the Themekey module? It is beginning to be a major problem for my client.

# Answer
No, there is no way you can change theme on this location using themekey.

You might consider to do this in your custom module. Something like this:

```
function YOUR_MODULE_NAME_init()
{
  global $custom_theme;
  if($_GET['q'] == 'admin/build/blocks'){
    $custom_theme = 'your_theme_name';
  }
}

```
> 1 votes

---
Tags: 6, theming
---


title: How do I force batch to use nojs?

text:
# Question
Title: How do I force batch to use nojs?
I am having trouble using batch. The problem is that on the client website, there is an error in the jquery file in the jquery\_update module and I am not allowed to change this because I am just building a custom module for them. So, JS won't run and batch is locked. I want to force batch to use do\_nojs such that the page is reloaded using http meta. Is there any solution I can use for that?

# Answer
> 4 votes
I've run into the inverse problem using Pressflow. From that I have learned:

1. The js version runs if and only if the has\_js cookie is set. If you are able to clear that cookie (and keep it away), you will be able to run batch.
2. When the cookie is not set, there is a query parameter in the meta refresh tag, namely op=do\_nojs (and not op=do as is normal). If it is a batch you are trying to run and one for which you know the batch id, you may be able to force a nojs solution.

Based on that, if you are only having problems with tunning batches yourself, the simple solution is to disable js in your browser before starting the batch operation.

---
Tags: 6, batch-operations
---


# Question
Title: Drupal 7 - Display Content type as Block and Block Naming Convention
I have created a content type which has some fields, and I want these fields to be displayed as a block.

I've tried renaming a block in my 'theme/template' as `block--[machine-name].tpl.php` but is of no use.

# Answer
So, if I understand this correctly, your asking how you can make a block which displays fields from a content type based on some logical requirements, then provide an .tpl override so you can do some custom work to the output of those fields? I hope thats right.

So this is relatively easy depending in how you want to go about this.

* Step 1: You've created your content type and added all of the fields that you want. I'm assuming you've also created some content already to test the next part.
* Step 2: You need to create a view that has a block display. See screenshot for an example. https://skitch.com/therealwebguy/8ksue/block-step-1
* Step 3: Set up your block view appropriately. See screenshot for more specific details for this: https://skitch.com/therealwebguy/8ksw9/block-step-2
* Step 4: If you refer to the screenshot provided in Step 3, you'll notice in the bottom right that I have highlighted the "Information" link for the Theme layer. Clicking this link will bring up a list of all of the .tpl files you can create for this view to target what you need. It has everything from the top-level view tpl to the output of a single field being rendered by the view. Choose the one that's best for you needs, copy the HTML provided and add it the view.tpl.php file you've chosen to use.

Lets recap:

* We've create a content type and added fields to it.
* We've added actual nodes of the new content type for testing.
* We've created a new view which will provide a block display, showing us the field values of our content type that we want to show.
* We've created a custom tpl override for the view of our choice to do some more customization at the theme level that best fits our needs.

The only thing left to do is to head over to your blocks administration and put the block where you want it.

Good Luck!
> 4 votes

# Answer
I'd suggest one of the following modules:

Node Blocks:

> This module allows you to specify content type(s) as being a block. This allows the content managers of the site to edit the block text and title without having to access the block administration page. Users only need edit access to that node in order to edit it.
>
> It is very handy to create a simple block content type and enable this content type for blocks and use these in place of the normal 'add block' functionality.

Nodes In Block:

> Nodes in block makes it possible to add nodes into a block. A number of configurable blocks are generated which you can assign to a region. Visibility settings of this block are automatically set to 'Show on only the listed pages'. On the node content form, you define the weight and visibility per node thus making it easier for content administration as all your content is now in the same place. With this module, you don't have to explain your customers how blocks work but is still able to decide on which pages content must be rendered.

Simply renaming a block template with the name of your custom content type won't generate a block from it.
> 1 votes

# Answer
Use the Bean module. It creates blocks as entities so you can add fields to them. Here is an excerpt about it from the module's project page:

> Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require. The bean content can then be placed around the site just like any other block.
> 0 votes

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


# Question
Title: Complex View Contextual Filter with User Relationships — how would I achieve this?
As I mentioned in the question I raised earlier this week, I'm using User Relationships to create unidirectional friendships between users on my site.

The friending paradigm is like Twitter, where Alice may follow Bob and that does not imply that Bob also follows Alice. That said, Bob is able subsequently to choose to follow Alice.

Looking in the database table `user_relationships`, I can see that this situation results in two rows for a reciprocated relationship:

```
mysql> select * from user_relationships where requester_id in (187767, 190348)
  and requestee_id in (187767, 190348);

+--------+--------------+--------------+------+----------+------------+------------+-------+
| rid    | requester_id | requestee_id | rtid | approved | created    | changed    | flags |
+--------+--------------+--------------+------+----------+------------+------------+-------+
| 200726 |       187767 |       190348 |    1 |        1 | 1331657565 | 1331657565 |     0 |
| 200723 |       190348 |       187767 |    1 |        1 | 1331656437 | 1331656437 |     0 |
+--------+--------------+--------------+------+----------+------------+------------+-------+
2 rows in set (0.00 sec)

```

For ease of discussion here, let's talk about a specific View — that of "users who follow you but you don't follow back". For these users, there will be a row in `user_relationship` with `requestee_id` being `$current_user‑>uid`, let's say this has a `requester_id` of `$follower‑>uid`. There will be no row, however where `$current_user‑>uid` is the `requester_id` and `$follower‑>uid` is the `requestee_id` (which would indicate that the current user had reciprocated by following back). So if we're looking at the output above, it would be the situation where only the first row (`rid = 200726`) exists, from the perspective of user `190348`.

This is slightly easier to explain with a Venn diagram that I've hastily knocked-up:
; my View here is of the area labelled `C`.

Now in my View (of which there is a now out-of-date screenshot), I have two Contextual Filters:

* "User relationships: Requester user", bound to the "requester" Relationship and set to Exclude; and
* "User relationships: Requestee user", bound to the "requestee" Relationship, *not* set to Exclude.

So far so good. Except this shows me *all* users who follow `$current_user`, not just the ones that `$current_user` does not also follow back — `B ∪ C`. If I want to show only the users in `C`, then I also need to check that no reverse row exists. If I go to add a new Contextual Filter, I don't have any option to check something like this (as it is not a property of the individual row I'm showing).

So how do I achieve this? I guess I'm going to have to write some PHP to prevent displaying users where this is the case and there are custom modules in my site already, but I don't understand Drupal well enough to know what hook I'm looking for or where to intercept the processing of the rows being displayed.

Help, please? :o)

# Answer
> 4 votes
Fixed it.

Last night I noticed that I have the ability to add PHP Filter Criteria (which I'd somehow not noticed before!), coming from the Views PHP Module. It turns out that this allows me to enter arbitrary PHP and it will take anything that returns `TRUE` as meaning the row should be removed from the resultset.

So I added a Filter Criterion that checks the SQL query `Select * From user_relationships Where requester_id = :current_uid And requestee_id = :follower_uid` and I `return TRUE;` if that query results in more than zero rows.

To do this, I needed to add new Fields, both set to be "Excluded from display":

* User: User ID (bound to Requester), with an administrative title of "Follower UID (not displayed)". This gets passed as the variable `$row->uid`
* User: User ID (bound to Requestee), with an administrative title of "Current UID (not displayed)". This gets passed as the variable `$row->uid_1`

Then in a new PHP Filter Criterion, I created a filter as follows:

```
$filter_result = db_query('Select * From user_relationships '.
  'Where requester_id = :current_uid And requestee_id = :follower_uid',
    array(
        ':current_uid' => $row->uid_1,
        ':follower_uid' => $row->uid,
    ));

$count = $filter_result->rowCount();

return $count > 0;

```

Then those superfluous rows no longer appear in my output.

For some reason, I *do* need to assign `$filter_result->rowCount()` to the variable `$count`; trying `return $filter_result->rowCount() > 0;` directly didn't want to work for some reason.

But problem solved. At last :o)

---

**Edit:** I've just corrected the Field bindings, having noticed I was doing it differently in two different places and I'd put the wrong one in my answer here. Note that the User Relationships fields "UR: Requester user ID" and "UR: Requestee user ID" do not output user IDs, so do not work in this query; you do have to use two different "User: User ID" Fields, one bound to each end of the relationship. (Irritatingly, this means they have the really unhelpful variable names of `$row->uid` and `$row->uid_1` when passed to the PHP Field; I haven't yet found a way around this.)

# Answer
> 3 votes
For the sake of usefulness for other users, other suggestions I didn't use include the following:

1. Turning on "Use aggregation" and messing with aggregation settings to look for the same `Count() < 1` check.
2. Attaching to the `hook_views_query_alter` hook, like the instructions on Better `WHERE`s for your Drupal forums with `hook_views_query_alter`, which would allowme to have written some bespoke logic in a module using something like:

```
function YOURMODULE_views_query_alter(&$view, &$query) {
    if ($view->name == 'YOURVIEW') {
        $view->query->add_where('advf_filter',
           "(node.type='%s' OR node_comment_statistics.comment_count >= %d)",
           'forum', 1);
        $view->query->set_group_operator('AND');
    }
}

```

which I helpfully found via #3686: Alter a Views query to use `OR` through the user interface from enjoylife.

There's also some documentation on Working with Views on Drupal.org, but I didn't find any of those particularly useful, as the information was mainly not what I was looking for.

It's also worth mentioning that the modeule Advanced Help does give some relatively basic contextual help within the Views UI, though you probably already know that, as my Drupal admin pages were screaming it at me ;o)

I hope this all proves useful to someone!

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


# Question
Title: Link to nodes in WYSIWYG Editor and Domain Access
I have a Drupal installation using Domain Access. Is there a solution for inserting links on nodes using WYSIWYG-Editor considering if the node is published to the particular domain. For Example:

Node A, published to domain Y and Z, has a link to node B, published only to domain Z. Viewing node A on domain Z the link is rendered as a link. Viewing node A on domain Y the link is rendered as plain text (without

Thanks in advance

# Answer
> 2 votes
See the LinkIt project.

Its flexible API should let you hook into the node listing logic it uses to inject SQL to group node listing by Domain. You should be able to make a plugin with it ... I see no existing solution off-hand (I've used LinkIt and DomainAccess, but not had users linking around sub-domains from the WYSIWYG. My domains were very separate from one another).

---
Tags: nodes, domain-access, navigation
---


# Question
Title: jQuery stops working in a ahah wrapper div returned as json data
I use #ahah binding to a form element to modify a #ahah\[‘wrapper’\] HTML div. It contains a ‘slider’ div for the EasySlider jQuery UI plugin. This div contains a list where each list item represents one slide. When the ahah event is triggered, the wrapper HTML is replaced by a new set of slides.

When the form loads the slider works fine.

Here’s the problem: when the ahah event is triggered the jQuery no longer works. The new slides display one below the other, no animation. Shouldn’t the jQuery function be called automatically, or what is needed to make the call?

# Answer
> 1 votes
Not really a Drupal question, but the slider is created in Javascript on the document.ready -event which can't as such be triggered manually.

When you fetch a piece of content via ajax to the page, it just replaces the html, but does not attach any event handlers or run any document.ready -code. You need to handle that explicitly.

What I'd do is I'd check out what function EasySlider calls on document.ready and just repeat that call after the ajax content is fetched.

---
Tags: javascript
---


# Question
Title: Automatic Node titles to generate a title based on taxonomy
I’m using Automatic Node titles to create node titles based on taxonomy terms. In my node I have 3 flat vocabulary:

Color, size, year.

One CCk field for the price.

And 1 hierarchical vocabulary(Makes and models)using a dropdown list.

I want the title to Show only terms from the hierarchical vocabulary(Makes and models)..Something like this:

```
 [Make term][ Model term ]  for [ price ] $.

```

This is easy to do with Drupal 7, using term patterns, but with Drupal 6, I guess the best option would be to use PHP. Which I have no clue about. I found this code here:

```
      <?php  $terms = array_values($node->taxonomy[1]);
       print taxonomy_get_term( $terms[0] )->name;
       print taxonomy_get_term( $terms[1] )->name;
       ?>

```

But It’s not working at all. Any idea?.

# Answer
I suppose that one of the simplest things to check would be that you're calling the correct taxonomy id at this step: `array_values($node->taxonomy[1])`. If the taxonomy id of the make and model vocabulary you created isn't `1`, this won't work as you expected.

The Devel module is very helpful for this. If you have it installed, you can open the node in question, click on the "Devel" tab and scroll down until you find taxonomy. It'll list the ids currently in use on the node.

Another way, if you don't have or want Devel, is to go to your taxonomy listing at 'admin/content/taxonomy'. When you click on "list terms" for your make and model vocabulary its id will be displayed in the URL.

That is the id you want to have in your first line: `array_values($node->taxonomy[1])`

-------------\[edit\]---------------

As per your comment below, I would suggest using something like this:

`$terms = taxonomy_node_get_terms_by_vocabulary($node, $vid, $key = 'tid');`

Where `$node` is the node object, `$vid` is the id of the vocabulary you want to limit the term search to.

~~Then you can loop through the terms using:~~

~~```
foreach($terms as $term) {
  print $term. " ";
}

```~~

------------\[update\]--------------

Use the standard PHP function `implode` to put in your spaces:

`implode(" ", $terms);`

The added space will put spaces between the terms in the array. This is, of course, assuming the terms will be returned in an order that makes sense for what you're doing.
> 1 votes

---
Tags: 6, taxonomy-terms, nodes
---


# Question
Title: Does service module expect Base64 encoding for file uploads through http-post (drupal 7)?
I have been having trouble getting a file to upload through http-post from my lisp application and I have noticed in all of the curl php examples I have found they have a like this:

```
$file = array(
  'filesize' => filesize($filename),
  'filename' => basename($filename),
  'file' => base64_encode(file_get_contents($filename)),
  'uid' => $logged_user->user->uid,
);

```

which includes the call to base64\_encode, I am not doing this from my lisp application and I always get a response of 200 but the file is not uploaded. I am using Services 3.x and a RESt server.

Does Services require that file uploads are base64 encoded?

# Answer
> 5 votes
Short answer yes it does. There is a create raw method but unfortunately, it doesn't work very well b/c drupal 7s file handling is a joke.

Ive created a patch that will allow you to attach files to a node and it uses multipart form, but its a work in progress.

http://drupal.org/node/1484992

---
Tags: 7, services
---


# Question
Title: Is there a media-handling module that can handle midi files?
I've been using MP3 Player to provide an on-page mp3 player, but I also need to be able to handle midi files. Right now the best I can do is allow them to be uploaded into the "mp3 file" field, but when it renders the node, it just gives a link to the file, which mean you have to navigate to the file (or open it in a new tab) for the browser to play it.

# Answer
MIDI files can be embedded straight into the page with the `<object>` tag, so there should be some way to then output that with the link that views gives you at the moment. If you went with a separate field then it's be easy enough to do with Views output rewriting.

After a quick look for a flash solution, it seems that flash itself doesn't have any support for MIDI, so a flash based player is unlikely.
> 3 votes

# Answer
If you actually want a module to do this, you can look at the Audio module. However, this module is currently said to be "unstable", even though over 3000 sites report having it installed. So with that many users it might be worth taking a look at anyways. The author also has an alternative suggestion using FileField and SWF Tools modules.
> 2 votes

# Answer
You can use the Media module in conjunction with either MediaElement or the MediaFront module to handle MP3 files.
> 2 votes

---
Tags: 7, media
---


# Question
Title: How can I theme profile field forms in an HTML table?
I put this code in Drupal 6, and made a template file called "user-register.tpl.php" to override the default registration page.

```
function my_theme_theme(){
  return array(
    'user_register' => array(
      'arguments' => array('form' => NULL),
      'template' => 'user-register',
    ),
  );
}

```

With this, I could print profile user name, email and password.

```
<?php print drupal_render($form['account']['name']); // prints the username field ?>
<?php print drupal_render($form['account']['mail']); // print the email field ?>
<?php print drupal_render($form['account']['pass']); // print the password field ?>

```

This code doesn't print the profile field form.

```
<?php print drupal_render($form['profile_category_name']['profile_field_name'] ); ?>

```

Ideally I would like to print the form itself separately from the title, and the description so that I can arrange them with `<table>` tags.

# Answer
> 0 votes
I found out why it didn't work. Because my category name was not ASCII characters and it now works after changing them to ASCII characters with the code above.

---
Tags: forms, theming, users
---


title: Partial URL transliteration?

text:
# Question
Title: Partial URL transliteration?
Is it possible to partially transliterate URL alias, so to leave for example the case of the node title unchanged, such as in:

```
/this/is/my/transliterated/path/THIS-IS-UNCHANGED-Node-Title-888

```

with the purpose behind it being to preserve product symbols, where similarity between lower and uppercase is unwanted.

And I mean fully automated behavior, such as with a template function or a module.

# Answer
> 2 votes
Certainly, you can call `path_set_alias()` (or `path_save()` in Drupal 7) and set up whatever you want. You could call these from within `nodeapi()` (or `node_op.....` in Drupal 7) and set up your path however you want. But, I also think that drupal isn't case sensitive, so, 'foo/bar/BAZ' is the same as 'foO/bAr/BaZ' as far as it's concerned here, so, gotta be careful.

ADDITION:

If you want pathauto to do this, quick hack would be to edit pathauto.inc and do this:

```
  if (true) {
    $foo=drupal_strolower(dirname($output));
    $bar=basename($output);
    $output=$foo . '/' . $bar;
  } else {
    // Optionally convert to lower case.
    if (variable_get('pathauto_case', 1)) {
      $output = drupal_strtolower($output);
    }
  }

```

where it does just this:

```
// Optionally convert to lower case.
if (variable_get('pathauto_case', 1)) {
  $output = drupal_strtolower($output);
}

```

but it's up to you to more refine `if(true)` otherwise it will do this for every alias.

# Answer
> 0 votes
I'm not familiar with Drupal, and I was just passing through.

Since case sensitivity and anti-similarity seems to be the primary goal, I'd imagine you could simply string break the URL in PHP with "/" as the division point as in the following code:

```
$arrayFullofURLPieces = explode("/",$originalURL,32);

```

You can do what you want with the pieces.

---
Tags: uri, transliteration
---


# Question
Title: "one more" ajax call for multiple node add forms on one page
I want a page with an initial node add form (in small size), the title line and body textarea 3x20 size;

And a button "one more" with ajax call to display another form plus another button etc etc.

and of course the submit button always at the bottom.

So the question is ... which module ? :) I hardly cant find the terms for searching!

**UPDATE:** I want to add , this task seemed to me quite often used and modular, so I thought there would be a module for it; Now as i work through related questions and learn about ajax form api http://randyfay.com/ajax it's okay to code it for me and maybe you can give some starting points.

# Answer
> 2 votes
I worked on similar case. I wanted to add few nodes at one time without reloading page.

Instead I did multi value field in my content type (mysomething), but I needed to have more elements than one field. So I found field collection module, made collection and put it as multi value field of type collection. Now when I do node/add/mysomething I have collection and \[Add more\] button below.

Creating collection allows You to add all core field types, so in your case I would add text field working as title and body field to collection.

The other thing is, that if someone add 3 collection at once it will be consider as one mysomething node by D7 core - You should make some views to see whats inside. Another approach is to catch node creation action of type mysomething and try to split it into nodes by rules, but I didn't do that so I'm not sure if it is possible. And finally someone probably can write custom module with ajax form, where submit button will save node for each element...

I think it's nice trick with no coding (UI visual puzzle). I can write step by step config for You, if needed, but it's pretty easy.

# Answer
> 0 votes
The default Fields API gives you the opportunity to use fields with unlimited number of values, with widgets that already embed the functionality you're talking about, mean an 'Add more' button.

Is there any reason you don't want to use it ?

---
Tags: 7, forms, ajax
---


title: Run cron on a different web server?

text:
# Question
Title: Run cron on a different web server?
Is it possible to stop the cron on the main web server and run it on another web server that is using the same codebase, same MySQL server and same Memcache sever?

The cron web server will run import and other heavy operations that Drupal is doing during Cron.

Is anyone doing this? Also some tips for the implementation of the shared codebase(performance wise) would help.

# Answer
> 1 votes
This would be very easy to do by either running a run cron job or a jenkins job on the server/node you want to run drupal cron on. This is very common practice in all of our projects.

If you are doing a large data import on cron, be sure you are using cron queue. http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_cron\_queue\_info/7

# Answer
> 0 votes
What I can advise you its to use two same servers, a frontend and a backend. In the backend where you will run the Cron you don't need to install caching stuff like Varnish or Memcache, as it's only to run your cron.

You should also create a circular replication between your frontend and backend server, like frontend server has backend slave and backend has frontend as slave. Like that, your heavy cron will not impact so much the frontend.

The both code base should be the same, even if the backend is not used for public, so its better to use Git or versioning system to keep it updated.

Finally, I suggest you to give a look to this module to improve your cron system.

---
Tags: cron, caching
---


title: Variable titles

text:
# Question
Title: Variable titles
I am using views and I want to make the title be: Username's Wall. Depending whose profile it is viewing the title should be automatically changed. How can I do that? this is for drupal 7

# Answer
Try putting the following, in the view title field:

> %user:name's Wall

Did you mean that you want to create a user profile page? Just use the Panels module, activate the user profile template, and in the title pane write the following:

> %user:name's Wall
> 1 votes

---
Tags: views, 7
---


# Question
Title: When I disable the poll module my add content page doesn't work. Why?
Im on d7. I no longer want to have a poll on my site. For some reason when I disable the poll module, the add content page becomes blank and says I have not yet created any content types. I have three other content types on my site and they display fine in the admin panel, just not on the node add page. Anyone have any suggestions? Thanks.

# Answer
Cache can often be a source to weird problems, clearing it could help. The poll module won't effect if other content types are active or not, so the problem shouldn't be related to the poll module directly.
> 0 votes

# Answer
I figured it out, it was due to the weird bug in the navigation menu that creates multiple empty add content links. Thanks
> 0 votes

---
Tags: 7, nodes
---


title: Replace rewrite output URL aliases

text:
# Question
Title: Replace rewrite output URL aliases
Is it possible to rewrite parts of taxonomy terms URL custom aliases before output, for example with something similar to the the following code?

```
  function replace_term_url ($term_alias) {
    // Url alias "article/first"
    $term_alias = str_replace("article", "article-sub", $term_alias);
  }

```

# Answer
In Drupal 7 there isn't a specific hook to alter the URL associated with a taxonomy term, but you can use the generic hooks for altering URLs, which are hook\_url\_inbound\_alter(), and hook\_url\_outbound\_alter().

```
function mymodule_url_outbound_alter(&$path, &$options, $original_path) {
  if (preg_match('|^taxonomy/term/([0-9]*)|', $path, $matches)) {
    // Alter $path; $matches[1] contains the term ID.
  }
}

function mymodule_url_inbound_alter(&$path, $original_path, $path_language) {
  // Revert the change done in mymodule_url_outbound_alter().
}

```

`hook_url_outbound_alter()` is invoked for URLs output from Drupal, `hook_url_inbound_alter()` is invoked for URLs Drupal is receiving.

In Drupal 6, it is possible to implement hook\_term\_path(), but that is invoked only for the module associated with the taxonomy term. The code invoking that hook is in taxonomy\_term\_path().

```
  if ($vocabulary->module != 'taxonomy' && $path = module_invoke($vocabulary->module, 'term_path', $term)) {
    return $path;
  }

```

If you want to use a third-party module, then there is the Pathauto module, which allows to automatically set the alias for users, nodes, and taxonomy terms.

> The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias. This allows you to have URL aliases like /category/my-node-title instead of /node/123. The aliases are based upon a "pattern" system that uses tokens which the administrator can change.
> 4 votes

# Answer
You should be able to do that with the Pathauto module:

You can use it to set up automatic aliases for taxonomy terms, as well as content and other things.
> 1 votes

---
Tags: path-aliases
---


# Question
Title: Fields on images, displayed on edit page
I'm trying to implement a way for users to add a "caption" and "credit" (name of the photographer) to photos which are attached to an article. The user should be able to upload an image and assign a caption and credit, preferably from the edit page for the article.

I've installed the media module and added "caption" and "credit" fields to the image file type, but I can't figure out where the user can edit those fields. Is there any way to show those fields somewhere on the edit page?

# Answer
> 2 votes
I did similar with creating photo albums connected to a content type using the field\_collection module. This way you can easily customise whats added very quickly as you are essentially creating a new type of entity (think of it as having an article entity and attaching a new photograph entity which has its own image, caption and credit fields).

---
Tags: entities, media, files
---


title: Blocks as Fields in Content Type

text:
# Question
Title: Blocks as Fields in Content Type
I really like the ability to edit a block in Drupal on whatever page it's on--without having to drill down through menus. However, a block doesn't seem to be a valid field for a content type. If something is promoted to the front page, I can edit the item in a similar fashion to a block.

A work-around is to create a page, and put the block on the page. However this creates additional maintenance. For instance if the page is deleted, someone has to remember to delete the block too.

Is there any way of creating a field type which would be a block? Or even better, is there any way in which a text field can be edited on the fly if it's not on the home page?

Any thoughts would be appreciated.

# Answer
> 1 votes
The display suite module has a "region to block" in its extras. This lets you put any of the fields displayed into its own block which can then be put where you want but I believe that editing will still take you to the full node edit page anyway.

For editing on the fly you should look into the jeditable module and/or editablefields module.

---
Tags: blocks
---


# Question
Title: Processing forms together for a tree of related entities
I have EntityA which has one or more EntityB's which have one or more EntityC's. EntityB references values of EntityA and EntityC references values of EntityB. My current plan is to have an id field of EntityB reference the id of EntityA and the same for EntityC referencing EntityB. Normal one-to-many relationships, possibly with foreign keys defined so mysql will enforce referential integrity.

I am trying to use the Subform module to build the lists of required forms inside the edit form for EntityA. EntityA builds the settings for a new EntityB into an object and passes that to EntityB's form via Subform '#subform\_arguments'.

My question is about how to save EntityB and EntityC forms. Should I save EntityB in the submit function for EntityA or try to communicate EntityA's id to the EntityB submit function and have it save its own entity? If the save logic for EntityB goes in the submit function for EntityA's form, how do I retrieve the subform values to save?

# Answer
> 1 votes
This is working now with entity saving logic neatly packaged with the sub-item entity code. Before saving the subitems, I set the value of a hidden element with the parent entity's id. I modified the wrapper form's submit handler array:

```
    '#submit' => array(
        'wrapper_form_submit',
        'update_subforms_before_save',
        'subform_submit_all',
    ),

```

First, the wrapper is saved and is assigned an id. Then it updates the subforms with that id. And finally the subforms are submitted. The function to update the subforms is modeled after subform\_submit\_all():

```
function update_subforms_before_save(&$form, &$form_state) {

    $wrapper_item_id = $form_state['values']['item_id'];

    if (!empty($form_state['temporary']['subform'])) {
        foreach ($form_state['temporary']['subform'] as $subform_name => &$subform_state) {

            $subform_element = &subform_array_get_nested_value($form, $subform_state['subform_element_parents'], $subform_exists);
            if ($subform_exists) {

                switch($subform_element['#subform_id']) {
                    case 'subitem_entity_form' :
                        $subform_state['values']['parent_item_id'] = $wrapper_item_id;
                        break;
                }

            }
        }
    }
}

```

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


# Question
Title: How do I print a link only if it doesn't lead to access denied
My nodes have fairly complex permissions set on them. I want to display a small edit link on the teaser for a specific content type, only if the user has the permissions required to edit that specific node. I already customise the display with the file node--newsletter.tpl.php

I tried:

```
<?php
$quick_links['quick-edit'] = array(
    'title' => 'Edit',
    'href' => 'node/' . $nid . '/edit');
?>
<div class="links quick-edit-links">
    <?php print theme('links', array('links' => $quick_links, 'class' => 'links inline')); ?>
</div>

```

But that prints out the edit link no matter what. What's the correct way to do this. Ideally I'd like to have a solution that is reasonably generic and works for practically any link (e.g. node/id/delete, or admin/) So I can use it elsewhere, but a solution which only works for this specific case would be OK.

# Answer
Now I feel silly, found an answer myself straight away, although it does only work for this specific example, I'd still be interested to see something more general.

```
<?php if (node_access('update', $node)):
    print l('edit', 'node/' . $nid . '/edit');
endif; ?>

```
> 4 votes

---
Tags: theming, users, navigation
---