# Question
Title: Reloading option in a select list with ajax
So here is my problem:

I have a form so users can create orders. There is a 'Client' select list where they can select the client of the order. When we select a client, we use ajax to load client info (address, tax rate, discount ...) and populate some field. This works fine.

I am now adding a feature to be able to create directly a client from the order, in a modal. So I have a button in the order form, that triggers ajax to open a modal and render the new client form:

```
  $account_form = drupal_get_form('mymodule_creation_account_custom_form',$form['field_client']);
  $output = drupal_render($account_form);

  $commands = array();
  $commands[] = ajax_command_invoke('div#createClientModal','foundation',array('reveal', 'open'));
  $commands[] = ajax_command_replace('#new-account-form-placeholder',$output);
  return array(
    '#type' => 'ajax',
    '#commands' => $commands,
  );

```

Then I fill in the info, and submit the account from the modal:

```
  $account = my_module_new_account_form_submit($form, $form_state);

  $form['client_hidden_field']['und']['#options'][$account->nid] = $account->title;
  $form['client_hidden_field']['und']['#default_value'] = $form['client_hidden_field']['und']['#value'] = $account->nid;

  $commands = array();
  // Closing the modal
  $commands[] = ajax_command_invoke('div#createClientModal','foundation',array('reveal', 'close'));
  $commands[] = ajax_command_replace('.field-name-field-client', render($form['client_hidden_field']));
  $commands[] = ajax_command_invoke('.field-name-field-client select','change');

  // Replace the form with an empty div
  $commands[] = ajax_command_replace('div#account-form-wrapper','<div id="new-account-form-placeholder"></div>');

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

```

So what I am doing in this last submit, is creating the new account (that works), it returns me the nid. Then, as I have stored in a variable ($form\['client\_hidden\_field'\]) the client field, I update it with the new option, select the option, replace the old client select list with the new one, and trigger change to call the old callback that loads a client info when it is selected.

I have tried lots of thing and each time I select the new client created, I get an 'Illegal choice'. I have tried without default value, without triggering a 'change', in JS with a command\_invoke and nothings seems to work.

The only success I had was : I do all these step, I manually select a client (one already existing before), and then select the new one. After that I didn't have the 'Illegal choice' and was able to save. But this is not a way to make it work.

If someone has any idea, I would love your help !

Thanks

Ed

# Answer
Ok, so I was finally able to succeed this. I didn't manage to return the new field to the form properly (cf. Resolve the error "An illegal choice has been detected...") because I am working with two forms (and maybe I am missing something).

So skipping the validation for that field in form.inc seems to be the only solution that I have. And the only way I found was to add a function in #after\_build to unset '#needs\_validation':

In form\_alter:

```
array_unshift($form['field_client']['und']['#after_build'],'remove_client_validation');

```

And the function:

```
function remove_client_validation($form_element) {
  unset($form_element['#needs_validation']);
  return $form_element;
}

```

Thanks to: I use jQuery to alter the exposed form select options. Got error: "An illegal choice has been detected." How to bypass validation?, where I found that solution.
> 0 votes

# Answer
Have you tried with `$form_state['rebuild']=TRUE`. It will help you to update your changes while adding new client.
> 0 votes

---
Tags: 7, ajax
---


title: Getting default user picture drupal 6

text:
# Question
Title: Getting default user picture drupal 6
Hi I got neat facebook style chat called arrowchat for my drupal website, however the script was lacking user picture integration. I managed to get user pictures but if user didn't set picture and is using default picture I'm getting broken image and 404 not found in logs. I've tried to fetch gravatar for users without picture set but couldn't make it work..

```
/**
 * This function returns the URL of the avatar of the specified user ID.
 *
 * @param userid the user ID of the user
 * @param image if the image includes more than just a user ID, this param is passed
 * in from the avatar row in the buddylist and get user details functions.
 * @return the link of the user ID's profile
 */
function get_avatar($image, $user_id, $account)
{
               return "http://mypage.com/files/pictures/picture-" . ($user_id) . ".jpg";

    if (empty($account->picture)) {
    return "http://www.gravatar.com/avfatar/" . md5($image) . "?d=identicon";
     }
}

```

# Answer
> 0 votes
There is already a Gravatar module out there. I think you would be better off using a vetted, bug tested code than having to build it yourself. Once you have it installed, you can use the function `gravatar_get_gravatar($mail, $options = array())` to do exactly what you're wanting.

---
Tags: 6
---


# Question
Title: Using #states API with an image field as a control field
On a form, is it possible to use #states to hide/show a field based on whether or not an image field has been filled in?

More specifically, I'd like to get this node form:

to only show the "Show featured image" checkbox if an image has been added. If it matters, I'm using the media browser widget for the image field.

I tried using #states, but it doesn't seem to work here. I had the following code in a hook\_form\_alter function, but adding an image didn't make field\_image\_show show up.

```
// Hide the "show featured image" field until a featured image is added.
if (isset($form['field_image_show'])) {
  $langcode = $form['field_image']['#language'];
  $form['field_image_show']['#states'] = array(
    'visible' => array(
      ':input[name="media[field_image_und_0]"]' => array('filled' => true),
    ),
  );
}

```

If it's not possible with #states, any idea how to handle it with custom JS? I tried the following JS, but it also didn't work.

```
$field_image_show = $('#edit-field-image-show');

var imageCheck = function() {
  if ($('#edit-field-image-und-0 .preview').is(':empty')) {
    $field_image_show.hide();
  }
  else {
    $field_image_show.show();
  }
}

// Check on initial page load.
imageCheck();

// Check when media browser does stuff.
// @nope This doesn't seem to actually ever fire.
$('#edit-field-image-und-0 input').change(function() {
  imageCheck();
});

```

# Answer
You should be able to do it with #states just fine. Maybe double check your input name or try something a little different depending on what the html for that element looks like. This is the code I am using that works.

```
 $form['field_hero_image']['#states'] = array(
  'visible' => array(
    ':input[name="field_image[und][0][fid]"]' => array('empty' => true),
  ),
);

```

This causes it to only appear if there is no value for the input fid. Pertinent HTML:

```
<input type="hidden" name="field_image[und][0][fid]" value="1088">
<input type="hidden" name="field_image[und][0][display]" value="1">
<input type="hidden" name="field_image[und][0][width]" value="915">
<input type="hidden" name="field_image[und][0][height]" value="450">

```

Note:

```
'visible' => array(
    ':input[name="field_image[und][0][fid]"]' => array('value' => 0),
  ),

```

may work just as well (untested)
> 1 votes

---
Tags: javascript
---


# Question
Title: How do I correct error: Contained fields field is required in Commerce Index Filters
Commerce Kickstart 2. I noticed that unpublished Products were still visible to users who are not logged in or have editing permissions.

I saw this topic: https://www.drupal.org/node/1899326 which states that one must check the 'Exclude unpublished nodes' box as well as the 'Exclude unpublished products' box in the Filters tab of

/admin/config/search/search\_api/index/product\_display/workflow

...but when I click 'Save' I get the error:

Contained fields field is required

...five times.

What is causing this? How do I correct?

# Answer
> 0 votes
I am not sure if you found the solution for this error, but here is what i did.

on the /admin/config/search/search\_api/index/product\_display/workflow, the aggragated field settings, remove the fields that you don't need or have "unchecked" on the fields tab.

Hope this helps

Karim

---
Tags: commerce, search
---


# Question
Title: Can you get the itok value programmatically?
I appreciate the 7.20 security measure that requires a `itok` parameter for generating new images, but I need to expose that to Services / AJAX driven projects.

Can you get the image token programmatically so that JavaScript can build valid image urls for any size dynamically?

I would like to avoid `$conf['image_allow_insecure_derivatives'] = TRUE;` unless someone has a project to apply this same security measure on a user session level as opposed to per image

# Answer
It should be possible to get the token via a custom ajax callback that returns:

```
$token_query = array(IMAGE_DERIVATIVE_TOKEN => image_style_path_token($style_name, $original_uri));

```

From a custom menu router path or services callback.
> 2 votes

---
Tags: ajax, services, media
---


title: Add an external jQuery based library

text:
# Question
Title: Add an external jQuery based library
How can we add an external javascript library that relies on jQuery by calling $(document)??

As Drupal 7's jQuery needs to be encapsulated, adding the library just generates errors:

> $(...) is not a function

I don't understand the point of not being able to use $ directly anymore. And adding jQuery as an external library seems to conflict with the Drupal's one

Thanks for the help

# Answer
Use `drupal_add_js()` for this.

Please also check these resources; they could help you out.

For using other versions of jQuery, there is the jQuery Update module.
> 1 votes

# Answer
You can add javascript library in your custom theme in preprocess-html.inc e.g.

```
 drupal_add_js(drupal_get_path('theme', 'themename') . '/js/fastclick.min.js');

```
> 1 votes

# Answer
Give this a try, it will assign $ to be jQuery. It's not the correct way to do this, but it seems like that 3rd party library did things wrong to begin with.

```
drupal_add_js('$ = jQuery;', array(
  'type' => 'inline',
  'scope' => 'header',
  'group' => JS_LIBRARY,
  'weight' => -1,
));

```

There is a module that does roughly the same thing: https://drupal.org/project/jquery\_dollar
> 1 votes

# Answer
Ok, it sounds like there may be two questions here, external libraries and using the dollar sign jQuery variable.

1) I use the Libraries API module to add external libraries that my custom modules need. It makes your code a little more concise I suppose: https://www.drupal.org/project/libraries

**Note:** I'd add that I've never had a 3rd parties jQuery mess with Drupal's jQuery using the Libraries API.

2) I use the following code to prevent my jQuery code from conflicting with Drupal's jQuery in my module and theme jQuery:

```
(function ($) {

  $(window).resize(function(){
    // Do something
  });

})(jQuery);

```
> 1 votes

---
Tags: javascript
---


# Question
Title: Getting the original form with error message in drupal ajax call back
I have a drupal form which accept email id and ajax call is implemented for the submit button.In addition to submit call back.The return values are collected in the wrapper and my requirement is to display the form along with an error message if the email is not valid.

I tried to return the form along with message to the wrapper from submit,but the ajax call was not happening.

Also i tried to reset the form\_state array empty in the submit call back, but execution stopped at that point.

Am i on the correct track? Please help me in solving this.Sorry for my english.

# Answer
For Drupal 7 you can use the below code

