# Question
Title: Drupal 7 add calendar module. Doubleclick on a day to add calender item for that day
Adding 50+ calender items to my drupal Calendar is a pain and takes a lot of time clicking and selecting the right date. What would be awesome is that it would be possible to just doubleclick or click on a + or something on the day that needs a new calender item. Does anyone have a clue on how to do this? Or something similar. I already added the link to add a calendar item above the calendar to add a calendar item from that view but then I still need to change the date unless it is the current day.

Thanks in Advance!

# Answer
The Calendar module does not provide such a feature per se. There is also another calendar module, FullCalendar. This uses the FullCalendar jQuery plugin. By default the Drupal module does not provide this functionality, but from the demo pages it seems that it is a relatively easy one to implement by yourself. You would have to study the demo a bit.
> 2 votes

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


# Question
Title: Commerce : adding optional insurance block to shopping cart form : ajax callback
Customers will be purposed **an optional insurance** in the shopping cart, calculated as a percentage of Cart Total. I added this feature as an editable field in a footer view of the shopping cart, and I'm **trying to setup ajax callback** to update the cart.

**EDIT** (@people who already read the question) : I solved the initial bugs, so this is a clean update. **You can jump to item 7** if you don't want to read the full implementation...

What I've done so far :

1. Created an *insurance taxonomy*, each term is an insurance option with a % decimal fields (in order to allow insurance options *changes* at any time).
2. Added this taxonomy to the order fields with a *term reference field* "Insurance" .
3. Created a very simple *view block* called `cart_field_assurances` with that Insurance field, with editable format.
4. Installed Cart View Override, cloned shoppping cart form and set that clone as shopping cart
5. Created a `views-view--commerce-cart-form-assurances.tpl.php` template with :

```
print $rows;
print views_embed_view('cart_field_assurances', 'block');

```
6. Moved insurance view before `#edit-actions` div with Jquery

```
var insurance = $('.view-id-cart_field_assurances').detach();
insurance.prependTo('#edit-actions');

```
7. Removed action buttons, added ajax to the field, declared insurance price component

```
function vts_insurance_form_views_form_cart_field_assurances_block_alter(&$form, &$form_state, $form_id) {
  $ajax = array(
    'callback' => 'vts_insurance_cart_refresh',
    'progress' => array('type' => 'throbber', 'message' => ''),
  );
  $form['field_order_assurances'][0]['field_order_assurances']['und']['#ajax'] = $ajax;
  //Hide buttons
  $form['field_order_assurances'][0]['actions']['submit']['#attributes']['class'] = array('hidden');
  $form['actions']['#attributes']['class'] = array('hidden');
}

//ajax callback
function vts_insurance_cart_refresh(&$form, &$form_state) {
  //Load the order
  $view = $form_state['build_info']['args'][0];
  $order_id = $view->result[0]->order_id;
  $order =  commerce_order_load($order_id);
  //set new value
  $order->field_order_assurances['und'][0]['tid'] = $form_state['values']['field_order_assurances'][0]['field_order_assurances']['und'][0]['tid'];
  commerce_order_save($order);
}

//insurance price component
function vts_insurance_commerce_price_component_type_info() {
  return array(
    'insurance' => array(
      'title' => t('Insurances'),
      'display_title' => t('Insurances'),
      'weight' => -10,
    ),
  );
}

```
8. Set up a rule : Before saving a commerce order, calculate the insurance amount and add it to total as an *Insurances price component*

## To illustrate, this is the shopping cart form, with the optional insurance field below

## The question

How to refresh the display of "Cart Commerce Order total" shopping form view (and its price components of course) in `vts_insurance_cart_refresh` ajax callback ?

# Answer
> 1 votes
To implement an optional insurance field in the shopping cart : first, follow question steps 1 to 6.

For a nice ajax replacement, create a very simple *Order total* view with a `Global: Custom text` field (which we'll hide with a css class, just to have the minimum :one field) and put `Commerce Order: Order total` field in footer.

Then alter the form and setup the ajax callback :

```
function vts_insurance_form_views_form_cart_field_assurances_block_alter(&$form, &$form_state, $form_id) {
  //add ajax to our field
  $form['field_order_assurances'][0]['field_order_assurances']['und']['#ajax'] = array(
    'callback' => 'vts_insurance_cart_refresh',
    'progress' => array('type' => 'throbber', 'message' => ''),
  );
  //unset unused buttons
  unset($form['field_order_assurances'][0]['actions']['submit']);
  unset($form['actions']);
}

function vts_insurance_cart_refresh(&$form, &$form_state) {
  $order = commerce_cart_order_load($GLOBALS['user']->uid);

  //set the order insurance field value & save it
  $order->field_order_assurances['und'][0]['tid'] = $form_state['values']['field_order_assurances'][0]['field_order_assurances']['und'][0]['tid'];
  commerce_order_save($order);
  commerce_cart_order_refresh($order);

  //Display a message to customer
  $term = taxonomy_term_load($order->field_order_assurances['und'][0]['tid']);
  dsm(t('Insurance : you selected ').$term->name);
  $commands[] = ajax_command_replace('.messages.status', theme('status_messages'));

  //Refresh the cart total display
  $cart_total = commerce_embed_view('shopping_cart_total', 'block', array($order->order_id));
  $commands[] = ajax_command_replace('.view-shopping-cart-total', $cart_total);

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

```

In the module js file, play with your DOM elements to display them as wished

```
(function ($) {

  $(document).ready(function(){
    //A wrapper for the first shopping cart total refresh
    $('.commerce-order-handler-area-order-total').wrap('<div class="view-shopping-cart-total"></div>');
    //Move the editable field above buttons
    var assurances = $('.view-id-cart_field_assurances').detach();
    $('.view-shopping-cart-total').before(assurances);
    //A wrapper for ajax messages
    var insurance_message = $("<div class='messages status insurance'></div>");
    insurance_message.appendTo(assurances).hide();
  });

})(jQuery);

```

A rule setting up a ***Fee*** *price component*, depending on the insurance field percentage value.

```
{ "rules_calcul_des_assurances" : {
    "LABEL" : "Calcul des assurances",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Commerce Cart" ],
    "REQUIRES" : [ "commerce", "rules", "commerce_fees" ],
    "ON" : { "commerce_fees_order" : [] },
    "IF" : [
      { "entity_exists" : {
          "type" : "commerce_order",
          "property" : "order_id",
          "value" : [ "commerce-order:order-id" ]
        }
      },
      { "entity_has_field" : { "entity" : [ "commerce-order" ], "field" : "field_order_assurances" } }
    ],
    "DO" : [
      { "data_calc" : {
          "USING" : {
            "input_1" : [ "commerce-order:commerce-order-total:amount-decimal" ],
            "op" : "*",
            "input_2" : [ "commerce-order:field-order-assurances:field-pourcentage" ]
          },
          "PROVIDE" : { "result" : { "assurance_cout" : "Co\u00fbt de l\u0027assurance" } }
        }
      },
      { "commerce_fees_apply" : {
          "entity" : [ "commerce-order" ],
          "fee" : "assurances",
          "amount" : [ "assurance-cout" ],
          "currency_code" : "EUR"
        }
      }
    ]
  }
}

```

With such implementation, it is possible to add *any kind of field* in the shopping cart footer, allowing customers to choose options that will *change the order total* adding a price component, with *Ajax* feature. Nice.

# Answer
> 0 votes
As I see you should add some line item to your cart. I would go with a product line item. So now if you have a product called insurance you need to assign the price of total shopping cart * 0.17 to your insurance product

I would try to put all the heavy lifting to rules module. Specially because of the fact rules can / will decide the prices including / exluding taxes. You can change tax depending on your taxonomy term selection if you choose so. And you could add pricing % to taxonomy fields.

Or another and maybe even better way could be https://www.drupal.org/project/commerce\_fees

---
Tags: commerce, ajax
---


title: Webform Content with admin approval

text:
# Question
Title: Webform Content with admin approval
Hi I have a webform which user will fill and get a confirmation link.On clicking the confirmation link the user is a confirmed user.I want an add on functionality of admin approval in it so that after the admin approval the approved user name is displayed in a list.Any help please.Thanks in advance

# Answer
There is a module for that. Check Webform Confirmation.

> This is confirmation module. It sends an e-mail to users who submit the webform for verification by taking the email id from the webform.
>
> On clicking on the confirmation link in the email, the user confirms that he/she is not a spammer. It works both for both Authenticated and Anonymous users.
>
> Also, the administrator is able to keep a track of users who have confirmed their submissions.
>
> Optionally, you can disable sending the confirmation link in the mail which would only send a "thank you" mail.
> 1 votes

---
Tags: nodes, webforms
---


title: How to translate the menu title?

text:
# Question
Title: How to translate the menu title?
Currently I am working on a multilingual website and have already a multilingual set-up. Now I have translated menu items and it is working great, however I also want the menu title to be translated.

This is how I get the menu titles:

```
$menuInfo = menu_load('menu-second-menu');

```

and I get the title through by $menuInfo\['title'\];

I print the links with the following code (and the title is displayed above):

```
print theme('links__system_main_menu', array('links' => $menu, 'attributes' => array('id' => $menuInfo['menu_name'], 'class' => array('links', 'clearfix')), 'heading' => array('text' => $menuInfo['title'], 'level' => 'h3')));

```

So the links are translated, but the $menuInfo\['title'\] not and $menuInfo does not contain any translated information.

Any help?

**Edit:** The issue is I do not know how to get the translated menu title (programmatically) I made in Structure -\> Menus -\> Second Menu -\> click the tab Translate and gave a different Menu title for the different languages. I am using the **Menu Translation** (sub)module of the **i18n Internationalization** module.

# Answer
The only solution I could come up with, to translate the menu title is by using the following:

```
$menu = menu_load('main-menu');
$menu_title = i18n_string_translate('menu:menu:main-menu:title', $menu['title']);
$menu_desc = i18n_string_translate('menu:menu:main-menu:description', $menu['description']);

```
> 2 votes

# Answer
Enable `locale` and `Translation` module, goto `admin/config/regional/translate/translate` select the language and enter the corresponding English statement, then translate it.
> 0 votes

---
Tags: 7, i18n-l10n, navigation
---


title: Check for string in URL

text:
# Question
Title: Check for string in URL
How can I check for a specific directory in my URL? I need to display an image if I'm in http://www.mywebsite.com/displayimg/mypage but not if I'm in http://www.mywebsite.com/mypage... would it be something involving drupal\_get\_path?

# Answer
> 1 votes
You can use arg to check for URL arguments. In your case, the second argument has to be empty, so you can try something like this:

```
if (arg(0) == 'displayimg' && arg(1) == 'mypage') {
  // Do something meaningful.
}

```

# Answer
> 1 votes
Better to use block to display image. Use block visibility setting for displaying on specific URL.

---
Tags: 7, uri
---


title: drush coder-review in specified folder

text:
# Question
Title: drush coder-review in specified folder
How can i perform code review with coder\_review command in a specified folder? I see that i can give it contrib or core directives, but i would like to only check a folder in my modules folder like

/modules/dev

/modules/contrib/

/modules/custom/

How should i instruct coder-review command to check those modules (custom) only?

Tried `drush coder-review <folder-path>` that doesnt seem to work, is there any other option, or should i patch the module to accept my 'custom' directive?

# Answer
This was solved with a patch to coder module(7.x-1.2), introducing my custom command argument, "custom" which selects the modules i want form the database using a machine name query.

Coder review will never work on a file-system basis, since it grabs the module info from the database not the file-system.
> 1 votes

---
Tags: drush
---


# Question
Title: how to rename password label on user edit page in Drupal?
I would like to change labels only on user edit page. String overrides module would not work because it would rename all labels (user register and user edit). I tried the following:

```
function theme_preprocess_page(&$vars, $hook) {
  if ($vars['template_files'][2] == 'page-user-edit') {
    $vars['content'] = str_replace('Password', 'New Password', $vars['content']);
    $vars['content'] = str_replace('Confirm password', 'Confirm new password', $vars['content']);
  }
}

```

# Answer
> 8 votes
If you're willing to do it in a module (you mentioned String Overrides module) you can easily do it with a simple `hook_form_alter()` in a small custom module.

```
function mymodule_form_user_edit_form_alter($form, &$form_state) {
  $form['desired_element']['#label'] = t('My label');
  return $form;
}

```

This method uses `hook_form_FORM_ID_alter()`. This way you'll be able to set individual labels as you see fit, though.

# Answer
> 5 votes
The password inputs are in fact a separate form element (`password_confirm` -- Form API reference) and although it is themable (see theme\_password\_confirm), all you can influence is the description, prefix/postfix and element title.

The real work happens in expand\_password\_confirm, which in turn is a process function specified in system\_elements. The latter is an implementation of hook\_elements and it lets Drupal know how to handle various form elements.

Luckily, one can use `hook_elements()` to specify custom form elements and that is the one you can use to override the system processing for the password\_confirm element.

A sample implementation follows:

```
<?php
/**
 * Implementation of hook_elements()
 * @see http://api.drupal.org/api/drupal/developer--hooks--core.php/function/hook_elements/6
 */
function mymodule_elements() {
  $type['password_confirm']['#process'][] = 'mymodule_process_password_confirm';
  return $type;
}

/**
 * Do a bit of processing for the password_confirm element.
 * Original processing happens in expand_password_confirm()
 */
function mymodule_process_password_confirm($element) {
  // check if we the parent element is 'account'. On the user edit page, that is the case
  // Of course, one could use arg() to check the path too
  if ($element['#array_parents'][0] == 'account') {
    $element['pass1']['#title'] = 'New password';
    $element['pass2']['#title'] = 'Confirm new password';
  }

  return $element;
}

```

Please note this is based on Drupal 6. In Drupal 7, `hook_elements()` became hook\_element\_info because there is a proper alter hook, hook\_element\_info\_alter

# Answer
> 1 votes
Put the below code in your theme folder's template.php file. Just double check that your template.php already has an existing `YOURTHEMENAME_preprocess_page(&$vars)` function, in that case, only add what is inside the function below.

```
function YOURTHEMENAME_form_user_profile_form_alter(&$form, &$form_state, $form_id){

 $form['account']['current_pass']['#title'] = 'New Label';

}

function YOURTHEMENAME_preprocess_page(&$vars){

$vars['page']['content']['system_main']['account']['pass']['pass1']['#title'] = 'Some New Label for Confirm Password';

$vars['page']['content']['system_main']['account']['pass']['pass2']['#title'] = 'Some Other  Label Confirm Password';
}

```

# Answer
> 1 votes
This is a solution for Drupal 6, based on theme\_password\_confirm:

```
function MYTHEME_password_confirm($element) {
  foreach (array('pass1', 'pass2') as $part) {
    $element[$part]['#attributes']['placeholder'] = $element[$part]['#title']; // Set the title text as placeholder
    unset($element[$part]['#title']); // Remove the title.
  }
  $element['#children'] = ''; // #children holds the html output
  foreach (element_children($element) as $key) {
    unset($element[$key]['#printed']); // Prepare to re-render.
    $element['#children'] .= drupal_render($element[$key]);
  }
  return theme('form_element', $element, $element['#children']);
}

```

# Answer
> 1 votes
Working solution for Drupal 7:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'user_profile_form'){
      // Here we need to provide an extra #process handler to allow us to modify
      // the password element that FAPI expands.
      $element_info = element_info('password_confirm');
      $process = $element_info['#process'];
      $process[] = 'MYMODULE_process_password_confirm';
      $form['account']['pass']['#process'] =  $process;
    }
}
  function MYMODULE_process_password_confirm($element) {
    $element['pass1']['#title'] = t("New Password");
    $element['pass2']['#title'] = t("Confirm New Password");
    return $element;
  }

