# Question
Title: ajax error with autocomplete widgets, field collection and content type created through api in module
I'm doing something wrong when configuring the autocomplete field in my content type.

Trying to use it results in a popup with the following message:

> ```
> An AJAX HTTP error occurred.
> HTTP Result Code: 200
> Debugging information follows.
> Path: http://volley3.localhost:8082/autocomplete_widgets/field_collection_item/spelersfiche_vraagantwoord/spelersfiche_va_vraag
> StatusText: OK
> ResponseText: <?php{"Naam":"\u003Cdiv class=\u0022reference-autocomplete\u0022\u003ENaam\u003C\u002Fdiv\u003E"}
>
> ```

When i look with firebug, the request being made is actualy:

> http://volley3.localhost:8082/autocomplete\_widgets/field\_collection\_item/spelersfiche\_vraagantwoord/spelersfiche\_va\_vraag/n

(with 'n' being the contents of the autocomplete box)

This returns the same response as the popup mentions.

The code from the module which i used to create the content type is as follows:

```
<?php
function spelersfiche_install() {
    $t = get_t();

    $spelersfiche = array(
        'type' => 'spelersfiche',
        'name' => $t('Spelersfiche'),
        'base' => 'node_content',
        'description' => $t('spelersfiche'),
        'title_label' => $t('title'),
        'custom' => TRUE
    );

    $content_type = node_type_set_defaults($spelersfiche);

    node_type_save($content_type);

    foreach (_spelersfiche_installed_fields() as $field) {
        field_create_field($field);
    }

    foreach (_spelersfiche_installed_instances() as $instance) {
        field_create_instance($instance);
    }

    node_types_rebuild();
    menu_rebuild();
}

function spelersfiche_uninstall() {
    // http://api.drupal.org/api/function/db_query/7
    $sql = 'SELECT nid FROM {node} n WHERE n.type = :type';
    $result = db_query($sql, array(':type' => 'spelersfiche'));
    $nids = array();
    foreach ($result as $row) {
        $nids[] = $row->nid;
    }

    // http://api.drupal.org/api/function/node_delete_multiple/7
    node_delete_multiple($nids);

    // http://api.drupal.org/api/function/field_delete_field/7
    foreach (array_keys(_spelersfiche_installed_fields()) as $field) {
        field_delete_field($field);
    }

    // http://api.drupal.org/api/function/field_delete_field/7
    $instances = field_info_instances('node', '_spelersfiche');
    foreach ($instances as $instance_name => $instance) {
        field_delete_instance($instance);
    }

    // http://api.drupal.org/api/function/node_type_delete/7
    node_type_delete('spelersfiche');

    // http://api.drupal.org/api/function/field_purge_batch/7
    field_purge_batch(1000);
}

function _spelersfiche_installed_fields() {
    $t = get_t();

    return array(
        'spelersfiche_va_vraag' => array(
            'field_name' => 'spelersfiche_va_vraag',
            'cardinality' => '1',
            'type' => 'text',
            'module' => 'text',
            'settings' => array(
                'max_length' => '255',
            )
        ),
        'spelersfiche_va_antwoord' => array(
            'field_name' => 'spelersfiche_va_antwoord',
            'cardinality' => '1',
            'type' => 'text',
            'settings' => array(
                'max_length' => '255',
            )
        ),
        'spelersfiche_vraagantwoord' => array(
            'field_name' => 'spelersfiche_vraagantwoord',
            'cardinality' => '-1',
            'type' => 'field_collection',
        )
    );
}

function _spelersfiche_installed_instances() {
    $t = get_t();

    return array(
        'spelersfiche_va_vraag' => array(
            'field_name' => 'spelersfiche_va_vraag',
            'label' => $t('vraag'),
            'entity_type' => 'field_collection_item',
            'bundle' => 'spelersfiche_vraagantwoord',
            'settings' => array(
                'text_processing' => '0',
                'user_register_form' => FALSE,
            ),
            'widget' => array(
                'settings' => array(
                    'autocomplete_case' => '1',
                    'autocomplete_match' => 'contains',
                    'size' => '60',
                ),
                'type' => 'autocomplete_widgets_flddata',
                'weight' => '1',
            ),
            'display' => array(
                'default' => array(
                    'label' => 'hidden',
                    'type' => 'text_default',
                ),
            )
        ),
        'spelersfiche_va_antwoord' => array(
            'field_name' => 'spelersfiche_va_antwoord',
            'label' => $t('antwoord'),
            'entity_type' => 'field_collection_item',
            'bundle' => 'spelersfiche_vraagantwoord',
            'widget' => array(
                'type' => 'text_textfield',
            ),
            'display' => array(
                'default' => array(
                    'label' => 'hidden',
                    'type' => 'text_default',
                ),
            )
        ),
        'spelersfiche_vraagantwoord' => array(
            'field_name' => 'spelersfiche_vraagantwoord',
            'entity_type' => 'node',
            'bundle' => 'spelersfiche',
            'display' => array(
                'default' => array(
                    'label' => 'above',
                    'module' => 'field_collection',
                    'settings' => array(
                        'add' => 'Add',
                        'delete' => 'Delete',
                        'description' => TRUE,
                        'edit' => 'Edit',
                        'view_mode' => 'full',
                    ),
                    'type' => 'field_collection_view',
                    'weight' => 1,
                ),
                'teaser' => array(
                    'label' => 'above',
                    'settings' => array(),
                    'type' => 'hidden',
                    'weight' => 0,
                ),
            ),
            'widget' => array(
                'type' => 'field_collection_embed',
            )
        )
    );
}

```

So basicaly it's a content type which has a field-collection field. The field collection contains 2 textfields of which i want the first one to be an autocomplete for the existing values but with possibility to add new items.

Serving as a question - answer input where the questions are reusable.

My guess would be that the `<?php` at the front of the response is making the response an invalid json object,

dependent modules used:

* Autocomplete Widgets
* Field collection

Any help is welcome.

# Answer
I discovered what the problem was.

I had carriage return and new line at the end of my lines instead of just a new line. Apparantly this causes the interface to have problems correctly closing and opening php code tags.

Because of this the answer from the other modules' ajax-call wasn't a valid json format anymore.
> 2 votes

---
Tags: nodes, entities, ajax
---


# Question
Title: Remove core and contrib. modules css files
I would like to prevent several contributed modules from using their own css files. Constantly having to reset their css and then apply your own is a waste of bandwidth IMO.

I tried this out with nice\_menus and it didn't seem to do anything.

Placed in template.php

```
    function phptemplate_variables($hook, $vars) {
        $css = drupal_add_css();

        $rm[] = drupal_get_path('module','nice_menus').'/nice_menus.css';
        $rm[] = drupal_get_path('module','nice_menus').'/nice_menus_default.css';

        foreach ($rm as $key => $value) {
            unset($css['all']['module'][$value]);
        }

        $vars['styles'] = drupal_get_css($css);
    }

```

# Answer
I think the function should be named MYTHEME\_preprocess\_page. Though a more common method is to add

```
stylesheets[all][] = nice_menus.css

```

to your theme's .info file. nice\_menus.css will be replaced by the one provided by your theme, or suppressed entirely if your theme doesn't contain this file.
> 2 votes

# Answer
For Drupal 7, use the following code.

```
function ko_css_alter(&$css) {
  if (isset($css['sites/all/modules/contrib/module/file.css'])) {
    unset($css['sites/all/modules/contrib/module/file.css']);
  }
}

```
> 0 votes

---
Tags: 7
---


title: Message + add class

text:
# Question
Title: Message + add class
i need to add another class to message div. That class must be the name of the module that creates the message.

Example: A new mail is added via "Simple suscription" module. Then the message div should be "div.error.simple\_suscription"

I need this since i have, contact/comment form within #main, and the #footer has a form for newsletter suscrptions. Plus i'm making images for the messages.

Thanks for your time.

# Answer
> 2 votes
as described here you can add your classes to message div:

```
drupal_set_message(t('Something horrible just happened.'),'error simple_suscription');

```

# Answer
> 2 votes
The theme function that handles the HTML output for system messages is theme\_status\_messages()

Unfortunately, the API function that modules use to set status messages, drupal\_set\_message(), does not collect any information about where the messages originate. Thus, there is no way to add module-specific classes to a system message when it is themed. The only option is to add the class when the message is created via the $type variable in drupal\_set\_message().

I do not see any reasonable solution if you are hoping to use this technique for all messages on a site and/or messages from core or contrib modules.

---
Tags: 7, theming
---


# Question
Title: Show certain content to roles based on taxonomy terms
I am trying to personalize the viewing experience for users on a site. I'm trying to figure out how to create a view that will show content tagged with taxonomy term 'a\_term' to users with the role 'a\_role'. I want to tag all of my content with these different tags so that users with 'b\_role' will see content tagged with 'b\_term', 'c\_role' -\> 'c\_term', etc...

Note: these are example names for roles/terms - there will be no naming convention like this.

# Answer
Have you taken a look at Taxonomy Access? It allows you to set access control for roles based on taxonomy terms.

EDIT: Ignore the above dumb reply and feel free to downvote.

I think you could do this by creating a custom contextual filter in Views. Your contextual filter would look at the current user and decide which taxonomy terms ids to return.

If you are using Drupal 7 you could tag the users themselves with the same terms as a way to store which terms are associated with which users. Otherwise you might need to create a separate table to store the user to taxonomy association.
> 1 votes

---
Tags: 7, views, taxonomy-terms, users
---


# Question
Title: Xdebug: What Drupal values for "Project URL" & "Index File" will NetBeans accept for a new Configuration?
I just slept at a Holiday Inn last night and watched this Vimeo Tut on Xdebug. I'm experiencing trouble with a Views plugin and wish to "step into the Matrix" to find where the error is occurring.

In NetBeans each project is set up with a default URL and template file. These are set from `File >> Project Properties -- Configuration (New)`. I have Netbeans and Xdebug working. The project default is the site home url and the top \[drupal\_root/\] index.php file. I'm *guessing* if I make a new configuration of "Project URL" and "Index File" then Netbeans will open the project and focus my debug session to this area of Drupal. But so far the urls and index pages I'm selecting--Netbeans doesn't like.

