# Question
Title: Create a simple date formatter to be used in views
I am using Views Data Export to create a custom RSS feed that looks like My Title 2012-05-12 22:33:00

Start date is a Date field provided by the Date module.

In order to achieve the date formatting on the second field I have to use the Plain formatter from the Date module to avoid theming tags. Unfortunately plain formatting, gives the raw date as stored in the DB ignoring timezone settings.

I have created a custom field formatter module to tackle this:

```
/**
* Implements hook_field_formatter_info().
*/
function rss_date_formatter_field_formatter_info() {
    return array(
        'rss' => array(
          'label' => t('RSS'),
          'description' => t('Displays a date as rss.'),
          'field types' => array('date', 'datestamp', 'datetime'),
    ),  );
}

/**
 * Implements hook_field_formatter_view().
 */
function rss_date_formatter_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
    $element = array();
    $settings = $display['settings'];
    $formatter = $display['type'];
    foreach ($items as $delta => $item) {
        $element[$delta] = array('#markup' => $item['value']);
    }
    return $element;
}

```

Problem is that no matter what I cannot set $element to return the localtime. $item\['value'\] contains a string of the date representation as it is stored in the DB (thus UTC). Converting it to a date and then back seems to output nothing. Also if I hardcode a string there, it seems the string is altered but I cannot find from which function this happens (eg. entering 'test' in the #markup returns '1est', like converting the first letter to a valid month (1-12).

Any clues on this? I never thought outputting a date in localtime without theming would be so hard.

# Answer
You should:

1. Create a new date format: /admin/config/regional/date-time/formats
2. Create a new date type that uses the format you just created: admin/config/regional/date-time
3. Use that date type in view.
> 1 votes

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


# Question
Title: Is it necessary to "activate" a file input field after a jQuery insertion?
I've got a Bootstrap modal that I use to present a form through which I can create and edit an node on my site. This object has an uploaded file associated with it, so things work in the usual way: when I create the object, I get the "Browse..." field for selecting the file; when I edit the object, I get a little rendering of the file and a "Remove" button that is meant to let me get rid of the old file and pick a new one.

I haven't been able to get/figure out the Drupal ajax mechanism to work with my modal form, and, without it, clicking the Remove button refreshes the whole page, which blows my modal away and is clearly the wrong thing. So I wrote some jQuery code for the Remove button: when the button is clicked, it removes the file's little rendering and inserts the same sort of file input field as when a node is created. This works; the code I get on the page is the same as what's there when I'm creating a new node.

The problem (finally!) is that, after this file field is inserted into the modal, clicking the "Browse..." button doesn't do anything -- it doesn't bring up the system file selection panel that will let me choose the file. I'm not seeing any error messages show up in the system log or the javascript console; I just get nothing (in several different browsers). Any clues on what's going wrong? Is there some initialization thing I have to do to get the system to pay attention to the newly-arrived input field?

# Answer
False alarm -- a bit more hacking showed that I was putting the field into a part of the page where it didn't want to be. Why this resulted in the "Browse..." button not working is still a mystery, but all is currently well.
> 0 votes

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


# Question
Title: How to add links to sidebar without using a block?
does anyone know how to add links or HTML onto the left sidebar of a drupal theme without using a block? I am using drupal 7.14. Any help would be appreciated.

# Answer
> 0 votes
Can be done using the \_phptemplate\_variables function in template.php in your theme directory.

```
function _phptemplate_variables($hook, $vars) {
  if ($hook == 'page') {
    foreach (array('left','right') as $region) {
      $vars[$region] = drupal_get_content($region);
      return $vars;
    }
  }
}

```

And just call this function below where you want to display the link.

```
$output = l('some link text','node/1234');
drupal_set_content('left', $output);

```

---
Tags: 7, theming, blocks
---


# Question
Title: Auto Complete for product variations use
Is there a way, when hiring for Attribute field setting

> (admin/commerce/config/product-variation-types/bags-cases/fields/field\_color)

to add an additional choice added.

I need urgently an auto-complete feature in the frontend for the field type term reference.

For a very large amount of product variations, it is otherwise with a 5 meter long drop down menu very user unfriendly (+4000 zip codes for a single service).

With the Finder module, I could not solve the problem unfortunately.

# Answer
You will need to write your own module and implement a hook\_form\_alter to override the normal Commerce way of displaying attribute selection.

A good example to look at is the Commerce Fancy Attributes module, which replaces the drop down with image selection. http://drupal.org/project/commerce\_fancy\_attributes

You can change the input type to autocomplete and point it to the correct callback url which returns your zipcode options in the format required for the product field.

```
$form['attribute_field_name']['#type'] = 'textfield';
$form['attribute_field_name']['#autocomplete_path'] = 'path/that/returns/list/of/zip/codes';

```
> 0 votes

---
Tags: entities, ajax, commerce
---


# Question
Title: How do I stop the page refresh on pressing "enter" in a form's text field?
How do I stop the page refresh on pressing "enter" in a form's text field?

# Answer
You need JS/JQuery assistance in this regard.

```
var stopSubmission = false;
jQuery('#q').keydown(function(e){
   if(e.keyCode == 13){
       stopSubmission = true;
   }else{
       stopSubmission = false;
   }
});

jQuery('form[action="/help/search"]').submit(function(){
    if(stopSubmission){
        return false;
    }
});

```
> 0 votes

# Answer
alternatively

```
$form['#attributes'] = array('onsubmit' => 'return false');

```
> 0 votes

---
Tags: 7, forms
---


title: how to add form data in database

text:
# Question
Title: how to add form data in database
My registration form is multi-step and the form is shown in popup. I m using lighbox2 for popup and working perfectly fine and i have added the form filed in a file that comes with lightbox2 and place in template folder and everything work fine, but the issue is how i can add the form data in database?

I use ajax when the ajax request sent it says access forbidden.

how I can insert data in database using ajax because my form is multi-step?

# Answer
> 1 votes
You'll need to define an ajax callback. This callback function can then be called by the form, and can submit values to the database for you using the Drupal database layer. In this case, I imagine the ajax handler will be added to the Next or Submit button.

```
$form['next'] = array(
  '#type' => 'submit',
  '#value' => t('Submit'),
  '#ajax' => array(
    'callback' => 'custom_ajax_callback'
  ),
);

```

Your module might also want to define its own database table to store temporary values for this.

---
Tags: 7, database, forms
---


# Question
Title: How can I execute jQuery within a *Basic page* content type node?
I would like to run some jquery within a *Basic page* content type node and the only place that I can place this code is within the Body section when within the *Edit Basic page*. After placing the following at the bottom of the Body section like the below: jQuery(window).unload( function () { alert("Bye now!"); } );

It errors off so that it appears that it does not have jQuery included within this content type. I tried putting a link to Jquery before calling jQuery but the link to it also errors off. How can I execute jQuery within a *Basic page* content type node?

# Answer
> 0 votes
I am not sure, but You can try to change filter to Full HTML, or the second method, create template file for that content type like node--NAMEOFNODETYPE.tpl.php and clear cache and put your javascript code inside it.

example:

```
<div>
     // Here YOUR JAVASCRIPT CODE
     <?php print render($content['body']); ?>
</div>

```

Or another method, in template\_preprocces\_page you can check: for all nodes by one type - just check:

```
$node = menu_get_object();
if($node->type == "your type") {
  drupal_add_js('YOUR CODE', 'inline');
}

```

for only one node by nid:

```
$node = menu_get_object();
if($node->nid == YOUR NID) {
  drupal_add_js('YOUR CODE', 'inline');
}

```

---
Tags: javascript
---


title: Need your advice. MultiSite

text:
# Question
Title: Need your advice. MultiSite
I want to create a project like http://www.chinatexnet.com/, but before begin writing code I want to ask for advice from the experts.

So, project that I am planning to develope contains just one main website and multiple sub-sites (about 500 subsites). If you look at http://www.chinatexnet.com/, there is one main site and too many subsites with same(simple) structure. The main site has noting its own it just gathers information from subsites. Subsites have defferent look, defferent information but same simple structure.

So what I am thinking is to create two sites, one for main site, the second is just template for subsites. Than create instalation profile by the second site (of course with the data which users inserted) and automate procces with drush. Finally get multisite system.

Is this right way or I need to use contrib modules like Domain Access or Subsites? I've read a lot about multisite system, and I know there can be problems like updating or gathering data to main site. But I can't see another way, so, if anyone has experience with such kind of projects, please, advise me.

P.S.: Sorry for my english :)

# Answer
> 0 votes
Given your description, the domain access module is the better way to go. Drupal multisites won't give you the capacity to have one main site and many smaller sub sites but that is the key feature of domain access:

> The Domain Access project is a suite of modules that provide tools for running a group of affiliated sites from one Drupal installation and a single shared database. The module allows you to share users, content, and configurations across a group of sites ...

---
Tags: multi-sites
---


# Question
Title: How to get notified when a user is blocked?
Is there a way to get notified when a user is blocked ? like a hook in user module or ? or there are another way ?

# Answer
There is hook\_user\_update() for this. Below is an example on how you can use it for your purpose:

```
/**
 * Implements hook_user_update().
 */
function my_module_user_update(&$edit, $account, $category) {
  // Check if the user was blocked
  if ($account->original->status != $account->status && $account->status == 0) {
    // Handle notification here
  }
}

```

To send an email programmatically from Drupal, you can check out this question.

**Another way to do this**, would be by using the Rules module and following the steps below:

1. Create a new rule that reacts on the user event "After updating an existing user account".
2. Add a condition of type "User is blocked" and save it with the defaults.
3. Add another condition of type "User is blocked", but this time use "account-unchanged" for the **Data Selector** and check the **Negate** checkbox.
4. Add an action of type System \> "Send mail" and play with it.
> 3 votes

# Answer
There are function - user\_is\_blocked($name). Where do you want to notify user?

But you can simply check user name like this:

```
  if (user_is_blocked($user->name) != FALSE) {
       drupal_set_message('account blocked');
  }

```

To notify user when account is blocked you can go to `admin/config/people/accounts` there are tab - `Account blocked` \- and you can check `Notify user when account is blocked.` You can set subject and body.
> 0 votes

---
Tags: hooks, users, blocks
---


title: The order of field in basic page

text:
# Question
Title: The order of field in basic page
I added a field image to my basic page and I set it to be displayed first. The problem is that the image still display after the field body.

How can I change the order in which those fields are shown?

# Answer
> 2 votes
Structure -\> Content Types -\> Your Type -\> Manage display-\> Change the position of image field with plus icon -\> Save