```

# Answer
> 0 votes
Try this one, hope it will work.

```
function your_module_form_alter(&$form, &$form_state, $form_id) {

  if($form_id == 'user_register_form') {

   $form['account']['pass']['#process'] = array('form_process_password_confirm',  'register_alter_password_confirm');

}

function register_alter_password_confirm($element) {

   $element['pass1']['#title'] = t("Password:");

   $element['pass2']['#title'] = t("Confirm Password:");

   return $element;

}

```

---
Tags: theming
---


# Question
Title: Custom module search ranking not working + ranking admin settings not showing properly
I'm using a custom module, with custom content type and custom search implementations and ranking. To rank the results I'm using the votes cast for the posts. But the voting system is custom too, i.e. it uses a custom table and not a standard drupal table. Now the problem is that:

1. The ranking doesn't work at all. I have set an influence value(content ranking factor) of 1 in the search settings for the ranking.
2. You know the ranking factors I mentioned above, in the search settings? It will only list my ranking factor, if and only if I enable the node module in the Active Search Modules section. As you might have figured I have my custom module in the Active Search Modules enabled.

Maybe problem #2 is the cause of #1?

The code for the `hook_ranking()` implementation is as follows:

```
function knowledge_ranking() {
    return array(
        'post_rating' => array(
            'title' => t('Post Rating'),
            'join' => array(
                'type' => 'LEFT',
                'table' => TABLE_POST_VOTES,
                'alias' => TABLE_POST_VOTES,
                'on' => TABLE_POST_VOTES . '.pid = i.sid',
            ),
            'score' => 'vote.average / CAST(:max_rating AS DECIMAL)',
            //I also did the following:
            //'score' => 'AVG(vote) / CAST(:max_rating AS DECIMAL)',
            'arguments' => array(':max_rating' => 5),
        ),
    );
}

```

It's worth mentioning that I have cleared cache, rerun cron and re-indexed the site several times.

Any help or tips are appreciated, thanks :-)

## Update 1:

Solved #2

You need to implement `yourmodule_search_admin()` and from there return that part of the form.

## Update 2:

I'm pretty sure that problem #1 lies within this line:

```
'score' => 'vote.average / CAST(:max_rating AS DECIMAL)',

```

So now I guess I have to put the average rating for each post in a field in the posts table. But there are gonna be a lot of more factors. So now the question is can't we use such complex scores at all?

# Answer
Finally I cracked this frigging case! As it turns out, there was no way for anyone to be able to answer this question since my given information was incomplete. Although in my defence if I knew that I should've given that info, I would've solved the problem long ago(two days) :-D.

## Solving problem #1:

Dead simple! In my case I had commented out the following line inside `hook_search_execute()`:

```
_node_ranking($query);

```

this functions adds the rankings to the results.

## Solving problem #2:

As for this problem, the influence choosing form doesn't show up automatically. The node module, if active in the Active search modules, lists all the factors for all Search active modules. But for a module to list its own factors, it must implement the `hook_search_admin()` function like this:

```
function hook_search_admin() {
  // Output form for defining rank factor weights.
  $form['post_ranking'] = array(
    '#type' => 'fieldset',
    '#title' => t('Post ranking'),
  );
  $form['post_ranking']['#theme'] = 'node_search_admin';
  $form['post_ranking']['info'] = array(
    '#markup' => '<p><em>' . t('Influence is a numeric multiplier used in ordering search results. A higher number means the corresponding factor has more influence on search results; zero means the factor is ignored. Changing these numbers does not require the search index to be rebuilt. Changes take effect immediately.') . '</em></p>'
  );

  // Note: reversed to reflect that higher number = higher ranking.
  $options = drupal_map_assoc(range(0, 10));
  foreach (knowledge_ranking() as $var => $values) {
    $form['post_ranking']['factors']['node_rank_' . $var] = array(
      '#title' => $values['title'],
      '#type' => 'select',
      '#options' => $options,
      '#default_value' => variable_get('node_rank_' . $var, 0),
    );
  }
  return $form;
}

```
> 0 votes

---
Tags: search, 7
---


# Question
Title: How to add Wishlist/Add to Cart in all products shown in front page in drupal 7?
I am work on commerce\_kickstart site. I was created 3 views in my front-page. In each view 3 products are there. I want to add Wishlist/AddToCart below in the list of every product. How can i do this. Please Help. Thanks

# Answer
Install and enable the Commerce Wishlist module and in views add the **Commerce Product: Add to Cart form** field, then you can see Wishlist/AddToCart button. Also Enable the checkbox "Link products added to the cart from this display to the current path the customer is viewing where the View is rendered".

Don't forget to set permission and configuration.

> Features
>
> * Provides an “Add to Wishlist” button on the display product node;
> * Creates a customizable list with Views to display all products on the Wishlist – both as a page and as a block;
> * Recognizes and stores product variations;
> * Makes it possible for users to easily delete or switch products in their Wishlist to their Shopping Cart with the click of a button;
> 2 votes

---
Tags: commerce
---


# Question
Title: Different front page template for different domains
I have Drupal 7 installation with the Domain Access module.

I need to have different page--front.tpl.php templates for some of the subdomains, for example:

www.example.com should have one type of the front page template (not a node, but some custom blocks and module outputs) and d1.example.com, d2.example.com and d3.example.com should have different kind of blocks, module outputs, forms, and template.

The style for the rest of the site should be pretty much the same for all domains.

How can I accomplish this?

# Answer
You can use a combination of the Context and the Delta modules to achieve this.

You can create a new instance of a theme using delta module and use context to use that instance for a specific module.

Alternatively, you can use Domain theme module (sub module of Domain module).

Let me know if you get stuck.
> 0 votes

---
Tags: 7, theming, domain-access
---


# Question
Title: Advanced forum topic list pagination settings is not applied
I tried to change the pagination settings (number of elements displayed) in the view corresponding to the topic list, but in the front end, this setting doesn't seem to be applied. the original value was 20 elements displayed, but the value really applied is 25. Does anybody know why is that and how can i set this setting properly ?

# Answer
> 0 votes
I found the solution : The pagination settings in the view are ignored, instead the number of topics displayed on a page is set in the forums configuration in /admin/structure/forum/settings

---
Tags: 7, views, paging, nodes
---


# Question
Title: Commerce Attribute price is not updating in cart
I am using commerce price attributes module then I am facing problem , price is updated on the product display node but not in my cart...also, there is no line item for the added price attribute.

Example :

In above images ,regular licence is showing price $2.00 and School licence is showing price $10.00. i select school licence then click on add to cart button but price is show $2.00 in cart.

# Answer
> 0 votes
Unfortunately, the https://www.drupal.org/project/commerce\_pricing\_attributes module and it's brethren (product options and product attributes) are a part of what I like to call the "hunziker approach." This removes the idea of separate SKUs per attribute. Which has the unfortunate effect of giving the masses what they expect and distorting/side-stepping a very deliberate separation of logic in Drupal Commerce. It would be like forcing Views to store taxonomy terms. It might make your task easier, but it is not the right approach.

The "hunziker" approach to Drupal Commerce is not supported nor recommended by the creators of Drupal Commerce. Thus, any problems you might have with the modules is "by design" unfortunately.

If you want attributes to update the pricing correctly, try creating separate product entities with unique and single attributes and attaching them to one single product display node.

---
Tags: commerce
---


# Question
Title: How can I generate commerce file audio preview automatically?
In a store of music files with the Commerce File module, how can I generate an audio preview of that file? Would be perfect if I could use the Rules module for detect the adding of file and SOX utility for audio trim (for example the first 20 seconds) and attach the generated file into another field.

If possibile compatible with Media and SoundManager2.

# Answer
This sounds like an awesome companion module that could be created and would be popular. From a bit of Googling, you can use SOX or FFMPEG-PHP and the exec() command to actually trim the audio file. From there, it's just a matter of saving this audio file to a new field. I would not use rules unless you need to expose it in the interface for some reason. You could easily achieve the programmatic saving of an audio field (probably a specialized file field) using any of a number of examples out there on the web.

Found an example here: https://stackoverflow.com/questions/7884960/ffmpeg-php-code-example-to-trim-mp3-file

```
<?php
exec('$ sox input.wav output.wav trim 0 10');
?>

```
> 0 votes

---
Tags: entities, commerce, files
---


title: how can I restore my site

text:
# Question
Title: how can I restore my site
I mistakedly erased a site from a server with ftp last night. Now luckily, I had a backup from not too long ago. I copied all the files from my back up directory back into my site using `filezilla` (I backed the site up using `wget`). Now when I go to my site, I gert an error like

> **Fatal error**: require\_once() \[function.require\]: Failed opening required 'includes/ckeditor.user.inc' (include\_path='.:/usr/local/php5/lib/php') in **/home/content/q/u/a/quaa7882/html/sites/all/modules/ckeditor/ckeditor.module** on line **48**

This error first appeared on my `apps` module. So I copied to `apps` directory out of the `sites/all/modules` directory but then, the same error appears again for the next module alphabetically so I assume it would appear for every single module. I tried to run `update.php` but I get a **Server error** in `Chrome`, it tells me:

> The website encountered an error while retrieving http://quaaoutlodge.com/update.php. It may be down for maintenance or configured incorrectly.

I'm wondering what might be going on here and how I can retore the site...?

Thank you!

**EDIt1**

The files in my backup directory are:

```
-rw-rw-r-- 1 ron ron 20581 Aug 24  2013 CHANGELOG.txt
-rw-rw-r-- 1 ron ron  2616 Aug 24  2013 ckeditor.api.php
-rw-rw-r-- 1 ron ron  3867 Aug 24  2013 ckeditor.config.js
-rw-rw-r-- 1 ron ron  3395 Aug 24  2013 ckeditor.css
-rw-rw-r-- 1 ron ron   354 Aug 24  2013 ckeditor.info
-rw-rw-r-- 1 ron ron 21467 Aug 24  2013 ckeditor.install
-rw-rw-r-- 1 ron ron 26478 Aug 24  2013 ckeditor.module
-rw-rw-r-- 1 ron ron   519 Aug 24  2013 ckeditor-rtl.css
-rw-rw-r-- 1 ron ron  3749 Aug 24  2013 ckeditor.styles.js
-rw-rw-r-- 1 ron ron 18092 Aug 24  2013 LICENSE.txt
-rw-rw-r-- 1 ron ron 21347 Aug 24  2013 README.txt
-rw-rw-r-- 1 ron ron 10521 Aug 24  2013 TROUBLESHOOTING.txt
-rw-rw-r-- 1 ron ron  1547 Aug 24  2013 UPGRADE.txt

```

---

**EDIT2**

I actually found my `ckeditor.user.inc` now, it was under `sites/all/libraries/includes/ckeditor.user.inc` instead and this is also where it is on my ftp. It's got a 175 lines of code and I didn't necessarily want to post the complete file unless required. What should I be looking out for?

# Answer
> 2 votes
Your backup is incomplete. Talk with your hosting company. In the meantime you can try to download fresh copy of ckeditor module, but even if it'll help, you will never know for sure what else is missing.

---
Tags: backups, files
---


# Question
Title: How to get specific fields in the login form
I'm trying to customize the login form. I added this to my template.php

```
function neptune_theme() {
  $items = array();
  $items['user_login'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'neptune') ,
    'template' => 'user-login',
    'preprocess functions' => array(
       'neptune_preprocess_user_login'
    ),
  );
  return $items;
}

