# Question
Title: What might be stopping this Contextualised Filter work in Block (please)?
I am stuck making a contextualised filter in Block View (and I guess if I knew my question, I would also know my answer).

The view comprises

1. A set of images which I can see in the View before I set up the Contextualised View with their tags
2. Relationship with Content: Taxonomy terms on node, choose the correct Taxonomy, and check required
3. Under Contextual Filters, Taxonomy:name
4. Default View
5. Raw value from Url
6. Position is tricky .. the path alias is albums/\[node:title\] but this is a multilingual site so en/albums/\[node:title\] (I have tried positions 1,2, 3)
7. Check Specific Validation Criteria
8. Validator:Taxonomy
9. Check correct taxonomy
10. Term Name
11. Tested check/unchecked spaces to hyphen Additional information The tag is input exactly as the \[node:title\] If the \[node:title\] is Barking Dogs, then that is the tag. So the \[node:title\] is changed by Drupal to barking-dogs and so is the tag. But the name of the tag is not. The name of the tag remain Barking Dogs. Results
12. When I put a tag name into the preview query, I get the correct results a. For one word tags b. When I type the phrase with space e.g. The Funniest Cat
13. When I type the shortened phrase, i.e., funniest-cat, I get no results. Checking the transform spaces into hyphens doesn’t help.
14. When I use the path alias /albums/\[node:title\], I get the title, such as The Funniest Cat, but no Block.
15. The Block itself works – If I request a summary when validation fails, that is displayed. But no contextualised filter.

I am out of ideas. If anyone can spot where I have gone wrong, I’d be grateful. Or have an idea how to test, as grateful. Thanks. Jo

# Answer
Found the answer - a logical issue rather than a question of using the controls.

The key was to reverse the order of bringing in content. Set the main content-type as galleries, then use an entity relationship (set that up first) on Relationship to bring in fields from images and sort on them.

With this procedure, Views can use a Contextual filter for the Galleries. I will wirtie it out more fully on my blog.
> 0 votes

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


title: ckeditor yellow buttons

text:
# Question
Title: ckeditor yellow buttons
I have installed ckeditor module for drupal 7. Whenever any drupal form loads up, it comes up with yellow ckeditor buttons. I have checked the configuration page to hide the yellow background of ckeditor ,but there's ain't any settings.

So how can I hide this yellow background color. Is this CKEDITOR theme or just configurable? Has anyone experienced this issue?

# Answer
It is Configurable. Go to

> Admin -\> Configuration -\> CKEditor

And Edit the relevant profile in the text formats.(In your Case choose edit the fullhtml) Choose **Editor Appearance** and there will be a Drop down to choose **User Interface Color**, Select **CKEditor Default**. If its already default then there must be some CSS override.
> 2 votes

---
Tags: wysiwyg
---


title: How to delete a Grant by GID

text:
# Question
Title: How to delete a Grant by GID
Typically grants are deleted by `$nid` whenever new grants are added. In fact this function is baked into node\_access\_write\_grants() (when `$delete = TRUE`).

I have been using custom GID's to represent different users's Address IDs (`$aid`). When a user edits his/her address I want all the old grants with that GID/AID to be deleted but leave the grants on the particular node to be untouched.

# Answer
It would appear to me that Drupal 7 has no built in way to delete grants by GID, only by `$node`. Because of this I'm advocating doing a simple database query very similar to the query in node\_access\_write\_grants().

Original:

```
 if ($delete) {
    $query = db_delete('node_access')
             ->condition('nid', $node->nid);
    if ($realm) {
      $query->condition('realm', array($realm, 'all'), 'IN');
    }
    $query->execute();
 }

```

My code:

```
$query = db_delete('node_access')
         ->condition('gid', $address->aid);
$query->execute();

```

Perhaps there's something to be said for using the 'realm' field to circumvent this issue. However, this seems to work. I'd love to know what the community thinks.
> 0 votes

---
Tags: users
---


# Question
Title: How can I insert conditional logic into a render array?
Given the following render array, I'd like to insert some logic so that that $number of rows are created, but I can't just insert a `for` loop in the middle of defining my render array, I don't think. What can I do? $number will always vary.

```
function foo($bar, $number) {
  return $table = array(
    '#theme' => 'table',
    '#header' => array(t('Header 1'), t('Header 2')
    '#rows' => array(
   // for ($count = 1; $count <= $number; ++$count) {
        array($bar[$count], $bar[$count])
   // }
    )
  );
}

```

Thanks

# Answer
> 1 votes
You could create the $rows array with PHP before passing it to theme\_table:

```
function foo($bar, $number) {
  $rows = array();
  for ($i = 0; $i < $number; $i++) {
    $rows[] = $bar[$i];
  }
  return array(
    '#theme' => 'table',
    '#header' => array(t('Header 1'), t('Header 2')),
    '#rows' => $rows,
  );
}

```

---
Tags: theming
---


title: Drupal Webform Radio button slider?

text:
# Question
Title: Drupal Webform Radio button slider?
I have created a webform in Drupal. It has a pagebreak after every question.

What I want to achieve is the following: When someone clicks on a radio button, the next question should slide up without the user clicking the next page button.

I have tried with theming, but I am not very experienced with Drupal, PHP, or jQuery.

This is the link to my webform.

# Answer
> 0 votes
You can add to your page something like

```
<script>
(function ($, Drupal, window, document, undefined) {
  $(document).ready(function() {
    $('.form-radio').click(function() { $('#edit-next').click(); });
  });
})(jQuery, Drupal, this, this.document);
</script>

```

This is better done by adding a .js file via `drupal_add_js()`. Be aware that, since you are forcing your user to submit a form, you should provide a way to get back and resubmit a different choice.

---
Tags: theming, nodes, webforms, javascript
---


# Question
Title: Drupal 7 db_insert() execute() error when table contains unique keys
I have a database (mysql) table that contains a unique key in `barcode` column.

What I intend is this:

* I have a form that has a `barcode` field.
* When user submits the form and the barcode entered already exists in the database table, I should just give an error message.
* Currently, it gives me `PDOException: ... Duplicate entry` and the page contents does not load.

This is how I did the insert:

`$insert = db_insert('mymodule_mytable')->fields($fieldarray)->execute();`

At that line, Drupal 7 returns PDO error so I cannot execute the lines after it. Thus, I cannot also check the return value in `$insert`.

Is there workaround to avoid the PDO error? I need to do something like:

```
if($insert === FALSE) {
  drupal_set_message(t('Error'), 'error');
}

```

# Answer
PHP has exception handling in the form of `try...catch` blocks:

```
try {
  $insert = db_insert('mymodule_mytable')->fields($fieldarray)->execute();
}
catch (PDOException $e) {
  drupal_set_message(t('Error: %message', array('%message' => $e->getMessage())), 'error');
}

```

So rather than ignore the error completely, you can actually respond to different types of exception and react accordingly.
> 7 votes

# Answer
I'm not sure if one should rely on exception handling here as the accepted answer suggests. Instead of introducing a `try...catch` block, a better approach could be to explicitly check if the record with the ID already exists before inserting it:

```
if (db_query("SELECT 1 FROM {mymodule_mytable} WHERE mid = :mid", array(':mid' => $mid))->fetchField()) {
  drupal_set_message(t('ID already exists!'), 'error');
}
else {
  // Perform the insertion.
}

```

**Edit:** As mentioned by kiamlaluno in the comments, the added advantage of this approach is that checking for a duplicate ID can take place separately in the form validation handler, where the user input is supposed to be checked.
> 2 votes

---
Tags: 7, database
---


title: Change colors of account

text:
# Question
Title: Change colors of account
I have created a field(select list) with some colors. I want to let my site users choose the color (color of menus, blocks ...) of their account.

How can I do this?

# Answer
> 1 votes
In my example I will assume that you have a color field called **color** (machine name: **field\_color**) already set to user fields `admin/config/people/accounts/fields`

By following these steps you'll be able to achieve what are you looking for.

1. Create Drupal custom module. Ref Creating modules.
2. Implement `hook_init` to your custom module
3. In the `hook_init` you need to implement `drupal_add_css`
4. Set HTML elements you need to let users to change; according to current user color selection.
5. The final code should look like the following:

---

```
function MODULE_NAME_init() {
  global $user;
  $account = user_load($user->uid);

  if(isset($account->field_color['und'])) {
    $color = $account->field_color['und'][0]['value'];

    drupal_add_css(t('#menu { background-color: #@color; }', array('@color' => $color)), array(
      'type' => 'inline',
      'media' => 'screen',
      'weight' => '10000',
    ));
  }
}

```

**Note:** change `MODULE_NAME` to your desirable module name.

---
Tags: entities, users
---


title: How Batch Works Around the PHP Timeout

text:
# Question
Title: How Batch Works Around the PHP Timeout
The Drupal 7 documentation introduces the Batch API as:

> Functions allowing forms processing to be spread out over several page requests, thus **ensuring that the processing does not get interrupted because of a PHP timeout**...

I took this to mean that Batch handles the timeout-related issues for the developer.

However, other posts (ie. How does the batch API work internally?) imply that it is the developer's responsibility to tell Batch how much work to do before waiting for another user to arrive and Batch to be invoked again --- thereby avoiding the timeout.

If the latter is true then I assume Batch does not guarantee that jobs won't be timed out. Does Batch provide any guarantees? Is it up to the developer to guess how much Batch can process before timing out?

Thank you!

# Answer
Batch simply says "I will do N number of things (at most) and then do a page refresh ... and do more."

If you say do 5 items per job chunk that take 5 seconds each you would be fine with the default php timeout value of 30 seconds.

If you say do 20 items per job chunk that take 5 seconds each, your workload per request is too high and will likely timeout.

Remember when your in PHP the lifecycle of a page is `request in -> response out`. And that your webserver keeps each thread alive for a finite amount of time. You have to work around that timeout -- which the Batch API helps you do.

Running stuff from say Drush, server side using community modules such as Migrate can help you completely avoid timeouts if need be.

**EDIT**

Also bear in mind that every page request is a full drupal bootstrap and Batch API picks off where it left off. That is one of the most expensive operations when using the Batch API, reloading drupal every N items. That's why people have been working on server side techniques to create nodes, import content, etc. Batch API is great for simple, repetitive tasks. But it tends to fall apart in either complex, or very very large datasets.
> 6 votes

# Answer
The batch API simply registers `_batch_shutdown()` as shutdown function with `register_shutdown_function()`. That function just saves in a database table the current state of the batch being executed.
The Batch API doesn't provide any guarantee that the operation you are executing is not interrupted in the middle. That is why batch operations normally execute simple operations like reading a database row from saving a table, and saving a database row in another table.
> 3 votes

