# Question
Title: When a checkbox is checked means it automatically hide all the fields in a drupal form?
Any body know the answer please help me.my code is like this

```
function my_module_menu() {
    $items = array();
    $items['my_module/form'] = array(
        'title' => t('My form'),
        'page callback' => 'my_module_form',
        'access arguments' => array('access content'),
        'description' => t('My form'),
        'type' => MENU_CALLBACK,
    );
    return $items;
}

function my_module_form() {
    return drupal_get_form('my_module_my_form');
}
function my_module_my_form($form,$form_state) {
    echo "Billing Information";
    echo '<hr>';
    /*$form['checkbox'] = array(
        '#type' => 'checkbox',
        '#title'=> 'HERE',
        '#ajax' => array(
            'callback' => 'checkbox1'
        ),
    );*/
    $form['store'] = array(
        '#type' => 'checkbox',
        '#title' => "use my stored details",
        '#ajax' => array(
            'callback' => 'checkbox1',
            'wrapper'=>'textfields',
        )

    );
    $form['previous'] = array(
        '#type' => 'checkbox',
        //'#disabled'=>'FALSE',
        '#title' => "use my details from the previous page",
    );

    /* $form['name'] = array(
        '#type' => 'fieldset',
        '#title' => t('Name'),
        '#collapsible' => TRUE,
        '#collapsed' => FALSE,
    );*/
    $form['fullname'] = array(
        '#type' => 'textfield',
        '#title' => t('Fullname'),
        '#required' => TRUE,
        '#access'=> TRUE,
        '#description' => "Please enter your full name",
        '#size' => 20,
        '#maxlength' => 255,
    );
    $form['selectbox'] = array(
        '#type' => 'select',
        '#title' => t('Country'),
        '#required' => TRUE,
        '#height' => 20,
        '#maxlength' => 255,
        '#options' => array(
            1 => 'Australia',
            2 => 'Burma',
            3 => 'China',
            4 => 'Denmark',
            5 => 'Egypt',
            6 => 'France',
            7 => 'Geneuva',
            8 => 'Holland',
            9 => 'India',
            10 => 'USA'
        ),
        '#description' => t('Please choose an option.'),
    );
    $form['address1'] = array(
        '#type' => 'textfield',
        '#title' => t('Address1'),
        '#description' => "please enter your Address1",
        '#required' => TRUE,
        '#size' => 20,
        '#maxlength' => 255,
    );
    $form['address2'] = array(
        '#type' => 'textfield',
        '#title' => t('Address2'),
        '#description' => "please enter your Address2",
        '#size' => 20,
        '#maxlength' => 255,
    );
    $form['city'] = array(
        '#type' => 'textfield',
        '#title' => t('City'),
        '#description' => "please enter your City name",
        '#required' => TRUE,
        '#size' => 20,
        '#maxlength' => 255,
    );
    $form['state'] = array(
        '#type' => 'select',
        '#title' => t('state'),
        '#required' => TRUE,
        '#height' => 20,
        '#maxlength' => 255,
        '#options' => array(
            1 => 'Assam',
            2 => 'Bihar',
            3 => 'Chandigar',
            4 => 'Gujarat',
            5 => 'Haryana',
            6 => 'Jammu',
            7 => 'Karnataka',
            8 => 'Maharsatra',
            9 => 'Orissa',
            10 => 'Punjab',
            11 => 'Rajasthan',
            12 => 'Tamilnadu',
            13 => 'Uttrapradesh',
            14 => 'WestBengal'
        ),
    );
    $form['zipcode'] = array(
        '#type' => 'textfield',
        '#title' => t('Zipcode'),
        '#description' => "please enter your Zipcode",
        '#required' => TRUE,
        '#size' => 20,
        '#maxlength'=> 255,
    );
    $form['ponumber'] = array(
        '#type' => 'textfield',
        '#title' => t('PO Number'),
        '#description' => "please enter your PO number",
        '#size' => 20,
        '#maxlength' => 255,
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
    );
    return $form;
}

function my_module_my_form_validate($form, &$form_state) {
  $year_of_birth = $form_state['values']['year_of_birth'];
  if ($year_of_birth && ($year_of_birth < 1900 || $year_of_birth > 2000)) {
    form_set_error('year_of_birth', 'Enter a year between 1900 and 2000.');
  }
}

// Adds a submit handler/function to our form to send a successful
// completion message to the screen.

function my_module_my_form_submit($form, &$form_state) {
    drupal_set_message(t('The form has been submitted.'));
}
function checkbox1($form, &$form_state) {
    //print_r($form);
    $form['fullname']['#access']=FALSE;
    //hide($form['fullname']);
    error_log(print_r($form,1));
    return;
}

```

# Answer
You can use Drupal states, which is probably the easiest and doesn't require you to do any jQuery. Here's an example:

```
$form['fullname'] = array(
  '#type' => 'textfield',
  '#title' => t('Fullname'),
  '#required' => TRUE,
  '#access'=> TRUE,
  '#description' => "Please enter your full name",
  '#size' => 20,
  '#maxlength' => 255,
  '#states' => array(
    // Only show this field when the 'store' checkbox is enabled.
    'visible' => array(
    ':input[name="store"]' => array('checked' => TRUE),
    ),
  ),
);

```
> 3 votes

# Answer
You can also make use of this module WebForm Conditional
> 2 votes

---
Tags: ajax
---


title: Insert form values in the database

text:
# Question
Title: Insert form values in the database
I am new to Drupal 7, and I am trying to insert the form values in a database table. I used many ways to do that, but I am not getting successful result. What is wrong with the code I am using?

```
drupal_write_record('formtest', $data);
function form_test_form_submit($form, &$form_state) {
  $id = db_insert('formtest')
    ->fields(array(
      'First name' => $form_state['values']['firstname'],
      'Lastname' => $form_state['values']['lastname'],
      'Email' => $form_state['values']['email'],
      'Password' => $form_state['values']['password'],
      'Year of birth' => $form_state['values']['birthdata'],
      'Image' => $form_state['values']['fileimage'],
  ))
  ->execute();
  drupal_set_message(t('your messagees is added is sucessfule'));
}

```

# Answer
Is your submit function getting called to begin with? Just put a dsm in the beginning of your submit function and make sure it is being called. If it is, then, dsm your form\_state\['values'\]. If you can see all the values in form\_state, then, make sure your table name and column names are spelled exactly the same as they are case-sensitive.
> 0 votes

---
Tags: forms
---


title: OK to replace images on server?

text:
# Question
Title: OK to replace images on server?
So my client has been populating the site with content, but their images aren't optimised for the web.

Can I just download all the images, and then upload new versions to overwrite them ? Or are images linked more carefully to the DB?

# Answer
> 5 votes
I've never had any problems just replacing images.

If there are any images that have image styles applied then don't forget to clear the image styles caches/files so they get regenerated as well. You can do them all at once with Image style flush

*tl;dr:*

Should be fine so long as the filenames match.

# Answer
> 5 votes
Personally, I have never had a problem with this, but keep in mind that the data in the `{file_managed}` will likely no longer be accurate.

In particular the `{file_managed.filesize}` and the `{file_managed.timestamp}` columns will be incorrect. This typically isn't a problem, but if you are using any of these fields (eg, in a view) they will be incorrect.

Any other module that implements `hook_file_insert()` may also end up with stale data. I am unaware of any modules that do this, though.

I have long term plans to write a drush command and/or module to update `{file_managed}` since I have clients who do this a lot. This may be a holiday project for me.

# Answer
> 0 votes
I found one issue with this, if the image is kept in the field, then image field will keep the old dimensions.

If the old dimensions are smaller such as width 100px height 100px

And imagestyle is width 600px height 600px

Even the replaced image is bigger than the imagestyle setting such as 1000px width/height, the image will be rendered in the old dimensions since the field will add the image attrbs from the field table.

---
Tags: 7, media
---


# Question
Title: How to add attributes to menu and menu items on the block level in THEME_preprocess_block()?
With `THEME_menu_tree()` we can change the markup of the `<ul>` element and with `THEME_menu_link()` we can add css classes to the items of it easely. But what if we have an IF IS IN THIS BLOCK condition to incept?

Not `THEME_menu_tree` nor `THEME_menu_link()` know in which block the menues are, they alter, because both will alter all menus known by system.

Two ways came in mind, but both were dead ends: 1) pass a variable from `THEME_preprocess_block()` to `THEME_menu_tree()` and `THEME_menu_link()` -\> No, makes no sense. Still, they don't know what to do with it nor can they follow the foreach() of `THEME_preprocess_block()`, because they have no conditions for blocks. 2) Finding a higher entry level to pass the condition over and alter the menu attributes and its item attributes from there.

Well. Good point. But where would that be? Printing out the $variables inside THEME\_preprocess\_block() was like counting drops in the ocean. Can someone please enlighten me if I am right with the second thought and with where to look at?

# Answer
> 4 votes
There are actually functions available for specific menus too:

> **Targeted overrides (suggestions) available for theme\_menu\_link() and theme\_menu\_tree()**
>
> In addition to other changes to menu rendering, a Drupal 7 theme can implement a `THEMENAME_menu_tree__MENU_NAME()` and/or `THEMENAME_menu_link__MENU_NAME()` function to override `theme_menu_tree()`/`theme_menu_link()` for a specific menu. For example, `THEMENAME_menu_link__management()` would override `theme_menu_link()` for links within the "Management" menu. This is similar to how "`node--article.tpl.php`" overrides "`node.tpl.php`".

Source: https://drupal.org/node/254940#theme-suggestions-for-menus

# Answer
> 1 votes
For clarification: The answer (actually provided by David Thomas) to this question is, that it doesn't need to get fired in `preprocess_block()`, since `THEMENAME_menu_link()` offers the option to append the menu name with a double \__ to target a special menu. Finally that makes more sense of course, since menus can (will) move into other blocks, but that was far away from my hope it could work. Not every code can be perfect. But it does.

Using `THEMENAME_menu_link_MENU_NAME()` did the trick.

Thanks to David Thomas who has pointed that out to me. I am not sure if the d.o. docs are mentioning this. I am still a little bit lost in the Drupal docs, but it gets better. A big system has big docs of course. I just have to learn how the doc system is build, to find my issues.

Thank you, David.

---
Tags: 7, theming
---