```

and this is my user-login.tpl.php

```
<p><?php print render($intro_text); ?></p>
<div class="user-login">
  <?php print drupal_render_children($form) ?>
     <div class="links">
    <a href="/user/register">Create an Account</a> | <a href="/user/password">Forgot Password</a>
  </div>
</div>

```

I wanna know how to show the username, password and submit fields separately in the user-login.tpl.php file. I want to put the links for "Create an account" and "Forgot your password" before the Submit button.

I want to show something like

---

|Username |

---

---

|Password |

---

Create an Account | Forgot your password

---

|Submit|

---

Thank You. I hope it makes sense. :)

# Answer
> 0 votes
You can create a user login template. In your theme file, put this function in and replace your\_themename with the machine name of your theme.

```
function your_themename_theme() {
  $items = array();
  $items['user_login'] = array(
  'render element' => 'form',
  'path' => drupal_get_path('theme', 'your_themename') . '/templates',
  'template' => 'user-login',
  'preprocess functions' => array(
  'your_themename_preprocess_user_login'
  ),
 );
return $items;
}

```

Then, you can split the individual fields of the form up in a template file called `user-login.tpl.php` and rearrange them however you want.

```
<?php
    print drupal_render($form['name']);
    print drupal_render($form['pass']);
    print drupal_render($form['form_build_id']);
    print drupal_render($form['form_id']);
    print drupal_render($form['actions']);
?>

```

Source: High Rock Media

---
Tags: users, forms
---


# Question
Title: Taxonomy not working with the ECK module
I have created a image gallery using the ECK module and for some reason the taxonomy is not working.

These are the step I follow to created the image gallery.

1. Created a Entity called Media
2. Created a Bundle called Pictures
3. Add a Image Field (image field is from Flickr Field so all the images are been pull from Flickr)
4. Add a term reference field (taxonomy)
5. I created a views to display the images (http://test-darrylnorris.gotpantheon.com/media/pictures-gallery)
6. Finally add some images to the entity media --\> bundle pictures and some taxonomy.

But when I click on the taxonomy term is showing me this error

> There is currently no content classified with this term.

That's not true they are different taxonomy using the term. Also I'm using the Content Taxonomy to provide the Auto-complete field.

How can I troubleshoot this problem ? Or why my taxonomy terms are not working?

# Answer
> 0 votes
Someone answer my question on Drupal.org forums.

> Taxonomy only works with nodes. It's been hard-coded that way.

https://www.drupal.org/node/2339147#comment-9151769

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


# Question
Title: Organic groups, group content types and pathauto
In pathauto module settings I have

> localhost/\[node:group\_group\]

for all group types. I have few group types: Ex Technology, Arts, Design etc and within each group type you can create as many groups as you want.

So when I create a group named google, the path looks like this :

> localhost/technologies/google

.

I want to have any article created within that group and to have a path like this

> localhost/\[node:group\_group\]/\[node:title\]/\[content-type\]/\[title\]

Ex:

> localhost/technologies/google/article/some-article

How to achieve something like this? I could not find any token replacement pattern for my use case in pathauto module. Is there some trick here?

Thanks

# Answer
> 2 votes
I tried:

```
[node:og-group-ref:url:relative]/[node:menu-link:parent]/[node:title]

```

Worked like a charm.

So, I guess that you should go with:

```
[node:og-group-ref:url:relative]/[node:content-type]/[node:title]

```

*Note: Posted the answer since this was the first result on Google (for me), and no answer was given... Perhaps it will put someone else in the right direction faster.*

# Answer
> 2 votes
`[node:og-group-ref]/[node:title]` is what worked for me.

# Answer
> 0 votes
this isn't a complete answer as I only have one group type ("projects"), but within admin/config/search/path/patterns I use

```
projects/[node:group_audience]/[node:content-type]/[node:title]

```

for each of the different content types, unless I want the url to display a different term than that of the content type. I believe this would cover the

```
google/article/some-article

```

part of your string. Presumably you'd just put your

```
[node:group_group]

```

in place of my "projects," unless \[node:group\_group\] produces "technology/google," in which case go with

`[node:group_group]/[node:content-type]/[node:title]`.

# Answer
> 0 votes
For me, this worked:

1. Install sandbox module `og_token`.
2. Apply patch `og_token-og_7.2-1930132-1.patch` to `og_token`, as per Drupal issue #1930132 comment 1.
3. Optionally, if you want the tokens to use the group's URL alias rather than group title: in file `og_token.module`, exchange function `og_token_get_group_labels()` with this:

```
function og_token_get_group_labels($nodes, $options) {
  $labels = array();
  $sanitize = !empty($options['sanitize']);

  foreach ($nodes as $group) {
    $label = drupal_get_path_alias('node/' . $group->nid);
    $labels[] = $sanitize ? check_plain($label) : $label;
  }
  return $labels;
}

```
4. Set your pathauto pattern to:

```
[node:og-group-audience:first]/[node:content-type]/[node:title]

