# Question
Title: How do I render the search form for a particular Apache SOLR search page on its own?
I have the SOLR search module installed, and have set up a couple of different search pages.

I need to render the form for one of these pages on a separate page. I thought I could just piggy back off the default `search_form()`, but it doesn't work.

Using this code:

```
$build['search_form'] = drupal_get_form('search_form', 'directory/search', '', 'apachesolr_search');

```

The search form is displayed, and has the correct `action` property. But when the form is submitted, it just redirects to `directory/search`, without the keys in the URL (which are obviously required for the search).

What am I missing?

# Answer
> 1 votes
I have been able to use the search form in a page with a path different from the canonical one, using the following code.

```
/**
 * Implements hook_menu().
 */
function code_testing_menu() {
  drupal_static_reset('search_get_info');
  $default_info = search_get_default_module_info();

  $items['test/search'] = array(
    'title' => 'User search test',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('code_testing_user_search_form'),
    'access callback' => 'search_is_active',
    'type' => MENU_CALLBACK,
  );

  $items["test/search/%menu_tail"] = array(
    'title' => 'User search test',
    'load arguments' => array('%map', '%index'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('code_testing_user_search_form', 2),
    'access callback' => '_search_menu_access',
    'access arguments' => array('user'),
    'type' => MENU_CALLBACK,
    'weight' => 0,
  );

  return $items;
}

function code_testing_user_search_form($form, &$form_state, $keys = '') {
  $info = FALSE;
  $keys = trim($keys);

  if (!$keys && !empty($_REQUEST['keys'])) {
    $keys = trim($_REQUEST['keys']);
  }

  $active_module_info = search_get_info();

  if (isset($active_module_info['user'])) {
    $info = $active_module_info['user'];
  }

  if (!$info) {
    form_set_error(NULL, t('Search is currently disabled.'), 'error');
    return $form;
  }

  $action = 'test/search';

  $form['#action'] = url($action);
  $form_state['action'] = $action;
  $form['#attributes']['class'][] = 'search-form';

  $form['module'] = array(
    '#type' => 'value',
    '#value' => 'user',
  );

  $form['basic'] = array(
    '#type' => 'container',
    '#attributes' => array('class' => array('container-inline')),
  );

  $form['basic']['keys'] = array(
    '#type' => 'textfield',
    '#title' => t('Enter your keywords'),
    '#default_value' => $keys,
    '#size' => 40,
    '#maxlength' => 255,
  );

  $form['basic']['processed_keys'] = array(
    '#type' => 'value',
    '#value' => '',
  );

  $form['basic']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Search'),
  );

  if (!empty($form_state['results'])) {
    $form['search_results'] = $form_state['results'];
  }

  return $form;
}

function code_testing_user_search_form_submit($form, &$form_state) {
  $active_module_info = search_get_info();
  $conditions = NULL;
  $keys = $form_state['values']['keys'];

  if (!empty($active_module_info[$form_state['values']['module']])) {
    $info = $active_module_info[$form_state['values']['module']];

    if (isset($info['conditions_callback']) && function_exists($info['conditions_callback'])) {
      $conditions = call_user_func($info['conditions_callback'], $keys);
    }
    if ($keys || !empty($conditions)) {
      $form_state['results'] = search_data($keys, $info['module'], $conditions);
      $form_state['rebuild'] = TRUE;
    }
  }
}

```

I tried writing the page callback (`code_testing_user_search_view()`) for test/search, and test/search/%menu\_tail basing on the search\_view() code, but it didn't work. I used `dpm($_POST, time());` in `code_testing_user_search_view()`, and I noticed the function was called twice, after the search form was submitted: In the first invocation, `$_POST` was populated with the expected values, while in the second invocation `$_POST` was an empty array. The code I used for `code_testing_user_search_view()` was slightly different from the code used by `search_view()` because `code_testing_user_search_view()` was not getting the name of the module implementing the search hooks as argument.

```
function code_testing_user_search_view($keys = '') {
  $info = FALSE;
  $redirect = FALSE;
  $keys = trim($keys);

  if (!$keys && !empty($_REQUEST['keys'])) {
    $keys = trim($_REQUEST['keys']);
  }

  $active_module_info = search_get_info();

  if (isset($active_module_info['user'])) {
    $info = $active_module_info['user'];
  }

  $results = array('#markup' => '');

  $conditions =  NULL;

  dpm($_POST);

  if (isset($info['conditions_callback']) && function_exists($info['conditions_callback'])) {
    $conditions = call_user_func($info['conditions_callback'], $keys);
  }

  if ($keys || !empty($conditions)) {
    $results = search_data($keys, $info['module'], $conditions);
  }

  $build['search_form'] = drupal_get_form('search_form', 'test/search', $keys, 'user');
  $build['search_results'] = $results;

  return $build;
}

```

# Answer
> 5 votes
Well I'm not sure what the problem was, but after a bit of further digging into apachesolr\_search I've come up with a work around which seems to do the trick:

```
$search_page = apachesolr_search_page_load('PAGE_ID');

module_load_include('inc', 'apachesolr_search', 'apachesolr_search.pages');
$build['search_form'] = drupal_get_form('apachesolr_search_custom_page_search_form', $search_page);

```

As kiamlaluno has noted in the comments it doesn't look like it's actually apachesolr\_saerch causing this behaviour, but rather the core search module doing...something.

Hopefully this code will save someone the time in the future.

# Answer
> 0 votes
The Answer By Clive helped a lot. Thank you. I couldn't post this under that answer but it belongs there. A couple additions and a problem I had. If you want to display two forms on the same page to two separate custom pages , I encountered a couple issues. Below is my custom php block where i display search forms to the image library and video library pages.
Problem 1: The forms had the same html id attribute. 2: The second form kept posting to the first search page. I finally fixed that by setting the #action to the forms. It defaulted to the current page the block was on.

Here is the working code. I add some custom classes, tweak the search prompt text,tweak the id , and tweak the action . Works great. Thanks .

```
<?php
$search_page = apachesolr_search_page_load('image_library');
module_load_include('inc', 'apachesolr_search', 'apachesolr_search.pages');
$form = drupal_get_form('apachesolr_search_custom_page_search_form',$search_page);
$form['#attributes']['class'][] = 'pogoe-libraries-search-box';
$form['#attributes']['class'][] = 'search-message';
$form['basic']['keys']['#title'] = t('Search Images:');
$form['#id'] = "image-search-form";
$form['#action'] = "image-library"; // This defaulted to current page but still worked
print '<div>' . drupal_render($form) . '</div>';
?>

<?php
$video_search_page = apachesolr_search_page_load('image_library_0');
$vform =drupal_get_form('apachesolr_search_custom_page_search_form',$video_search_page);
$vform['#attributes']['class'][] = 'pogoe-libraries-search-box';
$vform['#attributes']['class'][] = 'search-message';
$vform['#id'] = "video-search-form";
$vform['basic']['keys']['#title'] = t('Search Videos:');
$vform['#action'] = "video-library"; // This defaulted to current page but always took me to the image-library search until I set this to video-library

print '<div>' . drupal_render($vform) . '</div>';
?>

```

Hope that helps

---
Tags: search
---


# Question
Title: How do I change order of completion rules in checkout?
How do I change the order in which completion rules fire?

There is a default *Completition* reaction rule. I wanted to add a second rule which executes some custom PHP but it's never executed.

I see no way to change the weight as in other rules. I also tried adding what I need as an action in that default rule, but it also doesn't seem to fire.

This is the reaction rule that fires on order completion.

```
{ "rules_completion" : {
    "LABEL" : "completion",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "php", "rules", "commerce_checkout" ],
    "ON" : [ "commerce_checkout_complete" ],
    "DO" : [
      { "php_eval" : { "code" : "jch_send_quote()" } },
      { "commerce_checkout_complete" : { "commerce_order" : [ "commerce_order" ] } }
    ]
  }

```

This is the code for `jch_send_quote()` which doesn't seem to fire.

```
function jch_send_quote(){
    global $user;
    watchdog('dev', 'jch_send_quote running here');
    drupal_set_message($user->uid);
        die('jch_send_quote running here')
}

```

What am I missing?

# Answer
You should be able to edit the rule and set it's weight:

*Screenshot, showing reaction rule with weight of "2"*

Lastly, your rule should still fire, even with a different weight. If it's not firing, it's probably an issue with that rule itself.
> 0 votes

---
Tags: rules, commerce
---


# Question
Title: Help! Can't Login - Accidently set Omega content zone to not display in content section
mysite.com/user/login can't display the login form because I accidently set my content zone to not display. Is there a way to reverse this programmatically?

# Answer
> 0 votes
You can generate a one-time login link.

```
drush uli

```

---
Tags: users, theming
---


# Question
Title: D7 serving node content to related subdomain
I am using Drupal 7 with single installation. Requirement here is to serve node content which belongs to sub-domain

Example:

if user try abc.mysite.com then system will internally serve content from

mysite.com/node/abc but user will not see any change in URL

What i have tried so far but failed:

1. `htaccess` modification
2. Subdomain module
3. Drupal hook "`hook_url_inbound_alter`"

Here "abc" subdomain is dynamic as this is related to node content.

Please Help!!!

# Answer
> 0 votes
This should be pretty simple to do with some mod\_rewrite rules. Apache's mod\_rewrite supports proxying requests.

# Answer
> 0 votes
I finally solved this by using menu\_execute\_active\_handler() function. Here are the steps.

1. Hook up initial request by defining custom menu path as your landing page.
2. In callback function of landing page, use code to determine sub domain.
3. On basis of sub domain, we can query out desired path and display by passing it to menu\_execute\_active\_handler() function.
4. If sub domain is not available then we can skip/redirect to default execution.

---
Tags: subsites
---


title: Removing Unnecessary CSS Files

text:
# Question
Title: Removing Unnecessary CSS Files
I am in the process of optimizing my Drupal site by removing unnecessary css files.

Running an audit I have found that `/misc/ui/jquery.ui.core.css`, `/misc/ui/jquery.ui.theme.css` and `/misc/ui/jquery.ui.slider.css` are relatively large but are never called.

I have tried removing them in my template.php file with the following but they still remain. How can I unset them?

```
unset($css[DRUPAL_ROOT.'/misc/ui/jquery.ui.slider.css']);
unset($css[DRUPAL_ROOT.'/misc/ui/jquery.ui.core.css']);
unset($css[DRUPAL_ROOT.'/misc/ui/jquery.ui.theme.css']);

```