# Question
Title: How to show the edit form of a page just below the page itself in the frontend?
Just wondering if is there a way to expose the edit form of a page just below the page itself in the frontend.

Let's say I have the page Services, if you click a the **edit** tab you go to the admin page where you have the fields title and body for this page, here you can change its values and save.

I need to show the edit form (fields title, body and the button save) in the frontpage, just at the bottom of the page.

UPDATE: base in neok's answer: **But I can not use $output var in** `utilities_block_view($delta = '') {`

```
    function utilities_preprocess_page(&$variables, $arg, $delta=0) {

      if(arg(0) == 'node' && is_numeric(arg(1))) {
        $nid = arg(1);
        //you need to include node.pages
        module_load_include('inc', 'node', 'node.pages');
        $output = node_page_edit(node_load($nid));

        return $output;
      }
    }

    function utilities_block_info() {
      $blocks['edit_node_form'] = array(
        // info: The name of the block.
        'info' => t('Edit node Form'),
      );

      return $blocks;
    }

    function utilities_block_view($delta = '') {
      // The $delta parameter tells us which block is being requested.
      switch ($delta) {
        case 'edit_node_form':
          // Create your block content here
          $block['subject'] = t('Edit node Form');
          $block['content'] = $output;
          break;
      }

      return

 $block;
}

```

# Answer
> 5 votes
You can output edit form of current node with node\_page\_edit function. So you can create a block programmatically(show this block only on node pages of your content type - *Services* for example) and output edit form with `node_page_edit`.

```
  if(arg(0) == 'node' && is_numeric(arg(1)) {
    $nid = arg(1);
    //you need to include node.pages
    module_load_include('inc', 'node', 'node.pages');

    $output = node_page_edit(node_load($nid));
    return $output;
  }

```

Here you can find an example how create block.

---
Tags: 7
---


# Question
Title: How to add css class attributes to the anchor element inside the links of a given menu by theme function
Do I miss something or is it *impossible* **to theme the link anchor HTML element** `<ul class="main-menu"><li><a href="" class="put something in here"></li></ul>` for a targeted menu on the theming level (theme functions)?

We can theme the `<li>` elements and the menu block elements with HOOK\_menu\_link\_MENU\_NAME(). Thanks to David Thomas for pointing that out to me. But I had no luck with targeting the nested anchors itself. The Devel array output and the drupal.org docs only brought me to `theme_menu_item_link()`, `theme_links`, `theme_link()`, and others, but I can't see an opportunity here to elegantly incept dynamic values for css classes on the anchor element?

I would like to add style class attributes to the `<a>` element in ul \> li of a given menu (not of all menus, thats what `theme_links()` does)...

---

NOTES:

* nested css targeting by altering the upper element is not an option here, since the required css class is level sensitive and should NOT be applied to the upper html element.
* And yes, I know the menu\_attributes module. It's an awesome module I use very often. But the approach is different. I don't want to change the menu link data in the DB, but the output only.
* There is an issue for the `theme_links()` function on drupal.org mentioning some trouble with its scope and how it works: https://drupal.org/node/588148

> theme\_links(): Returns HTML for a set of links. =\> theme\_links($variables) https://drupal.org/node/588148 =\> theme\_links() is not really themeable \[#588148\] =\> Drupal core, theme system, normal, needs work, 49 comments, 1 IRC mention
* Another option would be to add `<span>` elements inside the anchor elements. I already did this for node objects but I don't know if this is possible here and if this is the right way to do it.
* Edit: Here are two questions -  \-  \- on stackexchange I read thru' atm, since there are near issues discussed. Maybe it will enlighten me soon ... (Thanks to Clive, who has pointed me to the second one.)

# Answer
Based on this it should be pretty simple:

```
function THEME_menu_link($vars) {
  $element  = $vars['element'];
  $menuname = $element['#original_link']['menu_name'];

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }

  // This is where you check the menu name and assign the class.
  if($menuname == 'main-menu') {
    $element['#localized_options']['attributes']['class'][] = 'main-menu-class-whatever';
    $element['#localized_options']['attributes']['class'][] = 'another-class';
  }

  $output = l($element['#title'], $element['#href'], $element['#localized_options']);

  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . '</li>';
}

```
> 3 votes

# Answer
I am probably looking at this upside down or backwards but, are you rendering this menu yourself, eg, you are calling `theme('links', $variables)` somewhere and can easily modify `$variables`?

If so, a quick look at the `theme_links()` function itself reveals the following comment...

```
/**
 * Returns HTML for a set of links.
 *
 * @param $variables
 *   An associative array containing:
 *   - links: An associative array of links to be themed. The key for each link
 *     is used as its CSS class. Each link should be itself an array, with the
 *     following elements:
 *     - title: The link text.
 *     - href: The link URL. If omitted, the 'title' is shown as a plain text
 *       item in the links list.
 *     - html: (optional) Whether or not 'title' is HTML. If set, the title
 *       will not be passed through check_plain().
 *     - attributes: (optional) Attributes for the anchor, or for the <span>
 *       tag used in its place if no 'href' is supplied. If element 'class' is
 *       included, it must be an array of one or more class names.
 *     If the 'href' element is supplied, the entire link array is passed to
 *     l() as its $options parameter.
 *   - attributes: A keyed array of attributes for the UL containing the
 *     list of links.
 *
 *  (rest of comment deleted)
 */

```

showing that what you need to do is put in an `attributes` key with each link, as, further on down in the code, when it is creating the link itself, it does, as the comment above also mentions, adds in the full `$link` as the `$options` parameter, eg...

```
$output .= l($link['title'], $link['href'], $link);

```

So, if you create an `attributes` key that points to an array with a key of `class` for whatever link needs a special class, and that key itself points to an array containing that name, this class will be added to the anchor.
> 3 votes

---
Tags: 7, theming
---


# Question
Title: How can I find (programmatically) which fields have been edited on a piece of content?
I want to have a computed field pull in the name and content of a field after it has been edited. I would also like the computed field to contain the content that was edited before edit (if that makes sense?). So what code do I need to find which field has been edited?

I also found this in the node\_form drupal api:

```
// Changed must be sent to the client, for later overwrite error checking.
$form['changed'] = array(
  '#type' => 'hidden',
  '#default_value' => isset($node->changed) ? $node->changed : NULL,
);

```

Is there a way I access this 'changed' value to check if a piece of content has been changed?

p.s. I am new to drupal and php, so stating your answer in simpler terms with more explination is greatly appreciated.

# Answer
In the node form submit, you can call `node_load($node->nid, NULL, TRUE)` for Drupal to retrieve the original about-to-be-overwritten node, allowing you to walk the list of fields, and compare them.

I would use `sha1sum(serialize($field))` to compare them, as that makes it easy to do regardless of field type.
> 2 votes

# Answer
If you can use hook\_node\_presave, you have the handy property $node-\>original

https://api.drupal.org/comment/24933#comment-24933

Which saves you making an additional node\_load
> 0 votes

---
Tags: 7, entities
---


title: Views permission does not work

text:
# Question
Title: Views permission does not work
I have created a view by the name of news and there is an option under page setting by the name of access.

I have selected view any news content for the access option, then I have faced a problem. The problem is when I give any kind of view permission for news view, I cant access except give the permission of view any news content.

What do I have to do to give a permission of 'view own news content' so every person can see his/her news content?

# Answer
Create a relationship between the current content type, and users.

Select Content: Author and click on Add and configure relationships. Leave the settings as they are and click on Apply (all displays).

**Filtering the view**

Now you need to filter the view to display only content authored by the current user.

Use the filter **"User: Current".**
> 1 votes

---
Tags: users
---


# Question
Title: Specifying text format when creating field on custom node type
I have a module that's creating a custom node type. I'm attaching a textarea to this node type. Currently it works, but the text formatting defaults to "Plain Text."

I would like to specify during installation that the field should be set to "Filtered Text," specifically, "Filtered HTML." This seems like something that should be possible when defining the instance of the field, but it's not working.

Here's the instance definition as it stands now:

```
<?php
// ...more fields above
    'release_notes' => array(
      'field_name' => 'release_notes',
      'type' => 'text_long',
      'label'  => $t('Notes'),
      'description'  => $t('Release notes (e.g. liner notes)'),
      'widget' => array('type' => 'text_textarea'),
      'settings' => array('text_processing ' => '1'), // Filtered HTML...?
      'weight' => 9,
    ),
// ...more fields below
?>

```

Does anyone have any ideas?

Thanks.

# Answer
I had thought that setting text\_processing in the settings array would automatically set the filter, but all that does is allow anything other than plaintext.

In fact, you need to set this, and you need to specify the format value for the instance as a whole. The key to allow filtered HTML is filter\_html.

So, here is the new hotness:

```
<?php
// ...more fields above
    'release_notes' => array(
      'field_name' => 'release_notes',
      'type' => 'text_long',
      'label'  => $t('Notes'),
      'description'  => $t('Release notes (e.g. liner notes)'),
      'widget' => array('type' => 'text_textarea'),
      'settings' => array('text_processing' => 1), // Allow text processing
      'format' => 'filter_html', // <<--- Set this value to allow filtered HTML
      'weight' => 9,
    ),
// ...more fields below
?>

```

You can get a list of the default filters in filter.module's implementation of hook\_filter\_info(): https://api.drupal.org/api/drupal/modules%21filter%21filter.module/funct...

Hope this helps someone, it took me forever to figure this out.

If you try to programmatically save a node with a custom field, and that field has HTML in it, then you need to do this. Otherwise the HTML won't be stripped - it will be converted to its entity counterparts and displayed to the user.
> 3 votes

# Answer
Set the `'format' => 'filtered_html'` to allow filtered html

```
<?php
    // ...more fields above
        'release_notes' => array(
          'field_name' => 'release_notes',
          'type' => 'text_long',
          'label'  => $t('Notes'),
          'description'  => $t('Release notes (e.g. liner notes)'),
          'widget' => array('type' => 'text_textarea'),
          'settings' => array('text_processing ' => '1'), // Filtered HTML...?
          'format' => 'filtered_html' // <<--- Set this value to allow filtered HTML
          'weight' => 9,
        ),
    // ...more fields below
    ?>

```
> 3 votes

---
Tags: forms
---


# Question
Title: Displaying fields from an entity reference of another entity's field
I have three content types: compositions, recordings and artists. Compositions have entity references to artists for the field composer. Recordings have entity references to compositions for the field composer and to artists for the field recording artist. This is what I want to do:

1. I would like to display a page with a list of all the compositions and their composer (entity reference to Artist content type). No problem here.
2. I would like another field with the field recording artist (an entity reference field in content type Recording) that is being referenced by an entity reference for the content type composition. This is the problem.

I think the main problem is I'm trying to call a field from an entity reference's entity reference. Is there a way to build that bridge?

# Answer
> 1 votes
You can use custom Displays to daisy-chain entity reference fields in this fashion (unless I misunderstand your requirements).

To do this...

1. Install the Entity View Mode module.
2. Then in configuration - system - entity view modes, create a new display for the entity in question and make sure it is attached to the recording type. Give your new display a self-explanatory name such as "embedded recording" to avoid confusion later.
3. Next, go to your **recording** entity's display mode settings, (eg 'manage display') and in the new "embedded recording" display make sure the Recording Artist entity reference field is visible.
4. Finally, go to your **Composition** entity's display mode settings (its 'manage display'), and for the **Recording** entity reference field, choose **rendered entity** as its format and pick "embedded recording" as its view mode (this option becomes available if you click on the little gear icon on the right hand side).

(Of course this would be far easier if you could add new display modes from the manage display setting! One day perhaps...)

# Answer
> 0 votes
I recently spent a lot of time on a very similar problem, so your question caught my eye. Note I'm new to Drupal, so take everything below with a good grain of salt.