```

    /**
     * Implements hook_menu().
     */
    function hook_menu() {
        $items['test_ajax'] = array(
            'title' => 'test ajax',
            'page callback' => 'drupal_get_form',
            'page arguments' => array('demo_form'),
            'access callback' => TRUE,
            'type' => MENU_CALLBACK,
        );
            ....
    }

    /**
     * Implements hook_form().
     */
    function demo_form($form, &$form_state) {
        return array(
            'email' => array(
                '#type' => 'textfield',
                '#title' => t("Join our Newsletter"),
                '#required' => TRUE,
                '#attributes' => array(
                    'placeholder' => t("mail@example.com")
                ),
            ),
            'submit' => array(
                '#type' => 'submit',
                '#value' => t('Subscribe'),
                '#ajax' => array(
                    'callback' => 'demo_form_ajax_submit',
                    'wrapper' => 'demo-form',
                    'method' => 'replace',
                    'effect' => 'fade',
                ),
            ),
        );
    }

    /**
     * Ajax callback function.
     */
    function demo_form_ajax_submit($form, $form_state) {
        drupal_set_message();
        $message = '';
        if (!empty($form_state['input']['email'])) {
            if (valid_email_address($form_state['input']['email'])) {
                $message = "subscription successful!!!";
                $status = 'status';
            }
            else {
                $message = 'Please enter valid email ID!!';
                $status = 'error';
            }
            drupal_set_message($message, $status);
        }
        $form_state['rebuild'] = TRUE;
        return $form;
    }

```
> 1 votes

# Answer
```
function demo_form_ajax_submit($form, &$form_state){
  $commands = array();

  if($form_state['values']['status']){ // some validations
      $commands[] = ajax_command_html('#id-form', theme('sussces_page'));
  }
  else{
      $commands[] = ajax_command_html('#message-error', theme('status_messages')); // message-error is a div defined in your form
  }
  return array('#type' => 'ajax', '#commands' => $commands);
}

```
> 0 votes

---
Tags: ajax
---


# Question
Title: Updating the CKeditor library in Drupal after Version 7.14?
I will now quote from CKeditor project page at Drupal.org:

> To use CKEditor in Drupal, you may need to download CKEditor (the library which this module relies on). This would not be necessary starting from version 7.x-1.14 (not released yet - 24 April, 2014), where the installation has been simplified and CKEditor from official CDN is available by default.

As you could see in the picture, my `sites/all/modules/ckeditor/ckeditor` folder is empty, i.e the folder where you put the library... So my question is, given that the library's folder is empty by default, is it even possible to update the JS library but not the module...? Is it even possible after version 7.x-1.14? Or should I wait to the coming Drupal module release? Thanks.

# Answer
> 2 votes
Yes.

Libraries should not be store in module directories for the reason that it makes it harder to update things.