I want to debug between the Edit View Page URL and the Configure Item URL. The error occurs between these two pages,

```
http://mysite.local/admin/structure/views/view/drag_test

```

And when I click on `Draggableviews: Weight (asc)` (under *Sort criteria*), the resulting non-JavaScript "configure item" page \[\*\] displays the errors at the top,

```
http://mysite.local/admin/structure/views/nojs/config-item/drag_test/page/sort/weight

```

I'm guessing the views template, views-ui-edit-item.tpl, is what I want. Netbeans of course wants an index file, but in Drupal that's the top page.

**What Drupal values for "Project URL" & "Index File" will NetBeans accept for a new Configuration?**

---

\[\*\] FYI. In case you're not immediately familiar with what a non-JavaScript Edit View Page is, remember how it was in Drupal 6 with options at the bottom of the page? Only in D7 options display on a new page when JavaScript overlay is off. (^\_^)

# Answer
> 2 votes
The trick to target a specific page using NetBeans and xDebug is to use Arguments.

```
File >> Project Properties >> Run Configuration
Project URL: http://hellofrom.local/
Index File: index.php
Arguments: q=admin/structure/views/view/post_drag/edit/page_1

```

---
Tags: debugging, views
---


# Question
Title: Whats the correct way to modify the author pane to add profile fields?
I want to add several fields from the user profile to the author pane.

Within the author-pane.tpl.php file, I added the following lines.

```
$fname = $account->field_profile_firstname[LANGUAGE_NONE][0]['value'];
    $lname = $account->field_profile_lastname[LANGUAGE_NONE][0]['value'];
    $dob = $account->field_profile_dob[LANGUAGE_NONE][0]['value'];
    $bio = $account->field_profile_bio[LANGUAGE_NONE][0]['value'];
    $phone = $account->field_profile_phone[LANGUAGE_NONE][0]['value'];
    $marital = $account->field_profile_marital[LANGUAGE_NONE][0]['value'];
    $religion = $account->field_profile_religion[LANGUAGE_NONE][0]['value'];
    $school['url'] = $account->field_profile_education[LANGUAGE_NONE][0]['url'];
    $school['title'] = $account->field_profile_education[LANGUAGE_NONE][0]['title'];
    $location['street'] = $account->locations[0]['street'];
    $location['city'] = $account->locations[0]['city'];
    $location['state'] = $account->locations[0]['province_name'];

```

Then to display the fields;

```
<div>
    <h2>Personal Info</h2>
          <?php if ($fname && $lname): ?> Name: <?php echo $fname." ".$lname ."<br>"; ?> <?php endif; ?>
          <?php if ($dob): ?> Date of Birth: <?php $dob = preg_replace('/00:00:00/',"",$dob); echo $dob . "<br>"; ?> <?php endif; ?>
          <?php if ($marital): ?> Marital Status: <?php echo $marital ."<br>"; ?> <?php endif; ?>
          <?php if ($religion): ?> Religion: <?php echo $religion ."<br>"; ?> <?php endif; ?>
    </div>

    <br>

    <h2>Contact Info</h2>
    <div>
        <?php if ($location['street']): ?> <?php echo $location['street'] ."<br>"; ?> <?php endif; ?>
        <?php if ($location['city']): ?><?php echo $location['city'] .", "; ?> <?php endif; ?>
        <?php if ($location['state']): ?><?php echo $location['state'] ."<br>"; ?> <?php endif; ?>
        <?php if ($phone): ?> Phone: <?php echo $phone ."<br>"; ?> <?php endif; ?>
    </div>

    <br>

    <h2>Education</h2>
    <div>
        <?php if ($school): ?>

            <?php echo "<a href='".$school['url']."' target='_blank'>".$school['title']."</a><br>"; ?>
        <?php endif; ?>
    </div>

    <br>

    <h2>Bio</h2>
    <div>
        <?php if ($bio): ?><?php echo $bio ."<br>"; ?> <?php endif; ?>
    </div>

```

But am getting errors;

```
Notice: Undefined index: und in include() (line 70 of /sites/all/modules/author_pane/author-pane.tpl.php).
Notice: Undefined index: und in include() (line 71 of /sites/all/modules/author_pane/author-pane.tpl.php).
Notice: Undefined index: und in include() (line 72 of /sites/all/modules/author_pane/author-pane.tpl.php).
Notice: Undefined index: und in include() (line 73 of /sites/all/modules/author_pane/author-pane.tpl.php).
Notice: Undefined index: und in include() (line 74 of /sites/all/modules/author_pane/author-pane.tpl.php).
Notice: Undefined index: und in include() (line 75 of /sites/all/modules/author_pane/author-pane.tpl.php).
Notice: Undefined offset: 0 in include() (line 76 of /sites/all/modules/author_pane/author-pane.tpl.php).
Notice: Undefined offset: 0 in include() (line 77 of /sites/all/modules/author_pane/author-pane.tpl.php).
Notice: Undefined offset: 0 in include() (line 78 of /sites/all/modules/author_pane/author-pane.tpl.php).

```

Now I know that the und errors are related to the language according to this post. http://drupal.org/node/1422606

Although when I tried to structure my code within the author\_pane.module, I was getting a 500 error on my server. So, to restate my question. What is the proper way to accomplish this?

EDIT/CLARIFICATION: When I say "proper way to accomplish this", I want to know if placing this code within .tpl file or .module and if am calling the field correctly.

# Answer
Make a view of the fields you'd like in the author bio area. Be sure and use contextual filters to show only the author passed.

Use Viewfield module to show this view for the content type as a field. Set it to show the author id as a contextual filter to the view.

Done. :-)
> 1 votes

---
Tags: 7
---


# Question
Title: How to get value from field widget during AJAX callback loop?
A select element on my form gets processed with an AJAX callback. There is a Multiselect widget on the form, and I want to see the new value of the field as if the form had been submitted. But, the $form\_state\['values'\]\['my\_multiselect'\] is always NULL when checked in the form builder function during AJAX callback. Where does Multiselect build the value from the form state?

# Answer
> 1 votes
Looks like there's an existing answer on Multiselect issue queue: Changing multiselect options using #ajax, and it has the solution.

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


# Question
Title: Using call_user_func_array on the db_select object
call\_user\_func\_array() makes calling a variable function with a set of arguments fairly simple. I would like to do the same with db\_select() passing in various options to different methods. Going to use dblog\_cron from 6.x and 7.x as the examples. How can I do something similar in D7?

D6 Code

```
<?php
// These 2 lines return the same thing in D6
$max = db_result(db_query('SELECT MAX(wid) FROM {watchdog}'));
$max = call_user_func_array('db_result', array(call_user_func_array('db_query', array('SELECT MAX(wid) FROM {watchdog}'))));
?>

```

D7 Code

```
<?php
$min_row = db_select('watchdog', 'w')
  ->fields('w', array('wid'))
  ->orderBy('wid', 'DESC')
  ->range(999, 1)
  ->execute()
  ->fetchField();

 // Getting closer but not what I'm looking for.
 $min_row = db_select('watchdog', 'w')
   ->{'fields'}('w', array('wid'))
   ->{'orderBy'}('wid', 'DESC')
   ->{'range'}(999, 1)
   ->{'execute'}()
   ->{'fetchField'}();
?>

```

How can I call the above code without eval using something like call\_user\_func\_array() or ReflectionMethod::invokeArgs?

# Answer
Breaking this down...

```
<?php
$x = call_user_func_array('db_select', array('watchdog', 'w'));
$x = call_user_func_array(array($x, 'fields'), array('w', array('wid')));
$x = call_user_func_array(array($x, 'orderBy'), array('wid', 'DESC'));
$x = call_user_func_array(array($x, 'range'), array(999, 1));
$x = call_user_func_array(array($x, 'execute'), array());
$min_row = call_user_func_array(array($x, 'fetchField'), array());
?>

```

In-lining everything... so it can be done.

```
<?php
$min_row = call_user_func_array(array(call_user_func_array(array(call_user_func_array(array(call_user_func_array(array(call_user_func_array(array(call_user_func_array('db_select', array('watchdog', 'w')), 'fields'), array('w', array('wid'))), 'orderBy'), array('wid', 'DESC')), 'range'), array(999, 1)), 'execute'), array()), 'fetchField'), array());
?>

```

---Solution below---

```
<?php
// Setup data array.
$args = array(
  array(
    'db_select', array(
      'watchdog', 'w',
    )
  ),
  array(
    'fields', array(
      'w', array('wid')
    )
  ),
  array(
    'orderBy', array(
      'wid', 'DESC'
    )
  ),
  array(
    'range', array(
      999, 1
    )
  ),
  array(
    'execute', array()
  ),
  array(
    'fetchField', array()
  ),
);

// Helper function.
foreach ($args as $data) {
  if (!isset($last)) {
    $last = call_user_func_array($data[0], $data[1]);
  }
  else {
    $last = call_user_func_array(array($last, $data[0]), $data[1]);
  }
}

// Get output
echo $last;
?>

```
> 0 votes

---
Tags: 7, database
---


# Question
Title: Filter strong and b from content through views
I'm use CKeditor, which inserts b and strong tags for bold text, and sometimes when Drupal is showing teasers, only the opening tag is included. Resulting in the bold type face cascading down and being applied to all the text below it. Is there any way to filter out particular html tags(strong, b) from the teaser display in views?

EDIT: If one chooses to use fields, there is also the option in views to strip all html but leave particular tags, which is can accomplish the same thing but from the opposite direction

# Answer
> 0 votes
I assume you are using "show teasers option" for rows if yes switch to fields option.

Once you are using the fields add body field and add "Trim this field" then you could either click field may contain html, which will close the html tags before cut-off or you could pick strip html all together...

---
Tags: views
---


# Question
Title: Email all users when a new content is published in Drupal 7
I want to send email notifications whenever a new content is published in the site. It would be helpful if I can do it by `Actions` \- using Actions & Triggers I can use token to mail a single user, i.e. author of a node. But how do I send email notification to **ALL *authenticated users*** of my site?

*P.S.* It is necessary that emails appear in bcc field, to avoid Spam. I've searched a lot, but no specific solution was found.

# Answer
> 2 votes
You can use the Rules module, a more powerful version of actions and triggers.