---
Tags: batch-operations
---


# Question
Title: get drupal base path in views rewrite result
i want to get Drupal base path in views rewrite result. but rewrite result doesn't support PHP code.

how can i add Drupal base path to **replacement patterns** in views rewrite result? i try installing some modules like entity api, token but it doesn't help.

i know there is http://drupal.org/project/views\_php and i get base path with php code but it has a dev release.

# Answer
> 1 votes
You can do this in the theme layer by overwriting the template and calling `base_path()`. If you are displaying Fields, you can overwrite the template for the field you want to rewrite.

# Answer
> 0 votes
1. Its pretty safe to use views\_php I have been using this without any problem so far.
2. May be without the module you can do the following things 2.1 Check the Output this field as a link 2.2 Give the link path let say your domain is www.xyz.com and you want to link this field to path www.xyz.com/xyz, so in the link path field jus give xyz and it will automatically pick your url.

look at screenshot if it helps.

---
Tags: 7, views
---


title: Custom site administration form/page

text:
# Question
Title: Custom site administration form/page
I'm looking to create a page on my site that will allow certain users to perform administrative tasks without them needing to have access to the entire administrative back end.

I want to create a page/form that will allow my user to:

* Change the default logo (like is on the Appearance page)
* Change the site slogan
* Put the site into maintenance mode/Change the maintenance mode text

I have no doubt there is not a module out there with this capability, so I assume I am going to have to make use of the form API, but I was wondering if anyone could give me a point in the right direction.

Kind regards

# Answer
Like @jimajamma said in the question comments, you most likely want to create a custom module that implements `hook_menu()`, creates a form, and handles the form submission. Also, notice the trick where you can use the `drupal_get_form()` page callback to build a page that is just rendering a form. To use this, you need to pass the name of the function that returns your form as a page argument.

```
/**
 * Implements hook_menu().
 */
function demo_menu() {
  $items['admin/config/demo'] = array(
    'title' => 'Demo page title',
    'type' => MENU_NORMAL_ITEM,
    'page callback' => 'drupal_get_form',
    'page arguments' => array('demo_form'),
    'access arguments' => array('administer content'),
    // Choose an appropriate permission or create your own using hook_permission()!
  );
}

/**
 * Provides an admin form to change the site slogan, put the site into
 * maintenance mode.
 */
function demo_form($form, &$form_state) {
  // Adapted from system.admin.inc line 1495.
  $form['site_slogan'] = array(
    '#type' => 'textfield',
    '#title' => t('Slogan'),
    '#default_value' => variable_get('site_slogan', ''),
    '#description' => t("Change the site's slogan."),
  );

  // Taken from system.admin.inc line 2201.
  $form['maintenance_mode'] = array(
    '#type' => 'checkbox',
    '#title' => t('Put site into maintenance mode'),
    '#default_value' => variable_get('maintenance_mode', 0),
    '#description' => t('When enabled, only users with the "Use the site in maintenance mode" <a href="@permissions-url">permission</a> are able to access your site to perform maintenance; all other visitors see the maintenance mode message configured below. Authorized users can log in directly via the <a href="@user-login">user login</a> page.', array('@permissions-url' => url('admin/people/permissions'), '@user-login' => url('user'))),
  );
  $form['maintenance_mode_message'] = array(
    '#type' => 'textarea',
    '#title' => t('Maintenance mode message'),
    '#default_value' => variable_get('maintenance_mode_message', t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Drupal')))),
    '#description' => t('Message to show visitors when the site is in maintenance mode.')
  );

  return $form;
}

/**
 * Submits demo_form().
 */
function demo_form_submit($form, &$form_state) {
  variable_set('site_slogan', $form_state['values']['site_slogan']);
  variable_set('maintenance_mode', $form_state['values']['maintenance_mode']);
  variable_set('maintenance_mode_message', $form_state['values']['maintenance_mode_message']);
}

```

The form elements for the logo are a bit more complicated, but I suggest you take a look at `system_theme_settings()` in system.admin.inc line 399.
> 1 votes

---
Tags: forms
---


# Question
Title: Error Drupal 7 body content missing when adding new content
Hi my drupal 7 creating a new content, suddenly the body field disappear? and i dont know what cause this? is there anyone can help me

# Answer
The body field is field attached to content type, so if its remove from particular content type, then it mean you have removed the fields from the content type.

You can enable the fields again for the content type by Administrator -\> Structure -\> Content type -\> \[type\] -\>Manage fields.

In the section "Add existing field", you can select the fields "body" and add to content type.
> 1 votes

---
Tags: views
---


# Question
Title: Is there a pre-styled Omega subtheme out there?
I am after a theme that looks good out of the box and I don't need to make a lot of theming changes. The customer is not fussed about the styling but obviously doesn't want a stark/bare looking site either. The omega theme fits the bill functionality wise, it's responsive and the regions/sections suit us. However, it is way too bare/stark. I've so far tried Omega kickstart, omega and omega-alpha.

Any suggestions on a pre styled free theme I can used that is based on the Omega "framework"?

# Answer
Here is the complete listing of themes which uses the omega theme as a base theme.

Apart from that you can get the list of various themes/sites which uses omega theme on omega theme project page
> 1 votes

---
Tags: theming
---


# Question
Title: Delete/ Deactivate account in a separate block
I want the authenticated users on my site to be able to delete their own account or temporarily block/de-active. I give the necessary permissions for this. Well and good for now. However, the tricky part is that i want these as separate forms in a page different that user edit. Something like shown in the image below: So that when the user navigates to this page say node/100 then the above is displayed. Any suggestions how to achieve this.

Regards

# Answer
What you are describing will require a custom module that will provide the non standard functionality.

You will need to provide hooks for blocks (hook\_block\_info and hook\_block\_view) producing forms using the FAPI to produce the forms as you are showing in your mock.

Deleting an account would require using form validation to test that the username and password is correct and matches the content that you are viewing as well matches the user that is logged in. Once validated you would call the user\_delete function, however be aware that this will delete all content owned by the user.

Disabling or Deactivating account will require a hook\_block\_info and hook\_block\_view as well the form using the FAPI as well a subset of the validation mentioned above, then calling the user\_cancel function passing in the appropriate arguments.

The forms could be rendered using... 1. the blocks ui with conditional visibility settings. 2. at the theme level using a preprocess\_page hook in template.php 3. other...

As Drupal is like a swiss army knife and this is one of many ways to solve the issue.
> 4 votes

# Answer
That can be achieved with a custom module. In the example code below we assume the custom module is called disable\_my\_account - if your module is called something different then replace everywhere is says disable\_my\_account with the name of your module.

First create a hook\_menu item for the disable my account page. This can call drupal\_get\_form directly and pass the name of our form as an argument:

```
function disable_my_account_menu() {
    $items['disable-my-account'] = array(
        'title' => 'Disable My Account',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('disable_my_account_form'),
        'access arguments' => array('access content'),
        'type' => MENU_NORMAL_ITEM,
    );
    return $items;
}

```

Now we need to define what is in the "disable\_my\_account\_form":

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

    $form = array();

    // put the delete part in one frameset

    $form['delete'] = array(
        '#type' => 'fieldset',
        '#title' => 'Delete Account',
        '#description' => t("Are you sure you want to PERMANENTLY DELETE your account?"),
    );
    $form['delete']['username'] = array(
        '#type' => 'textfield',
        '#title' => t('Email or username'),
        '#required' => TRUE,
    );
    $form['delete']['password'] = array(
        '#type' => 'password',
        '#title' => t('Password'),
        '#required' => TRUE,
    );
    $form['delete']['delete_submit'] = array(
        '#type' => 'submit',
        '#value' => t('DELETE MY ACCOUNT'),
    );

    // and put the disable part in a separate frameset

    $form['disable'] = array(
        '#type' => 'fieldset',
        '#title' => 'Disable Account',
    );
    $form['disable']['disable_account'] = array(
        '#type' => 'checkbox',
        '#title' => t('Temporarily deactive my account'),
    );
    $form['disable']['disable_submit'] = array(
        '#type' => 'submit',
        '#value' => t('OKAY'),
    );

    return $form;

}

```

Now the actual functionality to delete and disable accounts is going to sit in the form submit function:

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

    global $user;

    switch($form_state['values']['op']) {

        case 'DELETE MY ACCOUNT':

            // check the details supply authenticate and match the user currently logged in
            if(user_authenticate($form_state['values']['username'], $form_state['values']['password']) && $form_state['values']['username']==$user->name) {

                // delete the account
                user_delete($user->uid);
                // set a message and send the user to the homepage
                drupal_set_message('Your account has been deleted');
                drupal_goto();

            } else {
                drupal_set_message('That username and or password is not valid.');
            }

            break;

        case 'OKAY':

            // disable the account and save it
            $edit['status'] = 0;
            user_save($user, $edit);

            break;

    }

}

```
> 3 votes

# Answer
Hi I did this with some custom coding and using panels.in the following codes I assume user is logged in. Add the following code in your custom module and remember to change mymodulename with your module name.