# Answer
You can use `hook_ccs_alter`

```
function yourmodule_css_alter(&$css) {

  unset($css['misc/ui/jquery.ui.core.css']);
}

```
> 3 votes

# Answer
An alternative way in Drupal 7 using **YOUR\_THEME\_css\_alter()** is

```

    function YOUR_THEME_css_alter(&$css) {
    // Remove Drupal core css
        $exclude = array( //confirm path
            'misc/ui/jquery.ui.slider.css' => FALSE,
            'misc/ui/jquery.ui.core.css' => FALSE,
            'misc/ui/jquery.ui.theme.css' => FALSE,
            // Also you can remove contrib module CSS
            drupal_get_path('module', 'views') . '/css/views.css' => FALSE,);
        $css = array_diff_key($css, $exclude);
    }

```
> 2 votes

---
Tags: 7, theming
---


# Question
Title: adding panel to select field in content type
I created a content type for a new block. One of the fields in this needs to pull in category information from a magento site. I have code to get all of the categories and display them in a drop-down working in a panel template. The only step I am missing is know how to access this as a field in my new content type. I have read some articles about using something called hooks for this process but I'm not fully sure about how they work. Is a hook the best method and if so what exactly does it involve programmatically?

# Answer
> 0 votes
As mentioned in one of the comments I used the hook\_form\_alter but instead of pulling in the panel I just created another function to get the information and used that as the options for my select.

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

   $conf = $form_state['conf'];
   $categories = gacms_magecp_categories();

    $form['magecp'] = array(
     '#type' => 'select',
     '#options' => $categories,
     '#title' => t('Mage Category Product'),
     '#default_value' => isset($conf['magecp'])?$conf['magecp']:'',
     '#format' => isset($conf['format'])?$conf['format']:'full_html',
    );

    return $form;
  }

   function gacms_magecp_categories(){
    db_set_active('magento');

    $result = db_query("SELECT entity_id, name FROM catalog_category_flat_store_1");
        while ($row = $result->fetchAssoc()) {
           $content[$row['entity_id']]= $row['name'];
        }
        db_set_active();
        return $content;
    }

```

---
Tags: entities, hooks, nodes
---


title: Show content as per Taxonomy Term

text:
# Question
Title: Show content as per Taxonomy Term
I am new to `drupal` and using `drupal 7`. I have created some `taxonomies` and using it as menus using Taxonomy Menu module. The Taxonomies are being shown as menus.

Now I want to change content of the page as per term of the taxonomy. I have searched the problem but found different modules doing this task like Taxonomy Display, Taxonomy Menu Block. But I don't want to use any of the module and want to do it manually so that I can understand the inner working of `Drupal themes`.

Any help will be much appreciated.

# Answer
You can do this by Views:

1. Create view of block type (`admin/structure/views`)
2. Add fields want to display on term page.
3. Go to "Contextual filters" settings under "Advanced" tab.
4. Add the filters: "Content: Has taxonomy term ID (with depth)" and "Content: Has taxonomy term ID depth modifier". You can configure this on this filter: → When the filter value is NOT in the URL: → Provide default value → Type: Taxonomy Term ID from URL → under that, check the box "Load default filter from node page, that's good for related taxonomy blocks." → now check the boxes of the taxonomies you want involved here.
5. Now you need to add the second filter in order to exclude the current node from the list. Click \[+\] button of the contextual filters section.
6. Select Content: Nid.
7. Chosse the option "when argument is not present" to "Provide default argument".
8. Choose the "Default argument type" to "Content ID from URL".
9. Go to "MORE" , and check the "Exclude" box.
10. Move the filter "Content: Nid" to the top position.
11. Add a block to your view and embed the block on your node pages.
12. Save your view
> 1 votes

---
Tags: theming, nodes, taxonomy-terms
---


title: Is SimpleNews Cron Neccessary?

text:
# Question
Title: Is SimpleNews Cron Neccessary?
I'm running the latest stable version of SimpleNews 7.x.

I realise there is an option to disable sending via cron tasks and set a throttle. The description underneath this option advises it should only be used for testing purposes.

My SMTP server relays through Amazon SES. The SMTP server itself throttles email sending by default to 20 messages per connection.

So I'm wondering, is the cron task email sending really necessary if the messages just get queued up and throttled by my SMTP server anyway?

If I disable the cron sending are there any substantial problems I might encounter?

# Answer
> 1 votes
The throttle value you're mentioning is specific to cron jobs, not to a single send event. There's no easy way to throttle the number of mails delivered in a single send event.

In general, the main reason someone would want to use cron in this case is when your subscriber base is large enough that a single "Send" action will time out, due to the time taken to send the total number of emails exceeding your server's PHP maximum execution time directive.

Cron is utilised in this case to break up large subscriber bases into chunks your server can better manage.

In your case, you have a limitation of 20 outgoing mails imposed on you by your service provider. To ensure you can send mail to more than 20 people at a time, you will have to use cron to get around this limitation.

The throttle you refer to is the number of messages sent PER cron. Removing cron isn't advisable for a substantial list, as your server will connect to Amazon, attempt to deliver all the mails, of which only 20 would be accepted.

Without knowing the inner workings of Simplenews, one of two possible (and undesirable) scenarios would unfold:

1.) Any mail in excess of the first 20 would be ignored by Amazon, and sending would fail. Your site would ignore the errors, and of your entire "Send" event, 20 mails would go out.

2.) Simplenews might cache the remaining mails that Amazon doesn't accept in your DB. These would wait around to be sent at a later stage (next cron run), but because you're not running cron, Simplenews wouldn't be invoked during cron, and that queue would never be properly addressed. This would result in you sitting with a large number of unsent mails clogging up the Simplenews spool table.

Bottom line, disable cron at your peril. The second your subscriber base goes over 20, your newsletter sending process will start to give you issues.

---
Tags: emails
---


# Question
Title: 404 Not found: Could not find the controller
I am creating a resource for service module

```
function noteresource_services_resources() {
  return array(
    'note' => array(
      'retrieve' => array(
        'help' => 'Retrieves a note',
        'file' => array('file' => 'inc', 'module' => 'noteresource'),
        'callback' => '_noteresource_retrieve',
        'access callback' => '_noteresource_access',
        'access arguments' => array('view'),
        'access arguments append' => TRUE,
        'args' => array(
          array(
            'name' => 'id',
            'type' => 'int',
            'description' => 'The id of the note to get',
            'source' => array('path' => '0'),
            'optional' => FALSE,
          ),
        ),
      ),
      'create' => array(
        'help' => 'Creates a note',
        'file' => array('file' => 'inc', 'module' => 'noteresource'),
        'callback' => '_noteresource_create',
        'access arguments' => array('note resource create'),
        'access arguments append' => FALSE,
        'args' => array(
          array(
            'name' => 'data',
            'type' => 'struct',
            'description' => 'The note object',
            'source' => 'data',
            'optional' => FALSE,
          ),
        ),
      ),
      'update' => array(
        'help' => 'Updates a note',
        'file' => array('file' => 'inc', 'module' => 'noteresource'),
        'callback' => '_noteresource_update',
        'access callback' => '_noteresource_access',
        'access arguments' => array('update'),
        'access arguments append' => TRUE,
        'args' => array(
          array(
            'name' => 'id',
            'type' => 'int',
            'description' => 'The id of the node to update',
            'source' => array('path' => '0'),
            'optional' => FALSE,
          ),
          array(
            'name' => 'data',
            'type' => 'struct',
            'description' => 'The note data object',
            'source' => 'data',
            'optional' => FALSE,
          ),
        ),
      ),
      'delete' => array(
        'help' => 'Deletes a note',
        'file' => array('file' => 'inc', 'module' => 'noteresource'),
        'callback' => '_noteresource_delete',
        'access callback' => '_noteresource_access',
        'access arguments' => array('delete'),
        'access arguments append' => TRUE,
        'args' => array(
          array(
            'name' => 'nid',
            'type' => 'int',
            'description' => 'The id of the note to delete',
            'source' => array('path' => '0'),
            'optional' => FALSE,
          ),
        ),
      ),
      'index' => array(
        'help' => 'Retrieves a listing of notes',
        'file' => array('file' => 'inc', 'module' => 'noteresource'),
        'callback' => '_noteresource_index',
        'access callback' => 'user_access',
        'access arguments' => array('access content'),
        'access arguments append' => FALSE,
        'args' => array(
          array(
            'name' => 'page',
            'type' => 'int',
            'description' => '',
            'source' => array(
              'param' => 'page',
            ),
            'optional' => TRUE,
            'default value' => 0,
          ),
          array(
           'name' => 'parameters',
           'type' => 'array',
           'description' => '',
           'source' => 'param',
           'optional' => TRUE,
           'default value' => array(),
          ),
        ),
      ),
    ),
  );
}