```

This solution is based on lahode's work. It achieves the same effect as the answer by @Marcus Farrington to this very question, which for me does not work with the latest versions of modules `og`, `token` etc..

All these problems with OG tokens are discussed at length in Drupal issue #1088538.

---
Tags: 7, organic-groups, path-aliases
---


title: How do I create a photobox for image?

text:
# Question
Title: How do I create a photobox for image?
Can anyone please guide me on how do I create a photobox that contains image and I wanted to display that image on landing page.

I have created content type as an Image. But, I don't know how to display that image in landing page.

I am new to Drupal. Any help will be appreciated.

Thanks!

# Answer
> 1 votes
First of all: welcome to Drupal :) But then I right away have say *sorry*, but I think it's not really a good idea to ask people to "*guide you on how to…*". People here try to ask straight questions and give straight answers – if they can.

About your actual question: for displaying a specific page as your front page a.f.a.i.k. all you have to do is to go to **Configuration** \> then **Site Information** \> then you can adjust the **Default front page setting** by entering the path of any of your pages… Hope this helps…?

And last but not least I can just recommend you spend some time with some basic recources and tutorials – for example Drupal 7 – the Essentials is sheer greatness! And the Community Documentation has almost every important aspect of Drupal listed, that one could need for a start…

# Answer
> 0 votes
with tillinberlin answer I would like to add. tillinberlin told you about landing page. here I want to tell you about display images

Even I am doing same thing I gone through the YoxView and fancyBox modules to view of my images.

choose one to view your images which best suites for you.

# Answer
> 0 votes
@tillinberlin

I don't have question for "displaying a specific page as your front pag".

I asked question for "**Image.**" Anyways Thanks for some information though!!

I have created specific image style for my image box by going into "Configuration -\> Image Styles.

I have created Content Types for image.

For example lets say, Content type is: "Top Left Image". I have defined fields called "Image Name" and "Image" into "Top Left Image".

Then I have created one view called " Top Left Imagebox". In view, I have defined fields called Content: Image.

Formatter: Image

Image Style: Selected specific image style.

Link Image to: Nothing

I have used **Rewrite Rule** to make a view that displays image or video filed if present.

No Results Behavior: **\[field\_image\]**

Checked - **Hide rewriting if empty**

Checked Rewrite the output of this field.

I have defined this view into my Landing Panel Page. But, somehow **image is not displaying into the browser.**

Yes, I am using **Drupal-7**.

Thanks!

# Answer
> -1 votes
To get an image or any other field as content you should:

* Edit your page.tlp.php
* if theres only one image and if your field has a machine name 'image': **$image\_url** = file\_create\_url($node-\>image\["und"\]\[0\]\["uri"\]);

> **$node** is where your content is stored
>
> **"image"** followed by "-\>" is your machine name where you get by array all values related to your field
>
> and final **file\_create\_url()** converts your uri to url like the method's name suggests

To output your image you can do something simple like this:

```
<?php
   (...)
      $image_url = file_create_url($node->image["und"][0]["uri"]);
      echo "<img src='{$image_url}' width='300' />";

   (...)
?>

```

You can always add a module like this one Photobox to get the job done. I am assuming that your are using D7. please precise your Drupal's version next time :)

---
Tags: views, panels, media
---


# Question
Title: How can I preview the Drupal page as specific users?
I just started using Drupal, so I'm still learning myself how to configure it. I have seen some older tutorials where there's a module(?) installed where you can click on "Hello %user%" in the top right corner and select which user you want to preview the page as. Is there a module for this or some built in setting I have overlooked?

# Answer
The module called masquerade can do it. Not sure if it is the one you are refering to though.

> The masquerade module is designed as a tool for site designers and site administrators. It allows a user with the right permissions to switch users. While masquerading, a field is set on the $user object, and a menu item appears allowing the user to switch back. Watchdog entries are made any time a user masquerades or stops masquerading.
> 0 votes

---
Tags: 7
---


# Question
Title: Registration and Login form having different styles
I'm trying to style the login and registration form in different styles in my drupal 7 website. By default they share the same styles. Is there any way to change that?

# Answer
> 0 votes
Add this to your theme's template.php file:

```
function MYTHEME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register_form') {
    $form['#attached']['css'][] = path_to_theme() . '/css/user-register-form.css';
  }
  elseif ($form_id == 'user_login') {
    $form['#attached']['css'][] = path_to_theme() . '/css/user-login.css';
  }
}

```

And then define your two css files.

# Answer
> 1 votes
take a look at the themekey module:

> ThemeKey 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.

---
Tags: forms, users
---


# Question
Title: Views Eposed filter - proximity search, include content without a postal code
I have a proximity search set up using gmap location by postal code. Using Drupal 7/Views 3. The exposed filter allows the user to filter by (taxonomy)type and/or postal code.

This is what I need to Do: Include some content that will not have a postal code in all results. I already set up a view of this content (without postal code) to display as no results behavior. but I would like to include this same content in all searches. How do I do this?

# Answer
> 0 votes
If you can not do it with the 'And/Or' option on the filters (accessed by clicking the little arrow next to the filters in the views ui). This is the best option.

Or you could use hook\_views\_query\_alter to add something like "or where postcode = '' ".
I can not really go into detail of adding to the query as I dont know the structure of your query but you can take a look at the database api or search google.

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


title: Can't set options on form ajax callback

text:
# Question
Title: Can't set options on form ajax callback
I have created a custom form in a custom page in the admin of my Drupal 7 site. On this form I have two sets of radio buttons (cities and sectors). I want it so that when I change the cities radio selection, the sector radio values swap to my new set values.

I have the following code in the main form declaration which initially sets up the form.

```
$form['module']['cities'] = array(
    '#type' => 'radios',
    '#title' => t('City'),
    '#ajax' => array(
        'event' => 'change',
        'wrapper' => 'sector-wrapper',
        'callback' => 'module_field_city_change_ajax_callback',
        'method' => 'replace',
    ),
    '#options' => array("1" => "New York", "2" => "Moscow"),
    '#required' => TRUE,
);

$form['module']['sectors'] = array(
    '#type' => 'radios',
    '#title' => t('Sectors'),
    '#prefix' => '<div id="sector-wrapper">',
    '#suffix' => '</div>',
    '#options' => array("Sport"=>"Sport", "Media"=>"Media"),
    '#required' => TRUE,
);

```

This creates forms. You can see I've added a callback 'module\_field\_city\_change\_ajax\_callback'. The code for the callback is as follows:

```
function module_field_city_change_ajax_callback($form, $form_state){
    $form['module']['sectors'] = array(
        '#type' => 'radios',
        '#title' => t('Sectors'),
        '#prefix' => '<div id="sector-wrapper">',
        '#suffix' => '</div>',
        '#options' => array ('Aerospace' => 'Aerospace', 'Art' => 'Art' ),
        '#description' => t('Some text to show the div was updated?'),
        '#required' => TRUE,
    );
    return $form['module']['sectors'];
)

```

It almost works. The old sectors are updated with the new form element apart from one major part - the actual radio buttons (#options). I know the div has updated and the form rendered because it has the text 'Some text to show the div was updated?' injected. However there are just no values to click.

Any ideas?

# Answer
> 0 votes
I recently answered a question similar to this over at stack.

Basically, you should be doing all the form building and manipulation in the form builder function. The ajax callback function in your case should just return the form element.

This is because when the ajax is fired, just before the ajax callback function is executed, the form is rebuilt and the form building function is executed again (this time with a different form\_state which will include the ajax elements current state)(I think).

So you would have something similar to:

```
$form['module']['cities'] = array(
    '#type' => 'radios',
    '#title' => t('City'),
    '#ajax' => array(
        'event' => 'change',
        'wrapper' => 'sector-wrapper',
        'callback' => 'module_field_city_change_ajax_callback',
        'method' => 'replace',
    ),
    '#options' => array("1" => "New York", "2" => "Moscow"),
    '#required' => TRUE,
);

  // Check if a city is selected and set sectors
  //something like this.

  // $sectors = array("Sport"=>"Sport", "Media"=>"Media");
  // if(city is selected){
  //   $sectors = array ('Aerospace' => 'Aerospace', 'Art' => 'Art' );
  // }

  // you should be able to check if a vocabulary is selected by checking the
  // $form_state['values'] or $form_state['input'] (I forget which)

$form['module']['sectors'] = array(
    '#type' => 'radios',
    '#title' => t('Sectors'),
    '#prefix' => '<div id="sector-wrapper">',
    '#suffix' => '</div>',
    '#options' => $sectors,
    '#required' => TRUE,
);

```

ajax callback

```
function module_field_city_change_ajax_callback($form, $form_state){
    return $form['module']['sectors'];
)