```
<?php

/**
 *
 * Implements hook_menu_alter()
 * Setting permission for our final page for logged in user
 */
function mymodulename_menu_alter(&$items) {

// I have created panel page with path as user-settings
// You found me.
        $items['user-settings']['access callback'] = 'user_is_logged_in';
}

/**
 *
 * Implements hook_menu()
 * Redirect Path after user account is deactivated or deleted
 * @return
 *   $items array of menu items created programmatically
 */
function mymodulename_menu() {
  $items['user-change/%/%'] = array(
    'title' => t('Disable My Account'),
    'page callback' => '_custom_user_deleted_successfully',
    'page arguments' => array(1, 2),
    'access arguments' => array('access content'),
  );
  return $items;
}

/**
 *
 * Page Callback for hook_menu()
 * Redirect User to appropriate page after user deletion or diactivation with related messgae
 * @return
 *   $items array of menu items created programmatically
 */
function _custom_user_deleted_successfully($op, $uid) {
  if ($op == 'delete') {
    $success_message = 'User Account with user uid' . $uid . ' has been deleted';
  }
  elseif ($op == 'disable') {
    $success_message = 'User Account with user uid' . $uid . ' has been disabled';
  }
  unset($_SESSION['user_change']);
  return $success_message;
}

/**
 *
 * function which returns user delete form
 * @return
 *   $form array of form fields
 */
function _custom_user_delete($form, $form_state) {
  $form = array();
  $form['delete_account'] = array(
    '#type' => 'container',
  );
  $form['delete_account']['user_email'] = array(
    '#type' => 'textfield',
    '#title' => t('Email'),
    '#size' => 30,
    '#description' => t('Enter Your Email Address'),
  );
  $form['delete_account']['user_password'] = array(
    '#type' => 'password_confirm',
  );
  $form['submit_form'] = array(
    '#type' => 'submit',
    '#value' => t('Delete'),
    '#submit' => array('_custom_user_delete_submit'),
  );
  $form['#validate'] = array('_custom_user_delete_validation');
  return $form;
}

/**
 *
 * Validation function for custom user delete form
 * Validate if the email address input by the user is same as the email of curent logged in user.
 * validate the password input by the user
 */
function _custom_user_delete_validation(&$form, &$form_state) {
  global $user;
  if ($form_state['values']['user_email'] != $user->mail) {
    form_set_error('user_email', t('please enter your email address'));
  }
  $uid = _custom_user_authenticate($user, $form_state['values']['user_password']);
  if ($uid == 0 || $uid != $user->uid) {
    form_set_error('user_password', 'authentication failed');
  }
  if ($uid == 1) {
    form_set_error('user_password', 'Admin account can not be deleted');
  }
}

/**
 *
 * Submit function to delete user account
 */
function _custom_user_delete_submit($form, $form_state) {
  global $user;
  $_SESSION['user_change']['uid'] = $user->uid;
  user_delete($user->uid);
  drupal_goto('user-change/delete/' . $_SESSION['user_change']['uid']);
}

/**
 *
 * function to authenticate the password given by the logged in user
 */

function _custom_user_authenticate($account, $password) {

  require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
  if (user_check_password($password, $account)) {
// Successful authentication.
    $uid = $account->uid;
  }
  else {
    $uid = 0;
  }
  return $uid;
}

/**
 *
 *  function which creates the custom ser disbale account
 */
function _custom_user_disable($form, $form_state) {
  $form = array();
  $form['disable_account'] = array(
    '#type' => 'container',
  );
  $form['disable_account']['email'] = array(
    '#type' => 'checkbox',
    '#title' => t('Disable My Account'),
  );
  $form['submit_form'] = array(
    '#type' => 'submit',
    '#value' => t('Okay'),
    '#submit' => array('_custom_user_disable_submit'),
  );
  return $form;
}

/**
 *
 * Submit handler to cutom user disable account form
 * Diable a logged in user account
 */
function _custom_user_disable_submit($form, $form_state) {
  global $user;
  $_SESSION['user_change']['user_disable'] = $user->uid;
  $edit['status'] = 0;
  user_save($user, $edit);
  drupal_goto('user-change/disable/' . $_SESSION['user_change']['user_disable']);
}

Download and enable panels now
Create a panel page with path as user-settings.If you want to put the path of your choice then serach for user-settings in the above code till you find comment saying "You found me",change the user-settings path with the same path you gave for your panel page.
Choose 2 column layout for panel
Now enables Php Filter module(this modulw comes with drupal core).
Back to the panel page, as you must be seeing two column panel layout on the left panel column add content using "New Custom content".
It will open a form, where in the body field use Php code as text format and add the following code.
<?php
  print drupal_render(drupal_get_form('_custom_user_delete'));
?>
similarly in the right column panel pane add the following code.
<?php
  print drupal_render(drupal_get_form('_custom_user_disable'));
?>
* remember to turn PHP Code as text format

```

save the panel and browse yoursite/user-settings or whatever you have changed to.

here is a screenshot of accomplishment.
> 2 votes

# Answer
You can the try the following Drupal plugin and use the permissions within drupal admin page to set it so users can select functions on if they want to delete their account.

http://drupal.org/project/user\_delete

It allows you to do the following:

1. block a user
2. block a user and unpublish all submitted content, including nodes and comments
3. delete a user and reassign the submitted content to the anonymous user
4. delete a user and delete all submitted content including nodes and comments

Also have a read of the following: http://groups.drupal.org/node/252233
> -1 votes

---
Tags: 7, users
---


# Question
Title: Views Group By how to display only group headers with COUNT of rows
I would like my view to display just one field and additionally group by this field. So, I set the following:

* checked "Use Aggregation" in Advanced settings
* added the field to FIELDS section
* in FORMAT section set the Format-\>Settings to group by this field
* in FIELDS section, in Field-\>Aggregation chose "Group fields together"

As a result, I get the following output, assuming the field contains color values:

```
Blue
  Blue
  Blue
Red
  Red
  Red
  Red
Green
  Green

```

How to prevent displaying rows and only display group headers together with the COUNT of rows? Like this:

```
Blue (2)
Red (3)
Green (1)

```

# Answer
I solved it. The problem with my View was that it was by default sorted by post date. Displaying the underlying SQL query showed that it selects the Post Date to be able to sort by it and that's why it displays each row.

So in this case, getting rid of detail rows means getting rid of the default sort. After that, the view displays only the Group Header row and one "Group By" row per group.

```
Blue
  Blue
Red
  Red
Green
  Green

```

To get rid of the Group Header row, hide it in CSS or in a relevant template tpl.php

In order to display the count, add the same field to the FIELDS section again, but this time with Aggregation Settings set to Count. It will look like this:

```
Blue
2
Red
3
Green
1

```

To add parenthesses, add Prefix and Suffix to the Field format. To display inline, check both fields in FORMAT-\>Field Settings-\>Display inline.
> 1 votes

---
Tags: 7, views
---


title: Date picker in views for Drupal 6

text:
# Question
Title: Date picker in views for Drupal 6
Is there any way one can display date pickers as filter for a drupal 6 view?

# Answer
> 3 votes
Yes, just use Date-Filter (node) and expose as Popup. I assume you have the Date module (6.x-2.9 in my case) and Date Popup module installed and set your Datepicker on admin/settings/date\_popup...

In Views it probably won't work in the preview, but on the view itself it will.

---
Tags: views
---


title: create directory with node

text:
# Question
Title: create directory with node
I am interested in making a 'physical' folder structure to match a hierarchy I create through content types.

My hierarchy currently exists in the format

```
-Container
--folder
---presentation

```

and I want to create a folder structure when each level is created that mimics this, so that would be

```
[container_name]
[container_name]/[folder_name]
[container_name]/[folder_name]/[presentation_name]

```

I've been trying to use the drupal\_mkdir() function within a module of my own creation which uses hook\_node\_insert, but I am a little too 'green' to know exactly what to do.

# Answer
The method I used to solve this was that in my Drupal site I had entity references at each level that connected me all the way down to my root. It was a simple process of using the functions such as `node_load()` to return information about the entity and its title, which I was then able to concatenate into a string of text like is in the example above: container\_name\]/\[folder\_name\]/\[presentation\_name\] After that I was able to simply use this code to build the folder after each node was submitted:

```
//$path contained the remaining file path to be built
$dirpath=variable_get('file_public_path', conf_path() . '/files');
drupal_mkdir("$dirpath/$path");

```
> 2 votes

---
Tags: files, nodes
---


title: Metatags not generated for views pages

text:
# Question
Title: Metatags not generated for views pages
I have installed the metatag module but it only works on the node pages and does not generate tags for the views pages.

I have also tried the metatags\_quick module which provide the metatags per path but it also did not generate tags on the views pages.

Any other module which will be useful for views pages or any other method?

# Answer
> 2 votes
We use metatags\_quick for our websites with no problem. You must make sure you've **checked** the tickbox "Use path-based meta tags" in `admin/config/search/metatags_quick` under the fieldset `GLOBAL SETTINGS` (it might be collapsed by default)

---
Tags: 7, views, meta-tags
---


# Question
Title: Module to display file from an SVN repo?
Looking for a way to display text files that are stored in an SVN repo or local filesystem. Exactly like http://www.mediawiki.org/wiki/Extension:Include works for mediawiki. Thanks a lot

# Answer
Have a look at Version Control API with Version Control API -- Subversion backend

I didn't use it but you can try

> This module provides an implementation of the Version Control API that makes it possible to use the Subversion revision control system.

P.S. Drupal 5 and 6 only
> 0 votes

---
Tags: files
---


# Question
Title: Replace last item in a Views grid of images
let's say I have 1000 image files on my server and I am paging the 10 newest (2 rows with 5 images each) on my frontpage in a views block, formatted as a 'grid'. The settings of my view are:

Format: Grid, Show: Fields, File: Rendered, and then filter by File: Type (= Image) and sort by File: Upload date

Instead of adding a "see more" link I would like to replace the 10th image with a "see more" **button** which has the same format as the images. Is there a way to only render a grid of **9** images and tell views which image to use as the 10th?

# Answer
> 1 votes
> But is there no way to actually get it into the grid in html from the Views UI?

As I can see thare is no way for that in views UI.

But here are possible custom solutions:

**Solution1**

1. Add "more link" in PAGER section. Than specify link in 'Link display' section under ADVANCED.
2. Style your link with css

**Solution2** Add new views row in `[hook_views_pre_render][1]`

**Solution3** Add new views row in custon views `template`

---
Tags: views, media, files
---


# Question
Title: How to Port customField PHP from Drupal 6 Views 2 to Drupal 7 Views 3
I have this piece of code that was in a Drupal 6 Views 2 customField PHP that I need to port to Drupal 7 Views 3 in a Global: PHP field but I can't figure why I get an empty ajax error upon building this code in the Global: PHP field value code.

Did the accessibles variables changed?

```
<?php
//var_dump($data);
if ($data->node_type=="project") {
echo "node/".$data->nid;
}
else
{
echo $data->node_data_field_slider_include_field_slider_link_value;
}
?>

```

**ANSWER**

You need to remove the `<?php ?>` tags.

# Answer
> 0 votes
You need to remove the `<?php ?>` tags.

---
Tags: views, entities
---


# Question
Title: How do add a condition to check if created node is language source (in a multilingual site)?
I need to fire a rule action when a node is created and this node is the original source in a multilingual site. This means that this node is not the translation of other node.

How do add a condition to check if the created node the original source in a multilingual site?

# Answer
Check your created node if it has a $node-\>tnid. The tnid (translation id) would be not null if its a translation from another node.
> 1 votes

---
Tags: rules, i18n-l10n
---


# Question
Title: Custom basic .js from theme dir prevents Splashify module from working
I am using latest Drupal 7 with latest Splashify version. Splashify (Splash in D6) is a simple module that uses jStorage js (from libraries/ dir) to add a splash/intro page for your Drupal site. So i.e. user enters my site and it gives him some intro splash page with like links to Enter site or Leave and etc. And that page is any node who's path/alias is chosen as a splash page. More about Splashify drupal.org/project/splashify

Now I found out that this module is not working because of some basic js my theme has. I tried on default Bartik and the module works just fine.

The problem is I am not js developer and don't know what's the problem. So I only managed to track down the problem.

