# Question
Title: Translation of months and days in Calendar Views Module
The Views Calendar template displays months and days, i.e. June, July, Monday, Tuesday, etc.

When someone changes from english to french, how can I tell it to display the months in a different language?

# Answer
You need to translate the strings. Go to Administration » Configuration » Regional and language » Translate interface, in the menu.

Then search for !month-name and !day-abbreviation and translate the strings to your language.

You can also download translations for the whole module on https://localize.drupal.org/translate/languages/fr

You can also use the Localization update module. From the UI of the module you can download and keep track of new translations for your downloaded modules.
> 1 votes

---
Tags: views, datetime, i18n-l10n
---


title: Drupal 7 CKeditor always saves Array

text:
# Question
Title: Drupal 7 CKeditor always saves Array
I am developing a custom module with some entities inside. I created a form to edit them and I would like to use CKEditor in one of the fields.

I can see and use the CKEditor, but when it's time to save, it always saves the value 'Array'. You can find the code I am using below:

```
$form['description'] = array(
        '#type' => 'text_format',
        '#format' => 'full_html',
        '#title' => t('Content'),
        '#default_value' => $entity->content,
        '#weight' =>2,
        '#required' => FALSE,
    );

```

I'd say CKEditor changes the value before sending the form POST but I am not sure.

Any ideas?

# Answer
Ok, that was easier than I thought. When using WYSIWYG editors you have to save the info differently.

For a normal textarea:

```
$entity->content = $form_state['values']['description']

```

For a WYSIWYG:

```
$entity->content = $form_state['values']['description']['value']

```
> 1 votes

---
Tags: 7, wysiwyg
---


title: Add product to cart programmatically

text:
# Question
Title: Add product to cart programmatically
I want to add a product to the cart programmatically on form submit

My code below works only for root, but in my site an anonymous user can access the cart and checkout, but when submitting form with non user=1 it returns `Your shopping cart is empty`.

In my submit function:

```
$uid = ($user->uid) ? $user->uid : 0;
    $order = commerce_order_new($uid, 'checkout_checkout');

// Save the order to get its ID.
    commerce_order_save($order);

// Load whatever product represents the item the customer will be
// paying for and create a line item for it.
    $product = commerce_product_load($product_id);

    $line_item = commerce_product_line_item_new($product, 1, $order->order_id);
// Save the line item to get its ID.
    commerce_line_item_save($line_item);
// Add the line item to the order using fago's rockin' wrapper.
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    $order_wrapper->commerce_line_items[] = $line_item;

// Save the order again to update its line item reference field.
    commerce_order_save($order);
    //commerce_cart_order_refresh($order);
//    ym(commerce_cart_order_id($uid));
    //commerce_cart_commerce_order_load($order);
    //ym(commerce_cart_order_is_cart($order));
    //commerce_cart_product_add($uid, $line_item);
    //commerce_cart_product_add_by_id($product_id);
    //$form_state['redirect'] = 'cart';
    drupal_goto('cart');

```

Why does it not work correctly with non root (uid=1)?

# Answer
You don't need to change the order directly, commerce\_cart\_product\_add do it for you.

Try this code:

Variables:

```
 $product : commerce product
 $quantity: number of elements

```

Code

```
 global $user;
 // Create new line item:
 $line_item = commerce_product_line_item_new($product, $quantity);

 // Add to current user's cart: if the user is not logged in ($user->uid: 0) Drupal Commerce manages the $_SESSION
 $line_item_added = commerce_cart_product_add($user->uid, $line_item);

 // If $line_item_added !== FALSE the line_item has been added OK!

```
> 15 votes

# Answer
You need to add commerce\_cart\_order\_session\_save() so anonymous user have their session to link the browser with cart content.
> 2 votes

# Answer
You should check Anonymous User permissions on the store components.

I was trying to do something similar for authenticated users, and got the same sort of problem. I then checked my permissions for the various components in the store, and when I made them available to authenticated users, my (mostly your) code started to work.
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: Why D7 Update Manager keeps sending emails?
This is very weird,

http://example.com/admin/reports/updates/settings

keeps sending emails to my email while the owner of **example.com** has changed his website from **Drupal 7** to **weebly**! I mean, the Drupal installation does not exist!

# Answer
Update Manager is a module that exists and works inside your installation. This means that Drupal installation **exists**. Maybe it is no longer connected to domain, but it is there, up and running. Delete it and you'll be all right. Or, if you want to keep it for backup / rollback purposes, ask your sysadmin to delete it's CRON rule. Without system's cron and visitors, nothing will trigger update checks and mail sending.
> 1 votes

---
Tags: updating
---


# Question
Title: Page not found error when using plus"+" sign in the url alias
I am trying to create a new simple node with url alias as `test+node`. when i save the node the page is not showing the node, the url changes as

`http://server/packets/test%2Bnode`

but it only shows the following error

`Page not found
The requested page "/packets/test%2Bnode" could not be found.`

Can anyone help me to fix this issue out...

# Answer
Drupal url do not accept the + sign, so it will convert the url into "space" so that only i t return page not found value. Please remove the + sign from url.
> 1 votes

# Answer
RFC 2396 defines how URI works. URL is just a special case of URI, so all rules apply. See section 2.2:

> 2.2. Reserved Characters
>
> Many URI include components consisting of or delimited by, certain special characters. These characters are called "reserved", since their usage within the URI component is limited to their reserved purpose. If the data for a URI component would conflict with the reserved purpose, then the conflicting data must be escaped before forming the URI.
>
> ```
>  reserved    = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
>                 "$" | ","
>
> ```
>
> The "reserved" syntax class above refers to those characters that are allowed within a URI, but which may not be allowed within a particular component of the generic URI syntax; they are used as delimiters of the components described in Section 3.

On the other hand, as you can read here:

> RFC 1738 (as modified by 2396 and 3986) defines the scheme (http:), authority (//server.example.com), and path (/myfile/mypage.htm) component, and does not define any special meaning for the + character. The HTML spec defines the query component to be mime type application/x-www-form-urlencoded which is defined as "replace spaces with + and other special characters as in RFC1738".

This means that when you use `+`, Drupal tries to prevent it from being interpreted as space, so it encodes it. And then it fails to recognize your alias properly.

Probably you should file a bugreport. Given that Drupal 8 is almost out of beta, I highly doubt it will be fixed, though. So consider simply avoiding special characters in your aliases.
> 1 votes

# Answer
Special characters and few other characters are not accepted by the url. So it encode these characters to a plane string by replacing space and + (and special characters) by other characters.

So better to enter alias that will remain simple or let drupal generate alias itself first and then edit it later nearly similar to your format.
> 0 votes

---
Tags: path-aliases
---


# Question
Title: I want to create a view with filters filters
I want to create a view with Better Exposed filters, filters exactly like in http://www.shopmgd.com/gold-jewellery.html. I am new to drupal, so somebody please help How can i do dis? I am using drupal 7.

# Answer
Not sure how to close this question but I'll add my comments as answer so that Jumma can approve and close it.

You need to expose your filters using the Better Exposed filters module, see this tutorial.

To place your exposed filter in one region and the result of the view in another region you need to expose your filters in a block. See this tutorial learn how to do that.
> 0 votes

---
Tags: views
---


title: How do I create a progress bar?

text:
# Question
Title: How do I create a progress bar?
I need to implement a progress bar using Drupal 7. This is the code I am actually using.

```
$form[$name][$name.'_enc'] = array(
  '#type' => 'submit',
  '#value' => t($name.' Enable'),
  // '#submit' => array('submit_'.$name.'_enc'),
  '#ajax' => array(
    'callback' => 'submit_'.$name.'_enc',
    'wrapper' => 'ajax-response-goes-here',
    'method' => 'replace',
    'effect' => 'fade',
    'progress' => array (
      'type' => 'bar',
      'message' => 'convert..',
      'url' => 'misc/progress.js',
      'interval' => '1500'
)

```

# Answer
> 3 votes
What you set as `['#ajax']['progress']['url']` is wrong: It's not the URL for a JavaScript file, but it's the callback path to use to determine how full the progress bar is. The menu callback should return a value that indicates if the operation has been completed, or it is completed at 10%, 20%, 50%, etc. Looking at the code contained in the progress.js file, I notice the value is expected to be between 0 and 100.

As side note, the value passed in `['#ajax']['progress']['message']` should be passed to `t()`.

# Answer
> 1 votes
Progress bar example:

```
$form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Import'),
    '#ajax' => array(
        'callback' => 'import_submit_callback',
        'wrapper' => 'import-form',
        'progress' => array(
            'type' => 'bar',
            'message' => t('Importing..'),
            'url' => 'import/progress', //url to fetch current progress percentage
            'interval' => '1000' //progress bar will refresh in 1 second
        )
    ),
);

```

Then create menu like this for url 'import/progress' :

```
$items['import/progress'] = array(
    'title' => t('Import progress'),
    'page callback' => 'import_progress',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
);

```

Then output json data indicating current status like this in that page callback function:

```
function import_progress() {
    $progress = array(
        'message' => t('Starting import...'),
        'percentage' => -1,
    );

    $completed_percentage = variable_get('import_status'); // calculate progress percentage here

    if($completed_percentage){
        $progress['message'] = t('Importing...');
        $progress['percentage'] = $completed_percentage ;
    }

    drupal_json_output($progress);
}

```

# Answer
> 0 votes
I have created one menu call back called `sales/progress` . Here i have called one function as in below

```
function sales_progress() {
   echo '{"percentage":"25","message":"Processing more..."}';
}

```

Here 25 is a static percentage value. You can customize percentage value & message text as your wish.

Periodically the above function will be called. And progress bar value will be updated. For more details reference link

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


title: wysiwyg box only shows html

text:
# Question
Title: wysiwyg box only shows html
I manage a small drupal (openAtrium) site at work that we use for project management. Last week the wysiwyg textbox used to edit content stopped working. By stopped working I mean html was displayed regardless of the setting chosen. At the time I was using tinyMCE although since this I have tried CKEditor and openwysiwyg to no avail. For some users this only only an irritation but for others, who relied on the wrodprocessor features of wysiwyg mode it's more of a show stopper.

I can't find any error messages or indeed any indication that something is wrong in drupal. In terms of browsers I do get one JS error which maybe related.

*Error: Syntax error, unrecognized expression: select:\[name="field\_oa\_section\[und\]"\], select:\[name="field\_oa\_space\_type\[und\]"\]*

All browsers I have tried (IE, Firefox, Chrome, Konqueror) are affected. Does anyone have any ideas? I can't find anyone else who has experienced similar problems.

Thanks.

# Answer
> 0 votes
The problem turned out to be multiple required versions of jquery. A jquery manaement module solved the problem.

---
Tags: wysiwyg, distributions
---


# Question
Title: Let images work properly online and offline (MAMP)
I just started using MAMP to work offline on my drupal-projects.

Because MAMP and working offline is new to me I started today with a test-website.

I installed MAMP, no problems.

I installed a new drupal 7.30 offline in MAMP, no problems. I imported the CKEDITOR and IMCE for uploading images, no problems.

I created two test-pages and imported in each page a image using CKEDITOR & IMCE, no problems.

After that i tried to upload my offline website online: backup DB, create a new DB online, imported the offline DB, FTP my files online, change the settings-file for connecting instructions DB.

After all those steps my website was showing up online and i could login. Everything seems to work fine.

But then when i clicked one of the testpages, i saw that my images where not showing up...

When i checked the sourcecode i saw something like this:

When i removed /sweetmorning, and saved that code, the image was showing up again.

What is the best practice to still work with CKEDITOR IMCE and let the images showup offline and also after i put the website online.

Any tips, links, info are welcome :-)