Configure a rule as follows:

* **React on event**: (Node) After saving new content
* **Action**: (System) Send mail to all users of a role

However, you cannot select the `authenticated` role here. Instead, you will have to add another role to your site and use it instead. (You can create another rule to automatically add that role upon registration.)

Also, note that the Rules module has this warning about sending too many mails:

> WARNING: This may cause problems if there are too many users of these roles on your site, as your server may not be able to handle all the mail requests all at once.

So if you have a lot of users this probably isn't a good solution.

---
Tags: 7, emails, actions
---


# Question
Title: How to get the autocomplete feature for a taxonomy term profile field visible on the registration form?
I have Profile2 and Profile2 Registration Path modules enabled, I set up two different profiles, and for one of them I created a field which is a taxonomy term with the Autocomplete term widget (tagging).

When adding a user within the administration interface, I have the autocomplete widget working, but for anonymous users trying to create a profile the widget is not even attached to the field... I know it is not attached because a field with the widget has a "autocomplete" class and an icon for ajax status in background, but the field on the registration form has no class..

How to add this widget ? Is it a permission issue ? or adding the class to the field through `hook_form_FORM_ID_alter()` could be enough ? (I don't have the field in the `$form` array though...

# Answer
Turns out it is a permission issue : adding the permission for anonymous users to `View published content` solves my problem as I do not have any reason to not let them see the website content

I guess for websites where content is for registered users only, this permission would not be granted and the widget would not be used on the taxonomy term field.. Maybe the `Content Access` module could help those use-cases
> 2 votes

---
Tags: 7, taxonomy-terms, users, ajax
---


# Question
Title: How do I assign a new role to all the existing accounts on the site?
I have more than 300 users in my site. I want to assigned them a new role I just created.

How do I achieve this?

# Answer
One option would be to do it via the GUI (admin/people) where you can select all the shown users with the uppermost checkbox and then under 'update options' add the role you want. If it's a one time thing for ~300 users then this is probably the quickest way to handle it.

For a programmatic approach the user\_multiple\_role\_edit() function can be used. You need to pass the user id-s as an array, the operation and role id to the function and it'll do the rest for you. You can get the role id by checking the edit link of the wanted role via the GUI (admin/people/permissions/roles).

To get all the user id-s and assign them the role you could use the following example (modify where needed):

```
$result = db_query('SELECT uid FROM {users}');
$uids = array();
foreach ($result as $record) {
  if ($record->uid == 0) continue;
  $uids[] = $record->uid;
}
user_multiple_role_edit($uids, 'add_role', 4);

```
> 8 votes

# Answer
If you would like to do this programatically you should be able to do it using something like this:

```
// load user based on user id
$user = module_invoke('user', 'load', $uid);
// get array of roles for user
$roles = $user->roles[];
// assign a new role for the user
$roles[]  = 'newrole';
// save the updated roles for the user
module_invoke('user', 'save', $user, array('roles' => $roles));

```

Of course the above just works for a single record, but you could use a `db_query()` call to retrieve a list of all user ids.

The following link might come in handy: http://drupal.org/node/28379
> 3 votes

# Answer
If you want to go the module route, you can use Views Bulk Operations. Create a view (in Views) that lists all the users on your site and then add an "add a role" action with Views Bulk Operations; this will allow you to select all users on your site at once and apply the role.

VBO (Views Bulk Operations) can also be used to simplify many other administrative tasks. The module page links to a large number of tutorials so I won't link to any here.
> 2 votes

---
Tags: 7, users
---


# Question
Title: Help debugging "cron run exceeded the time limit"
I have written a custom module (for Drupal 7 and PHP 5.3) that utilizes `hook_nodeapi()` and doesn't allow access to a specific node type and simply redirects (with `drupal_goto()`) to the main listing page with a warning message.

However I have a suspicion that the Boost module (with "Don't cache pages with messages" enabled) chokes on cron runs when it gets to these content types and keeps getting redirected (I don't know how Boost exactly works but I guess it caches few pages on cron runs?).

The reason for my suspicion, and the real problem is that the cron, after a certain number of runs, starts failing with an error message, "Cron run exceeded the time limit and was aborted.", and immediately after this message on Watchdog there's the following message, "There are Drupal messages on this page, preventing boost from caching."

I put a debugging piece of code on module.inc (hacked core as was suggested here) to see which module was responsible for this failure, and everytime the cron fails, the last module that accessed the Cron seems to be the "Search" (core) module:

> boost 22/02/2012 - 9:00am There are Drupal messages on this ... Anonymous
> cron 22/02/2012 - 9:00am Cron run exceeded the time limit and was aborted. Anonymous
> cron 22/02/2012 - 9:00am hit search cron Anonymous
> cron 22/02/2012 - 9:00am hit node cron Anonymous
> cron 22/02/2012 - 9:00am hit filter cron Anonymous
> cron 22/02/2012 - 9:00am hit dblog cron Anonymous
> boost 22/02/2012 - 9:00am Expired stale files from static page cache. Anonymous
> cron 22/02/2012 - 9:00am hit boost cron Anonymous

I have since then reduced the number of pages to index but it didn't help. The cron that runs after the Search cron is the "System" cron but I have no idea what exactly this cron does.

The annoying thing is when you access the cron page through typing in the browser http://address/cron.php or through commandline `wget http://address/cron.php` it runs Ok. But from the system's cron jobs it eventually runs into this problem after few successful cron runs.

I would appreciate any help in getting to the bottom of this problem or a push in the right direction. Thanks.

```
/**
 * Implements hook_nodeapi().
 */
function rhask_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op) {
    case 'view':
      if($node->type == 'question' && arg(0) == 'node' && !user_access('administer questions')){
        drupal_set_message('Access Denied - You cannot access this content directly. Please use this page.', 'warning');
        drupal_goto('ask');
      }
      break;
  }
}

```

I guess I could do a redirection without setting any message. That might solve it if indeed Boost is causing problems with the cron, I'll edit this post when I get any result by doing so.

---

Edit: The cron has been running successfully every 30 minutes since yesterday and the change I've made to the XMLSitemap module's settings seems to have done the job. I will continue to monitor this website for few more days.

Edit2: Cron still fails. I've removed the drupal\_set\_message so now it redirects without setting any messages. However it doesn't prevent the cron from failing. Boost doesn't complain anymore and just logs that "Expired stale files from static page cache". I don't know how to proceed from here to isolate this problem.

# Answer
We've solved this. drupal\_goto invokes hook\_exit which was causing the cron runs to fail. We've stopped this by checking for variable `$a4` of `hook_nodeapi` if it's not `NULL` (means it's being called from `node_view()` and not from cron) then proceed with `drupal_goto`
> 0 votes

# Answer
I suspect you could check that `arg(0) == "node"` and `is_numeric(arg(1))`, which would detect the internal path for a node display and not cron. You would also need to check `arg(2)` for "edit" and a few others, that may (or may not) appear as local tasks for your nodes.
> 0 votes

---
Tags: 6, search, cron, caching
---


# Question
Title: How do you get dropdown menus with toolbar.module?
I'm personally more a fan of the admin\_menu style dropdown menus than Drupal 7's toolbar. I was watching a screencast by Randy Fay when I noticed he seems to have the toolbar displaying in a dropdown fashion. Does anyone know how he does that?

Check out the video at 1:50 to see it in action.

# Answer
Install the admin menu module and activate Administration menu Toolbar style , it's a module in the package of admin menu
> 5 votes

---
Tags: 7, toolbar
---


# Question
Title: Feed aggregator does not update RSS feeds when cron job is run (Drupal 7)
I have several feeds setup in the Feed Aggregator ( admin/config/services/aggregator ) in Drupal 7.

I know that my cron job is running regularly - by checking admin/reports/dblog

But the when I look at the feeds list, the "LAST UPDATE" for each of them shows dates from over a week ago. If I do the update manually, i.e. click update items then the feed is refreshed and new items are available.

But why is the cron job not triggering the updates?

If you can't provide a reason then what approaches to debugging can I use to find and solve the root cause?

I have searched this site already and not found an existing question about this problem. I did find RSS feed not updating using feeds module but that question is about the *Feeds* module - which I don't use.

# Answer
Yup, trying to solve my own question (again):

Similar problem here: http://drupal.org/node/1115978

and the possible solution here: http://drupal.org/node/1023190

**Update**

The above solution was about a database fix to do with feeds that have more than one category.

When I applied to patch I was informed that this was already in the version of aggregator.

So in summary the solution I gave above had already been applied.

However, another avenue to explore is cron job time out. In my situation I have a *lot* of feeds so it could be taking the job invoked by the cron a long time to update all of them.

Here is another possible solution to extend the time alloted to running a job triggered by cron, a cron job:

http://teqsnacks.com/2007/07/07/drupal-when-cron-jobs-do-not-complete-and-cron-jobs-tips/

To quote:

> Go to your `settings.php` file (under sites/default or wherever it is). At the bottom of it you will see a list of ini\_set commands. Add the following to the list:
>
> ```
> ini_set("max_execution_time", 60);
>
> ```
>
> The number at the end is the number of seconds a program can run before timing out. Setting it to 0 means "never timeout" which you should use very carefully, like on a development site where you have control over the server.

**Update 2 - and likely solution and root cause**

The cause of the problem likely stems from a corrupt database causing errors when the cron job is run. Details and remedy here:

http://drupal.org/node/1596220

**Update 3**

After following the above instructions you may still see the feeds not updating. Further things to consider:

* Clear all caches
* Check your site logs for cron job running successfully and new feed items being imported from the aggregator
* If you are using a View (of type aggregator) to process the feed then you would probably need to sort the feed by descending so that the latest feed items appear first. To do this you will need to define your own date format (check the PHP option) for the Aggregator Feed Item Timestamp in the View sort criteria, so that the date is big endian i.e. YYYY-MM-DD hh:mm:ss. The current date formats offered aren't purely big endian and the sort won't work properly e.g. because day comes before month.
> 2 votes

---
Tags: 7, updating, cron, feeds
---


title: Rules with VBO in views

text:
# Question
Title: Rules with VBO in views
I have a view (using the table display format) that is showing all the node of a content type (A), and that content type has a reference to nodes of another content type (B). I added a VBO field to that view.

How can I create a content type B node for each node of the selected node (content type A) by setting the values just one time in the content type B create form?
(I need to create B nodes with the same field values for each node of A.)

# Answer
> 2 votes
The best way to get started is to watch the video series Learn the Rules Framework. It will demonstrate how to create the node and populate any data fields according to the content in your type A node.

---
Tags: 7, rules, views
---


# Question
Title: UI issues with the "Registration" module
I am working on my second Drupal 7 site and try integrating the "Registration" and "Registration Views" module (7.x-1.0-alpha5) the first time to create an event system where members can join events and see who else joined.

For this I've created a content type "Events" with the event-fields as well as a Registration Type for the events (with some additional registration fields on it). Then I added the registration as a field to "Events". So far so good - no problem here.

The issues I now have is with the User Interface:

a) The registration is rendered on top of the content as a tabbed-UI. I like to see just a link to register or maybe an embedded register-form. I also like to show the list of members who actually have registered for this event. ...maybe as a block on the sidebar or something like this. Can I change the way the registration module renders? Is there a way to create a block to render the registrants into?