Best practice is to install the Libraries API module and put the library in sites/all/libraries (or an equivalent libraries directory if you're using an install profile or something).

CKEditor and a lot of other modules integrate with the libraries API module.

The CDN option that is referred to in your quoted text is different though. In that case you don't need to have the CKEditor plugin anywhere in your website files. Instead the module will use a copy of the library from the CDN.

It's possible there could be performance implications from not using a local version but I haven't actually tested that.

# Answer
> 0 votes
Yes, you can drop in the CKEditor JS libraries at any time. It shouldn't interfere since there are file exist checks made in the code. Many modules that require 3rd party libraries do this.

As for the post 7.1.14 upgrade, you should be fine add the libraries before then. It shouldn't interfere with the upgrade; after the upgrade it will be loading the libraries from a different, public CDN URL instead of your local site URL.

# Answer
> 0 votes
As @rooby said, you should be using the Libraries API module and then simply downloading the latest version of CKEditor and untar'ing it into */sites/all/libraries* so that you end up with */sites/all/libraries/ckeditor/*.

AKA Download this, and put it in your /sites/all/libraries folder. You should end up with */sites/all/libraries/ckeditor/* If not just shuffle around the directories until it's correct.

What's next? Download the WYSIWYG module and deploy it. When you go to configure it, assuming you deployed the CKEditor correctly into your libraries then this module should automagically detect that you have CKEditor installed and you can select it as the default editor for the various filter types (Filtered, Full etc).

Today, you should not be using the CKEditor module directly and should be using the WYSIWYG module instead. It allows you to deploy various different WYSIWYG editors of your choice for various different filter types at your choosing.

---
Tags: wysiwyg
---


# Question
Title: Uncaught TypeError: Cannot read property 'fn' of undefined
This occured after I added the following lines in the `hook_init()` implementation done from a custom module.

```
function myid_init() {
  drupal_add_js(drupal_get_path("module", "myid") . "/photobooth-js-gh-pages/photobooth_min.js");
  drupal_add_js(drupal_get_path("module", "myid") . "/photobooth-js-gh-pages/website/js/script.js");
}

```

It needs jQuery 1.11.2 to work, but Drupal already uses jQuery.

I installed the *jQuery Update* module and found out that, in the configuration setting, the newer jQuery version I could select is 1.10, but that is not sufficient for jQuery plugin I want to use.

How can I use jQuery 1.11.2 in a Drupal site?

# Answer
Check out the drupal.org document on using new versions of jQuery for a few solutions. One good solution is the JQuery Multi module that lets you target multiple versions of jQuery via its `hook_jqmulti_libraries()` hook (its README explains how).
> 1 votes

---
Tags: javascript
---


# Question
Title: How to get an image url given term_image_tid using the customfield-PHP views module
I have created a view of type Term that lists all the taxonomy terms plus each term's image. This works. But now I want to wrap the images in a link that links to another view. I am trying to use the `customfield: PHP Code` field to build up an html string containing the image and the link. The only bit that I cant figure out is how to get the url of the image.

If i do `print_r( $data);` I get...

```
stdClass Object ( [tid] => 7
[term_data_name] => Old Edinburgh
[term_data_vid] => 2
[term_image_tid] => 7 )

```

And the sql query is...

```
SELECT DISTINCT(term_data.tid) AS tid,
   term_data.name AS term_data_name,
   term_data.vid AS term_data_vid,
   term_image.tid AS term_image_tid
 FROM term_data term_data
 LEFT JOIN term_node term_node ON term_data.tid = term_node.tid
 INNER JOIN node node_term_node ON term_node.vid = node_term_node.vid
 LEFT JOIN term_image term_image ON term_data.tid = term_image.tid
  GROUP BY tid

```

# Answer
You shouldn't use a PHP code field, rather you can use the Image URL formatter module to create a image URL field, exclude it from display, & then use that image URL field to feed into a `Global: Custom text` field with your own custom `img` & `a` markup.
> 0 votes

---
Tags: views, 6
---


# Question
Title: Removing the "File Browser Tab" for certain roles
How would I go about removing the "File Browser Tab" from the user profile page for certain roles?

I only want authors, editors and administrators to be able to browse through and upload the files.

# Answer
> 1 votes
No need to do any coding. We can do it through admin dashboard itself.

Just go to below link:

> /admin/config/media/imce

Under "Role-profile assignments" just choose "Public Files" as NONE against a user role to whome you don't want to show the "File Browser".

---
Tags: 7
---


title: Status message prompted twice

text:
# Question
Title: Status message prompted twice
1. I am opening my registration form in ctools modal popup. I have applied custom module to get that popup.

Once user submit any form ajax window will be dismiss using `ctools_modal_command_dismiss()`.As window will be closed, status message will be printed using `ajax_command_append('.ctools-use-modal',theme('status_messages')`.

But the status message get printed twice. I had tried to unset session messages. but it was not working.

# Answer
> 0 votes
The function drupal\_set\_message takes 3 parameters, message, type and repeat. Default repeat is TRUE. If you set it to FALSE, it will prevent duplicates.

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


# Question
Title: How can I show the Sales Report for particular user?
I use Drupal 7 and the Drupal Commerce module.

My site has 3 roles defined:

1. **Admin**, who can publish and unpublish product of affiliate.
2. **Affiliate**, who can add the product in the site.
3. **Learner** who can see the show the all product and but the product.

My question is related to a learner buying a product which was added by an affiliate:

* When an affiliate checks the sales reports, then the report is null.
* But when an admin checks the sales reports, then it displays all functionality in the reports.
* And a learner can also check the sales reports.

So how can I solve these issues? Why are affiliate sales reports null?

# Answer
> 0 votes
Attempt to answer the "Why does an affiliate get an empty report?" part of your question (which I believe is part of your question): could it be related to some "**permission**" you have not granted to an affiliate (yet)?

Here are a few links related to permissions that may be helpful:

---
Tags: commerce
---


# Question
Title: Fallback values for OG Meta Tags / hiding some unused OG fields
I'm using D7 and the Open Graph Meta Tag module to allow open graph meta tags to be set for various content types.

With the OG:summary field if not specified it falls back to the first 200 characters of the article body. Can anyone suggest how to change this fallback behaviour so that it instead uses a different field from the content\_type as the fallback if not set?

Also is there a good way to hide some of the OG tags that are not going to be used? (location, type and contact sections specifically).

# Answer
> Also is there a good way to hide some of the OG tags that are not going to be used? (location, type and contact sections specifically).

You can use common css selector to do that:

```
.form-item-metatags-ru-og\:type-value,
.form-item-metatags-ru-og\:latitude-value,
.form-item-metatags-ru-og\:longitude-value,
.form-item-metatags-ru-og\:street-address-value,
.form-item-metatags-ru-og\:locality-value,
.form-item-metatags-ru-og\:region-value,
.form-item-metatags-ru-og\:postal-code-value,
.form-item-metatags-ru-og\:country-name-value,
.form-item-metatags-ru-og\:email-value,
.form-item-metatags-ru-og\:phone-number-value,
.form-item-metatags-ru-og\:fax-number-value {
  display:none;
}

```
> 1 votes

---
Tags: meta-tags
---


# Question
Title: VAT price will be 25% of product 'subtotal price and shipping price' instead of only 'subtotal price'
I am working on a `Drupal commerce` site. Everything is working fine as per my requirement. But I have to modify some setting for `checkout preview page (price detail table)`.

Currently into the product detail price table, there are `shipping price` and `VAT price` are there and the `VAT` price is depends on `Subtotal` price. `I mean the VAT price ($75) is 25% of Subtotal price ($300)`.

Now I want to change `VAT price functionality`, means the VAT price will be 25% of sum of `'Subtotal price and shipping price'` (i.e. `$300 + $78 = $378`). So now the VAT price will be `$94.5`.

and the sequence of the price type will be

```
1. Subtotal
2. Shipping
3. VAT
4. Order total

```

So how can I set VAT price 25% of 'Subtotal price and Shipping price'? And How can I manage their sequence?

Recently the table is showing look like the attached screenshot:

# Answer
> 1 votes
Aah!, finally I got the answer of my question and now everything is working absolutely fine as per my requirement.

For this we just create a new `Rule` for this. Here is the exported code of my created `Rule`.

```
{ "rules_taxes_shipping" : {
"LABEL" : "Taxes Shipping",
"PLUGIN" : "reaction rule",
"WEIGHT" : "9",
"OWNER" : "rules",
"TAGS" : [ "Shipping", "taxes" ],
"REQUIRES" : [ "commerce_tax", "commerce_shipping" ],
"ON" : { "commerce_shipping_calculate_rate" : [] },
"DO" : [
  { "commerce_tax_calculate_by_type" : {
      "commerce_line_item" : [ "commerce-line-item" ],
      "tax_type_name" : "vat"
    }
  }
]
}
}

```

And to rearrange the sequence of the price item just set `weight` for that particular item using `alter`, look like the below code.

```
function hook_commerce_price_formatted_components_alter(&$components, $price, $entity) {
  $components['flat_rate_shipping']['weight'] = 0;
  $components['tax|vat']['weight'] = 1;
}

```

This will set the sequence of this item.

```
1. Subtotal
2. Shipping
3. VAT
4. Order total

```

---
Tags: views, 7, commerce
---


# Question
Title: Passing Argument in Drupal 6 not working
Im very new to drupal. Recently I have started learning drupal 6 with reference project done by my friend. It was having so many bugs and fixed most of from the list.

Still Im not getting how hook menu works. One module called filedepot installed which is for uploading and downloading files. When Im clicking on download button its redirecting to homepage. I think there is pblm in hook\_menu

Download url : http://localhost/my\_project/?q=filedepot\_download/8/42

```
$items['filedepot_download/%node/%'] = array(
  'title' => 'File download',
  'page callback' => 'filedepot_download',
  'page arguments' => array(1, 2, 3, 4),
  'access callback' => 'filedepot_user_access',
  'access arguments' => array('access filedepot') ,
  'type' => MENU_CALLBACK,
  );

```

**function call**

```
function filedepot_download($node, $fid, $version, $mode='') {
  global $conf, $user;
  $filedepot = filedepot_filedepot();

  $field = content_fields('field_filedepot_file', $node->type);
  $db_info = content_database_info($field);

  $filepath = '';
  $content_disposition = 'attachment';

  if (empty($fid)) {
    watchdog('filedepot', "Download request - null file id");
    return drupal_access_denied();
  }
  elseif ($version == 'incoming') {
    $query = db_query("SELECT cckfid,orig_filename,title FROM {filedepot_import_queue} WHERE id=%d", $fid);
    list($cckfid, $fname, $filetitle) = array_values(db_fetch_array($query));
    if ($cckfid > 0) {
      $filepath = db_result(db_query("SELECT filepath FROM {files} WHERE fid=%d", $cckfid));
      if (file_exists($filepath)) {
        $result = db_query("SELECT * FROM {files} WHERE fid= %d", $cckfid);
        $file = db_fetch_object($result);
        $name = mime_header_encode($filetitle);
        $type = mime_header_encode($file->filemime);
        // By default, serve images, text, and flash content for display rather than
        // download. Or if variable 'filefield_inline_types' is set, use its patterns.
        $inline_types = variable_get('filefield_inline_types', array('^text/', '^image/', 'flash$'));
        $disposition = 'attachment';
        foreach ($inline_types as $inline_type) {
          // Exclamation marks are used as delimiters to avoid escaping slashes.
          if (preg_match('!' . $inline_type . '!', $file->filemime)) {
            $disposition = 'inline';
          }
        }
        $headers = array(
        'Content-Type: ' . $type . '; name="' . $filetitle . '"',
        'Content-Length: ' . $file->filesize,
        'Content-Disposition: ' . $disposition . '; filename="' . $filetitle . '"',
        'Cache-Control: private',
        );
        if (count($headers)) {
          watchdog('filedepot', 'Transferring incoming file %name (filedepot fid %fid, CCK fid %cckfid)',
            array('%name' => $filetitle, '%fid' => $fid, '%cckfid' => $cckfid), WATCHDOG_INFO);
          file_transfer($filepath, $headers);
        }

      }
      else {
        return drupal_not_found();
      }
    }
    else {
      watchdog('filedepot', "Download request for incoming file invalid");
      return drupal_access_denied();
    }

  }
  else {

    $version = intval($version);
    if ($version > 0) {
      $filetitle = db_result(db_query("SELECT title FROM {filedepot_files} WHERE fid=%d", $fid));
      $fname = db_result(db_query("SELECT fname FROM {filedepot_fileversions} WHERE fid=%d AND version=%d", $fid, $version));
      $cid = db_result(db_query("SELECT cid FROM {filedepot_files} WHERE fid=%d", $fid));
    }
    else if ($mode == 'moderator') {
      $query = db_query("SELECT cid,fname,tempname,title FROM {filedepot_filesubmissions} WHERE id=%d", $fid);
      $rec = db_fetch_array($query);
      if ($rec === FALSE) {
        watchdog('filedepot', "Download request for moderated file - invalid file reference");
        return drupal_access_denied();
      }
      list($cid, $fname, $tempname, $filetitle) = array_values($rec);
    }
    else {
      $query = db_query("SELECT cid,fname,title,version FROM {filedepot_files} WHERE fid=%d", $fid);
      $rec = db_fetch_array($query);
      if ($rec === FALSE) {
        watchdog('filedepot', "Download request - invalid file reference");
        return drupal_access_denied();
      }
      else {
        list($cid, $fname, $filetitle,$version) = array_values($rec);
      }
    }

    if ($cid == 0) {
      watchdog('filedepot', "Download request - null category id");
      return drupal_access_denied();
    }
    else {
      if ($mode == 'moderator') {
        $filepath = $filedepot->root_storage_path . "{$cid}/submissions/{$tempname}";
      }
      else {
        $filepath = $filedepot->root_storage_path . "{$cid}/{$fname}";
      }

      if ($filedepot->checkPermission($cid, 'view') === FALSE) {
        watchdog('filedepot', "Download request for incoming file invalid access to folder ($cid) for user: {$user->name}");
        return drupal_access_denied();
      }

      if (file_exists($filepath) AND !is_dir($filepath)) {
        $system_directory_path = $conf['file_directory_path'];
        $conf['file_directory_path'] = $filedepot->root_storage_path . $cid;
        $result = db_query("SELECT * FROM {files} WHERE filepath = '%s'", $filepath);

        if (!$file = db_fetch_object($result)) {
          // We don't really care about this file.
          watchdog('filedepot', "File record not found");
          return drupal_access_denied();
        }
        if ($mode == 'moderator') {
          $name = mime_header_encode($filetitle);
          $type = mime_header_encode($file->filemime);
        }
        else {
          if (db_result(db_query("SELECT COUNT(*) FROM {filedepot_downloads} WHERE uid=%d AND fid=%d", $user->uid, $fid)) == 0) {
            db_query("INSERT into {filedepot_downloads} (uid,fid,remote_ip,date) VALUES (%d,%d,'%s',%d)", $user->uid, $fid, $_SERVER['REMOTE_ADDR'], time());
          }
          $name = mime_header_encode($filetitle);
          $type = mime_header_encode($file->filemime);
        }
        // By default, serve images, text, and flash content for display rather than
        // download. Or if variable 'filefield_inline_types' is set, use its patterns.
        $inline_types = variable_get('filefield_inline_types', array('^text/', '^image/', 'flash$'));
        $disposition = 'attachment';
        foreach ($inline_types as $inline_type) {
          // Exclamation marks are used as delimiters to avoid escaping slashes.
          if (preg_match('!' . $inline_type . '!', $file->filemime)) {
            $disposition = 'inline';
          }
        }

        if ($mode == 'edit') { // User is using the download for edit function

          $ext = end(explode(".", $filetitle));
          $pos=strpos($filetitle, ".");

          // Generate a 15 character hash value (token) and append to filename
          // Create a unique filename for download and save the token for compare use on upload
          $filename=substr($filetitle, 0, $pos);
          $hash = md5(uniqid(rand()));
          $token=substr($hash, 0, 15);
          $newfilename=$filename . '{' . $token . 't}' . ".$ext";
          $newfilename=str_replace(' ', '+', $newfilename);

          //Update the MimeHeader that will be used to send the file to the browser - need to include token in filename
          $name = mime_header_encode($newfilename);

          $sql  = "INSERT INTO {filedepot_export_queue} (orig_filename,token,extension,timestamp,uid,fid) values ('%s','%s','%s',%d,%d,%d)";
          db_query($sql, $filetitle, $token, $ext, time(), $user->uid, $fid);
          // Change file status to locked - being edited
          db_query("UPDATE {filedepot_files} SET status = 2, status_changedby_uid = %d WHERE fid=%d", $user->uid, $fid);
        }

        $headers = array(
        'Content-Type: ' . $type . '; name="' . $name . '"',
        'Content-Length: ' . $file->filesize,
        'Content-Disposition: ' . $disposition . '; filename="' . $name . '"',
        'Cache-Control: private',
        );

        if (count($headers)) {
          watchdog('filedepot', 'Transferring file %name (filedepot fid %fid, CCK fid %cckfid)',
            array('%name' => $name, '%fid' => $fid, '%cckfid' => $file->fid), WATCHDOG_INFO);
          file_transfer($filepath, $headers);
        }
      }
      $conf['file_directory_path'] = $system_directory_path;
      return drupal_not_found();
    }
  }

}

```

Can anyone help me ? when Im clicking on download its redirecting to homepage

# Answer
I thought it was hook\_menu not triggering correctly. But I was wrong, path were not correct. So the file was not there, that's it was redirecting to homepage

Finally I found the issue.

There was two reason

```
1. File Upload Path, We can change the path from http://yoursite.com/?q=admin/settings/filedepot
2. Upload Path Folder Permission.

```

I hope this would help someone.
> 1 votes

---
Tags: 6, routes
---


# Question
Title: How do I add custom validations to Webform?
I have created the country and state fields with the Webform module, and I want to add a field validation for the state field when user select US as country.

How can I achieve this?

# Answer
The Webform Validation module should add the features you need.

> This module adds an extra tab to each webform node, allowing you to specify validation rules for your webform components. You can create one or more of the predefined validation rules, and select which webform component(s) should be validated against those. By using the hooks provided by this module, you can also define your own validation rules in your own modules.

If you need something more in depth or with possibly more control then check out the answer linked to in the question comments.
> 4 votes

# Answer
Make use of the validate function in hook\_form\_alter:

```
 if ($form_id == 'webform_client_form_14') {
    $form['#validate'][] = 'cork_creation_validate_custom';
 }

function cork_creation_validate_custom($form, &$form_state) {
  if (!preg_match('/^[A-Za-z]+$/', $form_state['values']['submitted']['name'])) {
            // $form['submitted'][$key]['#attributes']['class'] = 'error';
            form_set_error('name', t('Please enter alphabets only for Name.'));
 }

  }

```
> 7 votes

---
Tags: webforms, forms
---


# Question
Title: Unexplained change in module weight in registry table caused site error
EDIT: August 6, 2015

It turns out that this was actually caused by incomplete data of module\_implements cached in the database by Drupal which caused a hook\_init to not be called. We changed the weight but also had cleared the cache and had incorrectly attributed the fix to correcting the weight.

---

We have a Drupal 7 site with mimemail and htmlmail modules installed. The htmlmail has a weight of 10 since it needs to be loaded after mimemail.

However, recently, the following PHP error started occur in the logs:

> PHP Fatal error: Call to undefined function mailsystem\_html\_to\_text() in /path/to/sitefolder/sites/all/modules/htmlmail/htmlmail.mail.inc on line 62".

We were able to **track it down** to the "weight" column in the registry table where the weight for class "HTMLMailSystem" has a weight of 0 when it should have been 10. Manually changing it to back to 10 fixed the issue.

We **confirmed** that there has been no active development or any core/module updates around the site this error started to occur.

Does anyone know what could have caused the weight to change?

Futher investigation by running the following query revealed no discrepancies in module weight between the registry and system tables on the development site

```
SELECT r.*,
s.name,
s.weight
FROM `registry` r
LEFT JOIN `system` s ON r.module = s.name
WHERE r.weight != s.weight

```

However, on the production site, the following entries module entries have a different weight between the two tables so it's possible other modules were affected too by whatever caused this - it just hasn't caused additional errors (such as due to the default load order perhaps being fine for those).

```
views_plugin_localization_core
views_plugin_localization_none
views_plugin_row_user_view
WebformComponentsTestCase
WebformGeneralTestCase
WebformPermissionsTestCase
WebformSubmissionTestCase
WebformTestCase
webform_exporter
webform_exporter_delimited
webform_exporter_excel
webform_handler_field_form_body
webform_handler_field_is_draft
webform_handler_field_node_link_edit
webform_handler_field_node_link_results
webform_handler_field_submission_link
webform_handler_field_webform_status
webform_handler_filter_is_draft
webform_handler_filter_webform_status

```

# Answer
An easy way to solve this problem is to set the `status` of that module to `0` in the `system` table. Then try to uninstall them completely and then try to install and set them again.

I know this is not the best way (there are other ways), but sometimes short and not optimal method is better that spend more time on debugging.
> 0 votes

# Answer
Maybe it could help to find the answer to your question if you'd use contributed module "Registry Rebuild". That module integrates with Drush via the `Drush RR` command. It will then rebuild the system table.

DrupalEasy Podcast #133 further explains how this module / drush cmd can be used.

Like I wrote above, it "could" help, not sure if it "Will". The way I'd actually do it is to first clone the entire site (code and DB) in a local dev environment, then run Registry Rebuild (in the local dev site), and then compare the content of the local dev DB result with the operational site, at least for tables such as the System table. So it's like using this module to get advice (hints) on what might be the problem.

Another related thought: **if** the version of this Drupal site is below 7.32, **then** the answer to this question might simply be that your site was hacked. For way more details about that, and possible approaches to do more research on that, refer to Drupal SA-CORE-2014-005 - How to tell if my server / sites were compromised?, which also suggests to use the Drupalgeddon module.

To take this a step further (for a site with version below 7.32), look at the "accepted" answer in What kind of attacks does the patch for SA-CORE-2014-005 (Drupal 7.32) prevent? ... It should be obvious that an appropriate UPDATE SQL statement (i.e. for module "weight" in the registry table) could be the explanation of this mystery.
> 0 votes

---
Tags: 7
---


# Question
Title: Adding price field on Drupal Commerce that affect Order Price
**The case is**

When user place an order, shipping price must be manually calculated before the final invoice is sent to user.

**What I do**

I create Price custom field on Order named *shippingfee*.

**Problem is**

How to make shippingfee field affect the Order price?

Another thing that I tried is creating custom line item type. I'm thinking that by creating this custom line item type would update the value.But following this tutorial, the custom line item type did not appear when I check on `admin/commerce/config/line-items`.

Code added to custom module:

```
/**
 * Implements hook_commerce_line_item_type_info().
 */
function owemji_commerce_line_item_type_info() {
  return array(
    'owemji' => array(
        'name' => t('Shipping Fee'),
        'product' => false,
        'description' => t('Price of shipping.'),
        'base' => 'owemji',
    ),
  );
}

/**
 * Implements hook_enable().
 */
function owemji_enable() {
  commerce_line_item_configure_line_item_fields(array('owemji'));
}

```

I did try clear cache and disable -\> enable the owemji module, but it's still not there.

# Answer
> 3 votes
There is a contrib module developed espacially for shipping - Commerce Flat Rate

> This module allows you to define any number of flat rate shipping services via the user interface in conjunction with Commerce Shipping 2.x. When you define a new flat rate service, you specify the base rate for it in the add / edit form. You can further modify the base rate (enabling things like weight or quantity based shipping) using rate calculation rules.
>
> This is functionally equivalent to using product pricing rules to add discounts or fees to base product prices before adding them to the cart.

There are few old but still actual video casts from rfay about Commerce Shipping. Watch it for a basic understanding:

# Answer
> 0 votes
I think you can commerce\_fees and if you want update you price according to user data you can do it with some custom coding and this module is what you want.

# Answer
> 0 votes
As @milkovsky said Commerce Flat Rate seems like the way to go.

Or if you want an even simpler solution : just create a Shipping product and manually add it to your order when you know the shipping.

---
Tags: commerce
---


# Question
Title: How do I change the views handler type for a field from string to int?
I'm using Views 3 on Drupal 7 with the Computed Field module. My Computed Field calculates an int, and it is stored in the DB as an int, but Views is using the string handler by default.

How can I change the handler for one specific field from string to int?

This is the code I'm using in a custom module in `mymodule.views.inc`.

```
function mymodule_views_data_alter(&$data) {
  dpm($data);
  $data['user']['field_my_custom_field']['field']['handler'] = 'views_handler_field_numeric';
}

```

However, in my view, the filter choices are still:

* Is equal to
* Is not equal to
* Contains
* Contains any word
* Starts with
* etc.

These are the string options; I need them to be the choices for int (greater than, less than, etc.)

# Answer
> 1 votes
You "should" just need to override the *filter* handler for the field, e.g.

```
function mymodule_views_data_alter(&$data) {
  $data['user']['field_my_custom_field']['filter']['handler'] = 'views_handler_filter_numeric';
}

```

Untested, use with caution!

# Answer
> 0 votes
In this case, I ultimately solved the problem by changing the type of my Computed Field from *varchar* to *int*-- I thought I had set it as int, but I was mistaken.

---
Tags: views, entities
---


title: Theming a custom menu block in Drupal 7

text:
# Question
Title: Theming a custom menu block in Drupal 7
So I created a custom menu through the Drupal administration and named it "More Menu." Its machine name, *menu-more-menu*, was auto-generated by Drupal.

Creating this menu automatically created its corresponding block, and its now available under Blocks administration as More Menu. I then enabled the block and placed it under my desired Region.

I wanted to theme the output of this block. I tried creating a template by following the template suggestion as described here, block--*module*--*delta*.tpl.php.

The template file I created was named block--*menu*--*menu-more-menu*.tpl.php.

It doesn't seem to work, and I still cannot override it.

Am I missing something?

# Answer
For custom menu blocks the format for the block template file name is

```
block--menu--<menu_machine_name>.tpl.php

```

**Note**: All machine names begin with the 'menu\_' prefix and all hyphens are converted to underscores.
> 4 votes

# Answer
Just for the heck of it, can you try assigning the actual ID of the block in place of 'menu-more-menu'? So you'd end up with something like block--menu--23.tpl.php. It's just to prove to ourselves that the template system is in fact working and that something is running afoul with the name you're using.
> 1 votes

---
Tags: routes, theming
---


title: Common Exposed filter for each tab

text:
# Question
Title: Common Exposed filter for each tab
I have different fields and showing in different blocks, and want to apply exposed filter to all but my problem is it shows different exposed filters for each different block. I want to make it common for each block.

Below are the steps,

1. I made 5 blocks to be displayed for each buttons.
2. Added exposed filter for languages for each block.

Now each block showing its different exposed filter. But I want the exposed filter should be shown above the buttons and should work for each block display. Attached screenshot for the issue.

I installed `Views Global Filter` but is gives `Session error`.

# Answer
After 3 days, I haven't found the solution, even by programmatically.

Then what I had the last option(in my mind, huh) is,

1. I get all the fields in one block only, not creating the different blocks for different tab or buttons.
2. Used the description of Better Exposed Filters, in which I pasted my buttons/tab UI HTML as its.
3. Now on changing the language all the fields are fetched according to the selected language. But in this case my active tab/button get lost its activeness.
4. Now, I need to get the last active tab/buuton, so that I can click it again to get the active tab after filtering my languages.

Below is the piece of code which is need to my `js file`.

```
// Active target element to make the tab/button active after
// ajax responds in filter
var activeTargetElement;
Drupal.behaviors.events = {
    attach: function (context, settings) {
        $('#views-exposed-form-MY_VIEW_MACHINE_NAME-BLOCK_NAME', context).ajaxStart(function () {
            // my tabs/button are active on the basis of data-target attribute,
            // so need to memorise which tab/button is active before fitering any language
            activeTargetElement = $('#MY_TABS li.active a').data('target');
        }).ajaxSuccess(function () {
            // if any target is memorised, then simply click it or trigger a click event for it
            if($('[data-target="'+activeTargetElement+'"]').length){
                $('[data-target="'+activeTargetElement+'"]').click();
            }
        });
    }
};

```
> 0 votes

---
Tags: views
---


# Question
Title: Active a menu <li> when the menu entry is a view page
I have a section (call news) that have an "home page". This home page is created via "views" and via "views" I have insert a link item into "main menu" menu based on path (/news). When I go to /news the relative entry in "main menu" is active (the \<li\> item has "active-trail" class). All works.

How can I active the same menu when I'm into a node of type news ? I have read that I need to use menu\_tree\_set\_path() into a hook\_preprocess\_page(). So I have tried to add this line into THEME\_preprocess\_page(&$vars) :

```
menu_tree_set_path('main-menu','/news');

```

but it does not work. I have tried with:

```
menu_tree_set_path('main-menu','news');

```

Same result. Not working.

In all my search, all tutorials tells to set for the second parameter of menu\_tree\_set\_path a node/NID or a taxonomy/term/NID, but I have not this node/nid. I have a view page path.

So, How can I do it ? Thanks.

# Answer
I guess you could achieve this with Menu Position module, where you can set an active parent for specific node/content types.

https://www.drupal.org/project/menu\_position
> 1 votes

# Answer
I had to do a trick like that once. I just used `menu_set_active_item()` but I had to manage the breadcrumb display too and here is my piece of code for that:

```
// Activate the View menu item but memorize the actual nature of the node for the breadcrumb
function mymodule_node_view($node, $view_mode, $langcode) {
  if ($node->type == "news" && $view_mode == "full") {
    $_SESSION['mymodule_active_trail'] = serialize(menu_get_active_trail());
    $_GET['mymodule_node_id'] = $node->nid;
    menu_set_active_item("news");
  }
  else {
    if (isset($_SESSION['mymodule_active_trail'])) {
      unset($_SESSION['mymodule_active_trail']);
    }
  }
}
// Alter the breadcrumb to show the real path to your news node
function mymodule_menu_breadcrumb_alter(&$active_trail, $item) {
  if ($item && $item['path'] == "news") {
    if (isset($_GET['mymodule_node_id'])) {
      if (isset($_SESSION['mymodule_active_trail'])) {
        unset($_SESSION['mymodule_active_trail']);
      }
    }
    if (isset($_SESSION['mymodule_active_trail'])) {
      $original_active_trail = unserialize($_SESSION['mymodule_active_trail']);
      if (is_array($original_active_trail)) {
        $total = count($active_trail);
        $active_trail[$total] = $item;
      }
    }
  }
}

```
> 1 votes

---
Tags: 7, views, routes
---


# Question
Title: Process long query and output data to file
I have several nodes in my site (7822 at the moment) and I need to generate new data from those node values. I have a custom module with all the functions and calculations.

The problem is that, because is so many nodes and the calculations are long, I need this to run on the background in some way.

I also tried to use views because there are plenty of modules that allow me to export the data to a file (I need that also) but in views I can't access my module functions.

How can I solve this problem? In case the queries are long, what solution should I use?

Thanks.

EDIT: Following the advice from Topsitemakers, I tried the following code to loop trough all my nodes and set some new field values but I'm getting some errors:

```
function MYMODULE_menu() {
    $items['admin/creategamedata'] = array(
        'title' => 'Game Data',
        'page callback' => 'MYMODULE_creategamedata_batch',
        'access arguments' => array('access administration pages'),
        'type' => MENU_NORMAL_ITEM,
    );
    return $items;
}

function MYMODULE_creategamedata_batch() {
    $batch = array(
        'title' => t('Creating Game Data'),
        'operations' => array(
            array('MYMODULE_creategamedata_testing', array()),
        ),
        'finished' => 'my_finished_callback',
        'file' => 'path_to_file_containing_myfunctions',
    );
    batch_set($batch);
    batch_process('node');
}

function MYMODULE_creategamedata_testing() {
    if (empty($context['sandbox'])) {
        $context['sandbox']['progress'] = 0;
        $context['sandbox']['current_node'] = 0;

        $count = new EntityFieldQuery;
        $context['sandbox']['max'] = $count->entityCondition('entity_type', 'node')
          ->entityCondition('bundle', 'game_results')
          ->propertyCondition('status', 1)
          ->count()
          ->execute();

    }
    $limit = 505;

    $query = new EntityFieldQuery();
    $query
        ->entityCondition('entity_type', 'node')
        ->entityCondition('bundle', 'game_results')
        ->propertyCondition('status', 1)
        ->propertyCondition('nid', 'value', $context['sandbox']['current_node'], '>')
        ->propertyOrderBy('nid', 'value', 'ASC')
        ->range(0, $limit);

    $result = $query->execute();

    if (isset($result['node'])) {
        $nids = array_keys($result['node']);
        foreach ($nids as $nid) {
            $node = node_load($nid->nid, NULL, TRUE);
            $context['sandbox']['progress']++;
            $context['sandbox']['current_node'] = $node->nid;
            $ft_result = rand(1,10);
            $node->field_ft_result[$node->language][]['value'] = $ft_result;
            node_save($node);
        }
    }

    if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
        $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
    }
}