Thanks in advance, Kristof

# Answer
Part of your code did not go through; however I believe it's pretty clear that the issue is in image paths.

Check out Pathologic module, as it deals with exactly such issues:

> Pathologic is an input filter which can correct paths in links and images in your Drupal content in situations which would otherwise cause them to “break;” for example, if the URL of the site changes, or the content was moved to a different server. Pathologic can also solve the problem of missing images and broken links in your site’s RSS feeds. See more example use cases on the documentation page.
> 1 votes

# Answer
Here you can information how i fixed the problem:

http://sawmac.com/mamp/virtual/

This solution ensures that the name of the folder (project name - htdocs) in htdocs no longer used in the URL to the location of the photo. This creates NO problems when I place the website online.

With this i could move my offline project online and al the pictures showed up.

Probably a solution is also possible with Pathologic (and this looks like a good module, that can fix a lot of problems). So thank you again TOPSITEMAKERS.
> 0 votes

---
Tags: media, wysiwyg, files
---


title: Custom views handler without table

text:
# Question
Title: Custom views handler without table
This seemed easy at first but I'm losing my hair on this.

I simply want to add a custom view handler that uses no table.

I tried to do as views php proposed, `$data['views']['mycustomfield']` in `hook_views_data`, but still

> mycustomfield colum not found.

# Answer
Actually its easy. Just look at the implementation Views Global handlers which is available in views.views.inc.

Below is the example how you can add field handler without having a table,

1. Specify your custom handlers in hook\_views\_data like below,

```
/**
 * Implements hook_views_data().
 */
 function my_module_views_data() {
   $data['custom']['table']['group'] = t('Custom');
   $data['custom']['table']['join'] = array(
     // #global is a special flag which let's a table appear all the time.
     '#global' => array(),
   );

   $data['custom']['custom_handler'] = array(
     'title' => t('Custom Handler'),
     'help' => t('Custom Handler.'),
     'field' => array(
       'handler' => 'views_handler_custom_handler',
     ),
   );

   return $data;
}

```
2. Create a inc file for your handler an put your logic there. something like below Here the file name would be views\_handler\_custom\_handler.inc

```
/**
 * A handler to provide a field that is completely custom by the administrator.
 *
 * @ingroup views_field_handlers
 */
 class views_handler_custom_handler extends views_handler_field {
   function query() {
     // do nothing -- to override the parent query.
   }

   function option_definition() {
     $options = parent::option_definition();

     // Override the alter text option to always alter the text.
     $options['alter']['contains']['alter_text'] = array('default' => TRUE);
     return $options;
   }

   function options_form(&$form, &$form_state) {
     parent::options_form($form, $form_state);

     // Remove the checkbox
     unset($form['alter']['alter_text']);
     unset($form['alter']['text']['#dependency']);
     unset($form['alter']['text']['#process']);
   }

   function render($values) {
     // Render your content.
     return 'Sample';
   }
}

```
3. Specify this new handler file in your module's info file
4. Clear the caches

Now the new field handler will be there in the field list.
> 26 votes

# Answer
To be complete: you would need to add hook\_views\_api too

```
function my_module_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'my_module'),
  );
}

```
> 1 votes

---
Tags: 7, views
---


# Question
Title: How can I create a content type in a custom module?
I would like to create a content type called announcements for a module that I'm creating, but haven't found much to make this work. I tried this:

```
    function srl_dash_install() {
    //drupal_install_schema('srl_contactics_monthly_apps');
    $t = get_t(); // runs in both the installer and runtime

  /* Create and save a new content object */
  $announcement = 'announcement'; // machine name of the content type

  // define the node type
  $announcements = array(
    'type' => $announcement,
    'name' => $t('Announcement'),// Display name of the content type
    'base' => 'node_content',
    'announcement' => $t('Announcement'),
    'description' => $t('Add Contactics Announcements.'),
    'custom' => TRUE,
  );

  // set other node defaults not declared above
  $content_type = node_type_set_defaults($announcements);

  // add the body field
  node_add_body_field($content_type, $t('Body'));

  // save the content type
  node_type_save($content_type);
}

```

but I'm not sure how to make this hook run.

Any help would be appreciated.

# Answer
> 0 votes
That hook is only run when the module is installed, maybe you added the hook during development of your module and when it was enabled?

The hook should be placed in a file called srl\_dash.install.

Then disable your module and uninstall it, then enable it again. Now the hook will run.

# Answer
> 0 votes
If you are using Drupal 6 then please follow the link https://www.drupal.org/node/231019. You have to properly place the functions in proper files.

* In Module file create `hook_node_info`, `hook_perm`, `hook_access`.
* To add new CCK fields to the newly created content type follow here.

---
Tags: 6
---


# Question
Title: How to display programmaticaly default user picture?
I want to display programmatically default user picture if the user is not uploaded any. For that I have written code php code but its displaying user uploaded user picture correctly but not the one default when user doesn't upload his/her own. How to do that? help me.

```
$user = user_load($user->uid);
$account = user_load($user->uid);
print theme(
    'image_style',
    array( 'account' =>$user,
      'style_name' => 'x-small',
     // 'path' =>!empty($user->picture->uri)?$user->picture->uri:variable_get('user_picture_default'),
      'path' =>!empty($user->picture->uri)?$user->picture->uri:variable_get('user_picture_default',''),
      'attributes' => array(
        'class' => 'avatar'
      )
    )
  );

```

# Answer
> 1 votes
Why programmatically drupal provide this functionality out of the box. Go to Configuration \>\> People \>\> Account Settings. Under personalisation section you can provide the url of the default picture and can select the image style to use for the picture.

# Answer
> 2 votes
Its very straight forward. If you want to add a default picture then go ahead and add the picture from the admin page as the other answer suggested. Programmatically, The default picture is loaded via the variable `user_picture_default`. So you can do,

```
$user = user_load($uid);
print theme('image_style', array('path' => $user->picture->uri, 'style_name' => '<image-style>'));

if (!empty($user->picture)) {
  print theme('image_style', array('path' => $user->picture->uri, 'style_name' => 'CUSTOM_STYLE'));
}
else {
  $custom_default_image_path = 'public://default_image.png';
  print theme('image_style', array('path' => variable_get('user_picture_default', $custom_default_image_path), 'style_name' => 'CUSTOM_STYLE'));
}

```

However, you can also make the default image theme dependent/independent via the hook

# Answer
> 0 votes
First you need to assign a default picture path in Account settings in the drupal admin as described by Mutant Mahesh .

Then you can use this code to print picture anywhere in your code

```
<?php
global $user;
  $user = user_load($user->uid);
  print theme('user_picture', array('account' =>$user));
?>

```

Hope it will work for you.

---
Tags: users
---


title: webform date popup format

text:
# Question
Title: webform date popup format
I have a webform with a popop date the problem is the date in the textbox is shown in the format

```
2014-7-30

```

it need it to be

30/7/2014

how can I change this?

# Answer
> -1 votes
I use webform 7.x-3.20 it doesn't give text box option for date field rather it show select list except for year. If in your case it showing textbox make sure the configuration is as followed.

You can create new date format under date and time settings, Go to `admin/config/regional/date-time/formats`

Add new format in the form `j/n/Y` it will show date as `30/7/2014`.

**Under webform date field setting choose the Default value timezone to "Website timezone"**

**P.S** If you want to reorder select boxes then see: Re-ordering the elements of a Drupal Webform Datepicker

---
Tags: webforms, datetime
---


# Question
Title: Pathauto: Custom punctuation replacement
Instead of having Pathauto replace punctuation in the path alias with a default separator ( dash for example ), or remove it, can we somehow specify a custom input to replace with?

For example, ***"*** could be replaced with ***inches***

# Answer
> 1 votes
You can use `hook_pathauto_alias_alter()`.

---
Tags: path-aliases
---


title: Customising the views content template

text:
# Question
Title: Customising the views content template
This is all fairly new to me so I hope i've worded the question correctly.

So I have created a view which outputs a list of news posts, which you can then click on a news post and view the contents of that post. However I've modified the styling of the listings page using the different fields etc. Now I would like to modify the content of the selected news post.

I've created a new template in my templates directory called `'views-views.tpl.php'` but that seems to override the content for the listing view landing page as well as the content.

Do I need to use a different template?

If someone could point me in the right direction it would be mostly appreciated.

Thanks.

# Answer
> 0 votes
Step:1 : You have to choose the format Step:1 For this Image

Step:2: Click the **Advanced** link and go to theme:information Step:2 For this Image

Step:3 Choose the style output templete like : Step:3 For this Image

Step:4 Add tpl file and write your css and all. Rescan the templete files and save it..

I choose the style format like HTML List. So I Can wrote codings like this format:Codings

---
Tags: views
---


# Question
Title: feedback for duplicate registration attempt
if a user tries to register with a username or email that is already in use, there is no feedback telling them this, it just highlights the form field red, this is quite a bad UX.

How can I add translatable text to the effect of "that email is already in use, have you forgotten your password?" ?

I would really like to do this without adding a module.

Here you can see there is validation feedback, but it's not relevant, as my username meets its criteria, it should highlight the duplicate account problem. The user would just get frustrated at this point as they are told to do something which makes no difference.

# Answer
> 0 votes
It sounds like your theme is missing from the page template, which will usually show a description of the error at the top of the page.

I know you said no modules but I would recommend looking at Username originality AJAX check which is very small and does an ajax lookup before the form is submitted.

---
Tags: 7, users
---


