# Question
Title: How to trigger a form and pass variables to $form_state with jQuery?
What is the way to trigger a Drupal form via JavaScript, and pass new values to `$form_state` while doing so?

I have a main form, which has an element that triggers a jQuery UI dialog with a form in it. When submitting the dialog form, I want to bring the values back into `$form_state`. I want the main form to display and save the values from both forms. Both Ctools Ajax example and MonoDialog show examples that just manipulate the DOM of the main page/form after submitting a form in a dialog.

One thing I could maybe do is populate a hidden form field with the values from the dialog form in JSON format, and then trigger an ajax button with jQuery. I rather not do this as it doesn't sound like a clean solution.

What I try to achieve is kind of like the views ui interface, which has a form with form in dialogs. Submitting the dialog forms, updates the main form.

### Code example

```
<?php
function example_main_form($form, &$form_state) {
  // The main form is defined here. Includes a button which triggers a
  // callback function (example_main_form_callback) to open up a new form
  // in a dialog popup. Upon this ajax trigger, it also populates $form_state
  // with some values to pass to the dialog form.
}

function example_main_form_callback($form, &$form_state) {
  $commands = array();
  // open dialog
  $commands[] = ajax_command_invoke('#dialog', 'dialog', array('open'));
  // dialog title
  $title = t('Configure:') . ' ' . $form_state['dialog']['values']['title'];
  $commands[] = ajax_command_invoke('#dialog-title', 'html', array($title));
  // dialog body
  $body = drupal_render(drupal_get_form('example_dialog_form', $form_state['dialog']));
  $commands[] = ajax_command_invoke('#dialog-body', 'html', array($body));
  return array('#type' => 'ajax', '#commands' => $commands);
}

function example_dialog_form($form, &$form_state) {
  // include this file in build_info
  form_load_include($form_state, 'inc', 'example', 'example.forms');
  // The popup dialog form is defined here.
  // the submit button has an ajax callback, which calls
  // example_dialog_form_callback below.
}

function example_dialog_form_callback($form, &$form_state) {
  // This callback closes the dialog, but I also want to populate the
  // form_state of the main form with the values of this saved form. The values
  // are available in this callback's $form_state, but I'm not sure what the
  // best way is to pass them on to the main form. Is it possible to trigger
  // another form programmatically using jQuery?
  $commands = array();
  // close dialog
  $commands[] = ajax_command_invoke('#dialog', 'dialog', array('close'));
  return array('#type' => 'ajax', '#commands' => $commands);
}

```

I think I could attach the dialog form values to the `Drupal.ajax.example_element.options.data` object. In this way, when the main form is programmatically triggered for an Ajax callback, the values in `options.data` will be added to the main form `$form_state['input']`. That's the cleanest approach I found so far, but still not straightforward. A separate function is required to populate `options.data`. One options is to extend `options.beforeSerialize()`, but in my case the Ajax element is dynamic. (See How to extend or "hook" Drupal Form AJAX?) Thus this approach would work better:

In the dialog form callback:

```
<?php
function example_dialog_form_callback($form, &$form_state) {
  $dialog_id = 'dialog-id';
  $commands = array();
  // close dialog
  $commands[] = ajax_command_invoke('#dialog', 'dialog', array('close'));
  // Call function which attaches the dialog form values to Drupal.ajax.{dialog-id}.options.data.
  // After triggering the dialog ajax callback, the dialog values will be added to the $form_state of
  // the main form
  $data = array(
    'id' => $dialog_id,
    'values' => $form_state['input'], // for example, but could be cleaned up.
  );
  $commands[] = ajax_command_invoke(NULL, 'dialogValues', array($data));
  // trigger dialog button
  $commands[] = ajax_command_invoke('#' . $dialog_id, 'trigger', array('click'));
  return array('#type' => 'ajax', '#commands' => $commands);
}

```

The jQuery function:

```
$.fn.dialogValues = function(data) {
  // dialog ajax id
  var dialogAjaxId = data.id;
  // add values as JSON, so we can pass multi dimensional arrays
  Drupal.ajax[dialogAjaxId].options.data._dialog_values = JSON.stringify(data.values);
};

```

Is there a better solution?

# Answer
I can think of two ways that might work for you:

1. (a) In `example_dialog_form_submit()` (not in your question), get the submitted values from the `values` key of `$form_state` (values from the dialog form). Lets say we call this a *record*. You can either save the record using the `$_SESSION` super global or the CTools object cache.

(b) Now, when the main form is being validated, use the values from the *record* in the validate callback, say `example_main_form_validate()`. On failed validation, ignore. On successful validation, add values from the record to the `$form_state` of the main form using `form_set_value()`. Now, your main form submit handler can always assume that it'll have the values from the dialog form as well. (somewhere in its own `$form_state` tree)
2. An alternative way by which you can structure your forms is:

(a) Instead of loading your dialog form using AJAX, you can make it a part of the main form itself as a set of elements. `#limit_validation_errors` can help you define the boundary for the dialog "form" within the main form.

(b) On submit inside the dialog, you can just do a `$form_state['rebuild'] = TRUE` to allow the form to rebuild. In the AJAX callback, close the dialog and refresh the main form.

(c) In this approach, the form submit handler in the main form will always have the values from the dialog and it is easier to debug. Only caveat is if the form inside the dialog has a lot of elements in which case an AJAX load (like you are doing already) might be better.
> 0 votes

# Answer
FWIW/others: Rather than extending jQuery you can extend the Drupal.ajax commands, and thereby the commands you send back from Drupal to the JavaScript.

javascript:

```
Drupal.ajax.prototype.commands.mymodule_command = function(ajax, response, status) {
  console.log('mymodule_command', ajax, response, status);
  console.log('arguments', response.arguments);
};

```

php:

```
$commands[] = array(
  'command' => 'mymodule_command',
  'arguments' => array(...),
);

```
> 0 votes

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


# Question
Title: Possible to run views_embed_view() for a specific role
Without having to `user_load(SOME_UID_THAT_HAS_MY_INTENED_ROLES);` and swap the current `$user` object and then replace it.

Is it possible to say,

```
views_embed_view('view_of_articles');

```

But tell it to respect the permissions of a certain array of roles like,

```
views_embed_view('view_of_articles', array(SOME_RID));

```

I know the above wont work since the function isn't defined in such a way, but could this be possible with `theme()` functions, or something else I'm missing?

# Answer
In view check the option of "Access" and select roles. Now even if you call the view with views\_embed\_view() It wont display if the user is not part of the role that have access.
> 0 votes

---
Tags: views, users, theming
---


# Question
Title: Open Layers map not showing pointers drupal7
I have created a content type in drupal 7 and added a reference to a taxonomy term.The taxonomy term has geofield data i.e Longitude and Latitude. The challenge is when I create a view and use an Openlayers data overlay following what is provided in the open layers documentation I do not have a pointer on my map. Could there be anything I am not doing right here?

# Answer
> 0 votes
There's a slight tiff at the moment betwen Views 7x-3.5 and Openlayers 7x-2.0beta. I rolled back to 7x-3.3 and my markers were back. I am filing a bug report for views. Thank you people for your help.

# Answer
> 1 votes
I had the same problem when I used a non-default PIN image, the URL it then used was incorrect, it included '?q', so the pin image didnt display. This was using openlayers-7.x-2.0-beta1, and when I applied the openlayers-fix-marker-lang-path-1404912-3.patch (http://drupal.org/node/1404912) it was fixed and worked for me. Hope this helps.

# Answer
> 0 votes
You have to create a view with a page or block display and set it to "Openlayers map" mode.

The you add another display of type "Openlayers Overlay Data" and here add a relation based on term field. In this display add fields about latitude and longitude and edit settings of the display.

Finally you have to create map, or edit an existing map, and you have to add the layer "Openlayers Overlay Data" you have just create. Remember to set the right openlayers map on the display "openlayers map" in the view.

---
Tags: 7, javascript
---


# Question
Title: Twitter Cards with Metatag module not working
I've got the metatag module installed and enabled. I've also enabled the MetaTag: Twitter Cards sub-module so that it will render meta tags for twitter cards, but I'm not seeing any twitter: metatags in the head at all.

Here is a page on my site:

http://www.inadaydevelopment.com/app/ios/10bii-financial-calculator

Here is the export of the Node configuration, I believe the only thing I changed is that I set a creator value for my twitter account:

`$config = new stdClass();
$config->disabled = FALSE; /* Edit this to true to make a default config disabled initially */
$config->api_version = 1;
$config->cid = '1';
$config->instance = 'node';
$config->config = array(
 'title' => array(
 'value' => '[node:title] | [site:name]',
 ),
 'description' => array(
 'value' => '[node:summary]',
 ),
 'og:title' => array(
 'value' => '[node:title]',
 ),
 'og:description' => array(
 'value' => '[node:summary]',
 ),
 'twitter:creator' => array(
 'value' => '@inadaydev',
 ),
 'twitter:title' => array(
 'value' => '[node:title]',
 ),
 'twitter:description' => array(
 'value' => '[node:summary]',
 ),
);`

I created a new default metatag for content type App, here is the export:

`$config = new stdClass();
$config->disabled = FALSE; /* Edit this to true to make a default config disabled initially */
$config->api_version = 1;
$config->cid = '2';
$config->instance = 'node:app';
$config->config = array(
 'twitter:image' => array(
 'value' => '[node:field_phone_screenshots]',
 ),
);`

However, none of the twitter:card meta tags show up at all... what am I doing wrong?

# Answer
> 2 votes
If you´re using the **7.x-1.0-Beta4** version of metatag module (which is the most recent one at the time of writing this answer), you may want to apply the following patch:

http://drupal.org/node/1846978#comment-6764558

**(for Unix-like systems only)** For applying the patch, just go to a terminal, change the working directory to the directory of the metatag module and try this:

`curl http://drupal.org/files/metatag-fix_theme_hook_mismatch-1846978-0.patch | patch -p1`

---
Tags: 7, meta-tags, social-network
---


# Question
Title: syncronize drupal 7 users with magento 1.7 customers
The Module that is available in drupal is supporting the previous versions of Drupal (D6) and Magento(1.6). You can find it here

```
http://drupal.org/project/magento

```

I am using D7 with Magento 1.7, Is anybody out here can suggest me a flow how to add records in customer table while users are registering in drupal, Since i am very new to drupal as well as magento i am finding it a bit difficult to hack into D7 functions

Can this method be followed?

```
http://mysillypointofview.richardferaro.com/2010/09/07/how-to-pull-the-list-of-customers-from-magento-to-an-external-site/

```

Does this method have any security vulnerabilities associated with it?

I only need to add a few fields like

```
First Name
Last Name
Email
Password
Entity_type_id

```

Rest of the customer details can be updated using the magento engine itself once the user is logged in

Thanks

# Answer
I would use Rules to trigger an action whenever a new user is created (and/or updated which will also matter in your scenario). This action can be a PHP script so the possibilities you have to interact with other software (Magento) are endless.
> 1 votes

---
Tags: users
---


# Question
Title: How to add multistep registration form in default user registration
I need to create a user registration form in Drupal 7. My requirement is as follows:-

1. I want to use the default Drupal 7 User Registration Form i.e admin/config/people/accounts
2. Form must appear in popup/modal when user click on "Create new account" in User Login Form
3. Form should be Multistep i.e there will be 3/4 steps of filling the form.
4. Customize the form in such a way that UserName, Password and Email appears on last step of the form.

Please let me know if it is possible in Drupal 7 default user registration form and how?

# Answer
> 1 votes
You can try Field group

> Fieldgroup will, as the name implies, group fields together. All fieldable entities will have the possibility to add groups to wrap their fields together. Fieldgroup comes with default HTML wrappers like vertical tabs, horizontal tabs, accordions, fieldsets or div wrappers.

**Available group types**

* Fieldsets
* Horizontal tabs
* Vertical tabs
* Accordions
* Divs
* Multipage steps: **Note: This is only client side.**

The idea is to use *Multipage steps* to make the form steps.

# Answer
> 1 votes
Go through the Tutorial: Ten Step-by-Step Code Samples for Learning Form API, and check with Forms API.

or the following link : Building a Multistep Registration Form in Drupal 7.

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


# Question
Title: Views Exposed filter Multiple times on a Page Or Different id for views exposed filter if added one more time
I added a `views exposed filter` to block and I want to show the block multiple times on the `dashboard` page each can have different choices. Can it possible without adding any other `display`?

Or Can it be possible to change the make the id unique for each occurrences of same `exposed filter`?

My Actual Need is :

I am using `Homebox` module for creating a `Dashboard` for user. I created a `view` with `block display` so user can add it in their `Dashboard` multiple times. I added the `Exposed filter` of `taxonomy terms` and I entered the choices of user in my `custom table`. Now user can add same block with different choices. My questions is how to manage different choices with `blocks`,because `exposed filter` have same form id on each occurrences.

# Answer
While adding a filter there is a dropdown at the top as 'For', by default 'All displays' are selected, by selecting the specific block that particular filter will be displayed on selected block only. Please try and let me know if it worked.
> 0 votes

---
Tags: 6, blocks, views, dashboard
---


# Question
Title: showing translation of the related node in view
I have a node type called Match. Each match have two entity reference fields that points to two nodes that has the type of Team. I built a view and use the relationship to show the matches and the information of the host team and guest team and it's fine. My problem is that the Team node is multilingual and I want to show the translation of Team fields in the view. It is obvious that the fields has a reference to the original untranslated node ID and when I use the relationship in the view it will grab that node even if it has translations.

# Answer
> 0 votes
You can use the Translation redirect module (part of the Internationalization module) if your users are anonymous (unauthenticated). It just issues a 301 redirect whenever translated content exists.

If your users are logged in then there is another approach I have used, use an **URL alias** for your nodes. Set the alias to be the same for all translated content of a node and when linking to that node use the URL alias instead of the node number.

---
Tags: views, nodes, i18n-l10n
---


# Question
Title: How does a view (/admin/build/views/) relate to a .tpl file
I am new to Drupal and now maintaining a completed Drupal site and I am struggling to understand how it all came into existence :)