```

Errors:

> An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows. Path: /batch?id=1128&op=do StatusText: Service unavailable (with message) ResponseText: EntityMalformedException: Missing bundle property on entity of type node. in entity\_extract\_ids() (line 7818 of /home/.../public\_html/.../includes/common.inc).

What am I missing here?!?

# Answer
> 1 votes
Check out Batch API. It allows you to queue items for processing, which will then be processed by Drupal one by one.
This is already used by core when you for example want to delete nodes on bulk, update modules, etc.

See also the `batch_example` module in the Examples bundle.

Another example can be seen in my Drupal 7 boilerplate here.

If this is not what you have asked for, update your question please.

---
Tags: cron, database
---


# Question
Title: In custom module - No such file or directory in drupal_build_js_cache() (line 5008 of /mnt/www/html/xyzexample/docroot/includes/common.inc)
I am newbie and working on Drupal-7.

I have created **custom block module** called '**mycampaign**' to add script to **Retargeting Tags** into each page.

***Script:***

```
<script async src="http://i.simpli.fi/dpx.js?cid=0&segment=Segment+Name&campaign_id=0"></script>

```

But, I am getting this **error:**

**Warning:** file\_get\_contents(\sites\all\modules\mycampaign\mycampaign.js\mycampaign.js) \[function.file-get-contents\]: failed to open stream: No such file or directory in drupal\_build\_js\_cache() (line 5008 of /mnt/www/html/xyzexample/docroot/includes/common.inc).

Appreciate your help!

.info file for my custom module

```
name = mycampaign
description = This module provides a custom block with dynamic content.
package = MyModules
core = 7.x
; NEW LINE
configure = admin/config/content/mycampaign
scripts[] = mycampaign.js