title: How to change category for Panels IPE

text:
# Question
Title: How to change category for Panels IPE
How would I change the category from "Fielded panes" in Panels IPE to something else?

I can accomplish this through the following code:

```
function template_preprocess_panels_add_content_modal(&$vars) {
  $i = 0;
  foreach($vars['categories_array'] as $item) {
    $new_item = str_replace("Fielded panes", "New Content", $item);
    $vars['categories_array'][$i] = $new_item;
    $i++;
  }
}

```

However, I'd like to find a more elegant solution by altering the category name in a function that runs before **template\_preprocess\_panels\_add\_content\_modal()**.

# Answer
> 0 votes
Have a look at template\_preprocess\_panels\_add\_content\_modal() and `$vars['categories']`. You should be able to override the category names there.

**Edit:**

Ahh, yes, I forgot about hook\_ctools\_content\_subtype\_alter(). That's more elegant :)

From the documentation:

> This hook can be used to add things like 'render last' or change icons or categories or to rename content on specific sites.

In the example below the category "Fielded panes" is changed to "New category name".

```
/**
 * Implements hook_ctools_content_subtype_alter().
 */
function MYMODULE_ctools_content_subtype_alter(&$subtype, &$plugin) {
  if ($subtype['category'] == 'Fielded panes') {
    $subtype['category'] = 'New category name';
  }
}

```

# Answer
> 0 votes
After some research, I discovered that this can easily be accomplished via hook\_ctools\_content\_subtype\_alter().

```
  /**
  * Implements hook_ctools_content_subtype_alter().
  */
  function MYMODULE_ctools_content_subtype_alter(&$subtype, &$plugin) {
    if ($subtype['category'] == 'Fielded panes') {
      $subtype['category'] = 'New category name';
    }
  }

```

I also discovered that I can alter the title and the icon by doing something like this:

```
/**
* Implements hook_ctools_content_subtype_alter().
*/
function MYMODULE_ctools_content_subtype_alter(&$subtype, &$plugin) {
  // Change title and icon for rich_text Fielded panel pane content
  if (isset($subtype['bundle']) && $subtype['bundle'] == 'rich_text') {
    $subtype['title'] = 'Custom Content';
    $subtype['path'] = 'sites/default/files/ctools/icons';
    $subtype['icon'] = 'content.png';
  }
}

```

---
Tags: panels, chaos-tool-suite
---


# Question
Title: Auto-collapsing fieldsets on user_profile_form
I am following these guides:
Customize the User Edit page in Drupal 7: https://www.drupal.org/node/2279959
Collapsing default fieldsets (Drupal 6): https://www.drupal.org/node/733198

Basically, I just want to make all of the fieldsets on the user\_profile\_form (e.g. /user/1/edit) collapsed by default.

Here is what I've got so far, but it doesn't work - page never finishes loading (I have changed THEMENAME to the name of my theme). This still doesn't work however...

```
function THEMENAME_theme() {
  return array(
    // The form ID.
    'user_profile_form' => array(
      // Forms always take the form argument.
      'arguments' => array('form' => NULL),
      'render element' => 'form',
    ),
  );
}

function THEMENAME_user_profile_form($form) {
  //Create array to return
  $form_elements = element_children($form);
  foreach ($form_elements as $element) {
    //Identify fieldsets and collapse them
    if ($form[$element]['#type'] == 'fieldset') {
      $form[$element]['#collapsible'] = TRUE;
      $form[$element]['#collapsed']   = TRUE;
    }
  }
  return drupal_render($form);
}

```

I have a feeling that there is something that I am missing regarding converting this Drupal 6 code to work with Drupal 7 but I am lost. I have about 30 tabs open and have searched extensively on stackexchange, drupal.org, etc. to no avail. Please help!

EDIT: here is the code for a small custom module I wrote to easily test this (no need to clear the cache every time like with template.php)

```
function collapse_form_alter(&$form, &$form_state, $form_id)
{
    if ($form_id == "user_profile_form")
    {
        $form['edit-picture']['#collapsible'] = true;
        $form['edit-picture']['#collapsed'] = true;
       $form['edit-timezone']['#collapsible'] = true;
        $form['edit-timezone']['#collapsed'] = true;
        // test to make sure module and hook_form_alter is working
        $form['#attributes']['class'][] = 'foo7';
    }
}

```

I should add that I've tried dashes and underscores, e.g. edit\_picture and edit-picture.

# Answer
> 0 votes
OK I managed to figure out an answer to this. Thanks to Scott Joudry for helping me through this and giving me a lot of ideas. Eventually I got to this code, written in a custom module (this is the entire contents of my 'collapse.module' file):

```
<?php
// we use MODULENAME_form_FORMID_alter to restrict it to the specific form
// this helps reduce processing time, as Drupal will ignore this on any other forms
function collapse_form_user_profile_form_alter(&$form, &$form_state, $form_id)
{
    // can't hurt to double-check that we're on the right form
    if ($form_id == "user_profile_form")
    {
         // Note that the ID of the fieldset is "picture" not "edit-picture" like
         // the fieldset's HTML ID - you may have to guess-and-check to find it.
         // Usueally you remove the "edit-" part of the HTML ID, and replace any
         // spaces with underscores, i.e. "edit-signature-settings"
         // becomes "signature_sttings"
         // Only these two lines are needed if the fieldset you are trying
         // to collapse is not collapsible by default, such as the user picture.
         $form['picture']['#collapsible'] = true;
         $form['picture']['#collapsed'] = true;

         // A third line is needed if the fieldset you are trying to collapse
         // is collapsible, but is uncollapsed by default - for example, the timezone.
         // Note that depending on the fieldset, this third line MAY OR MAY NOT
         // be needed! Start without it, and if the fieldset isn't collapsing,
         // add the third line to force the addition of the 'collapsed' class.
         $form['timezone']['#collapsible'] = true;
         $form['timezone']['#collapsed'] = true;
         $form['timezone']['#attributes']['class'][] = 'collapsed';

         // Implement an "after_build" to put these changes into the form.
         // The array is just which function you are telling it to run.
        $form['#after_build'] = array('collapse_fieldsets');

         // Test to make sure module and hook_form_alter is working
         // and the page hasn't been cached - very easy to check if the
         // main form's class has been updated each time you refresh.
         // Just change the version number each time you upload this .module file.
        $form['#attributes']['class'][] = 'version-5';
    }
}

// this function renders the form content
function collapse_fieldsets($form_element, &$form_state)
{
        // Note that this is the same as above, but with $form_element instead of $form.
        // Everything you put in the above code must be duplicated here.
        $form_element['picture']['#collapsible'] = true;
        $form_element['picture']['#collapsed'] = true;

        $form_element['timezone']['#collapsible'] = true;
        $form_element['timezone']['#collapsed'] = true;
        $form_element['timezone']['#attributes']['class'][] = 'collapsed';

        return $form_element;
}

```

# Answer
> 1 votes
You want to use hook\_form\_alter here.

```
THEME_form_alter(&$form, &$form_state, $form_id)
{
    if ($form_id == "user_profile_form")
    {
        $form["FIELDSET"]["#collapsible"] = true;
        $form["FIELDSET"]["#collapsed"] = true;
    }
}

```

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


# Question
Title: Force a page to be rendered in admin theme (overlay mode)
Is there a way to force a page to be rendered in admin theme, Like pages that their path begins with 'admin/'?

# Answer
> 4 votes
There is a contrib module ThemeKey that

> allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules. In combination with Drupal's theme inheritance and ThemeKey Properties you can easily achieve features like:
>
> individually-styled channels a front-page / "splash" screen a date/time-selected Christmas theme mobile themes for different auto-detected mobile devices special themes for "limited" or "old" browsers content, user, or role -specific themes indicating your environment (production, staging, testing, sandbox, … ) testing your redesign safely on a live server

Check also related question here.

# Answer
> 14 votes
You can also do this by making a custom module.

**Method 1**

Use this if you want to theme an existing page, based on Drupal's internal path (aka path source). This example uses hook\_custom\_theme.

```
<?php
function MYMODULE_custom_theme() {
  // match node/1
  if (arg(0) == 'node' && arg(1) == '1') {
    return variable_get('admin_theme');
  }
}

```

**Method 2**

Use this if you want to theme an existing page, based on URL path (aka path alias). This example also uses hook\_custom\_theme.

```
<?php
function MYMODULE_custom_theme() {
  // get arguments
  $arg = explode('/', substr(request_uri(), strlen(base_path())));
  // match {wildcard}/path
  // Using strpos as $arg[1] may end up having stuff like so ?order=title&sort=asc
  if (isset($arg[1]) && strpos($arg[1], 'path') !== false && !isset($arg[2])) {
    return variable_get('admin_theme');
  }
}

```

**Method 3**

Use this if you want to theme and create a page. This example uses hook\_menu. To learn more, take a look at another great article on hook\_menu.

```
<?php
function MYMODULE_menu() {
  $items = array();

  // match some/path
  $output['some/path'] = array(
    'title' => t('Page Title'),
    'page callback' => 'MYMODULE_page',
    'theme callback' => 'variable_get',
    'theme arguments' => array('admin_theme'),
  )
}

function MYMODULE_page() {
  return 'Hello world.';
}

```

# Answer
> 7 votes
If you are a module developer, you can use hook\_admin\_paths to define which paths are to be rendered with the administration theme.

# Answer
> 4 votes
Simply give the page a path beginning with admin: 'admin/mypage'

# Answer
> 1 votes
1. This functionality is now in D7 core.
2. There's a module that effectively exposes "hook\_admin\_paths" to the UI: https://drupal.org/project/admin\_theme

---
Tags: 7, theming
---


title: How to theme Commerce Customer profile?

text:
# Question
Title: How to theme Commerce Customer profile?
In a Commerce project, I added some custom fields to the customer profile, and I’m using Addressbook. The customer profile is now displayed in the *address book tab* of each user page.

I need to change the display of this address book. Until now :

* I changed basic display settings of the fields in the "Manage Display" form, and this had a surprising effect : setting a label as hidden removed completely the default theming of all the view.
* I tried to use `hook_field_formatter_info()` and `hook_field_formatter_view()` as per that Clive answer : this is great but it alters only the native AddressFields, not the custom fields of the customer profile.
* In the *Commerce Addressbook Defaults view*, source of the display, there's only one field in the view : *Commerce Customer Profile: Rendered Commerce Customer profile*.

I could call the fields one by one in the view, but what if I want to alter directly the **Rendered Commerce Customer profile** field ? Where is it built, and how can I theme or alter it?