b) In the event-nodes (only on the event-nodes - not on other node-types) I have the comments elements above the regular node content (in this case the event-field-contents) and below the registration-tabs. How do I control where the comments appear?

Any help or pointing whould be great!

Cheers, Marc

# Answer
> 0 votes
It sounds like a lot of the issue is you you'll have to go into the theme and edit how it displays from there. The comments in particular you'll have to do this, you can create a tpl.php file specifically for for "Events" content type. You can learn how to do that here:

http://drupal.org/node/17565

---
Tags: 7
---


# Question
Title: How can I force a field to be required if another field has a certain value?
I have two fields, a select list of checkboxes and a taxonomy term reference. I would like the taxonomy term reference to be optional unless one of the checkboxes has a certain value, in which case a value must be entered into the taxonomy term reference field.

Is there a module that can accomplish this? I tried the Field Validation module but I couldn't find a way to configure it for this use case. Custom code is fine too if you could point me in the right direction.

# Answer
> 4 votes
With custom code you can do something like this:

add a new validation function using hook\_form\_alter()

```
your_module_form_alter($form, $form_state, $form_id) {
  if($form_id == 'the_form_ID') {
    $form['#validate'][] = 'your_custom_validation_function';
  }
}

```

then check to see if the conditions are met

```
function your_custom_validation_function($form, &$form_state){
  if( $form_state['values']['your_checkbox_name'] == 1 ) {
    // check to see if tags are set
    // use form_set_error('tags_field_id', 'error message') to set a error message
  }
}

```

---
Tags: entities
---


# Question
Title: Group search result of drupal 7 and show them in tabs
I am using function like this. I have grouped the search output and displaying, but i need to make these grouping in tabs using any tabs feature available, how do i do it over here by using any other module function.

```
function arras_preprocess_search_results(&$variables) {
    $variables['search_results'] = '';
    // get a list of node types
    $nodeTypes = node_type_get_types();
    // loop through results, group by type
    $resultTypes = array();
    foreach ($variables['results'] as $result) {
        $resultTypes[$result['node']->type][] = $result;
    }

    // create fieldsets for each type
    foreach ($resultTypes as $resultType => $resultTypeResults) {
        $value = "";
        // loop through entries
        foreach ($resultTypeResults as $result) {
            $value .= theme('search_result', array('result' => $result, 'module' => $variables['module']));
        }
        //$variables['search_results'] .= $value;
        // add fieldset

    /*    $variables['search_results'] .= theme('fieldset',
            array(
                'element' => array(
                    '#title' => $nodeTypes[$resultType]->name,
                    '#collapsible' => TRUE,
                    '#collapsed' => TRUE,
                    '#value' => $value
                )
            )
        );
      */

```

---

## /*** Problem here ***/

---

```
     $variables['search_results'] .=   quicktabs_build_quicktabs('test',array(),array('title' => $nodeTypes[$resultType]->name, 'contents' => 'test'));
    }
}

```

# Answer
Thank you for sharing. I made some minor changes in your code because I was getting some floating search results. So I changed this part:

```
    $output .=  '<div id="tabs-'.$i.'">';
    $output .=  $value;
    $output .=  '</div>';

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

     $variables['search_results'] = $output;

```

To this:

```
$output_results .=  '<div id="tabs-'.$i.'">';
$output_results .=  $value;
$output_results .=  '</div>';

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

 $variables['search_results'] = $output;

```
> 2 votes

# Answer
Thanks all for the code here, saved me a ton of time.

Word of warning though - you need to include the jQuery UI tabs in this way:

```
drupal_add_js('
(function ($) {
 jQuery("#tabs").tabs();
}(jQuery));', array("type" => "inline", "scope" => "footer", 'weight' => 1));

```

Otherwise you get weirdness and clashes with other libraries - I noticed that the tabs would not render if the user was not logged in, for instance. With the code included like this, the inconsistencies disappear.
> 1 votes

# Answer
I am answering my own question as i finally did wht i wanted searching google..

```
function arras_preprocess_search_results(&$variables) {
    global $base_path;
    drupal_add_library('system', 'ui.tabs');
    drupal_add_js('jQuery(document).ready(function(){jQuery("#tabs").tabs();});', 'inline');
    $variables['search_results'] = '';
    // get a list of node types
    $nodeTypes = node_type_get_types();
    // loop through results, group by type
    $resultTypes = array();
    foreach ($variables['results'] as $result) {
        $resultTypes[$result['node']->type][] = $result;
    }

    // create fieldsets for each type
        $output .= '<div id="tabs">';
        $output .= '<ul>';
        $i = 0;
    foreach ($resultTypes as $resultType => $resultTypeResults) {
        $i++;
        $value = "";
        // loop through entries
        foreach ($resultTypeResults as $result) {
            $value .= theme('search_result', array('result' => $result, 'module' => $variables['module']));
        }
        $output .=  '<li><a href="#tabs-'.$i.'">';
        $output .=  $nodeTypes[$resultType]->name.'</a></li>';
        $output .=  '<div id="tabs-'.$i.'">';
        $output .=  $value;
        $output .=  '</div>';

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

         $variables['search_results'] = $output;

}

```
> 0 votes

---
Tags: 7, search
---


# Question
Title: Users don't have access to view as soon as relation is added, drupal commerce
I'm creating a new drupal commerce site and I wanted to create a view of all my products.

I didn't want to use Format: content but Format: fields instead. Of course then I needed to add a relationship to get the right fields like price (which are not part of the product display but rather the product itself) in to my view.

All of this worked rather well, I can see my view and it lists the products nicely.

The problem is that only I, the admin, can see the view. Authenticated users and anonymous users are not able to see anything.

As far as I can tell, the query does not display a result for them... (I added a string in the no results behavior section)

I checked all of the permissions needed for this view and made sure that all the content is published and that the view shows published content.

I did notice however that when I remove the relationship, the view does have a result.

I find this rather strange and I cannot find the answer so I turn to you. Is there anyone here who knows what I'm missing?

Thanks in advance

# Answer
> 5 votes
This is an issue listed in the Drupal Commerce issues queue. http://drupal.org/node/1276450 Its happens when your view has a relationship to a commerce product. I came across this earlier today when I was doing the same thing as you.

Two different solutions are suggested at comments 5 and 6 on the issues page. The first is to disable SQL rewriting under the Advanced \> SQL Settings section of the view. This can have security implications if your using contextual or exposed filters. The other suggestion is give all user roles the 'View any product of any type' permission under permissions. This is what worked for me.

# Answer
> 3 votes
I have the same problem with views in Drupal commerce. One thing that helped me was to go to the view and go to Query Settings and Disable SQL rewriting. You can see more information about this problem in this link. I like #55 explanation. If this works be sure to figure it out what are the implications of turning off the query rewriting for your case.

http://drupal.org/node/1276450

\[updated\]

According to the link in #98 that the right solution is to grant users the "view any product of any type privilege" permission. And also says and I quote:

"It has a security warning, which is a mistake on our part, and the warning should be removed." from bojanz

I change my setting to the recommendation of bojanz and it worked perfectly

---
Tags: commerce, views
---


# Question
Title: Is it possible to post a file with drupal_http_request?
Is it possible to use `drupal_http_request()` to post a file? If not, what function can I use to submit a file to a webservice?

# Answer
> 4 votes
All you need is to set correct header information. I'd do it like so:

```
$boundary = 'A0sFSD';
$headers = array("Content-Type" => "multipart/form-data; boundary=$boundary");
drupal_http_request('some/url/you/want/to/post/file/to', $headers, 'POST', multipart_encode($boundary, $params));
if ($request->error) {
    watchdog("ipaper", "Request failed - ". $request->error .' - '. http_build_query($params));
}

```

...............

```
function multipart_encode($boundary, $params){
    $output = "";
    foreach ($params as $key => $value){
    $output .= "--$boundary\r\n";
    if ($key == 'file'){
        $output .= multipart_enc_file($value);
    }
    else {
        $output .= multipart_enc_text ($key, $value);
    }
    $output .="--$boundary--";
    return $output;
}

function multipart_enc_text($name, $value){
    return "Content-Disposition: form-data; name=\"$name\"\r\n\r\n$value\r\n";
}

function multipart_enc_file($path){
    if (substr($path, 0, 1) == "@") {
        $path = substr($path, 1);
    }
    $filename = basename($path);
    $mimetype = "application/octet-stream";
    $data = "Content-Disposition: form-data; name=\"file\"; filename=\"$filename\"\r\n";
    $data .= "Content-Transfer-Encoding: binary\r\n";
    $data .= "Content-Type: $mimetype\r\n\r\n";
    $data .= file_get_contents($path) . "\r\n";
    return $data;
}

```

You might also consider using cURL for this purpose.

---
Tags: 6, files
---


# Question
Title: Assigning permissions based on taxonomies
I have a hierarchical taxonomy that looks like this:

School\>Class\>Project

That is you could have a project that is part of a certain class that is part of a certain school. I would like to make it so that only students that are enrolled in a specific class can submit content to that class/project. Also, I would like to have a semi-adminstrator role called teacher that can only enroll students into a class that they are administering but cannot enroll students into other classes.