---
Tags: 7, entities
---


title: Node date in a different language?

text:
# Question
Title: Node date in a different language?
I use the following code to display the date in my node template:

```
<?php echo date("j F Y", $created); ?>

```

But I need to display the months in a different language, how can I do that?

# Answer
> 4 votes
I think you should use format\_date() function that allows you add you own format and Drupal will translate it into the currently website site language.

# Answer
> 0 votes
did you try ;-) Whatever the $language parameter, the format\_date() function doesn't change (for me) the language of the date.

---
Tags: 6, nodes, datetime, i18n-l10n
---


title: new content type permission

text:
# Question
Title: new content type permission
I created a content type called: **Spreed Sheets**. Then in */admin/people/permissions* I make sure I checked these 3 permissions for authenticated users :

> Spreed Sheets: Create new content
>
> Spreed Sheets: Edit own content
>
> Spreed Sheets: Delete own content

then I loged in with an authenticated user (not admin) and I only have access to *node/add/spreedsheets* but when I'm login with admin and want to add another content type such as article from *admin/content/add content* it always redirect me to *node/add/spreedsheets* !!what should i do to give back the full permission to admin?

# Answer
> 1 votes
If you want to create content-type (not content) then this is link `admin/structure/types` where all content types are listed (in drupal7). But If you are talking about create content then you can add content `node/add` here all types will be listed.

---
Tags: nodes, users
---


# Question
Title: How to to check if user has changed the password?
I wanted to send basic notification email to the user, after it has changed the password, to inform him of password change.

I am using `Rules` modules for that. But I am not finding any option there, to add condition if user has changed the password.

Is there any way I can check if user has changed his password using rules or pragmatically.

-- Many thanks for your time.

# Answer
> 7 votes
The easiest would be to do this using Rules. Following the next steps, should do the job.

1. Ensure you have enabled the "PHP filter" on the modules page. This is needed to be able to use PHP code inside Rules.
2. Create a rule that reacts on the user event "After saving a new user account".
3. Add a condition of type "Execute custom PHP code" and use the following snippet:
`return $account_unchanged->pass != $account->pass;`
4. Add your action(s) to send an email notification to the user or anything else that fits your purpose.

# Answer
> 4 votes
I haven't tried it in Rules before, but it would probably be a matter of comparing values on the `$account` and `$account->original` objects.

One way to do it in custom code is to implement `hook_user_presave()`:

```
function MYMODULE_user_presave(&$edit, $account, $category) {
  // Don't show message for registering users.
  if (isset($account->is_new) && $account->is_new) {
    return;
  }

  if (!empty($edit['pass']) && $account->pass != $edit['pass']) {
    // Password has been changed.
  }
}

```

You could probably do the same in `hook_user_update()`, but I haven't tried that before. The above is taken from a live project and works perfectly.

# Answer
> 1 votes
Using Rules might be easier since you are already using it, but you need to enable **PHP Filter** module.

The instructions as follow:

1. Enable PHP Filter module `admin/modules`
2. Create a new Rule `admin/config/workflow/rules`
3. Make sure to select `After updating an existing user account` from React on event dropdow list.
4. Add a condition and choose `Execute custom PHP code`
5. Add the following PHP custom code in the value section

`if(!empty($account->current_pass)) {
 return true;
}`
6. Then add an action and select `Send mail`
7. In the value section add `[account:mail]` and fill subject field and message field.

---
Tags: 7, users, rules
---


# Question
Title: (Newbie question) Something goes wrong here with db_add_field
I'm trying to adapt that D6 module to D7. I'm on the "add afield" part of .install

Here's my code :

```
function node_statistics_install() {
    db_add_field('accesslog', 'nid', array(
    'description' => 'Field added by node_statistics',
    'type' => 'int',
    'not null' => TRUE,
    'unsigned' => TRUE,
    'length' => 11,
    'default' => 0,
  ));

```

but nothing happens in the database on install, no errors in drupal logs... Am I missing something?

# Answer
First, make sure that **Statistics** module installed/enabled.

Second, replace your code with the following code:

```
function node_statistics_schema_alter(&$schema) {
  // Add field to existing schema.
  $schema['accesslog']['fields']['nid'] = array(
    'type' => 'int',
    'length' => '11',
    'default' => '0',
    'not null' => TRUE,
    'unsigned' => TRUE,
    'description' => 'Field added by node_statistics',
  );
}

function node_statistics_install() {
  $table = 'accesslog';

  $schema = drupal_get_schema($table);

  db_add_field($table, 'nid', $schema['fields']['nid']);
}

```

Note: make sure to uninstall and install your module after you apply the new code.
> 0 votes

---
Tags: 7, entities, hooks
---


# Question
Title: At user creation set different default timezone
When a new user applies for an account, how does one set the timezone default from 'America/Denver' to 'UTC' timzeone? It's ok to allow the user to change the timezone to a preferred timezone. However, most of my users will be signing up from the UK. Is there a way to set the default to UTC rather than America/Denver?

# Answer
> 3 votes
Try visiting `admin/config/regional/settings` to set default timezones.

I've also created a module called Timezone Detect that will detect and set user timezones automatically using javascript.

---
Tags: datetime
---


# Question
Title: Modifying behavior of "You Saved..." info in cart when attributes are chosen
I'd like to modify/eliminate the "you saved" text/info on the Cart page when a certain attribute (or attributes) has been chosen for the product in the cart.

This is the code from uc\_cart.module that appears to handle the "you saved" info:

```
      $totalfield = '<div class="cart-normalprice">'.uc_price($display_item['#total'], $context).'</div>';
  if ($item->list_price > $item->price) {
    $savings = $item->list_price - $item->price;
    $savings = $savings * $item->qty;
    $totalsavings += $savings;
    $totalfield .= '<div class="cart-savings">You saved '.uc_price($savings, $context).'!</div>';
  }

```

And I'd like to add something like "Do not display the 'You Saved' div if Option X, Option Y, or Option Z have been chosen".

Can anyone here direct me on how to accomplish that? Or could a jquery snippet such as this provide the same "hide" functionality?

```
(function($) {
 $(document).ready(function(){
if ($('.item-list > li:contains("sometexthere")').length > 0) {
    $(".cart-savings").addClass("newclass");
}
});
 })(jQuery);

```

The "newclass" would have a CSS display:none property that would hide the cart-savings div if the item-list (attribute options listing) div contained one of the words that is only used in these options. Or, it could be flip-flopped, where the div is already hidden via CSS, and the jquery adds a new css class that unhides it via "display:block".

Thanks!

# Answer
> 2 votes
Doing this in jquery is probably going to be the quickest way to achieve this, especially since you're dealing with custom code. The jquery code you posted is close, but you need a different approach to test if the list-item contains text:

```
$(document).ready(function(){
    if ($('.item-list' + ':contains("someothertext")').length != 0 ) {
        $(".cart-savings").toggle();
    }
});

```

Also, note I used the toggle() function here which is a quicker way to determine visibility than adding / unadding a visibility class.

You can verify the above code here: http://jsfiddle.net/JZnPq/

---
Tags: 6, ubercart
---


title: Modifying Commerce Cart Before Display

text:
# Question
Title: Modifying Commerce Cart Before Display
We have a Drupal Commerce cart. The pricing can be altered based on discounts that come in from an external database via XML httprequests. It worked -fine- when the XML requests were made when the user hit the 'Add' button. But another developer removed that code and now wants the XML requests to be made on the cart form.

The problem I'm having is that it appears that the cart wants to display -before- my code will trigger and update the line items.

So... is there a way to hook onto a cart form/view so that my update code fires -before- the view is actually rendered? Below is a snippet. What happens is that the default pricing displays and -then- when the user hits the 'Update Cart' button, the code fires and updates the pricing with the discounts from the external database.

```
function formxml_form_alter($form, $form_state, $form_id){
global $user;
if(! $user)
  return;

if($form_id == 'views_form_commerce_cart_form_default')
      $order = commerce_cart_order_load($user->uid);

     // request pricing from external site and store in array
 $request_string = 'http://mysite/Start?CartID=' . $customer_number . '&Cust=' . $customer_number . '&Cntact=' . $contact_number;
    $result = drupal_http_request($request_string, $options);

$seq = 1;
foreach ($order_wrapper->commerce_line_items as $line_item_wrapper) {
    $line_item = $line_item_wrapper->value();
    $my_product_id =  $line_item->commerce_product[LANGUAGE_NONE][0]['product_id'];
    $product = commerce_product_load($my_product_id);
        $my_product_title = rtrim($product->title);
            // update each line item with prices from external db array
            ...
     }
    // now save order
$form_state['order'] = commerce_order_status_update($order, 'cart', TRUE);
commerce_order_save($form_state['order']);

```

# Answer
> 1 votes
The best and cleanest way to achieve what you want is with a product pricing rule and a custom action with what you have above. That way it goes through the normal Commerce hooks. You just create a rule reacting on "Calculate the sell price of a product."

If you only want the rule to fire on cart and checkout pages, you can also create a custom condition that checks your current path (or there might be a module that adds that condition for you.)

So instead of a hook\_form\_alter, you want to declare a hook\_rules\_action\_info().

---
Tags: commerce, forms
---


title: Dynamic and/or flexible content types

text:
# Question
Title: Dynamic and/or flexible content types
First of all, apologies if this has already been covered, but since I have no idea of what I'm looking for, it's a bit hard to find information about my problem.

Then, the problem: I'm looking for a way to create pages with any number of any type of (pre-existing) fields. For example, I may want a plain old page with its body text and that's it. Then some day I might want a page with body text and a picture gallery, and that's also easy. Then I might wake up one morning and want to have a page with a gallery to begin with, then some text, then another gallery, then a list of mp3 files. And then whatever I need on a daily basis.

Now, as this is for my personal web site, I could easily get my hands dirty with HTML and be done with that, but suppose one day one crazy client of mine comes up with a similar request. What am I supposed to do? Surrender to the evil "15yo nephew" that "can do it no sweat in a matter of hours and a fraction of your paycheck"? See, I use my web site as sandbox/gym to prevent situations like these :)