# Answer
> 1 votes
Generally speaking you can theme field output like other Drupal output. If you use devel\_themer\* you can normally see the template used and suggestions available. By default fields use `theme('field')` which by default has a number of suggestions:

```
// Add specific suggestions that can override the default implementation.
$variables['theme_hook_suggestions'] = array(
  'field__' . $element['#field_type'],
  'field__' . $element['#field_name'],
  'field__' . $element['#bundle'],
  'field__' . $element['#field_name'] . '__' . $element['#bundle'],
);

```

For example, the first suggestion allows you to override the template/function used for a particular type of field. In this case we could create `MYTHEME_field__addressfield()` and it would be used for addressfields only. You can add your own suggestions as well.

There are some field API routes as well though. You can use contrib or custom formatters (some of which in turn provide their own theme functions that you can override). Formatters can have settings that might give the results you want. You can add extra settings with a contrib module if you want to extend a formatter. There are also some field-specific hooks that might be useful:

* As you say devel\_themer is heavy. It massively changes the markup, and often messes up your JS. I only ever switch it on when I need it and then switch if off immediately afterwards, YMMV!

---
Tags: theming, commerce, users
---


# Question
Title: The update.php doesn't want to run it's complete course
I updated core Drupal (D7.14) and all seems to running perfectly. Only some updates for the database are required. So I run the update.php and I get through the first stages and I can see the pending updates when I am on the Review updates page. But when I continue (press the button). It seems to get stuck. I don't get to next screen, it just keeps on loading. In one browser I get a blank screen but that's it.

# Answer
> 1 votes
Happened to me too. One update took a lot of memory on my shared host. I tried it several times during the Day until I got Lucky. Maybe a glance in the Apache log Files will help?

# Answer
> 0 votes
If you have multi-sites running off one installation, make sure you are running the update.php on the original site, as this same behaviour seems to happen if you are trying to run the script from one of the other sites.

---
Tags: 7, database, updating
---


# Question
Title: Resolve the error "An illegal choice has been detected..."
I have written code like below and all works fine, but while submitting the form I get the error below. I am trying to filter the second dropdown based on the first drop down selection.

> An illegal choice has been detected. Please contact the site administrator.

How do I overcome that error?

```
function dynamic_location_dropdown_form_alter(&$form, $form_state, $form_id) {
  if($form_id == 'product_node_form') {

  $location_options = array();

  if(isset($form['field_destination']['und']['#default_value'][0])) {
    $destination = $form['field_destination']['und']['#default_value'][0];
  }
  else {
    $destination = 0;
  }

  $location_options = dynamic_location_dropdown_locations($destination);

  $form['field_destination']['und']['#ajax'] = array(
    'event' => 'change',
    'wrapper' => 'squadron-wrapper',
    'callback' => 'dynamic_location_dropdown_ajax_callback',
    'method' => 'replace',
  );
  $form['field_product_location']['#validated'] = true;
  $form['field_product_location']['und']['#prefix'] = '<div id="squadron-wrapper">';
  $form['field_product_location']['und']['#suffix'] = '</div>';
  $form['field_product_location']['und']['#options'] = $location_options;
  }
}

function dynamic_location_dropdown_ajax_callback($form, $form_state) {
  $country_id = $form['field_destination']['und']['#value'];
  $form['field_product_location']['#validated'] = true;
  $form['field_product_location']['und']['#options'] =  dynamic_location_dropdown_locations($country_id);

  return $form['field_product_location'];
}

function dynamic_location_dropdown_locations($destination_id) {
  $nodes = array();
  $nodes[''] = '- None -';
  if($destination_id != '') {
    $select = db_query("
      SELECT node.title AS node_title, node.nid AS nid, node.created AS node_created
      FROM {node} node
      LEFT JOIN {field_data_field_location_country} field_data_field_location_country
      ON node.nid = field_data_field_location_country.entity_id
      AND (field_data_field_location_country.entity_type = 'node'
      AND field_data_field_location_country.deleted = '0')
      WHERE (( (node.status = '1')
      AND (node.type IN  ('location'))
      AND (field_data_field_location_country.field_location_country_nid = $destination_id)))
      ORDER BY node_title ASC
    ");
    $nodes[''] = '- None -';
    foreach ($select as $node) {
      $nodes[$node->nid] = $node->node_title;
    }
  }

  return $nodes;
}

```

# Answer
> 8 votes
The problem is most likely because of a requirement for FAPI AJAX which is documented in AJAX Forms in Drupal 7, though can be easily missed.

> Changes to the form must only be made in the form builder function (ajax\_example\_autocheckboxes() in the example here), or validation will fail. The callback function must not alter the form or any other state.

The fact that you're setting the form element `[#options]` in the AJAX callback is definitely a problem. The AJAX callback should only return the array or HTML to be printed, not change the form. That callback should only contain the `return` statement.

The changes to your form should be made in the form\_alter. Also, you should use the form\_state array to check whether a value has been selected for your first dropdown. This will be updated during an AJAX request.

I recommend looking at the examples module, as well as these pages for more information on AJAX in FAPI. It can definitely be tricky.

# Answer
> 3 votes
The below method can be used to neglect errors only for those fields into which value has been added through ajax
As per the code given below you can enter the field element which gives error so that the value changed in the second dropdown due to change in the first dropdown due to the use of ajax will not show an error.

```
/**
 * Custom Form Validation.
 * Removes all form validation errors caused by a 'foo][bar' form element.
 */
function my_module_form_validate($form, &$form_state) {
  $errors = form_get_errors();
  if ($errors) {
    // Clear errors.
    form_clear_error();
    // Clear error messages.
    $error_messages = drupal_get_messages('error');
    // Initialize an array where removed error messages are stored.
    $removed_messages = array();

// Remove all errors originated by the 'foo][bar' element.
    foreach ($errors as $name => $error_message) {
      if ($name == 'foo][bar') {
        $removed_messages[] = $error_message;
        unset($errors[$name]);
      }
    }

// Reinstate remaining errors.
    foreach ($errors as $name => $error) {
      form_set_error($name, $error);
      // form_set_error() calls drupal_set_message(), so we have to filter out
      // these from the error messages as well.
      $removed_messages[] = $error;
    }

// Reinstate remaining error messages (which, at this point, are messages that
    // were originated outside of the validation process).
    foreach (array_diff($error_messages['error'], $removed_messages) as $message) {
      drupal_set_message($message, 'error');
    }
  }
}

```

# Answer
> 1 votes
This seems to be a core bug https://www.drupal.org/node/153774 and solutions mentioned here actually cause more problems.

When #ajax is used for a select element, if more than one options is selected "illegal choice error" will be generated. But why? After a bit of investigation it turned out that when #ajax is enabled it causes the select element to submit values like array(200,250) instead of array(200 =\> 200, 250 =\> 250) So it causes problem with options validation code inside \_form\_validate function and it no longer can check selected options against available options, here is the code : This happens only when more than one option is selected and #ajax is used. The fix is to correct the submitted value before validation

I've written a module to automatically workaround this bug, it may not work in all cases but it's a clear workaround you can use it as a starting point.

https://www.drupal.org/sandbox/sinasalek/2312751

---
Tags: 7, forms
---


# Question
Title: How to hide my hook_menu items from the navigation menu?
I've got a custom module which I use to define some urls that are used for a json api. I don't want them to show up in the Navigation menu. How do I change my hook\_menu configuration so these urls are excluded from the menu?

Here is an example of two of my menu items that I want to hide, and a third one I would like to be visible:

```
$items['mymodule/1/login'] = array(
    'page callback' => 'mymodule_login',
    'access callback' => TRUE,
);
$items['mymodule/1/signup'] = array(
    'page callback' => 'mymodule_signup',
    'access callback' => TRUE,
);
$items['mymodule_bulkupload'] = array(
    'title' => 'Bulk Upload',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymoduleapi_form_bulkupload'),
    'access callback' => 'mymoduleapi_user_is_mymodule_owner',
);

```

I end up getting a bunch of empty items in my Nav menu. I would like to be able to hide those api menu items.

How do I control that from within hook\_menu?

# Answer
> 4 votes
I think what you need is MENU\_CALLBACK in 'type.

It's for hidden items like API calls that don't want to go in menus

https://api.drupal.org/api/drupal/includes%21menu.inc/constant/MENU\_CALLBACK/7

---
Tags: 7, routes
---


title: Google Analytics Drupal browser

text:
# Question
Title: Google Analytics Drupal browser
"Drupal" is showing in our Google Analytics as the top browser. We're using Drupal 7 with the google\_analytics module. What could cause this?

# Answer
Do you use many modal frames or many functions like `$result = drupal_http_request($url, $options);` on your site?

In both these cases the user agent is set to "Drupal".
> 1 votes

---
Tags: 7, google-analytics
---


title: Override Module for mobile users

text:
# Question
Title: Override Module for mobile users
I'm using Manual Crop, which is not functional on a mobile phone (you can't drag the resize tool), so I'd like to prevent the init on a mobile device.

Any advice on how to override a module for smaller screen widths?

I could set the mobile user to not have access via Mobile Tools, but I'm not confident that module will work for D7, plus it may be overkill for my needs.

Thoughts? Is this even possible?

Kate H

# Answer
I can think of two approaches.

**The quick(er) dirty way:**

Hide it with CSS!

Problems:

* I assume you're using seven or some other admin theme that you can't edit so all this will need to go in a module with `drupal_add_js()` or some other method for inserting JS.
* After we determine if the visitor is on a touch device, we can't hide the element with simple jQuery because the element is dynamically inserted.

First, we'll need a way for JS to add CSS to the page. This function will let us do that:

```
function addCss(cssCode) {
  var styleElement = document.createElement("style");
  styleElement.type = "text/css";
  if (styleElement.styleSheet) {
    styleElement.styleSheet.cssText = cssCode;
  } else {
    styleElement.appendChild(document.createTextNode(cssCode));
  }
  document.getElementsByTagName("head")[0].appendChild(styleElement);
}

```

Then determine if the current visitor is on a touch device:

```
var is_touch_device = 'ontouchstart' in document.documentElement;

```

If so, add some CSS to page that hides the "Crop" button.

```
if (is_touch_device) {
  addCss('.manualcrop-style-button-holder {display: none;}');
}

```

**The harder way:**
Somehow determine if the current visitor is on a touch device via PHP. I don't have a foolproof method for this, but you can look into something like php-mobile-detect.

If you can determine that the visitor is on a touch device in PHP, you can return the `manualcrop_croptool_process()` function early. (Line 151 of `manualcrop.helpers.inc`). Of course, that will require filing an issue with module maintainer and providing a patch of those changes.
> 0 votes