```

---
Tags: forms, ajax
---


title: Organic Groups and Panels

text:
# Question
Title: Organic Groups and Panels
I've got Panels working with Organic Groups (d7) using the documentation about "Drupal 7 Panels integration guide (OG 7.x-1.x)". It describes how to create a node panel that detects when you are viewing a group and then displays the layout accordingly.

This is great, however, I would now would like to create a new variant that would allow more specific customization of a specific group. Say for example I have a special group called "Education" that would need to arrange their group home page slightly different from others.

I have made some adjustments to what I think would do the trick, but it does not work. Here is what I have done:

* Cloned the original varient from the documentation
* Under Contexts, added a new context "Organic groups group" and specified the group id of the "Education" Group
* Under Selection rules, added a new "Context exists", and selected my context created in the above step
* Made some adjustments to layout
* Saved, and reordered variants to make this one come first

This worked.... however for some reason it applies to all groups not just to my "Education" group. Again, I would like to have a custom layout for my "Education" group, and have a default layout for the rest. I'm still new at panels, can anyone spot what I'm doing wrong based on my description?

# Answer
> 3 votes
You could also try specifying by url string "education/\*" or even node ID instead.

# Answer
> 2 votes
My guess is that your contexts are set to "only one criteria must pass" instead of "all criteria must pass". To change this, go to selection rules and select "all criteria must pass" at the bottom, then save.

# Answer
> 1 votes
**How it's meant to work.** Selection rules are designed to work for group content selection like this:

1. In your Panel variant's "Selection rules" section, add the selection rule "Node : groups audience field" (or whatever your `og_group_ref` field is called there).
2. In the form that appears, select the group that you want to create the group default panel for.
3. If your group may contain several node types, configure "Only one criteria must pass." in your selection rules section and repeat steps 1-2 for each node type.

This method is however effectively blocked by Drupal issue #2242511 at the moment. (The issue thread mentions a workaround, but it's impractical.)

**Your misunderstanding: two things called context.** In total, it seems you (like myself) had misunderstood what a "context" is in Panels. It's a way to pass in arguments to the content elements of a panel, similar to what "contextual filters" do for Views. The "Context exists" use is just a side use of this, which can be used to check if a certain argument is supplied at all. "Context exists" has *nothing* to do with "context is set" of the `context` module – the `panels` and `context` modules have nothing to do with each other, as there is no dependency between them. It's just two different things called "context" ...

**More options.** For a discussion of other working and non-working alternatives to create group-specific default panels in Drupal 7, see my blog post about it.

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


# Question
Title: How do I do per-item shipping based on the number of products?
I'm doing a favor for a family member by helping set up their store. I've never worked with Drupal before.

They are selling one item, but they want the shipping cost per item to change based on the number of items purchased.

* 1 item - $3.50 shipping
* 2 to 9 items - $2.75 shipping PER ITEM
* more than 10 items - $2.00 shipping PER ITEM

After a few hours of research I half-understand the rules system, but I can't figure out how to combine rules like this. Can anyone point me in the right direction?

# Answer
> 2 votes
Pontus Nilsson has the right idea, just shared it as a comment instead of an answer?

I decided this was a good teachable moment (this also turned out to be a head scratcher at more than one turn), so below is the screencast of how to do this and a step-by-step:

https://www.youtube.com/watch?v=trLydGpimD4

**STEP BY STEP**

1. Install https://www.drupal.org/project/commerce\_shipping and https://www.drupal.org/project/commerce\_flat\_rate
2. Create three different flat rates (I recommend you keep the "Title" different, but change the "Display Title" to be the same, so the rate change is transparent to the user)
3. Configure each flat rate component to have a condition on "Total product quantity comparison" so that only the appropriate rates show up based on number of products. Note this will only work if you use the standard line item type "Product" ... if you have custom line item types, you will have to create a component that does the comparison/counting that you need.
4. In order to count the number of eligible products, we will need to create a component rule that has a "line item" parameter and has an "number decimal" provided called "is\_a\_product".

This component simply needs to have a condition on entity bundle for "Product" and needs an action that "sets a data value" ... the is\_a\_product ... to the line-item:quantity.

5. Next, we will need to create a pricing rule for your first "Medium" level shipping price calculation.

A. Once you discover where to create the shipping price calculation rule you will need to create two conditions:

* Entity has field (it should have the shipping service field)
    * Data Comparison (the shipping service field should equal the medium shipping service)

B. Now you will need to count the number of products. Let's add an action "create a variable" for an number decimal called "num\_products"

C. Next you will need to loop over all the line items in the order.

D. Next you will add an action for the component you created in step 4.

E. Then you will need to "Calculate a value" by adding the "num\_products" and the "is\_a\_product" (through some testing I confirmed the integer is zero by default) and then save the result by "setting a data value" and setting "num\_products" to the result value

F. Finally, you will need to "Multiply the unit price by some amount" and select the num\_products as the multiplier
6. Repeat step 5 for each breakdown of product quantity rate change

---
Tags: commerce
---


# Question
Title: Non-Members of Organic Group can still view Node links
I'm on Drupal 7 with Organic Groups installed. I've created a Private Group for my IT Team, meaning that only members of that group can see the group content.

The problem I'm seeing is that when I publish group content, Non-Members can still see the node link from the homepage, and click on it, even though the content is not displayed.

How can I make group content only visible to group members? (Meaning, the node itself is not visible to non-members.).

# Answer
> 5 votes
Please allow me to offer helpful insights even 6 months after your posted question. Hopefully, this will help others who are struggling with the Drupal module OG as well.

Note that in your content type, you should already have bundled **Group content visibility** as another field. Go to `/admin/config/group/fields` to accomplish this:

In this picture as my live example, note that my **Content Group** is the Group content type and that the **Content Group Submission** is the content type FOR hosting **articles** that should only be visible to any particular group. What you need to do is bundle **Group content visibility** as a new field for this content type as shown below.

This means that you will have **Group content visibility** field as an additional field to your own content type.

The **Groups audience** field is meant to make content authors specify the intended audience of the content they are authoring. The **Group content visibility** field is meant to make content authors specify the exposition criteria of that particular content. This is best shown in the following two pictures. Let us now look at the field set of my content type **Content Group Submission**. In my example, I went to `/admin/structure/types/manage/content_group_submission/fields`.

If you edit this field, you will see its values to be constrained to the following options by default:

```
- None -,
Use group defaults,
Public,
accessible to all site users

```

and Private - `accessible only to group members`.

The last one appears to be what you are interested in. You should make that as your default value for this field.

Save all of that. And your content authors will be offered with these options. In my case, go to `/node/add/content-group-submission`.

And this is how your content authors would be able to constrain your article's exposition to only his/her intended groups. By this method, non-group members would not be able to see nor access the nodes (even titles only) that are intended for private groups where they do not belong.

# Answer
> 3 votes
If your content links are being displayed in a View, you need to configure the View with a Relationship to the OG user membership. Then, you will be able to set a filter to only display nodes of which a user is a current member.

# Answer
> 1 votes
another option is to make group content visible only to group member by default is to implement hook\_node\_access in a custom module like this:

```
/**
 * Implements hook_node_access()
 */
function mymodule_node_access($node, $op, $account){
    if($op=='view' && isset($node->og_group_ref[LANGUAGE_NONE])){
        $user=user_load($account->uid);
        $node_og_group_nid=$node->og_group_ref[LANGUAGE_NONE][0]['target_id'];
        $user_og_group_nid=$user->og_user_node[LANGUAGE_NONE][0]['target_id'];
        if($node_og_group_nid!=$user_og_group_nid) return NODE_ACCESS_DENY;
    }
}

```

# Answer
> 0 votes
If you use the 'group content visibility' option, you will only hide the content, and you would still see the link as a non-member.

If you don't want the link to show up at all, you have to add the field "Group Visibility". To add the field go to `/admin/config/group/fields`.

This will hide the group link as well as all of the content inside.

---
Tags: organic-groups, users
---


# Question
Title: how to add #states property to an $element of the custom field?
i develop a custom field and have some errors on property #states.

The method of using #states in $element is quiet different with the $form.

The code i write is below.

```
 function cellphonefield_field_widget_form(&$form,&$form_state,$field,$instance,$langcode,$items,$delta,$element)
    {
        $base=$element;

        $element['cellphone']=array(
         '#type' => 'textfield',
         '#title'=>t('Enter your Cell phone Number!'),
         '#description'=>t('System will send you a message '),
         '#default_value'=>isset($items[$delta]['cellphone'])?$items[$delta]['cellphone']:'test for this field',
         '#weight'=>0,
        )+$base;

      $element['send_sms']=array(
         '#type' => 'button',
         '#name'=>'send_sms',
         '#title' => t('validate your cellphone number'),
         '#weight'=>1,
         '#value'=>t('Send the validation code!'),
         '#ajax'=>array(
            'callback'=>'ajax_send_sms_callback_function',
            'wrapper'=>'replace_markup_to_textfield',
            'effect'=>'fade',
            'speed'=>'fast',
            'method'=>'replace',
         ),
         '#states'=>array(
            'disable'=>array(
              ':input[name="profile_main[field_cellphone][und][0][cellphone]"]'=>array('filled'=>TRUE),
            ),
         ),
        );

    $element['validation_fieldset']=array(
    '#type'=>'markup',
    '#weight'=>2,
    '#prefix'=>'<div id="replace_markup_to_textfield">',
    '#suffix'=>'</div>',
  );

   return $element;
}

```

No matter what i replace the input name of the #states, it's still not working.

i checked the html form and the code blow

```
<input type="text" id="edit-profile-main-field-cellphone-und-0-cellphone" name="profile_main[field_cellphone][und][0][cellphone]" value="" size="60" maxlength="128" class="form-text" />

```

what could the problem be?

# Answer
`drupal_process_states()` takes the parameter `$elements` and contains the example:

```
array(
  'visible' => array(
    ':input[name="remote_checkbox"]' => array('checked' => TRUE),
  ),
)

```

Your example is very similar:

```
array(
  'disable'=>array(
    ':input[name="profile_main[field_cellphone][und][0][cellphone]"]'=>array('filled'=>TRUE),
   ),
 )

```

But I noticed that 'visible' is an adjective while 'disable' is a verb so I checked the list of available states on the `drupal_process_states()` documentation and found:

> The following states may be applied to an element:
>
> * enabled
> * disabled
> * required
> * optional
> * visible
> * invisible
> * checked
> * unchecked
> * expanded
> * collapsed

So it looks like your problem boils down to a missing letter 'd' on 'disabled'.
> 1 votes

# Answer
Did you tried with the input id instead the name?:

```
'#states'=>array(
  'disable'=>array(
    '#edit-profile-main-field-cellphone-und-0-cellphone'=>array('filled'=>TRUE),
  ),
),

```
> 0 votes

# Answer
I created a function for when I need to use #states in hook\_field\_widget\_form. It looks like this:

```
function jquery_selector($field_name,$langcode,$delta,$item_name){
  $jquery_selector = '\':input[name="' . $field_name . '[' . implode('][',
    array($langcode,$delta,$item_name)) . ']"]\'';
    return $jquery_selector;
 }

```

In your hook\_field\_widget\_form implementation you can use it like this:

```
'#states'=>array(
        'disable'=>array(
          jquery_selector($instance['field_name'], $langcode, $delta,
          'cellphone')=>array('filled'=>TRUE),
        ),
     ),

```
> 0 votes

---
Tags: 7, javascript
---


title: Change title of webform

text:
# Question
Title: Change title of webform
I added a webform to my site. Everything works fine, except that the title (surrounded red) is saying "webform", but I want it to change to "Kontakt" (as the title in the form itself).

Theme is "TB Corpal".

Two questions:

1. What is the right terminology for this type of title? Is this just called "title" or what is the proper name in drupal?
2. How can I change that? (I already tried the module "Automatic Nodetitles" but this changes just the title in the form istself)

Or can I do this using "views"? If yes, how?

# Answer
I got an answer here: http://www.themebrain.com/question/how-change-string-title-bar

Worked like a charm!
> 0 votes

# Answer
Sounds like the theme you are using is doing this. The answer may have nothing to do with the Webform module. When you use a Theme provided by a company that sells themes, you are building your site ontop of a site that they already built for you. Yes, this saves some time, but sadly, you have to find out how that site works. Often times, they have made some "very interesting" decisions that can not be easily explained.

Do you have a link to this page? I am wondering if maybe that title is appearing in a BLOCK. If you mouse over that title, does a gear appear to the far right of that title?

As for the terminology, I do not know. This does not sound like the way Drupal handles titles. I suspect the crew that built this theme made interesting decisions. The webform module simple creates nodes where the content is fields. Each webform-node has a node-title in the same way that all nodes have titles. To edit the title of a node, simply edit the node and change the title and save it. The new title should appear. If this is not how your site works, then whoever built the theme is doing something very strange.

I hope that helps.
> 1 votes

---
Tags: views, theming
---


# Question
Title: Stop caching for a specific node (by nid) Drupal 7
Ideally i want to set custom params for caching in some particular nodes using conditions in my **template.php**

***E.g. algorithm:*** *for node with known **nid** set custom caching params*

But that's enough for my purpose simply exclude from caching particular node. I fond this solution: Stop caching for a specific node type Drupal 7 this is exacly what im looking for but how i can change condition of checking from node type to nid.

I know about CacheExclude module, but for me unwanted to install module for just exclude one node for caching.

I'll be very grateful for helping me.

# Answer
> 0 votes
A module with the below in it should stop caching on node 2. Change the number to do it on a different node id.

```
function MYMODULE_init(){
  if (arg(0) == 'node' && arg(1) == 2) {
    drupal_page_is_cacheable(FALSE);
  }
}