There's the code, maybe someone knows what might be the issue, it's jQuery:

```
(function ($) {
  /* Slideshow */
  Drupal.behaviors.MYSITE = {
    attach: function (context, settings) {
      $(".carousel").jCarouselLite({
        btnNext: ".next",
        btnPrev: ".prev"
      });

      /* Rollover info */
      $(".block1").hover(function(){
        $(this).find("span.info").stop(false, true).fadeIn("fast");
      }, function(){
        $(this).find("span.info").stop(false, true).fadeOut("fast");
      });

      // Class for every 3rd row.
      $(".view-flavor-listings .views-row:nth-child(3n-3)").addClass("diff-margin");
      $(".view-content-inner .views-row:nth-child(5n-4)").addClass("diff-mrg");

      /* slidePager */
      $('.pages').slidePager({
        last:6,
        borders:1,
        change:function(n){
          var els=$('.thumbs li').removeClass('mrk')
          els.eq(n).addClass('mrk')
          els.eq(n+1).addClass('mrk')
          els.eq(n+2).addClass('mrk')
          $('.thumbs li').css('opacity',1)
          $('.thumbs li:not(.mrk)').css('opacity',1)
        }
      })
    }};

    // Make Plupload default.
    $('.filefield-sources-list').each(function() {
      $('a.filefield-source-plupload', this).trigger('click');
      $(this).hide();
    });
  })(jQuery);

```

To be exact it's that part:

```
/* slidePager */
$('.pages').slidePager({
  last:6,
  borders:1,
  change:function(n){
    var els=$('.thumbs li').removeClass('mrk')
    els.eq(n).addClass('mrk')
    els.eq(n+1).addClass('mrk')
    els.eq(n+2).addClass('mrk')
    $('.thumbs li').css('opacity',1)
    $('.thumbs li:not(.mrk)').css('opacity',1)
  }
})

```

Maybe its missing some () or {} or something like that. I remember I built that .js from surfing Google throughout.

# Answer
> 1 votes
Looks like simple syntax error :

```
(function ($) {
  /* Slideshow */
  Drupal.behaviors.MYSITE = {
    attach: function (context, settings) {
      $(".carousel").jCarouselLite({
        btnNext: ".next",
        btnPrev: ".prev"
      });

      /* Rollover info */
      $(".block1").hover(function(){
        $(this).find("span.info").stop(false, true).fadeIn("fast");
      }, function(){
        $(this).find("span.info").stop(false, true).fadeOut("fast");
      });

      // Class for every 3rd row.
      $(".view-flavor-listings .views-row:nth-child(3n-3)").addClass("diff-margin");
      $(".view-content-inner .views-row:nth-child(5n-4)").addClass("diff-mrg");

      /* slidePager */
      $('.pages').slidePager({
        last:6,
        borders:1,
        change:function(n){
          var els=$('.thumbs li').removeClass('mrk');
          els.eq(n).addClass('mrk');
          els.eq(n+1).addClass('mrk');
          els.eq(n+2).addClass('mrk');
          $('.thumbs li').css('opacity',1);
          $('.thumbs li:not(.mrk)').css('opacity',1);
        }
      });

      // Make Plupload default.
      $('.filefield-sources-list').each(function() {
        $('a.filefield-source-plupload', this).trigger('click');
        $(this).hide();
      });
    } // attach
  } // behavior
})(jQuery);

```

---
Tags: 7, javascript
---


# Question
Title: Toggle text field depending on checkbox value in drupal 6
I need to toggle a textbox depending upon the checkbox value.

Basically i need to take email entries for updates.

Here is the form elements I used.

```
$form['chkupdates'] = array(
        '#type' => 'checkbox',
        '#title' => t('Sign up to receive email updates about Green Apple'),
        '#options' => array(
        '1' => t('Yes'),
        '0' => t('No')
        ),
        '#default_value' => FALSE,
        '#attributes' => Array('class'=>'sub-form-element',
        'id'=>'chkbox'),
);

$form['chkmail'] = array(
'#type' => 'textfield',
'#title' => t(''),
'#attributes' => Array('class'=>'field','id'=>'chktext'),
);

```

Please guide.I am rendering elements in tpl files so jQuery is acceptable. Thanks

# Answer
You could do something along these lines:

```
$('#CHKBOX').click( function() {

  if ($('#CHKBOX').is(':checked')) {
    $('#CHKTEXT').display();
  } else {
    $('#CHKTEXT').hide();
  }

});

```

where CHKBOX and CHKTEXT are the CSS ids of the form elements in the resulting HTML. If you know it will be hidden at the start, this can be simplified further into:

```
$('#CHKBOX').click( function() {
  $('#CHKTEXT').toggle();
});

```
> 1 votes

---
Tags: forms
---


title: Hide payment options with rules

text:
# Question
Title: Hide payment options with rules
My client wants to bypass payment options if a custom chooses shipping outside the US. I have figured out some of the parts using rules but I cannot figure out how to 1) skip the payment selection step or 2) hide the other shipping options.

For option 2, would I disable all payment methods in the Admin UI and then, using a series of rules, enable the ones I want based on the shipping method selected? That seems a little backward but it might work.

# Answer
> 2 votes
I would recommend you to disable payment method by default on which you have to operate(enable/disable). In rules you can check the condition where you have to enable the particular payment method & in action you can simply enable the payment method you want to.

This is what I have done in one project...as in action part it's hard to find remove option.

# Answer
> 0 votes
Try this module rules\_form

> Rules Forms Support provides a Rules based method for controlling forms and their elements. The module can be used to alter any form provided by Drupal core or contributed modules. Change element titles, descriptions, weights, and more, or validate form data and set form errors. Rules forms saves time and cost by affording site builders the ability to monitor and alter forms without the need to implement a custom module.

---
Tags: 7, commerce
---


title: Dynamically inject page content

text:
# Question
Title: Dynamically inject page content
I'm using Drupal 7. I want to set up a dynamic page, which shows expertises' portfolios. I want to have a basic framework for that page and query data dynamically into the page.

For example, when someone goes to site/expertise?=em, they will find Em's portfolio, but when someone goes to site/expertise?=sarah, they will find Sarah's portfolio. It should be the same page, but just dynamically injected data.

Ideally the administrator will be able to upload xml or excel files and somewhere in the template will query the data from the uploaded database to update the data. Is that even possible, or are there any modules I can use?

# Answer
You can create a view and add a contextual filter

Contextual filter :

Author filter :

Accept the author's name in the url :
> 1 votes

---
Tags: 7
---


title: Fill #options of select field

text:
# Question
Title: Fill #options of select field
I have a select field for a content type which has options generated dynamically. The options are updated in hook\_form\_alter(). The problem is that when I try to manipulate the posted data in submit callback, the field values are empty. Below is an example to better understand the issue.

```
function my_form_alter(&$form, &$form_state) {
    $options = array('a' => 1, 'b' => 2, 'c' => 3);
    $form['my_field'] = array(
        '#type' => 'select',
        '#title' => t('Label'),
        '#multiple' => TRUE,
        '#options' => $options,
        '#default_value' => '',
    );
    $form['#submit'][] = 'my_submit_handler';
}

function my_submit_handler($form) {
    echo "<pre>";
    var_dump($form['my_field']);
    echo "</pre>";
}

```

If I select options 2 and 3 for example; the var\_dump returns empty array().

# Answer
Submitted values are contained in `$form_state['values']`:

```
function my_submit_handler($form) {
  $selected_options = array_filter($form_state['values']['my_field']);
}

```

e.g. if you select '1' and '2' on the form, `$selected_options` will be `array('a', 'b')`
> 1 votes

---
Tags: 7, forms
---


# Question
Title: Varnish problem, user logged out for a HIT page
Have someone experienced simmilar problem, I've installed Varnish(v3, on Debian 6, Drupal 7), and also Varnish Drupal module, conigured settings php and vcl, and everything seems to work fine, except Logged-in users sometimes get "logged out", ie when they click on link they are redirected to cached Varnish page (HIT). For pages that are MISS everything is fine.

How can in enforce for logged in user to never hit cached page, thus get logged out?

Administrative pages are working well and never express such behaviour, as i followed few tutorials/setting how to setup vcl and config files.

Thanks!

# Answer
> 4 votes
Maybe too late, but I had exactly the same problem, I spent two days looking for what is wrong, then I read in settings.php:

> Without "Vary:Cookie", authenticated users would also be served the anonymous page from the cache.

So change `'ommit_vary_cookies'` from `TRUE` to `FALSE` in `settings.php` solved the problem.

```
$conf['omit_vary_cookie'] = FALSE;

```

# Answer
> 1 votes
You should use this rule in your default.vcl

```
# Remove all cookies that Drupal doesn't need to know about. ANY remaining
  # cookie will cause the request to pass-through to a backend. For the most part
  # we always set the NO_CACHE cookie after any POST request, disabling the
  # Varnish cache temporarily. The session cookie allows all authenticated users
  # to pass through as long as they're logged in.
  #
  # 1. Append a semi-colon to the front of the cookie string.
  # 2. Remove all spaces that appear after semi-colons.
  # 3. Match the cookies we want to keep, adding the space we removed
  # previously, back. (\1) is first matching group in the regsuball.
  # 4. Remove all other cookies, identifying them by the fact that they have
  # no space after the preceding semi-colon.
  # 5. Remove all spaces and semi-colons from the beginning and end of the
  # cookie string.
  if (req.http.Cookie) {
    set req.http.Cookie = ";" + req.http.Cookie;
    set req.http.Cookie = regsuball(req.http.Cookie, "; +", ";");
    set req.http.Cookie = regsuball(req.http.Cookie, ";(S{1,2}ESS[a-z0-9]+|NO_CACHE)=", "; \1=");
    set req.http.Cookie = regsuball(req.http.Cookie, ";[^ ][^;]*", "");
    set req.http.Cookie = regsuball(req.http.Cookie, "^[; ]+|[; ]+$", "");

    if (req.http.Cookie == "") {
      # If there are no remaining cookies, remove the cookie header. If there
      # aren't any cookie headers, Varnish's default behavior will be to cache
      # the page.
      unset req.http.Cookie;
    }
    else {
      # If there is any cookies left (a session or NO_CACHE cookie), do not
      # cache the page. Pass it on to Apache directly.
      return (pass);
    }
  }

```

---
Tags: proxies
---


# Question
Title: Organic Groups access to Entityforms: is it possible?
**The Gist**:

*Is it possible (and advisable) to use Organic Groups memberships to control access to Entityforms?*

**Explanation**:

I use OG groups for content access on an institutional site. All users have OG memberships that reflect the institutional department(s) they belong to. Nodes, views, and taxonomy terms all have fields (`OG Audience`) specifying which groups can view them.