```

Which is created sucessfully.

Now I have also created a `function _noteresource_create($data) { echo "hello"; exit;}` under inc file.

Now when I am accesing resouce as websitename/endpoint/resource/create and via Post and passing variable it gives me error:

**Response does not contain any data.**

And:

> Under Status 404 Not found: Could not find the controller.

Does anybody can tell me how to fix this issue?

# Answer
Added **actions** in **create** resource where POST method is using. I hope it would work for you.

```
function noteresource_services_resources() {
  return array(
    'note' => array(
      'retrieve' => array(
        'help' => 'Retrieves a note',
        'file' => array('file' => 'inc', 'module' => 'noteresource'),
        'callback' => '_noteresource_retrieve',
        'access callback' => '_noteresource_access',
        'access arguments' => array('view'),
        'access arguments append' => TRUE,
        'args' => array(
          array(
            'name' => 'id',
            'type' => 'int',
            'description' => 'The id of the note to get',
            'source' => array('path' => '0'),
            'optional' => FALSE,
          ),
        ),
      ),
      'actions' => array(
          'create' => array(
            'help' => 'Creates a note',
            'file' => array('file' => 'inc', 'module' => 'noteresource'),
            'callback' => '_noteresource_create',
            'access arguments' => array('note resource create'),
            'access arguments append' => FALSE,
            'args' => array(
              array(
                'name' => 'data',
                'type' => 'struct',
                'description' => 'The note object',
                'source' => 'data',
                'optional' => FALSE,
              ),
            ),
          ),
      ),
      'update' => array(
        'help' => 'Updates a note',
        'file' => array('file' => 'inc', 'module' => 'noteresource'),
        'callback' => '_noteresource_update',
        'access callback' => '_noteresource_access',
        'access arguments' => array('update'),
        'access arguments append' => TRUE,
        'args' => array(
          array(
            'name' => 'id',
            'type' => 'int',
            'description' => 'The id of the node to update',
            'source' => array('path' => '0'),
            'optional' => FALSE,
          ),
          array(
            'name' => 'data',
            'type' => 'struct',
            'description' => 'The note data object',
            'source' => 'data',
            'optional' => FALSE,
          ),
        ),
      ),
      'delete' => array(
        'help' => 'Deletes a note',
        'file' => array('file' => 'inc', 'module' => 'noteresource'),
        'callback' => '_noteresource_delete',
        'access callback' => '_noteresource_access',
        'access arguments' => array('delete'),
        'access arguments append' => TRUE,
        'args' => array(
          array(
            'name' => 'nid',
            'type' => 'int',
            'description' => 'The id of the note to delete',
            'source' => array('path' => '0'),
            'optional' => FALSE,
          ),
        ),
      ),
      'index' => array(
        'help' => 'Retrieves a listing of notes',
        'file' => array('file' => 'inc', 'module' => 'noteresource'),
        'callback' => '_noteresource_index',
        'access callback' => 'user_access',
        'access arguments' => array('access content'),
        'access arguments append' => FALSE,
        'args' => array(
          array(
            'name' => 'page',
            'type' => 'int',
            'description' => '',
            'source' => array(
              'param' => 'page',
            ),
            'optional' => TRUE,
            'default value' => 0,
          ),
          array(
           'name' => 'parameters',
           'type' => 'array',
           'description' => '',
           'source' => 'param',
           'optional' => TRUE,
           'default value' => array(),
          ),
        ),
      ),
    ),
  );
}

```
> 0 votes

---
Tags: services
---


title: Body class name has an ampersand

text:
# Question
Title: Body class name has an ampersand
I am styling a page in a Drupal 7 site that has the title "Weddings & Private Events" and a URL alias of `/weddings-private-events` but the body class name is `weddings-&-private-events` which is invalid in CSS See screenshot below:

Is this a bug in D7? I'm using 7.26. Is there a way for me to fix this? I want to style a page specific element without using the node id which may change on export.

# Answer
> 7 votes
It's not a D7 bug - all core code uses `drupal_html_class()`, which removes any dodgy characters (including ampersands) by running the incoming string through `drupal_clean_css_identifier()`.

Presumably your theme (or a custom/contrib module) is adding a class without sanitising it. Look for something like:

```
function MYTHEME_preprocess_html(&$vars) {
  if ($node = menu_get_object()) {
    $vars['classes_array'][] = str_replace(' ', '-', $node->title);
  }
}

```

and change it to use

```
$vars['classes_array'][] = drupal_html_class($node->title);

```

---
Tags: theming
---


# Question
Title: Get Organic Group roles of the current user
It seems a few different versions of this question exist so apologies if it seems I am repeating but I dont think I am. I am trying to use the api to get the og role(s) of the current user, not just which groups the user belongs to. I hope to able to create an array that looks like this for the current user:

```
Array
(
['Group 1'] => Array
    (
        [0] => 'OG Admin'
        [1] => 'OG Member'
    )

['Group 2'] => Array
    (
        [0] => 'OG Moderator'
        [1] => 'OG Member'
    )

['Group 3'] => Array
    (
        [0] => 'OG Member'
    )

)

```

# Answer
Here is the data structure I ended up with:

```
Array
(
// Index 0 will be site-wide rid and roles
[gid] => Array
    (
        [rid] => 'OG Role Label'
    )
)

```

Here is the code I hacked together to get it to work. I placed this code into a custom module but I can't seem to get the function to get called from the desired location. I have a file ../sites/all/themes/THEME/templates/includes/toolbar.php. The function call is inside this file but for some reason is never executed. Any ideas on how to make the function call correctly??

```
function _MYMODULE_get_user_roles($scope=ALL) {
    global $user;
    $user_roles[]=$user->roles;

    if ($scope==ALL || $scope == SITE_ONLY)
    {
        $user_roles['SITE'] = $user->roles;
        switch (true) {
            case in_array ( 'System Administrator', array_values ( $user->roles ) ) :
                //drupal_set_message ( '<pre>Load System Administrator Toolbar</pre>' );
                break;
            case in_array ( 'Site Account Admin', array_values ( $user->roles ) ) :
                //drupal_set_message ( '<pre>Load Site Account Administrator Toolbar</pre>' );
                break;
            case in_array ( 'Site Content Admin', array_values ( $user->roles ) ) :
                //drupal_set_message ( '<pre>Load Site Content Administrator Toolbar</pre>' );
                break;
            case in_array ( 'authenticated user', array_values ( $user->roles ) ) :
                //drupal_set_message ( '<pre>Load Member Toolbar</pre>' );
                break;
            default :
                //drupal_set_message ( '<pre>No Member roles found: Do Not load a toolbar</pre>' );
                break;
        }
    }
    if ($scope==ALL || $scope == OG_ONLY)
    {
        $groups=og_get_groups_by_user();
        foreach ($groups['node'] as $group )
        {
            $roles = MYLEGACYMODULE_get_user_roles($group);
            $group_string = node_load($group)->title;
            $group_string .= ' (gid: ' . $group . ')';
            $group_string .= ' as ';
            foreach ($roles as $role )
            {
                switch ($role)
                {
                    case 7:
                        $role_string = '"Group Content Manager"';
                        $role_string .= ' (rid: ' . $role . ')';
                        $user_roles[$group]=array(
                                $role=>'Group Content Manager'
                        );
                        break;
                    case 8:
                        $role_string = '"Group Account Manager"';
                        $role_string .= ' (rid: ' . $role . ')';
                        $user_roles[$group]=array(
                                $role=>'Group Account Manager'
                        );
                        break;
                    default:
                        if (empty($role))
                        {
                            /*  Note: Note that in PHP the switch statement is considered a looping structure for the purposes of continue.
                             *  continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of.
                            *   The default value is 1, thus skipping to the end of the current loop.
                            *   --http://www.php.net/manual/en/control-structures.continue.php
                            */
                            continue 2;
                        }
                        $role_string = '"Unknown Group Role"';
                        $role_string .= ' (rid: ' . $role . ')';
                        $user_roles[$group]=array($role=>'Unknown Group Role');
                        break;
                }

            }
        }

    }
    return $user_roles;
}

```
> 2 votes

---
Tags: organic-groups, users
---


# Question
Title: How can I "merge" two fields when a form is submitted?
I have a form from a unique content type which has two fields, when I submit that form, I wish the value entered in the second field was "included" in the end of the first field and then the content type saves.

Like

```
field1, value: "John"
field2, value: "Doo"

```

but when the content type is saved, this happens:

```
field1, value: "John Doo" // the space which divide the two words is required as well.
field2, value: "Doo"

```

thanks.

# Answer
> 3 votes
I would suggest you hook\_node\_presave() for this. Write this function somewhere in your custom module, just print the $node array. You would found all the fields value there that you can alter accordingly. Your code should be something like this.

```
function mymodule_node_presave($node) {
  if ($node->type == 'content type name') {
   // Append last name field value with first name field.
  }
}

```

This hook function get executed before node\_save() that will save your changes in db.

# Answer
> 1 votes
Hook\_form\_alter() would be another option. You can grab the form values in a custom submit handler. Code would look something like this:

```
function yourmodule_form_alter(&$form,&$form_state,$form_id)
{
     if($form_id == "your_node_form_id")
     {
          $form['#submit'][] = '_yourmodule_form_custom_submit_handler';
     }
}

function _yourmodule_form_custom_submit_handler($form,$form_state)
{
     //here you can grab and alter the $form_state values accordingly
}

```

---
Tags: entities, nodes, rules
---


# Question
Title: Is there any module that let (selected) users (/roles?) see the Administration pages in read-only mode?
Is there a module out there which lets us assign a permission to a role which lets a user look at the site from the perspective of an Administrator, or better, from within the permissions of any selected other role; in a view-only/read-only mode?

That would be useful to let people explore Drupal on sites with existing setup and content without having to create/clone and maintain example sites for such purposes.

(Click around in any (admin/content management) page related to the given "read-only role" without the ability to make/save changes.)

# Answer
> 1 votes
Interesting requirement.

Presumably you could assign the relevant admin permissions to the role, e.g "*access administration pages*", "*administer site configuration*" etc..

After that, you could prevent changing any settings with a `hook_form_alter`, adding the `$form['#validate']` handler to `form_set_error` for non-admin users / users of that role. You could also possibly hide the submit button with a suitable #access check e.g `#access => user_access('special permission');` on the button itself.

e.g

```
/**
 * Implements hook_form_alter
 */
function MODULE_form_alter(&$form, &$form_state, $form_id) {
  $form['#validate'][] = 'MODULE_readonly_admin_access';
}

/**
 * Custom validate callback
 */
function MODULE_readonly_admin_access(&$form, &$form_state) {
  if (path_is_admin(current_path()) && !user_access('admin write access')) {
    form_set_error(NULL, t('Operating in read-only mode.'));
  }
}

```

It would definitely need a lot of careful testing to ensure no loopholes (e.g services API access, `#limit_validation_errors` cases) - make sure all bases are covered.

# Answer
> 0 votes
You could replace the default Drupal core admin content with admin\_views, then manage permissions within the View itself.

You can also clone the pre-provided views and remove 'edit' links etc… and manage permission on access to each view-\>display using the View access UI.

---
Tags: users
---


# Question
Title: How to add a field to Views table output with hook_views_pre_render?
I have a view displaying node titles formatted as a table. In a custom module I'm using hook\_views\_pre\_execute to do do a table join and add a field to the views query. (I cannot use a regular relationship in Views to accomplish the join, because it has to be a RIGHT JOIN).

When I inspect the resulting view object with `dpm($view)` in hook\_views\_pre\_render, I can see that the objects in `$view->result` contain the string values of the node\_title, nid, and field\_myfield\_value (where field\_myfield\_value is added via the custom module).

But how do I actually display field\_myfield\_value in the view? And more specifically, how do I make it a column of the table?

# Answer
> 7 votes
To take a different approach: you could add the field through the UI as normal, and use `hook_views_query_alter()` to change the join type:

```
function MYMODULE views_query_alter(&$view, &$query) {
  if ($view->name == 'my_view' && $view->current_display == 'foo') {
    $query->table_queue['field_data_field_myfield']['join']->type = 'RIGHT';
  }
}

```

That should get you the same effect with a bit less effort.

# Answer
> 1 votes
I guess the easiest would be to add i.e. the title field again in the views ui and then in hook\_views\_post\_execute set `$row->title2` (or whatever it would be called) to the value of your field.

Alternatively, you might try to describe the join to views, add the column in the ui "normally" and "only" alter the join. (Clive was faster with that one :)

# Answer
> 0 votes
I think Clive is right about using hook\_views\_query\_alter being a little easier.

The views\_join class also lets you define what is the left\_table, left\_field, (right) table and (right) field. Perhaps you would need to do more re-building in your hook\_views\_query\_alter to get all the tables in the right place.

Considering the last part of your question "But how do I actually display field\_myfield\_value in the view?" hasn't been addressed yet, I think you might need to write a module to add the field to views. This article seems pretty straight-forward: http://www.grasmash.com/article/demystifying-views-api-developers-guide-integrating-views In it, they discuss hook\_views\_data() (adding data to a view via a custom table and extending the views\_handler\_field class to display the data.

---
Tags: 7, views
---


# Question
Title: How to return drupal's articles image upload
I am new in drupal

when I click on content\>add content I don't have the browse button to uploading image for article, maybe I removed accidentally from structure\>content type or other...

How can I see that browse button again?

# Answer
Go to Structure » Content types » Article \>\> Manage fileds

Add new field. Here is the sample screenshot
> 2 votes

---
Tags: nodes, media
---


# Question
Title: Using drush to change options of contrib module
I would like to use drush to change one of the options stored in a large options field of a contrib module configuration table.

drush vset/vget, as far as I know, only work on the options that are stored in the variables table.

Is there a way to do this using drush on the variable directly, short of retrieving the whole field (using drush sql-query), modifying it (using unix tools), and updating it (again, using drush sql-query)? It needs to be automated, as this is a frequent task.

Or can anybody suggest a different approach that is more elegant?

# Answer
Check to see if the contrib module has a modulename.drush.inc file in it. If it does, then the module provides Drush commands, and you can find out about them via `drush help --filter=modulename`.

If the command does not supply any Drush commands, the next thing to do is to open up the modulename.module and scan through the source code, and see if it has any API functions that perform the operation that you want to do. This can sometimes seem intimidating, but it's worth a shot! If you'd like to set the frobulation level of the module to 28, maybe, just maybe, you might find a line that reads `function modulename_set_frobulation_level($value) ...`. If you do, then you can call it with Drush like this:

`drush ev 'modulename_set_frobulation_level(28);'`

If you do this a lot, you could make a Bash function for it, or, better yet, create a custom Drush command and contribute it back to the contrib module. Making a custom Drush function is really easy with the drushify command.

If you are unlucky, you will not find a nice set\_frobulation\_level function; sometimes, the code you want is only available in a form submit handler. This is distressingly common in contrib modules. Rather than try to figure out how to post a fake form submit, an even better option is to just factor out the code you'd like to call, and make the modulename\_set\_frobulation\_level function yourself. Then, it's easy to create a Drush command for it, and you can contribute the whole shebang back to the contrib module when you are done, helping out the next person who travels this same road.

This might sound like a bit of work, but it's no harder than reverse-engineering the sql commands you'd need to run, and the results are much more satisfying.
> 6 votes

---
Tags: 7, drush
---


title: field widget with multiple input fields

text:
# Question
Title: field widget with multiple input fields
I need to create a custom field widget that is actually a 2 input fields group. I also need to save these values (I guess this is done through `hook_field_schema()`)

The main problem is that I'm a little bit confused about how to use `hook_field_widget_info()` and `hook_field_widget_form()` and how are these connected with the `hook_field_schema()`

Any insights / links about this? Thanks

# Answer
As well as their schema and other basic definitions, fields have

* Widgets

> Field API widgets specify how fields are displayed in edit forms. Fields of a given field type may be edited using more than one widget. In this case, the Field UI module allows the site builder to choose which widget to use. Widget types are defined by implementing hook\_field\_widget\_info().
* Formatters

> Field API formatters specify how fields are displayed when the entity to which the field is attached is displayed. Fields of a given field type may be displayed using more than one formatter. In this case, the Field UI module allows the site builder to choose which formatter to use. Field formatters are defined by implementing hook\_field\_formatter\_info().

Each field needs a widget and formatter to do anything useful, but they don't necessarily have to be implemented by the same module that implements the field. For example, you could piggyback off of one of the select widgets if that made sense for your field.

For full code examples, check out the Examples module
> 1 votes

---
Tags: 7, entities
---


# Question
Title: How can I create a very simple entity definition for Webform submissions?
I make extensive use of the Webform module and often use Views for managing the webform submissions.

I'm fairly new to the Actions/Rules/Triggers backend of Views Bulk Operations (VBO), but I'd really like to be able to use it in my submission management views.

I've written a module that accepts submission IDs from the URL like so: `mymodule/form/314/submissions/201+202+203` and generates a page with information from all the listed submissions (in this case, submissions 201, 202, and 203).

I want to use the VBO "Pass ids as arguments to a page" operation to select submissions in a my Views table, and pass their IDs to my custom page.

As far as I can tell, this isn't possible since webform submissions are not entities. So what I'm wondering is, **how can I define a very simple entity type for webform submissions**, so that I can use VBO on them?

I assume I should implement `hook_entity_info()`. I think the entity really only needs to include the submission ID in my case (the `sid` column in the `webform_submissions` db table).

I've read through the docs on defining custom entities, but can't figure out how to apply that stuff where I'm not actually wanting to create an entity type from scratch. Thanks!

# Answer
Got it working. In a custom module (`mymodule`), I implemented hook\_entity\_info() like so:

```
function mymodule_entity_info() {
  $info = array();
  $info['mm_submission'] = array(
    'label' => t('Simple Webform Submission Entity'),
    'base table' => 'webform_submissions',
    'fieldable' => FALSE,
    'entity keys' => array(
      'id' => 'sid',
      'label' => 'sid',
    ),
  );
  return $info;
}

```

This very simple entity definition was sufficient for VBO to treat my submissions as entities and pass their IDs to my custom URL.

Though I didn't need to, it should be possible to override the entity class controller and its entity functions (load, save, delete, etc) should you need to. This tutorial by Ronald Ashri was useful to me and talks more about that.

After installing my custom module, I was pleasantly surprised to see a "**Bulk operations: Webform submissions**" field magically appear in the list of available Views fields.

I didn't make any other connection between Webform submissions and my custom entity type, nor otherwise tell VBO to treat the Views results as `mm_submission` entities--somebody (Views/VBO/Webform?) just automatically made it happen; which is *awesome*.

I presume VBO knew to process the submissions as `mm_submission` entities because of the entity type `base table` attribute? Not sure without looking more closely; perhaps someone else can shed more light on that.
> 0 votes

# Answer
There is a module available called Webform Entity that does just that although it goes further and makes the submissions fieldable. From that project page:

> This module exposes webform submissions as a fieldable entity on behalf of webform and optionally provides a bundle for each of the content types for which webform functionality is enabled. This allows you to configure fields on a base form that are appended to the fields for the webform for that individual node and these fields can be exposed to views.
> 0 votes

---
Tags: webforms, views
---


title: How to query drupal timefield data

text:
# Question
Title: How to query drupal timefield data
Scenario:

We have a bunch of events, each event has a date field, and a separate time field that has a start and end value. I'm trying to build a module pulls in the next event that hasn't ended yet. Also, if there are more than one events on that day, we need to pull all of them.

My main problem is figuring out how to construct the values that I need to query that time field with, it seems to be stored is a format that I'm not familiar with, e.g. the value 4:30PM is stored as 59400. I can't find any documentation that specifies how to convert that value back and forth.

Any Drupal gurus / php gurus out there know what that conversion is?

Thanks, Neil

# Answer
> 0 votes
Think of it as "the number of seconds since the the start of the day". To get the number of hours from that:

```
59400 / 60 / 60 = 16.5

```

So 16.5 hours since the start of the day: 16:30, or 4:30PM.

If you're looking to get something meaningful out of '16.5' for display on the front end, the timefield module has a theme function:

```
$formatted = theme('timefield_formatter', array('time' => $time));

```

Or if you have the value in the field of an entity object, you could use `field_view_field()` instead. The theme function has more options, you'd need to scan through the module code to understand what these are and which you might want to use.

---
Tags: datetime, database
---


# Question
Title: Does inactive modules can make my drupal site slower?
I have some modules that Im not using and they are inactive, if I uninstall and delete those modules could I improve th performance of my site, my site is becoming very very slow, the ajax requests are slow everything is slow....

# Answer
Definitely it would slow down your site performance as realized from my personal experience. Every time drupal look for .info file and unnecessary read that, if any hook alter function is there it also get executed every time. It also checking for latest updates, unnecessary increasing headache to your system. If some js or css is using in that module, also including and evaluating by drupal bootstrap every time. It increasing overhead for module\_invoke\_all() function. At last I would say, don't think twice and get uninstalled these modules because it unnecessary increasing overhead on db and slow down your site performance. Even this is not a good practice to keep unused module in site without uninstall.

For more info see following links.

https://drupal.org/node/250783

Do non-enabled modules affect performance?

In past I also faced this issue, I just uninstalled all disabled modules and ran update.php for all my contributed modules that help me to increase site performance.
> 2 votes

# Answer
I don't understand Jance's response. He says "it won't hurt", but then says these disabled modules are sucking up resources?

Saying inactive modules don't impact performance is not completely accurate... but it certainly is less important than the number of enabled modules.

While the hooks of an inactive module with code left in sites/all/modules aren't loaded when a specific form or page is loaded, all .info files from any code active or inactive are scanned when loading the admin/modules and admin/themes. Drush also scans all directories for Drush related includes in profiles and sites... regardless of what's active. Inactive modules aren't going to cause as much of a hit to CPU and memory as an enabled module, but having unused code in sites/all/modules isn't a good thing. Best practice would be to only install modules on a test site. Never install a module on a live site just to test it. Even when uninstalled, modules can leave a lot of cruft behind that can impact performance.