What I have gathered from poking around the current code base is that there is some kind of relation from a view you create in the admin section to a .tpl file, and for the life of me I cannot figure out what it is.... am I even on the right track?

Any help or good reads would be much appreciated!

# Answer
Actually, a view will use many template files (which you can override in a theme if desired); it depends a lot on how you configured your view (e.g. style, content).

The most useful information can be found when you're configuring your View. Just click `Theme: Information` in the `Basic settings` pane of your View, and the View itself will give you a list of tpl.php files that are used for rendering. Don't forget that there **isn't only one** tpl.php - there are many, and they wrap each other a lot (they're nested). Reading about generic Drupal theming will help a lot. The same rendering basics are used for Views.

If you want a template file for **one specific View**, look at the suggestions given by "Theme: Information." You can override any template file, for a specific View only (identified by its machine-name). This is probably what you're asking for, actually.

A good link on the subject is Theming Views.
> 3 votes

---
Tags: views, theming
---


# Question
Title: Drupal 7: check login password with DB password
I'm working on drupal 7, i'm looking for developing customize user log-in module into my site. but facing a problem in that, when we are submit log-in page then password doesn't match with DB password. because drupal not using MD5 encryption method for storing password into it.

So what would be the batter solution for it? how can i achieve my task without fail.? Please help me, its appreciate.

Thanks.

# Answer
You can tweak the existing user login form by implementing hook\_form\_alter or one of its friends (see link). It allows you to add your own password validation functions.

If you don't know which form ID to use, you can add this code to a custom module to get all used form ids printed out:

```
mymodule_form_alter(&$form, &$form_state, $form_id) {
    dpm($form_id);
}

```

You need the Devel module, and appropriate permissions to see the output of `dpm()`.

But there's more. You have to think about password changes, password retrieval, account creation, etc. To let users log in (with your own password check) you need to have a valid Drupal user account for every user. It's not enough to just validate the password against your own database. A possibility would be creating the user accounts in the background once the password check was positive.

A completely different approach: Import your existing users into the Drupal users table, and let them know they have to go through password retrieval.
> 2 votes

# Answer
Drupal 7 doesn't store the MD5, but the password's hash.

You can compare the passwords pretty easily: Use user\_hash\_password() to get the corresponding hash of the entered password. The function is found inside includes/password.inc.

You can do the comparison in a custom module through a validation handler for the user login form.
> 2 votes

# Answer
To compare the passwords you could try `user_check_password()`.

> Check whether a plain text password matches a stored hashed password.
>
> **Parameters**
>
> **$password**: A plain-text password
>
> **$account**: A user object with at least the fields from the {users} table.
>
> **Return value**
>
> TRUE or FALSE.

See also Secure password hashing functions for user authentication.
> 1 votes

---
Tags: 7, users
---


# Question
Title: Added ajax to a Link but its not working
I added a class `use-ajax` to a link but Its not updating the wrapper \`div. My Code is:

```
function custom_menu(){
  $items['testing'] = array(
    'page callback' => 'articlenodeform',
    'access arguments' => array('access content'),
  );
  $items['customajaxcallback'] = array(
   'page callback' => 'custom_ajaxcallback',
   'access arguments' => array('access content'),
  );
  return $items;
}

function articlenodeform(){
   drupal_add_library('system', 'drupal.ajax');
   drupal_add_js('misc/ajax.js');
   $link = l(t('Say Hello'), 'customajaxcallback/ajax', array('attributes' => array('class' => 'use-ajax')));
   return '<div>'.$link.'</div><div id="sayinghello"></div>';
}

function custom_ajaxcallback($type = 'ajax') {
  if($type == 'ajax') {
    $output = t('Hello World!');
    $command = array();
    $commands[] = ajax_command_append('#sayinghello', $output);
    $page = array('#type' => 'ajax', '#ajax_command' => $commands);
    ajax_deliver($page);
  }
  else{
    return t("Hello world in new page.");
  }
}

```

# Answer
> 1 votes
I did it : The problem was in my callback function :

```
function custom_ajaxcallback($type = 'ajax') {
  if($type == 'ajax') {
    $output = t('Hello World!');
    $command = array();
    $commands[] = ajax_command_append('#sayinghello', $output);
    $page = array('#type' => 'ajax', '#commands' => $commands); --> In this line
    ajax_deliver($page);
  }
  else{
    return t("Hello world in new page.");
  }
}

```

# Answer
> 0 votes
Change your link to this:

```
$link = l(t('Say Hello'), 'customajaxcallback/ajax', array('attributes' => array('class' => array('use-ajax'))));

```

class element itself must also be an array. read about it here

# Answer
> 0 votes
```
function custom_menu(){
  $items['testing'] = array(
    'page callback' => 'articlenodeform',
    'access arguments' => array('access content'),
  );
  $items['customajaxcallback/%'] = array(
   'page callback' => 'custom_ajaxcallback',
   'access arguments' => array('access content'),
    'page arguments' => array(1),
  );
  return $items;
}

function articlenodeform(){
   drupal_add_library('system', 'drupal.ajax');
   $link = l(t('Say Hello'), 'customajaxcallback/nojs', array('attributes' => array('class' => 'use-ajax')));
   return '<div>'.$link.'</div><div id="sayinghello"></div>';
}

function custom_ajaxcallback($ajax) {
  if($ajax == 'ajax') {
    $output = t('Hello World!');
    $command = array();
    $commands[] = ajax_command_append('#sayinghello', $output);
    $page = array('#type' => 'ajax', '#ajax_command' => $commands);
    ajax_deliver($page);
  }
  else{
    return t("Hello world in new page.");
  }
}

```

**edit: If you noticed, there were several changes made in the code.**

1. link has been changed to `customajaxcallback/nojs`
2. hook menu is now `customajaxcallback/%`
3. We pass argument 1 to the callback function custom\_ajaxcallback `'page arguments' => array(1),`
4. Callback function has been changed by removing the default value and making it look like this `custom_ajaxcallback($ajax)`

---
Tags: 7, ajax
---


# Question
Title: is it ok to use system_check_directory in a custom module?
I love the easiness of applying system\_check\_directory to a form field. You just add

```
'#after_build' => array('system_check_directory'),