Any suggestion is welcome (although I'd rather keep Panels as a last resort, and I'm not even sure it does what I'm asking).

**EDIT** Here's a good example of what I'm trying to achieve, except that that site is uses Wordpress so I'm guessing everything has to be done by hand

# Answer
A CMS like Drupal is a way to create structured content types to make it easier to author large numbers of pages with the same structure. This is actually great from a user experience perspective, as the user expects information to be presented to her in a consistent manner from one page to the next.

The user will be fine with multiple presentation types if the information architecture is consistent, but if your structure is all over the map, the user will quickly tire of having to figure things out.

So for the majority of your site, plain old content types will probably serve you best.

If you are talking about overview pages, then getting used to Panels will probably make it something other than a 'last resort'. It is quite powerful, and customizable. The alternative, if you wanted daily customization, would be to create a single content type, and add and remove fields at will. However, I believe that after a while you are going to wish you had selected to use panels. Eventually you are going to want to re-use something you had before.

When you are using a CMS, think in terms of building blocks, and how to combine them to reach your goals.
> 0 votes

---
Tags: entities, nodes
---


# Question
Title: How can I customize the display of messages sent with privatemsg?
Use case: When a user is viewing a private message (from the privatemsg module), I would like to display the following:

* a picture field from the user's profile (not the user's profile picture)
* a link to flag the user (to report potential abuse)

Senders should see values for recipients and recipients should see values for senders. How might I go about implementing this?

**What I've found out so far:**

Out of the box, privatemsg cannot be overriden by Panels. The Panelizer project is not able to add panes on, either. There is a Privatemsg Panels sandbox project for which some work has been done but I need a more mainstream, maintainable solution.

Work on the D7 version of Privatemsg Views is currently stalled.

# Answer
> 2 votes
I've just implemented the Privatemsg Panels plugin with the D7 Patch through the pm\_existing\_pages plugin and it's working quite well! Here's how it all goes down for Drupal 7:

* Grab the master branch of the privatemsg\_panels module and upload to your modules directory
* Patch Manager is super handy - install it and run the panels\_privatemsg7.patch file to upgrade the module to a 7.x branch (or patch by hand or drush or eclipse etc)
* Optional: Install PM Existing Pages and add override the default /messages/ path with a new panel. Of course you could create a new panels page just as easily.
* Add content to your panel - Privatemsg should be a menu item now:
* Create a nice little custom link block from the instructions over here \- might be useful for your particular view!
* Optional: override privatemsg-view.tpl.php for a more custom layout. I haven't quite got this far, will try to remember to update this when I give it a shot.

**Edit - Adding info!**

* Overriding privatemsg-view.tpl.php works great, just remember to clear the cache after you add the file to your theme folder.
* Take a look at the Privatemsg Theming Documentation. All of the functions that start with *phptemplate\_* can be overridden by your own theme. Example: drop this into your template.php file

```
function YOURTHEMENAME_privatemsg_list_field__participants($variables) {
    $thread = $variables['thread'];
    $field = array();

    if ($thread['has_tokens']) {
        $message = privatemsg_message_load($thread['thread_id']);
    }
    if (!isset($message)) {
        $message = privatemsg_message_load($thread['thread_id']);
    }

    $participants = _privatemsg_generate_user_array($thread['participants'], -4);

    $field['data'] = theme('user_picture', array('account' => $message->author));
    $field['data'] .= '<div class="user-name">'. _privatemsg_format_participants($participants, 3, TRUE).'</div>';

    $field['class'] = 'privatemsg-list-participants';

    return $field;
}

```

This will add a user picture to the recipients field! AWESOME! Just remember that each overridden fuction expects to have 3 things returned: a field, a header theme pattern, and a field theme pattern - the documentation explains it better than I can ;)
* The functions at the Privatemsg Theming Documentation starting with *theme\_* can be overridden using a `function YOURTHEMENAME_form_alter()` hook. If you add this function to your template.php, drop `dsm($form_id); dsm($form);` in to get a better idea of exactly what form you're working with.
* Looking to change column order around? It's easier than you might think - check out the drag-and-drop column order at /admin/config/messaging/privatemsg

There has been a bit of discussion about how to add custom columns to the output but I'm not there yet.. I'll have to point you at the Privatemsg Issue Queue for that one.

Good luck!

# Answer
> 1 votes
Yeah, Privatemsg doesn't really integrate with the world of Views and Panels.

However, we do have enough hooks and templates to implement this. You can use privatemsg\_message\_view\_alter() to add additional things like a report link (look at pm\_block\_user.module for an example of that) to the message body. And you can override the privatemsg-view.tpl.php template file to customize the whole thing.

---
Tags: 7, privatemsg
---


# Question
Title: webform submitted by the user the email that is sent is wrapped after around 75 characters
I am using a Drupal 7 webform and when the webform is submitted by the user the email that is sent is wrapped after around 75 characters. The confirmation page which is displayed and uses the same elements as the webform does not wrap after 75 but instead continue on the same line. How can I get the webform email that is sent to not wrap after 75 characters.

# Answer
DefaultMailSystem::format uses drupal\_wrap\_mail() to wrap the body text on sending. There is no option to send unwrapped text.
> 2 votes

---
Tags: webforms
---


title: Views 3 List Style CSS

text:
# Question
Title: Views 3 List Style CSS
Usually, when I make a views block list, and I want it horizontal, I would just add CSS styles to the block itself.

```
#block-views-something li
{
  display: inline;
  list-style-type: none;
  padding-right: 20px;
}

```

Having to do this for each block is a pain. I know Views 3 lets me add a class to the view to style the list, but I have never been able to do it. I have tried HTML List, and adding classes to Page: Style options Row class, and Wrapper class or even List class. I have tried it with a dot like .mystyle and without the dot 'mystyle'.

In fact, I just get myself into a right old mess. Could anyone advise me the simplest route to take to add the class to whatever box I should add it to?

# Answer
> 1 votes
The only good way is to use the 'add a class'-option in views. That allows for maximum flexibility and should not break if something in the view changes. (block-view-id-something can break when numbers or names change).

One you have added a css class to the field, something like `horizontal`. Then you can define it in your theme file css with `.horizontal {...}`.

But since themes can update their css, overwriting your changes, you are even better off using an extra stylesheet in your themes folder. Give it any name you want, add the `.horizontal {...}` lines. Then open the \*.info file in your theme and add `stylesheets[all][] = <stylename>.css`.

If it might break after a style update, all you have to do is add this line again.

---
Tags: views
---


# Question
Title: Using computed fields module to display certain fields?
I just installed the computed fields module and I'm a little lost as to how to use it. I have 2 fields in my content type: `field_shortdesc` and `field_audio_description`.

If `field_shortdesc` is blank I need to display `field_audio_description` and vice-versa.

What code do I need to place into the computed code and display code areas?

# Answer
> 1 votes
Sorry for the late response, but this is an issue I struggled with as well.

In the first box, 'Computed Code' you determine the value of the computed field based on what is present in the $entity object. Calculations are possible, but drupal functions or methods are not available. In your case the entire determination can be performed here:

```
if ( isset($entity->field_shortdesc) && trim($entity->field_shortdesc[$entity->language][0]['value']) != "") {
  $entity_field[0]['value'] = $entity->field_shortdesc[$entity->language][0]['value'];
} elseif (isset($entity->field_audio_description)) {
  $entity_field[0]['value'] = :$entity->field_audio_description[$entity->language][0]['value'];
} else {
  $entity_field[0]['value'] = "";
}

```

The second box, 'Display Code', is for processing the value you determined in the first box. If you have to call drupal functions to load a user object or to format text this is where you would do it. In your case, no further processing is required, so you would leave the default:

```
$display_output = $entity_field_item['value'];

```

Then if your fields are using an input format (eg. 'Filtered HTML') you will want to set the display format (under 'Manage Display') to 'Filtered markup'.

---
Tags: 7, entities
---


title: Module to make View Tokens available

text:
# Question
Title: Module to make View Tokens available
I'm looking for a module which adds Views into tokens. E.g within some content, I want to be able to use \[view-vid\], or something similar.

Is there anyway for me to do this without needing to write custom code?

# Answer
> 0 votes
In D7 you can use a phpsnippet calling views\_embed\_view. Modules to do the job like Views embed filter seem to have died at the D6 stage.

---
Tags: views, tokens
---


title: Manage content items using Views

text:
# Question
Title: Manage content items using Views
I'm creating a user-upload photo gallery, and I require admin approval on all user uploads. Photos will be a content type with just a few fields (Image, Taxonomy, Tags). I'd like to be able to view a grid of all uploaded photos at a glance, and then check a box next to each one and publish/unpublish all that are selected. Is there a method by which I an do this using Views? If not, is there another method/module that can provide this type of functionality?

Thanks!

# Answer
> 1 votes
Create a content view, filter by your gallery content type, add the image field, add the field "Content: Published" (to let you know if content is published). Then add "Bulk operations: Content" (you need to install Views Bulk Operations module). In the field settings you should select the option "Publish content" and "Unpublish content". You should now be able to bulk publish and unpublish the image galleries.

---
Tags: 7, views, media
---


title: DatePicker is not working

text:
# Question
Title: DatePicker is not working
Datepicker is not working. This code working with Drupal 6, but not with Drupal 7.

```
drupal_add_js(drupal_get_path('module', 'PROPERTY') .'/jquery/jquery-1.4.1.js', 'module');
drupal_add_js(drupal_get_path('module', 'PROPERTY') .'/jquery/jquery.min.js', 'module');
drupal_add_js(drupal_get_path('module', 'PROPERTY') .'/jquery/jquery-ui.min.js', 'module');
drupal_add_js(drupal_get_path('module', 'PROPERTY') .'/jquery/datepicker.js', 'module');
drupal_add_js(drupal_get_path('module', 'PROPERTY') .'/jquery/ztfb_datepicker.js', 'module');
drupal_add_css(drupal_get_path('module', 'PROPERTY') .'/jquery/ui.all.css', 'module');

drupal_add_js(drupal_get_path('module', 'PROPERTY') .'/jquery/scrollJump.js', 'module');

```

```
$(document).ready(function() {
  $("#startdate").datepicker({
    dateFormat:'dd-mm-yy',
    autosize:false,
    changeYear:true,
    changeMonth:true
  });
});

```

I include the file in PROPERTY\_Form.admin.inc file.

```
require_once("D://wamp/www/propertysite/cron/includes/jquerydatepicker.php");

function PROPERTY_Form() {
  global $user;
  $form = array();

  $form['PROPERTY_Form']['startSyncFrom'] = array(
    '#type' => 'textfield',
    '#prefix'=>'<tr><td>',
    '#suffix'=>'</td></tr>',
    '#id'=>'startdate',
    '#default_value'=>date('d-m-Y'),
    '#description' => '(You can select any past date to ensure even your old Data gets synced)',
    '#attributes'=>array('tabindex'=>9,'style'=>'width:70px;'),
  );

  return $form;
}

```