---
Tags: mobile-tools
---


title: Add class to sub-taxonomy terms

text:
# Question
Title: Add class to sub-taxonomy terms
Is it possible to add a class to my subterms in a taxonomy vocabulary? So I can style theme and indent them. This is my taxonomy vocabulary:

And in my front-end it looks like this:

I'd like to `remove the "-"` and give them a `padding-left`. But how can I do this?

I'm showing this as a term reference in my registration form shown as checkboxes.

# Answer
> 2 votes
If you're using them in a form you could use this module to have much more control of your checkboxes tree and you will have different classes for parents and children:

https://www.drupal.org/project/term\_reference\_tree

1. Enable the Term Reference Tree module.
2. Go to the Manage Fields tab of any fieldable entity (such as a content type, taxonomy term, or user.
3. Add a new field with a type of Term Reference.
4. In the widget select box, select Term reference tree.

---
Tags: theming, taxonomy-terms
---


# Question
Title: Configuring an Entityform with a term reference field
I have an entityform that users use to upload pdf files. On the form there is a 'Term Reference' field (select list) that lets them choose the type of document that they are uploading, e.g. 'letter', 'contract', 'invoice' etc...

These entityform submissions are then displayed as a view with the 'term reference' field displayed next to a link to the uploaded document.

My problem is that when I click on the term reference the term's page is not populated with the entityform submissions that have been labeled with it.

# Answer
> 1 votes
* Add new view that shows content of type: entityform submissions.
* Add a field Entityform Submission field 'Document type'
* Set the path to /taxonomy/term/%
* Add a contextual filter, entityform submission 'Document type' and 'provide default value' - 'taxonomy term ID from url'

Done.

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


# Question
Title: Drupal 6 not playing nice with jquery 1.11.1
I am trying to incorperate a sequential fadIn of several img using a simple Jquery script

```
     $(document).ready(function(){
$(".fadeInCopy").each(function(index) {
    $(this).delay(900*index).fadeIn("900");
});
 });

```

I have the jquery loading properly and no errors in the javascript panel. However, the script will not reveal the elements. I have this working on a test page but once I install in Druapl 6 it does not respond. Any ideas?

# Answer
I would comment this, but I'm new to drupal stack exchange. Try wrapping this method around your javascript/jquery:

```
(function ($){
   $(document).ready(function(){
      //code here
   });
})(jQuery);

```

Sometimes the $ symbol alias for jQuery causes conflict.

Or you can replace all $ symbols with jQuery and see if that works.
> 1 votes

---
Tags: javascript
---


# Question
Title: How to export / import images uploaded using CKeditor
Exporting and importing image fields is easy. How to export images uploaded using CKeditor in the body field of node? I have a view which exports the content from D6 (in XML format). In D7 i have feed importer which imports the content. I can add all fields in view and get all data exported. This works well for everything except images placed in body field. They don't get migrated as it is not part of node field.

# Answer
You can get the uploaded files from the D6 files directory, and upload them to the default directory that CKEditor is set to use in D7. When you import those nodes, you can either change your XML source directly, or use the Feeds Tamper module find/replace plugin to rewrite the paths in the body field to the new location.
> 1 votes

---
Tags: views, feeds, wysiwyg, importing-exporting
---


# Question
Title: I want to have two page.tpl.php on my site
I want to have two page.tpl.php on my site ..one for my front page and other for rest of pages ...now both have same name page.tpl.php what should I do to make one of them for Front page and other for rest of pages

# Answer
> 5 votes
To implement two templates files into a site.

By default, `page.tpl.php` already exists in a drupal theme.

Creating a front page template is rather simple. In your theme folder (sites/all/themes/), copy the `page.tpl.php` file from drupal core(e.g. garland) or your parent theme. Then rename it accordingly (see below). You probably won't see the results until you clear your cache; so make sure to do that.

`page--front.tpl.php`(drupal 7)

To do a custom front page that is mostly unique, yet merges seamlessly with Drupal, you can:

1. Create a file called `page--front.tpl.php` in your active theme directory.
2. Paste in solid, static HTML, with appropriate file path fixes.
3. Compare your page with the themes normal `page.tpl.php` and copy as much of the code tags as is logical into your new file in appropriate places.
4. You can put $content in the middle, sidebars in a useful place for you to call blocks into later, and the $footer in your footer zone, etc. Try to copy as much as possible - most of it can be useful, and is the real reason for using a CMS.

For more information regarding template files Click Here

---
Tags: theming
---


# Question
Title: Why is session.cookie_lifetime set to 23 days?
As far as I understand the session lifetime at Drupal is limited by `session.gc_maxlifetime` setting is by default set to some 2.3 days.

**Then what is the use of `session.cookie_lifetime` being set to 23 days?**

Here is the snippet from settings.php:

```
/**
 * Set session lifetime (in seconds), i.e. the time from the user's last visit
 * to the active session may be deleted by the session garbage collector. When
 * a session is deleted, authenticated users are logged out, and the contents
 * of the user's $_SESSION variable is discarded.
 */
ini_set('session.gc_maxlifetime', 200000);

/**
 * Set session cookie lifetime (in seconds), i.e. the time from the session is
 * created to the cookie expires, i.e. when the browser is expected to discard
 * the cookie. The value 0 means "until the browser is closed".
 */
ini_set('session.cookie_lifetime', 2000000);

```

Please assume that I've set both `session.gc_probability` and `session.gc_divisor` to 1 just for the sake of this question.

# Answer
> ini\_set('session.gc\_maxlifetime', 200000);

1. This value is for the server.
2. It is a settings for Session Garbage Collection.
3. If the users last visit happened before 200000s then this session is eligible for garbage collection.
4. Since it is GC, the session value may be discarded and not compulsory. If a GC action happens after the session was made eligible for the GC, it will be deleted.

> ```
> ini_set('session.cookie_lifetime', 2000000);
>
> ```

1. This value is for the browser.
2. This is the absolute maximum time till which a browser can keep this cookie active.
3. A 0 value here means immediate or when the browser is closed.

**To answer your question in particular.**

1. If the user doesn't hit the server back in 2.3 days, his session will be deleted when the session garbage collection runs.
2. If he keeps on hitting one page on the server every 2.2 (less than 2.3 days) then his session will stay active. But it can be active only until 23 days from the time the session was first generated.
3. So what that means is `session.cookie_lifetime` is the absolute maximum lifetime of a session.
> 18 votes

---
Tags: 7
---


title: Passing an object to hook_menu

text:
# Question
Title: Passing an object to hook_menu
I am trying to pass an object from a function to the menu item (Not sure if drupal allows that), I get the following error 'Recoverable fatal error:Object of class stdClass could not be converted to string'. The following is my function and the menu item.

```
function add2basket_link($val) {
  $build = array();
  $build['add2basket_link'] = array(
  '#type' => 'link',
  '#title' => t('Bucket'),
   '#href' => 'basket/add/'.$val. '/nojs/',
  );
  return render($build);
  }

 function bucket_menu(){
   $items['basket/add/%'] = array(
   'page callback' => 'data_add2basket',
   'page arguments' => array(2),
   'access arguments' => array('use basket'),
   'type' => MENU_CALLBACK,
   'file' => 'data.inc',
   );
  return $items;
 }

The error points to the line of " '#href' => 'basket/add/'.$val. '/nojs/', " from the add2basket_link function

```

# Answer
> 1 votes
You could concat only string with strings, It's php :) What you can do is to use `hook_load()` something like this:

```
function add2basket_link($val) {
  $build = array();
  $build['add2basket_link'] = array(
    '#type' => 'link',
    '#title' => t('Bucket'),
    '#href' => 'basket/add/'. $val->lid . '/nojs/',
  );
  return render($build);
}

/**
 * Implements hook_menu().
 */
function bucket_menu(){
  $items['basket/add/%bucket_link_id'] = array(
    'page callback' => 'data_add2basket',
    'page arguments' => array(2),
    'access arguments' => array('use basket'),
    'type' => MENU_CALLBACK,
    'file' => 'data.inc',
  );
  return $items;
}

/**
 * Implements hook_load().
 */
function bucket_link_id_load($lid) {
  // 'bucket_link_id' is from hook_menu() from $items['basket/add/%bucket_link_id'].
  // lid is id that was passed from add2basket_link() to the #href.
  // link_load() is function to load your object.
  return link_load($lid);
}

```

---
Tags: routes
---


# Question
Title: Drupal 6 - Get 5 newest nodes of a certain type
I have a content type called "announcements". They each have a title and field for the announcement. I'd like to be able to, in my .module, get the last five announcements and print out their contents to the page. How can I do this?

# Answer
Use the Views module. It is awesome.
> 0 votes

---
Tags: 6, nodes
---


# Question
Title: Database error after transferring Drupal 6 site
I just moved a Drupal 6 site from one server to another and have just started getting an error.

```
Warning: Table 'mydatabase.watchdog' doesn't exist.

```

The table does exist in the database and it does have the proper data in it. Some content does show up so the connection information is correct. Does anyone have any suggestions for this error? I am stumped.

# Answer
Check that the table isn't corrupted or locked in some way. phpmyadmin should show you this when you view the list of tables in the database.

Try dropping the table and re-importing just that table, not the entire DB.
> 0 votes

---
Tags: 6, database
---


# Question
Title: Exclude certain taxonomies from url reachbility
I have the following structure example.com/taxonomy/term/334 and there are several terms that I don't want to be reachable by domain.

I use the autopath module, so for example it could be I want example.com/status/green and example.com/status/red so to say every example.com/status/\* to be reachable, but example.com/media/blu-ray and example.com/media/dvd or example.com/media/\* not.

Any ideas how this can get realized?

# Answer
> 1 votes
Use hook\_menu\_alter to change the access control for taxonomy/term/%

---
Tags: taxonomy-terms, path-aliases
---


title: Wildcard Search in Views

text:
# Question
Title: Wildcard Search in Views
Is there a way to use Wildcards (like \*) in Views filters. I do not want to give the user the dropdown with all the operators but use a wildcard.
For example, when he writes *name it will use "ends with", on name* "begins with", on name "contains" and so on. Is there something out there that can do that, or do I have to write it on my own?

# Answer
> 0 votes
Rather than filtering on a certain field (and then exposing the filter), try adding a filter of the type 'Search terms'. That uses drupal's search module to search, which has much smarter ways of searching.

---
Tags: views
---


# Question
Title: Problems adding javascript to a specific page
Drupal Version: 6.x

Currently, I have a custom module created. In my template, I keep html code that I would like to embed within a container, such as a div, with a particular id. For this question, let's say `<div id = "embeddableContainer"></div>`. Right now, I am able to perform the task of embedding the html code from the template like this:

```
function first_order_decay_init() {
  $path = drupal_get_path('module', 'first_order_decay');
  $path .= '/';

  $code = file_get_contents($path . 'templates/first_order_decay-static.tpl.php', false);
  $code = preg_replace("/[\r\n]*/","",$code);
  drupal_add_js('var code = \'' . $code . '\'', 'inline');
  drupal_add_js($path . 'scripts/jquery.flot.js');
  drupal_add_js($path .'scripts/jquery.flot.dashes.js');
  drupal_add_js($path . 'scripts/jquery.flot.selection.js');
  drupal_add_js($path . 'scripts/flotScript.js');
}

```

The flotScript.js file appends the code within the "embeddableContainer". However, I am not particularly certain that adding these scripts on module\_init is the best practice. Is there a way to load these scripts only on a page that contains an "embeddableContainer"? (Later in the question, you will read about my issue with jmol. I was told jmol uses a certain hook to load scripts correctly) The issue is that the php is executed before the page load, so I do not see a way this is possible.

The second issue I have is that the module does not correctly work with the jmol module we use to display interactive images. When including an instance of jmol in the same page, my scripts are not executed. To fix this, I tried adjusting my module's weight to load the scripts before jmol scripts, but nothing changed. We also use jsmol. Here's a link to some drupal documentation about jmol: https://www.drupal.org/project/jmol. I am not particularly knowledgeable about the module, and I was wondering if anyone else had experience with it or a similar issue as mine. I know that jmol/jsmol works by identifying a container in a similar manner. I believe it searches for text like this, `[JMOL](13C60)`, that matches one of our jmol/jsmol instances. I am not particularly certain about the implementation of the scripts it uses because they are minified, and I do not know the source of them or even where I would begin looking within them.

To sum everything up, how can I load scripts on only pages with "embeddableContainers," and how can I avoid the conflict with jmol/jsmol?

EDIT: MORE INFORMATION ON JMOL

I was given this information about jmol.

"The Jmol module uses hook\_nodeapi (specifically during the "alter" operation) to replace the placeholders on page load. Hook\_nodeapi allows for modules to modify the content of nodes defined by other modules ("alter" occurs after the node content has been filtered and rendered by drupal and is used for simple text operations)."

In my script, flotScript.js, I wait for `$(document).ready`. Could this have any effect when replacing the text? I am thinking about making a separate js file that replaces only the text within the container. I am thinking that I should not be using `$(document).ready` for replacing the text.

Relevant jmol code:

```
function jmol_nodeapi(&$node, $op, $a3, $a4) {
  if($op == 'alter') {
    $placeholders = _jmol_get_placeholders($node->body);

    // If the node doesn't have any placeholders, do nothing
    if(count($placeholders) != 0) {
      _jmol_replace_placeholders($node, $placeholders);
    }
  }
}

function _jmol_get_placeholders($text) {
  $placeholders = array();

  // Match placeholders of the form [JMOL]('placeholder')
  preg_match_all('/\\[JMOL\\]\(([[:graph:]]+?)\)/', $text, $placeholders);

  return $placeholders;
}

function _jmol_replace_placeholders(&$node, $placeholders) {
  foreach($placeholders[0] as $i=>$placeholder) {
    // Load the instance associated with this placeholder from the db
    $instance = _jmol_load_instance_by_placeholder($placeholders[1][$i]);

    $applet_container_html = jmol_get_applet_container_html($instance);

    // Replace the placeholder with the applet container html
    $node->body = str_replace($placeholder, $applet_container_html, $node->body);
  }
}

function _jmol_load_instance_by_placeholder($placeholder) {
  $instance = db_fetch_object(db_query('SELECT * FROM {jmol_instances} WHERE placeholder=\'%s\'', $placeholder));

  if($instance === FALSE) return FALSE;

  // Get the models associated with the instance
  $instance->models = _jmol_get_models($instance->jid);

  return $instance;
}

```

EDIT: SOLUTION TO CONFLICT WITH JMOL

```
function first_order_decay_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  if($op == 'alter') {
    $path = drupal_get_path('module', 'first_order_decay');
    $path .= '/';

    $code = file_get_contents($path . 'templates/first_order_decay-static.tpl.php', false);
    $code = preg_replace("/[\r\n]*/","",$code);
    drupal_add_js('var code = \'' . $code . '\'', 'inline');
    drupal_add_js($path . 'scripts/jquery.flot.js');
    drupal_add_js($path .'scripts/jquery.flot.dashes.js');
    drupal_add_js($path . 'scripts/jquery.flot.selection.js');
    drupal_add_js($path . 'scripts/flotScript.js');
  }
}

```

Will I still be able to check content types for loading scripts?

# Answer
> 1 votes
If you are dealing with content on node pages you could add something like this in your init function:

```
if ($node = menu_get_item()) {
  // If we have an article node, add our js.
  if ($node->type == 'article') {
    // Add your js here.
  }
}

```

You could do other similar things to make it so you are not unnecessarily loading your js as much (although it may still be unnecessarily loading sometimes).

That will probably not help you if you also have this markup on listing pages because it deals with individual node pages.

For all node views you could do something like this:

```
function MODULENAME_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op) {
    case 'view':
      // Your js gets loaded here.
      // You can also single out specific node types here, or check
      // nodes for a specific field having a non-empty value, or check
      // the view mode, etc. to further limit the adding of your js.
      break;
  }
}

```

If you are also dealing with non-node entities then there are other similar hooks that could help you out. You might need to have a function that adds all your js and then call it from a few places to catch all your use cases.

# Answer
> 2 votes
It is probably better to create a input filter by using hook\_filter and then applying that filter to the 'Full HTML' input format (at /admin/settings/filters).

Input filters are used to massage HTML before output.

---
Tags: javascript, hooks
---


title: drupal7 custom form drop down show 0

text:
# Question
Title: drupal7 custom form drop down show 0
I get a problem with my dropdown that shows "--select--","0","foods","meals" when I developing custom form with Drupal 7. The purpose of my dropdown is used to show "foods" and "meals" from category table. How does this "0" come from? I am hoping anyone suggestion to fix it.

```
function subcategory_form($form, &$form_state= NULL, $my_object= '', $subcategoryId, $name, $categoryId) {

     $category = db_select('category', 'cat')
    ->fields('cat')
    ->execute();

    $rows[] = array();
    while($data = $category->fetchAssoc())
    {
        $rows[$data['id']] = t($data['name']);
        dpm($rows);
    }

    $form['category_name'] = array(
    '#type' => 'select',
    '#title' => t('Category'),
    '#options' => $rows,
    '#default_value' =>t($categoryId),
    '#description' => t("Please select category."),
    '#required' => 'true'
  );

  return $form;
}

```

# Answer
> 2 votes
The code `$rows[] = array();` will become a row in the array itself and will not just create an array as you probably want.

Change `$rows[] = array();` to `$rows = array();`

---
Tags: forms
---


title: Save user fields in commerce profile

text:
# Question
Title: Save user fields in commerce profile
I add some fields to default user fields,like phone,address,city,... , I want If user edit or filled up his user information in `user/uid/edit` when submit ,if there is not any commerce shipping profile, create a profile to him/her, and if there is , update default shipping profile , how can I achieve this job? I know I can create profile with something like below code

```
 $new_profile = commerce_customer_profile_new($type);
  $wrapper = entity_metadata_wrapper('commerce_customer_profile', $new_profile);
  $wrapper->uid = $account;
  $wrapper->commerce_customer_address->country = $country;
  $wrapper->commerce_customer_address->name_line = $name_line;
  $wrapper->commerce_customer_address->first_name = $first_name;
  $wrapper->commerce_customer_address->last_name = $last_name;
  $wrapper->commerce_customer_address->organisation_name = $organisation;
  $wrapper->commerce_customer_address->administrative_area = $administrative_area;
  $wrapper->commerce_customer_address->sub_administrative_area = $sub_administrative_area;
  $wrapper->commerce_customer_address->locality = $locality;
  $wrapper->commerce_customer_address->dependent_locality = $dependent_locality;
  $wrapper->commerce_customer_address->postal_code = $postal_code;
  $wrapper->commerce_customer_address->thoroughfare = $thoroughfare;
  $wrapper->commerce_customer_address->premise = $premise;
  $wrapper->field_bcg_customer_phone = $phone;
  commerce_customer_profile_save($new_profile);

```

but my question is , how can set it as default, after user edited (updated) if there is default profile , update it also

**appreciate any help**

# Answer
As you mention you're looking for setting the profile as default, I'm assuming you're using Commerce Addressbook or in any case looking for a very similar feature of what that module provides.

> Commerce Addressbook is a module that allows authenticated customers to reuse previously entered addresses during checkout. They can manage all entered addresses in their user panel (user/%user/addressbook).

You can use `commerce_addressbook_set_default_profile` function to set the default (one per type). Example:

```
$billing_profile = commerce_customer_profile_new('billing', $user->uid);
  $billing_profile->commerce_customer_address[LANGUAGE_NONE][0]['name_line'] = 'Sample Customer';
  $billing_profile->commerce_customer_address[LANGUAGE_NONE][0]['country'] = 'US';
  $billing_profile->commerce_customer_address[LANGUAGE_NONE][0]['thoroughfare'] = '16 Hampton Ct';
  $billing_profile->commerce_customer_address[LANGUAGE_NONE][0]['locality'] = 'Visalia';
  $billing_profile->commerce_customer_address[LANGUAGE_NONE][0]['administrative_area'] = 'CA';
  $billing_profile->commerce_customer_address[LANGUAGE_NONE][0]['postal_code'] = '93277-8329';
  commerce_customer_profile_save($billing_profile);
  commerce_addressbook_set_default_profile($billing_profile);

```

I'd recommend another way to create the profile, for example:

```
    // Create the new profile now.
    $profile = commerce_customer_profile_new('billing', $order->uid);

    // Add the address value.
    $profile_wrapper = entity_metadata_wrapper('commerce_customer_profile', $profile);

    $profile_wrapper->commerce_customer_address = array_merge(addressfield_default_values(), array(
      'country' => $country,
      'name_line' => $name . ' ' . $last_name,
      'first_name' => $first_name,
      'last_name' => $last_name,
    ));

    // Save the profile.
    $profile_wrapper->save();

```
> 9 votes

# Answer
You should provide more information about you problem set. As I see it. You save some data to user object and later you would like to reuse it for customer profile. Now you need to attach this new customer id to order. You can do it with

* Commerce addressbook
* Commerce singeaddress
* with some custom code.

Now you will have new problem. Users can edit this information at checkout page. If they do so then new commerce customer profile will be created and the question is how you gonna solve this. Should they be able to edit it so or not. If they can do it then you need to update user profile and if not then they will have to go and change their profiles and now you need to update current order customer profile id if there is any.

So what I would like to say this what pcambra suggested would be easier because you would use widely tested solution. If You are really sure you need something similar to what I wrote then you should expect quite many hours of work and testing.
> 1 votes

---
Tags: commerce, users, entities
---


# Question
Title: How to parse current page URL query parameters to create link using l() function
I have a view in D7 with a few exposed filters. This view generates a URL/page like this: example.com/node?location=XXX&check-in=XXX&check-out=XXX&lang=XXX.

I am looking to build a link passing in a couple of the current page's query parameters from above. I am using the `l()` function and currently have the following:

```
print l("link_name","http://www.example.com/path", array('attributes'=>array('target'=>'blank'), 'query'=>array('lang'=>'en', 'currency'=>'USD', 'standardCheckin'=>$view->get_exposed_input(), 'standardCheckout'=>$view->get_exposed_input())));

```

I am looking to pass in the check-in and check-out parameter values from the views-generated page in to my link function's standardCheckin and standardCheckout keys. What I currently have obviously does not work. I'm using the `view::get_exposed_input` function to pull in the values that are in the exposed filter, but it is pulling in ALL of the query parameters. This function does not seem to have any query parameters to limit the query. I also looked at using `drupal_parse_url` and `drupal_get_query_parameter`s, but can not get those to work either (again, getting all parameters - can not limit to just the two I need).

I can pull the values from either the URL or from the exposed filter. My PHP is a bit limited, but what is the best function to use (and a nudge syntactically on how to limit the query would be appreciated)? Or is there a better Drupal method for achieving this?

# Answer
Maybe something like this would be sufficient?

```
$url = drupal_parse_url('example.com/node?location=XXX&check-in=XXX&check-out=XXX&lang=XXX.');
$desired_params = array_intersect_key($url['query'], array_flip(array('check-in', 'check-out')));

```

`array_intersect_key()` will return the values in the first array whose keys also exist in the second array, while `array_flip()` inverts the values in the array with their keys, actually generating something like the following (in my example):

```
array(
  'check-in' => 0,
  'check-out' => 1,
)

```

You can probably use the same approach or a very similar one with `view::get_exposed_input`, which is probably the best way of getting the data you need.

---

I didn't get that you also needed to rename the parameters. Then I don't think there's any advantage in filtering the parameters, just pull out the ones you need by hand.

```
$params = drupal_parse_url('...');
l("link_name","http://www.example.com/path",
  array('attributes' => array('target' => 'blank'),
  'query'=>array(
    'lang' => 'en',
    'currency' => 'USD',
    'standardCheckin' => $params['query']['check-in'],
    'standardCheckout'=>$params['query']['check-out']
   )
  )
);

```
> 0 votes

---
Tags: hooks, uri, navigation
---


title: Responsive Blocks

text:
# Question
Title: Responsive Blocks
How can I make blocks shrink while staying on the same line as the window gets smaller? As of right now my blocks are going under other blocks as my window gets smaller. How can I make my theme responsive, but have the blocks stay on the same line? I am using Drupal 7.

# Answer
If you don't want to go into code, you could take a look at the panels module https://www.drupal.org/project/panels . You can create a panel page where the regions have their widths in percentages. And then you can place blocks in these regions.
> 1 votes

# Answer
To make your site or block **responsive** you can either create your own custom theme and in its css file you can follow these media queries as per your requirement or also you can try using Zen or else Bootsrap theme which gives by default resposive look to the site.
> 1 votes

# Answer
Use CSS to set their width to a `percentage` rather than a `pixel` number. But before that you have to set your most outer div's width to the layout's `max-width` so that it will fit in since the calculation of `pixel` to `percentage` is totally dependent on the `width` defined to any of the parent element.

Assuming you have a container div is 800px wide if you have a col div in the container as 384px wide then that would be 48%

```
384*100/800 = 48%

```
> 1 votes

---
Tags: blocks, theming
---


title: Generate PDF and send mail

text:
# Question
Title: Generate PDF and send mail
I have need to send pdf via drupal mail. I want to use tcpdf library but when im trying to use example i have error: http: //..../tcpdf\_example/download/simple

Fatal error: Call to a member function DrupalInitialize() on a non-object in C:\xampp\htdocs\drupalac\_gw\sites\all\modules\tcpdf\tcpdf\_example\tcpdf\_example.pages.inc on line 55

```
  $html = theme('tcpdf_example_basic_html');

  // Never make an instance of TCPDF or TCPDFDrupal classes manually.
  // Use tcpdf_get_instance() instead.
  $tcpdf = tcpdf_get_instance();
  /* DrupalInitialize() is an extra method added to TCPDFDrupal that initializes
  *  some TCPDF variables (like font types), and makes possible to change the
  *  default header or footer without creating a new class.
  */
  $tcpdf->DrupalInitialize(array(
    'footer' => array(
      'html' => 'This is a test!! <em>Bottom of the page</em>',
    ),
    'header' => array(
      'callback' => array(
        'function' => 'tcpdf_example_default_header',
        // You can pass extra data to your callback.
        'context' => array(
          'welcome_message' => 'Hello, context array!',
        ),
      ),
    ),
  ));

```

then somehow...

```
  ...
  $attachment = array(
  'filecontent' => $tcpdf->Output('', 'E');
  'filename' => 'test.txt',
  'filemime' => 'text/plain',
  );

  switch($key) {
  case 'notice':
  $langcode = $message['language']->language;
  $message['subject'] = 'example submission from' . $account;
  $message['body'][] =''. $account .' has submitted an example.';
  $message['params']['attachments'][] = $attachment;
  break;
  ...

```

What i need to correct to get rid of error?

# Answer
> 3 votes
Ok First off all Installing drupal TCPDF module is not enough to have working pdf-s. We are also obligated to download TCPDF libray from http //www.tcpdf.org/ and place it to drupal files so that library will be avaible like this

> C:\xampp\htdocs\drupalac\_gw\sites\all\libraries\tcpdf\tcpdf.php

above will solve:

> Fatal error: Call to a member function DrupalInitialize()

With working pdf library sending emails with attachments is easy i have like this:

```
drupal_mail('module', 'notice', "to@mail","", array(), "from@mail");

```

where:

```
function module_mail($key, &$message, $params) {
  $attachment = array(
    'filecontent' => generatePdf("S"),
    'filename' => 'example-filename',
    'filemime' => 'application/pdf',
  );

  switch($key) {
    case 'notice':
      $langcode = $message['language']->language;
      $message['subject'] = 'example submission from ';
      $message['body'][] ='my example.';
      $message['params']['attachments'][] = $attachment;
      break;
  }
}

```

And where:

```
function generatePdf($where="S") {
  $pdf = tcpdf_get_instance();

  $pdf->setFontSubsetting(true);

  // set font
  $pdf->SetFont('freeserif', '', 12);

  $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 008', PDF_HEADER_STRING);

  // set header and footer fonts
  $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
  $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

  // set default monospaced font
  $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

  // set margins
  $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP+10, PDF_MARGIN_RIGHT);
  $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
  $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

  // set auto page breaks
  $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

  // set image scale factor
  $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
  return $pdf->Output('example_008.pdf', $where);
}

```

Above is now my working example :)