```

to your field definition in a form and it does it all :

* check if the dir exists
    + create it if not
* check if it is writeable
* report to the user

As seen (on TV) in the drupal core.
Indeed, it probably does a little too much - the extra .htaccess file ... Could that cause any problem ? The description of the function looks almost as if it was **only** for the system form.

# Answer
> 2 votes
Of course it is ok to use this function in a custom module as long as you take care of securing the form where this is used in. You should keep in mind that the error messages generated by this function could give valuable information about your file system to malicious users. If you limit access to the form that uses this function to trusted users only then there shouldn't be problem.

The function is tailored for core use, you can already see that in the way that it generates the .htaccess file depending on the #name attribute of the form array. But if you want to provide a configurable private directory to store uploaded files for a custom module then it seems like a convenient solution.

---
Tags: forms
---


# Question
Title: How do I show the form for adding a node as block?
I have a content type with the title and name fields. How can I the form for adding a node as block, in the front page?

I am using Drupal 7.

```
function mail_block_info() {
  $blocks = array();
  $blocks['mail_block'] = array(
    'info' => t('backend info left block'),
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

function mail_block_view($block_name = '') {
  if ($block_name == 'mail_block') {
    $match = TRUE;
    $types = array('mailin_list_node_form' => 1);
    if (arg(0) == 'node' && is_numeric(arg(1))) {
      $node = node_load(array('nid' => $nid));
      $type = $node->type;
      if (isset($types[$type])) {
        $match = FALSE;
      }
    }

    $contact_node = node_load($node);

    drupal_get_form($node);
    $block = array(
      'subject' => t(''),
      'content' => $content,
    );

    return $block;
  }
}

```

# Answer
Try this:

```
function mail_block_info() {
  $blocks = array();
  $blocks['mail_block'] = array(
    'info' => t('backend info left block'),
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

function mail_block_view($block_name = '') {
  global $user;

  if ($block_name == 'mail_block') {
    // This is required if you want to show this block even if user profile page.
    module_load_include('inc', 'node', 'node.pages');

    // Create a node for the content type.
    $node = new stdClass();
    $node->uid = $user->uid;
    $node->name = $user->name;
    $node->type = 'CONTENT_TYPE_NAME';
    $node->language = LANGUAGE_NONE;
    // Create the form.
    $form = drupal_get_form('CONTENT_TYPE_NAME_node_form', $node);

    $block = array(
      'subject' => t(''),
      'content' => drupal_render($form),
    );

    return $block;
  }
}

```
> 1 votes

# Answer
Try node\_add():

```
$content = node_add($type);

```

or:

```
$content = drupal_get_form($type . '_node_form', $node);

```

Also, please keep in mind that `node_load()` changed in D7. You should use it like this:

```
node_load($nid);

```
> 2 votes

# Answer
There are some errors in your code.

```
    $types = array('mailin_list_node_form' => 1);
    if (arg(0) == 'node' && is_numeric(arg(1))) {
      $node = node_load(array('nid' => $nid));
      $type = $node->type;
      if (isset($types[$type])) {
        $match = FALSE;
      }
    }

```

In Drupal 7, the first argument of node\_load() is the node ID, not an array. The full code snippet is unnecessary complex. All that code can be replaced with a call to menu\_get\_object(), and to check the content type of a node you just compare `$node->type` with a string.

```
    $contact_node = node_load($node);

```

You are passing to `node_load()` an object you already obtained from `node_load()`. First, `node_load()` doesn't accept an object, in Drupal 7 (nor would it accept a node as first argument, in Drupal 6); secondly, it doesn't make sense to call `node_load()` when you have already obtained a node object from that function.
You initialize `$contact_node`, but that variable is not used from the rest of your code.

```
    drupal_get_form($node);

```

The parameters passed to drupal\_get\_form() are wrong; the first argument passed is the form ID, and you didn't pass that argument to the function. The result returned from the function is not saved; probably you were supposed to save it in the `$content` variable.

I would use code similar to the following one.

```
function mail_block_view($delta = '') {
  if ($delta == 'mail_block' && ($node = menu_get_object()) && $node->type == 'YOUR CONTENT TYPE') {
    $block = array(
      'subject' => '',
      'content' => drupal_get_form('YOUR CONTENT TYPE FORM ID', $node),
    );

    return $block;
  }
}

```

Replace `'YOUR CONTENT TYPE'` with the ID of the content type, and `'YOUR CONTENT TYPE FORM ID'` with the form ID for the form, which is normally similar to `<your_content_type>_node_form`, where `<your_content_type>` is the string you used for `'YOUR CONTENT TYPE FORM ID'`.

To notice that it is not necessary to pass an empty string to `t()` because an empty string is still an empty string in all the languages; there is no need to translate it.
> 1 votes

# Answer
There is a module Form Block

> Enables the presentation of user registration, site wide contact, or node creation forms in blocks. This is particularly useful for including forms on panels.

As its dev in D7 make sure you read the Issues for Form Block
> 1 votes

# Answer
```
function mail_block_view($block_name = '') {
  if ($block_name == 'mail_block') {
    $form = drupal_get_form('mailin_list_node_form');
    $block = array(
        'subject' => t(''),
        'content' => drupal_render($form),
    );
    return $block;
  }
}

```
> 0 votes

---
Tags: nodes, hooks, blocks
---


title: How to know, if on taxonomy page?

text:
# Question
Title: How to know, if on taxonomy page?
> **Possible Duplicate:**
> Check if current page is taxonomy term

For now, I use something like this to decide, if I'm on a taxonomy page.

```
if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
   $tid = intval(arg(2));
   $parents = taxonomy_get_parents($tid);
   $term = $parents[0];

   ...
}

```

Is there a more elegant way to decide, if I'm on a taxonomy page than this arg(0), arg(1), arg(2) thing? Same would apply to a node page `if (arg(0) == 'node' && is_numeric(arg(1)))`.

I didn't find any reference in the net. But maybe I ask the wrong questions.

# Answer
> 4 votes
You could try `menu_get_object()`, it's slightly cleaner:

```
$term = menu_get_object('taxonomy_term', 2);
if ($term) {
  // You're on a term page and have the loaded object in $term
}

```

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


# Question
Title: how do I add extra classes to a date field at views?
I am using **Drupal 7**. I created a view, that is using a date field. I would like to create extra classes to the date field for that specific view.

For example,

```
<div class="field-content">
 <span class="date">10</span>
 <span class="month">June</span>
 <span class="year">2011</span>
 <span class="time"> 8:00 </span>
</div>

```

Now I have a code:

```
<div class="field-content">
 <span class="date-display-single">10 June 2011, 8:00</span>
</div>

```

How can I do it step by step?

# Answer
> 3 votes
1. You need to install token module (latest beta version includes field tokens) and **custom formatters** module from http://drupal.org/project/custom\_formatters.
2. Then enable it from modules page.
3. Go to admin-\>structure-\>formatters.
4. Add a new formatter, put it a name that you like.
5. Format: HTML + Tokens
6. Field type: Date
7. Formatter:

> ```
> <span class="day">[node:source:field-datefieldname:custom:j]</span>
> <span class="month">[node:source:field-datefieldname:custom:F]</span>
> <span class="year">[node:source:field-datefieldname:custom:Y]</span>
>
> ```
8. Save

Now, you have created a custom date formatter, that you may use at your view!

# Answer
> 4 votes
You can do this without any additional modules.

1. Add the date field. Exclude this from the display. Choose custom, and write d in the box (as in php date for the day). Change the 'Style Settings' - Customize field HMTL (set to none) and Customize field and label wrapper HTML (set to none).
2. Add the date field again. Exclude this also from the display. Choose custom, and write M in the box (as in php date for the month). Change the 'Style Settings' - Customize field HMTL (set to none) and Customize field and label wrapper HTML (set to none).
3. Add the date field again. Exclude this also from the display. Choose custom, and write Y in the box (as in php date for the year). Change the 'Style Settings' - Customize field HMTL (set to none) and Customize field and label wrapper HTML (set to none).
4. Add the date field again (LAST TIME!). DO NOT EXCLUDE THIS FROM THE DISPLAY. Choose custom, and write G:i (as in php date for the hours and minutes). Change the 'Style Settings' - Customize field HMTL (set to none) and Customize field and label wrapper HTML (set to none).
5. Rewrite the results of this final date field. Using the replacement patterns, you can then write something like this:

```
<div class="date">
  <span class="day">
    [created]
  </span>
  <span class="month">
    [created_1]
  </span>
  <span class="year">
    [created_2]
  </span>
</div>

```

# Answer
> 3 votes
A reasonably quick (if you can write php), but slightly hackish solution would be to override the template for that field (see Views theming basics), process the raw date value with php to take out the separate pieces and then glue them together with the HTML of your choice.

Alternatively, I think you could write a custom date field formatter (here is someone who did that for D6). That would be a nice solution in case you want to re-use the custom formatter in your nodes.

# Answer
> 1 votes
This is not possible using the Views UI. You would need a rather complex bit of code, and I'd be curious about your use case before encouraging you to embark on figuring that out.

If you asked how to add classes to the field as a whole, the answer would be something like this:

1. Click on the field in the Views interface.
2. Expand the "Style Settings" fieldset.
3. Check the "Customize field HTML" checkbox, then the "Create a CSS class" checkbox.
4. Enter your desired class.

Perhaps that solution will be enough. Otherwise, I wish you luck.

# Answer
> 1 votes
This is really easy, (once you know how)

Use a display suite custom field

Go to admin/structure/ds/fields

(In the menu: Structure -\> Display Suite -\> Fields)

Click add a code field

For my use case I entered the following

**Label**

Anything

**Entities**

Node

**Limit field**

Left blank

**Field code**

```
<div>
  <span class="mf-month">[node:created:custom:M]</span>
  <span class="mf-day">[node:created:custom:d]</span>
</div>

```

**Token**

checked

Once you've created the field, then go to the manage display page for the content type and view mode that you're adjusting and select the new custom field.

**Screenshot of the setup above**

---
Tags: 7, theming, datetime
---


title: How to export Drupal page as PDF?

text:
# Question
Title: How to export Drupal page as PDF?
I am using Drupal 7.17, and have created content of type book. I want the users to be able to export it to PDF format. The pages contains images, HTML tables, HTML ordered and unordered list (ul and li). What is the best way to do this? The content styles should be preserved when exported.

# Answer
You can use the Print module

> This module allows you to generate the following printer-friendly versions of any node:
>
> Printer-friendly version (webpage format) (at www.example.com/print/nid) PDF version (at www.example.com/printpdf/nid) Send by email (at www.example.com/printmail/nid) where nid is the node id of content to render.

And your choice of one of the 4 PDF libraries it supports. It does have very high memory requirements when generating PDF as previous comments have noted. It is well documented and the PDF output is fully themeable.
> 6 votes

---
Tags: files
---


title: Twig & Drupal: state of art

text:
# Question
Title: Twig & Drupal: state of art
I'm a really newbie in Drupal world. I use Plone since 2004 but now I've to learn also Drupal for various reasons. I'm reading books and tutorials, using this CMS as power user and many more.

Now it's time to go deep and the first thing goal is: theming from scratch. I've notice that PhpTemplate it's not exactly a clean pagetemplate system (for my point of view), while Twig seems very interesting, but I don't understand if Twig could be clearly used in Drupal7 or not.

# Answer
> 2 votes
Twig is in Drupal 8 core, but you can use it in Drupal 7. Check out this sandbox that provides twig as a theme engine.

# Answer
> 0 votes
All twig realisations in development state:
\[meta\] New theme system \- wait for Drupal 8.
Also read this note about Twig and Drupal and development state for current versions.
One solid module for twig:
Twig template engine \- Provides the Twig template engine as an input filter - it's just input filter, so it's not for you.

Also I am agree with this comment.

---
Tags: 7, theming
---


# Question
Title: Is it possible to have a custom filter for exposed criteria?
When I've created a view where the filter criteria is:

```
"Content: Has taxonomy terms (with depth) (exposed)"

```

It works well, but I'd like to filter the terms. I have some "`main term`" and a lot of "`sub-terms`" for each "`main term`". What I'd like for this view, is to search ***only*** through "`main term`", i.e. propose in the list only "`main term`", not "`sub-terms`".

How can I achieve this?

If that may help: the parents of main "`main term`"s == 0 (in other words, "`main term`"s have no parents)

# Answer
> 1 votes
Here's the solution that works for me. I've been heavily inspired by this solution which is for Drupal 6, so I've adapted it for Drupal 7 and it works for me:

(Nota: I give two hints in the code : (1) how to make a query that asks for all nodes that have no parent (join on `taxonomy_term_hierarchy` where `parent=0`) and (2) how to search form terms using `LIKE` statement):

```
/**
 * Implements hook_form_alter().
 */
function bcg_form_alter(&$form, &$form_state, $form_id) {
    if ($form['#form_id']=='views_exposed_form') {
        // override the original completion path which was:
        // 'admin/views/ajax/autocomplete/taxonomy/2'
        $form['term_node_tid_depth']['#autocomplete_path'] = 'admin/bcg/ajax/autocomplete/user';
    }
}

function bcg_menu() {
    $items = array();
    $items['admin/bcg/ajax/autocomplete/user'] = array(
        'page callback' => 'bcg_ajax_autocomplete_user',
        'access callback' => 'user_access',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
    );
    return $items;
}

/**
 * bcg_ajax_autocomplete_user makes specific autocompletion
 */
function bcg_ajax_autocomplete_user($ajax_search = '') {
    $result = array();
    $vocabularies = taxonomy_get_vocabularies();
    foreach ($vocabularies as $obj) {
        if ($obj->name == 'MY_OWN_VOCABULARY') {
            $vid=$obj->vid;
            break;
        }
    }
    if (isset($vid)) {
        $results = db_query(
            'SELECT td.name ' .
            'FROM taxonomy_term_data td ' .
            'JOIN taxonomy_term_hierarchy th ' .
            'ON th.tid=td.tid ' .
            'AND th.parent=0 ' .
            'WHERE (' .
                ' td.name LIKE :name ' .
                'OR ' .
                ' td.description LIKE :name ) ' .
            'ORDER BY 1',
            array(
                ':name' => '%'.$string.'%'
            )
        )->fetchAll();
        foreach ($results as $obj) {
            $result[$obj->name] = $obj->name;
        }
    }
    drupal_json_output($result);
}

```

# Answer
> 0 votes
> Yes, subterms are children of main terms (or you may say main terms are parents of subterms, and the parents of main terms == 0 (in other words, main terms have no parents))

You just use hook\_form\_alter and target your exposed filter.

Use a DB query or taxonomy\_get\_tree (using like `parent=0` and `depth=1`) to get just your `main` terms TIDs.

`unset()` all term value TIDs in the view exposed filter FAPI `#options` that are not found in your list of `$tree` items.

# Answer
> 0 votes
Other than the hook\_form\_alter solution already described, there is the Hierarchical select module on drupal.org. The module has a pretty comprehensive demo page, so have a look at the second "Taxonomy" tab on its demo page to see its functionality.

Now here's the bad news: Unfortunately, it doesn't integrate with views yet! The hierarchical select is still only available on the node edit and node create forms for tagging. The integration with views is still on its to-do list and active and you can follow that ticket here (I'm following it myself!).

What I've found is this thread of work-arounds until the much needed feature is released: http://drupal.org/node/1758844. Includes javascript solutions, as well as somebody who has posted a module for sale for $20 with that functionality...

Just throwing those workarounds in the mix for you, in case they're helpful!

---
Tags: views
---


# Question
Title: "Notice: Undefined index: und in include()"
Since this morning, I get this message on my website.

It says the error is on line 7 in my template file, but when I look at the line 7 the code on it is `<?php if (!$page): ?>`.

My template file looks like the following.

```
<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?>">
  <div class="node-inner">
    <?php if (!$page): ?>
      <h2<?php print $title_attributes; ?>>
      <?php if (($type == "article") && ($node->field_add_taxonomy_tag_articles[$node->language][0]['tid'] == 26)): ?>
        <a href="/discoveries#node-<?php print $node->nid; ?>"><?php print $title; ?></a></h2>
      <?php else:?>
        <a href="<?php print $node_url; ?>"><?php print $title; ?></a></h2>
      <?php endif; ?>
    <?php endif; ?>
    <?php print $user_picture; ?>
    <?php if ($display_submitted): ?>
      <span class="submitted"><?php print $date; ?> Ñ <?php print $name; ?></span>
    <?php endif; ?>
    <div class="content">
      <?php
        hide($content['comments']);
        hide($content['links']);
        print render($content);
      ?>
      <?php if (!empty($content['links'])): ?>
        <span class="links">
          <?php print render($content['links']); ?>
        </span>
      <?php endif; ?>
    </div>
    <?php if (!empty($content['links']['terms'])): ?>
      <div class="terms">
        <?php print render($content['links']['terms']); ?>
      </div>
    <?php endif;?>
  </div> <!-- /node-inner -->
</div> <!-- /node-->
<?php print render($content['comments']); ?>'

```

# Answer
The line that is causing that error message is the following one.

```
<?php if (($type == "article") && ($node->field_add_taxonomy_tag_articles[$node->language][0]['tid'] == 26)): ?>

```

`'und'` is the value for the constant LANGUAGE\_NONE, which is used for `$node->language`, when the node is language-neutral.

When you want to obtain the value of a field, you should use field\_get\_items(), as in the following code.

```
<?php $items = field_get_items('node', $node, 'field_add_taxonomy_tag_articles'); ?>
<?php if (($type == "article") && ($items[0]['tid'] == 26)): ?>

```
> 5 votes

---
Tags: theming
---


title: Conditionally expose filter

text:
# Question
Title: Conditionally expose filter
I have a view for which I want to expose a filter only to users with certain roles and/or permissions. For users without, I do not want them to be able to use this exposed filter. The documentation for hook\_views\_pre\_render() isn't clear on whether it can be used to modify exposed filters. How would I go about conditionally hiding/removing an exposed filter in code?

# Answer
I would make a view with your base settings, and then make two displays: one with the exposed filter, and then one without. Then use your normal access control methods to show the proper display at the proper setting.

For example, if you use views-as-blocks, add visibility rules. If you use panels, use a new page variant w/ access settings, or add access settings to the content pane.

Otherwise, your best option is to implement the view hooks and experiment. See what `$view` looks like with the exposed filter and without. Add your logic, and make the one look like the other. Unfortunately, what you can do in view hooks is rather sparsely documented; I always tackle this through trial and error.
> 3 votes

# Answer
Here's what I ended up doing (no guarantees about it being the best way, but it's up on drupal.org awaiting the maintainer's feedback):

For the filter in question I changed

```
$handler->display->display_options['filters']['status']['exposed'] = TRUE;

```

to

```
global $user;
if((in_array('administrator', $user->roles)) ||
    (user_access('view own unpublished content') == TRUE) ||
    (user_access('bypass node access') == TRUE)) {
  $handler->display->display_options['filters']['status']['exposed'] = TRUE;
} else {
  $handler->display->display_options['filters']['status']['exposed'] = FALSE;
}

```

Which exposes the filter in question if any one of the following three conditions are met:

1. The current user has role "administrator"
2. The current user has permission "view own unpublished content"
3. The current user has permission "bypass node access"

It would be better if Drupal had a "view unpublished content" blanket permission, or a "view unpublished \[foo\] content" for each node type, but in the absence of such controls, these three conditions seem like they would be adequate for the vast majority of use cases.
> 1 votes

---
Tags: users, views
---


# Question
Title: Configuring Drupal for Upstream Deployment
I'm trying to help a co-worker configure a Drupal site so that we can deploy the same site upstream without making database changes. We're having trouble with file paths. Here's what I have:

1. A Nginx webroot pointing to the root of my Drupal 7 (in this case) install (`/opt/frameworks/drupal-7`).
2. The content for this site is in `/opt/www/my-site`.
3. A symlink exists in `/opt/frameworks/drupal-7/sites`: `dev-my-site -> /opt/www/dev-my-site`

Because of some sharing that's going on, there are multiple versions of `my-site` on the box, so they have to have different symlink names. Right now, the "file system path" is set to `sites/dev-my-site/files` which breaks when moved upstream.

We're both inexperienced with Drupal and trying to help out a client. Upstream we get this:

```
Fatal error: require_once() [function.require]: Failed opening required '/opt/frameworks/drupal-7.15/sites/www.productionurl.com/modules/entity/includes/entity.inc' (include_path='.:/usr/share/php:/usr/share/pear') in /opt/frameworks/drupal-7.15/includes/bootstrap.inc on line 3084

```

At each point in the deployment process (dev, staging, production), the path will be slightly different. For example, `.../sites/dev.myclient.com/modules/...`, `.../sites/stg.myclient.com/modules/...` and `.../sites/myclient.com/modules/...`. When I deploy, what do I need to change to ensure that this works?

In Drupal 6, I was able to set the `file_directory_path` variable in `settings.php`, but that doesn't seem to be an option in Drupal 7. What's the alternative? Is there one?

# Answer
> 0 votes
This might be just a shorthand difference, but the include is looking for /drupal-7.15/ but you mention /drupal-7/ earlier in the post. Do you have two different versions of Drupal installed somehow, or is this all deployed from the same duplicate codebase and you're just trying to switch directories depending on the env?

---
Tags: 7
---


title: Modifying a Views 3 underlying query

text:
# Question
Title: Modifying a Views 3 underlying query
I have a View and it's based on a query and I'd like to modify the query that it is based on. What is the best way to do this?

More specifically, the query generated by Views is like this:

```
SELECT blah, blah, field-repeating-date, field-startdate, blah blah
FROM etc. etc.
WHERE this, that and the other
ORDER BY field-repeating-date ASC, field-startdate ASC

```

and I'd like the query to be:

```
SELECT blah, blah, IFNULL(field-repeating-date, field-startdate) AS thedate, blah blah
FROM etc. etc.
WHERE this, that and the other
ORDER BY thedate

```

in order to be able to mix the two date fields and have them sort properly. The modified query does what I want when entered through phpMyAdmin.

I'm using Drupal 7 with Views 3.

Edit: I did find a solution, but I can't post an answer for another 3 hours because I do not have a reputation here.

# Answer
A little googling and I found one solution, I'm not sure if it is the correct way to go.

I created a small module with one function, installed and enabled the module and it seems to work exactly as I need.

The mymodule.module file contains the following code:

```
function mymodule_views_query_alter(&$view, &$query) {
  // this is the name of our View and Display
  if ($view->name == 'upcoming' && $view->current_display == 'block') {
    // override the ordering
    // this is because the two different date fields are one or the other
    // but not both fields, so we coalesce.
    $query->orderby = array(
      array(
        'field' => 'COALESCE( field_data_field_repeatdate_field_repeatdate_value, field_data_field_startdate_field_startdate_value)',
        'direction' => 'ASC',
      )
    );
  }
}

```

This gets called in when needed and uses COALLESCE to on the sort order (
> 2 votes

# Answer
You can use hook\_views\_query\_alter

> This hook should be placed in MODULENAME.views.inc and it will be auto-loaded. MODULENAME.views.inc must be in the directory specified by the 'path' key returned by MODULENAME\_views\_api(), or the same directory as the .module file, if 'path' is unspecified.
>
> **Parameters**
>
> **$view:** The view object about to be processed.
>
> **$query:** An object describing the query.

Read Views hooks
> 0 votes

---
Tags: views
---


# Question
Title: How do I theme a block created with the Views module?
I'm Newbie user in drupal, i need to custom design theme block created for views module.

Example HTML:

```
<div id="content">
   <ul>
     <li>
        <div class="title">title1</div>
        <div class="thumbs"><img 1 ......></div>
        <div class="content">content1</div>
     </li>
     <li>
        <div class="title">title2</div>
        <div class="thumbs"><img 2 ......></div>
        <div class="content">content2</div>
     </li>
   </ul>
</div>

```

# Answer
> 0 votes
I'm not perfectly sure what you are asking...

If you want to theme a view then you can add a css class name under the advanced drop-down, or add a css class to any field.

Or are you looking to adjust how a block appears using views?

# Answer
> 0 votes
There are two options to choose from.

1. Use the native template suggestion system that Drupal provides for you. Check template information when editing your view.
2. Use a contributed module like Semantic Views which lets you customize the output of your view thoroughly from the back-end configuration.

---
Tags: views, 7, theming
---


# Question
Title: Why is it easily possible to theme node add forms and not node edit forms?
Why can i override:

`page--node--add--mycontenttype.tpl.php`

and not:

`page--node--edit--mycontenttype.tpl.php`

What is actually quite the same form?

# Answer
> 1 votes
Have you got the code in your template.php file set up correctly?

It should look like this:

```
function THEMENAME_theme($existing, $type, $theme, $path) {
    return array(
        'FORMNAME' => array(
           'arguments' => array('form' => NULL),
           'template' => 'page--node--add--mycontenttype.tpl.php',
          'render element' => 'form',
          ),

```

You can find FORMNAME, by viewing the source of the page and looking for the id of the form.

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


# Question
Title: What are the most appropriate system permissions for sites on shared hosting?
Although the Drupal site goes into great detail about permissions and security, there are only vague/unclear references to *shared* hosting. From a Drupal point of view, what is the most secure set-up (ownership and permission levels) for a site on shared hosting?

As an example of the kind of info I'm looking for, WordPress suggests the following shared hosting settings:

* All files should be owned by the actual user's account, not the user account used for the httpd process.
* Group ownership is irrelevant, unless there's specific group requirements for the web-server process permissions checking. This is not usually the case.
* All directories should be 755 or 750.
* All files should be 644 or 640. Exception: wp-config.php should be 600 to prevent other users on the server from reading it.
* No directories should ever be given 777, even upload directories. Since the php process is running as the owner of the files, it gets the owners permissions and can write to even a 755 directory.

# Answer
> 11 votes
**Hosting options**

Hosting options for a website site is generally one of the following:

* dedicated server
* virtual private server (VPS)
* shared hosting

With a dedicated server, only one site is hosted on a physical computer, and the configuration is as secure as the computer itself.

With a VPS, your software runs on the same physical computer as other users' virtual machines. However, it is functionally equivalent to a dedicated server. Most important, a VPS has the privacy and security of a dedicated server.

With shared hosting, your web site resides on a file system shared with other users. This, unfortunately, makes it less secure than when it is running on a dedicated server or VPS. The rest of this article discusses the security of a WCMS in shared hosting environment.

**Environment**

A shared hosting environment can be regarded as consisting of a web server, a file system, a settings file, a database, and some users.

In the following examples, it is assumed that the owner account is "tom", and that the settings file (holding database credentials) is named "settings.php".

The web server process may run with the user permissions of the owner account "tom", or with group permissions of the group "www", depending upon the configuration.

Also, a standard Gnu/Linux or Unix environment is assumed, and it is assumed that the reader understands the Unix access control system with separate read (r), write (w) and execute/access directory (x) permissions split into three blocks (user, group, other).

Before I go on to discuss specific settings, it may be helpful to list the conditions we want to satisfy:

1. For a web-site to be operational, the web server must have *read* access to all the files that make up the site, and access directory access to all the directories that make up the site.
2. For secure operation, web server must not have *write* access to any of the files it handles.
3. For secure operation, a web script run by a rogue user must not have *read* access to the files owned by another user.
4. For the owner to work on his own site using the CLI, the user must have *read* and *write* access to his own files.
5. To protect the files from being accessed by other users using the CLI, the "other" block should have *no* permissions set.

Unfortunately, on a shared host, you can only have 4 out of 5. I know of no way you can satisfy *all* five conditions on a shared host.

As far as I know, two different configurations are used by shared host providers. Both are discussed below, along with the permissions to use to best protect files and directories, and what condition the configuration fails to satisfy.

**Config 1: Web server is running as owner**

This is AFAIK the most widely used configuration. The web server is running as owner of the files. This means that a rogue user cannot use his web server user to run a script to read another user's files. This type of configuration also protects users from each other in the CLI.

However, it also means that we can't have separate permissions for the owner and the web server. To satisfy condition 2 with this type of setup, you need to restrict write permissions for the owner in order to prevent write access for the web server to everything except the upload directory.

Permissions:

```
Directories:  500 r-x --- --- tom.tom
Files:        400 r-- --- --- tom.tom
settings.php: 400 r-- --- --- tom.tom
Upload Dir.:  700 rwx --- --- tom.tom

```

Unfortunately, this means that condition 4 cannot be satisfied. I.e. the site cannot be maintained through the CLI. The owner will be constrained to use some sort of web-based dashboard to access the site (my recommendation is that the owner maintains a copy on some staging server where he has unrestricted access, and mirror changes made on the staging server to the shared host).

**Config 2: Web server is running as a member of the www group**

This configuration is used by some (IMHO) less professional providers of a shared host solution. The web server is running as a member of the www group, and is given the required read access through the group block:

Permissions:

```
Directories:  750 rwx r-x --- tom.www
Files:        640 rw- r-- --- tom.www
settings.php: 640 rw- r-- --- tom.www
Upload Dir.:  770 rwx rwx --- tom.www

```

These settings have the advantage of giving the owner full access to his files through the CLI, and restricts the web server to read access only.

However, it also fails to satisfy condition 3. I.e. it allows a rogue user on the shared host (or a hacker that as compromised the site of another user sharing the host) to run a script to read *any* file that can be read by the web server. This gives the rogue script access to the file settings.php with the database credentials, which makes it trivial to completely take over the site.

My recommendation is to avoid this type of configuration.

**Addendum: How dangerous is it to use a shared host?**

I certainly would not put anything sensitive, such as credit card numbers or medical records, on a shared host. But shared hosting is cheap, and there is an attraction in that. I use shared hosting myself for several of my sites. I haven't been hacked yet, but I know that the risk exists and I am prepared for the day when it happens. If I am hacked, I will simply delete *everything* on the shared host, and reinstall the site from a mirror copy I keep on a secure staging server.

With "config 2", the main problem is the *others*. If some *other* website that you share the host with gets compromised, your website is also lunch. Making security depend upon another party you don't know and have no control over is not a good idea. This is why my recommendation is to avoid "config 2"-type hosting arrangements.

With "config 1", you alone control your web site's security. This is better (in particular if you know what you're doing). But it is not fool-proof. Nobody's perfect, and if you goof up and your site is compromised, the attacker will have access to *every* file stored on that host that belongs to you. In other words, to minimize the damange when you're hacked, do not keep *anything* on that host that will cause harm if someone else gains access to it. In particular, do *not* keep your email on that shared host. There is usually tons of sensitive data in email, so you do not want it anywhere near a web server executing as "you".

And if your web applicaton is handling sensitive data, make sure your budget allows for a dedicated host or a VPS.

You may also want to see this guide to Securing file permissions and ownership at Drupal.org.

---
Tags: files
---


# Question
Title: Upload file and fill in fields in one step; or trigger a rule when a file is uploaded
I want to make use of the Media module and the File entity module to upload files, in particular images, to my site without having to attach them to a node. Solely uploading images works like a charm, as the Media module automatically places an "add file" link within the navigation menu.

I also added a couple of fields to my image file type. Unfortunately, the Media module doesn't allow me to choose the image file and fill in the fields at the same time, and then submit. Instead, I have to upload the file, go back to the file, click on edit and fill in the fields **afterwards**, which in my opinion is pretty annoying.

I am not sure if this issue can be resolved somehow. If it can *not* be, this could be a workaround:

When I upload a file, a rule is triggered that sends me to the edit page. This way uploading the image and filling in the fields somewhat forms a unit.

However, the Rules module does not offer to react on file uploads.

Does anyone have an idea how to get around this issue?

# Answer
So I believe that uploading and editing files works correctly with the latest dev release of the media module when using a file field or image field.

Like you said when you go to file/add it is using the file\_entity module which I believe they are discussing adding upload and editing here http://drupal.org/node/1553114.
> 0 votes

# Answer
You could also try the File Entity Inline module, which allows you to inline edit the files after they are uploaded.

Here is a quote about it (from the module's project page):

> ... aims to provide the ability to edit File entities inline, as part of another form (such as nodes). This should enable the ability for reusable and site-wide editing of file properties, such as description, alt text, captions, bylines, etc.
>
> Configuration is on a per-field basis. So to configure this module, you must visit the "Manage Fields" tab for your content type (or taxonomy terms, comments, etc.) By default, all fields on all file types are displayed. If you want to make things like "description" and "alt text" global instead of per-usage, you should disable the built-in description and alt text fields and use those provided by a file type instead.
> 0 votes

---
Tags: 7, entities, rules, files, media
---


# Question
Title: Remove menu item in template.php drupal 7
After quite a bit of googling I'm asking here which `theme_*` function I use to remove a menu item.

I already use `theme_menu_link` to alter 2 of the menu items in this menu but I want this one to dissapear completely.

Wasn't there a field I could add to the array that would hide it or am I thinking of something else?

# Answer
> -2 votes
I think you're looking for:

```
$element['hidden'] = 1;

```

Using: http://api.drupal.org/api/drupal/includes%21menu.inc/function/theme\_menu\_link/7

check that it's the element you want, and set the "hidden" value to 1. I have not tested this.

---
Tags: routes, theming
---


title: Access Damp over LAN

text:
# Question
Title: Access Damp over LAN
I have installed Drupal. I followed a tutorial in Lynda.com that uses Acquia Dev Desktop, and then the core Drupal inside. (http://www.lynda.com/tutorials/73655-2.html)

I'm not sure if it is the best way to install Drupal. Anyway, it works. But now I need to access to the web from another laptop that is in another room. I can't.

When I see the web in the original mac, I have: `http://nameofproject:8082/`

From a second mac, to access to the Drupal web installed, I tried and it doesn't work:

* `http://IPnumber:8082/`(This drives me to the generic Acquia Drupal site)
* `http://IPnumber:8082/nameofproject`
* `http://IPnumber/nameofproject:8082/`
* `http://IPnumber/nameofproject/`

# Answer
If you have a web server installed on your local network, and you type the IP address in the URL (e.g. IPaddress:port/nameofproject), you should get your Drupal site.
The fact that when you just type the IP, and the port you get the default server page means that your router settings are already working.
> 1 votes

# Answer
I got it to work by adding to the host file.

My mac has Acquia Dev Desktop installed. I'm trying to access the site "example:8082" on a Windows 7 virtual machine.

I go to the virtual machine and edit the host file like this: 10.10.17.111 example

Then to access this from the Windows 7 browser, go to "http://example:8082"

Bingo, it works!
> 0 votes

---
Tags: installation
---


# Question
Title: Collapsiblock module - can I have horizontal expanding tabs instead of vertical?
Collapsiblock: http://drupal.org/project/collapsiblock

I am looking for a way to allow the sidebar blocks to be collapsible left-to-right instead of top-to-bottom using the Collapsiblock module. It would basically be a way to hide the left and right-column blocks until someone clicks the tab, after which the block would expand to the width of the column. It seems as though it should be a fairly straightforward change in the JS file, but I cannot figure it out. Can anyone here provide any insight into this?

Thanks!

# Answer
> 2 votes
Search `slideUp` and `slideDown` in `collapsiblock.js`and replace with `animate`, for example:

```
$(this.target).animate({width:'toggle'},slidespeed);

```

Useful post: Slide Elements in Different Directions

---
Tags: blocks
---


# Question
Title: Searching through nodes and outputting the details on gmap
I have a gmap that is displaying all the information of real estate listings that I put in.

Now I want a text search that basically searches through the nodes and outputs the information in the same map and filter it basically.

So if I search for 2 bedroom in Boston in a simple text search. (Hopefully the search will have auto complete)

It will only show me the two bedrooms in boston I selected. (Boston is a node type) not part of gmap.

Basically I need a text search to filter the map listings which I dropped on it.

I don't want spatial searching.

Help!

# Answer
> 2 votes
Does it have to be a search box? If not, use GMAP's Views integration and create exposed filters for the fields you want to filter by. Instead of a search box, use a dropdown for bedrooms, city, and whatever other filterable fields you include.

Using a text input/search box may cause usability issues. You can't account for the variety of keywords a user may input, nor will you be able to filter appropriately for unknown terms. Giving the user defined filters (which they are familiar with) will be much easier for them to understand and use.

Better Exposed Filters may come in handy here depending on what type of filters you use -\> http://drupal.org/project/better\_exposed\_filters

---
Tags: location, google-maps
---


# Question
Title: How do you create a view in which users can assign tasks to themselves?
**What I want to do.**

* A user clicks on his profile page.
* A view displays that shows a list of completed tasks.
* A task consists of a list of check-boxes (a checklist) and a "pending and finished" dropdown.
* The user should also be able to create a task for himself, selected from a list of checklists.

**This is my solution so far**

* Create a content type "checklists"
* create a role reference field
* create the checkbox field
* create a view with CONTEXTUAL FILTERS to show the tasks assigned to the user

**Ive also tried a few modules**

* checklist
* QA Checklist
* SEO Checklist

*But they dont seem to have the features i want.*

Am i going in the right direction?

> Flags also looks promising - It looks like you can create a flag(button:create task) and then use actions or rules to create the node and reference the user automatically

# Answer
> 0 votes
**Finally got something right.**

Its actually quite easy, you can do it with just views and one module

1. Install http://drupal.org/project/userreference\_url
2. Create a field "User reference" with widget "Reference from URL"
3. Create a view to display nodes with relationship to user.
4. Enable the button to create referenced node in the module.

# Answer
> 0 votes
Please go through the following modules,

To do list for Drupal 6 only

> Offers a content-type for a simple To do list. It can be used for anything that needs to be done: getting milk at the store, reminding yourself to update a profile, telling your users to vote on a poll by a certain date...

and myTinyTodo \- Available for D6 & D7

> A simple way to manage your todo list. This module is based on myTinyTodo.

Otherwise you can do the same system with your current approach

---
Tags: users, nodes, forms
---


# Question
Title: How do I show only 3 of the latest posts for each term in a view?
With the help of another question: Show newest nodes for each taxonomy term in Views I have been able to create the view I require, except that it displays all posts for each term (grouped by term)? How do I limit each term to display only 3 of their latest posts.

e.g.

Term 1
\- Post 1
\- Post 2
\- Post 3

Term 2
\- Post 1
\- Post 2
\- Post 3

Term 3
\- Post 1
\- Post 2
\- Post 3

# Answer
> 9 votes
If you need only one node you can use “Representative node” relationship. But if you need three nodes per each term, use something like Views Field View.

1) Create "child" view for content. Something like this:

Add taxonomy term argument, pager limits, sorting and etc:

Now you can attach this view to another one.

2) Create taxonomy view:

Add hidden term ID field and then add “Global: View” field:

Don't forget to configure caching. From Views Field View page:

> It's highly recommended to use this module in conjunction with views caching. Views Content cache and Cache Actions are good ways of caching views.

# Answer
> 7 votes
Upon further investigation, it seems like Peek Summary might be exactly what you want. The screenshots on the documentation are for Drupal 6, and it's slightly different in Drupal 7, so I've attached some updated screenshots.

* Choose Peek Summary from 'Contextual Filters' \> 'When the filter value is not in the URL' \> 'Display a summary' \> 'Format'

* You'll see a view of sub-views. Click on the gear next to the pager for the group you'd like to limit.

* Enter the max items to display on the pager options.

~~You'll have to edit the pager for each and every group you'd like to limit, which is unfortunate.~~ When you edit the pager for one group, it changes the settings for all groups. If you want to display a number of nodes per group different than the total number of groups, override that in the 'Format' settings under 'Contextual Filters' (on first screenshot in purple).

It has the disadvantage of essentially creating \[n\] views for \[n\] groupings, which could be a performance issue depending on how many groupings you have, but it does limit the query to only the number set to display. This could improve your performance, depending on your use case. As always, cache responsibly.

# Answer
> 2 votes
A way to limit this in code would be to add something like the following to a custom module:

```
function custom_views_pre_render(&$view) {
  //get the rows from the view just before render
  $results = $view->result;
  //create a counter
  $count = '';
  //we're going to built up a new $result array
  $new_results = array();
  //iterate through each view row
  foreach($results as $result) {
    //find the taxonomy term
    $term = $result->taxonomy_term_data_name;
    //add the term to a string of all the terms we've seen so far
    $count .= $term;
    //make sure to separate them with spaces to make them easier to count
    $count .= ' ' ;
    //count how many rows have the same term as the current one
    $term_count = array_count_values(str_word_count($count, 1));

    if($term_count[$term] <= 3){
      //if this is the third or fewer row with this term, add it to the new result array
      $new_results[] = $result;
    }
  }
  //instead of the normal view output, only show the results we put in our array.
  $view->result = $new_results;
}

```

This is for a view of taxonomy terms that is connected to nodes via a relationship. If you just have a view of nodes, your mileage may vary.

Though it prevents the display of more than 3 per term, this will not prevent the query from returning all the results for each term, so it doesn't improve SQL performance at all. If you have a very large number of results for each term, making separate view panel displays and putting them all in one region using something like CTools Page Manager so you're not running huge queries.

As always, you're going to want to cache this stuff on production.

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


title: drupal and ndb cluster engines

text:
# Question
Title: drupal and ndb cluster engines
we have an application which was built with drupal connecting to a mysql db. upon go-live we found that the production db is a clustered one and requires us to change our db tables to NDB cluster engines.

Is drupal capable of working with clustered db's and how do we do this?

# Answer
> 1 votes
# OBSERVATIONS

If is straightforwards to convert MyISAM to InnoDB, such as with the following:

```
ALTER TABLE node ENGINE=InnoDB;

```

Not so with **NDB**. For the table `node`, let's take the following approach:

```
mysqldump -u... -p... dbname --no-create-info node > node_data.sql

```

Then, load the table into the NDB Cluster

```
mysql -u... -p... -Ddbname -A < node_data.sql

```

and you let all the management nodes and SQL nodes determine where to store/shard the data.

If and only if you have the patience to

* upgrade Drupal
* avoid using FULLTEXT indexes (currently not supported by NDB)
* apply plugins
    + drop FULLTEXT indexes
    + convert any MyISAM tables to NDB
* migrate/reload data

then it is worth a shot.

Please post NDB Cluster questions in the DBA StackExchange.

DISCLAIMER : Not Drupal Expert, Not CMCDBA (not Cluster Certified), just CMDBA

---
Tags: database
---


title: Rated user interests

text:
# Question
Title: Rated user interests
I would like to create rated inteterests for each user. Until now what I have is a taxonomy term vocabulary defined and a field in the user account attached to this vocabulary. Until here what a user can do is to check or not each term of the vocabulary, using the widget options\_list. What I would like to do is to let the user select the level (0-10) of preference for each term.

I've tried to create a custom field with two columns, tid and value, then linking each tid with taxonomy term in hook\_field\_widget\_form, but no luck as I'm not an expert in fields, so I'm confused about how to implement:

```
/**
 * Implements hook_field_widget_form().
 */
function taxonomy_value_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $tids = isset($items[$delta]['tid']) ? $items[$delta]['tid'] : array();
  $values = isset($items[$delta]['value']) ? $items[$delta]['value'] : array();
  $element += array(
    '#delta' => $delta,
  );

  switch ($instance['widget']['type']) {

    case 'taxonomy_value_widget':
      if ($vocabulary = taxonomy_vocabulary_machine_name_load('tags')) {
        if ($terms = taxonomy_get_tree($vocabulary->vid)) {
          foreach ($terms as $term) {
            if ($term->depth == 0) {
              $element[$term->tid] = array(
                '#markup'  => '</br><strong>' . $term->name . '</strong>',
              );
            } else {
              $element[$term->tid]['term'] = array(
                '#markup'  => '</br>' . $term->name,
              );

              $element[$term->tid]['tid'] = array(
                '#type'          => 'value',
                '#value'         => $term->tid,
              );

              $element[$term->tid]['value'] = array(
                '#type'          => 'textfield',
                '#value'         => in_array($term->tid, $values) ? $values[$term->tid] : 5,
              );

            }
          }
        }
      }

      break;
  }

  return $element;
}

```

# Answer
> 0 votes
The problem was with values: they had to be trasposed. This solution uses transfer\_slider from jquery.

```
/**
 * Implements hook_field_widget_form().
 */
function taxonomy_value_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $values = taxonomy_value_traspose_values($items);
  $element += array(
    '#delta' => $delta,
  );

  switch ($instance['widget']['type']) {

    case 'taxonomy_value_widget':

      if ($vocabulary = taxonomy_vocabulary_machine_name_load('tags')) {
        if ($terms = taxonomy_get_tree($vocabulary->vid)) {
          foreach ($terms as $term) {
            if ($term->depth == 0) {
              $element[$term->tid] = array(
                '#markup'  => '</br><strong>' . $term->name . '</strong>',
              );
            } else {
              $element[$term->tid]['term'] = array(
                '#markup'  => '<span class="taxonomy_value-taxonomy-string">' .  $term->name . '</span>',
              );

              $element[$term->tid]['tid'] = array(
                '#type'          => 'value',
                '#value'         => $term->tid,
              );

              $element[$term->tid]['slidervalue'] = array(
                '#type'          => 'transfer_slider',
                '#title'         => '',
                '#left_value'    => array_key_exists($term->tid, $values) ? $values[$term->tid] : 5,
                '#right_value'   => array_key_exists($term->tid, $values) ? 10 - $values[$term->tid] : 5,
                '#left'          => '',
                '#right'         => '',
              );

              // Tengo que hacerlo así ya que transfer_slider está diseñado para tener 2 textfields. Este campo lo actualizo en presave.
              $element[$term->tid]['value'] = array(
                '#type'          => 'value',
                '#value'         => array_key_exists($term->tid, $values) ? $values[$term->tid] : 5
              );
            }
          }
        }
      }

      break;
  }

  return $element;
}

/**
 * Dado un array 'delta' => ('tid' => X, 'value' => Y), devuelve un array associativo 'X' => Y.
 * @param unknown_type $items
 */
function taxonomy_value_traspose_values($items) {
  $values = array();
  foreach ($items as $item) {
    $values[$item['tid']] = $item['value'];
  }

  return $values;
}

```

# Answer
> 0 votes
what not using Field Collection ?

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


# Question
Title: How can you add a multiple value field to an entity?
**Edit:** My question is similar to How to create multi-value, multi-bundle entity reference fields in code?, except the field doesn't need to reference multiple bundles.

We have an existing view of custom entities. The view needs to now be filtered based on some related fields that are not part of the entity (or any entity). **Kind of like adding a Taxonomy Reference field to a Content Type.** What is the best way to add those fields to the entity?

I see that many modules use attachLoad to attach fields to an entity, but when I try my implementation those fields don't show up in my list of Fields or Filters in Views.

This is a screenshot of the checkboxes field:

This is my controller:

```
class ContactsController extends EntityAPIController {

  public function attachLoad(&$queried_entities, $revision_id = FALSE)
  {
    foreach ($queried_entities as $key => $entity)
    {
      $queried_entities[$key]->foo = "bar";
    }
    parent::attachLoad($queried_entities, $revision_id);
  }

}

```

And this is my hook\_entity\_info:

```
function contacts_entity_info() {
  $return = array(
    'contacts' => array(
      'label' => t('Contact'),
      'entity class' => 'Contacts',
      'controller class' => 'ContactsController',
      'views controller class' => 'ContactsViewsController',
      'base table' => 'contacts',
      'fieldable' => TRUE,
      'entity keys' => array(
        'id' => 'ckid',
        'bundle' => array(),
      ),
      'bundle keys' => array(),
      'bundles' => array(),
      'load hook' => 'contacts_load',
      'view modes' => array(
        'full' => array(
          'label' => t('Default'),
          'custom settings' => FALSE,
        ),
      ),
      'label callback' => 'entity_class_label',
      'uri callback' => 'entity_class_uri',
      'module' => 'contacts',
      'access callback' => 'contacts_access',
    ),
  );

  return $return;
}

```

This is a suggested implementation of EntityDefaultViewsController:

```
/**
* EntityTest Views Controller class.
*/
class ContactsViewsController extends EntityDefaultViewsController {

  /**
   * Add extra fields to views_data().
   */
  public function views_data() {
    $data = parent::views_data();

    // Add your custom data here
    $data['contacts_topics']['table'] = array(
      'group' => t('Contacts Topics'),
      'base' => array(
        'field' => 'ckid',
        'title' => t('Contacts Topics'),
      ),
      'join' => array(
        'contacts' => array(
          'left_field' => 'ckid',
          'field' => 'ckid',
        ),
      ),
    );

    $data['contacts_topics'] = array(
      'ckid' => array(
        'title' => 'Contact Entity ID',
        'field' => array(
          'handler' => 'views_handler_field_numeric',
          'click sortable' => TRUE,
        ),
        'sort' => array(
          'handler' => 'views_handler_sort',
        ),
        'filter' => array(
          'handler' => 'views_handler_filter_numeric',
        ),
        'relationship' => array(
          'base' => 'contacts',
          'base field' => 'ckid',
          'handler' => 'views_handler_relationship',
          'label' => t('Contact entity relationship'),
          'title' => t('Conact entity relationship'),
        ),
      ),
    );

    return $data;
  }
}

```

Unfortunately I don't see anything in the Views SQL that shows that any of these attempts to add the fields or join the topics table to the contacts table are working.

# Answer
> 3 votes
How to attach a field to an entity programically solved this problem for me. It's not an exact duplicate, but the answer and the comments pointed me to the right direction.

So this code creates the field and the instance and it attaches it to the entity very nicely:

```
function contacts_enable()
{
  if (!field_info_field('related_topics'))
  {
    $field = array(
      'field_name' => 'related_topics',
      'type' => 'list_text',
      'cardinality' => -1,
      'settings' => array(
        'allowed_values_function' => '_contacts_get_related_topics',
      ),
    );

    field_create_field($field);

    $instance = array(
      'field_name' => 'related_topics',
      'entity_type' => 'contacts',
      'label' => 'Related Topics',
      'bundle' => 'contacts',
      'default_value' => NULL,
      'settings' => array(
        'user_register_form' => FALSE,
      ),
      'widget' => array(
        'active' => 1,
        'module' => 'options',
        'settings' => array(),
        'type' => 'options_buttons',
        'weight' => -1,
      ),
    );

    field_create_instance($instance);
  }
}

```

---
Tags: 7, views, entities
---


# Question
Title: Inserting div wrappers - changing hierarchy of the html
I have placed a number of blocks in my Main Section of the site. I have finished all the standard styling for the site, but now that I've moved on to the mobile/phone layouts, I find that I need more control over this list of blocks - I need to wrap some of these blocks so as to position them properly.

Image: http://i720.photobucket.com/albums/ww203/Nongolf/divhierarchy.jpg

I have looked at CCS Injector (which would be more aptly named 'CSS Adder'), and moving blocks for mobile browsers, but far as I can tell I can only move all blocks or none at all.

I really do not want to change the default sections for the blocks now, as the styles are all in place and would be largely ruined by moving them to another section.

So now I'm about to use some jQuery magic to strong-arm the html. But before I do so I wanted to ask you good people if there's another way?

# Answer
Completely forgot to return and give my solution. This is it:

```
jQuery(document).ready(function() {
    my_selection = [];
    my_selection.push(['#block-views-dyn-box-1-slider-block']);
    my_selection.push(['#block-views-dyn-box-2-slider-block']);
    my_selection.push(['#block-views-dyn-box-3-slider-block']);
    my_selection.push(['#block-views-dyn-box-4-slider-block']);
    my_selection.push(['#block-views-static-boxes-test-block']);
    jQuery( my_selection.join(',')).wrapAll('<div class="dyn-box-wrap"></div>');
});

```

I'm little more than a jquery novice, so I'm sure there are more efficient ways, but this worked just fine for me.
> 0 votes

---
Tags: blocks, theming
---


# Question
Title: Creating nodes and sub-nodes from database table
For example I have a database table defined from the following SQL.

```
CREATE TABLE IF NOT EXISTS `mytable` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `base_id` int(11) NOT NULL,
  `page_type` smallint(4) NOT NULL,
  `page_title` varchar(50) NOT NULL,
  `page_content` text NOT NULL,
  `previous_id` int(11) NOT NULL,
  `next_positive_id` int(11) NOT NULL,
  `next_negative_id` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;

```

I need to create nodes/content by using records inside that table. For example I have a base node, its id is 1. I get its title and its content from mytable. Inside this page I ask a question: "Do you like cats?" If the user selects yes, I send him to sub-node. I get sub-node address, title and content from mytable. You can see the flow like the below. Until the latest sub-node I give options to user. He selects YES or NO and sees relevant content/sub-node.

How can I make it with a Drupal 7 site?
I have another Drupal website but I have never used such complex flow. I created nodes and used contributed modules. Is it so hard to make this flow? Which modules should I use to setup such hierarchy and content management?

# Answer
> 4 votes
One solution would be to create a new content-type, let's call it `Question-Page` and the install Entity Reference, which provides a field type that can reference other nodes. Then you could add three new fields for `previous_id`, `next_positive_id` and `next_negative_id`.

To import the data from your table I think you could use the Feeds module. First create one importer that will create the actual nodes. Second an importer that will update each node and set the node reference fields.

1. First importer that will only create all nodes.

2. Second importer, that will setup the reference fields.

---
Tags: nodes
---


# Question
Title: So I've installed FirebugForDrupal (updated)
I installed the browser plug in and module in drupal. On this (development environment) I gave authenticated users access to the 'Access Firebug Debug' permission. Site Admin has access to that and 'Execute Firebug PHP'.

Browser/Client

* Firefox 17.0.1
* Ubuntu 11.10
* Firebug 1.11.0
* DrupalForFirebug ~~0.0.8~~ 2.0
* Logged in as User 1

Server (development box)

* Drupal 6.25
* Redhat 5.8
* PHP 5.3.3

## **UPDATE:**

Just this morning DfFB released it's 2.0 version. I spun up the DfFB module again, ran cron, and cleared cache. In the source code of my page, I can now see `<div>`'s with class names such as `drupalforfirebug_general` and `drupalforfirebug_sql`. So it appears that information is binging handed to the browser from Drupal.

## **UPDATE 2:**

I switched to DfFB 2.0a and this what I see.

Is this what I'm supposed to see?

# Answer
> 2 votes
The Drupal variable/object you have in the pic could be had by just typing `console.log(Drupal)` on the console tab in FireBug. It's the Drupal JavaScript object that's recommended to be extended. eg if you run `console.log(Drupal.behaviors)` you'll see all the JavaScript functions that get called by Drupal on page load.

Anything specific you're trying to debug?

Just to make sure you've seen:

http://drupal.org/project/devel

http://drupal.org/project/devel\_themer

http://drupal.org/project/search\_krumo

# Answer
> 4 votes
It seems the extension is not compatible with Firefox 14. The issue report has been opened on July 19, 2012, and it still is open.

The last comments from one of the co-maintainers of the module say:

> unfourtunatly no, currently the new (from the ground up) plugin registers itself with firebug and firefox; it displays the drupal tabs and subtabs. But it doesn't gather the data from the drupalforfirebug drupal module yet.
>
> Once it is ready I will package it as an xpi and allow it to be downloaded from bitbucket while mozilla reviews the update. I should be done sometime this week.

> So now the code on bitbucket is functional. I wouldn't call it testable -- still hanging around pre-alpha.
>
> Before I we call it testable I need to do two things.
>
> 1. Further abstract the connection between the Drupal Module and the Firefox Module. Right now the presentation layer calls the connector that returns the content directly. However, once I abstract that connection to an API call layer then changes to the API will be less problematic for Firefox plugin to deal with.
> 2. Remove the dependency on jQuery for the plugin. Currently the plugin loads jQuery to deal with a couple of UI niceties.\<-- this is what is blocking the release.
>
> By all means though, If you know how to install from code a firefox plugin then please do so. It works just like the old one for the time being.

---
Tags: debugging
---


# Question
Title: Record video clip from webcam in Drupal 7 custom module
I want to capture the video clip from webcam in my own Drupal 7 custom module. Is there any way to capture the webcam and record the video clips in Drupal 7? Please, anyone can help me on this?

Thanks in advance.

# Answer
> 3 votes
There is Media: Webcam

> This project (still under active development) will add a Webcam capture tool for video and images to FileField. Video requires a Red5 or Flash Media server to also be available; documentation for this coming soon enough.

Browse the `SOURCE` to get some inspiration.

---
Tags: files
---


# Question
Title: How to handle pdo exception error gracefully for user experience
Integer fileds can accidentally be entered with 'Out of range' error. This time a user has no other option but to click back button. Any suggestions on templating these kinds of errors or for any other errors of the same nature?

# Answer
> 0 votes
What? ... add a custom FAPI validator to your forms so there is no out-of-range error.

You could build on, or start off by using: http://api.drupal.org/api/drupal/includes%21form.inc/function/element\_validate\_integer/7

---
Tags: 7, entities
---


# Question
Title: Is there a way to do concurrent editing?
Is there a MediaWiki-like method for supporting concurrent editing of text bodies in Drupal 7?

If no feature currently exists, what are some decent PHP diff libraries that could be wrapped up by a Drupal module that could do the job?

# Answer
You can use etherpad kind of feature which allows you to do concurrent edit of node body.

Etherpad is collaborative editor by which you can write any node field using concurrent editing. Check Readme.txt for installation purpose.

And one more thing if you have no permission to install etherpad on your server(as shared hosting will not allow it) then you can use Piratepad module, which allows you to embed the pad using iframe from piratepad site.
> 11 votes

---
Tags: 7
---


title: Template suggestions not recognized

text:
# Question
Title: Template suggestions not recognized
I have just introduced my custom template suggestions in `MYTHEME_preprocess_node`, based on a certain field's value. Won't work somehow.

The content type is `project`. In my template folder I have already a file named `node--project.tpl.php`, and my suggestions append additional two: `node--project--pcgame.tpl.php` and `node--project--movie.tpl.php`. They are visible when I `dpm()` the variables, but are not found/applied to the node, even when I remove `node--project.tpl.php`.

Cache cleared.

Any clue as per what could be the cause?

---

The code I'm using:

```
function MYTHEME_preprocess_node($variables){
  if(isset($variables['node'])){
    $node = $variables['node'];
    if($node->type == 'project'){
      // Determine project type based on a term field.
      $project_type = (int) $node->field_genre['und'][0]['tid'];

      switch($project_type){
        case 4:
          $variables['theme_hook_suggestions'][] = 'node__project__pcgame';
          break;
        default:
          $variables['theme_hook_suggestions'][] = 'node__project__movie';
      }
      dpm($variables['theme_hook_suggestions']);
      }
   }
}

```

# Answer
> 0 votes
You try this code.

```
 function youthemename_preprocess_node(&$variables) {
 $node = $variables['node'];
    if($node->type == 'project'){
      // Determine project type based on a term field.
      $project_type = $node->field_genre['und'][0]['tid'];

      switch($project_type){
        case 4:
          $variables['theme_hook_suggestions'][] = 'node__project_pcgame';
          break;
        default:
          $variables['theme_hook_suggestions'][] = 'node__project_movie';
      }
    }
}

```

You file name should be node--project\_pcgame.tpl.php and node--project\_movie.tpl.php. Clear performance cache, it should call `hook_theme_registry_alter(&$theme_registry).`

---
Tags: theming
---


# Question
Title: Date API: Proper method of parsing dates
I'm working on a simple event sign up module. The functionality is split in two modules, one which provides an Event content type with title, description and date (from - to) fields, and the second with sign up functionality and sign up window dates for Event content type. The problem is that I don't seem to find a way to properly parse and do comparisons and calculations on the event/signup dates.

Date API documention is quite light on specifics on this area, so it has not been much of a help.

* How can I use the Date API to obtain DateObject from the event date stored on the node?
* How can I determine whether the stored event is an all day event?

# Answer
> How can I use the Date API to obtain DateObject from the event date stored on the node?

Offhand, I'm not 100% sure the right way to do this. It sounds like you want to use the DateObject to perform some calculations -- not just to run through a theme field\_formatter. This date issue thread has some code kinda trying to use date fields and their values, but doesnt help much.

Simply because I can understand it (and have used this module myself) I recommend trying out the sub-module of Date, date\_api, and an additional 3rd party module: field\_extract.

With field extract you can easily (and correctly) access a fields value for instance as a timestamp:

```
  // Extract from a date, this extracts the first value and provides a
  // formatted date output, uses the specified format, by name.
  $event_timestamp = field_extract_value('node', $node, 'field_event_time', 0, array('format' => 'timestamp'));

```

You can then use the DateAPI to create a DateObject:

```
$date = new DateObject($event_timestamp);

```

> How can I determine whether the stored event is an all day event?

Use the date\_is\_all\_day() function found in the date\_api module, it compares 2 date fields to check if they encompass a full day.

```
 function date_is_all_day($string1, $string2, $granularity = 'second', $increment = 1) { ... }

```
> 0 votes

---
Tags: 7, datetime
---


# Question
Title: Highlight active page in a table row using views
I have a drupal 7 view that is outputting the titles of nodes which is in table form.

```
<table class="views-table cols-0" thmr="thmr_80">
  <tbody>
    <tr class="odd views-row-first">
      <td class="views-field views-field-counter">
       <a href="#">Link 1</a>
      </td>
    </tr>
    <tr class="even">
      <td class="views-field views-field-counter">
        <a href="#" class="active">Link 2</a>
      </td>
    </tr>
  </tbody>
</table>

```

Drupal gets me close by adding "active" class to the link (Link 2), but I would like it for the entire row (TR).

I saw another question like this one asked for an unordered list, but I tried that code and it didn't work. Maybe a little tweaking needed?

Thanks guys!

# Answer
I was able to get the answer using jquery. Hope this will help others who need it. Just add this code into the top of the page template and it will create the active class for you.

```
<script type="text/javascript" charset="utf-8">

$(function() {
   $('.views-table a.active').closest('tr').addClass('active_row');
});

</script>

```

Remember to change the "views-table" to match your own table.
> 2 votes

---
Tags: 7, views, theming
---


# Question
Title: When does system generate global variable $user?
I want to add some data to global variable `$user` when user login, so when does system generate `$user`, and which hook I should implement?

# Answer
The way is to make use of `hook_user_load`

> Act on user objects when loaded from the database.
>
> **Parameters**
>
> **$users**: An array of user objects, indexed by uid.

Also see UserController

> Controller class for users.
>
> This extends the DrupalDefaultEntityController class, adding required special handling for user objects.
> 2 votes

# Answer
Drupal initializes the global `$user` during bootstrap. Unfortunately, it doesn't invoke any hook, as modules are not yet loaded. (Loading the enabled modules is the last step of Drupal bootstrap.)

The following code is used in the Drupal session handler \_drupal\_session\_read().

```
  // Handle the case of first time visitors and clients that don't store
  // cookies (eg. web crawlers).
  $insecure_session_name = substr(session_name(), 1);
  if (!isset($_COOKIE[session_name()]) && !isset($_COOKIE[$insecure_session_name])) {
    $user = drupal_anonymous_user();
    return '';
  }

  // Otherwise, if the session is still active, we have a record of the
  // client's session in the database. If it's HTTPS then we are either have
  // a HTTPS session or we are about to log in so we check the sessions table
  // for an anonymous session with the non-HTTPS-only cookie.
  if ($is_https) {
    $user = db_query("SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.ssid = :ssid", array(':ssid' => $sid))->fetchObject();
    if (!$user) {
      if (isset($_COOKIE[$insecure_session_name])) {
        $user = db_query("SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.sid = :sid AND s.uid = 0", array(
          ':sid' => $_COOKIE[$insecure_session_name],
        ))
        ->fetchObject();
      }
    }
  }
  else {
    $user = db_query("SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.sid = :sid", array(':sid' => $sid))->fetchObject();
  }

```

To extend the global `$user`, you can implement `hook_boot()`, which is invoked when Drupal is still bootstrapping, or `hook_init()`, which is not invoked for cached pages. `hook_user_load()` is invoked when `user_load()` is called, but `user_load()` is not used for the global `$user`.

As side note, the global `$user` is not a complete user object. It contains the data saved in the "users" table, and not (for example) the value of any field (fields implemented from the field API) associated to the user entity.
`$user->data` can be used to store extra data for the user object. Its content can be altered through `hook_user_presave()` in the same way done by overlay\_user\_presave().

```
function overlay_user_presave(&$edit, $account, $category) {
  if (isset($edit['overlay'])) {
    $edit['data']['overlay'] = $edit['overlay'];
  }
}

```
> 7 votes

# Answer
If you want to add some data to `$user` just after login, you need to implement hook\_user\_login in your module as

```
function ModuleName_user_login(&$edit, $account) {
  //add your code here
}

```
> 1 votes

---
Tags: 7, users
---