```

**File code from my custom module:**

```
<?php

/**
 * Implements hook_help().
 *
 * Displays help and module information.
 *
 * @param path
 *   Which path of the site we're using to display help
 * @param arg
 *   Array that holds the current path as returned from arg() function
 */
  /**
* Implements hook_block_info().
*/

function mycampaign_help($path, $arg) {
  switch ($path) {
    case "admin/help#mycampaign":
      return '<p>' . t("Displays links to nodes created on this date") . '</p>';
      break;
  }
}

/**
 * Declaring the block
 */
function mycampaign_block_info() {
  $blocks['mycampaign'] = array(
    // The name that will appear in the block list.
    'info' => t('mycampaign'),
    // Default setting.
    'cache' => DRUPAL_CACHE_PER_ROLE,
  );
  return $blocks;
}

function mycampaign_block_view($delta = ' ') {
  if ($delta == 'mycampaign_delta') {
    $block = array(
      'subject' => t('mycampaign block title'),
      'content' => array(
        '#markup' => '<p>' . t('mycampaign block output.') . '</p>',
        '#attached' => array(
          'js' => array('\sites\all\modules\mycampaign\mycampaign.js'),
        ),
      ),
      drupal_add_html_head($viewport, 'viewport')
    );
    return $block;
  }
}

/**
 * Implements hook_menu().
 */
function mycampaign_menu() {
 // $items = array();

  $items['admin/config/content/mycampaign'] = array(
    'title' => 'My Campaign',
    'description' => 'Configuration for My Campaign module',
//    'page callback' => '_mycampaign_page',
    'page arguments' => array('mycampaign_form'),
    'access arguments' => array('access mycampaign content'),
        'type' => MENU_NORMAL_ITEM, //Will appear in Navigation menu.
      );
    return $items;

}

function mycampaign_init(){
    drupal_add_js(drupal_get_path('mycampaign', 'mycampaign').'\sites\all\modules\mycampaign\mycampaign.js\mycampaign.js');
}

/**
 * Creating the configuration form
 */

 function mycampaign_contents() {
  //Get today's date.
  $today = getdate();
  //Calculate midnight a week ago.
  $start_time = mktime(0, 0, 0,$today['mon'],($today['mday'] - 7), $today['year']);
  //Get all posts from one week ago to the present.
  $end_time = time();

 //NEW LINE
 $max_num = variable_get('mycampaign_max', 3);

  //Use Database API to retrieve my campaign.
  $query = db_select('node', 'n')
    ->fields('n', array('nid', 'title', 'created'))
    ->condition('status', 1) //Published.
    ->condition('created', array($start_time, $end_time), 'BETWEEN')
    ->orderBy('created', 'DESC') //Most recent first.
    ->range(0, $max_num) //NEW LINE
    ->execute();
  return $query;
}
/**
 * Validating the data
 */
 /**
 * Implements validation from the Form API.
 *
 * @param $form
 *   A structured array containing the elements and properties of the form.
 * @param $form_state
 *   An array that stores information about the form's current state
 *   during processing.
 */
function mycampaign_form_validate($form, &$form_state){
  $max_num = $form_state['values']['mycampaign_max'];
  if (!is_numeric($max_num)){
    form_set_error('mycampaign_max', t('You must enter a number for the maximum number of posts to display.'));
  }
  elseif ($max_num <= 0){
    form_set_error('mycampaign_max', t('Maximum number of posts to display must be positive.'));
  }
}

/**
 * Specifying a custom permission for a new page
 * Implements hook_permission().
 */

function mycampaign_permission() {
  return array(
    'access mycampaign content' => array(
      'title' => t('Access content for the mycampaign module'),
    )
  );
}

/**
* Implements hook_menu().
*/
/*
function mycampaign_menu() {
    $items = array();
    $items['mycampaign'] = array(
        'title' => 'My Campaign',
        'page callback' => '_mycampaign_page',
        'access arguments' => array('access mycampaign content'),
        'type' => MENU_NORMAL_ITEM, //Will appear in Navigation menu.
      );
    return $items;
}
 * */

```

And script in JS file

```
<script async src="http://i.simpli.fi/dpx.js?cid=0&segment=Segment+Name&campaign_id=0"></script>

```

# Answer
> 1 votes
The error message means that Drupal is unable to locate `mycampaign.js`.

This may be because you've got the path wrong, or because the file and/or the directory it is in is so well protected that your web server don't have access to it.

In your case, you have the path wrong on two counts. Change:

```
function mycampaign_init(){
  drupal_add_js(drupal_get_path('mycampaign', 'mycampaign').'\sites\all\modules\mycampaign\mycampaign.js\mycampaign.js');
}

```

into:

```
function mycampaign_init(){
  drupal_add_js(drupal_get_path('module', 'mycampaign').'\sites\all\modules\mycampaign\mycampaign.js');
}

```

Pay attention to the first parameter as well as the path.

You also have two implementations of `hook_menu`. That should have produced another runtime error.

Since the script is not found, it is not loaded. I.e. at this point, it doesn't matter what it contains.

---
Tags: 7, javascript
---


title: Print Link field in View template

text:
# Question
Title: Print Link field in View template
I have a 'Link' field that is entered in plain text by user. I am trying to display the raw value of this field in my views template. I did `dsm($fields);` in the views template.

For the field, the raw data shows as a node id, not the url the user entered. The content attribute shows the url but it is wrapped in html. This is also the case when using `->content` or `->raw` in my views template.

I need to only print the plain url text the user entered in the template. How can I do this?

Here are the results for content and raw value:

# Answer
if you're using the Link module, you can choose how the link is displayed, including plain text

> The link module can be count to the top 50 modules in Drupal installations and provides a standard custom content field for links. With this module links can be added easily to any content types and profiles and include advanced validating and different ways of storing internal or external links and URLs. It also supports additional link text title, site wide tokens for titles and title attributes, target attributes, css class attribution, static repeating values, input conversion, and many more.
> 1 votes

# Answer
I figured out what needed to be used in the Views template:

```
$row->field_field_news_link[0]['rendered']['#markup']