# Answer
> 1 votes
You do not have to include all of that jquery libraries: Drupal core has that libraries. You can just include any jquery.ui library with `drupal_add_library('system', 'ui.datepicker')` or another library which you want to include. Then, in your JavaScript file, you can write something like this.

```
(function ($) {
  Drupal.behaviors.custom_js = {
    attach: function(context) {
      $('#YOURID input[type="text"]').datepicker({
        showOn: "button",
        buttonImage: Drupal.settings.basePath + "sites/all/themes/YOURTHEME/images/calendar.png",
        dateFormat: "dd-mm-yy",
        showAnim: "slideDown",
        buttonImageOnly: true
      });
    }
  };
})(jQuery);

```

If you want to use the datepicker with the form API, you have to change the type element to 'date\_popup'.

---
Tags: datetime
---


# Question
Title: Clientside-validation for form-api for field either digits or empty
A particular form field can be left blank or filled with digits, with no other valid characters including dash"-"

```
$form['hours'] = array(
    '#type' => 'textfield',
    '#title' => t('Hours worked per week'),
    '#size' => 3,
    '#maxlength' => 3,
    '#default_value' => '',
    '#rules' => array(
      "digit",
      'length[0, 3]',
    ),
    '#filters' => array('numeric', 'trim')
  );

```

I have a minimum length of 0, but an empty field appears to be invalid. I've tried using "numeric" instead of "digit" but this allows dashes.

Is there some way to do this without using a custom handler?

# Answer
> 3 votes
The way I did this was to add a custom validation handler. I know I asked for a solution without one, but it turned out to be a fairly simple thing to do. See the "#element\_validate' array element below.

```
$form['hours'] = array(
  '#type' => 'textfield',
  '#title' => t('Hours worked per week'),
  '#size' => 3,
  '#maxlength' => 3,
  '#element_validate' => array('mymodule_validate_integer'),
  '#default_value' => '',
  '#rules' => array(),
  '#filters' => array('numeric', 'trim')
);

function mymodule_validate_integer($element, &$form_state, $form) {
  if (!empty($element['#value']) && (!is_numeric(parse_size($element['#value'])) || $element['#value'] < 0)) {
    form_error($element, t('"!name" must be a positive number.', array('!name' => t($element['#title']))));
   }
 }

function mymodule_clientside_validation_rule_alter(&$js_rules, $element, $context) {
switch($context['type']) {
case 'element_validate':
  if (in_array('mymodule_validate_integer', $context['functions'])) {
    _clientside_validation_set_minmax(
        $element['#name'],
        $element['#title'],
        0,
        99999,
        $js_rules,
        t('"!name" must be a positive number.', array('!name' => t($element['#title'])))
    );
  }
  break;
  }
}

```

I hope this helps someone in the future.

---
Tags: 7, forms
---


# Question
Title: In Drupal 7, moving the comment form above the comments
Before anyone suggest the Comment Form Above Comments, I have already tried that it did not work.

Honestly there seems to be amazingly little documentation on this issue, given that comment form above the comments is so standard on many sites now a days I would figure there would be a simple button to click to make this happen.

This leads me to believe that either there is a simple solution that I am completely missing or there is no way to do this and I am doomed. Me I am hoping for the first one.

I have a blog site... I read about altering the core code of the comments module, but I have also heard that it is bad practice to alter the core code. So if there is another solution out there available to drupal 7 I would appreciate it.

# Answer
I think you should copy `modules/comment/comment-wrapper.tpl.php` to your theme and change it there. The file is pretty much self explanatory. Hope it's helpful.
> 7 votes

# Answer
I am not sure what you mean by

> Before anyone suggest the Comment Form Above Comments, I have already tried that it did not work.

But the following works for me.

In node.tpl.php I printed the form in the following order

```
  <?php print render($content['comments']['comment_form']); ?>

  <?php print render($content['comments']); ?>

```

The form and the comments are contained with in the variable `$content['comments']` so when you render this variable it does so with both the comments as well as the comment form. The comment form is found with in the variable called `$content['comments']['comment_form']` so if you render this one first it would be removed from the array and wont be rendered in the subsequent call to the render function.

Please see it in action in below image
> 6 votes

---
Tags: 7, comments
---


# Question
Title: How to add an argument to a view programmatically?
I want to add an argument to a view. I want to set this argument programmatically (not by url).

The field i want to filter is not directly in the view query, because this is a field on a node reference, so I cannot use `hook_views_query_alter`.

How can i can add programmatically an argument to a view? I mean, which hook is better to do it?

# Answer
You can use `hook_views_pre_view()` and set arguments you want.

```
function hook_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'your_view_name') {
    $view->set_arguments(array('arg1', 'arg2'));
  }
}

```
> 9 votes

---
Tags: 6, views
---


title: Post-installation PHP crash

text:
# Question
Title: Post-installation PHP crash
I decided to give a shy try to Drupal 8. Installation went quite smooth, but when everything was ready to hit the home page I was delighted with the following error:

> CRASH: PHP segmentation violation in method\_exists() called at \[/core/vendor/symfony/http-kernel/Symfony/Component/HttpKernel/Controller/ControllerResolver.php:72\], in Symfony\Component\HttpKernel\Controller\ControllerResolver::getController() called at \[/core/vendor/symfony/http-kernel/Symfony/Component/HttpKernel/HttpKernel.php:117\], in Symfony\Component\HttpKernel\HttpKernel::handleRaw() called at \[/core/vendor/symfony/http-kernel/Symfony/Component/HttpKernel/HttpKernel.php:73\], in Symfony\Component\HttpKernel\HttpKernel::handle() called at \[/core/lib/Drupal/Core/HttpKernel.php:52\], in Drupal\Core\HttpKernel::handle() called at \[/core/vendor/symfony/http-kernel/Symfony/Component/HttpKernel/Kernel.php:197\], in Symfony\Component\HttpKernel\Kernel::handle() called at \[/core/includes/bootstrap.inc:2208\], in drupal\_handle\_request() called at \[/index.php:12\]

How would I go about solving this? Is that something of a Drupal programming error? Is that something that depends on final configuration? I kind of don't believe this would massively occur to all people, so I assume it might be caused by something in my setup.

I'm running PHP 5.3.21 with a local php.ini setting the magic quotes flags to off. Due to the hosting, I had to comment out the htaccess bottom part for gzip compression, if that matters.

# Answer
> 4 votes
A PHP `segmentation violation` is a PHP bug. You can not solve this at the PHP, or Drupal level, this needs a bug report for PHP itself, here.

Segmentation violation means that PHP somehow mismanaged it's memory, which is impossible to directly cause with PHP code, since pointers aren't available.

Notice though that there are two releases of 5.3 after the one you're running, upgrading should be your action, as a problem in `method_exists()` should have gotten a lot of attention, and is hopefully already fixed.

---
Tags: 8
---


# Question
Title: Field Max Size limited to 10 for Integer in Number Module
I'm trying to add an Integer as a new field to Users. Have installed the Number module and added a field type 'Integer' with a maximum value of 999999999999999999. But when I edit a user the field has a max length of 10. Is there a way to edit this?

# Answer
Maximum number that Number module can hold is 2 147 483 647 (231 \- 1), because of the size of SQL `INT` datatype. For larger numbers you must use string field or Bigint module, that allows to storing numbers up to 9 223 372 036 854 775 807 (263 \- 1).
> 9 votes

---
Tags: entities
---


title: Using Rules to perform Node Export

text:
# Question
Title: Using Rules to perform Node Export
I would like to be able to use Rules to have the Node Export module create an XML file whenever a certain type of node has been updated. I have set up a Content Type with a display and an edit screen. The edit screen includes a Save button. I have also set up a Node Export which has successfully created an XML file with data from the node. It runs via a Node Export tab on the display screen of the node. What I would like to do is have the Node Export to XML occur whenever the Save Button is clicked, right after the update of the data is done. I began to create a Rule for this. For the Event, I chose "After updating existing content". However, under "Actions" I was not able to find any reference to Node Export. Has anyone been able to do this or can anyone point me in the right direction? Thank you.

# Answer
The Node Export tab points to a link, so I was able to get this working by setting 'Actions' to 'Page redirect', and pointing it to the page that the Node Export tab points to, a page within the node called 'node\_export', e.g. '../node/1602/node\_export', where '1602' is the node id (nid). So I entered 'node/\[node:nid\]/node\_export' as the Value of the URL to which it is to be redirected. I also left 'Force redirect' checked. Now when I click the Save button it performs the node export to XML after updating.
> 0 votes

---
Tags: rules, importing-exporting
---


title: Preserve database relationships

text:
# Question
Title: Preserve database relationships
We're in the process of figuring out quite how much work upgrading to Drupal 7 is going to be. The thing that is really worrying me, is that we currently have our main content as Nodes:

* Equipment
* Person
* Company
* Address
* Contract
* Timesheet

Now, these are linked together using join tables (timesheet for person, address for company, etc) using the node ids, obviously.

Anyway, the possibility of exporting all of this information somehow is quite frankly impossible. The only way we can possibly do it is to be able to import Nodes into the new format and preserve the current Node IDs.

Is this possible?

# Answer
> 0 votes
upgrading is a pain in the ass you will need to migrate things which will not work upon migration, you will have to reset options in views as views will not recognize migrated content. I've been doing this for 2 month I still dont know how to migrate this drupal 6 to drupal 7

---
Tags: 7, nodes, upgrading
---


title: Theme folder in drupal 8

text:
# Question
Title: Theme folder in drupal 8
In Drupal 8, the theme folder for contributed themes seemed to have moved.

Where do themes go in drupal 8?

# Answer
> 9 votes
The theme location moved to /themes, while the core themes moved to /core/themes.

This is how the directory structure looks like in Drupal 8.

---
Tags: theming, 8
---


# Question
Title: How to automatically select the organic group audience when adding content?
How can I setup a link on a group page to add content that automatically selects the group audience as the referred group?

For instance:

I'm a member of the group "Puppy Kittens" and I'm logged in to that group page (node/12) and I have links on that page to "Add Post". The link "Add Post" opens up and allows me to add a post for my group without me having to select my group.

# Answer
> 0 votes
OG group extras

> Extra functions, blocks, and views for Organic Groups 7.2. In particular, this module adds views and blocks needed by sites that are not using Panels.

This only works on OG 7.2 but not on OG 7.1. If you are using OG 7.1, you can use panels and add a create group content panel to the node page.

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