I have found a depreciated module called taxonomy based permissions but it seems like it was abandoned after drupal 5 (I am using drupal 7). Are there any new modules that might help me accomplish these goals? If not, this problem seems a little bit outside of the intended functionality of taxonomies, I am wondering if I am using the wrong kind of model for my site. Any feedback on this though?

# Answer
> 1 votes
Organic Groups sounds like a better way to go in this situation. Each class is a group (can still categorize them using taxonomy), but will give you the sub-permissions you require per class (group) (e.g. teacher being able to enroll and administer their own group and students only being able to submit content in their own class)

OG enables users to create and manage their own 'groups'. Each group can have subscribers, and maintains a group home page where subscribers communicate amongst themselves.

They do so by posting the usual node types: blog, story, page, etc. A block is shown on the group home page which facilitates these posts. The block also provides summary information about the group.

Groups may be selective or not. Selective groups require approval in order to become a member, or even invitation -only groups. There are lots of preferences to configure groups as you need.

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


# Question
Title: Is there a way I can set access to specific form elements?
I'm writing a custom ticketing system module for my company and I would like certain form elements disabled based on permissions. Is there a way I can do this **without** needing to make two separate forms (ex: user form, admin form)

I know for the items array in a menu hook, you can just set 'access arguments.' Preferably I'd like to just use the existing permissions I've already created for my module or even make it role specific.

# Answer
> 5 votes
You can use the FAPI `#access` property:

```
$form['some_element']['#access'] = user_access('some permission');

```

---
Tags: 7, forms, users
---


# Question
Title: Global $user object isn't always "Fully Loaded"
I have a Drupal 6 module that implements hook\_user() to add a custom property on op='load';

```
mymodule_user($op, &$edit, &$account, $category = NULL) {
  $account->external_id = mymodule_get_user_external_id($account->uid);
}

```

In modules, I access the global $user object. What I find is sometimes it has my -\>external\_id property, and sometimes it doesn't.

As a result, I end up having to check to see if my custom property is set, and if not, call user\_load()

```
if(isset($GLOBALS['user']->external_id)) {
  $account = $GLOBALS['user'];
} else {
  $account = user_load($GLOBALS['user']->uid);
}

```

Yuck! Is this a known problem, or does it sound like I'm doing something wrong?

# Answer
> 3 votes
Nope, you are doing it right as this is a known issue/behavior. Check out http://api.drupal.org/api/drupal/developer%21globals.php/global/user/6 for a lot more information on it. A link from there, http://drupal.org/node/57287, talks to your point directly (it is for D7 but is germaine to D6).

# Answer
> 1 votes
With the user hooks, a general rule of thumb is that when the parameter in the API is specified as `$account`, don't expect it to be interchangeable with `$user`. So, in your case, doing a `user_load()` to explicitly load the extra information is appropriate and needed. `hook_node_access` in Drupal 7 is another example that does this. A similar thing happens with fieldable entities with some hooks, where not all of the fields are present in the argument passed into a hook.

There is an answer on the main SO site that goes into this topic in more detail. There is also a related issue on drupal.org about it, too.

---
Tags: 6, users
---


# Question
Title: What is the skeleton structure for a Drupal 7 module?
What are the files necessary for building a Drupal 7 module? What are the requirements for constructing a basic .info file? The essence of this question is to provide a skeleton for building a basic Drupal 7 module from scratch.

# Answer
> 13 votes
**Minimum files needed:**

Normally, the minimum files needed for a module is the following:

sites/all/modules/{name of your module}

* `{your module}.info`
* `{your module}.module`

**Or use the examples module:**

The examples module on drupal.org provides you skeleton modules to develop custom/contrib modules. Just use that to copy and create your modules off of.

Check out the project page:

> This project aims to provide high-quality, well-documented API examples for a broad range of Drupal core functionality.
>
> (Interested in other, non-core examples?)
>
> Developers can learn how to use a particular API quickly by experimenting with the examples, and adapt them for their own use.

Link to the git repository: http://drupalcode.org/project/examples.git/tree/refs/heads/7.x-1.x

**Code from the examples module:**

I've also just pasted in the code you could get from the examples module.

example.info file:

```
name = Examples For Developers
description = A variety of example code for you to learn from and hack upon.
package = Example modules
core = 7.x

```

example.module file:

```
<?php

/**
 * @file
 * This file serves as a stub file for the many Examples modules in the
 * @link http://drupal.org/project/examples Examples for Developers Project @endlink
 * which you can download and experiment with.
 *
 * One might say that examples.module is an example of documentation. However,
 * note that the example submodules define many doxygen groups, which may or
 * may not be a good strategy for other modules.
 */

/**
 * @defgroup examples Examples
 * @{
 * Well-documented API examples for a broad range of Drupal 7 core functionality.
 *
 * Developers can learn how to use a particular API quickly by experimenting
 * with the examples, and adapt them for their own use.
 *
 * Download the Examples for Developers Project (and participate with
 * submissions, bug reports, patches, and documentation) at
 * http://drupal.org/project/examples
 */

/**
 * Implements hook_help().
 */
function examples_help($path, $arg) {
  // re: http://drupal.org/node/767204
  // 5. We need a master group (Examples) that will be in a main
  // examples.module.
  // The examples.module should be mostly doxy comments that point to the other
  // examples.  It will also have a hook_help() explaining its purpose and how
  // to access the other examples.
}

/**
 * @} End of 'defgroup examples'.
 */

```

# Answer
> 8 votes
1) Decide on a name for the module (for example: mymodule).

2) Create a folder inside sites/all/modules with your module's name.

3) Inside the folder create a mymodule.module file with a opening php tag (`<?php`) - the closing tag (`?>`) should be omitted.