```

This gets the text entered by the user. No need to change to Link field or get the raw value.
> 0 votes

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


title: Track error on file permission?

text:
# Question
Title: Track error on file permission?
I get this error when running Status Report:

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

Where should I look for this folder?

# Answer
That should be in the base of your site's file directory. Navigate to **/admin/config/media/file-system** to see where it is configured.
> 1 votes

---
Tags: files
---


# Question
Title: when i want to reinstall the modules i get this error
```
Fatal error: Call to undefined function node_type_get_names() in /home/aukhma/public_html/modules/comment/comment.module on line 119

```

I got a blank page when I would try to reinstall the node and the menu modules.

The cause that pushed me to reinstall those modules is that when I want to create a node for a new content type I can't find my new content type in the "add node" page. So I did some research and found a solution that said I need to rebuild the menu. I did that but got no result. I've also cleared the cache multiple times through the dash board.

Please, if any one can help find a solution I will be so happy, and thank you for the quick reply.

# Answer
The content type you create is stored in your database, no reason to do what you are trying to do. Check your db tables for that types.

These are core modules that are never meant to be uninstalled, cause these kind of functions are used by other modules and core files without even a dependency on them cause they are considered ... core.

Better try with a fresh install.
> 0 votes

---
Tags: 7
---


# Question
Title: Add a class to the first li.pager-item for a view pager?
How can I add a class to the first li.pager-item and a different class to the last li.pager-item for for a Views pager?

I know that I need to make a theme override of theme\_pager https://api.drupal.org/api/drupal/includes!pager.inc/function/theme\_pager/7

However I cant figure out what PHP to change.

# Answer
> 2 votes
If you implement theme\_pager you'll be expected to create the entire pager render array from scratch using several theme function - theme\_pager\_first, theme\_pager\_previous, theme\_pager\_next and theme\_pager\_last. That seems like entirely too much work for adding one class.

Since theme\_pager calls theme\_item\_list at the very end to build the final render array, you can use hook\_preprocess\_HOOK to modify the pager render array before drupal renders it into HTML.

```
function THEME_preprocess_item_list(&$vars) {
  // make sure we're dealing with a pager item list
  if (isset($vars['attributes']['class']) && in_array('pager', $vars['attributes']['class'])) {
    // make sure there are items
    if (count($vars['items'])) {
      $vars['items'][0]['class'][] = 'test';
    }
  }
}

```

Clear the cache after adding this hook.

**UPDATE**: find the first li.pager-item:

```
function THEME_preprocess_item_list(&$vars) {
  // make sure we're dealing with a pager item list
  if (isset($vars['attributes']['class']) && in_array('pager', $vars['attributes']['class'])) {
    // loop the items and find the first .pager-item
    foreach ($vars['items'] as $index => $item) {
      if (in_array('pager-item', $item['class'])) {
        $vars['items'][$index]['class'][] = 'test';
        break;
      }
    }
  }
}

```

**UPDATE2**: find first and last li.pager-item:

```
function THEME_preprocess_item_list(&$vars) {
  // make sure we're dealing with a pager item list
  if (isset($vars['attributes']['class']) && in_array('pager', $vars['attributes']['class'])) {

    // loop the items and find the first and last .pager-item
    $first = FALSE;
    $last = NULL;
    foreach ($vars['items'] as $index => $item) {
      if (in_array('pager-item', $item['class'])) {

        // first
        if (!$first) {
          $vars['items'][$index]['class'][] = 'test';
          $first = TRUE;
        }

        // last
        $last = $index;
      }
    }

    if (!empty($last)) {
      $vars['items'][$last]['class'][] = 'test2';
    }
  }
}

```

# Answer
> 0 votes
Scott Joudry's answer is correct. However when your on the first page of a view. The li has a class of pager-current not pager-item as it isnt a link. Therefore if you want to add a class to the the li that contains the text "1" then use this:

```
function THEMENAME_preprocess_item_list(&$vars) {
  // make sure we're dealing with a pager item list
  if (isset($vars['attributes']['class']) && in_array('pager', $vars['attributes']['class'])) {

    // loop the items and find the first and last .pager-item
    $first = FALSE;
    $last = NULL;
    foreach ($vars['items'] as $index => $item) {
      if ((in_array('pager-item', $item['class'])) or ( in_array('pager-current', $item['class']))) {

        // first
        if (!$first) {
          $vars['items'][$index]['class'][] = 'test';
          $first = TRUE;
        }

        // last
        $last = $index;
      }
    }

    if (!empty($last)) {
      $vars['items'][$last]['class'][] = 'test2';
    }
  }
}

```

---
Tags: views, theming
---


# Question
Title: Drupal Views rewrite link dependent on boolean value
I have a view that has a boolean field in it and a field that links to a file. I want to use the boolean field to where if it is checked, it will direct to a static link, regardless of what file is uploaded. If it is unchecked and there is no file, I want it to output nothing. If it is unchecked and there is a file, then output the file link. I tried setting up Views PHP and setting this up there, no luck. First question is does Views PHP recognize rewrite rules that you've established in other fields, and if not, how can I accomplish this? Below is the code I tried in Views php. All it does is output the node id for every entry.

```
<?php
  if($row->field_booleanval) {
    echo '<a href="http://www.example.com">Link</a>';
  }
  else if(!($row->field_booleanval) && !($row->field_file)) {
    echo ' ';
  }
  else {
     echo $row->field_file;
  }
?>

```

# Answer
> 1 votes
I finally got it to work as follows:

PHP field, Value Code:

```
return $data->field_field_booleanval[0]['raw']['value'];

```

Output Code:

```
<?php
  print_r($value);
?>

```

This returns the correct VALUE for the boolean field. So you can skip the Value Code unless you plan on using the variable elsewhere, and output could look something like:

```
<?php
  $booleanval = $data->field_field_booleanval[0]['raw']['value'];
  $fileval = isset($data->field_field_file[0]); // shouldn't be set if no value

  if($booleanval) {
    echo '<a href="http://www.example.com">Link</a>';
  }
  else if(!$booleanval && !$fileval) {
    echo ' ';
  }
  else {
     echo $row->field_file;
  }
?>

```

---
Tags: views
---


title: Commerce: Modify the order price

text:
# Question
Title: Commerce: Modify the order price
I want to modify the price of the order, but I was unable to change that if the order status is either "Shopping cart" or "Checkout".

What I did is changed the order status to "Pending", then the price can be modify. After modifying the price, I changed back the order status to "Shopping cart", then the price becomes disabled again.

When I check my cart, the price is same as with the original price, so I looked at the order again and find out that the price has been changed back into its original price.

Why is this happening? I'm not familiar yet with commerce.

# Answer
If I understand it correctly, a shopping cart refresh causes the recalculation of your line item price(s). For documentation on this topic, see sell price calculation on drupalcommerce.org and the referenced Prezi presentation on that page.

Maybe you can adjust the price calculation, by adding pricing rules that react on the event 'Calculating the sell price of a product' and use the action 'Set the unit price to a specific amount'.

Otherwise, you could implement one of the hooks provided by commerce\_product\_pricing.api.php.
> 2 votes

---
Tags: commerce
---


# Question
Title: ThemeKey: Use main theme for Node/edit and user/edit
By default, Drupal uses the "main theme" for the main site, and the "admin theme" for the admin pages.

I want to use my "main theme" for the `user/edit` pages and `node/edit` & `node/add` pages of the "journal" content type only. For all other administration pages (including the `node/edit` & `node/add` pages of other content types) , I want to use the "admin theme".

How can I do this? In Theme Key there doesn't seem to be options to select `node/edit` & node add pages of a particular content type (or options to select `user/edit` pages).

# Answer
> 3 votes
you will need to create a hierarchical set up:

In this example set up, it checks for user:1 (admin), that the node type (content type) is article, and that the path meets the relevant criteria. You will need to adjust accordingly. Simply drag and drop the sub-elements into place.

---
Tags: theme-negotiation
---


title: How to get text before the title?

text:
# Question
Title: How to get text before the title?
I suppose this is something about theming, but I haven't found a way to do this. I'm using the Pixtures Reloaded subtheme of Adaptive Themes.

I have a group of pages that need to have the structure: `Pretitle
 Title
 Subtitle
 Body` that should come out looking like this: `A true story:
 The Amazing Thing
 And Why it's Amazing
This is the story of...` The title and subtitle are centered.

When I create a "Basic page", I have to specify a title for the page, and that title is displayed at the top-left of the page. I tried two ways to get something to be shown before the title.

First I defined a block called "Pretitle" and placed it in the theme's region called "Secondary content", which in the "Block region demonstration" is shown as being above the title. But when I displayed the page, the pretitle was exhibited under a big banner that said "Pretitle". That's not okay.

Next, I deleted that and defined a text field called "Pretitle" and placed that above the title in the Field Manager. When I displayed the page, the pretitle appeared at the very bottom of the page, under a line that said "Pretitle:". Again, not okay.

Aside from not seeing how to get a line of text to appear before the title (without a banner saying that it's a pretitle), I also have not a seen a way to get the title to be centered horizontally on the page.

I'm guessing this problem is because there's something really simple about composing pages in Drupal that I don't know about. Can you tell me what I'm missing?

Please don't give an answer that requires writing my own module because I'm not nearly ready to do that yet.

Thank you.

# Answer
> 1 votes
to center the title: find the appropriate css file, and change:

```
.title, #page-title
{
...
}

```

to include

```
.title, #page-title
{
  text-align:center;
}

```

It could be listed as either the class title, or id, depending on the theme. This is basic CSS.

to include the other fields:

1) you can alter the page.tpl.php file for theme, but if modules are out, I assume most any php is out, so this is probably not suitable.

2) reassign your block if it otherwise worked, but in the block set up, change the Block Title to `<none>`

---
Tags: 7
---


# Question
Title: Generate match list from two different content type on price basis
I have two content type A & B in my application. The content type A have some attributes and a price attribute. The content type B have some other attribute and a price attribute.

Now say A have one item as A1 having price value X. And B has one item B1 that has price value Y.

I need to populate items of content A and B based on following price matching algorithm:

```
 (y- 20 percent of y) < X < (y+ 20 percent of y)

```

E.g:

```
content type A :
items price
A1 - 100
A2 - 200
A3 - 300
A4 - 110