```

---
Tags: theming, caching
---


# Question
Title: Drupal 7, Entity Reference user autocomplete field
I have a custom content type that has a users: entity reference autocomplete field. For some reason the list gets populated as \[realname\] (\[name\]). In other words the realname and username tokens are both shown in the autocomplete list. Is there a way to only show the realname token?

I would like to go from this...

To this

# Answer
> 0 votes
Set up a view for the autocomplete.

You can use this tutorial: http://speaksdrupal.com/blog/custom-entityreference-handlers-using-views

Then add that as the view to use for autocomplete.

http://screencast.com/t/8m0O7F8zV

Whatever fields are searched will show up in the drop down. So if you remove e-mail from the list of fields searched, it won't show up in the drop-down.

---
Tags: ajax, entities
---


title: My theme is automatically disabled!

text:
# Question
Title: My theme is automatically disabled!
My Drupal website has a sub-domain. there is a theme that is in the sub-domain folder. the `settings.php` in the sub-domain folder is same as the one that is in the `/default` folder so they both display the same web page. the problem is after a few hours this theme is automatically disabled and I have to enable it again.

why such thing happens?

# Answer
Do you mean you have 2 URL (www.ex.com and sub.ex.com) with the dir/ and files:

```
/sites

   all/

      themes/

      modules/

   www.ex.com/

      themes/

        your_theme/

   sub.ex.com/

```

and no "/sites/sites.php" in here? (read for ex "example.sites.php")

And selected in www.ex.com/admin/appearance for ex bartik as default and for sub.ex.com/admin/appearance "the your\_theme" as default (and clear cache)?

and each time, you need to go in sub.ex.com/admin/appearance in order to set "the your\_theme" as default, with no error in logs?
> 0 votes

---
Tags: theming, subsites
---


title: How to set a value for a date field?

text:
# Question
Title: How to set a value for a date field?
I need to set a value for a date field with type datetime in `hook_form_alter`. I tried with below codes. But it is not working.

```
$form["field_event_date"]["und"][0]['#default_value']['value'] = $new_date;
$form_state['values']['field_event_date']['und'][0]['value']['date'] = $new_date;
$form['field_event_date'][LANGUAGE_NONE][0]['#default_value']['value'] = $new_date;

```

This `$new_date` will be a value from another field in this form and it should be in '2014-09-23 00:00:00' format. And 'field\_event\_date' will be a hidden field.

I can save the value to this field using the `node_presave` function. Please see the below code. If anyone trying to save a value to a date field with a static value, you can use this method.

```
function MY_MODULE_node_presave($node) {
     $node->field_event_date['und'][0]['value'] =  '2014-09-23 00:00:00';
}

```

But in my case, I need to get the value from a field that defined in the form alter. And need to set this value to the field\_event\_date. Can anyone help me on this? Is there any way to get a custom field value in `node_presave` function?

# Answer
> 2 votes
To set a value to a date field follow below codes.

Using hook\_form\_alter

```
$form["field_event_date"]["und"][0]['#default_value']['value'] = $new_date;

```

Using hook\_node\_submit or hook\_node\_presave (Saving the value to the database)

```
 function MY_MODULE_node_presave($node)
  {
      $node->field_event_date['und'][0]['value'] =  '2014-09-23 00:00:00';
  }

```

Or if you need to save value of one custom field(defined in hook\_form\_alter) to another, see below codes.

```
function MY_MODULE_node_submit($node, $form, &$form_state) {
  if($node->type == 'my_node_type') {
    $test_date =  $form['test_date ']['#value'];
    //Ensure that $test_date format is '2014-09-23 00:00:00'
    $node->field_event_date['und'][0]['value'] =  $test_date ;
   }
}

```

I think it may help anyone who is searching for the solution.

# Answer
> 1 votes
It depends upon the format you are providing to save the date, whether it is unix or formatted date. Pick one already saved node using **node\_load($nid)** in your form\_alter function or in some other testing page and check the format the data is saved.

```
    $nodesaved = node_load($nid); //e.g. $nid = 10
    echo "<pre>";
    print_r($nodesaved);
die;

```

Now pass the same format statically and then make it dynamic. I think issue is with the format you are providing. Usually it is in unix, it converts automatically in the display

Hope it will help!

# Answer
> 0 votes
I got it worked using hook\_node\_submit function. Let test\_date is a custom select field that list dates and this is defined in hook\_form\_alter. And to set and save the value from this date field to another field field\_event\_date(defined in field base and instance). Please follow below codes.

```
function MY_MODULE_node_submit($node, $form, &$form_state) {
  if($node->type == 'my_node_type') {
    $test_date =  $form['test_date ']['#value'];
    //Ensure that $test_date format is '2014-09-23 00:00:00'
    $node->field_event_date['und'][0]['value'] =  $test_date ;
   }
}

```

---
Tags: 7, datetime, forms
---


title: User directories for blog images

text:
# Question
Title: User directories for blog images
I am setting up a multi-blog site in Drupal. I'm currently learning Drupal and I'm a beginner. I am setting up Organic groups, to make blogs for groups. I have added CKEditor to get RTE in the text fields for the blog entries. I have also added IMCE to be able to upload images in the RTE.

Now my question is. How can I give each user an individual folder for uploading files? I don't want the users to access the full upload root.

# Answer
Seems like I had to assign a profile to my user role. Configuration\>Media\>IMCE. Create a profile with access to browse, upload, thumbnails, delete and resize for \users\user%uid. Atleast that worked for me.
> 2 votes

---
Tags: users, files
---


# Question
Title: Fieldable panels panes - add a default category when creating
With Fieldable panels panes is it possible to programatically add a default category for all reusable entities?

Im adding new instances as follows, but it would be great if I could hard-code or even just suggest a category for all panes of this type to be created under. This way the Panels IPE wouldn't be such a mess if (when) editors don't set a category and everything gets lumped into 'Reusable Content'.

```
function logic_pane_bundles_entity_info_alter(&$entity_info) {

$entity_info['fieldable_panels_pane']['bundles']['poster_pane'] =
array(
    'label' => t('Poster Pane'),
    'pane category' => t('Hello bundles'),
    'pane top level' => TRUE, // set to true to make this show as a top level icon
    'pane icon' => '',
    'admin' => array(
        'path' => 'admin/structure/fieldable-panels-panes/manage/%fieldable_panels_panes_type',
        'bundle argument' => 4,
        // Note that this has all _ replaced with - from the bundle name.
        'real path' => 'admin/structure/fieldable-panels-panes/manage/poster-pane',
        'access arguments' => array('administer fieldable panels panes'),
    ),
);

```

}

Many thanks!

# Answer
Currently it's not possible to assign a category in hook\_entity\_info\_alter. See feature request https://www.drupal.org/node/2149989

To achieve this, couldn't you just fill the category form field, using hook\_form\_alter in a custom module, like in my other answer?
> 1 votes

---
Tags: 7, panels
---


# Question
Title: How to detect which module creates session?
I am trying to achive Varnish HIT for anonymous user but get only MISSes.

It seems that my Drupal 7 site somehow starts new session for every anonymous user which opens even main page of the site. I want to detect which module makes session to start?

# Answer
Unless you have a strong suspicion on a particular module or a small number of modules that could be creating a session, finding the 'culprit' module could be too tiresome.

I would suggest searching for the 'cookie name' instead of a string like '\_SESSION' as a more accurate and a faster way.

Say if the cookie name is 'PLAY\_ACTIVE\_ACCOUNT' (real example from site play.google.com), you could navigate to the parent directory of your contrib module and do a `grep -iRn PLAY_ACTIVE_ACCOUNT *` to find the filename and line number of where this session cookie is being set. And then disable the module or take other action.

You can discover the name of your cookie by using your browser. In chrome you could do this by typing `chrome://settings/content` in a new tab and then clicking on the button 'All cookies and site data'. And then typing in the name of your site domain (like I have used play.google.com for example)
> 2 votes

# Answer
If you think this is a problem in one of the contrib modules installed, you could either deactivate them one after the other to see when the problem goes away, or you could search the code for anything that initializes a session.

The link you posted in the comment can be a viable starting point. My first search would go like this though: `grep -r '_SESSION' *`

Issued from the root of your contrib modules, e.g. sites/all/modules.
> 1 votes

# Answer
You'll need to look into the database to get the module name from the session cookie.
> -1 votes

---
Tags: sessions, proxies
---


# Question
Title: How to extend entityreference field by another custom field?
I want to add another field, which needs to be accessible by views (for display and ordering), to the entityreference table field\_data\_field\_FIELDNAME. Structure of that table is:

* entity\_type VARCHAR(128)
* bundle VARCHAR(128)
* deleted TINYINT(4)
* entity\_id INT(10)
* revision\_id INT(10)
* language VARCHAR(32)
* delta INT(10)
* field\_FIELDNAME\_target\_id INT(10)

I want to have a column storing DateTime information here, so I can attach information about when this reference was added/ updated for that referenced entity. There also needs to be a way to save the newly added field directly in the array structure for that reference such as:

```
$node->field_reference['und'][] = array(
  'target_id' => 123,
  'my_new_column' => '2014-03-13 15:29:29'
);

```

I know I could solve this by using field\_collections or relation module, but both would cause significant performance issues.

# Answer
Gave an approach here https://www.drupal.org/node/2001822#comment-9165509

Hope that it will work for you
> 2 votes

---
Tags: entities, views
---


# Question
Title: Views are disappearing randomly; always needing to flush caches
I am writing a module that has 2 views in code. At first, I pasted the code that was exported from views directly into hook\_views\_default\_views() like so...

```
function MY_MODULE_views_default_views() {
  $views = array();

  // Copy and pasted code from views export here...

  $views[$view->name] = $view;
  return $views;
}

```

After installing the module, the only way to get the views to show up would be to run cron and then flush the caches. I tried just running cron, or just flushing caches, and it would only work if I ran them both in that order. Once the views showed up, I could go along with things fine for a little while, then randomly the view would disappear again. I could not figure out a pattern to why they would disappear. Flushing caches would mostly fix it. Sometimes I had to flush caches two or three times or run cron and flush caches to get the views to appear again.

I searched around for some help and was able to find this post... A whole view disappears. This seems to be a similar problem. The function is too long and each view needs to be split into separate files. Okay, I did that and now my code looks like this...

```
// Files located in "my_module/views":
my_module.view_1.view
my_module.view_2.view

/**
 * Implementation of hook_views_default_views().
 */
function MY_MODULE_views_default_views() {
  $views = array();
  $files = file_scan_directory(drupal_get_path('module', 'MY_MODULE'). '/views', '/.*\.view$/');
  foreach ($files as $filepath => $file) {
    require $filepath;
    if (isset($view)) {
      $views[$view->name] = $view;
    }
  }
  return $views;
}

```

This is a nice solution as it makes adding new views very easy and clean. However, I am having the exact same experience as before. After installing the module, it still takes a cron run and a cache flush for the views to show, which they eventually do, but then they still disappear randomly. The only way to get them back is to flushes the caches (sometimes several times), or run cron and flush caches.

I'm feeling pretty stuck here. If anyone would be so kind as to offer some guidance, that would be most appreciated. Thank you.

# Answer
Thank you so much to kladria on IRC #drupal-support for helping me through this one!

After using a debugger to step through the code, I saw that my implementation of hook\_views\_default\_views() was not being called. The problem I was having was that the function was in the wrong file. Originally, I had the function "MY\_MODULE\_views\_default\_views()" in the file "My\_MODULE.views.inc", and it is supposed to go in "My\_MODULE.views\_default.inc". That "\_default" made all the difference for it to be auto-loaded correctly.

So far, there has been no more needing to flush caches, and the views haven't disappeared. I'm pretty sure this did the trick.
> 1 votes

---
Tags: views, caching
---


# Question
Title: Im using entityforms to make events on a Calendar. How can i prevent duplicated dates?
I am developing a Booking System and I am having a issue i.e. How can I prevent duplicate events to be registered ?

Right now I am using: Calendar and Date for the event management and Entity Form for the booking system.

Users book a date and a time (for example: 09 / 10 / 2014, 14:30 and this is done with the Date field)

The problem I am facing that I don't want to let the users book a date and hour that is already selected. How can I prevent that?

For example: If an user books 09 / 10 / 2014, 14:30, no other user can book for the same date and time. How can i achieve this? Entity Forms has the option to set rules (via the rules module) but my knowledge on rules is not that good. Hope someone could give me a hint. Thanks in advance.

# Answer
You could do this with Entity Rules, VBO, and Entityform if you are using 2.x(if not should upgrade).

It actually would an advanced Rule but here are the general steps.

1. Make a VBO View that has date time contextual filter. You would want to return any Entityform Submission that matched.
2. Make an Entity Rules Validation Rules.
3. Within Rule check the Number of results of the View from step #1 when you send it the date value of the current Entityform Submission.
4. If any results are returned then you have found a Entityform Submission that is for the existing date.

You would have to learn how to use Rules, Entity Rules, and VBO.
> 1 votes

---
Tags: views, datetime
---


# Question
Title: How to allow users to choose different theme?
Some of my site users prefer a light theme, others prefer dark one. In drupal 6, is there a way to allow users to choose their favorite theme? How? Thanks

# Answer
> 1 votes
I didn't look this up, but if I'm not mistaken, you should enable the themes users can choose from, and give the appropriate user role(s) the "select different theme" permission.

# Answer
> 1 votes
Try Themekey module. After installing this module from 'ThemeKey User Profile' configuration, enable the option for user to select their own themes, so that it will be available in user profile and user can select their own themes.

# Answer
> 1 votes
I am also convinced with Switch Theme module. It provides a dropdown created in a block that provides option to choose any of the theme enabled from the backend.

So you just need to enable themes from backend that you want to show users to switch.

Hope it will help!

# Answer
> 0 votes
I just found Switchtheme, which will give you a block that allows users to switch.

---
Tags: theming
---


title: Hide or disable node fields

text:
# Question
Title: Hide or disable node fields
I am using drupal 6 and i have created my own content type and few CCK fields. When user is creating a node, i don't want to show him fields like menu settings, revison information, and many others, is it possible in Drupal 6.

# Answer
The access to menu settings/revision information, etc. is controlled by permissions. For example the user will require 'administer menu' permission in order to choose what menus their content will go in.

You just need to find the permissions the relate to whatever task you're trying to deny access to, and make sure the users in question don't have that permission (at http://mysite.com/admin/user/permissions).

Failing that, you should use a `hook_form_alter()` function in a custom module, and set the field/fieldset `#access` to `FALSE`:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'my_form_id') {
    $form['the_field']['#access'] = FALSE;
  }
}