# Question
Title: Wiki-like "create this page" with page manager?
I want to make it easier for editors to create new pages with page manager. Is there a way to provide a "create this page" functionality for non-existent paths, so that editors can insert a new path in existing pages and proceed to create and edit the new page, just like editing a wiki?

I am wondering if I can implement this feature by using a menu tab like this to redirect unhandled path to the page manager's creating page. Helps are very much appreciated.

# Answer
> 2 votes
You should achieve that by using the following extensions:

You should have a look at this screencast: http://www.youtube.com/watch?v=KHsjjHzYOSg

It is done with Drupal 7, however, wikitools is still in alpha for Drupal 7.

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


# Question
Title: how to manually add a node in drupal 7 in the database
I have managed to display the title but im missing the body of the title. i cant find in the database which table i missed to edit.

here's the list of tables i editted:

1. node
2. node\_revision
3. node\_comment\_statistics
4. taxonomy\_index

for the body i assume that these fields are responsible for it:

1. field\_data\_body
2. field\_revision\_body
3. field\_data\_taxonomy\_forums
4. field\_revision\_taxonomy\_forums

The node i made has no comments so no comment table is editted.

Am i missing other tables to edit here?

SO i assume i have editted all the necessary tables but i seemed to have missed something here cause **ONLY THE BODY IS MISSING.**

# Answer
Because you are trying to understand Drupal database concept, you are checking every insert you made in the Drupal admin section, and by doing so Drupal is caching your data.

So you are not missing anything. You only need to clear Drupal cache, try to truncate each cache table one by one.
> 2 votes

# Answer
I hope this is just an academic exercise to better understand Drupal storage.

If you have the nid of the page, go to /node/{insert NID}/edit (or use the Edit tab), and make your changes there. Then go to the database and see where the changes took place. Pay particular attention to the vid (Version ID) as it may or may not match the Node ID. Your assumptions about the tables involved are correct.
> 0 votes

---
Tags: database
---


# Question
Title: Views exposed filters - how to show "You searched for [exposed filters]" above results?
I'd like to summarize the current filters used on the data in the results.

What's the easiest way to do this?

```
[ ] Cats
[x] Dogs

[Search]

You searched for Dogs

===============================
Lassie        Movie star
Bones         Runner
Hobbes        Show-dog

```

Thanks!

# Answer
Use the Exposed Filter Data module. With it you can print the filters used in the view header.
> 0 votes

---
Tags: views
---


# Question
Title: Choose a facet using the search form and then show filtered results
The requirement is that the user specifies a facet *before* they search. Here's what the search form should look like:

Adding the select list to the search form is a straight forward form\_alter(). My problem is how do I send the selected audience value from the drupal form to solr?

Once I have the audience value in the solr query object, I think I would apply the facet by using HOOK\_apachesolr\_query\_prepare() (or HOOK\_apachesolr\_query\_alter()).

Thanks!

# Answer
Here's my solution:

Add the select menu to the form and append a custom submit function

```
  function ucb_parking_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case "search_block_form":
      // Add the audience select list
      $form['search_audience'] = array(
       '#type' => 'select',
       //'#title' => t('Choose Audience'),
       '#options' => array(
      47 => t('Faculty/Staff'),
      36 => t('Student'),
      ),
       '#description' => t('Focus your search on an audience.'),
      );
      //Add a custom submit function to the end of the array of functions.
      //(This function will run after apachesolr_search_form_search_submit().)
      array_push($form['#submit'], 'ucb_parking_front_page_search_submit');
      break;
  }

}

```

In the custom submit function construct the solr url with a query string representing the facet that should be applied and redirect the user there:

```
function ucb_parking_front_page_search_submit($form, &$form_state) {
  /*
   * Simply construct the solr url for the search.
   * Note the querystring for the facet must be passed via an array with the 'query' key
   * to ensure correct urlencoding.
   */
  $form_state['redirect'] = array($form_state['redirect'], array('query' => array('f[0]' => 'im_field_audience:' . $form_state['values']['search_audience'])));
  //drupal_goto is probably equivalent
  //drupal_goto($form_state['redirect'], array('query' => array('f[0]' => 'im_field_audience:' . $form_state['values']['search_audience'])));
}

```

I think that this is the correct approach because apachesolr does pretty much the same thing with $form\_state\['redirect'\]:

```
/**
 * Added form submit function to retain filters.
 *
 * @see apachesolr_search_form_search_form_alter()
 */
function apachesolr_search_form_search_submit($form, &$form_state) {
  $fv = $form_state['values'];
  // Replace keys with their rawurlencoded value
  if (isset($fv['search_block_form'])) {
    $raw_keys = str_replace("/","%2f",$fv['search_block_form']);
    $form_state['redirect'] = str_replace($fv['search_block_form'], $raw_keys, $form_state['redirect']);
  }
}

```
> 0 votes

---
Tags: 7, search
---


# Question
Title: Which actions in Drupal needs clearing the cache?
I'm a newbie in Drupal. I usually use the clear cache function from Devel module for each changes(sometime I use `drush` command line tool) like: modify CSS, create/change blocks, change permissions, create new content type, create new web form, change template files... and clearing the cache costs a lot of time on my local environment (I've just 1GB of RAM). So can anyone show me which actions in Drupal that we need to clear cache.

# Answer
> 1 votes
### REQUIRED

1. When you implement hooks (not all): like `hook_menu`, `hook_init`, `hook_block_info`, `hook_block_view`, `hook_theme` and so on.
2. If you have checked JS/CSS aggregation and you change your these files.
3. When you implement template functions in your `template.php` file (not modifications of existing functions).
4. When you override template files of core and contrib modules.
5. Changes of `hook_menu` and `.info` files. ...

### NOT REQUIRED

1. Modifications of existing template functions.
2. Creating users, contents, content types, webforms, etc.
3. Changes of existing template files, permissions, etc.
4. Changes of js/css when aggregation is off.

And so on.

# Answer
> 1 votes
Strategy is quite easy - clear it when you changed something in code or database.

Below some popular cases (based on my experience):

* you added new content and need to update cached pages, views or blocks (for example you enables cache for anonymous users)
* you changed JS or CSS files and you have enabled aggregation
* you installed new modules (in this case need to run update.php)
* you did modifications in existing module which require update cache. For instance added menu item or implemented some hooks.
* you did changes in theme files

---
Tags: hooks, caching
---


title: Show VIEW attachments in a block

text:
# Question
Title: Show VIEW attachments in a block
i have a page-view that shows all avatars from the community. This view has an exposed filter.

This community-view has two attachment-views: \- most comments \- best authors

Now i want to have the attachment-views shown in the sidebar as a block.

How can i handle the attachment like a block?

Thanx Michi

# Answer
You can create a block-view display with no content and then attach those attachment-view to the block-view display. This may be a possible hack if i understand you correctly.
> 0 votes

---
Tags: views
---


# Question
Title: How to force rules configuration to load
There is a rule that comes with Commerce Paypal, commerce\_payment\_paypal\_wpp, it implements an Action: "PayPal WPP - Credit Card", which provides an admin interface to configuring the PayPal WPP, with API Username, password, etc. We've implemented our settings for this, as with other rules, as commerce\_paypal\_wpp.rules\_defaults.inc.

The problem is that, in this case, commerce\_paypal\_wpp.rules\_defaults.inc is not loaded for some reason when the rule is installed. After installation, we have to log in, navigate to that admin form, open it and press save, no changes, just press save.

We tried without success:

```
function MODULE_default_rules_configuration_alter(&$configs) {
  $configs['commerce_payment_paypal_wpp']->active = TRUE;
  $rule = rules_config_load('commerce_payment_paypal_wpp');
  $rule->save;
}

```

What do we need to do in code that would do the work of clicking that save button? This is the last obstacle to a zero-touch installation, would really like to get that in. Any ideas?

# Answer
> 0 votes
Your question is a bit confusing, because the default Rule in question is defined by the Payment module in commerce\_payment.rules\_defaults.inc, not by the PayPal module. It sounds to me like a general case of cache trouble, though in my testing and development of the PayPal module I've never seen any issues with it. If what you mean is simply that the payment method rule is disabled by default, that's just how we've built the modules - enabling it like you show with your custom code will just be a necessary step.

---
Tags: commerce, payment-gateways
---


title: how to use entity_load() result?

text:
# Question
Title: how to use entity_load() result?
I am quite new to Drupal so this question may be very simple or basic. I created a module and I've extracted list of a custom content type for each user by using **EntityFieldQuery** and then I used **entity\_load** to make the results ready. the question is how should I use the $archive\_items in my template ?!?

> ```
> <?php
> $archive_items = entity_load('node', $archive_items_nids);
> ?>
>
> ```

# Answer
Your function will give an array of entity objects, indexed by their entity\_id's. So:

```
foreach ($archive_items as $entity_id => $archive_entity) {
  /* Process each entity */
}

```

will allow you to iterate through the entities and to do what you need to each. Beyond that, we will have to know what result you are trying to achieve.
> 3 votes

# Answer
Assuming that you want to render your collection of nodes, you would use `node_view_multiple()`. It's worth noting there's a node specific version of `entity_load()`, `node_load_multiple()`.

With that in mind I imagine you're looking for code like the following:

```
$efq = new EntityFieldQuery();
$efq->entityCondition('entity_type', 'node');
// etc...

$results = $efq->execute();
$nodes = node_load_multiple(array_keys($results['node']));
$views = node_view_multiple($nodes);

$output = drupal_render($views);

```

`$output` will contain a list of teasers representing the nodes found in the EFQ.

It's also worth noting this kind of logic should not happen in the template file, but rather in a preprocess function. This will prevent potential problems with caching later on, and is just good programming practice all-round.
> 0 votes

---
Tags: entities
---


title: path alias hook menu i18n

text:
# Question
Title: path alias hook menu i18n
Is it possible to make path alias that is not storing in database, like using system hook menu path I want to make url for en/weather and rs/vreme.

e.g

```
<?php
function weather_menu() {
    $items = array();
    $items['weather'] = array(
      'title' => 'title',
      'description' => t('description hook menu'),
      'page callback' => 'weather_page',
      'access callback' => TRUE,
      'type' => MENU_CALLBACK
    );
     return $items;
}
?>

```

# Answer
> 1 votes
Follow below steps to add path aliases to "weather" menu path

* Enable locale module
* Go to admin/config/search/path/add
* Select language rs and add path alias as "vreme" and Existing system path as "weather"

That should work !:-)