content type B :
    items price
    B1 - 80
    B2 - 100
    B3 - 290
    B4 - 310

Final list :
    A1 - B1, B2
    A2 -
    A3 - B3,B4
    A4 - B1,B2

```

Can any one suggest me how to archive this in drupal 7.

# Answer
> 0 votes
it could probably be done using Views

> You need Views if
>
> You like the default front page view, but you find you want to sort it differently. You like the default taxonomy/term view, but you find you want to sort it differently; for example, alphabetically. You use /tracker, but you want to restrict it to posts of a certain type. You like the idea of the 'article' module, but it doesn't display articles the way you like. You want a way to display a block with the 5 most recent posts of some particular type. You want to provide 'unread forum posts'. You want a monthly archive similar to the typical Movable Type/Wordpress archives that displays a link to the in the form of "Month, YYYY (X)" where X is the number of posts that month, and displays them in a block. The links lead to a simple list of posts for that month. Views can do a lot more than that, but those are some of the obvious uses of Views.

and Views PHP

> This module allows the admin account (user 1) to add fields, filters and sorts to views which use PHP code. It also supports additional accounts when the core PHP Filter module is enabled.

Creating a View limited to those content types, and including the relevant fields - it would allow you to create a Global:PHP sort field, in which you could use your formula to determine the sort order. It would be tricky though, since it appears you want to include duplicates and group them together.

---
Tags: 7
---


# Question
Title: $_FILES superglobal array key is not what file.inc expects
I'm trying to do some custom stuff with a file upload field via the form API. I call to `file_save_upload()` but it thinks that the upload is empty because it's examining `$_FILES['files']` but for some reason, my file is actually in `$_FILES['CSV_file']` even when the file I uploaded is not a csv.

How might files superglobal end up with a `CSV_file` array key?

UPDATE

So apparently the form array

```
$form['my_menu_csv'] = array(
  '#name' => 'CSV files',
  '#type' => 'file',
  '#title' => t('Choose a CSV file'),
  '#title_display' => 'invisible',
  '#size' => 22,
  '#theme_wrappers' => array(),
  '#weight' => -10,
);

```

was causing the field to have the following HTML:

```
<input type="file" id="edit-my-menu-csv" name="CSV file" size="22" class="form-file">

```

and apparently the files array goes like `$_FILES[$name]`, where $name = whatever the name attribute is in the HTML element. Makes sense! What doesn't make sense is why `file_save_upload()` expects to only ever encounter `$_FILES['files']` but the form API uses a custom field name. Is this a bug in the form API?

# Answer
I don't think it's a bug.

$\_FILES\['files'\] is hard-coded into file\_save\_upload().

I believe you need to change how you construct your `#name` property. The usage example in the Form API does it like this:

```
'#name' => 'files[' . implode('_', $element['#parents']) . ']',

```
> 1 votes

---
Tags: forms, files
---


# Question
Title: Move fields on User edit page between pages
I am using Simple News, which changes the `user/1/edit` page by adding a new "Newsletter' Page" that is at `user/1/edit/simplenews` ("1" can be any userId). This page has a *Newsletter option field*.

I would like to move this option field so it is on the main user/1/edit page.

How can I do this?

I have created my own customer user-edit template (tpl.php), following the instructions here. The template effects both `user/1/edit` and `user/1/edit/simplenews`.

I can print out the Newsletter option field with `<?php print drupal_render($form['subscriptions']);?>`. But the field only prints out when the user goes to `user/1/edit/simplenews`. On `user/1/edit` it disappears.

# Answer
> 1 votes
Neither are pretty but, you could customise SimpleNews so that it includes the correct form data on the page you want (instead of creating its own local menu entry), or use hook\_form\_alter() with a custom submit and validation handler on the user edit form to update the db properly - you should be able to steal the code from simplenews for the validation and submit, that way it will update the db the way it was intended. If you go for the former, new updates to simplenews will be difficult to deal with and if you go with the latter however, be aware that future updates to simplenews may break this functionality if they change table names, etc.

---
Tags: forms, theming, users
---


title: Change user picture via services 3

text:
# Question
Title: Change user picture via services 3
I'm update user profile data via services 3 but I have a problem with user picture. I send user picture to my web site via services and it works:

```
{"fid":"1078","uri":"http://MyDomain/rest/file/1078"}

```

But how can I pass this "FID" to the user update method ? Which is the correct parameter name ?

Thanks.

M.

# Answer
The file ID is stored in the `picture` column of the users table

> Foreign key: {file\_managed}.fid of user's picture.

So your payload to the update resource would look something like

```
{
  "uid": "123",
  "data": {
    "picture": "1078",
    # rest of user data
  }
}

```
> 1 votes

# Answer
The `fid` you pass there is just ignored. You have to write a bit of code in a module to save the `fid` yourself.

You can find code ready to be copy-pasted here: https://www.drupal.org/node/2471178#comment-9825329

Note: the `picture_upload` field is processed server-side but it won't actually work either because the file upload module looks at `$_FILES` and that'll be empty. The `$user->picture` `fid` will thus be set to 0 (current avatar, if any, will be removed).
> 1 votes

---
Tags: 7, services, media, users
---


# Question
Title: Loading term references into a custom module
I have a term reference field in my content type. I'd like to be able to access the vocabulary items from that field in a custom module so I can pre-select one based on a users selection of an item from a field list. How is this possible?

An example might help illustrate the problem:

```
Content type: resource
field 1: Category (field list)
field 2: Group (term reference, hidden)

```
1. User selects one of eight options in the 'field 1' drop down select box. Selections include things like 'paper', 'metal', 'stone', etc.
2. The hidden 'Group' field detects which selection the user made above and auto-fills itself by selecting the vocabulary item in the associated taxonomy that maps to the selection they made. There are only three possibilities for 'Group' however so I'd also have to specify in the module WHICH selections from the field list map to which terms from the taxonomy to make sure the selections are correct.

For example, if a user selects 'paper' in the field list then Group should auto-select the term 'recyclable' before saving the record.

Anyone know how to do this?

I was going to approach it with hook\_form\_alter and hook\_node\_presave...but I'm not very comfortable with coding in modules yet.

Thanks!

# Answer
> 1 votes
If the field is hidden and doesn't do anything client-side, you shouldn't touch it client-side. Do the Category -\> Group translation server-side even if you're not very comfortable with it yet.

hook\_node\_presave should do the trick.

---
Tags: taxonomy-terms, nodes
---


title: Locking fields on a content type

text:
# Question
Title: Locking fields on a content type
Using Drupal 7:

I have several content types with their own sets of fields, but I also have a set of fields that they must all share in common. That is easy enough through the administrative UI, but I'm writing a module that programmatically will add the fields to all node content types that I specify. Additionally, I do not want the administrator to be able to remove or edit those fields through the administrative UI.

How can I make it so that as an administrator is managing content types that the admin cannot modify or remove these fields that I have specified?

Alternatively, I know that I can create a separate entity and force field existence that way, but then I loose access to a lot of the functionality already built into the node entity, especially the function hook\_node\_access which is also a requirement for this module.

Anyone have any suggestions or know how to solve this?

# Answer
> 3 votes
Refer to the field api documentation here. You do not have to add permissions to block the delete. All you need to do is add the "locked" attribute to the field definition.

> locked (integer): Whether or not the field is available for editing. If TRUE, users can't change field settings or create new instances of the field in the UI. Defaults to FALSE.

# Answer
> 0 votes
There is a module for that names "Field Lock".

Of course it uses the API field definition "locked" as mentioned before.

Here is a short description from the module page:

> Field lock adds additional level of permissions so certain users can lock a field, enter code herepreventing others from editing or deleting it.

# Answer
> 0 votes
For existing fields that are provided by (eg, media\_gallery or commerce) You can run-once the snippet from http://atlantic-canary.net/es/how-to-lockunlock-a-field-in-drupal

```
<?php
$field_name = 'field_name';
$field = field_read_field($field_name);
$field['locked'] = 0; // 0: unlock; 1: lock.
field_update_field($field);
?>

```

I did it for myself in an update hook, to ensure that my extension to media\_gallery could expose some settings.

```
/**
 * UNLOCK the description field provided by media_gallery so we can tweak settings.
 */
function niwa_media_update_7002() {
  $field = field_read_field('media_description');
  $field['locked'] = FALSE;
  field_update_field($field);
}

```

In my case I just wanted to limit the text formats that were available as an image caption, as full\_HTML was causing problems. better\_formats.module could not help me until I'd unlocked the field.

---
Tags: nodes, entities
---


title: Oracle Weblogic Server

text:
# Question
Title: Oracle Weblogic Server
My doubts about drupal requirements are: \- Can run Drupal 7 on a Oracle WebLogic Server? How would the integration be? \- Can i use the Oracle driver for this porpuse?

# Answer
Yes you have to use Oracle Driver.

> This is a driver that allows Drupal to use an Oracle Database instead of MySQL as the primary backend.

Refer to these links :

1. Link 1
2. Link 2

I hope these links may definitely solve your query.
> 1 votes

---
Tags: 7, installation
---


# Question
Title: How can I add an argument in the URL that link from a content
I have been searching for the answer for so long but still none of the solution that I can finish my goal...

my content structure is as following:

* I have Content-type that keep a list of Quotes - I named it \[A\]
* I have Content-type that keep a list of Titles - I named it \[B\]
* In a 'Quote', I have a field that refer to which 'Title' that it is referring.

EXAMPLE (not codes)

> Quote-1 have a field referring to Title-1
>
> Quote-2 have a field referring to Title-1
>
> Quote-3 have a field referring to Title-2
>
> Quote-4 have a field referring to Title-3
>
> Quote-5 have a field referring to Title-1
>
> (multiple Quotes can referring to the same Title)

So...I used Views(block) to display this Quotes\[A\] in a page and...HERE is what I want...

I want each 'Quote' to link into another page which require 2 parameters...

1. node ID (which is already sent by default Drupal (q=...))
2. Title ID (that is referring in a field of the Quote)

by default, the Drupal have value of 'q' sent to another page but ...

How can I add Title ID parameter into each 'Quote' link?

# Answer
You could add the Title ID field to your view, exclude it from display, move it above the link, enable rewriting on the link field and write the link format you want, including the Title id.

Edit following the follow-up question: Well, in my opinion, you shouldn't have to put the Title id in the URL at all. What I wrote above solves your specific problem but, really, I think you should do things differently and thus wouldn't have this problem or the follow-up one.

Link to node/quoteid and load the Title node by looking at `field_title_id` (replace by the actual field name). You can do that loading in hook\_preprocess\_node by calling `node_load($node->field_title_id[LANGUAGE_NONE][0]['nid'])` from there you can either render the whole title node (`node_view`) or just get one field and send it to your template.