```

In case you need to control access to certain CCK fields that you've created, the Field Permissions module is available for Drupal 6 and Drupal 7 and will do just that.

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.
> 6 votes

# Answer
There are 2 modules that I found that seem to do similar tricks.

Jammer https://www.drupal.org/project/formfilter

FormFilter https://www.drupal.org/project/jammer
> 0 votes

---
Tags: 6
---


title: Problem installing REST Server module

text:
# Question
Title: Problem installing REST Server module
When I attempt to enable the REST Server module, I get the following error message:

> A library is missing for rest\_server to work (Currently using Missing library Please download spyc and create a file called spyc.php in rest\_server/lib)

The spyc.php file is included with the module in the `rest_server/lib` directory, but the error is still reported, and prevents the module from being enabled.

Drupal version: **6.22**

Rest Server module version: **6.x-2.0-beta3**

I reported the issue on the module page.

Just wondering if you see any patterns that could help me debug this issue.

# Answer
> 7 votes
Download spyc from http://code.google.com/p/spyc/. Inside the spyc folder find the file called spyc.php and copy it to the Services Module 'servers/rest\_server/lib/' directory.

# Answer
> 0 votes
after you put the spyc.php in the modules/services/servers/rest\_server/lib folder, go the the Modules configuration, disable the REST server, then re-enable it.

That worked for me.

# Answer
> 0 votes
Some places you can put rpyc (download from http://code.google.com/p/spyc/downloads/detail?name=spyc-0.5.zip):

```
servers/rest_server/lib
modules/services/servers/rest_server/lib
profiles/<someprofiles>/modules/services/servers/rest_server/lib

```

Hope this help

---
Tags: 6, installation
---


# Question
Title: Drupal 7 custom submit handler not getting triggered
I am having a problem connecting a custom submit handler to a form. I am trying to switch off redirecting after the save of an eck entity on edit form. But i am not getting that far as my submit handler is not getting called.

The first debug log is as you would expect original handler and my custom one returned (so the alter part seems fine), but my on submit debug is never displayed on submission. I have switched the same code to the user\_profile\_form and it works fine, both debug logs coming through as expected. Why would this form be different??

Code:

```
function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'eck__entity__form_edit_myentity') {
    $form['#submit'][] = 'mymodule_eck_ent_submit';
    dd($form['#submit']);
  }
}
function mymodule_eck_ent_submit($form, &$form_state)
{
    dd("smashed in !!");
}

```

Many Thanks Mathew

# Answer
> 1 votes
Another form alter may affect this form and maybe detach your sumbit handler.

Try

```
$form['#submit'] = array('mymodule_eck_ent_submit');

```

And see if it fires.

# Answer
> 0 votes
Here's the solution, Place this code in your template.php,

```
function yourtheme_form_alter(&$form, $form_state, $form_id) {
    switch ($form_id) {
      case 'your_form':
      $form['#submit'][] = 'edit_form_submit_handler'; //your function name
         break;
    }
}

function edit_form_submit_handler(&$form, &$form_state) {
    $form_state['redirect'] = 'redirect-url'; //the url that you wants to redirect.
}

```

I hope this helps you!! Thanks

---
Tags: 7, forms, entities
---


title: Rewrite the html tags for frontpage

text:
# Question
Title: Rewrite the html tags for frontpage
I am using views for front page. I was able to customize some things.

But I have some `<h1></h1>` in the body of an article and for the frontpage I want to change that automatically into `<h2></h2>`. Is that possible with views and if yes, how?

# Answer
> 2 votes
If you are having issue with the content that is being printed on the front page. Then you can create a `page--front.tpl.php` and print the variable according to the requiremt.

If `$title` gives you the `<h1>` and `<h2>` tags, then you can `strip_tags($title, 'tags that need to be maintained e.g. <a>')` to remove the tags.

If you have issues with views field label, you can use '**Rewrite the output of this field**' and '**Strip HTML tags**' to change the output mentioned in the image below:-

Hope it will help!

# Answer
> 1 votes
Assuming you are using a page display and set this page as the front page. Under the advanced section in views there is a section called theme, next to that is a link called 'information'. When clicking that you see a list of templates used by views. You can copy the one that is used for your frontpage and edit that.

for example views-view--page.tpl.php, is listed in one of my views. I would copy that name and make a new tpl file in my theme. Then copy the content of a template higher up in the hiarchy of the list this tpl name was in and put it in the new tpl. Then you can change it to fit your needs

---
Tags: views
---


# Question
Title: How to add description like: "Comments for paragraph 1" to comments
I have written a module that allows users to put comment on each paragraph. So in comment form there is a field that asks the user which paragraph do they want to put comment on. I have to mention that I have added a column to my comment table, which saves that paragraph number.

```
function Annotations_form_comment_form_alter(&$form, &$form_state, $form_id) {
$form['paragraph_id'] = array(
    '#type' => 'textfield',
    '#title' => t('Which paragraph you want to put comment on?'),
    '#required' => TRUE,
    '#size' => 10,
    '#maxlength' => 2,
    '#default_value' => !empty($form['#entity']->paragraph_id) ? $form['#entity']-   >paragraph_id : NULL, // set the default value to the current paragraph value
     '#weight' => $form['subject']['#weight'] + 1, // place after the subject   field by setting the weight to +1 of subject weight
);

$form['#validate'][] = 'annotations_form_comment_form_validate';
$form['#submit'][] = 'annotations_form_comment_form_submit';

 }