If I understood correctly, you want the following architecture: Composition references Recording. Recording references Artist (let's call this Recording Artist).
And you want the following functionality. Firstly, you want to access the Recording Artist fields (e.g. name), given the Composition entity. Secondly, you want to add Recording Artist fields to the Composition entities' content object, so it could be printed out by templates along with other Composition fields. In other words, you want to make the Recording Artist fields accessible through the Composition entities' content object.

Consult this very nice answer by juhog. I believe it relates very well to what you're trying to do. It explains how to 'gain access to referenced entities' and how to append fields from referenced entities to referencing entities.

With this I was trying to nudge you in the right direction, because your question seemed confused (you have my sympathy, I've been there). I have limited experience so I will refrain from giving coding examples.

# Answer
> 0 votes
You just need to add a relationship of the third content type in the view and use a field of that content type in your field list, it will pick it up because when you add a relationship views will add a join statement in your sql query and you can use the columns of that joined table in your output.

---
Tags: views, entities
---


# Question
Title: How do I append HTML after a form title?
This is the output I want:

```
<label>Name</label><span>!</span>

```

The only way I can think of is to concatenate my HTML to the form title value

```
'#title' => t('Name') . '<span>!</span>',

```

This kind of works, but is ugly: the output is:

```
<label>Name<span>!</span></label>

```

The #suffix property won't do because it adds my HTML outside of the form element's wrapping div.

Any ideas. Thanks.

# Answer
You shouldn't concatenate the result of the `t()` function, it should rather be built up as a single string:

```
'#title' => t('Name <span>!</span>'),

```

Other than that, you're already doing this about the cleanest way possible. Other approaches would involve post-processing the form element(s) to render their title in a different way than standard. I imagine that would end up being more trouble than it's worth unless you wanted to do it globally for every element in every form in the site.
> 4 votes

---
Tags: forms
---


# Question
Title: What else apart do I need enabled, apart from "block to region" in Display Suite Extras for the "block regions" vertical tab to appear?
I've enabled "block to regions" in Display Suite Extras and I have enabled "Full Content" in "Manage Display".

But the "block regions" vertical tab still does not appear among the other tabs beneath the field table in "Manage Display".

Is there anything I should do to make the "block regions" appear?

# Answer
> 0 votes
You can't use the Default display view mode. You have to enable the Full Content view mode, which will then give you things like Block Regions and custom Page Title options.

---
Tags: 7, entities, blocks, display-suite, theming
---


# Question
Title: Does Google crawl Drupal sites in maintenance mode?
I'm using Aegir to clone copies of my site under a subdomain name ie test.mydomain.com. These copies are in maintenance mode to keep away spammers and prying eyes. I then use these copies to carry out tests and development work before committing changes to my main site mydomain.com

But am I hurting my SEO by the existence of these cloned sites? Does google crawl a sites which has been put in maintenance mode? Will it penalize me for having so many dead end subdomains?

# Answer
When you put a Drupal site in maintenance mode, non-administrators see the standard maintenance mode page (assuming you clear caches after doing so). If you examine the response, you will see that it is sent back with a HTTP status code of 503, which from RFC 2616 is:

> **503 Service Unavailable**
> The server is currently unable to handle the request due to a temporary overloading or maintenance of the server. The implication is that this is a temporary condition which will be alleviated after some delay. If known, the length of the delay MAY be indicated in a Retry-After header. If no Retry-After is given, the client SHOULD handle the response as it would for a 500 response.

And from the Official Google Webmaster blog:

> **If my site is down for maintenance, how can I tell Googlebot to come back later rather than to index the "down for maintenance" page?**
> You should configure your server to return a status of 503 (network unavailable) rather than 200 (successful). That lets Googlebot know to try the pages again later.

So, that gives evidence that Drupal does the right thing, and that Google will revisit your site and index pages the next time it gets back a non 5XX status code.
> 21 votes

# Answer
Unless you've done something custom to allow it, Google can't crawl your site in maintenance mode.

Because you need to be logged in to view, googlebot will see the designated maintenance page.

For additional guidelines from Google see the following links:
> 6 votes

# Answer
Your concerns:

If you do not know whether maintenance mode is blocking "everything you want blocked" by 100% (!) -- but at the same time are very concerned about "whether someone like google might still access it". ... then maintenance mode might be a bad choice for blocking your development site in the first place.

Recommendation:

Personally, I recommend simply adding a **.htpasswd** to your dev sites.

It is simple to automate even inside aegir deployments. It never gets in your way, because your browser and every command-line tool can skip it for you. You can let other people in. It blocks the site in all completeness 100% to google etc.
> 2 votes

---
Tags: multi-sites, maintenance-mode, aegir
---


title: no pictures show up

text:
# Question
Title: no pictures show up
Since that I have uploaded my files and my DB to an actual server, NONE of the pictures of the website show up. I already checked the permissions and it should be fine. I ran a general report. There was one serious warning in CTools:

> The CTools CSS cache directory, ctools/css could not be created due to a misconfigured files directory. Please ensure that the files directory is correctly configured and that the webserver has permission to create directories.

I am working on that one right now. Could that be the problem? Any ideas?

# Answer
> 1 votes
you will have to verifiy that your paths for drupal file systems, including the tmp directory are set correctly on /admin/config/media/file-system

These directories also need to be writable by the php process, so they usually need owner, or group write access rights. these can be chmod 755 if the process is running in the same group as the file owner, or in worst case chmod 777

# Answer
> 0 votes
Drupal's file system might need to be updated since your server's directories are different from your local environment's.

---
Tags: media, migrations, chaos-tool-suite, backups
---


# Question
Title: Using IN queries or joining to a temporary table inside views for data managers to use with VBO for one-off updates
Our data managers routinely analyze Drupal content in external mapping and analysis programs and generate lists of nodes that require updates. I'm looking for a solution that will allow them to update this arbitrary list of nids, preferably within a friendly UI.

**Background**

We've recently migrated from a custom database application to Drupal. In the past our data managers would perform a sql in query (SELECT * FROM table WHERE ID IN (27, 83, 99, ....)) or upload a temporary table to the database, do a join and perform updates. I'm looking for a way for them to do the same thing, but inside of Drupal so the proper update hooks are fired.

So far my Google skills and searches on drupal.org are failing me. It seems this should be a common problem? Is there a best practice when performing these sorts of one-off query/updates?

**Some related solutions I've considered**

* Views contextual filters using either default arguments or arguments in the url (Create a view from specific Node ID's) - This is limited to only a few dozen nid's as a default argument or maximum url length. Not suitable for long lists of nid's
* Researched using Node Queue with the solution above but the UI doesn't seem to allow bulk adding of nodes, but perhaps I'm overlooking something.
* Custom module to expose a table to views (Join a custom table on a View) - not ideal since requires programming every time a new update needs to be performed
* Write a custom query and update to perform IN queries (Using IN clause in db\_query) - again requires code, which I'm not opposed to if I can work up a reusable solution that our data managers (not programmers) can use to maintain our data.

An ideal solution would be a fiter criteria that allowed our data managers to paste a long csv string. Something like "In list" which operates similar to the "Is between" functionality.

I'm overlooking something obvious! Ideas?

# Answer
You could try Feeds as well .... but ...

Use either a CSV file or one of its other Migrate Sources, for instance it can use another database table as your source of change-data. But I recommend the Migrate module.

Your CSV can hold the primary key and whatever fields you need to update. You could use the new hash() functionality in Migrate 2.6 to check for changes in your data so that content is either Updated or Inserted as needed.
> 1 votes

---
Tags: views
---


# Question
Title: hook_preprocess_page for mobile detection
I am attempting to set a variable $is\_mobile that I can use in my page.tpl.php function.

```
function mytheme_preprocess_page(&$vars)
{
    require_once(libraries_get_path('mobile_detect').'/Mobile_Detect.php');
    $detect = new Mobile_Detect();
    $is_mobile = $detect->isMobile() or $detect->isTablet();
    $vars['is_mobile'] = $is_mobile;
}

```

It seems the result is cached and whatever the first hit will be used.

My overall goal is to create a dynamic menu for mobile and desktop. (One for each)

What is the best way to approach to this?

# Answer
> 1 votes
You could use panels and create a variant for mobile and other for non mobile.

the mobile detect module provide a selection rule for that by using mobile\_detect\_ctools

---
Tags: routes
---


title: Custom node tpl being ignored

text:
# Question
Title: Custom node tpl being ignored
I have created a content type called 'Home' and I also create a new file called, node-home.tpl.php.

What I understood from the drupal documentation, that when a Node has the content type it should use node-contenttypename.tpl.php as the node template file, if it exists.

But mine isen't working and its defaulting back to node.tp.php.

Any idea what I'm doing wrong?

# Answer
> 2 votes
The file has to be called node--home.tpl.php. There always has to be 2 '-' between type and name.

---
Tags: nodes
---


# Question
Title: In Drupal 7 Views what is the php code to validate a field against a contextual filter argument?
Currently I am using the path url to pass in arguments:

path: /%/%/%

On the 3rd argument I am loading a Taxonomy term. I also have a field loaded called: **field: device type**

What do I have to put in my contextual filter validation PHP code? I did a dsm($view), but my device type shows recursion. I'm not sure how to reference the field properly to create a conditional to compare it to the contextual argument.

# Answer
Below is a code sample of my contextual filter validation code for drupal 7 views 3 validation.

My view contains a page display with the following path set: **blog/%/%/%**

Here is a sample path argument of what I'm trying to accomplish: **Path URL:** blog/7/node-title/taxonomy-name

```
if ( is_numeric(arg(1)) && is_string(arg(3)) ) {
//check to make sure arg 1 is text and arg 2 is a string

  $node = node_load(arg(1));
//load the node

  $terms = taxonomy_get_term_by_name(arg(3));
//get the terms array and TID from arg 3.

  if (!empty($terms)) {
    $first_term = array_shift($terms);
    foreach($node->field_repair_states_region['und'] as $x => $y) {
      if( $y['tid'] == $first_term->tid ) { return TRUE; }
//make sure the TID matches the TID to the node.

    }
  }
}

```

Screenshot of Validation Page: http://prntscr.com/1dcl4v

Screenshot of View: http://prntscr.com/1dclly
> 0 votes

---
Tags: 7, views
---


# Question
Title: WYSIWYG+CKEditor outputting span with style attribute
I have a strange behaviour on the text editor on my D7 site. I am using WYSIWYG-7.x-2.1 module with CKEditor v.3.6.3.7474.

If I type:

> test
>
> test
>
> test

on the editor then Disable rich-text I can see:

`<p>test</p><p>test</p><p>test</p>`

Which is correct. Now if I Enable rich-text and then put my cursor at end of line 1 then press delete, it makes the 2nd line join the end of the first line:

> testtest
>
> test

Then I press Return again to separate those lines:

> test
>
> test
>
> test

Now if I Disable rich-text I get:

`<p>test</p><p><span style="line-height: 1.538em;">test</span></p><p>test</p>`

As you can see it has created a span tag with line-height css.

It not only does this for paragraphs, it also changes heading tags, like H2 will get changed to a span with style attributes that duplicates the display of h2 but it's a span inside a paragraph tag...

A lot of different developers have worked on this website, but I can't reach them to ask what they did, they probably won't remember anyway.

So I'm asking if anyone else has had this issue and could point me in the right direction. Is it CKEditor config? WYSIWYG config? Drupal config? Version bug? Tried to search Google but don't get much relevant results.

# Answer
Fix can be found at https://github.com/RomanMinkin/webkit-span-fix

Caused by a Webkit bug - http://dev.ckeditor.com/ticket/9998
> 1 votes

# Answer
So i might not have the most informed answer, but i think i have a solution:

I face the same problem on our D7 site.

It turns out, if you use Chrome, content you paste in the WYSIWYG usually gets these strange line-spacings. (Regardless of if you choose "paste as plain text", or copy-paste from Notepad).

**Use Firefox** \- and you wont see any `<span style="line-height: 1.538em;">` stuff in the HTML!

If anyone knows how to use Chrome and not have these span elements show up - please let me know!

Cheers,

R
> 1 votes

---
Tags: 7, wysiwyg
---


# Question
Title: How to fix call to undefined function libraries_get_path() in multi-site install?
I am setting up a multi-site Drupal 7 install. I have the base site set up correctly and running just fine. When I create the second site (a sub domain of the first site), the install.php script ran fine but when I try to view the site I get the following error:

```
Fatal error: Call to undefined function libraries_get_path() in /var/www/drupalhome/d7/sites/all/themes/mytheme/template-preprocess.php on line 75

```

I assume that since the second site inherits everything from the first site (since it is the default install) that the second site should display just fine. However it looks like the second site doesn't know about the libraries module and is throwing the above error (at least that is my interpretation of it). My question is: how can I fix this?

Thanks.

# Answer
> ...since the second site inherits everything from the first site..."

To the best of my knowledge that's not how a multi-site setup works; in my experience there's no inheritance involved. Core code/modules/themes/libraries etc can be shared between any number of sites, but each has their own separate database (and files structure, potential for site-specific modules/themes etc.).

When you add a new site you get a fresh Drupal install, none of the settings from any of the other sites in the setup are copied over.

An inheritance-based workflow wouldn't make sense, as multi-sites can contain any number of completely different Drupal sites - the point is that they can share the resources mentioned above, and when it comes time to upgrade core/contrib modules you only have to do it once for all the sites in the setup.

You can solve the specific problem you're currently having by enabling the libraries module on the new site; but if your custom theme relies on other contrib modules to be installed as well, those will need to be enabled before the site will work properly. Similarly, if the custom theme relies on settings/variables that were available in the default site, those will need to be restored.

I think in your case it would make more sense to clone the default site and database into the new one (bypassing the installation procedure entirely), then make the necessary adjustments to distinguish it from the default site afterwards.

Either that, or wrap the default site's functionality up in Features/Config, perhaps creating an install profile along the way, and use that to instantiate the a clone when you need one.
> 2 votes

---
Tags: 7, multi-sites, theming
---


title: Adding roles to users

text:
# Question
Title: Adding roles to users
I added some users to my site.

Is there a way to add roles to thousands of users at the same time?

Thank you.

# Answer
> 6 votes
you have to install the Views Bulk Operations and Administration views module. After that, go to the users management interface (admin/people), select the users and select "Change user roles".

PS 1: You can select users by role ***(1 on the attached picture)***

PS 2: If you need to select ALL of the users, just click the button "Select all xxx rows in this view" ***(2 on the attached picture)***

2/ For selecting only users without role:

You'll have to modify the Views who handle the display:

1. Go to **http:///admin/structure/views/view/admin\_views\_user/edit/system\_1**
2. On the "Filter criteria" section, click on "User:Roles"
3. Check the "Expose operator" box
4. Save and go back to the user selection page
5. Select the 'Only has the Authenticated user role' on the "Role" dropdown

That should really do it now! :)

---
Tags: users
---


# Question
Title: Add field to an entity_view for dispaly in a tapir table in ubercart
In the simplest terms I am trying to add a 'vendor' column to the order view table in Ubercart which will display the author of each line item product.

Below is the table of interest. I have hacked the direct code contained in `uc_order.order_pane.inc` but will refactor with hooks the drupal way ASAP. I have added my comments in the code below.

```
function uc_op_products_view_table($order) {
  dpm($order);
  $table = array(
    '#type' => 'tapir_table',
    '#attributes' => array('class' => array('order-pane-table')),
  );

  $table['#columns']['qty'] = array(
    'cell' => array(
      'data' => theme('uc_qty_label'),
      'class' => array('qty'),
    ),
    'weight' => 0,
  );
  $table['#columns']['product'] = array(
    'cell' => array(
      'data' => t('Product'),
      'class' => array('product'),
    ),
    'weight' => 1,
  );

```

Added by me:

```
  $table['#columns']['Vendor'] = array(
    'cell' => array(
      'data' => t('Vendor'),
      'class' => array('vendor'),
    ),
    'weight' => 1.5,
  );

```

.

```
  $table['#columns']['model'] = array(
    'cell' => array(
      'data' => t('SKU'),
      'class' => array('sku'),
    ),
    'weight' => 2,
  );
  if (user_access('administer products')) {
    $table['#columns']['cost'] = array(
      'cell' => array(
        'data' => t('Cost'),
        'class' => array('cost'),
      ),
      'weight' => 3,
    );
  }
  $table['#columns']['price'] = array(
    'cell' => array(
      'data' => t('Price'),
      'class' => array('price'),
    ),
    'weight' => 4,
  );
  $table['#columns']['total'] = array(
    'cell' => array(
      'data' => t('Total'),
      'class' => array('total'),
    ),
    'weight' => 5,
  );

  if (!empty($order->products)) {
    $build = entity_view('uc_order_product', $order->products);

```

This is the entity I want to edit. `uc_order_product` needs to have a field for Author / Vendor to make my table look right.

```
    dpm($build);
    $table['#rows'] = $build['uc_order_product'];
  }
  else {
    $table['#rows'][]['product'] = array(
      '#markup' => t('This order contains no products.'),
      '#cell_attributes' => array('colspan' => 'full'),
    );
  }

  return $table;
}

```

# Answer
So this is the ugly hack I used to resolve the issue:

```
  if (!empty($order->products)) {
    $build = entity_view('uc_order_product', $order->products);
    foreach($build['uc_order_product'] as $line_item) {
      $node = node_load($line_item['#entity']->nid);
      $vendor['#markup'] = '<a href=' . url('user/' . $node->uid) . '>' . $node->uid . '</a>';
      $vendor['#cell_attributes']['class'][] = 'vendor';
      $line_item_id = $line_item['#entity']->order_product_id;
      $build['uc_order_product'][$line_item_id]['vendor'] = $vendor;
    }
    $table['#rows'] = $build['uc_order_product'];
  }

```
> 0 votes

---
Tags: theming, ubercart
---


# Question
Title: User defined field not updating with PHP code
I am using the uc\_node\_checkout and I need to set some fields that I have created. The php code is this

```
if (isset($order)) {
  foreach ($order->products as $product) {
    if (isset($product->data['node_checkout_nid'])) {
      $node = node_load($product->data['node_checkout_nid']);
      $node->field_productid['0']['value'] = $order->order_id;
      node_save($node);
    }
  }
}

```

If I create an order and add this line to the end of the php code, it dies and show a number. die($node-\>field\_productid\['0'\]\['value'\]); When I remove that line and place and order the productid is empty.

# Answer
> 3 votes
Change this:

```
<?php
      $node->field_productid['0']['value'] = $order->order_id;
?>

```

To this:

```
<?php
      $node->field_productid[LANGUAGE_NONE][0]['value'] = $order->order_id;
?>

```

See if that helps.

---
Tags: users, ubercart
---


title: Upgrading a site

text:
# Question
Title: Upgrading a site
I am attempting to upgrade one of my sites from Drupal 6 to Drupal 7. I have downloaded and made Drush executable. I've also install the Drush site-upgrade command. The problem I'm having is understanding the steps or the process of aliases. I really need someone to explain it to me in layman's terms as I am just learning all of this. I've tried several different configurations and still can't seem to get it to work. So after some digging around within Drush I have also noticed when I do the drush st command I get this (posted below)

PHP configuration : /home/user/drush/php.ini /home/user/drush/php.ini Drush version : 5.9
Drush configuration :
Drush alias files : /home/user/.drush/cm.aliases.drushrc.php

Which I'm thinking is wrong, I shouldn't have 2 php.ini files show up for my PHP configuration should I? I should mention I have a multi domain site. I'm guessing I need to fix this first before I figure out the aliases issue, but I have posted what I put in the .drush folder as my cm.aliaes.drushrc.php file

```
$aliases['test'] = array(
  'root' => '/public_html/folder-of-domain-to-update',
  'uri' => 'localhost',
);

```

If I go to the /home folder and run the command `drush sa`, I get:

```
@cm
@cm.test
@none

```

If I go to the /home/user/public\_html/folder-of-domain-to-update and run the command `drush sa`, I get:

```
@cm
@cm.test
@none
@self
default

```

When I run the command `drush sup` at the /home/user/public\_html/folder-of-domain-to-update level I get this:

> No target argument specified. To perform the site upgrade, define an alias record for the target site.

If someone could give me some direction or help I would greatly appreciate it.

# Answer
You could use the Migrate module for this purpose.

> The migrate module provides a flexible framework for migrating content into Drupal from other sources (e.g., when converting a web site from another CMS to Drupal). Out-of-the-box, support for creating core Drupal objects such as nodes, users, files, terms, and comments are included - it can easily be extended for migrating other kinds of content. Content is imported and rolled back using a bundled web interface (Migrate UI module) or included Drush commands (strongly recommended).

For more details you could go through the README.txt of this module.
> 1 votes

# Answer
Hope this will help you,

For Upgrading from D6 to D7 you need to use Drush Site Upgrade module. You can go through **Use Drush to Upgrade from Drupal 6 to Drupal 7**

You can also refer Use Drush to Upgrade from Drupal 6 to Drupal 7
> 0 votes

---
Tags: 7, drush, upgrading
---


# Question
Title: In Drupal 7, how do I display my taxonomy term fields while creating content when using a checkbox field?
I currently have the following below as a taxonomy reference field in one of my content types as a checkbox list widget during content creation.

Currently its only showing the term name, but I want it to show the term name and its fields. My end results would be something like this:

nc - North Carolina

nj - New Jersey

ny - New York

How can that be done?

# Answer
> 1 votes
I don't think there's a way to do this using the UI, but you should be able to do this using template\_preprocess\_field().

Store the full version of each acronym as the description on each of your taxonomy terms. The acronym would be the title.

Then you'll want to do something like:

\*note that this is all pseudo-code as I don't have a version of Drupal handy to test this, but with some kpr() or var\_dump() calls you should be able to debug it for your needs\*

```
<?php
function my_theme_preprocess_field(&$vars) {
  $element = $vars['element'];
  // Modify the output of the taxonomy term field
  if ($element['#field_name'] === 'field_my_taxonomy_term') {
    // Get the title and description
    $item = $vars['items'];
    $acronym = $vars['items'][0]['title'];
    $description = $vars['items'][0]['description'];

    //create the html you want
    $html = '<span>'.$acronym.' - '.$description.'</span>';

    //now replace the default field markup with your new markup
    $vars['items'][0]['#markup'] = $html;

  }
}
?>

```

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


# Question
Title: Mollom and Spamicide are not slowing down spam registrations
I have a drupal 6 site. I'm using both Mollom and Spamicide.

Mollom is doing a great job at stopping spam comments but spambots are registering at an extremely high rate over 6 per minute.

Registration uses a captcha from Mollom and Spamicide but they seem to be going right through both. Spamicide slowed them down for about half a day but now that seems to be doing nothing.

Additionally, about 80% of the spambot accounts are validating their accounts through email - they create tons hotmail accounts with generic names.

Any ideas or recommendations on stemming the tide?

I've been trying to find a way of automatically blocking IPs that are throwing a high number of registrations or other suspect activity.

# Answer
> 2 votes
You can still try to use CloudFlare service, coupling with Mollom it's very effective.

Also, I'm not sure that they (bots I mean) are creating account e-mail to validate their account. The problem with Drupal 6, its has an algorithm to create the validation link that it's easier to reproduce (much harder with Drupal 7 as its has a secret key when you install).

Well, if with CloudFlare it doesn't slow down your spam problem, you can either change the validation algorithm or upgrade to Drupal 7.

# Answer
> 0 votes
Spammers seem to be working at a faster rate then we can block them for the most part, but there's still some things I find helpful in slowing them down.

I find using image captcha vs regular captcha works way better. If you're finding that that you're getting hit from the same IP address, google it and find out if it's a known spammer. If it is, block it.

Since not filling in the field verifies you're human with Spamicide, calling the field a name that spambots normally fill in are more likely to fail validation. Spambots won't fill in a field called "what's my mom's name?", but likely will fill out "city" or "name." Assuming you don't need those fields anyway.

# Answer
> 0 votes
in order to know the ip address of a user and multiple accounts he created, you can use this module https://drupal.org/project/ip

# Answer
> 0 votes
For preventing spam login creation I suggest you ask simple GK questions like "largest bank in your country", "largest river" etc.

For comments I suggest you block http:// or https:// in comments. Plenty of spam( I guess at least 25%) will be filtered.

Don't block IP's. For example in India plenty of IP's are dynamic. I guest IP's of most of wireless internet directly from provider will be dynamic.

---
Tags: 6, security, advertising
---


# Question
Title: How to create a new properties to $node (or $user and so on)
I would like to add a properties to the node object (or user, file, etc).

I know that I can use a field, but it could be useful to do this.

Which is the way?

Thanks, Sergio

# Answer
In conjunction with the Entity API module, you can use

`hook_entity_property_info`

> Allow modules to define metadata about entity properties.
>
> Modules providing properties for any entities defined in hook\_entity\_info() can implement this hook to provide metadata about this properties.

e.g:

```
/**
 * Implements hook_entity_property_info
 */
function MODULE_entity_property_info() {
  $info = array();
  $properties = &$info['node']['properties'];

  $properties['nid'] = array(
    'label' => t("Content ID"),
    'type' => 'integer',
    'description' => t("The unique content ID."),
  );
  return $info;
}

```

See also `entity_metadata_node_entity_property_info` for default node property definitions.
> 2 votes

---
Tags: 7
---


# Question
Title: When creating a Chaos Tools content type plugin, what is a subtype and how are they used?
I'm perfectly fine with creating Chaos Tools content types for use in Panels, but I've always used `single => TRUE`.

I've looked through the docs, but still can't quite seem to grok how to utilise subtypes. None of the examples shipped with Chaos Tools seem to use them (they also all implement `single => TRUE`, and a quick grep of the Chaos Tools directory only shows the Custom Content type using subtypes, and it only *appears* to use it for including the export functionality (unless I'm reading it wrong - which is likely).

# Answer
> 3 votes
It's a good question, and some further information can be found in the ctools help file *context-content.html*

> The CTools pluggable content system provides various pieces of content as discrete bits of data that can be added to other applications, such as Panels or Dashboard via the UI. Whatever the content is added to stores the configuration for that individual piece of content, and provides this to the content.
>
> Each content type plugin will be contained in a .inc file, with subsidiary files, if necessary, in or near the same directory. Each content type consists of some information and one or more subtypes, which all use the same renderer. **Subtypes are considered to be instances of the type. For example, the 'views' content type would have each view in the system as a subtype.** Many content types will have exactly one subtype.

Also, in `ctools_content_get_subtypes`

> Get all of the individual subtypes provided by a given content type. This would be all of the blocks for the block type, or all of the views for the view type.

So in a sense, the subtypes are individual instances of that type, such as individual Views or Blocks, or custom content instances, that use the same rendering functions as the parent content type.

For example, you can see in `ctools_content_process`

```
// If a subtype plugin exists, try to use it. Otherwise assume single.
if (function_exists($function_base . 'content_types')) {
  $plugin['content types'] = $function_base . 'content_types';
}

```

In the example of the block content type, this function returns the content types, or sub types for that plugin.

```
/**
 * Return all block content types available.
 *
 * Modules wanting to make special adjustments the way that CTools handles their blocks
 * can implement an extension to the hook_block() family, where the function name is
 * of the form "$module . '_ctools_block_info'".
 */
function ctools_block_content_type_content_types() {
  $types = array();
  foreach (module_implements('block_info') as $module) {
    $module_blocks = module_invoke($module, 'block_info');
    if ($module_blocks) {
      foreach ($module_blocks as $delta => $block) {
        $info = _ctools_block_content_type_content_type($module, $delta, $block);
        // this check means modules can remove their blocks; particularly useful
        // if they offer the block some other way (like we do for views)
        if ($info) {
          $types["$module-$delta"] = $info;
        }
      }
    }
  }
  return $types;
}

```

Lastly one more example for good measure from the views\_content content type plugin

```
/**
 * Return all content types available.
 */
function views_content_views_content_type_content_types($plugin) {
  $types = array();
  // It can be fairly intensive to calculate this, so let's cache this in the
  // cache_views table. The nice thing there is that if views ever change, that
  // table will always be cleared. Except for the occasional default view, so
  // we must use the Views caching functions in order to respect Views caching
  // settings.
  views_include('cache');
  $data = views_cache_get('views_content_all', TRUE);
  if (!empty($data->data)) {
    $types = $data->data;
  }

  if (empty($types)) {
    $views = views_get_all_views();

    foreach ($views as $view) {
      if (empty($view->disabled)) {
        $types[$view->name] = _views_content_views_content_type($view);
      }
    }

    views_cache_set('views_content_all', $types, TRUE);
  }

  return $types;
}

```

In this case `_views_content_views_content_type` returns

```
function _views_content_views_content_type($view) {
  $title = $view->get_human_name();

  $icon = 'icon_views_page_legacy.png';

  return array(
    'view' => $view->name,
    'title' => $title,
    'icon' => $icon,
    'description' => filter_xss_admin($view->description),
    'category' => t('Views'),
  );

}

```

---
Tags: chaos-tool-suite
---


title: copy database for duplicate site?

text:
# Question
Title: copy database for duplicate site?
Now have set up multi-sites is it possible to just cp database.sql to other databases so the site is duplicated but running independently?

I remember when I first set up multi-sites I got it wrong so that when changes were made to one database , it would translate to other until I separately created databases for each.

I know there are other ways of saving settings for a commonly created site in features which I have yet to try but isn't it easier to just copy the mysql over to other database and make small changes from there?

# Answer
You can simply copy database all right, if you remember about critical points:

* Make sure settings.php really points to proper databases
* Before importing SQL file to new database, find and replace old URL and site name with new one.
* If you keep any cache settings for external tools, like memcached, in database, make sure you either uninstall them before SQL export and then install again, or find & replace in SQL file before importing.
> 2 votes

---
Tags: database
---


# Question
Title: drush user-block feature and 'You do not have permission to block'
I'm trying to use drush's user-block feature and I'm getting following error:

```
# drush -r . -l fqdn ublk 'user.email@host.tld.dev'
You do not have permission to block user.email@host.tld.dev.           [error]
#

```

I'm doing it from shell and I am *root*, so I'm not sure which permissions is it talking about.

# Answer
Sometimes modules does not respect that user with UID 1 should be allowed to do everything. *And sometimes you simply want hooks to fire with specific user's ID.*

When it happens, you can use `drush --user=123` where 123 is UID of an user that is allowed to perform given action.

Source: Drush issue 1126240.
> 2 votes

---
Tags: drush, 6
---


# Question
Title: Remove/hide title/subject from published comments
How can the title/subject not be displayed in a *published* comment.

I have already disabled the subject/title field for entering comments, meaning that users only have a comment body box for which to enter text. (I used the following question and answer to achieve that: Remove subject field from comments )

However, even with this disabled, the initial few words of the comment body get displayed automatically as the subject/title.

Background: I'm developing a stackexchange question/answer style system for my site and am looking for a similar kind of layout.

P.S. I'd be happy with a code-based solution (in a module, or theme) to override a hook (I'm examining the mark-up for clues myself) Or a module would be fine.

# Answer
In your theme folder, if you do not have a comment.tpl.php file, create one. And customize yours to not have the title. Just take out the title from the file

Another option is to try removing it in your template.php file in the `yourtheme_preprocess_comment()` function
> 2 votes

---
Tags: 7, comments
---


title: Form API Radio Button Submit

text:
# Question
Title: Form API Radio Button Submit
I'm building a form that is being built by pulling information from an api and loops through it. The issue I'm having is I cant seem to pass the information to the submit page.

Here is a snippit of my code, let me know if you need more:

```
// Loop through resources and make fieldset for each.
for($i = 0; $i < count($resources['subscriptionResources']); $i++){
  $resource = $resources['subscriptionResources'][$i];

```

...

```
  $form['resources'][$resource['resourceID']]['add-qty'] = array(
    '#type' => 'radio',
    '#title' => t('Upgrade'),
    '#return_value' => 1,
    '#default_value' => 0,
    '#disabled' => FALSE,
    '#prefix' => "<table class='upgrade'><tr><td>",
    '#suffix' => t("</td>"),
    '#attributes' => array(
      'name' => 'upgrade',
    ),
  );

```

... So the outcome is, I get three different forms each with a radio button. They are all connected due to the 'name' attribute, so only one can be selected at any given time.

But when submitting, the default\_value stays 0 and return\_value stays 1 for all three. I'd like some way to display the information of the 'checked' radio to the submit page. Currently I'm seeing nothing (if default\_value is 0) or everything is default\_value = 1.

Again, let me know if you need more information.

Thanks!

# Answer
> 2 votes
```
$resourcids = array();
 // Loop through resources and make fieldset for each.
    for($i = 0; $i < count($resources['subscriptionResources']); $i++){
      $resource = $resources['subscriptionResources'][$i];
      $resourcids[$resource['resourceID']]=$resource['resourceID'];
    }

      $form['resources'] = array(
        '#type' => 'radios',
        '#title' => t('Upgrade'),
        '#options' => $resourcids,
        ),
      );

```

you dont need to use name attributes. drupal form api give name attributes by form name.

when you submit form you get resource id in form\_state\['values'\]\['resources'\] of which is selected. then you identify which radio button is selected.

and By default disabled is false. so you dont need to add disabled.

dont add t() in before t("

")

```
'#suffix' => t("</td>"),

```

---
Tags: forms
---


# Question
Title: Ubercart Line item tax not displayed first time
Im adding a line item to ubercart order at checkout validation. When at the review page I can see the line item but its not used in the tax calculation. But when i go to the review page for the second time it is.

Who can help me?

# Answer
> 0 votes
I added the line items at validate. However at that moment the tax is already calculated. What needs to happen is recalc the taxes. This can be done from a ajax call when a field changes value.

```
function My_Module_update_line_items($form, $form_state) {
  $commands = array();
  if (isset($form['panes']['payment']['line_items'])) {
    $commands[] = ajax_command_replace('#line-items-div', drupal_render($form['panes']['payment']['line_items']));
    $commands[] = ajax_command_prepend('#line-items-div', theme('status_messages'));
  }

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

```

---
Tags: ubercart, commerce
---


title: drupal_get_form of custom content types

text:
# Question
Title: drupal_get_form of custom content types
I am wracking my brain to try to figure out how to retrieve a custom content type's edit form programatically.

For example, I created a content type called "address", and have this:

```
$form = drupal_get_form("address_node_form");

```

But it does not work. I get back this warning:

> Warning: call\_user\_func\_array() \[function.call-user-func-array\]: First argument is expected to be a valid callback, 'node\_form' was given in drupal\_retrieve\_form() (line 771 of /home/richardp/public\_html/drupal7/d7/includes/form.inc).

I know that in D6 you also had to include an object where you specify the type, but I have tried this and it still doesn't work.

When I try simply `$x = node_add("page");` I get a white screen of death, presumably because I ran into a PHP error.

Am I supposed to be including a file first or something like that?

# Answer
> 5 votes
Here is the code to display the Edit Form in Node View page:

```
<?php
// modules/custom/custom.module

function custom_preprocess_node(&$vars) {
    module_load_include('inc', 'node', 'node.pages');
    $node = $vars['node'];
    $form = drupal_get_form('mytype_node_form', $node);
    $vars['content']['edit_form'] = $form;
}
?>

```

Notes:

1. You need to replace custom with your module's name and mytype with the machine-readable name of your content-type.
2. I just used a clone of $vars\['node'\] to prevent probable problems caused by the fact that $vars is passed by reference; though it might not be necessary.

---
Tags: forms, nodes
---


title: hook_field_prepare_view not called

text:
# Question
Title: hook_field_prepare_view not called
If I understand correctly, hook\_field\_prepare\_view should be called each time, when some field value is displayed. But when I visit some node page, that contains some fields, my hook\_field\_prepare\_view is not called. I have simple hook implementation as follows:

```
function mymodule_field_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items) {
watchdog('mymodule', 'field');
}

```

I have no record 'field' in log messages, so I think my function is not called. I flushed caches several times. Could anybody help, where can be problem?

# Answer
> 0 votes
As documentation says:

> This hook is invoked before the field values are handed to formatters for display

It will not be called when content is served from cache - as values are not handed anywhere, it's just output taken from cache table (or other cache bin) and sent to display.

---
Tags: entities, hooks
---


# Question
Title: How to display second level menu on another node page
I created a menu by Menu block module. I added a link 'to /news' in the first level. The second level are news categories (taxonomy items). I want to display the categories (2 level) on node page. How to do that?

# Answer
> 1 votes
Try the Taxonomy Menu Module. It creates you a menu item for each term which you then can place in your menu.

# Answer
> 0 votes
Try this: menu\_block It allows you to have different levels of your menu in different blocks. Just create a menu-block for your main navigation(only level 1) and a second for level 2 only. Set the second menu-block only to show up on `node*` or what ever you need.

---
Tags: views, routes, taxonomy-terms
---


title: Field validation: hooks vs callbacks

text:
# Question
Title: Field validation: hooks vs callbacks
In D7 there appear to be various methods by which a module can carry out validation of a form's fields, including:

* #element\_validate callback
* #validate callback
* hook\_field\_validate() implementation
* hook\_form\_validate() implementation
* hook\_field\_attach\_validate() implementation

Firstly, can anyone list the execution order of the above?

Secondly, can anyone please explain why one might choose to use a callback instead of a hook or a hook instead of a callback?

# Answer
> 4 votes
* `#element_validate` is used to provide validation for a *specific element*.
* `#validate` is used for the form, and for elements that cause the form to submit (button, image\_button, submit). It provides the names of extra functions to call during the validation process.
* `hook_field_validate()` is for validating fields (not standard form elements). This doesn't necessarily take place in the context of a form submission.
* There's isn't a `hook_form_validate()` \- by convention if a function called `FORM_ID_validate()` exists then it will be used as part of the above `#validate` array for the form. This is used to validate any part of the form, not just a specific element.
* `hook_field_attach_validate()` runs as validation when fields are attached to an entity, it doesn't run in the context of a form (see `field_attach_validate()`)

Not all of the above are executed at any one time, or in any single context, so listing an execution order isn't possible.

Hopefully the above distinctions will make it obvious which one to use in what circumstance.

---
Tags: hooks, forms
---


title: TinyMCE not appearing on custom form

text:
# Question
Title: TinyMCE not appearing on custom form
I am creating a custom form and have run into a problem. I'm using the WYSIWYG module and for some reason the text areas on this custom form don't show as rich text editors (tinymce shows on other parts of he site)

```
    $form['terms_format'][implode('~', array(MODULE_NAME, FIELD_TERMS))] = array(
    '#title'         => t('Terms and Conditions')
   ,'#type'          => 'textarea'
   ,'#description'   => t('Terms and conditiona')
   ,'#default_value' => variable_get(implode('~', array(MODULE_NAME, FIELD_TERMS)), "")
   ,'#required'      => TRUE
);
$form['terms_format']['format'] = filter_form(FILTER_FORMAT_DEFAULT);

```

Any ideas what i'm doing wrong? I'm using drupal 6.

# Answer
you need to specify the format value `'format' => 'filtered_html'` to allow filtered html or '#format' =\> 'full\_html'

```
$form['terms_format'][implode('~', array(MODULE_NAME, FIELD_TERMS))] = array(
    '#title'         => t('Terms and Conditions')
   ,'#type'          => 'textarea'
   ,'#description'   => t('Terms and conditiona')
   ,'#default_value' => variable_get(implode('~', array(MODULE_NAME, FIELD_TERMS)), "")
   ,'#required'      => TRUE
   'format' => 'filtered_html',
);

```

For drupal 6 try

```
if (!isset($edit['format'])) {
  $edit['format'] = FILTER_FORMAT_DEFAULT;
}
$form['terms_format']['format'] = filter_form($edit['format']);

```

Make sure your default filter format is filtered html or full html
> 0 votes

---
Tags: 6, input-formats
---


# Question
Title: Automatically add a new node to a drop-down menu
When a user creates a node of a certain type, I want that node to be added to a drop-down menu at the top of the screen: i.e., so that when the user mouseovers the parent item in that menu, a list of all the nodes of that type is displayed. What's the best way to achieve this?

# Answer
I achieved this effect by using https://drupal.org/project/nice\_menus, and building a view that contains all of the nodes I want displayed in the drop-down. Then https://drupal.org/project/menu\_views can display that view as menu items within the menu that Nice Menus has built.
> 0 votes

---
Tags: 7, nodes, routes
---


# Question
Title: How to remove 'error' class from form field?
I need to remove the error class from field after form submit. How to do that?

I found the function called \_form\_set\_class but I suppose I can't overwrite it.

# Answer
`_form_set_class()` is called from a bunch of different theme functions, including

(the rest are here)

You can override whichever of those functions you need to in your theme by renaming the function as (e.g.)

```
function MYTHEME_checkbox($vars) {

```

Then copy in the original code from the function, remove the call to `_form_get_class()`, and replace it with whatever makes sense for your use case.
> 1 votes

---
Tags: forms, theming
---


title: When to use taxonomy vs content type?

text:
# Question
Title: When to use taxonomy vs content type?
I have a project that allows people to add 'skills' and 'resources' to a system. Initially I was using a taxonomy field for the objects themselves because it seemed to make it easy to look up other 'skills' and 'resources' that had already been added to the system.

However, I am beginning to wonder whether this is the best plan. The taxonomy system allows for a 'library' of objects to be created which can be shared but this isn't the right way to use taxonomy which should be for 'meta-information'.

I could have a preexisting taxonomy structure of 'stuff' like ebay's categorie and allow people to add their own stuff to this library. People would add 'skills' and 'resources' as their own content types with additional fields- title, body, image, and then tag them within this taxnonomy structure. However, I was attracted to the idea of keeping it really simple; e.g. a drill is only a drill not a bosch, 12v battery powered handheld drill with hammer setting and masonry bit :)

If I wanted to have a 'drill' categories with a pool of 'drills' with more specific drill information what would be the best way to do that?

Sorry there are a few questions here, but I'm hoping to put together question an exciting distribution from this project, so any thoughts will help and hopefully go to something worthwhile.

# Answer
Content type defines **kind** of information, different content types means different structure and different nature of content. Taxonomy is for categorisation. They can be interchangeable to some extent, but it's really up to how you want your data defined.

If all nodes we are talking about perform the same function in the system and are supposed to have the same fields, keep them categorised by taxonomy. If their function should be different, make content types - it does not mean you need to give up taxonomy then (but you may if it's no longer needed).
> 2 votes

---
Tags: nodes
---


# Question
Title: What is the proper way to create a custom user field programatically?
I'm currently working a custom user registration module for a project I'm busy with. I need to add a boolean field which will be attached to user entities. The value will just serve as a flag to check whether a user has answered a CAPTCHA question as a final step of registration. I've been trying to define a boolean field which should have no widget selection dropdown or edit / delete operations within the "Manage fields" section for users.

It seems that the best way to define the field would be during hook\_enable or hook\_field\_schema (inside your .install file), but I'm confused as to what the best practise is.

Also, is there anyway to give the database table a better name when defining your field? I find the table prefix for fields "field\_data\_xx" pretty confusing if you're defining numerous custom fields.

Thanks in advance :)

# Answer
Q1: The field should be added in `hook_enable()` and removed in `hook_disable()` if you want the field to be removed and then added when you enable/disable the module. However I suggest implementing it in `hook_install()` and `hook_uninstall` as that will only remove the field and its data from the user entity when the module is uninstalled as oppose to simply disabled. `hook_field_schema` is not for these kinds of tasks as it's for defining a database table.

Q2: You'd have to hack your way through the field.module to make these database table name changes. This is really bad practice (VERY VERY) and plus I don't see the point of this, or never even heard anyone attempting this. The database tables are for Drupal and not for human eyes. As such they're in a consistent and systematic naming conventions so the field module as well as other modules that use them can easily extract data.
> 2 votes

---
Tags: entities, installation
---


# Question
Title: Drupal 7: Adding a save button to save content to user profile page
I want a signed-in user to have the ability to save an image (that is being displayed in some kind of slideshow or gallery) and have it appear on that users profile page. So the image will be on the same site, maybe added by another user or the site admin and then any other user would be able to click a save button and have it added to their own profile. That image being saved (when being saved to the users profile) should have a link that returns you to the gallery from which you saved it.

How to do this?

# Answer
> 1 votes
For something really simple, you can use the Favorites module where users can add nodes to a "favorites" list. This is based off of the URL though, so a gallery of images rotating on one page wouldn't really work.

For a more robust system, you can configure a bunch of Flags, which can do many different things like bookmarks, favorites, etc.

---
Tags: users
---


# Question
Title: Same menu display only a couple of levels down when used normally but when used within the "Site map" module it would display all the levels?
In order to display all the links using the "Site map" module I am adding everything we want in our site map to the primary links menu, going in as many levels deep as I need. Then I don't actually display all the levels in our menu but the site map will display all the links within the primary links menu.
Is there a way to have the same menu display only say a couple of levels down when used normally but when used within the "Site map" module it would display all the levels?

# Answer
You can install the Menu Block module to help with that.

You can define a define a block for a specific menu, and in the block configuration you can choose the maximum depth (see the active select list in the image below). Then you can add that block to your header/whatever region in place of the menu that's there now.

This won't affect the underlying menu itself though, just the display of it for that particular block. So in the sitemap, all levels of links will show.

Obviously you may need to make a few CSS tweaks to your menu as the wrapping classes will probably have changed, but I think this is by far the quickest method to get what you're looking for.
> 6 votes

---
Tags: routes
---


# Question
Title: 500 Internal Server Error after logging in
I have a D7 site. I start getting a 500 internal server error. I get the default Chrome (my browser) error page, instead of the one from my server.

This error occurs only after I log in and have navigated through a page or two. The apache error log shows nothing except for the following message :

```
[Sun Jul 15 21:53:27 2012] [debug] mod_deflate.c(615): [client 127.0.0.1] Zlib: Compressed 0 to 8 : URL /php5-fcgi/index.php, referer: http://new.whack.co.in/admin/modules

```

I can browse through the whole site anonymously without encountering any problems. I can even access the site temporarily by clearing my browser's cache.

The site uses a combination of Varnish+Apache 2+APC+php-fpm+memcache. I have a D6 site installed on the same server and I can navigate through it without encountering any problems.

This site was installed by using Drush Site Upgrade. Contents and settings were migrated from a the previously mentioned D6 site. The D6 site is stored on /var/www/drupal (Accesible from default domain) while the D7 site on /var/www/seven - (accessible from a subdomain).

What can be the possible cause of the problem and how can I fix it? Please do let me know if any other information is required.

# Answer
> 4 votes
From my research there are basically four things that could cause the '500 internal server error' with drupal :

1. Misconfgured server (you will have to dig into your server configs)
2. Misconfigured .htaccess file (replace your existing .htaccess with the drupal default)
3. Misconfigured file permissions
4. Low php memory\_limit setting

In my case, the culprit was the memory\_limit setting. After doubling the same, my site is flying right now.

# Answer
> 1 votes
I would like to add 5. to the above list. This catches me up when I configure the base URL in settings.php and forget to alter it after I migrate to a live server. Check to see the base url and that the domain configuration for caching is correct. Maybe use a default settings.php file with correct db settings and see if that helps.

# Answer
> 0 votes
Another possible cause: a module which produces different results depending on logged in / logged out state. This is esp. probable if some types of pages are still accessible, while others are not.

In my specific case, there was a bug in a Drupal Commons 7.x-3.2 view called "Commons Activity Streams - Activity (Site-wide)". When removing it, or switching it from the "Activity - Full view" display to "Activity (Sidebar)", all pages worked fine again.

---
Tags: 7
---


title: Theming comments in node.tpl.php

text:
# Question
Title: Theming comments in node.tpl.php
How can i theming the comments like this in the node.tpl.php (with a new column after 3 comments)? I want to use this:

```
$cols = array();

$cols[] = '<div class="headline">' . t(`Kommentare`) . '</div>';

$comments = comment_render($node, $node->cid);
$comcolnum = 0;

foreach($node-cid as $comcol){
$comcolnum++;
$cols[] = '<div class=description-' . $comcolnum . '">' . $comcol['view'] . '</div>';
}

$cols[] = '<div class="comment-form">' . drupal_get_form('comment_form',array('nid' =>
$node->nid)) . '</div>';

print theme_table(array(), array($cols))

```

$node-\>comments, &comments or ... doesn\`t work. I think first i need to override the comment output in the template.php like this for Drupal 6:

```
function phptemplate_preprocess_node(&$vars) {
$vars['node']->comment = 0;
$vars['comments'] = $vars['comment_form'] = '';
if (module_exists('comment') && isset($vars['node'])) {
$vars['comments'] = comment_render($vars['node'], $vars['node']->cid);
$vars['comment_form'] = drupal_get_form('comment_form', array('nid' =>
$vars['node']->nid));
}
}

```

But! What i need to get every comment for the foreach function? I\`m really new with PHP and Drupal API, but i want to learn it! Can someone show me the right way?

Greeting Bruno

# Answer
> 0 votes
Use `MYTHEME_preprocess_node($vars)` instead of `MYTHEME_preprocess_page($vars)` to get your declared variables in `template.php` to get in `node.tpl.php`.

I see you are already using template\_preprocess\_node(), so just put all those things which are intended for `node.tpl.php` in that function.

---
Tags: theming, comments
---


title: Does Drupal support Multitenancy?

text:
# Question
Title: Does Drupal support Multitenancy?
I have not been able to determine whether Drupal supports multitenancy:

> Multitenancy refers to a principle in software architecture where a single instance of the software runs on a server, serving multiple client-organizations (tenants).

Specifically, I am interested in a single Drupal installation supporting multiple user organizations that would share the same environment but be able to have separate interface configurations and settings, and otherwise being totally unaware of other tenants (users).

An example would be a single install of Drupal being used to serve up multiple organizational websites in a SaaS type offering.

Does anyone have any information on this?

# Answer
> 16 votes
One of the strengths of Drupal is that it's not just a tool for building a single website. It can be used equally well for managing multiple companion sites together. This capability has existed for many years, but is not always well understood.

And in true Drupal fashion, modern Drupal has several different options available for users looking to run a series of Drupal sites together, each with its own trade-offs.

* Separate installs
* Features-based installs
* Multi-site
* Domain Access
* Organic Groups
* Mix and match

---

**Separate installs** : Sometimes the best strategy is to not unify sites at all. In this case, any similarity between different sites is largely coincidental. If there will be a large number of sites then some automation tools such as Drush or Aegir may make spinning up new sites easier, but from a site building perspective they are different sites.

**Features-based installs** : As a slight variation of separate installs, it's possible to run multiple installs with the Features module. For those not yet familiar with it (and you should be), Features is essentially an automation tool for those pieces of configuration that Drupal allows to be mirrored to code so that they may be checked into version control. These days much (but sadly not all) of Drupal's configuration can be feature-ized. The most effective configuration components to manage this way include content types, views, panels, and image styles.

**Multi-site** : For years Drupal has had the ability to run multiple sites off of a single install base. In this case, there is a single copy of Drupal's code base but each college or department has its own settings.php file, which points to a different database. From a site builder perspective, this is almost the same as having separate installs. Every site must be configured independently, but every site may also be configured independently. Each site may also live on its own domain or in subdirectories, although the latter requires some symbolic link trickery and editing the Apache .htaccess file to make work.

**Domain Access** : Domain Access (DA) is actually an access control module that uses the node grants system. With DA, a site administrator can point multiple domains to a single Drupal install. Drupal will then self-filter any nodes in the system to display only on specific domains. There is still a single database, single code base, single user base, and single content pool.

**Organic Groups** : With OG, each node (any entity, really) can be made into a "group", and then other nodes can be associated to one or more groups. Depending on the configuration, that could impact navigation, path aliases, theme selection, and so forth, to give the impression of different "sites".

**Mix and match** : When planning a large-scale Drupal rollout, it's also possible to consider combining strategies. For instance, both Domain Access and Organic Groups can run on their own Drupal instance that just so happens to be multi-site... and have other Drupal sites hosted on it as well. Workbench can be used for administration of content on a single Drupal instance independently of whether it uses DA or OG, and can easily be enabled on multiple instances on the same install as well. As of this writing Workbench does not integrate with either module, so for instance Organic Groups or Domains cannot be used to define "sections" in Workbench, but such integration is possible.

---

**Conclusion**

Drupal offers a variety of solutions to address multiple sites with shared and separate content. As with all things Drupal there is no right solution — just options for your specific needs. Evaluate your goals and make decisions based on them; you may find that Domain Access is a better fit for your content editors or a multi-site setup is much easier to manage for your system administrators.

# Answer
> 4 votes
Has anyone considered recommending Organic Groups? this is a lightweight less complete solution, but uses one Drupal installation and separates out each group as a unique and independent section. Also. A much more elegant and true solution would be to use Aegir as a Host manager that spins up any number of unique sites for organizations.

---
Tags: 7
---


# Question
Title: How can I use jQuery 1.7 without having issues in the admin pages?
Is anybody successfully running jQuery 1.7? I'm using a jQuery component on my pages which requires jQuery 1.7 or later. This version causes some unwanted side effects in the admin UI, such as checked checkboxes that don't reveal additional controls when available, or field widget not being active.

I was wondering if there's a solution that could let me easily work with jQuery 1.7.

I saw this answer before asking. As far as I understand, there are 2 separate issues: updating src of the jQuery to 1.7.x, and updating the javascript used by admin. I tried to use the latest jquery\_update development snapshot, and apply a patch, but it does not solve the above-mentioned problems with UI.

# Answer
> 11 votes
I would look at Clive's advice on doing it manually here:

How do I update jQuery to the latest version I can download?

and add some more intelligence into the script to not do it on admin pages, eg:

```
if (arg(0)=='admin') {
  return;
}

```

You would also have to do that on `node/#/add` and `node/#/edit` pages etc so as to not disrupt anything "core" there, or, if you want, dive into drupal core and bring everything else up to 1.7 as well.

Depending on what version of Drupal you are running, this might also work:

```
function YOURTHEME_preprocess_page(&$vars) {
  if (YOUR CONDITION HERE) {
    $scripts = drupal_add_js('PATH TO YOUR JQUERY FILE');
    unset($scripts['core']['PATH TO DRUPAL JQUERY FILE']);
    $variables['scripts'] = drupal_get_js('header', $scripts);
  }
}

```

where you could set "YOUR CONDITION HERE" to be whatever pages you want the new jquery on, eg, `arg(0)!='admin'` etc.

# Answer
> 2 votes
jQuery Update now has the ability to enable different jQuery versions for the front-end and the back-end. Download the latest dev version and you're good to go: 1.5 in the backend, so it works with the Views UI, and 1.7 or 1.8 in the frontend, for extra jQuery goodness.

---
Tags: javascript
---


# Question
Title: multiple (two at least) user registration forms
I have built a registration form with a few custom fields, works fine. Now I need to another registration form, but with a dozen or so more fields. Both need to force drupal into its user registration/validation process.

it has to be done this way, I cannot just redirect a user to register first then fill out a survey.

Alex

# Answer
You can achieve this using Profile 2 and Profile2 Registration Path module.

**Profile 2**

> Multiple profile types may be created via the UI (e.g. a general profile + a customer profile), whereas the module provides separated permissions for those

**Profile2 Registration Path**

> This module enables administrators to set unique registration paths per Profile2 profile type
> 0 votes

# Answer
if you want to add data to the user, add fields here (admin/config/people/accounts). see here

webform is a very nice module, where you can create forms via the UI, also offers stats etc.
> -1 votes

---
Tags: users
---


title: Countdown with Views

text:
# Question
Title: Countdown with Views
i'm trying to format a countdown block in views to look like . This was done with the Countdown Module, however I'd like it to change automatically based on the nearest event date and not have to enter in each event manually. I can set this up in views, however I'm having trouble trying to figure out how to format it. Right now it looks like this. So i'd like hence/ago to read since or until after the number of days, followed by the event name. Thanks for any help!

Sharon

# Answer
If you use Display Suite, you can create a custom field with the Display Suite Format and use the following (with your own date field name). You could also use a custom PHP field or some kind of hook, but the following logic still applies.

```
<?php
if (!empty($entity->field_event_start)) {

    // Get the starting time value and the timezone.
    $start_value = $entity->field_event_start['und'][0]['value'];
    $timezone = $entity->field_event_start['und'][0]['timezone'];

    // Create the date objects for now and the day of the event.
    $start_date = new DateObject($start_value, $timezone);
    $now = new DateObject(time(), $timezone);

    // Take the difference between now and the beginning date, in days format.
    $duration = $now->difference($start_date, 'days');
    print $duration . ' Days';
}
?>

```

You should end of with something like the following, and then jazz it up with your own styling.

**Edit**

I just realized you wanted "since" as in after, so just switch it up a bit and use the end date instead of the start date, if one exists. I also made a quick video on how to add in the custom code field, so hopefully this helps!

Custom Date Since field in Display Suite
> 1 votes

---
Tags: views, datetime
---


# Question
Title: how to show message in popup when user register to site?
I just want to show message in popup when user register to site."Further instructions have been sent to your e-mail address". This message i want to show in pop-up.

# Answer
Use this module to show popup on the specific page.Use the latest dev version https://drupal.org/project/popup\_message
> 2 votes

# Answer
You can check Better message module for this purpose.

From the module's project page:

> Better Messages is a very simple module that provides "Popup-like" Drupal messages.
>
> Better Messages intends to let you control where and how you want to see your Drupal messages! Combine different animations and override `better_messages.tpl.php` to create your custom look.
> 0 votes

---
Tags: theming
---


title: How to show in pop up box message in D7

text:
# Question
Title: How to show in pop up box message in D7
I am developing custom module in D7. And created one custom block. And how can show the conent in the block as pop up box?sample block code is \`

> $block\['content'\] = t('Test message');

I want show 'Test message' as in pop up..

\`

# Answer
> 1 votes
There are several modules that you may be able to use or deconstruct to help with your custom module.

# Answer
> 0 votes
There is the Popup message module which provides you the same functionality as you need.

From the module's project page:

> Display popup message for users once per browser session.
>
> Based on javascript code: http://yensdesign.com/2008/09/how-to-create-a-stunning-and-smooth-popup-using-jquery/

---
Tags: blocks, javascript
---


# Question
Title: Uninstalled modules still in system table?
Right now I,m facing problem with high resource usage of my Drupal 6 website, I can't find the solution to solve the issue, when I checked the system table, **uninstalled modules still in system table**, Is this **normal** or not uninstalled properly.

# Answer
There is apparently infinite loop of "marked as dulpicate" bug reports related to this on Drupal.org. Starts form me with Deleted modules are not removed from system table. Long story short, yes, it happens, and it seems it can be both due to Drupal bug or bug in a modules in question.

There used to be a module to clean this up, but it wasn't even finished before this functionality ended up in Drupal 7 core. If you feel like risking, you can download sources using Repository viewer.

On the other hand, most queries filter by status field, and there should be already a BTREE index on it, so leftovers should not hurt you much anyway. If you want to cleanup manually, be sure nothing depends on modules you are about to purge and their files are already deleted, make backups, put site in maintenance mode, logout everyone (including you) and be prepared to restore `{system}` table (or whole database) from backup if needed.
> 2 votes

# Answer
Drupal adds an entry in system table for each module present in the filesystem, even if it has never been enabled. This is the same for Drupal 6 and 7. In Drupal 8 the system table has been removed.

So, if you want to get rid of entries in system table for uninstalled modules, remove them from the filesystem once they're uninstalled.

See \_system\_rebuild\_module\_data() for details in Drupal7. In drupal 6 this function was called module\_rebuild\_cache().
> 3 votes

---
Tags: 6, database
---