---
Tags: files
---


# Question
Title: Drupal sending SPAM, can't log in anymore
My unupdated drupal website has been sending large amounts of spam. I have now blocked the website with HTTP Basic authentication, but I can't seem to get in my admin account of the website. I've tried setting a new hash, but logging does not seem to work, as I don't get any error message when trying to.

Also the password reset function and create new account function do not work, I've tried showing error messages in my template.php file, etc.

Do any of you have any experience with this kind of hack? My Drupal was unupdated and is currently on version 7.15. How do I get back in? Or is it best to set up a new site and transfer the content.

\[UPDATE\] I have currently updated my drupal system to the most recent version, 7.30. But still no success. I can still not login, even though all the files are renewed. I have also reverted back to the garland theme, but also this theme is not giving me any error messages.

Thanks in advance.

# Answer
I've managed to log in programmatically using a theme function, explained in this post.

How do I programmatically log in a user?
> 1 votes

---
Tags: users, advertising
---


# Question
Title: Creating an editable table which can be updated
I have a site with about 150 users. I am going to implement a system whereby things that they do in the real world (it's a fitness company), such as attending sessions, introducing new customers etc will earn them points.

I would like to create a table with 3 columns:

Name | Points | Update

so something like this:

The idea being that my client (editor role) could log in and amend the points that each user has and then click update to modify each row. I guess the table would be equally useful if there were just a single 'update' button at the bottom of the table to update all entries at once.

I don't know how I might go about making a table such as this 'editable', but would really appreciate some pointers as to how you might accomplish this. I would stress that I'm okay with using contributed modules, but quite poor with creating modules and PHP in general!

# Answer
> 4 votes
For your requirement Slickgrid is the best option for you and for that you need to use views module.

> At the front end, users can show/hide, resize, reorder columns & resize the height of the grid. These settings will be stored per user and used next time the grid is shown. Saving the view (via the usual views UI) will reset these settings.

For every field defined in the view, you can set its column width, whether it's sortable, and formatters (how the cell data is displayed), an editor, a validator and filters (for filtering the column data).

This modules comes with the following plugins ready to use:

> Editors:
>
> * Inline cell editor - for excel-like editing of text & numeric data.
> * Popup field form - the field form pops up in an overlay. All field types can be edited.

---

Features of the grid:

> * Grouping field - group fields with a common value together
> * Collapsible taxonomy fields (tree structures)
> * Tabs - organise columns into tabs
> * Resize, reorder & hide columns
> * Delete entities via the grid
> * Force fit columns (to fill the available column space)
> * Undo (undo previous changes - uses node revisions)
> * Set viewport height
> * Set row height
> * Add entities via the grid\*
> * Clone entities\*
> * Export data (via the views data export module)\*
> * Multi edit/delete/clone/export (checkboxes will be displayed in the rows - select as many rows as you want to perform action against)\***

---

or as Pontus Nilsson said use this Editable Views module.

# Answer
> 2 votes
Just in case someone else will be searching for solution.

Editable Views module (https://www.drupal.org/project/editableviews) - works good, has only one Save button for whole table (not a row). Cannot be used with non-FieldAPI-based fields (e.g. no Views Bulk Operations and no Weights). Should be good enough for your task.

Editablefields module (https://www.drupal.org/project/editablefields) - works not so good - it saves every field right after it's editing with AJAX. The fast editing of multiple fields may result to data lost.

Unfortunately there's no ready solution to save data per table row.

# Answer
> -1 votes
You need the WYSIWYG module. Once you have installed the module, you'll need to install an editor, such as CKEditor or IMCE.

---
Tags: 7, views
---


title: How to use Susy with Zen theme

text:
# Question
Title: How to use Susy with Zen theme
I'm trying to change the grid system in the Zen theme to use susy but can not find any documentation on how to do it with the 7.5.5 version.

I have installed susy through compass and have added require 'susy' to my config.rb file.

But from here I'm not sure what I need to do.

Do I have to delete the \_responsive.scss file that comes with Zen and code my own?

If anyone could provide a run down of the steps needed that would be very helpful.

Many thanks,

Terry.

# Answer
> Do I have to delete the \_responsive.scss file that comes with Zen and code my own?

Whether you delete specific files or not is incidental, but what you *do* need to do is replace everything in Zen's default Sass that relates to grids with your Susy-based system.

Because of the nature of Susy there's a good chance you won't need to change any of the markup Zen builds, but of course your mileage may vary depending on exactly how customised your theme is.
> 0 votes

---
Tags: theming
---


# Question
Title: Git with Drupal 7 multi-site, naming directories
I have been working in a single installation of Drupal 7, which has two sites built upon it.

In Drupal 7 multiple sites are served by naming a directory for each site to be served under /sites and include settings, themes and modules specific to that site.

```
sites
|
|__ 8888.website-one.dev
|   |__ settings.php
|   |__ files
|   |__ themes
|
|__ 8888.website-two.dev
    |__ settings.php
    |__ files
    |__ themes

```

So the system identifies the site based upon the domain (in my case the preceding 8888 is the port number I use to work internally).

When I push this installation to a remote dev server using Git, the domains I use to access the installation will need to change, and so the directory names would have to change too; which means that I wouldn't be able to have the installation working on both my local and remote development boxes.

Is it possible, with Git, to change a directory name on the remote server, and keep it the same on my local server, *while still tracking the files inside those folders?*

Many thanks!

# Answer
You don't need to consider a whacky git-based solution to this, Drupal has you covered.

Just uses aliases in sites.php, and use whatever method you like (assume-unchanged in the index, .gitignore, whatever) to keep sites.php out of the repo.

So on your local machine your sites.php might contain

```
$sites['website-one.dev'] = 'website-one';
$sites['website-two.dev'] = 'website-two';

```

And on a remote server:

```
$sites['website-one.staging'] = 'website-one';
$sites['website-two.staging'] = 'website-two';

```

And prod:

```
$sites['website-one.com'] = 'website-one';
$sites['website-two.com'] = 'website-two';

```

All the while, your sites live in 'website-one' and 'website-two' respectively; no need for tricks.

If you don't want to consider a Drupal-based solution, and still want to use git, I'd advise taking this over to Stack Overflow where such a question would be on-topic.
> 1 votes

---
Tags: 7, multi-sites, version-control
---


# Question
Title: How to get relationship id in views drupal 7?
I am using User relationships module and created relation friends. Where we can send and receive friend requests just like fb. So l have created view to list all my-friends and also added remove link to the each friend. In view "status link (action)" field is providing remove link which can be used to remove the particular friend from our friend's list, but the link is not accessible to the users other than admin. I want to get relationship id (rid) in view so that I can create remove link. Is there anyone who knows the way to get rid? I just want to create url like below myhomesite.com/user/26/relationships/1115/remove?destination=user/373/friends . where 26 is logged in user id and 1115 is the relationship id.Thanks.

# Answer
> 0 votes
If you want to output a link in views which leads to the page where the user's account can be deleted you can use the field "User: Cancel link". That field should be present in your view since you have the user as a relationship.

If you still want the user's uid and link to some page on your own you need to add the field called "User: uid" and then rewrite the output of the field.

Add the field called User: uid, then under the settings for the field expand Rewrite results and click Rewrite the output of this field, enter the text that should be displayed. Then click output this field as a link and use the \[uid\] placeholder in the link. The \[uid\] will be replaced with the user's uid when the View is rendered. You can see an example of the settings in the image below.

---
Tags: views, users
---


# Question
Title: Add meta tags when block exist on page and its cached
I have block with social sharing buttons. Need add 'og' and 'twitter' meta tags on page where block exists. I know that can add it throw `drupal_add_html_head()` inside block content render, but if block is cached meta tags not appear. How do this?

# Answer
Instead of adding php code in the block you could add the code in a preprocess function for the block.

```
/**
 * Implements template_preprocess_block().
 */
function MYTHEME_preprocess_block(&$variables) {
  if ($variables['block']->bid == 'MYBLOCKID') {
    $og_title = array(
      '#tag' => 'meta',
      '#attributes' => array(
        'property' => 'og:title',
        'content' => "My example title",
      ),
    );
    drupal_add_html_head($og_title, 'MYMODULE_og_title');
  }
}

```
> 1 votes

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


# Question
Title: 7 - Panels node form, file/image gets removed when field not present in the custom form
I am using Panels to customise node forms by separating them into multiple pages.

On one page I have text fields and on another file/image fields, when saving the text field form variant all the files get removed from the node - if I add a field in that form variant, it will get saved (not removed).

Is this a normal behaviour?

# Answer
> 1 votes
I've also encountered that. The node form and the image field's value will be submitted as empty and resulting in as you say that the image get removed from the node.

It is an unfortunate side effect of how the form api works. Someone could try to work around it in Panels, and/or limit panels to prevent you from doing this, but both of these would be hacks on top of form api.

One workaround is adding the pane *General form* that you will find under Form when adding panes. Then click settings for the pane and under CSS properties set the class to "element-invisible". This way all other form elements that you have not placed as panes will be present but hidden by css.

I know it feels wrong but at least it get's the job done :)

---
Tags: nodes, forms, panels
---


title: Check if field has value (content)

text:
# Question
Title: Check if field has value (content)
I have code which checks if field exists, but I try to change it to check if field has value (content) or not.

In views I have one field to show all content (Rewrite results). So all fields are loaded always. Thats why I need code which checks does field have content or not.

This is what I got now, but it adds "has\_no\_field" to all - no matter if field\_image has content or not.

```
function theme_preprocess_views_view_unformatted(&$vars) {
  $view = $vars['view'];
  $rows = $vars['rows'];

foreach ($vars['view']->result as $id => $row) {

    if (isset($row->field_image['und'][0]['value']) == 1) {
      $vars['classes_array'][$id] = 'has_field';
    }
    else {
      $vars['classes_array'][$id] = 'has_no_field';
    }
  }
}

```

# Answer
> 5 votes
Try changing

```
if (isset($row->field_image['und'][0]['value']) == 1) {

```

to

```
if (!empty($row->field_field_image)) {

```

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


# Question
Title: querying content type via drupal database API
Using Drupal 7 I have created a content type called 'fauna'. I simply want to filter by an attribute (eg: 'area') using Drupal database API.

As far as I have seen around, most of people follow queries like...

$query = db\_select('my\_table\_name')

applying then some filters.

But I have no table at all regarding my content type where I could apply these filters, i just have a bunch of tables field\_data\_field\_fauna\_name, field\_data\_field\_fauna\_area ... (these are the fields defined for my Content type).

# Answer
> 1 votes
Instead of querying directly against a table you can use Entity field query.

I'll assume the machine name of your content type is called *fauna* and that there is a field called *field\_fauna\_area*. Now lets find all nodes where the field *field\_fauna\_area* is "Europe".

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'fauna')
  ->fieldCondition('field_fauna_area', 'value', 'Europe', '=')
$result = $query->execute();
if (isset($result['node'])) {
  $fauna_nids = array_keys($result['node']);
  $fauna_items = entity_load('node', $fauna_nids);
}

```

In $fauna\_nids you will find all node ids and in $fauna\_items all the nodes will be loaded.

# Answer
> 0 votes
You want to look at the node table where all nodes of all content types are listed. Then filter by your content type there.

---
Tags: views, database
---


# Question
Title: How to clear Text in search box once the user selects other option
I have created a view for to search my channels. But when user searches for a specific channel, and when he clicks any other option or on any other event,he redirects to other page but text in search box is not cleared,what i want is, the text in search box should get cleared once he clicks on other option.How can i do this??

# Answer
> 0 votes
You can reset the value of search box with Javascript when page get ready. Create a simple custom module and create a js file in that module. Something like:

```
//custom.js
(function($, Drupal, window, document, undefined) {
  $(document).ready(function(){
    $('SEARCH-FROM-INPUT').val('');
  });
})(jQuery, Drupal, this, this.document);

```

Attach this file to the pages those have that search form.

```
function custom_form_alter(&$form, &$form_state, $form_id){
  if ($form_id == 'SERCH_FORM_ID') {
    $form['#attached']['js'] = array(
      drupal_get_path('module', 'custom') . '/custom.js' => array(
        'type' => 'file',
      ),
    );
  }
}

```

**Update:** updated code as per @Andy comment, adding js with '#attached' property

# Answer
> 0 votes
I think you can do it in 2 ways:

1. You can use **javascript** to clear the value of textfield after page load or on click.
2. You need to rewrite field or rebuild form when option changes.

It\`s all that i can say without some code.

---
Tags: search
---


# Question
Title: Drupal overlay is not working for content links
I have installed my own custom theme in Drupal 7.29. Overlay is not working for my content links such as

```
http://localhost/node/add#overlay-context=.
http://localhost/node/add
http://localhost/node/add/page
http://localhost/node/add/article

```

But for other links overlay works just fine

```
http://localhost/node/add/page#overlay=admin/structure
http://localhost/node/add/page#overlay=admin/structure/block
http://localhost/node/add/page#overlay=admin/structure/types

```

Overlay Working

Overlay not Working for content links

Please help me solve this problem. Any help is appriciated

thanks

# Answer
First of all, make sure that the user that is trying to use the overlay has the appropriate permissions to do so (the permission is called: **"Access the administrative overlay"**). If you are trying to add/edit content as admin, then that's not the problem.

Also, make sure that in **admin/appearance** page, the option **"Use the administration theme when editing or creating content"** is selected. Notice, that if a role does not have the permissions to use the administrative theme (or the overlay for that matter), the users with the specific role will be adding/editing content through the default theme of your site.
> 2 votes

---
Tags: 7, modal-dialogs
---