```

I also have Annotations\_form\_comment\_form\_validate and Annotations\_form\_comment\_form\_submit functions for validation and submitting.

I have also written the following code to sort the comments based on the number of the paragraph. So first you see the comments on paragraph 1, and then 2, etc.

```
    <?php

  define('COMMENT_SORT_OLDER_FIRST', 1); // default
  define('COMMENT_SORT_Paragraph', 2);
 /* Alter node type form: allow user to decide comments sorting */
  function Annotations_form_node_type_form_alter(&$form, $form_state) {
  $form['comment']['comment_default_sorting'] = array(
 '#title' => t('Sort'),
 '#type' => 'select',
 '#options' => array(1 => t('Older first'),
                     2 => t('Paragraph Number')),
 '#default_value' => variable_get('comment_default_sorting_' . $form['#node_type']->type, COMMENT_SORT_OLDER_FIRST),
 );
  }

  /* Alter comments query */
 function Annotations_query_comment_filter_alter(QueryAlterableInterface $query){
  if ( ($node = $query->getMetaData('node')) && (get_class($query) == 'PagerDefault')             ) {
  $sort = variable_get('comment_default_sorting_' . $node->type,              COMMENT_SORT_OLDER_FIRST);
    if ($sort == COMMENT_SORT_Paragraph) {
  $orderby =& $query->getOrderBy();
  $expressions =& $query->getExpressions();
  if (isset($orderby['torder'])) {
      unset($expressions['torder']);
      unset($orderby['torder']);
      $orderby['c.paragraph_id'] = 'ASC';
  } else {
    $orderby['c.cid'] = 'DESC';
    }
   }
 }
}

```

I want to have a line like: " Comments on Paragraph 1 " and then show the comments for paragraph 1, and the same for rest of the comments.

Does anybody know how can I do that or which hooks I can use? Do you know some other modules or examples that do something similar, so it will give me some idea that how to do it?

# Answer
> 0 votes
I don't think it will **really** be answerable without the code you wrote.

General answer is:

1. alter query that gets comments to include paragraph number (`hook_query_alter`)
2. alter their rendering, so paragraph number is sent to .tpl files (`hook_comment_view_alter`)
3. change tpl file of your theme to display that number.

---
Tags: comments
---


# Question
Title: Facebook Friend List Import using fboauth
I am using fboauth for enabling login with facebook for the website. Here is an overview of how I achieve the functionality:

When the user clicks on the facebook login button on the website, he or she is taken to a facebook login page. After logging in with facebook, the user is taken to the app authorization page where the user asks for permission to connect with the app. Once necessary permissions are granted, a local account (account at my website) is automatically created for the user and the user is brought back to a welcome page to set password. The user won't even have to verify their email address. On subsequent visits, when the user clicks on the login link, he/she is taken to the same facebook login page where they supply their login credentials. On successful login, they are brought back to the website. So far, everything works fine with the fboauth module.

What I am trying to achieve now is a functionality similar to what is found with the fbconnect module. The user is provided with a block/page where the user can import the list of his friends who has authorized with the app, and see the links to their local accounts (accounts at the website). How to achieve this functionality? The fboauth module has its own API which can be utilized. Here is what I already have, written using the API of fboauth.

`<?php
function mymodule_fboauth_actions() {
 $actions['mymodule_friend_import'] = array(
 'title' => t('Imports your friends),
 'callback' => 'mymodule_fboauth_action_friend_import',
 'permissions' => array(
 'user_friends',
 ),
);
 return $actions;
}
function mymodule_fboauth_action_friend_import($app_id, $access_token) {
$result = fboauth_graph_query('me/friends?fields=name', $access_token);
drupal_set_message(t('Import complete!'));
}
?>`

This will import all the friends of a user as an object into $result. However, what I am finding it difficult is to display those names with the user's corresponding local accounts (accounts at the website). This is because of my lack of knowledge in php. What I am looking for is here is the exact lines of code that can be inserted after $result recieves its value so that the names of the users are displayed along with the links to their profile pages at my website.

# Answer
> 3 votes
The code you have there is returning friend's names which could be problematic if any of the user's friends have the same name (names like John Smith and Mohammed Abdul spring to mind).

You should change your friend import function to get the facebook user id like this:

```
function mymodule_fboauth_action_friend_import($app_id, $access_token) {
  $result = fboauth_graph_query('me/friends?fields=id', $access_token);
  drupal_set_message(t('Import complete!'));
}

```

As you rightly pointed out fboauth has a useful API including this method which turns facebook user ids into Drupal user ids:

```
/**
 * Load a Drupal User ID given a Facebook ID.
 */
function fboauth_uid_load($fbid) {
  $result = db_query("SELECT uid FROM {fboauth_users} WHERE fbid = :fbid", array(':fbid' => $fbid));
  $uid = $result->fetchField();
  return $uid ? (int) $uid : FALSE;
}

```

To make an array of Drupal user profiles you could write this in your code:

```
$accounts = array();
foreach($result->data as $fbuid){
  $accounts[] = user_load(fboauth_uid_load($fbuid->id));
}

```

How you then use those profiles depends on where you want to display them, but something like this should do the trick:

```
foreach($accounts as $account){
  print l($account->name, 'user/'.$account->uid);
}

```

If you put it all together you will have something like this - you may need to adjust some of the specifics as I do not know how you wish the information to be displayed:

```
<?php
function mymodule_fboauth_actions() {
  $actions['mymodule_friend_import'] = array(
    'title' => t('Imports your friends'),
    'callback' => 'mymodule_fboauth_action_friend_import',
    'arguments' => array)
      'app_id' => MISSING,
      'access_token' => MISSING,
    ),
    'permissions' => array(
      'user_friends',
    ),
);
  return $actions;
}

function mymodule_fboauth_action_friend_import($app_id, $access_token) {
  $result = fboauth_graph_query('me/friends?fields=id', $access_token);
  drupal_set_message(t('Import complete!'));

  $accounts = array();
  foreach($result->data as $fbuid){
    $accounts[] = user_load(fboauth_uid_load($fbuid->id));
  }

  foreach($accounts as $account){
    print l($account->name, 'user/'.$account->uid);
  }
}

```

If this doesn't display anything that means `print` is the wrong function to use in this context. How you get the items to display depends entirely on where and how you are calling this function. If it's part of a hook such as hook\_node\_view() you can edit the node entity before it is rendered, but if (as I suspect) this function is being run in the background without refreshing the screen you will likely have to employ some JQuery or AJAX to get the relevant items to display.

I would start with this post on Javascript and JQuery for an explanation of how Drupal uses JQuery, and this post on building AJAX into non-form elements in Drupal.

---
Tags: 7, social-network
---


# Question
Title: SMTP module: The following From address failed
all,

Here is something I don't quite understand.

First of all, my site-wide email address configured on Site Information page is **my\_gmail\_address@gmail.com**.

Then, I use smtp module to send emails out from my site. I configure SMTP settings with my yahoo email address **my\_yahoo\_mail\_address@ymail.com**.

I tries to send a test email out to my other gmail address **my\_other\_gmail\_address@gmail.com**, but failed. Email can never be sent out in this situation.

Here is watchdog log details:

```
Type    smtp
Date    Monday, September 22, 2014 - 11:29
User    lyon
Location    http://localhost:8888/drupal-test/admin/config/system/smtp
Referrer    http://localhost:8888/drupal-test/admin/config/system/smtp
Message Error sending e-mail from my_gmail_address@gmail.com to my_other_gmail_address@gmail.com : The following From address failed: my_gmail_address@gmail.com
SMTP server error: From address not verified - see http://help.yahoo.com/l/us/yahoo/mail/original/manage/sendfrom-07.html

Severity    error
Hostname    ::1
Operations

```

SMTP configuration didn't go wrong, because in the following two situations, email can be sent out well:

1. configure site-wide email address to be the same one configured in SMTP settings: **my\_yahoo\_mail\_address@ymail.com**.
2. configure SMTP settings with a gmail address, then configuring site-wide email address to be any email address will work well. (People on Internet says Gmail can override it).

I don't want the SMTP configuration to be tied with Gmail account, it should support any mail host. How can I overcome this problem?

I appreciate your help.

# Answer
> 1 votes
I believe the problem lies with Yahoo not having your permission to send from the gmail account. You could try setting up Yahoo to send from your gmail account but I'm not sure Yahoo will do that.

You could look into a mail service like MailJet, which is cheap and scalable.

Or, assuming you're using the drupal\_mail function, simply set your $from variable in 'params' to 'my\_yahoo\_mail\_address@ymail.com'.

---
Tags: 7, emails
---


title: Commerce Quantity Volume Discount Rules

text:
# Question
Title: Commerce Quantity Volume Discount Rules
I'm trying to make a drupal commerce pricing rule so that if the customer has 14 items in their cart they'll get 10% off their order. Here's what I tried:

```
{ "rules_overall_discount" : {
    "LABEL" : "Volume Discount",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [
      "php",
      "inline_conditions",
      "commerce_line_item",
      "commerce_product_reference"
    ],
    "ON" : { "commerce_product_calculate_sell_price" : [] },
    "IF" : [
      { "commerce_order_has_specific_quantity_products" : {
          "commerce_order" : [ "site:current-cart-order" ],
          "products" : "\u003C? $commerce_line_item ?\u003E",
          "operator" : "\u003C",
          "quantity" : "14"
        }
      }
    ],
    "DO" : [
      { "commerce_line_item_unit_price_multiply" : {
          "commerce_line_item" : [ "commerce_line_item" ],
          "amount" : ".9",
          "component_name" : "base_price",
          "round_mode" : "1"
        }
      }
    ]
  }
}

```

I think the:

```
"products" : "\u003C? $commerce_line_item ?\u003E",

```

might be the problem. It's asking for SKU's but I simply want it to apply to everything.

# Answer
> 2 votes
Figured it out. Here's the rules settings. This will take 10% off your order if the total quantity of your cart is 14+

```
{ "rules_overall_discount" : {
    "LABEL" : "Volume Discount",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "commerce_order", "commerce_line_item", "commerce_product_reference" ],
    "ON" : { "commerce_product_calculate_sell_price" : [] },
    "IF" : [
      { "commerce_order_compare_total_product_quantity" : {
          "commerce_order" : [ "site:current-cart-order" ],
          "operator" : "\u003E=",
          "value" : "14"
        }
      }
    ],
    "DO" : [
      { "commerce_line_item_unit_price_multiply" : {
          "commerce_line_item" : [ "commerce_line_item" ],
          "amount" : ".9",
          "component_name" : "base_price",
          "round_mode" : "1"
        }
      }
    ]
  }
}

```

---
Tags: rules, commerce
---


# Question
Title: exculde content type from search result even for admin
Is it possible to disable specific content type from search result even from administrator, I did for all user types except the administrator using Search configuration module.

# Answer
You can do what you're attempting if you implement Apache Solr which has all kinds of cool options - but that involves actually setting up Solr on your server which might be overkill if that is all you wish to achieve.
> 0 votes

# Answer
You can use Search API for that. You can setup search API with database search to index only content type that you need.
> 0 votes

---
Tags: search, users
---