Basically, the Quote-\>Title relation is in the database, there's no reason you should have to express it in the form of a URL. The reverse would make sense, if you had a Title page where you want to show a single quote.

Second edit following the second follow-up question:

To display all other Quotes linked to the same title you could create a view with Title ID as a contextual filter. You can render the view manually in your template, passing it the Title ID. That'll display all quotes, including the main one displayed in that page. You probably want to filter that one out one way or another.
> 0 votes

---
Tags: views
---


title: Show more fields under admin/people

text:
# Question
Title: Show more fields under admin/people
when i go to admin/people section. it is showing me

username, roles, etc.

I want to show first\_name, last\_name as well.

is there is any way to do this

Thanks

# Answer
Install the module Admin Views

An overview from the module page:

> Replaces administrative overview/listing pages with actual views for superior usability.
>
> Features
>
> * Filter all administrative views via AJAX.
> * Perform any kind of bulk/mass operations on items in administrative views.
> * Filter content by title, node type, author, published status, and/or vocabulary.
> * Filter comments by title, author, node title, or published status.
> * Filter users by name, ban/blocked status, or user roles.

Once installed this module will replace the main admin content page, and the admin user page with pre-made views. You can then customise these to suit your needs (adding or removing fields / filters).
> 3 votes

# Answer
Yes. Make *your own* view that displays users with whichever fields you want to see. You can also set filters, bulk actions and so on.

You can't make it show when you click on 'People' but you can certainly link to it in your shortcuts.
> 0 votes

# Answer
Yes, There are couple of ways to do this.

First, You can install profile2 module. This module creates both public and private profile for every user and you can add any field you want in there. This module has some other benefits as well.

Second, using Drupal core go to `admin/config/people/accounts/fields` address and add any field you want to the users.
> 0 votes

---
Tags: views, 7
---


# Question
Title: How to get the unread message count using EntityFieldQuery
Using below query I am getting the count of all messages of a user. Now i need to filter them to unread messages only.

```
global $user;
$query = new EntityFieldQuery();
$count = $query->entityCondition('entity_type', 'message')
 ->propertyCondition('uid', $user->uid)
 ->count()
 ->execute();

```

# Answer
If you are using the privatemsg module you can use privatemsg\_unread\_count().
> 0 votes

---
Tags: 7, database
---


# Question
Title: Adding a table with items and prices to a drupal site
I am not sure how to ask this question, but I hope I will be making myself clear.

We are building a CMS-like site for the most part, but the customer also wants the capability of adding a prices table for goods that can be consumed by a user on a daily basis.

So far, there is a custom content type 'user daily report' whose purpose is to store info of the likes of:

user1 - 2015/05/01 - 1 breakfast - 1 lunch - 3 drinks

At the end of the month, I have to be able to provide a report which summarizes how much the user has to be charged for his/her accumulated consumption.

I'm not sure how to exactly phrase my question here, since I'm fairly new to Drupal. Therefor I'll try to describe my requirement / question using some language I'm more familiar with:

* Have Drupal create a products table, a prices table (foreign key-ed to the products table), and add a couple fields to the daily report content type (product\_id, amount).
* In order to create the monthly report, I think I would just use a grouping SQL query (with group by and sum).

The above is not very 'drupalish'. But at the same time, I fail to see how the products and prices tables could be implemented using **content types**.

To make the question more precise, it is actually a 2 parts question, being:

1) I am not sure that putting the products and prices info inside of Drupal is best achieved by using custom content types. What is the best way to go for you people when faced to this type of functionality?

2) What is the best way of extracting/summarizing the info at the end of the month? I have struggled my way using the views module, but being myself much of an 'old school programmer' I am not necessarily confident that all I need can be achieved by using 'views'.

With all that in mind, my question is: what's the best approach to achieve this goal in a way that integrates well with 'the Drupal way'?

Any hint on the topic is most welcome!

Thanks In Advance!

PS. I've tried the entity-references + views\_calc way with a wee prototype. In general, I feel satisfied with the tests I've carried out.

What we need to be able to implement is several tables of products/prices available to different sets of users. All of it based on organic groups (we are using an openatrium distribution).

Using an entity-reference as a field in the users content type, and then adding the necessary relationship when using the views module, I can get what I need. Plus with the Views Calc module I get the summarized stuff.

I still have to try it all in our fully fledged openatrium dev install and see what happens when associating products/prices to groups. But so far, seems promising.

I've learned that my original version of the question didn't fit the questions policy because it was too loose and prone to answers based in personal opinion vs facts (and sorry about that). Maybe the edited version will prevent it from getting closed?

I'll choose Pierre's answer as right, as it has certainly been helpful.

# Answer
> 1 votes
Your question consists of 2 questions ... I'll use the same numbers to answer them.

# 1. Alternatives to using Custom Content types

## a) Use Drupal Entities (Option 1)

Use the Entity Construction Kit (ECK) module to create 'entities' (= fieldable things ...) like Products and Prices. For each of those entities use "fields" for each of the columns you mentioned. Should you run into fields such as dates, you would have to add modules such as date also.

For the "foreign keys" use the Entity reference module (possibly some related modules of it also, extending its functionality, as mentioned on the ECK project page) and/or the References module (cfr. 'node\_reference' and 'user\_reference' as contained in CCK for D6).

Maybe modules like Display Suite or Panels could help to enhance the look and feel of it all also?

## b) Use custom tables and/or an external database (Option 2)

**Custom tables** are tables you create yourself, in the same Drupal database. **External Databases** are databases that are different from the Drupal database, which are typically in formats such as Oracle, PostGress, MS Sql, MySQL, SQLite, some PDO compliant DBMS.

Using this alternative, you can use the Forena module for reporting about the data from within a Drupal site (as further explaining within "reporting" below also). To perform updates (delets, inserts, etc), you'd use your own tools that you'd prefer for the DBMS of your choice. Same for creating the tables, etc.

# 2. Reporting

Consider using modules such as (either one, or both, depending on your requirements):

Disclosure: I'm a (co-)maintainer of some of the modules mentioned,
I hope this does not violate the site's policy on self-promotion.

---
Tags: nodes
---


# Question
Title: Disable payment if Drupal Commerce Order Balance Total is <250
I am trying to disable a payment option if the order balance total is over $250. I currently have the following, but it throws an error as there is nothing to drill down into after "order-total:"

# Answer
> 4 votes
Actually the correct condition is called: Price Comparison and not Balance total

see here:

# Answer
> 1 votes
Value must be in Cents: for 50$ the value must be 5000 See here: https://www.drupal.org/node/1294606

---
Tags: 7, rules, commerce
---


# Question
Title: Add as a particular role while creating an account in Drupal 7?
In Drupal 7, I have a role named as "blogger". When user goes to blog site and created an account then a role should set by default as "blogger" rather than "authenticated user". How to do this? Any Suggestions please.

# Answer
> 0 votes
I found the solution from this Auto Assign Role Module - http://drupal.org/project/autoassignrole .

In congifuration settings, We can assign for automatic role.

# Answer
> 2 votes
Adding my comment as answer. If every user is a blogger then the easiest way I see is not to have it as a separate role at all; instead assign similar permissions to authenticated user.

Or you could change the role of the user by implementing hook\_user\_insert():

```
function MODULE_user_insert(&$edit, $account, $category) {
  $account->role = 'blogger';
  user_save($account, $edit = array(), $category = 'account');
}

```

# Answer
> 0 votes
I found that you need to add the role name - together with its key - into the new user's 'roles' array. In the example below, the role 'teacher' has a rid of 8:-

```
function MODULE_user_insert(&$edit, $account, $category){
  $account->roles[8]='teacher';
}

```

---
Tags: users
---


title: Tree like structure in views

text:
# Question
Title: Tree like structure in views
I have a content type in which I have following fields

Title, year, and report type. I create a block using **BEF** for exposed report type. which is working fine

Now I want to show results as

```
- 2014
    --Title1
    -- Title2
+ 2013
     --Title 2013
     --- Title 2013 1

```

and so on

When i click on + icon result will expand.

Can we do this using views or I have to right custom code for this?

# Answer
Maybe you should look at the Views tree module, to see how well it would fit your needs. Here is a quote about the module (from its project page):

> ... provides a tree-based style plugin for Views.
>
> It is based off of the list style. Although it generates a nested view, there is still only a single query run for the view making it quite performant.
> 1 votes

---
Tags: 7, views
---


# Question
Title: Call a Javascript Function and Update my Form Element at the same time
This is my ajax callback function

```
function myid_search_idnumber($form, $form_state)
{
    return $form['id'];
}

```

It updates the values in `$form['id']`. But Because I wanted to call a javascript function as well as update the form, I added a few codes:

```
function myid_search_idnumber($form, $form_state)
{
    $commands[] = ajax_command_invoke(NULL, 'myid_update_id_number');
    $page = array( '#type' => 'ajax', '#commands' => $commands, );
    ajax_deliver($page);

    return $form['id'];
}

```

The three lines of code added above, calls a javascript function.

```
$.fn.myid_update_id_number = function(){
    alert('Wew');
}

```

Performing those only calls the javascript function but does not update anymore my form. How will I call my javascript and at the same time update my form?

# Answer
> 1 votes
Just to ad to the above answer by Ollie.
To return `form['id']` too (same as the default behavior), you can use ajax\_command\_replace

```
function myid_search_idnumber($form, $form_state){
    $commands[] = ajax_command_replace(NULL, render($form['id']));
    $commands[] = ajax_command_invoke(NULL, 'myid_update_id_number', array($form['id']));
    $page = array(
         '#type' => 'ajax',
         '#commands' => $commands,
      );
    ajax_deliver($page);
  }

```

# Answer
> 0 votes
`ajax_deliver()` calls `ajax_footer()`, which basically terminates the request, and exits. Hence your `return $form['id']` isn't called.

Why don't you simply add the form\_id as a parmeter to `ajax_command_invoke`? Haven't tested it, but it should work. Have a look at the documentation for the `ajax_command_invoke` function in /includes/ajax.inc around line 1185.

`function myid_search_idnumber($form, $form_state){
 $commands[] = ajax_command_invoke(NULL, 'myid_update_id_number', array($form['id']));
 $page = array(
 '#type' => 'ajax',
 '#commands' => $commands,
 );
 ajax_deliver($page);
 }`

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


# Question
Title: Filter by postal code as location within user defined radius
I have to make a filter in which user will add postal code and select a radius. Suppose, user entered postal code = 12345 (which results into city 'XYZ') and the radius of 200 miles. So all nodes containing the location within the radius of 200 miles of the city 'XYZ' will be the output.

Can anyone suggest some solutions?

# Answer
geofield should have what you're after. It includes proximity handling and an exposable views filter.
> 1 votes

# Answer
Views exposed filter with Proximity/Distance worked..... :)
> 0 votes

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