4) Create a mymodule.info file (inside your module's folder) with the following 3 lines:

```
 name = Mymodule
 description = Description for the module
 core = 7.x

```

With this much you already have a Drupal 7 module that you can enable via the GUI (it doesn't do anything as long as you haven't added any functions/code inside the mymodule.module file). Note that all the mymodule instances used here should be replaced with your actual module's name and 'Description for the module' should be a proper description.

---
Tags: 7
---


# Question
Title: How does one 'override' string used in a core file?
I'm trying to change the text "Already a member?" located in commons\_core.blocks.inc to a different value. I would preferrably like to override this value and not directly edit a file in /profiles/drupal\_commons/.

Can anyone recommend a good solution?

# Answer
> 3 votes
The string you are referring is used on line 167 of the commons\_core.block.inc file, that is part of `_commons_core_header_login_block_view()`, and which is included in the following control statement.

```
  if (drupal_is_front_page()) {
    // Only provide a link
    $block['content'] = t('Already a member? !login', array('!login' => l(t('Login'), 'user')));
  }

```

You can use the String Overrides module as suggested by Clive. The help provided from the module says:

> To replace a string, enter **the complete string** that is passed through the t() function. String Overrides cannot translate user-defined content; it can only replace strings wrapped in the `t()` function. To find the strings you can actually change, open up a module and look for `t()` function calls. Places where %, @, or ! are used means that the translation contains dynamic information (such as the node type or title in the above examples); these are not translated while the text around them is.

In your case, you need to use the string "Already a member? !login" because that is the string passed to `t()`, not the string containing the login link as replaced by `t()`.

You can also change the code in the settings.php file as suggested by md2. In this case, the code that you need to add to the file is the following one.

```
$conf['locale_custom_strings_en'] = array(
  'Already a member? !login' => 'YOUR STRING',
);

```

Replace `'YOUR STRING'` with the string you want to use.

What of the two methods you should use depends from how many strings you need to replace. If you have a single string to replace, then you could use the settings.php method, especially if there is just a limited number of users that would need to alter that string, and those users are comfortable doing it without using the user interface offered by Drupal, but through FTP, or SSH. In the case you are going to use the settings.php method, you could write your customizations in a different file that is then included from settings.php; in this way:

* You can use the same settings for different domains/sub-domains, without to even copy that part in different settings.php files.
* You can control who has the permission to write the settings.php file, which contains the most sensitive information, without to be so restrictive on who can change the other settings available on settings.php.

If vice-versa, you need to change more than one string, your site is using more than two languages (which could be possibly increased on the near future), or your need that more than two users can alter the strings, without to give them FTP, or SSH access, then you should use the String Overrides module.

Both the methods replaces any occurrence of the string with the one you supply. It is not possible to replace the string only in specific pages, or in a specific block, using these methods; if there is another module that uses the same string, the string will be replaced with the string you set.

As the string is not used from a theme function (which could be overridden with your own theme function), the alternative to the methods I reported here would be to implement a block in your custom module, which is used to replace the block already implemented in Drupal Commons, and which uses the string you want to use.
In Drupal 7 would be easier, as it allows a module to implement hook\_block\_view\_alter(), or hook\_block\_view\_MODULE\_DELTA\_alter() to alter how the block implemented from another module is rendered.

# Answer
> 5 votes
For overriding a few text strings the easiest way is probably to use the String Overrides module:

> Provides a quick and easy way to replace any text on the site.

**UPDATE**

The line that sets this particular string is:

```
$block['content'] = t('Already a member? !login', array('!login' => l(t('Login'), 'user')));

```

Once it's built up, the string will actually look something like this:

```
'Already a member? <a href="/user">Login</a>'

```

That's why you're having difficulty targeting it with the string overrides module at the moment. If you're not developing a multilingual site you might just get away with inspecting the `<a>` tag in the block, and using that HTML in string overrides. I'm pretty sure it'll work.

# Answer
> 2 votes
If you edit the settings.php file for your site and scroll down to near the end you'll find the following if your site is Drupal 6:

```
# $conf['locale_custom_strings_en'] = array(
#   'forum'      => 'Discussion board',
#   '@count min' => '@count minutes',
# );

```

The settings.php file for Drupal 7 contains the following instead (note values are nested within an additional array):

```
# $conf['locale_custom_strings_en'][''] = array(
#   'forum'      => 'Discussion board',
#   '@count min' => '@count minutes',
# );

```

If you are simply doing a single replace and not translating many many strings I would say this is the way to go.

~Mark

---
Tags: 7
---


# Question
Title: Trying to submit a node add form via AJAX but failing
I'm simply trying to submit a node add form via AJAX:

```
function input_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'page_node_form':
      $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
        '#ajax' => array(
            'wrapper' => 'apple-node-form',
            'callback' => 'node_add_callback',
            'method' => 'replace',
            'effect' => 'fade'
        )
      );
      break;
  }
  return;
}

function node_add_callback(){
  $node = new stdClass();
  $node->type = 'page';
  return drupal_get_form('node_form', $node);
}

```

`input_form_alter()` DOES get called. And when I click the submit button, I even see the standard ajax gif and "Please wait" message. The gif and wait message then disappear, as expected. However, no new node has actually been created.

# Answer
Solved it. The problem was this code:

```
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#ajax' => array(
        'wrapper' => 'apple-node-form',
        'callback' => 'node_add_callback',
        'method' => 'replace',
        'effect' => 'fade'
    )
  );

```

This overwrites the `$form['actions']['submit']` array that already existed, recreating it with the values I specified. Since all I wanted to do was add an AJAX submission, the following code should replace the above:

```
    $form['actions']['submit']['#ajax'] = array(
        'wrapper' => 'apple-node-form',
        'callback' => 'node_add_callback',
        'method' => 'replace',
        'effect' => 'fade'
    );

```

In other words, we're just adding an `#ajax` item to the already created `$form['actions']['submit']` array.
> 2 votes

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


# Question
Title: determine which template file a contrib module is using?
I'm using a contrib module. It doesn't seem to be using the right template file. I'm trying to triage whether the problem exists in my template or if it is just the hook template suggestion.

What is the cheapest way to debug which template file a particular contrib module is using?

FYI: i'm using the commerce export ftp module. It has it's own template inside the module but i'd like it to use the template file within my theme.

I would like an answer that would be a general debugging practice. Not one specific to this particular module: how do you dump the file path that the contrib module is using? Is the only way of doing so with devel\_ui ? I'm looking for a programatic way of doing this.

# Answer
> 1 votes
I thing something like this could tell you what is going on :

```
$reg = theme_get_registry();
dpm($reg['commerce_order_ftp_export']);

```

---
Tags: debugging
---


# Question
Title: Limit access to a view based on profile field
I'm trying to figure out the best way to limit access to a view based on a boolean field in the user profile. If the user checks the box for that field they will have access to the view, otherwise not.

I could use views\_php for the access control of the view. Would that prevent the view from getting cached with views caching?

Or should I use a hook\_form\_alter() to check for the value each time the profile is saved and then add or remove from a special role?

# Answer
I do this on my site using Rules. I use the `Data comparison` condition on profile save and then add or remove the role as necessary. If you do decide to use the Rules module, make sure to add a NOT `Data comparison` as well to make sure the Rule doesn't get called multiple times (I had problems with this).

Example:

* **Event**: *After updating an existing user account*
* **Condition**: *NOT Data Comparison*: account-unchanged:field\_mycheckbox is Yes
* **Condition**: *Data Comparison*: account:field\_mycheckbox is Yes
* **Action**: *Add a role*
> 1 votes

---
Tags: 7, views
---


# Question
Title: Ubercart Module for handling subscriptions?
Trying to figure out the best UC module to use for this...

Essentially, I'm trying to create a site where users may purchase subscriptions. There are about 15 different subscriptions a user may purchase. The first subscription (regardless of which one it is) will sell at $20. Every additional subscription purchase after that will cost $10.

Not sure which module to use (or if one even exists) to accomplish this. There appears to be so many contributed modules, and the descriptions "kinda sorta" seem like what I need, but a lot of them sound very similar...

If someone knows a good way to accomplish this, that'd be great...

# Answer
Look at UC Recurring module. It should do what you need. The instruction on how to set it up is here.
> 3 votes

# Answer
Paypal and I think perhaps one or two other gateways have recurring payments APIs that Ubercart can work with. In that setup, Ubercart just initiates a subscription and Paypal takes it from there, and you manage the subscriptions from within Paypal. It's good because I trust Paypal with this sort of thing a little more than Drupal, but its bad because the Paypal interface is terrible and you can't really change Payment amounts once a subscription is initiated (you just have to cancel and re-subscribe).
> 2 votes

# Answer
There is also a **Ubercart Contributed Module** called Subscriptions

> uc\_subscribe provides a framework for tracking and acting on subscriptions.
> 2 votes

# Answer
There was a session on subscriptions at Drupalcon Denver 2012 (watch the video of the session at the link) specifically on the problems Lullabot encountered setting up drupalize.me.
> 1 votes

# Answer
The moneyscripts module (unfortunately its not free) worked for me when I built a website for a customer of ours. I can't remember where I found it but do a search for moneyscripts and there is a really good recurring payments module there. It operates outside of ubercart which is kind of nasty if you also need ubercart but if subscriptions is all you want its brilliant.
> 0 votes

---
Tags: ubercart, notifications
---


# Question
Title: When creating a 'status' entry with the statuses module, stop it from creating a double post
Am using statuses 7.x-1.0-unstable4+43-dev. I've spoken to some of the "maintainers" on the drupal.org site and none have been able to answer this question, blamed another module or have ignored my question. So I'm taking this question to the greatest site on earth, Stack Exchange!.

When I create a 'status' from a user profile page. It create 1 entry in the DB but displays a duplicate of the entry on the user page. According to the one of the maintainers, its an issues with views. I've tried to tinker with views to no avail. I was also told it was a problem with one of the contrib submodules... The problem with that is.. I ONLY HAVE THE MAIN MODULE ENABLED! So, do you gurus have any idea why this would create a duplicate display of a single entry in statuses?

# Answer
Gosh, never posted here before, but the rules seem kind of draconian. I don't have a fix for this, but I thought I could relate that I've had the exact same problem and note some of the things I've tried.

I notice than when I look at the View under "Preview" and specify a user\_id, it works perfectly. My hope is that IceCreamYou (the main contributor, who is particularly arrogant, when you read his responses to questions) will stumble upon this and a lightbulb will go off in his head.

Otherwise, my suggestion would be to intercept the SQL (you can see it with the Devel module), try to roll your own (with the inclusion of the DISTINCT keyword, which when I add it to the query generated removes the duplicates).

Note that the code for the "statuses" view is embedded in the Statuses module, so you'll have to extract it from there first.

If this sort of post is against the rules, feel free to delete it :-)
> 2 votes

# Answer
I've last looked at this project 6 months ago and there seems to be a lot of development on it. However, IMHO, it looks like an ambitious project with tons of integrations which to me means "complexity".

Not sure what your requirements are but you might be able to do most with content types, custom fields and/or comments in Drupal 7, possibly combined with views.

For example, checkout Ajax Comments for a cool ajax submit without having to reload the page.
> 0 votes

---
Tags: views, 7
---


# Question
Title: Add JavaScript 'effects' to be used with AJAX form submissions
Consider the following code:

```
        $form['actions']['submit']['#ajax'] = array(
            'wrapper' => 'apple-node-form',
            'callback' => 'node_add_callback',
            'method' => 'replace',
            'effect' => 'fade'
        );

```

This will produce a JavaScript fade animation. But how can I define my own animations? For example, `'effect' => 'myCustomAnimation'`.

I'm really just looking for a way to be able to define my own JavaScript function, and have that function handle the AJAX request. I could just call `.ajaxComplete()` on the `document` and have a series of switch statements in there that figure out what to do with the response. But that's a bit hacky, and the switch statements (as well as the initial response parsing) would be additional logic. If I can just define right there in the `$form` array PHP code the JS function to be used, no ugly switch statement would be necessary.

# Answer
It appears you need to install the interface elements library to add custom effects.

As indicated in the forms api.

http://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7

# ajax\['effect'\]

**Description:** Specifies the effect used when adding the content from an AJAX request.

**Values:** String. Possible values: 'none' (default), 'fade', 'slide'. If the interface elements library is installed, any effect with the name effectToggle may also be used.

I hope this helps :)
> 0 votes

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


# Question
Title: Website saves separate sessions for "www.domain.com" and "domain.com"
* I open a browser, type "www(dot)mydomain(dot)com"
* I login as an admin
* I open a new tab, type "mydomain(dot)com". I'm logged out, and i can login as a different user..

It's weird. I can't find anything helpful on google (or i don't know the right search keywords). Does anyone here have any idea?

Thanks :)

# Answer
> 5 votes
For usability (this problem) and SEO reasons you should redirect all visitors to a single version of the site. Look in the .htaccess file and you should see instructions on how to do a 301 redirect to send people to either the www or the non-www version of the site.

If you really really do want to make the site work on both versions, open your settings.php and find the line for $cookie\_domain. Set it to be the "example.com" version and it should work.

# Answer
> 1 votes
Here's my .htaccess solution for www Resolve to Apache.

Make sure to place the .htaccess file you build in the root directory of your web site.

```
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]

```

Here are the three lines of code to use if you want to drop the www.

```
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]

```

---
Tags: sessions
---


# Question
Title: Direct link to view unpublished node causes redirect loop
When I unpublish a node and have another user without permissions to view unpublished content trying to access that node (through an external link for example) it will generate a redirect loop. It just does a bunch of 302's to the same page, until the browser stops it.

I would expect an "access denied" page. What could cause the redirects to the same page?

Disabling "global redirect" module didn't have an effect. I don't have any rules or module code relating to it either.

**Update:**

Anonymous visitors get redirected to the /user/login page. Authenticated users don't have "view unpublished nodes" permission.

I guess I can change my 403 page to something other than /user/login to fix the redirect loop.

**Question:**

How would I create a regular page and show the login form if they are not logged in already, otherwise show a "page has been deleted" error?

# Answer
> I guess I can change my 403 page to something other than /user/login to fix the redirect loop.

Yes, that seems like it would cause the redirect problem.

But it sounds like you want to have a login page when the user gets an access denied message, and there is a module to do exactly that: r4032login

LoginToboggan may provide a similar feature, but I find that r4032login does a very simple thing and it does it well. On the other hand, I've run into several bugs with LoginToboggan.
> 5 votes

# Answer
Apologies if I haven't understood this properly, but I think the LoginToboggan module can help with this. One of its features is to:

> Provide a login form on Access Denied pages for non-logged-in (anonymous) users.