# Answer
> 0 votes
Oh, I know perfectly what you mean. This is a nightmare in Drupal, to be frank. I don't know why we cannot filter aliases by their module signature and bulk operations are destructive to manually created aliases... But anyway:

If this is a non-Views page, in `hook_init()` of a module, you could check if the alias exists and if not, create it using path\_save(). Then bind it into a path translation set via i18n\_translation\_set\_create()

If this is a Views-generated page you could give a try to http://drupal.org/project/i18\_page\_views.

---
Tags: 7, path-aliases, i18n-l10n
---


title: Search template page in Drupal 7

text:
# Question
Title: Search template page in Drupal 7
In search results page,

the search form and search results are in the content area.

Can we insert another block between the search form and results list? Or adjust the order for example put "spelling-suggestions" on the top of the form, then add another block between the form and search extra provided by display suite.

If without existing templates, guessing we will have to modify the $node\['content'\].

Any ideas are welcome, thanks

```
<form id="search-form" class="search-form" accept-charset="UTF-8" method="post" action="/search/all/test">
<div class="spelling-suggestions">
<div class="ds-search-extra">One result</div>

```

# Answer
My current method is dirty:

```
  $build['search_form_resort'] = $build['search_form'];
  unset($build['search_form']);

```

Then put the $build\['search\_form\_resort'\] under the $build\['suggestions'\].

Read more: http://api.drupal.org/api/drupal/modules%21search%21search.pages.inc/function/search\_view/7
> 0 votes

---
Tags: 7, theming, search
---


title: I can't add links to any of my menu

text:
# Question
Title: I can't add links to any of my menu
I can't add links to any of my menus.

I go to the menu, click on **add link**, and fill all the required data; I get the message, "Your configuration has been saved." It doesn't seem it is what it is done.

All modules and core are updated to the last versions.

# Answer
I fixed it. The problem was that the path contained "20%" instead of a space.
> 3 votes

# Answer
I encountered something similar, but in my case I hadn't noticed that **I had unchecked the 'published' checkbox,** so eventually ended up with about a dozen duplicate links after retrying!
> 2 votes

# Answer
If you do want to be able to provide a menu link to unpublished content there's a module for that - http://drupal.org/project/menu\_view\_unpublished
> 0 votes

---
Tags: routes
---


# Question
Title: how can I export table content to excel or csv
I am using drupal 6, I have created a table using

```
$tableHeader = array (
  array('data' => 'Ebooks','field' => 'etitle'),
  array('data' => 'Volumes','field' => 'Volume' ),
  array('data' => 'Chapter','field' => 'ctitle'),
  array('data' => 'Total Sale'),
);

$TableRows[] = array (
  l($row->etitle,$ebookinfo),
  $row->name,
  str_replace("&", "&" ,$row->ctitle ),
  round($row->totalsale,2).' $',
);

$output .= theme('table', $tableHeader, $TableRows);// get the pager
$output .= theme('pager', NULL, 5, 0);

```

How can I export it to MS Excel or CSV?

# Answer
Maybe the following code can help you.

```
$filename= 'export.csv';
drupal_set_header('Content-Type: text/csv');
drupal_set_header('Content-Disposition: attachment; filename=' . $filename);

```

You can add a function to send the row values, filename, and column title.

```
function export_to_excel_page($row_array, $filename, $column_titles) {
  drupal_set_header('Content-Type: text/csv');
  drupal_set_header('Content-Disposition: attachment; filename=' . $filename);

  foreach ($column_titles as $key => $value) {
    $keys[] = $value;
  }

  if ($keys) {
    print implode(',', $keys) ."\r\n";
    unset($keys);
  }

  foreach ($row_array as $key => $value) {
    $values[] =$value;
  }

  print implode(',', $values) ."\r\n";
  unset($values);

  drupal_exit();
}

```
> 7 votes

# Answer
Here's an updated function that should work for D7.

```
<?php
/**
 * Exports a CSV.
 *
 * @param array $variables
 *   An associative array of data containing "header" and "rows" keys.
 *   This is ready to be passed to theme_table(). See api.drupal.org/node/22950.
 *   Also contains the key "filename" specifying the filename.
 */
function _epc_standards_statistics_export_csv($variables) {
  drupal_add_http_header('Content-Type', 'text/csv; utf-8');
  drupal_add_http_header('Content-Disposition', 'attachment; filename=' . $variables['filename']);

  $output = '';
  $keys = array();
  foreach ($variables['header'] as $key => $value) {
    $keys[] = $value['data'];
  }
  if ($keys) {
    $output .= implode("\t", $keys) . "\n";
  }
  foreach ($variables['rows'] as $value) {
    $output .= implode("\t", $value) . "\n";
  }
  print $output;
  exit;
}
?>

```
> 5 votes

# Answer
If you are trying to export Nodes content, then you can able to use views\_data\_export module and export content using views !

> This module is designed to provide a way to export large amounts of data from views. It provides a display plugin that can rendered progressively in a batch. Style plugins are included that support exporting in the following types:
>
> CSV, Microsoft XLS, Microsoft DOC, Basic, TXT, XML.

If you want to export database tables data then you can consider data module.

> Data module helps you model, manage and query related sets of tables. It offers an administration interface and a low level API for manipulating tables and accessing their contents. Data module provides Views integration for displaying table data and Drupal search integration for searching table content.
> 1 votes

---
Tags: 6, importing-exporting
---


title: Duplicate taxonomy terms from view

text:
# Question
Title: Duplicate taxonomy terms from view
So I haven't yet been able to find a solution to this without using a preprocess function to check for duplicates or just using the 'tagadelic' module.. it'd be nice to get some closure.