Modules that were once installed, but are now inactive could create tables and define variables add to the cruft at the database layer. Even if you uninstall the module, the uninstall process relies on the developers who wrote the module to clean up after themselves. Modules that use Features often leave even more cruft behind. Disabling a Feature "module" does not remove the content types, taxonomies, fields, views, blocks, etc that it created. Even uninstalling and deleting the code doesn't always clean up after a Feature.

I realize that not everyone can afford the type of dev -\> test -\> live workflow you get with a Drupal specific host like Acquia or Pantheon or has the technical skill to run a local version of their site, but if you don't have that type of testing environment be prudent about the modules you enable then uninstall.

Alas, hindsite is 20/20... for modules you've already enabled in the past that you've decided not to use, uninstall them and remove the code from sites/all any module. This won't improve performance as much as reducing the number of modules enabled, but leaving this code certainly won't help performance or your ability to maintain the site.
> 3 votes

# Answer
It won't hurt. Depending on how many modules you have, each time a given hook is fired off, all those modules maybe jumping in with unused functions.

Also, as your not using those modules, your probably not keeping them up to date, which would cause a security risk. It's also probably sucking your php memory. All good reasons to uninstall them if you aren't using them.
> 0 votes

---
Tags: 7, ajax, installation
---


# Question
Title: Custom Module Separate Settings for Each User
I am working on a custom module. I am currently using system\_settings\_form to enter an API key and it works fine. However, I need users to be able to enter different api keys. What is the best way to do this?

# Answer
You need to create module with .install file that would help you to create custom table where you can store individual user API key. I am sharing with you some code to achieve this. It should be something like that. Rest your code will be same you just need to make some minor changes like use `return $form` instead of `return system_settings_form()`. You also need to write `hook_form_submit()` function.

**Module Name:** custom **1. custom.install**

```
/**
 * Implements hook_install().
 */
function custom_install() {
    // Create tables.
    drupal_install_schema('custom_table');
}

/**
 * Implements hook_uninstall().
 */
function custom_uninstall() {
    // Drop tables.
    drupal_uninstall_schema('custom_table');
}

/**
 * Implements hook_schema().
 */
function custom_schema() {
  $schema = array();
    $schema['custom_table'] = array(
        'description' => 'Stored user api key',
        'fields' => array(
          'id' => array(
            'type' => 'serial',
            'not null' => TRUE,
            'description' => 'Primary Key: Unique ID.',
          ),
          'api_key' => array(
            'type' => 'varchar',
            'length' => 256,
            'default' => '',
            'not null' => TRUE,
            'description' => 'Store api key',
          ),
        ),
    'primary key' => array('id'),
  );
  return $schema;
}

```

**custom.module**

```
/* Submit hook function for submission form. */
function custom_form_submit($form, &$form_state) {
  // insert your api key in your custom table using db_insert() function or you can use db_merge() for both insert/update operation.
}

```
> 2 votes

---
Tags: 7, forms
---


# Question
Title: form or content type creation interface?
I want users to insert information. I can define a complex Content type with multiple fields, restricting the kind of info user is allowed to insert (integer, text…), as well as rules… and expose it as if it were a form when user clicks on 'add new info'.

But I want more complex things to happen, for example, when user submits data.

I am confused about how to achieve that (hooks in a module?).

Moreover, I have seen many tutorials around about creating forms (which imply a lot of coding for things like defining the data types, validation...that can be easily defined in Content type creation UI). Which difference would be between 'hacking' the 'add new content type' operation and creating a brand new form?

Sorry, as you may notice I am a brand new beginner in Drupal.

# Answer
You don't usually create a custom module just to have fancy fields in a form. If it can be done with *fields*, you do it with fields (i.e. you use the content type creation UI). For data types that doesn't exist in the core (e.g. links and entity references) there is almost always a module that let you add fields of those types to a standard Drupal entity.

You only create a custom content type if you want to do a lot *more* than just capturing the data. With "more", I means such things as computing aggregates, transforming it, combining it with other data, visualizing it, etc.

My rule of thumb is: If it can be done with *fields* and contributed modules - do it with fields. If it can't be done with fields, create a custom module. And in that case, I let the custom module also manage the form and data validation (but built-in top of the Form API).

If you want do just want to interact with the creating, validation or deletion of an entity, there is a lot of good examples of what you can do in the `entity_example.module`.

For instance, to have a submit handler that does extra validation before saving, look at `function entity_example_basic_form_validate`.
> 1 votes

# Answer
If you are just looking to add new fields to a content type, then you should edit it via the UI and add fields that way. If you have another type of field you'd like to add that doesn't already exist in Drupal, you can look up modules that provide the functionality you're looking for. For example, the link module provides the ability to add link fields to your entities.

If you can't find one that gives you the field type you want you can always fork a module or start one from scratch.

I recommend watching this helpful module development tutorial before you get started. You can then use the Drupal Form API reference page to help you edit forms.
> 0 votes

---
Tags: forms
---


title: uid 1 super user - what is is for

text:
# Question
Title: uid 1 super user - what is is for
There is Drupal super user with uid = 1. I was trying to find out what is so special about this account and what activities will require this account. Is it necessary to have access to this account for Drupal page administration. I would like to know a list of thing that will require super user access. I would also like to know what is so special about this account. As far as I know there can be only one super user in Drupal.

# Answer
> 2 votes
The Drupal user with uid = 1 is created by Drupal during the installation process of Drupal. User 1 bypasses all `access callbacks` in the system by default -- he can see/do anything.

Beyond that it is a typical Drupal user. If you want to secure the "admin" or uid=1 user please refer to this documentation page: Securing user #1 on steps you can take to secure the usage of the uid=1 user.

---
Tags: users
---


# Question
Title: How to configure breakpoints and picture to use span data-picture
I have follow the documentation that appear here: Picture documentation, but I'm not able to configure the module to use the same html that appear in the examples.

This is the code from the example Page:

```
<span data-picture>
  <span data-src="http://picture7w.h011.attiks.com/sites/picture7w.h011.attiks.com/files/styles/piccustom_user_tablet_1_5x/public/field/image/38054784.jpg?itok=zyO3uMRu" data-width="1300" data-height="867"></span>
  <noscript><img typeof="foaf:Image" src="http://picture7w.h011.attiks.com/sites/picture7w.h011.attiks.com/files/styles/piccustom_user_tablet_1_5x/public/field/image/38054784.jpg?itok=zyO3uMRu" width="1300" height="867" alt="" /></noscript>
  <img alt="picture" width="1024" height="683" class="match" src="http://picture7w.h011.attiks.com/sites/picture7w.h011.attiks.com/files/styles/piccustom_user_desk_1x/public/field/image/38054784.jpg?itok=3Or90dqg">
</span>

```

Instead I get this html code:

```
<picture title="ejemplo">
  <!--[if IE 9]><video style="display: none;"><![endif]-->
  <source srcset="http://domain.new/sites/default/files/styles/verisure_breakpoints_theme_tc_mobile_1x/public/block/footer/LADRONA_en.jpg?itok=TrydhOr5 990w" media="only screen and (max-width: 767px)" sizes="(max-width: 767px)">
  <!--[if IE 9]></video><![endif]-->
  <img alt="ejemlo" title="ejemplo" src="http://domain.new/sites/default/files/styles/verisure_breakpoints_theme_tc_retina_1x/public/block/footer/LADRONA_en.jpg?itok=DPGm0iG4">
</picture>

```

Any idea how to configure the module?

Thanks

Oskar

# Answer
The demo page you've linked says it was `Submitted by admin on Thu, 04/25/2013 - 13:31`. That's over 1 year ago.

What makes you think the output you're seeing isn't correct for your current installed version of Picture? If your breakpoints are installed and configured correctly as in the documentation you have linked, then the images should be responsive.
> 0 votes

---
Tags: 7, media
---


# Question
Title: Ajax callback values not saved on submit
I added an Ajax callback to **Add to cart form** on two fields : *quantity* and a *date line item field*, because I need customers to choose the product id depending on these values (see study case if you wish more details).

Everything works fine... except that Ajax values, especially product\_id, **aren't saved in cart on form submit** :(

# Relevant parts of code

## Add to cart form alter

```
/**
* Implements hook_form_alter().
*/
function vts_commerce_form_alter(&$form, &$form_state, $form_id) {

  if (strstr($form_id, 'commerce_cart_add_to_cart_form')) {
    //line item field callback
    $form['line_item_fields']['field_date_de_d_part_line_item']['und'][0]['#ajax'] = array(
      'callback' => 'vts_commerce_liberte_addtocart',
     );
    //wrapping $form['product_id']
    $form['product_id']['#prefix']='<div id="liberte_pid">';
    $form['product_id']['#suffix']='</div>';

    // ... SOME CODE setting $options

    //overwriting native $form['quantity'] to have a select with specific options
    $form['quantity']= array(
      '#type' => 'select',
      '#title' => t('Number of participants'),
      '#default_value' =>  1,
      '#datatype'  => 'integer',
      '#size' =>  1,
      '#weight' => 45,
      '#prefix' => '<div id="qty">',
      '#suffix' => '</div>',
      '#options' => $options,
      '#ajax' => array(
        'callback' => 'vts_commerce_liberte_addtocart',
        'wrapper' => 'qty',
        'method' => 'replace',
      ),
    );
  }
}

```

## Ajax callback

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

  $commands = array();

  // ... SOME CODE setting $pid and other stuff, messages...

  //TRYING TO UPDATE PRODUCT ID with drupal_render
  $form['product_id'] = array(
    '#type' => 'select',
    '#options' => array(
       $pid => 'product title: '.$pid, // TODO retrieve product title
    ),
    '#default_value' => $pid,
    '#weight' => 0,
  );
  $commands[] = ajax_command_replace('#liberte_pid', drupal_render($form['product_id']));

  //TRYING TO UPDATE PRODUCT ID with $form_state['values']
  $form_state['values']['product_id'] = $pid;
  $form_state['rebuild'] = TRUE;

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