That would mean anonymous users accessing your unpublished nodes would be presented with a login form, and authenticated users accessing it would get a 403 error.

Then you can take off any 403 redirect you have to user/login as the login will display by default on those pages.
> 3 votes

# Answer
Assuming you want to keep your 403 set to user/login then you could create a new rule as follows for auth users:

1. Event: Content is viewed
2. Condition: Content is (NOT) published.
3. Condition AND User has role: Authenticated.
4. Action: Redirect to
5. Action: AND Show a message "This content has been unpublished."

That said you could also remove the 403 set so that authenticated users get Drupal's default access denied message and then redirect anonymous users to the login page using either Rules or LoginToboggan.
> 1 votes

---
Tags: 7, redirection
---


# Question
Title: How do you save data that is in fields inserted via hook_form_alter?
I created a module that just uses the hook\_form\_alter to add additional fields to an existing form. The problem now is when I enter in the information and submit none of the information inputed in the additional fields get saved when I go back to the form.

# Answer
Other modules aren't generally programmed to be aware of your custom additions and don't know where/how you want to save the data. If you add fields via hook\_form\_alter() then you should also add your own submit and possibly validation handlers to the form similarly to this:

```
$form['#validate'][] = 'mymodule_someform_custom_validation';
$form['#submit'][] = 'mymodule_someform_custom_submission';

```

In the validation handler you can then validate your custom field data (if needed) and in the submit function you should save it. Small amounts of information can be stored in a variable, but if there's bigger amounts of data from different users you'll probably want to create a custom database table where to store all the information in.
> 3 votes

---
Tags: 7, forms, hooks
---


# Question
Title: Moving, Removing, Disabling Administration on live server
On my staging server people should be able to access the administration to add, delete or edit content. The complete installation including the database is then deployed to a live server. On the live server I don't want anyone to be able to access the administration. In other words if a user goes to `mylivesite.com/admin` the response would be a `404 - not found`. What would be the best approach to achieve this?

# Answer
> 2 votes
The best approach would be to deny access to the administration pages for certain roles on your live site using standard Drupal permissions ( http://example.com/admin/people/permissions ).

The permission you're looking for is called "Use the administration pages and help".

Returning a 404 for all admin pages doesn't seem like the correct thing to do here, as the page *has* been found. A 403 is the correct semantic response for this.

If you're desperate, having the following code in a module on your live site only would do the trick:

```
function MYMODULE_init() {
  if (arg(0) == 'admin' && $GLOBALS['user']->uid != 1) {
    drupal_not_found();
  }
}

```

But I can't say I'd recommend it :)

---
Tags: 7, users
---


# Question
Title: How do you make the list of Organic Group (OG) members of a group visible only to group members?
In Drupal 7 I have public and private groups. I would like the list of members that show up in the View: OG members block to only show members of the group if the the current user is a member of that group as well.

This seems like a fundamental capability of OG yet I can't seem to find how to set it.

A version of this question is at http://drupal.org/node/707738 \- posted on February 8, 2010

Any help would be appreciated.

# Answer
I would suggest you to go in Views under `Block Settings > Access` and try OG Permissions
> 1 votes

# Answer
If you've set up your og page as a node template, you will find the OG Members block in the content section of your page setup. If you click the gear icon on the block, you will see "Visibility Rules". Click "add new rule" and select "OG: user membership in group".

That's how I did it, and it worked for me.
> 1 votes

---
Tags: organic-groups
---


# Question
Title: How to allow users to create only one group using Organic Groups 7
I am trying to use OG7 to get users to create groups as companies - i.e., each group set up will be a company. I would like to to make sure that ea ch group admin can only create one group (i.e., her/his company); and the "add content\>\> group" link is disabled or not displayed once a company has been created.

How do I do that?

# Answer
You could try Node Limit module to limit to one the number of nodes of your group content type to be created by user.
> 0 votes

---
Tags: organic-groups
---


title: Set input value in custom search module

text:
# Question
Title: Set input value in custom search module
I'm using custom search module in my site. What I want to do is set a value for the input (text box) in the username and password field.
How can I do that?

# Answer
> 1 votes
The Form API is your friend. Take a look in the Form API Quickstart Guide, how to change a form for your needs.

---
Tags: 7, forms
---


# Question
Title: Easy Way to change all instances of 'Content Types' in admin to a different phrase
For a project I am working every Content Type available to a user is a 'Survey'. The terminology 'Content Type' confuses the users. I was wondering if there was a simple way to change all menu instances of 'Content Type' to 'Survey' in the admin. I was thinking use `hook_page_alter` but this could grow teduios and be difficult to maintain. Has anyone ever done this before? Thank you.

# Answer
> 4 votes
To do this with just one or two strings in the user interface ("Content Type" is such a string), you can use the String Overrides module.

If you end up re-writing lots of phrases, you should make a custom language since String Overrides will cause a performance hit if you use it for too many things.

---
Tags: 7, nodes, users
---


# Question
Title: Recommendation for modules/workflow to build a premium link directory
I'm just about to start building a link directory and I'm at odds over the best way to go about it.

The directory will accept both standard (free) and premium subscriptions. Premium subscribers will have extra fields available to them to fill out and display on their 'profile' page (standard link directory model I guess).

The front-end directory itself will be based on taxonomy/views so that's not an issue, but I'm struggling with the best way to handle the subscriptions. Conceptually I guess I would be selling access to a user role for a limited period of time, and showing/hiding various fields on the profile form based on the role's permissions.

I'd prefer to use Commerce and I'm struggling to find a stable module (or example using rules) that would help me plan out this subscription system.

Has anyone built a similar system before? If not can anyone think of a good collection of modules/workflow to accomplish this? I'm happy to write as much custom code as is needed but I'd rather not reinvent the wheel where possible, and it seems like Drupal is *made* for this kind of thing.

**EDIT**

Following Patrick Kenny's comment I should add that I don't need these subscriptions to recur automatically, just for the access to the role to expire after a certain amount of time.

If this will be difficult to do with Commerce I'd love to hear any other ideas (Ubercart, etc).

# Answer
I'm building a site with free and paid memberships now; my use case isn't exactly the same but I'll share what I can.

I'm not using Drupal Commerce; in my case, users make a payment with PayPal and then I manually add a *paid* role to each account. I intend to eventually set this up in Drupal Commerce but I haven't had the time yet.

When I add the *paid* role, a rule is triggered that automatically sets an expiration date using the Role Expire module. Until very recently the 7.x rules integration was bugged but I am happy to report that it is now fixed and works great.

As for working with Commerce, Randy Fay also did a screencast on setting up content access for a membership site. I'm not sure if the content access part is relevant but the final part of the screencast covers:

> * Create a product representing the premium role.
> * Create a rule that grants the premium role on order completion:
>     1. After updating an order
>     2. If the order state is Completed
>     3. And the order contains our premium product
>     4. Add a role to the user who is the owner of the order
> 5 votes

---
Tags: commerce, notifications
---


# Question
Title: How can I show only terms from a certain vocabulary in a view summary?
I have a View that has a contextual filter for Taxonomy terms... I have selected that if the parameter is not given just show a summary, but I want that summary to show only terms of a certain vocabulary... is that possible?

**UPDATE:** Just to be clear. I'm selecting nodes that has two fields that points to different vocabularies, so in the summary the view is showing all the terms form both vocabularies, I just want to show the terms that are only on one of them.

# Answer
> 2 votes
I was looking for the same thing. I found my answer here: http://drupal.org/node/1243488#comment-4843640

It's not very intuitive, but it works.

# Answer
> 0 votes
As far as I know this isn't trivial to accomplish.

In this case you're probably better off specifying a default argument for the vocabulary you want.

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


# Question
Title: Which configuration settings should be used to prevent "No statistics available" in the Admin Reports?
When I view the Admin Reports like Top Referrers, Top Pages, Top Users, etc (by navigating to /admin/reports), those pages simply say "No statistics available". I am using Drupal version 7 with an admin account with all permissions.

Google Analytics is successfully collecting this data, so I don't understand why Drupal is not. I can't find any configuration setting to enable these reports. Could this be an issue with my webhost?

I apologize if this post is vague. I just don't know how to go about diagnosing this problem.

# Answer
This has nothing to do with Google Analytics or your Provider. Check `/admin/config/system/statistics`. This will populate your `/admin/reports/hits`.
> 5 votes

---
Tags: 7, log-messages
---


# Question
Title: Access custom theme settings from within views
I have a few custom theme settings which so on my themes settings page.. this all works fine and as expected.

I now need to create a view that gets that custom theme setting. I can't find anything on how to do this.

I have installed the views php module and I know this `theme_get_setting('setting_name')` is what i used to get the theme settings in my `template.php` file.

Any help with this will be much appreciated.

Regards C

# Answer
Just for other people who come across this here is the answer:

`<?php print theme_get_setting('tm_qrule_url'); ?>` works using the `views_php` module

It doesn't show in the views preview but does in the actual page load.

Thanks goes to @sheena\_d for helping with this.
> 1 votes

---
Tags: theming, views
---


title: Views exposed filter Date - Year

text:
# Question
Title: Views exposed filter Date - Year
I need to create an exposed filter to a view that should handle the content's post date and more specifically the year. So I need a jump list that should contain values like '2009', 2010', '2011' etc.

I read Exposed Post date filter on views and it's all very helpful but I cannot figure out how to automate the starting date so it can be the year of the oldest content posted an the ending one the year of the newest.

Any help?

# Answer
You'll need to use hook\_form\_alter in a custom module to set the options as the form is loaded.

Something like this:

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

  switch ($form['#id']){
    case "my_form_id":

      //use db_select to get the oldest and newest years,
      //loop through them to end up with an array like this one:
      $years_array = array('2009', '2010', '2011');

      //set the options to your array of years
      $form_state['input'][my_form_input_name]['#options'] =  $years_array;
      break;
  }
}