For example, Admissions Office employees can access any content marked as accessible to the 'Admissions Office' OG group. Students can likewise access any content marked as accessible to the 'Students' OG group, etc.

Then comes Entity Forms. I'd love to have the same OG association for them, but as far as I can tell, this isn't supported (don't know if that's an OG or an Entity Form thing).

For an example of this, I have an "Academic Alert" eform type that only members of the 'Faculty' OG group should have access to/be able to submit. The group already exists, but how do I connect my eform types to my groups? Is that possible?

**Ideas I've Toyed With:**

1. *Rules* \- I know I should theoretically be able to create an eform access rule that hides the form from users without a certain group membership. This is less appealing because it means I have to create a Rule for every group that needs exclusive access to an eform--and then I have to manage a long list of groups *and* a long list of access rules. Additionally, the access rule simply hides the eform body, so links to the eforms still show up in menus for users that can't actually submit them.
2. *Custom module* \- I'm thinking of writing a module that allows me to specify an OG Audience for each entityform type (I'll somehow have to store a mapping, perhaps in a field or variable). Then I'll have to write custom access checks to compare the current user's OG memberships to the groups that "own" the entityform type being created. Someone please save my life and tell me there's a better solution than this. :)

Any thoughts, insights, clues, or direction would be very appreciated. Thanks!

# Answer
> 2 votes
I wrote a small custom module called `og_entityforms` that uses the Chain Menu Access API.

**The basics**:

1. Use `hook_menu_alter()` to chain a custom access callback to whatever eform pages you want to restrict. The result of the custom access callback is `AND`-ed with the result of the original callback to determine the access permission.
2. In the custom access callback `og_entityforms_entityform_access()` do your custom checking. I simply check to see if the user is a member of any of the groups that I want to have access to the eform.

* If it interests you, I also implement `hook_form_alter()` and add a 'Group Visibility' field to the `entityform_type_form`. That field is a multi-select list of groups. When the form is submitted, those groups are stored in a variable, and that variable is what I use in my access checks to tell which groups should have access to the eform.

**The code**:

```
/**
 * Implements hook_menu_alter().
 */
function og_entityforms_menu_alter(&$items) {
  $mappings = array(
    'og_entityforms_entityform_access' => array(
      'eform/submit/%entityform_empty',
      'eform/%entityform_type/confirm',
      'entityform/%entityform',
      'entityform/%entityform/edit',
      'entityform/%entityform/view',
    ),
    // 'og_entityforms_submissions_access' => array(
    //   'eform/%entityform_type/submissions',
    //  ),
  );
  foreach($mappings as $access_callback=>$paths) {
    foreach($paths as $path) {
      if (isset($items[$path]['access callback'])) {
        $args = isset($items[$path]['access arguments'])? $items[$path]['access arguments'] : array();
        chain_menu_access_chain($items, $path, $access_callback, $args, FALSE);
      }
    }
  }
}

/**
 * Access callback for entityforms.
 *
 * The result of this function gets ANDed with the result of entityform_access()
 * to make the final access permission.
 *
 * @param $op
 *   The operation being performed. One of 'view', 'update', 'create', 'delete'
 *   or just 'edit' (being the same as 'create' or 'update').
 * @param $entityform
 *   Optionally a entityform or a entityform type to check access for. If nothing is
 *   given, access for all entityforms is determined.
 * @param $account
 *   The user to check for. Leave it to NULL to check for the global user.
 *
 * @return boolean
 *   Whether access is allowed or not.
 *
 * @see og_entityforms_entity_info_alter()
 * @see entityform_entity_info()
 */
function og_entityforms_entityform_access($op, $entityform = NULL, $account = NULL) {
  $type = is_object($entityform)? $entityform->type : $entityform;

  // Get entityform access groups.
  $access_groups = variable_get(_og_entityforms_variable($type), array());
  if (empty($access_groups)) {
    return TRUE;
  }

  // Get user (do not restrict user 1).
  if (is_null($account)) {
    global $user;
    $account = $user;
    if ($account->uid === 1 || user_access('administer group', $account)) return TRUE;
  }

  // See if the user is a member of any access groups.
  $has_group_access = FALSE;
  $user_groups = og_get_entity_groups('user', $account);
  foreach($access_groups as $gid) {
    if (array_search($gid, $user_groups['node']) !== FALSE) {
      $has_group_access = TRUE;
      break;
    }
  }

  return $has_group_access;
}

/**
 * Implements hook_form_alter().
 */
function og_entityforms_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id === 'entityform_type_form') {
    $eform_type = $form['type']['#default_value'];

    $options = array();
    foreach(og_get_all_group() as $gid) {
      $group = node_load($gid);
      $options[$gid] =  $group->title;
    }

    $form['data']['access_set']['og_groups'] = array(
      '#title' => t('Group Visibility'),
      '#description' => t('The group(s) that should be able to view/submit eforms of this type. Optional, leave empty to skip restricting access by group membership.'),
      '#type' => 'select',
      '#options' => $options,
      '#default_value' => variable_get(_og_entityforms_variable($eform_type), NULL),
      '#multiple' => TRUE,
    );

    $form['#submit'][] = 'og_entityforms_set_entityform_type_groups';
    $form_state['og_entityforms']['original_name'] = $eform_type;
  }
}

/**
 * Save the organic groups that have access to an entityform type.
 */
function og_entityforms_set_entityform_type_groups(&$form, &$form_state) {
  $eform_type = $form_state['values']['type'];

  // Make sure to update variable names when the entityform types changes.
  if ($eform_type !== $form_state['og_entityforms']['original_name']) {
    variable_del(_og_entityforms_variable($form_state['og_entityforms']['original_name']));
  }

  // Set the groups variable for this entityform type.
  $var = _og_entityforms_variable($eform_type);
  if (isset($form_state['values']['data']['access_set']['og_groups']) && !empty($form_state['values']['data']['access_set']['og_groups'])) {
    variable_set($var, $form_state['values']['data']['access_set']['og_groups']);
  }
  // Remove the variable if the groups field is empty and previously had values.
  else if (variable_get($var, 'VAR_NOT_SET') != 'VAR_NOT_SET') {
    variable_del($var);
  }
}

/**
 * A simple helper function for generating og entityforms variable names.
 *
 * @param string $eform_type
 *  Machine name of the entityform type to get groups variable for.
 *
 * @return string
 *  The variable name (to be used in variable_get(), variable_set(), or
 * variable_del().
 */
function _og_entityforms_variable($eform_type) {
  return 'og_entityforms_' . $eform_type . '_groups';
}

```

# Answer
> 2 votes
had exactly the same problem. What I ended up doing is as follows:

> 1) create entityform, add your fields etc
>
> 2) create, of course, OG group and OG content type.
>
> 3) to your OG content type add entity ref field, referencing entityform type.

Now every time you create new node of that type you will be able to reference any of your created entityforms.

Very important - make sure that they can't access entityforms directly under

> /eform/submit/

you can do something like

> if (arg(0) == "eform" && arg(1) == "submit" && (not admin)) -\> redirect

there are other things that you should look into as well

# Answer
> 1 votes
I wrote Entityforms and thought would let other know of some changes in Entityform 2.x that will make some of this easier.

First of all I have added hook\_entityform\_access alter see: http://drupal.org/node/1937526 So it should be able to connect access to an Organic Group.

Also I proposed a feature:

> Reference only for Entityform Types
>
> Add option to restrict submitting a particular Entityform Type to only work when it is used as Entity Reference. This would make it possible for Entityform Nodes module to restrict the viewing of the Entityform Type to only work when it is shown with the node(no direct url to the Entityform Type submit page).

See: http://drupal.org/node/1896712

I didn't much interest in that feature but I think it would solve the problem that @sly notes about being able to access the form direclty at eform/submit/\*

I am thinking maybe a checkbox on Entityform Types for "Provide Submit Page" which would default to true.

If you have interest in making this feature happen comment on issues above.

---
Tags: organic-groups, entities
---


# Question
Title: Internal relative links in Menu by using http:/alias/path/to/link
In Drupal 7.22, I would like to link create an additional link to an existing node from with in a menu. This target node already has an alias and its own menu entry. I'd like to create an additional link to that node. I thought the method would be to enter the url as `http:/alias/path/to/link`. However, this seems to fail.

If you notice from the devel\_themer output that the `path` contains `http:/contact`. My hope that this link resolves to `http://mysite/contact`.

# Answer
> 0 votes
The module better jump menu seems to have been causing the issue. For any link such as `http:/contact` it stripped the http. I disabled the module and things worked as they did before.

# Answer
> 0 votes
You should be able to go to **/admin/structure/menu**, select the menu you wish to add the link to, and list links. At the top select *Add link* and enter the title and link. You can use either the alias or system path. Then on the list, place the new menu item where you want it. It should not overwrite the existing menu entry.

Do not prefix the links with http:.

---
Tags: 7, routes, navigation
---


title: Date Selector not showing up in Rules

text:
# Question
Title: Date Selector not showing up in Rules
I have created an Entity Reference view, that provides a list of users. This is used as a field in a content type so that someone creating the content type, can check off one or more users from the list.

I then have a rule with a "Content is of type" condition. In my Action I add a variable that is a "list of user items" and using the Data Selector, I was able to choose "\[node:field-people\]" which I could loop through and get the selected users and then proceed to email them.

The rule worked great. Then I tried to recreate it in my test system. And for the life of me, I cannot get the \[node:field-people\] to show up as a Data Selector anymore. I also tried going back to my Dev system, and if I create another field using the same Entity Reference view, and naming the field peopletest, identical to the original field, "\[node:field-peopletest\]" doesn't show up either! So, I can't recreate the rule in either Dev or Test, even though I have created it once already in Dev.

Is there any chance I disabled or removed a module that had created "\[node:field-people\]" for me? Or does someone know which module is supposed to create that node:field-people for me so I can see if there's configuration that has been changed or maybe I've run into a bug in that module?

# Answer
Rules works in an interesting way and only shows you fields in the actions based on selections you have already made in the 'Conditions' sections.

Frequently, including a '**Content is of type**' condition or a '**Entity has field**' condition, will trigger it to include related fields in the 'Action' sections.

So double-check the newly created rules. If you're not making sure your node is of a certain type or contains specific fields, the Actions section will only include generic fields for you.

Let us know if that works in your case...
> 0 votes

---
Tags: views, rules, entities
---


# Question
Title: jquery cannot hide span attribute in Drupal 7
What is wrong with this jQuery code and why can it not hide the span attribute?

```
jQuery(document).ready(function($){
    $('span.fieldset-legend').hide();
});

```