```

Either `$form['product_id']` and `$form_state['values']['product_id']` **are changed** by the callback, but when I submit the form, it takes the product id selected on page load **instead of the one passed through** the callback.

With or without `$form_state['rebuild'] = TRUE;` in my callback doesn't changes anything...

As an alternative (or complement), I also noticed that `product_id`'s callback is `commerce_cart_attributes_refresh_alter()`, which updates the values given to cart, but I don't know how/where to call or trigger it in the ajax process ?

# Answer
> 0 votes
So, *product\_id* was rendered but its value not passed to the `commerce_cart_add_to_cart_form`. This is how I solved it.

## Add to Cart Form Alter

```
if (strstr($form_id, 'commerce_cart_add_to_cart_form')) {

  $form['product_id']['#type']='hidden';
  $form['product_id']['#prefix']='<div id="liberte_pid">';
  $form['product_id']['#suffix']='</div>';
  //...

```

## Ajax callback

```
$form['product_id']['#value'] = array(
  $pid,
);
$commands[] = ajax_command_replace('#liberte_pid', drupal_render($form['product_id']));

```

It's quite simple once you know it : before calling `ajax_command_replace()` you don't need to rebuild the full form element, just set the wanted attribute, and `drupal_render($form['form_elt']))` will do the magic :)

---
Tags: commerce, ajax
---


title: How to add CC to a webform email?

text:
# Question
Title: How to add CC to a webform email?
I'm using Drupal 7.

Is it possible to add a CC to a webform email?

I was using

```
function theme_webform_mail_headers($variables) {
  $headers = array(
    'X-Mailer' => 'Drupal Webform (PHP/' . phpversion() . ')',
  );
  return $headers;
}

```

changing it with

```
    function MYTHEME_webform_mail_headers($variables) {
      $headers = array(
'CC' => 'ccmeail@domain.com', 'X-Mailer' => 'Drupal Webform (PHP/'. phpversion() .')',
 );
      return $headers;
    }

```

It does not work, I've cleared all the chaches and it does not add the CC. How could I add the CC?

Thanks in advance.

# Answer
It shouldn't be done in theme, but in a module (business vs presentation logic).

Don't know if it's still relevant, but this post explains how to mail to several addresses.
> 1 votes

# Answer
Just posting this for future viewers:

You can add a hook to the theme\_webform\_mail\_headers in your theme's template.php

```
function mytheme_webform_mail_headers($variables) {
    $headers = array(
    'X-Mailer' => 'Drupal Webform (PHP/' . phpversion() . ')',
    );

    $headers['cc'] = 'email@example.com';

    return $headers;
}