```
> 1 votes

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


title: LDAP + Workbench or LDAP + OG

text:
# Question
Title: LDAP + Workbench or LDAP + OG
**I have come to an impasse in the development.**

**MY GOAL:** Setup department pages on the site, giving editing access to specific LDAP roles Creating workflow for the data(draft,review,publish). Creating private content for department users.

**My Solution(SO FAR):**

I have the LDAP module install on our D7 site. I am mapping LDAP fields to the profiles and roles, Using LDAP queries with a view to display a "staff" page.

I have tinkered around with OG, Workbench, Workflow, TAC and TAC\_lite. SO FAR NONE really meet the control and goals we have set out to obtain.

***I am hoping that there is someone out here that has conquered a similar setup and could impart some of their wisdom on me.***

***All constructive thoughts will be appreciated***

# Answer
Well after much trial and error which included rebuilding permissions more times that I want to count. I came up with a solution based on the following link:

http://drupal.org/node/200631

A combination of Taxononmy Access Control and Taxonomy on content type, which allows for a almost module-less solution.

Hope this helps someone else.
> 1 votes

---
Tags: workflows, authentication-authorization, taxonomy-terms
---


title: Drupal aggregate css crashes IE7

text:
# Question
Title: Drupal aggregate css crashes IE7
If I turn on aggregate css in my performance config and then load my site in IE7, the browser crashes. Any ideas why that might be?

Thanks, Paul

# Answer
There is a size limit of 300kb per file and a limit of 32 files.

http://joshua.perina.com/africa/gambia/fajara/post/internet-explorer-css-file-size-limit

http://social.msdn.microsoft.com/Forums/en-US/iewebdevelopment/thread/ad1b6e88-bbfa-4cc4-9e95-3889b82a7c1d
> 5 votes

---
Tags: 7, theming, performance
---


title: How to embed a search result on a node?

text:
# Question
Title: How to embed a search result on a node?
I am looking for a while to include a search results on a node.

Let me explain:

Administrator side, i wish i could, when i create a node, enter search criteria (eg "home + garden"-cellar), which generates me, when viewing the node, a list of nodes matching these criteria.

It will give : The title of my node, body, and below the result of my research.

I do not know if this is clear, but how could I do that?

I'm using Search API on my site, i should programmatically execute a search in the index from keywords ... but I'm stuck on this point.

Thank you in advance! Joel.

# Answer
> 0 votes
So, I will create my own module to do that. The module will offer a new field can be created on any type of content, and will accept search criterias, the number to display, and so a search result will appear in the node.

# Answer
> 0 votes
Drupal's core Search module should be enough for what you want to achieve. But in case you need more information about Search in Drupal this article should help you out.

---
Tags: views, search
---


title: Markdown and Google Prettify

text:
# Question
Title: Markdown and Google Prettify
I have been working on a site, that allows users to submit encryption algorithms, for other users to test and/or crack them.

The problem I am having is in the text editor that I want to use to do this with. Being that I am now very used to, and comfortable with the Stack Exchange Markdown, I wanted to make my site use the same thing.

What I tried, was downloading the Markdown filter module, along with the Markdown Editor for BUEditor and Google Code Prettify modules.

I have been playing around with it for a little while, trying to configure it, and I noticed that there are several problems, that I can't figure out how to solve.

1. Block quotes don't work: When attempting to make a block quote, instead of making it correctly, it just looks like `> this is pseudo block quote text`.
Is there a library that I need to / can install to get this to work?
2. Google prettify is working, but not coloring the code.
Basically, I can get prettify to make the code look like this:

```
public static void main (String[] args) {
  System.out.println("this is a test example");
}

```

It is not highlighted.

```
public static void main (String[] args) {
  System.out.println("this is a test example");
}

```

What am I doing wrong? Is this just a simple css issue? Is it something bigger? Should I use a different module entirely, and if so, which one? (I am using omega as my default theme. You can see an example of this that I created for debugging purposes here.)

(Note: This is not a question about a module bug, I am wondering if there is something that I have forgotten to set up, or am doing wrong, not the module itself.)

# Answer
> 4 votes
I'm getting a 403 forbidden on your prettify.js. If you change the permissions of the `sites/all/libraries/prettify/src` folder to 777, It should solve your problem.

---
Tags: 7, input-formats
---


# Question
Title: Noob question about private files and Content Access
This is almost certainly a really stupid question, but the Drupal 7 site we're building has an image gallery that users can upload content to. Unauthenticated users should not be able to see these images, but some other rôles should be able to see all the images uploaded by other users. The way we first built it, images all show up from a directory below the webroot, so anyone can see the image, if they know the URL.

I thought Private files would be my solution, so I followed the instructions there, setting up a folder in our filesystem (above the webroot, so you can only get there via Drupal) and changing the field settings within the appropriate content type to use Private files as the Upload destination and then went to set a bunch of Custom permissions, so that the appropriate users have "View anyone's value for field *Image*" (and so on) but that Anonymous users don't.

Then I cleared all the caches and went to upload a new image. If I go to the node page and right click to get the image URL, though, pasting that into an Anonymous Browser Mode window still shows me the image.

So I figured maybe I just needed something more fine-grained or that I'd implemented it wrong.

So I enabled the Content Access module and went back to the appropriate Content type and set the Access Control settings so that only the appropriate rôles can "View any gallery\_image content" (and so on). Clearing the caches, uploading another new image, I can still grab the URL and see it from a new Anonymous Browser Mode window.

Now the Private files thing seems to be doing the right thing — the image URL is now `/system/files/styles/image_thumbnail/private/gallery/images/filename.jpg` and the files are appearing in the right part of the filesytem, but Drupal doesn't seem to be respecting the access control — or even just requiring that you log in.

Presumably I've done something wrong somewhere, as it seems like I'm implementing the right thing and I've just made a mistake somewhere. So is there an obvious step I'm missing?

**Update:** The hosting environment is RedHat Linux and we don't allow `.htaccess` files (we're developing the site, a third-party is responsible for security, so they would rather everything go into the `httpd.conf` instead). This is part of why I deliberately close a directory above the webroot, so that a `.htaccess` file would not be necessary. I do notice, though, that if I try to access `/system/files/styles/image_thumbnail/private/gallery/images/` in a browser, I get a Drupal 403 message, not the apache one.

# Answer
I believe that this issue was fixed in SA-CORE-2012-002 - Drupal core multiple vulnerabilities instead of being posted to a public site like this. In the future something like this should be reported to the security team. And, if upgrading Drupal core doesn't fix your bug let's discuss more details by having you submit a new Core security issue where we can figure out what's going on in private and then, if appropriate, release a patch that fixes the bug.
> 5 votes

# Answer
I did a site similar to this also. My setup was nodeaccess to configure permissions on the gallery and setting the file system to private that way a user could not just browse to yoursite.com/sites/all/files/image.jpg this seems to be working great for me and it also gives you the ability to control other content types if you so choose. Not sure if this is going down the right path or not if you think it might help I would be happy to discuss it further with you.

Thanks, Justin
> 2 votes

---
Tags: 7, media, users, files
---


# Question
Title: User-submitted reviews of multiple aspects of a business?
My site is based off of user-submitted reviews of businesses. Instead of just an overall rating as provided by fivestar, I want users to rate different aspects & services provided by the business. For example, I'd want them to rate "staff" on a scale of "very unhelpful" to "very helpful," and "quality of clothing" on a scale of 1-10. I'd ideally also want a form field where the user could enter, for instance, how much they spent at the store.

What would be the best way to create a review form for users to fill out, and then to subsequently display the average ratings/amounts of each individual aspect on the business node?

Additionally, I'd need to add up all of these average ratings in order to create an overall "grade" of the business (i.e. if there are two aspects to be reviewed, each worth 10 points, and one has an average of 5 while the other has an average 6, then the business would get an overall grade of 11/20). Hopefully this would be possible with whatever system is suggested. Preferably, I'd like to use Display Suite to display the gathered averages and overall grade since I already have a template for my pages created in it.

# Answer
In Drupal 7, you can create a review as a custom content type. Staff could be rated as "very unhelpful" to "very helpful" using a field of type `list (integer)`. Quality of clothing could also be done with a `list (integer)`. For the time customers spent at the store, the field type to use depends on what you will do with the data later.

You could then create custom displays for this content type using Views. Views integrates with Display Suite as well so you could use that if you liked, though I'm not sure it's the best solution.

As for the averages, you'll need to know some PHP, but you can use the Computed Field module. Even if you are not very familiar with PHP, there are many examples on that module's documentation page.

If you're new to Drupal and all of this is very confusing, I highly recommend the book *Using Drupal* published by O'Reilly. The second edition just came out recently and covers Drupal 7; it contains an explanation of how to use fields/content types and views (chapter two) as well as how to build a job posting site (chapter three) and product review site (chapter five), two examples that would probably be highly informative for you.

Good luck!
> 1 votes

---
Tags: forms
---


# Question
Title: how to update a field created with field_create_instance
I'm building a module which implements hook\_enable to create fields. But as I'm developing I noticed a error in my code causing fields to be created in a wrong way.

Is there a way to update these fields? preferably using code so I can also use this code to hide these fields from lets say a user profile once the module is disabled.

here's my code that I used to create those fields:

```
//calling my function
popover_create_user_field('field_firstname', 'Voornaam', 'textfield', 1);

/**
 * field creator helper function
 */
function popover_create_user_field($field_name, $field_label, $field_type, $visible_on_registration_form = 1) {
    // Check if our field is not already created.
    if (!field_info_field($field_name)) {
        $field = array(
            'field_name' => $field_name,
            'type' => 'text',
        );
        field_create_field($field);

        // Create the instance on the bundle.
        $instance = array(
            'field_name' => $field_name,
            'entity_type' => 'user',
            'label' => $field_label,
            'bundle' => 'user',
            // If you don't set the "required" property then the field wont be required by default.
            'required' => TRUE,
            'settings' => array(
            // Here you inform either or not you want this field showing up on the registration form.
                'user_register_form' => $visible_on_registration_form,
            ),
            'widget' => array(
                'type' => $field_type,
            ),
        );
        field_create_instance($instance);
    }
}

```

Lets say I want to update the `user_register_form` visibility to `0` so it will be hidden.

# Answer
You can use a combination of `field_info_instance()` and `field_update_instance()`:

```
// Load the instance
$instance = field_info_instance('user', $field_name, 'user');

// Make whatever changes you need to, e.g.
$instance['settings']['user_register_form'] = 0;

// And save it again
field_update_instance($instance);

```
> 3 votes

---
Tags: 7, entities
---