Heck, just trying to hide the entire span and it still does not work!

```
jQuery(document).ready(function($){
    $('span').hide();
});

```

If it helps, I am trying to hide a horizontal item in a horizontal group.

I can confirm that my jQuery is generally working. For example, the below works fine

```
alert('test');

```

This also works fine

```
jQuery(document).ready(function($){
    $('p').hide();
});

```

# Answer
Just a wild guess but

```
jQuery(document).ready(function($){
  $('span.fieldset-legend').hide();
  console.log('Hidden the spans');
});

```

Try the above code and see if "Hidden the spans" gets output on your javascript console. If it does, then the module you're using (Horizontal Groups? or whatever) is tampering with the spans and perhaps showing them after your code has run and hidden them.
> 1 votes

# Answer
I have tried your code on my Drupal 7 website and it hides all my spans perfectly (display:none). Did you add the spans using jQuery? For example with wrapInner()? If you did check wheter the code is executed before you hide() it. You can also try trouble shooting your selector with a function that always works: addClass('foo'). If the spans receive the classes you can rule out a wrong jQuery selector...
> 0 votes

# Answer
You can give every SPAN-element a unique ID with jQuery and adress them individually with CSS:

```
$(document).ready(function(){
    var nth = 0;
    $('body span').each(function(){
        nth = nth + 1;
        $(this).attr('id','span-'+nth);
    });
});

```
> 0 votes

---
Tags: 7, javascript
---


# Question
Title: Detailed breakdown of what takes Drupal so long?
I'm trying to figure out why my Drupal 7 take so long to render. I've installed the "performance log" module, but it was underwhelming, to say the least. It tells me a page took 2785 ms to render, with 51 ms in queries.

Now what? That's 2.7 seconds spent in PHP. Can I break it down further?

The site load is essentially zero.

# Answer
> 2 votes
You need the xhprof extension and module.

---
Tags: 7, performance
---


# Question
Title: EFQ propertyCondition Doesn't work in Simpletest
This Entity Field Query works as expected outside of simpletest:

```
$query->entityCondition('entity_type', 'node')
  ->fieldCondition('field_exhibition_window_start', 'value', $date, '<=')
  ->fieldCondition('field_exhibition_window_end', 'value', $date, '>=')
  ->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT')
  ->propertyCondition('status', '0');

```

Inside of a simpletest, after the creation of an unpublished node within specified parameters, it unexpectedly returns zero results.

However, if I comment out this line:

```
  ->propertyCondition('status', '0');

```

(and put a semicolon on the line above) then the query works as expected and returns a node ID. I've even done a node\_load() on the node ID returned and inspected the node to be sure that it is, in fact, at that exact moment in time, unpublished.

My simpletest has a user with node access bypass permissions, and I'm using `DANGEROUS_ACCESS_CHECK_OPT_OUT`, so it doesn't seem like a permissions issue.

Does Simpletest do something weird with EFQs? Why isn't it finding my unpublished node?

# Answer
It turns out that the status of my node was, in fact, being set to '1' immediately prior to this query running, but that despite the fact that the `node_save()` that was called immediately after `node_publish_action()` should have cleared the cache, `node_load()` was in fact calling a cached version of the node.

I got around this by adding the `TRUE` parameter to `node_load()`.

NOTE: You can't skip the middle parameter, á la `node_load($nid, TRUE)`. This is annoying, because it will fail silently and it will just return a boolean FALSE. To get a node without caching, and also without specifying a VID, you must use `node_load($nid, NULL, TRUE)`.

In a simpletest, you can also use a `TRUE` parameter like so: `drupalWebTestCase::drupalGetNodeByTitle($nid, TRUE)`.
> 0 votes

---
Tags: testing, database
---


# Question
Title: Imagecache_external: Thumbnails of external URLs aren't accessible
**Modules:**

Imagecache External, Media, Remote Stream Wrapper

**Scenario:**

I created a content type, in which I want to collect Movie Actors. My aim is to add images of those actors which arent hosted on my drupal site itself. They are being linked via Remote Stream Wrapper but RSW doesnt allow to use Image Styles on those external images (for example thumbnails). The solution is Imagecache External, which allow Image Styles even on external hosted images.

**Problem:**

* Imagecache External returns Image-URLs which ends with a cryptic snippet, which resolves into an error message: Access denied

> localhost/drupal/sites/default/files/styles/cover/http/img4.picload.org/image/acdcwwi/imagestyle\_examp.png%3Fitok%3DAyQfRnDQ
* Thumbnails are being saved in a directory, which represents the URL of the external image:

> drupal\sites\default\files\styles\cover\http\img4.picload.org\image\acdcwwi\imagestyle\_examp.png

**Detailed Problem Description:**

Imagecache External creates thumbnails with such URLs:

> localhost/drupal/sites/default/files/styles/cover/http/img4.picload.org/image/acdcwwi/imagestyle\_examp.png%3Fitok%3DAyQfRnDQ

If I open this URL directly, I get an "Access Denied" error because I dont have permission for that page (-\> even as an admin!?). If I remove this cryptic snippet at the end of the URL (%3Fitok%3DAyQfRnDQ), the Thumbnail is accessible.

The other problem is that the thumbnails are saved in a directory, which is equal to the external URL:

> drupal\sites\default\files\styles\cover\http\img4.picload.org\image\acdcwwi\imagestyle\_examp.png

This will result in a not overviewable directory tree.

The external image I linked externally for example is this one: http://img4.picload.org/image/acdcwwi/imagestyle\_examp.png

I hope anybody has a solution to my problem. :-/

Greetings, KG

# Answer
> 0 votes
I think it is a bug in imagecache external when there are special characters in the URL. Try to file an issue on the module queue on drupal.org to see.

About the "cryptic" end, it's http://drupal.org/node/1934498.

---
Tags: uri, media, database
---


# Question
Title: d7 link two pages within a (draggable) view by image
I'm trying to set up an image gallery that needs to be sortable in D7. So I installed the Views and Draggable-Views modules. Now I have one view with three pages: Gallery, Sort Gallery and Single Image. (Single Image being a view with one larger image and a previous/next link)

All of this works but I can not find a way to link an image in the Gallery-grid to the Single Image view. In the properties of the imagefield I can set up a link, but only to "content" and "file". I need to link that image to that image in my Single Image page. How can I do that?

Any ideas or solutions would be greatly appreciated!!

thanks

# Answer
I guess you must be taking nid as contextual filter in the single image view if yes then in your grid view you can rewrite the output for the image field and check the output as link field and link path will be the path of your single image view with nid of current node containing image Please check the screenshot
> 0 votes

---
Tags: media, navigation, views
---


title: Link to node in views

text:
# Question
Title: Link to node in views
I have a view which has 2 displays :

* List : Which is a unformatted list that contains a page
* Table : Displays the nodes titles in a table.

What i need is to make the title in each row of the second display redirect to the corresponding node in the first display, regardless of the "item per page" and sorting.

# Answer
May be this can be a good way to start with 1.I think you will need views\_infinite\_scroll module for the list view. 2. Set your views listing path as path/% 3. For list view set row classes as nids 3. Now with custom jquery code you take the nid from url and do a $.scrollTo(..) and nids set as row classes may help you finding the appropriate position to scroll to. does it make sense?
> 0 votes

---
Tags: 7, views, nodes, navigation
---


# Question
Title: How to test if user is denied access when her role has no "access content"
Wanting to test that only users with "access content" have access:

```
public function testOnlyAccessContentAccessible() {
  $web_user = $this->drupalCreateUser();
  $this->drupalLogin($web_user);
  $this->drupalGet("foo");
  $this->assertResponse(403);
}

```

The module under test, relevant `hook_menu`-entry:

```
$items['foo'] = array(
  'title' => 'Foo',
  'page callback' => 'foo',
  'access arguments' => array("access content"),
  'expanded' => TRUE,
);

```

What is wrong here? My `drupalCreateUser` has not recieved an array with permissions, so it did not receive the "access content" permission either; yet Drupal hands out this permission by default, so I guess this is a permission that is "default" when nothing is posted.

So, how to check that only users with permission "access content" can access a page?

# Answer
I recommend saving out your permissions using Features and then loading your custom feature in your test. By doing that, you can test out your configuration settings.

If you really just want to turn programmatically create a user that does not have the 'access content' permission, try this before you create your `$web_user`:

```
user_role_revoke_permissions(1, array('access content'));

```

This will revoke the 'access content' permission for anonymous users (role 1). See http://api.drupal.org/api/drupal/modules%21user%21user.module/function/user\_role\_revoke\_permissions/7 for more help.
> 2 votes

# Answer
A couple of issue going on here.

The default installation profile is going to grant both anonymous and authenticated users access to the "access content" permission.

If this is a custom module which will be running in a custom profile then a simple way around this is to set up your own Testing profile which doesn't give any roles any permissions by default.