How do I configure a (block) view to only display a list of terms for a vocab, each term displayed once (maybe followed by a number indicating how many times it's used) - even though the term may be used by multiple nodes? 'Distinct' doesn't do the job.. Fields 'Taxonomy:All terms' and 'Taxonomy: Term' both yield similar duplicate item when the term is reused by another node.

It's a fairly basic request, I'm sure I'm missing something but can't find a solid answer for dealing with it in views

# Answer
I think you're using a Node view instead of a Term (Taxonomy) view. So you're pulling in nodes and getting the tags associated with them. Since multiple nodes can have multiple tags, you're getting duplicates. I think the "Distinct" doesn't work because it's checking the Nodes to make sure they're distinct, not each field you add to the view.

So instead, try creating a view and choosing the Term type, instead of Node. I put together a very simple view without even using Distinct and I have no duplicated values, even though each term is definitely used on more than one node.

I don't know how you would do the count next to each term using Views, but I know the Advanced Taxonomy Blocks module does this.
> 5 votes

# Answer
Using aggregation is the answer!

Enable 'Use Aggregation' (hidden under the 'Other' section of 'Advanced'), then you can set fields to 'Group results together' and only one distinct term will display. Make sure you have removed all sorting criteria, as they cause conflicts. You can also use aggregation to display the number of results, by adding a duplicate field and setting the aggregation type to 'Count'.

Here's a good screencast about the whole process.
> 3 votes

# Answer
Are you creating a Term view, a Node view or something else? I was able to create a Term view which by default simply lists all terms (terms listed only once). You could then filter by vocab, etc.
> 2 votes

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


# Question
Title: how to pass variables from a views style-template to the row-template it invokes
I created a custom style-plugin for views, and a corresponding style-template (*my-style-template.tpl.php*). Similarly, I created a custom row-plugin for views and a corresponding row-template.

The style-template loops through the views-rows, and invokes the row-template on each row:

`print $row;`

**What I am trying to accomplish:**

The style-plugin defines certain settings in the $options variable, which gets passed to the style-template. The row-template needs access to some of these settings.

**My question:**

Is there a way to pass variables from my style-template to my row-template? For example, rather than invoking `print $row` from the style-template, is there some other way of invoking the row-template, which allows me to pass variables to the row-template?

Thanks very much!

# Answer
> 5 votes
You can't pass variables from one template file to another. That is not how things work.

However, a general rule is that every template file has a corresponding preprocess function for creating the variables available in the template.

So, you need to figure out what preprocess functions are being called. The Theme Developer module can help out with this. The theme.inc file lists all of the preprocess functions that the Views module uses.

With those, the standard way of handling things is something like

```
function mymodule_preprocess_views_view(&$variables) {
  $view = $variables['view'];
}

```

Once you have the `$view` object, you have everything you need. However, you often need to `dpm($view)` to figure out what is there and/or look at the default preprocess functions.

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


title: Private methods within a custom module

text:
# Question
Title: Private methods within a custom module
I am grouping some shared functionality that will be used across multiple template files within a custom theme. I would like certain methods within this module to be accessible to the theme (ie. public) and certain modules only available to the module itself (ie. private).

I understand that modules in Drupal aren't classes, but I hate the idea of the modules 'private' functions being available across the site - it seems to unnecessarily pollute the global namespace.

Is there a way to hide/make private certain methods/functions within a module?

# Answer
> 8 votes
> I understand that modules in Drupal aren't classes

Yes, however Drupal modules can certainly make use of classes, and many do.

You can use as many classes as you like.

Put your private functions in class definitions and access them that way.

Include the class file in your module.info file:

```
files[] = includes/MyModuleClass.class.php

```

You can use public and private variables in your class

```
public $public_var;
private $private_var;

```

Add private methods to your class

```
// Public
public function myPublicFunction(){
  $this->public_var = 'Public';
}

// Private
private function myPrivateFunction(){
  $this->private_var = 'Private';
}

```

Instantiate an object with

```
$options = array(); // example constructor params
$object = new MyModuleClass($options);

echo $object->public_var; // OK
echo $object->private_var; // Error

$object->myPublicFunction(); // OK
$object->myPrivateFunction(); // Error

```

More info in the PHP OO docs

# Answer
> 5 votes
In drupal-7 you can use classes and a common pattern is to implement everything that is not a drupal hook in a class.

In mymodule.info add:

```
files[] = includes/MyModuleHelper.inc

```

The drupal autoloader will then make this class available throughout the site. It isn't namespaced to the specific module, but the coding standard/convention of prefixing class names with the name of the module helps (not a specific standard). Note that only classes should be loaded this way.

The convention for preventing namespace clashes on module hook functions is to prefix them with the module name. e.g. mymodule\_hook\_form\_alter(..) or with an underscore to indicate that the function should be considered private. e.g. \_mymodule\_private\_function(). The drupal hook system entrenches mymodule\_hook\_form\_alter() naming by looking for specific function names for hooks.

---
Tags: 7
---


# Question
Title: Is it possible to redirect a user to avoid showing an AJAX batch processing error?
I'm trying to allow users to cancel their accounts without requiring e-mail confirmation as described in this question.

Currently, when I use the following code, the user account is cancelled properly, but the AJAX display shows a nasty error.

```
  else {
    // Cancel the account
    user_cancel($form_state['values'], $account->uid, $form_state['values']['user_cancel_method']);

```

I tried adding `drupal_goto('user/logout');` after `user_cancel()`, but this immediately logs the user out and the account is not cancelled. What I would like to do is cancel the account, log the user out, and somehow not display this error.

# Answer
> 0 votes
I found the cause of the error-- I had a custom rule that sent an e-mail to the admin when the account was cancelled. By deleting this rule, the error disappears and the user is logged out properly.

---
Tags: forms, ajax
---


# Question
Title: Change no results behavior of the result of a link generated from a view
I created a view that displays links to all of the terms in one of my vocabularies, which was easy enough, but now I am having trouble with what happens when one of those links is clicked. By default, it will show all content tagged with those terms, which is right, but I want to change the no results behavior when there is not content tagged with a term.

I'm confused as to where I would change the no results behavior for this, do I have to create a separate view, or is this to be done in the view of listing taxonomy terms?

# Answer
OK! So after hours of research and playing around in my views, I figured out that the problem was I was having the individual links go to the Taxonomy page for that term. I turned that off and re-wrote the results of each link to be the term: Name instead of that term's url alias. I got rid of all my URL aliases for the terms. I also added a second view that used the term and node relationship and a term: Name contextual filter, and added the custom no results behavior I wanted on that view.

In the end my URLs are not as clean since spaces and ampersands are converted to html escape characters, like "%26", but at least I have a no results behavior I want.
> 0 votes

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


title: Omega theme background color problems

text:
# Question
Title: Omega theme background color problems
What would be the best option for achieving following:

I need to have a background color blue under website and the body of the website (including all regions) would be white. Best for demonstrating would be to visit this site

> http://www.prevention.com/health/healthy-living/50-healthiest-eco-spas-america

By default `alpha-default-normal-12.css` contains rule for body `min-width: 960px`. I can solve it by changing body width to `width:960px` and adding `margin: 0 auto;`.

However after switching to fluid layout, width is taken from my `global.css` and it of course restricts layout to be fluid.

My question is what would be best way to achieve this without editing other css files. Or is it ok to edit them?

# Answer
You can edit `global.css` insted of editing `alpha_default_normal.css` so that changes will persists even if you changes your browser resolution. And according to me, set the width of the div in percentage... so it will automatically adjust to other screen resolutions. eg.

```
width:70%;
margin : 0 auto;

```
> 1 votes

---
Tags: 7, theming
---


# Question
Title: audiofile throwing error on file size even though settings changed
> An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (2 MB) that this server supports.

Every time try to upload 8mb mp3 I get the above error even though have changed settings in field edit from 2 MB to 20 MB and using unmanaged VPS with plenty of space and memory plus php.ini file increased.

# Answer
> 2 votes
If you don't have apache access control, you can try to add the `php.ini` settings into

```
ini_set('post_max_size','16M');

```

and

```
ini_set('upload_max_filesize','16M');

```

---
Tags: files
---


title: How do I run multiple cron jobs?

text:
# Question
Title: How do I run multiple cron jobs?
I want to run 4 cron jobs inside Drupal, in four different times.

How can I achieve that? Is there any module for that?

# Answer
> 8 votes
Try out the Ultimate Cron module.

> Runs cron jobs individually in parallel using configurable rules, pool management and load balancing. Multiple rules per cron job. Configuration per job (enable/disable, rules, etc.)

There is also the Elysia Cron module.

> Elysia Cron extends Drupal standard cron, allowing a fine grain control over each task and several ways to add custom cron jobs to your site.

# Answer
> 3 votes
Elysia Cron is the module you are looking for.

> Elysia Cron extends Drupal standard cron, allowing a fine grain control over each task and several ways to add custom cron jobs to your site.

---
Tags: 7, cron
---


# Question
Title: How to see the call stack of the functions being called in a page
I am beginning to work on a project that has quite a few modules(around 20) which I am not really familiar with. Is there a tool or suggestion, besides dpm-ing the function name, to detect the functions and modules being used in a random page?

# Answer
If you want to see the complete callstack of the functions being called, you should set up a debugging environment for doing so.

The quickest way to do is by downloading the Quickstart: Prebuilt Drupal Development Environment, which is a virtual machine copy of preconfigured ubuntu. The netbeans IDE is configured for debugging the Drupal code. It also has an display to look at the callstack at the bottom of the IDE, when in debug mode.

> What all is included in it:
>
> * Support for Drupal 7 and Drupal 6
> * Ubuntu Linux, Apache, MySQL, APC, XDebug, IMAP, UploadProgress
> * Firefox (with developer plugins) and Chrome
> * Drush, drush make, and custom drush commands
> * Install scripts for: Apache Solr, Aegir, Hudson, and Oracle
> * Netbeans and Eclipse, configured with XDebug
> * XHProf and Webgrind profilers. Emails logged as files
> * cvs, subversion, git, bazaar

You can have a look at its dedicated youtube channel for helpful screencasts.
> 1 votes

---
Tags: 7
---


# Question
Title: Migrating taxonomy terms when source is a separate table?
I'm writing a migrator for a now-unsupported WordPress plugin that used a single "attachments" table to store data ranging from thumbnails to musical genres. It looks like this:

```
mysql> describe attachment;
+----------------------+--------------+------+-----+---------+----------------+
| Field                | Type         | Null | Key | Default | Extra          |
+----------------------+--------------+------+-----+---------+----------------+
| attachment_id        | mediumint(7) | NO   | PRI | NULL    | auto_increment |
| attachment_target    | varchar(32)  | YES  |     | NULL    |                |
| attachment_target_id | mediumint(7) | YES  |     | 0       |                |
| attachment_type      | varchar(32)  | YES  |     | NULL    |                |
| attachment_info      | text         | YES  |     | NULL    |                |
+----------------------+--------------+------+-----+---------+----------------+
6 rows in set (0.00 sec)

```

`attachment_id` is just an ID, `attachment_target_id` will correspond to a NID from the "artist" content type I'm trying to import this into, `attachment_type` is either "genre" or "thumbnail" and `attachment_info` is the actual data contained in the row ("Disco", as an example for a genre.).

To import all the genres into a taxonomy field, it seems I would extend the class that imports all the artists from the other table, then using `$this->systemOfRecord = Migration::DESTINATION`, import each row into the existing nodes. Alas, given each row would be a new migration item, it seems this would overwrite the values.

I've also thought about adding a sub-query to my initial artist migration that returns a comma-separated list of genres; alas, I'm not sure how I'd do that with Drupal database abstraction layer.

Any help? Thanks!

# Answer
> 1 votes
The piece I was missing was GROUP\_CONCAT for the attachment table. My query now looks like this:

```
$query = Database::getConnection('default', 'wp')
       ->select('artists', 'a');
$query->join('attachment', 'at', 'a.artist_id = at.attachment_target_id');
$query->fields('a',
          array(
              'artist_id',
              'artist_name',
              'artist_publish_date',
              'artist_bio',
              'artist_record_company',
              'artist_social_links',
          )
        );
//Pull in genres.
$query->addExpression('GROUP_CONCAT(DISTINCT at.attachment_info)', 'genres');
$query->condition('at.attachment_target', 'artist');
$query->condition('at.attachment_type', 'genre');
$query->groupBy('a.artist_id');

```

---
Tags: taxonomy-terms, database, migrations
---


# Question
Title: Linking two different content types with Views
I was wondering if one can link up the data with views in this way:

I have two content types (current\_state & desired\_state), both have 3 fields (location, item, quantity)

How can I join the data, so that it displays in a table like:

```
location | item | desired_quantity | current_quantity

```

I separated those content types because people with other permissions are allowed to edit them.

# Answer
Suppose we have 2 **content types A and B** and want to display the content of content type B which have a **field reference** ie both A and B both have a common field. then:

1. We simply **add B** to the **Filter Criteria** of the **view**.
2. Add an **nid of A** using **Contextual Filter** in the **advance Options**.
3. Add a **relationship of B** in **reverse order** in the **relationship field** in **advance options**.
> 3 votes

# Answer
Follow these steps:

1. Install the module refernces
2. Create a new view.
3. In the filter criteria section add the *second* content type which you want to get displayed.
4. Then in contextual filter section,add the field node reference with which you have linked the *second* content type.
5. Lastly, add a relationship of second content type in reverse order to get the output.
> 1 votes

# Answer
You can make use of relationship in views tutorial i found here
> 0 votes

# Answer
One way to do this would be to use the References module to create a relationship between the two nodes:

1. After installing References, add a node reference to one of the content types that you can use to point to the other one.
2. When creating the View, add a Relationship to the Referenced node.
3. You will then be able to see fields from the Referenced nodes when you go to add a Field to the View.

So if, for example, you added a node reference field on the current\_quantity field to reference nodes of type desired\_quantity, you can then add a Relationship to related desired\_quantity nodes, then add a desired\_quantity field to your View of current\_quantity fields.
> 0 votes

# Answer
If you want to just display those two content types in the table (views) you don't need to relation between the content typs.

Just follow this steps:
1- Create new view (table display) .
2- Filter : content type (current\_state & desired\_state).
3- Add your fields.
4- In format section click on settings beside "table".
5- You can display two field (each one from different content type) by selecting the field in "COLUMN" . For example i have two fields (Car model,motor model) so from "COLUMN" of (motor model) select (car model) and they will display in one column.

6- Rename the first field (here in my example will rename the "Car model" field to "model").

Repeat step 5 and 6 for all fields you have in tour views.
> 0 votes

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


# Question
Title: How to display menu bar over slideshow block?
On my site, I am not able to show menu bar over the slider block in content. When I click the menu over the slide image, part of it disappear under the slide block.

When I click on the Services menu, it shows odd things. This problem is not persist on IE.

# Answer
You can increase the z-index property of your menu bar.

If this does not help, add the `position:absolute` property in CSS class; and also add the `position:relative` property to the container of the menu bar class.
> 2 votes

# Answer
Add the following CSS style to your CSS file.

```
    #views_slideshow_cycle_teaser_section_sunday_jam_image_slider-block {
       z-index: 0;
    }

```

Alternatively, try adding z-index to your dropdown class.

```
/* Navigation Style */
.dropdown {
  z-index: 1000;
}

```
> 0 votes

# Answer
By simply giving a css property to the menu.

1. giving position as absolute position:absolute;
2. giving a positive z index z-index:100;
> 0 votes

---
Tags: views
---


# Question
Title: Multiple nodes from a single content type?
I'm trying to create a single content type that displays data across multiple pages for a client. For example:

DOG content type with fields:

* List item
* Name (Title)
* Breed
* History (Body)
* Age
* Weight
* Height
* Previous Owner Name
* Previous Owner State
* Previous Owner Gender

and then I would I like these pages created automatically:

```
/dog/<name> (overview page that includes Name, Breed, History)
/dog/<name>/details (includes age, weight, height)
/dog/<name>/owner (includes previous owner name, state, gender)

```

Each page would have a submenu that links to the other pages. I can create the first overview page no problem, but how would I create the the second and third pages? Would I look at the URL pattern to find content matching the name?

# Answer
> 2 votes
As fas as i understand the question your requirement is to display those content on different pages. So it is better to create a three different views displaying the required data.For example you can create first view name dog1 having field name , breed and history and a second view name dog2 having field age weight and height and so on. And also you add submenu of those two pages link.

# Answer
> 1 votes
According to me one should create 3 different views and according to the requirement one can select the fields. Like let the first view be **dog1** having fields **Name, Breed, History**. second view be **dog2** having fields **age, weight, height**. third view be **dog3** having fields **previous owner name, state, gender**.

# Answer
> 1 votes
you can create thre diffrent views for your three pagess and regarding the display of views and sub menu on a common page u can go for node pages structure just design a page and add varient to it ..!! hope this would be helpful

# Answer
> 0 votes
you can create views with contexual filters and create menu path like dog/%/details(or owner), pass argument from cont.filter or, second method, read about hook\_menu and \_to\_arg() function..

# Answer
> 0 votes
Personally, I would prefer to solve this with tabs. JavaScript-based tabs are better for SEO because the entire node can be indexed at once. I also think that views adds unnecessary overhead if you use it to display only one node. See https://stackoverflow.com/questions/8550534/how-to-display-node-fields-in-tabs for instructions.

# Answer
> 0 votes
Try Node Embed it's used by www.whitehouse.gov and is cited

> Node Embed provides an input filter for CKEditor & FCKEditor integration allowing a content editor the ability to embed the rendering of nodes within the body/fields of another node.

Im not much of a programer but this seems to be a nice simple solution.

Best of luck!

# Answer
> 0 votes
Also consider using Ctools Page Manager \+ Display Suite. It's possible to build exactly what you have asked for using these 2 modules in combination: Page Manager to create the tabs and Display Suite to define the content display for each one. There's quite a lot to learn when using these modules but once you have become familiar with them you'll find there's tremendous flexibility available to you.

---
Tags: nodes
---


# Question
Title: How to format multi value field as a grid?
I created content type "photo gallery" that have multi-value field of images - for user convenience. I would like to create a view, that would show all that kind of galleries with their titles on one page, formatted as grid. How is this possible?

# Answer
> 4 votes
We had a *similar type* of requirement to display in a **grid/table layout** multiple *"Related"* nodes rendered with a particular *view mode (added with Display Suite)*, referenced through an Entity Reference field. We came up with the following module: Grid Field Formatter, which is now available with a stable release.

If you look at the screenshots on the project page or the description in the content you should be able to find that it would seem to correspond to the initial requirements you described.

Feel free to let us know if I missed something, this doesn't work, or if you would have any more questions, comments or issues related with this requirement or module, I would be glad to provide more information or explain in more details.

Any more feedback, reporting, testing, comments or questions would be highly appreciated. Thanks in advance!

---
Tags: 7, entities
---


# Question
Title: How can I add commerce product automatically when saving a node 'product display'
I want to create a default product reference with the price to zero, title to node\_title, sku to author\_node\_title. So each time I create a display product node type I haven't to fill the product reference info. If I created one display product node type -\> system will create one product and auto reference that product to display product node.

Thanks in advance!

# Answer
You could use a triggered rule using Rules on the event "After saving new content", creating the product entity, saving it and editing the product reference field after as well.
> 1 votes

# Answer
Why don't you do the opposite? When you create a product, a display is also created.

Commerce Bulk Product Creation
> 1 votes

# Answer
Just use the 'Auto Product Display' module which simply Product Display creation process by providing option the create it at the same time with Product creation.

> Features
>
> * Provide the Product Display creation form along with the Product creation form. User can fill that form to create Product Display at
> the same time with Product creation.
> * That form, which used to create Product Display, will be the same as the form when user try to create Product Display manually. So, If you have additional fields in your Product Display node type, those fields will also appear in the form.
> * If the product is referenced by only one Product Display, the Product Display content is displayed directly to the form, so it will be automatically updated when you save the product.
> * If the product is referenced by more than one Product Display, the referencing Product Displays will be displayed in list, so you can
> also update the Product Display by clicking the link from that list
> first.
> 0 votes

---
Tags: commerce
---


# Question
Title: User page tab with node edit, file upload image widget not working
On every user profile page i have a tab `My company` its a node edit form of content type `Company`. Here the code:

```
/**
 * Implementation of hook_menu().
 */
function feature_directory_section_menu(){
  $items = array();

  $items['user/%user/company'] = array(
    'title' => 'My company',
    'page callback' => 'feature_directory_section_user_company',
    'page arguments' => array(1),
    'access callback' => 'feature_directory_section_access_user_company',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => 10,
  );

  return $items;
}
//callback function
function feature_directory_section_user_company($account) {
  $uid = is_object($account) ? $account->uid : (int) $account;
  module_load_include('inc', 'node', 'node.pages');
  $output = '';
  $nid = db_query("SELECT n.nid FROM {node} n WHERE n.uid = :uid", array(':uid'=> $uid))->fetchField();

  if (is_numeric($nid)) {
    $output = node_page_edit(node_load($nid));
  } else {
    $output = t('You have no company. Please contact the site administrator.');
  }

  return $output;
}

```

Content type company has alot of fields, when i trying to edit node on `user/%user/company` page everything works fine, but one thing not working its ajax image upload or i can't delete image of my field(`field_company_gallery`) - its just a image field and u can upload unlimited count of images.

I get a lot of errors. If i go to `node/%nid/edit` i can manage images. but on user profile tab i can't.

Some `errors` are next:

```
Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'node_form' not found or invalid function name in drupal_retrieve_form() (line 798 of /home/www/buildit/htdocs/includes/form.inc).
Notice: Undefined index: #node in comment_form_node_form_alter() (line 1194 of /home/www/buildit/htdocs/modules/comment/comment.module).

Notice: Undefined index: field_company_gallery in file_ajax_upload() (line 271 of /home/www/buildit/htdocs/modules/file/file.module).
Notice: Undefined index: #suffix in file_ajax_upload() (line 280 of /home/www/buildit/htdocs/modules/file/file.module).

```

I guess i need to load all the modules with this function `module_load_include` or maybe not, i am stuck here.

# Answer
> 1 votes
Ok i found solution:

If your node form has a file upload widget, you should add this code to `hook_menu`.

```
'file path' => drupal_get_path('module', 'node'),
'file' => 'node.pages.inc',

```

---
Tags: 7, nodes, media
---


# Question
Title: How to let a user choose a role after their very first login?
I want to let users to select their role. There are 4 available roles (created by me as an admin) and the selection should be done **after** first login, so not on the registration form.

Can anyone help me to resolve this problem?

Note: the question let the user choose role upon registration is not exactly the same as my question here: that one contains "**... with their chosen role ...**", which is clearly something they entered on the registration form.

# Answer
I am not sure, but you can try somthing lke this: create form with Form API, on submission change value of Role array in user object. Example:

```
function MENUCALLBACKNAME($form, &$form_state, $user) {
 $form = array();
 $form['role'] = array(
  '#title' => t('select role'),
  '#type' => 'select',
  '#options' => //Array of your roles like array(id_of_role => t('Name of Role'), ...)
 );

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

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

 return $form;
}

function MENUCALLBACKNAME_submit($form, &$form_state) {
 $uid = $form_state['values']['uid'];
 $role = $form_state['values']['role'];

 $account = user_load($uid);

 $account->roles = $role;
 user_save($account);
 $form_state['redirect'] = 'SOME PATH';
}

```
> 0 votes

---
Tags: users
---


# Question
Title: How to use the Profiles2 module for Drupal
I would like to use the Profiles2 module for Drupal 7 to create user profiles that are separate from user accounts.

I'm trying to find out what is the url for editing the user profiles created with the Profiles2 module? For example:

```
    http://www.example.com/url-for-profile-editing-page

```

And what is the template file I have to modify in order to cutomize this page?

Does anyone know?

# Answer
The URL is dynamic, per-user and per-profile... for my site, it's something like the following: user/\[user-id\]/edit/\[profile2-machine-name\].

This would be different depending on

* the user whose profile is being edited
* the profile2 profile that is being edited for that user

Alternatively, of course, you might want to just go to your 'my account' page (at /user), click on 'Edit,' and then in the local menu tasks (under the edit tab), you can click on the profile2 profile you'd like to edit.

With regard to a template to change the page, I'm not sure if there is one. You could do a hook\_form\_alter() in a custom module to change the form values a bit, but you might want to look around the profile2 documentation or module itself to see how these pages are built.
> 1 votes

# Answer
if the above answer did'nt worked for you the url may vary to this

```
http://[site_addres]/profile-[profile_machine_name]/[User_ID]/edit

```

Example: http://mysite.com/profile-main/1/edit

happy coding
> 0 votes

---
Tags: 7, theming, users
---


title: scrollable views in drupal 6 is needed

text:
# Question
Title: scrollable views in drupal 6 is needed
I want to create a views with scrollable content. I've searched using google and found this : http://drupal.org/project/scrollable but it is abandoned.

Is there anything similar to it ? I use Drupal 6.

# Answer
You can download it from the "View all releases" link (near the bottom of the module's project page). That page contains a link to scrollable 6.x-1.x-dev.
> 1 votes

# Answer
Use the Scrollable Content module, select the style as Scrollable Content. Here is a quote about it (from the module's project page):

> ... provides a scrolling functionality for your content. Scrollable Content will give you a nice content slider preview of your site's nodes, and provides some display options.
>
> The basic use is via blocks page, you'll find a block called "Scrollable Content" and if you want more control & you know how to use Views, you should use the Views style for Scrollable Content.

Hope it will match your requirement.
> 1 votes

---
Tags: views
---