```
> 2 votes

# Answer
I actually patched webform\_reply\_to to work with webform-7.x-4.0-rc3 (using patch identified in Issues) and then modified it to create a Cc header field instead of Reply-To.

In order for it to work with multiple email addresses, you need to comment out the validate call in the module.

Also, email type fields won't take multiple addresses, so you need to use a textfield for your cc field on the form and use the token for that field instead of selecting a pre-defined email field.

Works well, though.
> 1 votes

---
Tags: 7, webforms
---


# Question
Title: How to allow OG admins to view private groups?
The scenario I try to achieve:

1. Groups that are not public, are hidden for all users that are not member of the group.
2. Users with the permission "Administer Organic groups permissions (Administer all groups and permissions)" should be able to view it regardless.

The OG setting for "strict node access" is enabled to prevent other users from viewing content that belongs to foreign private groups.

The problem lies with 2. Even though users with the "Admin OG permissions" permission can access /node/%/edit to modify the group entity, or even view the member list and add users to the group, viewing the group page itself is not possible nor is the group listed in the /groups view.

Is this a configuration issue or rather a bug?

# Answer
After spending some time in the debugger, I would say this is a flaw in OG.

Users allowed to administer OG permissions should be granted access to view *any group*. Solution: patched og\_node\_access() in og.module:490

*patch format:*

```
--- og.module
+++ og.module
@@ -490,6 +490,11 @@ function og_og_default_roles() {
 function og_node_access($node, $op, $account) {
   $type = is_string($node) ? $node : (is_array($node) ? $node['type'] : $node->type);

+  //   Grant access to view any OG group content if the user is allowed to administer OG permissions
+  if ($op == 'view' && user_access('administer group', $account)) {
+    return NODE_ACCESS_ALLOW;
+  }
+
   if ($op == 'create' && og_is_group_content_type('node', $type)) {
     // Save some legwork if the user has the core permission and strict node
     // access is not set.

```

The interesting bit is just this:

```
  //   Grant access to view any OG group content if the user is allowed to administer OG permissions
  if ($op == 'view' && user_access('administer group', $account)) {
    return NODE_ACCESS_ALLOW;
  }

```

---

---

The above solved the issue with OG-Admins not being able to view private groups they did not belong to. There was another issue involving views. When for example creating a list of all groups with views, the same problem occurs. In this case, creating a separate view for admins and effectively disabling node access checks for it:

> In the Advanced tab of Views UI under Query settings, select the Disable SQL rewriting checkbox

Various approaches detailed here: https://drupal.org/node/677644
> 1 votes

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


title: Events Tickets Profit for the comany

text:
# Question
Title: Events Tickets Profit for the comany
I am trying to create an event ticketing system with drupal 7 and would like to insert the company's commission to it. In simple explanation. If event planner ticket price is $x Company commission rate is 15%

The planner to choose whether the customers pay for the commission + ticket or the planner pays upfront.

Is there any module that support something like this?

# Answer
> 0 votes
If you're looking for a pct fee on top of your order, you've got a couple of options, the quick and dirty one is to create a fake tax of the percentage you want, see http://www.drupalcommerce.org/user-guide/tax-configuration, another option is to multiply the amount by 0.15 or whatever quantity on the rules event you choose.

For fixed fees you can check Commerce Fees

You've got also commerce discount and commerce coupon that do the exact opposite operation, so you can check how to add and modify stuff in the checkout, if you're looking for a more advanced solution.

---
Tags: commerce
---


# Question
Title: Can't get workflow to show up on D7 Menus
The workflow menu doesn't seem to show in the menu system in Drupal 7. The only place that I see "workflow" is in the configuration section, and it appears as a section called "workflow" and it only has Rules in it!

This is the exact same problem on the documentation (https://drupal.org/node/872876), however that did not help!

I've installed workflow UI and workflow API, Rules and Rules UI, flushed all caches, uninstalled rules and workflow modules, reinstalled, tried various combinations of the modules, etc. Still no workflow option in the configuration menu.

I must be missing something stupid because lots of people are using workflow...

# Answer
> 0 votes
Make sure your account has "Administer workflow" permission.

# Answer
> 0 votes
I'm having this same problem. The issue is the implementation of `hook_permission()` in the 7.x-2.3 version. You can update to a beta or you can edit that hook in the Workflow module.

Currently, workflow's menu access looks for "administer workflow" when the permission is "administer workflows"; the access is always denied because nobody has the "administer workflow" permission, which cannot be assigned from the UI since no module defines it.

---
Tags: 7, workflows
---


title: Where do I input drush commands?

text:
# Question
Title: Where do I input drush commands?
I am developing a Drupal 6.28 core website from a PC and was wondering where I would make `drush` commands to update the Drupal core to 7.

I am new to Drupal and PC Development, but I assume that it is a terminal command? Can I use the Windows Command Prompt? What directory would I need to be in to successfully run `drush pm-update projects drupal-7`.

# Answer
If the server (where the site lives) is not this same Windows machine, you can use a tool like Putty: http://www.putty.org/ to SSH to that box, and the putty window will serve as "terminal" from which you can use unix commands (like drush).
> 1 votes

# Answer
Drush core does not support upgrading from Drupal 6 to Drupal 7 with any of the built-in commands pm-update only supports minor updates. You'll need the Drush Site Upgrade command to advance to the next major version.

Note that this command has not been tested on Windows; it would probably be safer to run the command in a Linux environment. Use a virtual machine (e.g. virtualbox) if you do not have a dedicated Linux environment.

Doing a major upgrade from Drupal 6 to Drupal 7 is a serious endevour; the Drush site-upgrade command will help you walk through the process, but it does not do all of the work for you. The process isn't too hard if it goes smoothly, but you may run into contrib bugs that complicate the process. An alternative method to upgrade would be to just make an equivalent Drupal 7 site from scratch, and then use drupal-to-drupal migration to move your content over.

Finally, to answer your specific question, there are a number of ways to specify the Drupal site that you would like Drush to operate on, but the easiest and most straightforward way would be to cd to the directory that contains your settings.php file (often `sites/default`). You will also need to set up an alias (for your target Drupal site) if you use the Drush site-upgrade command; see the file examples.aliases.drushrc.php for instructions on how to do that.
> 3 votes

# Answer
Drush has a page on it's website about writing custom drush commands (here)

Another option would be to just write a shell script of the drush commands you want to run to execute a full update (such as disabling modules, updating modules, etc.)
> 0 votes

---
Tags: drush
---


title: How to make summary report views

text:
# Question
Title: How to make summary report views
im trying to make a report in a view from other view(a table). i've tried view calculator and it's not what i want.

i want it like this :
Total people below 20 years old : xxx
Total Male : xxx
Total Female : xxx
Total people that have *** : xxx

# Answer
Can you make 1 View per *report* you want. Using Views `aggregates` and filter conditions you should be able to generate the values you want.

Then make 1 master View and use `views attachments` to build your single massive report page by showing all these reports in that page view.
> 0 votes

---
Tags: views
---


# Question
Title: #attached css in render array not working
I am trying to render a block with a custom css with it. I have obtained a render array for the block and now I add to it:

```
$render_array['#attached']['css'] = array(
   base_path() . 'path/to/module/css/abcd.css',
);

return drupal_render($render_array);

```

The path to the css file is correct, I am able to access it in the browser. However, the css styles are not applied to the block. What are the proper steps to take now to debug this problem?

Thanks in advance!

Edit: I have tried out Option 1, this is the result of dpm($block) in in the hook\_block\_view.

```
subject (String, 15 characters ) Correct subject
content (Array, 2 elements)

  #markup (String, 45 characters ) <span class="testtest"> Red text </span>
  #attached (Array, 1 element)
    css (Array, 1 element)
        0 (String, 58 characters ) /path/to/css

```

And the contents in the css file:

```
.testtest {
  color: #C43C55;
}

```

Could it be a site configuration? Thanks!

# Answer
You are saying, you have already rendered content array for the block and after that you are adding css to this block. If block array is already rendered then where you are applying this css because array is already rendered for you. Now you have two options here.

**Option 1:** Add custom CSS to your block It should be something like this.

```
function foo_block_view($delta = '')
{
  if($delta == 'foo_delta')
  {
    $block = array
    (
      'subject' => t('Foo title'),
      'content' => array
      (
        '#markup' => '<p>' . t('Lorem ipsum text.') . '</p>',
        '#attached' => array
        (
           'css' => array('path/to/my.css'),
        ),
      ),
    );
    return $block;
  }
}

```

**Option 2:** Add custom CSS to your page before this block rendered **(Not a great option for your case)**.

```
$content = array();
$content['#attached']['css'] = array(
  $path . 'my.css' => array(
      'group' => CSS_AGGREGATE_THEME,
      'weight' => 999
    ),
  );
return $content;

```
> 0 votes

---
Tags: theming
---


title: display suite modifications

text:
# Question
Title: display suite modifications
I am using Display Suite for the first time and experimenting with the 2-columns layout.

What I didn't expect is that the module will override my existing node layout.

Can anyone tell me if I can use my 2-column layout in combination with my existing layout? This is especially important as I have information which needs to be displays outside of columns above and below it.

Thanks

# Answer
i will advice you to use "Fluid two column stacked" layout. This layout provides a header region, then two left and right columns and one footer region. So you can display your data by putting appropriate fields in the right regions. Also if you don't have any fields in any region that region will simply not display and if you don't have data in the left column then the right column will shift to the left side. Hope this solves your problem.
> 0 votes

---
Tags: display-suite
---


# Question
Title: How to create a views page of discounted products list?
I'am using commerce discount module in commerce kickstart 2.11 And need to create a page with a list of dicounted products using views filter and/or search API. I've tryed without any success. Please Anyone, any help to do this.

# Answer
> 0 votes
I'm affraid there's no working solution right now.

you can see and follow List all discounted products in commerce discount issue list for further information and workarounds.

---
Tags: search, commerce, views
---


# Question
Title: Features code changes overriding automatically
I have a panels page in Features but as soon as i change the Features code, it automatically overrides the DB, this means that i don't get to see the "Overridden" state grey button, but always the normal "Default" state is shown and the changes are automatically shown on the web page.

The features should not change automatically the code, but only after i choose to override them.

Any ideas why this is happening?

I thought that was an UUID problem, but after removing the UUID module, the issue still persists.

# Answer
No, this is how Features work. If your feature is in `Default` state, code change will cause direct effect on the components (there are some exceptions when clear cache is required). This is actually one of the biggest points and benefits of features, you can easily deploy updated code without any further required action.

Maybe there is a problem with your workflow, you should create you features on you Dev environment (configurations etc), then export them and deploy to Stage/Prod. It is not a good practice to directly change the configuration of components on Stage/Prod environments, you should always do your changes on Dev, then recreate the feature and deploy.
> 1 votes

---
Tags: features
---


# Question
Title: D7 - How to get mlid value from path of menu item
Quick question. How to get mlid value from path of menu item. There is a function called menu\_link\_load() but it requires an mlid value, but I need something exacly the same function using path.

# Answer
> 6 votes
There's no build-in function for this. You can use menu\_tree\_all\_data(), but it returns all the menu. After that you can compare in loops your path with the paths returend. But there is a better and easier answer. Here it is:

```
$mlid = array();
$q = 'your-path';
$menu_info = db_select('menu_links' , 'ml')
  ->condition('ml.link_path' , $q)
  ->fields('ml', array('mlid', 'plid'))
  ->execute()
  ->fetchAll();

foreach($menu_info as $key => $value) {
  $mlid[] = $menu_info[$key]->mlid;
}

```

# Answer
> -2 votes
Try using menu\_get\_item(), this should load your menu item directly from your path.

---
Tags: routes, uri
---


title: Restrict people from sites

text:
# Question
Title: Restrict people from sites
Is there any module that can restrict people from accessing certain pages when they are not logged in?

# Answer
> 2 votes
There's a contrib module, contentaccess which is fairly easy to use and permissions can be managed on a node by node basis.

There's a good article about Drupal content access control here

---
Tags: 7
---


# Question
Title: How do I hide buttons like the "delete" one in a node form?
Consider I created a CCK node called *assignment*, and I am adding assignments with that.

There is a field called "published" with a check box. If the assignment is published, then it should not be deleted.

My problem is how I can hide the "delete" button if the assignment is published. By using prefix and suffix and using `display: none;` in `hook_form_alter()` will work, but it is not the secured way. I need something in the Drupal way.

# Answer
> 1 votes
We can use the below to hide the buttons in form alter.

> unset($form\['buttons'\]\['delete'\]);

# Answer
> 2 votes
You can use hook\_access().
Super simple example will hide button "Delete" automaticaly and disallow deletion of some nodes in any other places in Drupal.

Important note:

> The administrative account (user ID #1) always passes any access check, so this hook is not called in that case.

```
function MYMODULE_access($op, $node, $account) {
   if ($op == 'delete') {
      if ($node->something != 'something') {
          return FALSE;
      }
   }
}

```

For Drupal 7 there is hook\_node\_access() for this stuff.

# Answer
> 0 votes
In Drupal 7 each content type has a permission (on the permissions page at yourdomain.com/admin/people/permissions) called "Delete own content" which you can use as long as the user isn't an administrator because admins have all permissions enabled by default.

If you need to disable it for the admin user as well there's a module called Jammer.

# Answer
> 0 votes
use unset($form\['actions'\]\['delete'\]);

---
Tags: forms
---


# Question
Title: Can a drupal admin user get FTP rights to a godaddy server
I have a Drupal 7.28 site running on a godaddy server. I just recently copied it from my local box to godaddy's. I can't use the function "add module by using URL" method now. I see the message that I must have FTP rights. I do have FTP rights when logged in to godaddy through their interface, but wondering if a drupal admin user can be given FTP rights and then be able to add modules, etc through URL's at the "Add module" page? How does everyone deal with this? Do you just manually FTP modules to the server and then go back to drupal's interface and enable? Or do you use Drush to install modules remotely? Just wondering how everyone deals with this... Is it best practice to not make a site live until all modules are installed locally and then move the site to a remote server?

Thanks for the help.

Dave N

# Answer
I don't use Drush. But using the install module function at admin/modules/install I have installed modules before when live on a GoDaddy server.

I don't know what is causing the problem, I would maybe contact their support. But certainly it's doable, and I've done it in the past.

However depending on the module I would stay clear of installing on a live server, particularly if you are on shared hosting environment with GoDaddy (contrary to a lot of people I actually find them okay and the best solution at that price for hosting a site).

However whilst you'll find installing modules okay you may find you run into problems enabling them with PHP memory limits, or other server issues. Generally doing dev on a local machine if you have hosting like GoDaddy is going to be faster, more flexible, and generally easier.
> 1 votes

---
Tags: 7, files
---


# Question
Title: Is there a way to cancel a node deletion using rules?
I have a node type that represents a phone call. The user can schedule a call, then record notes about the call. I want to give the user the ability to deleted these call nodes, but only if the call has not happened yet. Is there a way to review a call node (using rules) the cancel the delete operation if specific criteria fail?

This could also be used to make an "Are you sure?" option for node deletes.

# Answer
> 1 votes
You should be able to do this via the conditions field in the rules module. Unsure how to create an 'are you sure' option, but you could certainly stop them from doing it with rules.

There might be better solutions, but here's what I'd do if I wanted to achieve what you are doing.

Install Flags and Rules module. Create flag to appear on Content Type 'Phone call' called 'Delete this call'.

In rules create two rules. One called Delete call, the other called 'display message about unable to delete call'.

First rule:

Triggered on action - node is flagged Conditions - Entity has field call date/time (whatever the field is called) \- Data comparison - select the date/time field, then is greater than +1 minute.

Then action - unpublish content

For the second rule do the same but change second condition to less than - 1 minute. Then as the action do 'display message on the site' and select message as 'Unable to delete calls that have passed'.

That should work.

---
Tags: nodes, rules
---


# Question
Title: Location of data directories under AEgir on Debian
I've got an out-of-the-box AEgir installation (Apache2, MySQL) running on Debian on a VirtualBox machine. I'd like to move the site data directories off the virtual drive onto my host's drive and use VirtualBox's shared folders to access them.

Which directories do I need to move?

`/var/aegir/platforms` is already on the host.

`/var/lib/mysql` holds the sites, so I will move that.

`/var/aegir/clients` would also need to be moved.

Are there any others?

# Answer
`/var/aegir/config` and `/var/aegir/backups`

Or you could just move the entire /var/aegir/ tree
> 1 votes

---
Tags: backups, aegir
---


# Question
Title: In form alter change the allowed value list programatically of select box defined using admin content type
I have added a select list field using admin ui in a content type and I want to alter allowed value list and fill dynamically in form alter in drupal 7

# Answer
> 1 votes
I think last solution won't work because drupal has a mechanism to verify between allowed value and submitted value for field type list. Please see here for more information, https://api.drupal.org/api/drupal/modules%21field%21modules%21list%21list.module/7

I found below solution.Please replace field name with yours,

```
function test_form_node_gallery_item_node_form_alter(&$form, &$form_state, $form_id) {
  $options = system_region_list('commons_origins', $show = REGIONS_ALL);
  $all_fields_all = field_info_fields();
  $all_fields_all['field_region_list']['settings']['allowed_values'] = $options;
  field_update_field($all_fields_all['field_region_list']);
  $options = system_region_list('commons_origins', $show = REGIONS_ALL);
  $form['field_region_list']['und']['#options'] = $options;
}

```

It will work like a charm :)

# Answer
> 0 votes
After little bit googling, you can easily get answer of this question. Any how, you need to execute this with **#after\_build**, something like following code.

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

function mymodule_after_build($form, &$form_state) {
  $form['your_field_name']['value']['#options'] = array("Allowed options value");
  return $form;
}

```

More info: https://drupal.org/node/726282

# Answer
> 0 votes
You have to install Content Construction Kit (CCK) module. After installing this module you get a text field for Allowed value function in field setting of desired field. Put the function name here to get country list. Also put following function in a module. You may have to modify query as per your requirement. After doing all these thing you will able to get country list in that field.

```
function _get_country_list(){
    $country = array();
    $query = db_select('country', 'c');
    $query->fields('c', array('country_name','country_id'));
    $result = $query->execute();
    if ($result) {
        while ($row = $result->fetchObject()) {
            $country[$row->country_id] = t($row->country_name);
        }
    }
    return $country;
}

```

---
Tags: 7, forms
---


# Question
Title: Small problem with Facebook Autopost module / Facebook App
I have installed the Facebook Autopost module after setting up my Facebook App. When I add a new content, my rule should post it to facebook, however I get the following message:

Facebook SDK threw an error: OAuthException (#200) The user hasn't authorized the application to perform this action

Do you know what I have or haven't done correctly and how I could resolve this? I think it's something to do with permissions or something in my Facebook App?

Thanks

# Answer
I managed to fix this by setting appropriate permissions for each role under /admin/config/services/fbpermissions
> 1 votes

---
Tags: rules, social-network
---


# Question
Title: How do I automatically remove spaces from a path in the blog module
Some places on the site are correct e.g. http://groundhogresearch.com/blogs/bob-schweickert-jr but the blog module block show this path http://groundhogresearch.com/blogs/Bob%20Schweickert%20Jr. which of course can't be found

# Answer
Using Pathauto you can replace spaces with a character of your choice (and do a lot of other stuff too), like for example a dash. Once you have enabled the module go to `admin/config/search/path/settings` and start configuring the module.
> 1 votes

# Answer
As you have already installed PathAuto moduel, Navigate to `admin/config/search/path/settings` and change the `Word separator` for your URL.
> 0 votes

# Answer
You can use Pathauto to configure that kind of behaviour.
> -1 votes

---
Tags: nodes
---


# Question
Title: Override user/%user page callback for a role
I have done this by altering the 'page callback' for the path and then checking for the user role in the callback function. I am not sure if this is the best way to go about it.

```
function mymodule_hook_alter(&$items) {
  // change callback for user view page to our dashboard function
  $items['user/%user']['page callback'] = '_client_dashboard';
}

/**
 * Callback function for menu item user/%
 */
function _client_dashboard($account) {
  global $user;
  // since we override user.module page callback for user/%user
  // perform default function for users without client role
  if(!in_array('client', $user->roles)) {
    // return the function used by user.module passing in account
    return user_view_page($account);
  }
  return t('Dashboard');
}

```

I know you cannot have logic in hook\_menu\_alter since it's only called when caches cleared and stored in routing table.

# Answer
The approach that you took is fine. It's one of the ways that you can control which page you have to show depending on (this case) the role.

Tip: take in consideration if "client" is going to be always the role allowed to see that page. If that could change in the future (add more roles or change to other), try to make it configurable.
> 1 votes

---
Tags: routes
---


# Question
Title: Dependent Dropdown based on Database Queries
I've been working through the Drupal 7 AJAX form examples in the Examples module, and am trying to set up a dependent dropdown form element with 2 select lists populated from the database.

Basically, I have Select called Specialties, that pulls a list of items, and a second Select called Physicians—which should be populated with Physicians tagged (via Node Reference field) with the chosen specialty. So, for example, the end user selects "Back" from the Specialties select list, and the second should populate with a list of the 3 physicians containing this Node Reference.

From what I can tell, both queries are returning the right types of nodes, and if i place a condition in the Physicians query to hard-code the specialty field:

```
->condition('field_specialty_nodereference_nid', '90')

```

it populates the second list with all doctors tagged with that nodeference.

What I am struggling with is how to make that condition dynamic, so a value from the first select is passed through to the second on change. Thank you in advance for any help you can provide.

Here is my code:

```
<?php

function docappt_states_form($form, &$form_state) {

// Grab the list of specialties from the DB

  $query = db_select('node', 'n')
  ->fields('n', array('nid','title'))
  ->condition('type', 'specialty')
  ->orderBy('title', 'ASC');
  $results = $query->execute()->fetchALL();

  //define rows
  $specialtylist = array();
  foreach ($results as $result) {
      $specialtylist[$result->nid] = $result->title;
  }

// Let's call some docs by specialty reference
  $query = db_select('node', 'n');
  $query->join('field_data_field_specialty_nodereference', 'specnr', 'n.nid = specnr.entity_id');
  $query
  ->fields('n', array('nid','title'))
  ->fields('specnr', array('field_specialty_nodereference_nid', 'entity_id'))
  ->condition('type', 'physician_profile');
  $docresults = $query->execute()->fetchALL();

  //define rows
  $docfoptions = array();
  foreach ($docresults as $docresult) {
      $docfoptions[$docresult->nid] = $docresult->title;
  }

  $specialties = isset($form_state['values']['specialties']) ? $form_state['values']['specialties'] : key($specialtylist);
  $form['specialties'] = array(
    '#type' => 'select',
    '#title' => 'Specialties',
    '#options' => array(
      0 => t('- Select -')) + $specialtylist,
    '#default_value' => isset($form_state['values']['specialties']) ? $form_state['values']['specialties'] : 0,
    '#ajax' => array(
        'callback' => 'docappt_dependent_dropdown_callback',
        'wrapper' => 'filtered_doc_list',
        'event' => 'change',
        'method' => 'replace',
        ),
    );
  $filtereddoc = isset($form_state['values']['filtereddoc']) ? $form_state['values']['filtereddoc'] : key($docfoptions);
  $form['filtereddoc'] = array(
    '#type' => 'select',
    '#title' => $specialtylist[$specialties] . ' ' . t('Doctors'),
    '#prefix' => '<div id="filtered_doc_list">',
    '#suffix' => '</div>',
    '#options' => $docfoptions,
    );

  return $form;
}

function docappt_dependent_dropdown_callback($form, $form_state) {
  return $form['filtereddoc'];
}

```

# Answer
> 0 votes
Just a follow up...this was fixed by modifying the second query as follows:

Change:

```
->condition('type', 'physician_profile');
  $docresults = $query->execute()->fetchALL();

```

to:

```
->condition('type', 'physician_profile');
  if ( !empty($form_state['values']) && !empty($form_state['values']['specialties']) ) {
     $query->condition('field_specialty_nodereference_nid', $form_state['values']['specialties']);
  }
  $docresults = $query->execute()->fetchALL();

```

Thanks to drupal.org user nevets for the solve.

# Answer
> 0 votes
use FF or Chromes `console.log` function and be sure your Ajax is being called properly. Or use `dd()` from the devel module to log whats going on when the `change` event or other JS actions are called.

---
Tags: forms, database
---


# Question
Title: how to use a submit handler which is in an .inc file
I am adding a submit handler to the drupal commerce submit form:

```

module_load_include('inc', 'my_module', 'cim_profile');
$form['buttons']['continue']['#submit'][] = 'my_module_create_cim_profile';

```

The submit handler is located in a .inc file. I assumed that the code above would load the .inc file to be used by the submit, but that doesn't seem to be the case, I keep getting an error that the file isn't found. When I tested the module include with

```
 $inc = module_load_include('inc', 'my_module', 'cim_profile');
dpm($inc);
```

it did print out the path to the .inc file, so I know it was located.

How can I load my .inc in so that it is available for the submit handler?

# Answer
You want `form_load_include()` instead:

> Ensures an include file is loaded whenever the form is processed.
>
> ...
>
> Use this function instead of module\_load\_include() from inside a form constructor or any form processing logic as it ensures that the include file is loaded whenever the form is processed. In contrast to using module\_load\_include() directly, form\_load\_include() makes sure the include file is correctly loaded also if the form is cached.
> 7 votes

---
Tags: 7, forms
---


# Question
Title: How to build a block on form submission?
I know how to build a block using these functions :

```
hook_block_info()
hook_block_configure()
hook_block_save()
hook_block_view()

```

But on a form submission a few information is saved into DB and based on those information one block must be created. how do I can build a block in that way?

# Answer
> 1 votes
I will encourage you to look at bean contributed module. Using this you can create **block types** whose instances can be created using bean\_create function.

Example snippet:

```
$values = array(
  'delta' => 'test_bean',
  'label' => t('Test Bean'),
  'title' => t('Test Bean'),
  'type' => some_block_type_that_you_will_create_through_UI,
  'view_mode' => 'default',
  'data' => array(
    'test_boolean' => FALSE,
    'test_string' => t('New String'),
    'test_array' => array(
      'test_array_1' => 'new_value',
    ),
  ),
);

$bean = bean_create($values);

```

The bean content (block) can then be placed around the site just like any other block.

---
Tags: 7, blocks, forms
---


title: when the hook_block_info is get called?

text:
# Question
Title: when the hook_block_info is get called?
when

```
hook_block_info()
hook_block_configure()
hook_block_save()
hook_block_view()

```

are get called? is it possible to call these hooks manually in a module?

# Answer
> 2 votes
From the comments, I think you're confusing things a bit. There are two types of block:

**Custom**

the ones you create through the UI. The content for these is stored in the `block_custom` table.

**Programatically defined**

the ones that Drupal auto-discovers for modules that implement `hook_block_info()`. The content for these is defined in `hook_block_view()`, and is built on-the-fly, so to speak. The content can be cached, but when that cache is invalidated the implementation of `hook_block_view()` will be responsible for re-building it. Drupal doesn't store this content anywhere on your behalf.

You can use either type for your needs. If you want to use custom blocks there's a good approach here.

If you want to use the hooks, the approach should be like this (this assumes you have a data table called `my_table` that you've populated with the necessary content for the block):

```
function MYMODULE_block_info() {
  // Get identifiers for all your custom blocks.
  $deltas = db_query('SELECT delta FROM {my_table}')->fetchCol();
  $blocks = array();

  foreach ($deltas as $delta) {
    $blocks[$delta] = array( /* Block definition */ );
  }

  return $blocks;
}

function MYMODULE_block_view($delta = '') {
  $block = array();

  if (!empty($delta)) {
    // Get your custom data for this delta
    $data = db_query('SELECT * FROM {my_table} WHERE delta = :delta', array(':delta' => $delta))->fetchObject();

    // And populate the block with it.
    $block['subject'] = $data->title;
    $block['content'] = $data->content;
  }

  return $block;
}

```

Obviously that's a trivial example and you'll want to add error checking and the like, but it should get you started. Note that you won't be able to have a temporary table as such with this method, your data will need to persist so it can be re-queried when the time comes.

---
Tags: 7, hooks, blocks
---


title: Clear varnish cache for a specific node

text:
# Question
Title: Clear varnish cache for a specific node
I am populating one of the node fields making third party api call. Since the data from api is supposed to change frequently mainly on node view. My question is, is it possible to clear caching for a specific node in varnish.

# Answer
> 2 votes
If you are using the Varnish HTTP Accelerator Integration module, you can use the varnish\_expire\_cache() function, that accepts specifics paths like nodes or could be for other paths too.

---
Tags: proxies
---