At 1st I was going to recommend you switch your test to use the Testing profile (Which you can still do if you're using the default profile, since thats faster). Sadly after checking the testing profile also grants access to both anonymous and authenticated users the "access content" permission.

So that's one issue, combined with when you create a user with the drupalCreateUser and log that user in that user is always going to have the the default permissions derived from the "authenticated users" role.

If you really want to "uncheck" that permission you need to remember to do it **inside the same test case** because the Test environment will be rebuild in each test case which means the default permissions will be reassign to the authenticated role when you run your test.

So in short:

* Either disable the permission inside your testOnlyAccessContentAccessible test case
* or create a custom testing profile that doesn't assign that permission to the authenticated role. (An make sure you change your web test class to use that profile).
> 1 votes

# Answer
Access content is granted by default by Drupal to all users, even if they are anonymous.

If you need your site to behave any different, you should unset the view published content permission for anonymous users. This is normally done, in Drupal 7, by visiting the page `admin/people/permissions` and remove the checkmark for `view published content` for the user.
> 0 votes

---
Tags: testing
---


# Question
Title: Trying to make a custom region disappear upon user login, then reappear when user logs out
I've looked everywhere for an answer to my problem, but can't find one. My goal is to collapse/force a custom region on my website to disappear when a user logs in, and then have it reappear when the user logs out. Or, if it's not possible to collapse a region, to replace the region with an empty region that, through CSS, I have styled to display with zero height. Basically, I'm trying to make a custom region disappear upon user login, and then make it so the region reappears when the user logs out.

The reason for this is I'm putting the final touches on transforming the login block on my website so that instead of appearing in the sidebar, it appears as a horizontal login bar. I'm 90% of the way there. I created a custom region at the very top of the page to house the bar, and the bar kind of looks like the horizontal login bar you see on Facebook. But in reformatting the login block using CSS, I was only able to achieve the look I wanted by forcing the "Forgot your password?" and "Create a new account" links not to appear (otherwise, the links would reside between the password field and the "Log in" button, which looked weird).

But that left me with no login help links. To try to resolve this problem, I created a new region directly under the "username" and "password" fields to house the "Forgot your password?" and "Create a new account" links, which displays really nicely. But, of course, whenever someone logs in, those links remain on the screen, which is obviously weird.

I need to figure out a way to make the new region disappear when the user logs in, and to reappear when the user logs out. Also, I want the other regions in the header directly below the two new custom regions to move up once the region disappears so that there's not a gaping hole in the space where the region used to be. I'm pretty new to PHP, so what I've tried may be way wrong, but this is what I attempted, which didn't work -- it's the option of trying to swap out the region with the links with the empty region when a user logs in:

```
     <?php
        if(isset($username) == false):
        print render($page['nameofregion1']);
        else: ?></div>
        <div id="region2style">
        <?php print render($page['nameofregion2']);
        endif;
     ?>

```

where the CSS for 'region2style' is set to "height: 0px" to give it zero height. My suspicion is that I'm misusing the variable $user here, among other errors, but I can't seem to figure out what variable holds username info in Drupal. I'm sure there's a more elegant way of doing this, and if someone could point me in the right direction, I'd really appreciate it. Thank you.

# Answer
Context is a great plugin for remodelling sections of your website - paired with Delta and the Omega theme, you can overhaul your entire layout based on nearly any condition without editing any code by hand.

There's a decent intro tutorial for Context and Delta over here.

But if that doesn't fit the bill, you're on the right track with your .tpl.php files. Checking for user login is quick, just remember to global the variable first:

```
<?php
global $user;

if ( $user->uid ) {
  // Logged in user
}
else {
  // Not logged in
}
?>

```

... and by inserting the desired code between braces you could easily toggle blocks, regions, messages and nearly anything else accessible from the template.

This is my "PRINT ALL THE THINGS!!" snippet, try it out for the $user variable:

```
<?php global $user; echo '<pre>'.print_r($user, true).'</pre>'; ?>

```

Good luck!
> 1 votes

# Answer
If the login block is the *only* content in that region, you can achieve this without any custom modules, template overrides, or custom code, just by means of Drupal's built-in role based access control.

The key is that Drupal will not display an empty region. By making the login block inaccessible to *authenticated users*, the login block will disappear as soon as the user logs in.

Assuming Drupal 7, you go to Structure -\> Blocks, and click "configure" for the User login block. You then go to the Roles panel, and tick the box under "Show block for specific roles" to make the *anonymous* user the only role that is allowed to see this block.

(This method for works in Drupal 6 as well, but the navigation path is slightly different.)
> 1 votes

---
Tags: users, theming
---


title: Database Query to test new users

text:
# Question
Title: Database Query to test new users
In my Drupal 7 site, I inserted values into the 'surname' and 'date of birth' fields of my database tables. I want to prevent new users whose username and date of birth do not match those on my database from being able to log into my site. How do I achieve this? Thank you in anticipation.

# Answer
> 2 votes
There is (AFAIK) no module that will do this for you.

But you will be able to add and process any additional criteria for logging in by using `hook_user_login` to insert your own business logic into the login process. In this hook, you may insert code to redirect those users that you do not want to login to a page that explains the situation. There is an example on how to redirect logins in the comment thread in the API documentation for `hook_user_login` on Drupal.org.

For sake of completeness, I also mention that it is also possible to stop users not meeting specific criteria from registering in the first place. To do this, you add an additional validation callback function for the registration form processing using `hook_form_FORM_ID_alter`. There is a question on Stack Overflow that explains how to do this in detail for Drupal 6.

---
Tags: 7, database
---


# Question
Title: How do I get fields of a certain field type?
I've seen how to get lists of fields by entity and bundle with `field_info_instances()` and `field_info_field()`, but I'm not seeing a way to get all fields of a particular type.

I was able to cook this up to do exactly what I want:

```
function field_get_fields_of_type($type) {
  $fields_info = field_info_instances();
  $return = array();
  foreach ($fields_info as $entity => $bundles) {
    foreach ($bundles as $bundle => $fields) {
      foreach ($fields as $field_name => $info) {
        $more_info_because_type_isnt_included = field_info_field($field_name);
        if ( $more_info_because_type_isnt_included['type'] == $type) {
          $return[$field_name] = $more_info_because_type_isnt_included;
        }
      }
    }
  }
  return $return;
}

dpm(field_get_fields_of_type('entityreference')); // prints out all entityreference fields

```

But that seems to be an awful lot of code, and and awful lot of looping to get something that should probably be reachable through the field API.

Does anyone know of a Field API function that will more efficiently retrieve the data I'm looking for?

# Answer
> 24 votes
I came across this the other day and remembered seeing this question, so here it is, a somehow very unknown function (I have neveer seen anyone mention it in a blog or anything):

field\_read\_fields()

and the companion function:

field\_read\_instances()

For example, get all taxonomy term fields:

```
$taxonomy_fields = field_read_fields(array('type' => 'taxonomy_term_reference'));

```

Or get the instances for a field with the a machine name of `field_image`:

```
$image_field_instances = field_read_instances(array('field_name' => 'field_image'));

```

---
Tags: 7, entities
---


title: Add counter to comments

text:
# Question
Title: Add counter to comments
I would like to add a coutner to comments, so when I view a node I've something like:

> ```
> Comment #1 - Text
> Comment #2 - Text
> Comment #3 - Text
>
> and so on..
>
> ```

Is there a way to obtain this? Obviously #1, #2 and #3 are number relative to every singole node.

Thanks!

# Answer
Override `comment.tpl.php` and add the following to it:

```
<?php print 'Comment #' . $id; ?>

```

(You obviously add it to the spot in the template where you want the comment number to appear.)

Here is the contents of my override for `comment.tpl.php` for Bartik;

```
<div class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

  <div class="attribution">

    <?php print $picture; ?>

    <div class="submitted">
      <p class="commenter-name">
        <?php print $author; ?>
        <?php print 'comment #' . $id; ?>
      </p>
      <p class="comment-time">
        <?php print $created; ?>
      </p>
      <p class="comment-permalink">
        <?php print $permalink; ?>
      </p>
    </div>
  </div>

  <div class="comment-text">
    <div class="comment-arrow"></div>

    <?php if ($new): ?>
      <span class="new"><?php print $new; ?></span>
    <?php endif; ?>

    <?php print render($title_prefix); ?>
    <h3<?php print $title_attributes; ?>><?php print $title; ?></h3>
    <?php print render($title_suffix); ?>

    <div class="content"<?php print $content_attributes; ?>>
      <?php
        // We hide the comments and links now so that we can render them later.
        hide($content['links']);
        print render($content);
      ?>
      <?php if ($signature): ?>
      <div class="user-signature clearfix">
        <?php print $signature; ?>
      </div>
      <?php endif; ?>
    </div> <!-- /.content -->

    <?php print render($content['links']); ?>
  </div> <!-- /.comment-text -->
</div>

```
> 6 votes

---
Tags: 7, comments
---


title: Problem adding a tab to the user menu

text:
# Question
Title: Problem adding a tab to the user menu
I created a panel page using the Panels module, **Contact list** at the path `messages/contact-list`.

The Privatemsg module causes several tabs (Inbox, Sent messages, All messages) to be displayed across the top of pages with path `messages`. I am attempting to add an additional tab that links to my Panels page, **Contact list**.

Based on the code in privatemsg.module for the "Sent messages" tab:

```
  $items['messages/sent'] = array(
    'title'            => 'Sent messages',
    'page callback'    => 'privatemsg_list_page',
    'page arguments'   => array('sent'),
    'file'             => 'privatemsg.pages.inc',
    'file path'        => drupal_get_path('module', 'privatemsg'),
    'access callback'  => 'privatemsg_user_access',
    'type'             => MENU_LOCAL_TASK,
    'weight'           => -12,
    'menu_name'        => 'user-menu',
  );

```

I added this code to `hook_menu()` in a custom module:

```
  $items['messages/contact-list'] = array(
    'title'            => 'Contact List',
    'page callback'    => 'drupal_goto',
    'page arguments'    => array('messages/contact-list'),
    'access callback'  => 'privatemsg_user_access',
    'access arguments' => array('read privatemsg'),
    'type'             => MENU_LOCAL_TASK,
    'weight'           => 10,
    'menu_name'        => 'user-menu',
  );

```

However, although this produces no errors, even after clearing the cache multiple times no tab appears anywhere. I tried moving the code from my custom module into the privatemsg module to no effect. I've looked at the documentation for hook\_menu() but it still isn't clear to me what I'm doing wrong.

# Answer
> 2 votes
The reason for your problem is that page manager has already defined a menu entry for that path. Just as well, because the menu item you have created would cause an infinite chain of redirection. You would need to change the path for your panels page to be something different in order for the redirection to work.

But you can simply remove your menu entry altogether and use page manager to define the menu item for the page as a tab under Settings -\> Menu. You shouldn't need any extra code to do that.

---
Tags: routes
---


# Question
Title: How can I display a form button on top of the form?
In my custom module, I have added a button to the node edit form, using the following code.

```
  $form['actions']['my_submit'] = array(
    '#type' => 'submit',
    '#value' => t('My custom action'),
    '#weight' => -1000,
    '#submit' => array('node_form_submit', 'my_custom_node_form_submit')
  );

```

It is currently displayed either to the left or to the right of the standard "Save" button, depending on the weight value. Is there a way to display it on top of the form, before the first field?

# Answer
If you use `$form['actions']['my_submit']` like this, then you will get the button inside `$form['actions']`. `$form['actions']` weight would be considered with the weight of other fields. Try the following code.

```
 $form['my_submit'] = array(
  '#type' => 'submit',
  '#value' => t('My custom action'),
  '#weight' => -1000,
  '#submit' => array('node_form_submit', 'my_custom_node_form_submit')
 );

```
> 3 votes

---
Tags: 7, forms
---


# Question
Title: How do I display individual date display nodes of a commerce event with recurring dates?
I have created a commerce product type for a class that occurs every Monday for 10 weeks. I have the 10 dates displaying in a Calendar view using a start date and a repeat rule. What I can't figure out is how to create display nodes for the individual dates so I can add a recording of the class after it has occurred...possibly required reading beforehand; anyway, is there a way to display individual nodes in this context?

# Answer
> 0 votes
Repeating Dates in Calendar are single nodes that store all the occurances of the event, so for this to work you may have to create single events instead of one that is repeated. Good reading on that issue found here: http://drupal.org/node/298334

---
Tags: commerce, datetime
---


title: Update error: why?

text:
# Question
Title: Update error: why?
I have just set up a Drupal 7 website. Being new to Drupal 7, I am not sure why I get this error whenever I try to create an article or blog:

> Error loading meta tag data, do the /?q=update.php"\>database updates need to be ran?

I am not able to even add a page to the menu. I am also not able to enable clean URLs on the site. Can anyone tell me what I may be missing?

# Answer
Have you run update.php? If not, you need to do this.

There is a link to run it on the Reports -\> Status Reports admin page if you need to run it.

If this does not work, and if this is a fresh, unused install of Drupal 7, and you get this error, my suggestion is to start from scratch with just the core, and then install modules one by one, and test after each, to identify the module that triggers this.

To enable clean URLs you need to set up your web server to allow rewrite rules.

If you run Apcahe2, in order to have clean URLs with Drupal, it is necessary to enable an extension to the Apache web-server known as `mod_rewrite`. You do this with the following shell command:

```
sudo a2enmod rewrite

```

Then navigate to /etc/apache2/sites-available and edit the file named `default`. Locate the following block of text:

```
<Directory /var/www>
    Options Indexes FollowSymLinks
    AllowOverride None
    Order allow,deny
    allow from all
</Directory>

```

And change the AllowOverride directive to:

```
<Directory /var/www>
    Options Indexes FollowSymLinks
    AllowOverride All
    Order allow,deny
    allow from all
</Directory>

```

When done, restart Apache.

```
sudo service apache2 restart

```

(The above example is assuming you're running a standard Apache configuration on Ubuntu ver. 12. YMMV, and you may have to dig out the documentation for your system to see how to do something similar.)
> 5 votes

---
Tags: updating
---


# Question
Title: How to execute javascript from within an ajax request
OK, I'm doing some basic validation inside of an ajax form callback. I'd like to use the result to execute some javascript. What I've tried looks something like this:

inside my form alter:

```
if (isset($form_state['values']['field_temp_age'])) {
  if (validate())
  {
    //...return product information
  } else {
    drupal_add_js('alert("Validation fails!");', 'inline');
  }
}

```

This doesn't work. In this case, nothing is returned.

Also, tried this from inside the ajax callback:

```
function my_ajax_callback(&$form, &$form_state) {
  if (!validate()) drupal_add_js('alert("Foo!");', 'inline');
}

```

Not sure what's the approach here. How can I execute arbitrary javascript based on information returned from an ajax request?

Thanks.

# Answer
Not sure of how you are making the AJAX call, but jQuery AJAX calls such as $.ajax let you execute a callback after the result has been returned. I recommend returning FALSE or a code indicating an error to your calling function and placing your "validation failed" logic inside of that in the success handler.
> 1 votes

# Answer
drupal\_add\_js doesn't work properly in an AJAX callback. If you need to execute a JavaScript function within an AJAX callback, here's the way :

First, in your form, you have to create the JavaScript function :

```
function my_module_form($form, &$form_state) {
// [...]
  drupal_add_js(
    'Drupal.ajax.prototype.commands.myFunction = function(ajax, response, status) {
      // Whatever you want to do. i.e. :
      window.open("http://www.google.com")
    }',
    'inline'
  );
// [...]
  return $form;
}

```

Then, in your AJAX callback, you need to call this function you created :

```
function my_module_my_ajax_callback($form, &$form_state) {
// [...]
  $commands[] = array("command" => 'myFunction',);
// [...]
  return array('#type' => 'ajax', '#commands' => $commands);
}

```

Hope it helps !
> 1 votes

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


# Question
Title: Is there a module that can hide sidebars and expand them when required?
I need a more space in the centre of the web page but the side bars take up too much space.

Is there a module that can place the sidebars in a single block that can be expanded and contracted as necessary? What I have in mind is something like http://drupal.org/project/admin, but one that contains all the sidebar content. Context is not suitable here as this should be available all the time.

# Answer
You can do this with Jquery. Search for jquery show/ hide or toggle and then apply this to the containers you want to hide and have a tab as a toggle handle.
> 2 votes

# Answer
Yes, there is a module for that, and it makes each block collapsible.
> 0 votes

---
Tags: 7, blocks
---


# Question
Title: Automate clear of mysql database in drush site install
Is is possible to automate clearing the database when I run site install? e.g. here is my drush command:

```
drush si geoslate --db-url='mysql://root:root@localhost/geo_test' --site-name=Geoslate

```

But the db has to be cleared first. Can I automate this process?

# Answer
Chapabu is correct, but if you're using drush 5.7, this is unnecessary with site-install. If there's an existing db, drush will warn you it will drop all tables in the existing database.

For example:

```
drush dl drupal --drupal-project-rename=test
cd test
% drush site-install standard --db-url=mysql://root:root@127.0.0.1/test --site-name=test
You are about to create a sites/default/files directory and create a sites/default/settings.php file and DROP all tables in your 'test' database. Do you want to continue? (y/n): y
No tables to drop.                                                                          [ok]
Starting Drupal installation. This takes a few seconds ...                                  [ok]
Installation complete.  User name: admin  User password: 6SkT989sPX

```

So let's rerun the site-install command over the now existing "test" directory

```
% drush site-install standard --db-url=mysql://root:root@127.0.0.1/test --site-name=test         130 ↵
You are about to DROP all tables in your 'test' database. Do you want to continue? (y/n):

```
> 8 votes

# Answer
If by *cleared*, you mean *drop all tables*, then you can use `drush sql-drop`

> Drop all tables in a given database.

Official documentation for sql-drop
> 6 votes

---
Tags: database, drush
---


# Question
Title: How to update all hyperlinks which are in the content
Hello I am using book\_copy module for creating a new version of the book so i have copied a book which is having more than 1000 pages with the book copy module. Now the new book copy has all working links but for the new book i needed the new urls. like for previous book it was content/2012 now i needed content/2013 which i have done with pathauto but problem is that while copying a book it takes url for pages as content/2013 but in the page there are hyperlinks which are not updated and pointing to old book pages. So let me know if any module for fixing this issue o/w i need to go on each link and update it which is really a difficult task.

# Answer
Export the database, run a find and replace over the dumped sql and re-import it.

e.g.:

```
#1 mysqldump ... > output.sql
#2 copy output.sql to output_mangled.sql as a backup
#3 perl -pi -e 's/content\/2012/content\/2013/' output.sql
#4 cat output.sql | mysql ...

```

Replacing ... with authentication and database specification parameters.

To be safer, make the regular expression in the replacement step more specific.
> 0 votes

---
Tags: navigation, nodes
---


title: How to view simpletest results?

text:
# Question
Title: How to view simpletest results?
It looks like it's something obvious but I can't find the web interface to view simpletest results. Where should I view the errors besides the DB?

# Answer
You can find the Simpletest interface at `admin/config/development/testing`

Be sure to clear your Drupal cache if you have enabled the Simpletest module and you cannot access `admin/config/development/testing`
> 3 votes

# Answer
If you have drush installed you can run test via command line:

```
drush test-run YourClassName

```

The errors will show up after the test is run. Testing from command line is faster than using the UI found at admin/config/development/testing. However you cannot see the succesful steps and the verbose messages.

Between tests make sure yo clean the previous Drupal tables

```
drush test-clean

```
> 1 votes

---
Tags: testing
---


# Question
Title: Automatically Subscribing Nodes to Organic Groups based on Taxonomy Term
Use Case: We want to automatically add nodes to groups based on existing taxonomy terms. So when we create a new group it is populated with existing site content such as case studies and white papers that may be relevant.

I was hoping the rules module would allow this but it is not immediately obvious as I was thinking you could set up a series of rules to run that have a logic of if node has taxonomy term x then place in Organic Group Y. This would be nice as removes error and also means editors do not have to add taxonomy terms and then also decide which groups to post into.

# Answer
> 0 votes
Custom module will help. I would use node\_insert() and node\_update() although we have used submit handlers for this in the past also.

Code to add a node to a group is:

```
$form['group_audience'][LANGUAGE_NONE]['#default_value'] = $group_audience;

```

I have read that og\_group() can set a node type entity as group content, but the api looked like it changed to us.

The taxonomy\_access module might provide another way of thinking of this that suits your needs.

---
Tags: rules, organic-groups
---


# Question
Title: Can db_select cope with mysql "case when" structures?
I have a complex mysql query with "case when" to combine values across multiple rows in columns. I'm currenty using db\_query, but I would like to use the TableSort and Pager extenders. But (correct me if I'm wrong) those only work with db\_select.

This is the query:

```
SELECT gsid, created_by_uid, difficulty, gametime, max(submitted_on), score, mission, name,
 ifnull(max(case when mission = 1 then score end),0) as mission_1,
 ifnull(max(case when mission = 2 then score end),0) as mission_2,
 ifnull(max(case when mission = 3 then score end),0) as mission_3,
 ifnull(max(case when mission = 4 then score end),0) as mission_4,
 ifnull(max(case when mission = 5 then score end),0) as mission_5,
 ifnull(max(case when mission = 6 then score end),0) as mission_6
FROM `game_sessions` m
INNER JOIN `users` u ON m.created_by_uid = u.uid
GROUP BY created_by_uid

```

The game\_sessions table contains a row for each game mission that a user played. The game mission can be 1-6. This query gives me an overview with the maximum score for each mission per user (each row is a user).

Is it possible to rewrite this query using db\_select? I'm using Drupal 7.

# Answer
`SelectQuery` has the `addExpression()` method for adding arbitrary expressions. e.g.

```
$query = db_select('game_sessions', 'm')->fields('m');
$query->addExpression('ifnull(max(case when mission = 1 then score end),0)', 'mission_1');

```

Yields:

```
SELECT m.*, ifnull(max(case when mission = 1 then score end),0) AS mission_1
FROM {game_sessions} m

```
> 5 votes

---
Tags: 7, database
---


title: Removing "Member for"

text:
# Question
Title: Removing "Member for"
How can I remove the *Member for* information from appearing on accounts? I know I can hide the field, but the problem is that Ubercart order link appears in the history field, so I can't hide the field. I have tried using CSS to hide the details, but failed as hiding the dl tag hides the whole field.

# Answer
> 1 votes
From this comment:

> in D7 history is a field on the user entity
>
> goto `admin/config/people/accounts/display` set the format of the history field to 'hidden'

# Answer
> 0 votes
you remove it in this hook hook\_user\_view

or you can add your one .tpl. file, and just hide it there user-profile-category.tpl.php

```
 $profile_items

```

here you'll mess with a html\_string - see also https://stackoverflow.com/questions/13620249/how-to-hide-history-section-in-drupal-user-profile-page

---
Tags: 7, users
---