title: What happened with AHAH?

text:
# Question
Title: What happened with AHAH?
I notice that all my AHAH forms (in the admin) don't work all of a sudden after I updated Drupal and jquery\_update. Now that I am working with building a form with the Form API and want to make it dynamic with AHAH through ahah\_helper, it hangs itself.

For example, if I type something into a textfield that is supposed to change on blur, the throbber pops up and I can see that the form is trying to POST the change, but then this error comes up:

> uncaught exception: Syntax error, unrecognized expression: /\x3e\n\x3c/div\x3e\n\x3c/div\x3e"

and it says it's from the jquery.min.js file. I am using 1.5.

I have heard that this can be because of conflicting files in other modules, and I have tried several different patches for those modules; none of them work.

Does anyone have an insight on this? Or should I use AJAX instead?

# Answer
Better late than never...

Well the problem is in the Drupal server response, which is not valid json. You need to patch drupal\_js function in commons.inc.

```
diff --git a/includes/common.inc b/includes/common.inc
index 80fc911..084b5fc 100644
--- a/includes/common.inc
+++ b/includes/common.inc
@@ -2551,8 +2551,8 @@ function drupal_to_js($var) {
     case 'resource':
     case 'string':
       return '"'. str_replace(array("\r", "\n", "<", ">", "&"),
-                              array('\r', '\n', '\x3c', '\x3e', '\x26'),
-                              addslashes($var)) .'"';
+                              array('\r', '\n', '\u003c', '\u003e', '\u0026'),
+                              str_replace("\'","'", addslashes($var))) .'"';
     case 'array':
       // Arrays in JSON can't be associative. If the array is empty or if it
       // has sequential whole number keys starting with 0, it's not associative

```
> 2 votes

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


# Question
Title: Error trying to connect to database when installing new site on localhost
Has anyone come across this problem? Once I get drupal all ready to install on my localhost I go to the URL and start going through the installation process and when it comes to my database it fails.

So I import the site into Acquia Dev Desktop, create the database, and then go to the URL, select the type of installation and then when I come to the database information page it fails.

Failed to connect to your database server. The server reports the following message: SQLSTATE\[HY000\] \[2002\] Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2).

I can't find any helpful documentation on this issue. Can anyone help?

Thanks!!

# Answer
> 0 votes
Thanks for the responses everyone. I ended up getting so frustrated I uninstalled Aquia Dev Desktop and then re-installed a newer version of it. It seems to have solved the problem because I haven't run into this issue since.

# Answer
> 0 votes
We're having this same problem with Dev Desktop 2 beta. In the my.cnf that comes with dev desktop, the socket line is as follows...

\[mysql\] socket="/Applications/Dev Desktop/mysql/data/mysql.sock"

Which one is correct? The one Drupal is trying to use, or the one dev desktop is trying to assign?

We tried adding a line under \[mysqld\] for socket = /tmp/mysql.sock but nothing changed.

---
Tags: 7, database
---


# Question
Title: Views slideshow - 3 items per slide - how to center them?
I've been trawling the web on and off for months searching for an answer to the following:

I'm using Views Slideshow to show a series of logos in rotation. I have set there to be 3 items per slide in the slideshow settings. What I would like is for the three logos to be centred - i.e. an equal amount of space to either side of the logos. At the moment, they float left and I cannot for the life of me find the right CSS to do this, or where to add it.

I would really appreciate it if someone from the community could take a glance at the logo slideshow at the following url:

http://eunic-global.aptalops.com/

Please note that's it's the **rotating logo carousel at the bottom of the page** I'm having trouble with, **not the slider under the main menu**.

Best wishes, A~

# Answer
#views\_slideshow\_cycle\_teaser\_section\_eunic\_members-block { margin: 0 auto; }
> -1 votes

---
Tags: theming, views
---


# Question
Title: Drupal Hook_Mail_Alter Custom Template fields
We have a Drupal 6 contact us Webform with e-mail. There is a custom template with the following fields: Facility: %value\[facility\] First Name: %value\[first\_name\] Last Name: %value\[last\_name\] Email: %value\[email\_address\] Phone: %value\[phone\_number\] I wish to be contacted: %value\[contact\_user\] Subject: %value\[subject\] Comments: %value\[comments\] The results of this submission may be viewed at: %submission\_url

I want to access both the subject and the facility field. I'm not sure my keys are correct using "headers". Is this the correct way to access both the subject and facility fields?

Here is my code in the custom module test:

```
test_mail_alter(&$message)
{

    if (($message['id'] == 'contact_us'))
    {
        $mail_listing = array();

        // pick up subject e-mails
        $subject = str_replace(' ','',$message['headers']['subject']);
        $subject_listing = explode(',',$subject);
        foreach ($subject_listing as $s){

            if (preg_match('/[a-zA-Z0-9_-.+]+@[a-zA-Z0-9-]+.[a-zA-Z]+/',$s)){
                array_push($mail_listing,$s);
            }

        }

        // pick up facility if it exists and combine it with the subject listing
        $facility = str_replace(' ','',$message['headers']['facility']);
        $facility_listing = explode(',',$facility);
        foreach ($facility_listing as $f){

            if (preg_match('/[a-zA-Z0-9_-.+]+@[a-zA-Z0-9-]+.[a-zA-Z]+/',$f)){
                array_push($mail_listing,$f);
            }

        }

        $message['headers']['to'] = implode(',',$mail_listing);
    }
}

```

# Answer
In Drupal 6, you can specify further settings:

* Navigate to the Contact Form settings page (http://example.com/admin/build/contact/settings)
* In the "Additional Information" section, enter the text to display with the contact form.
* In the "Hourly Threshold" list, select the maximum number of submissions that a user can make per hour.
> -1 votes

---
Tags: hooks, emails
---


title: Adding Social counter

text:
# Question
Title: Adding Social counter
i need to show in my site the social media counter like Facebook fans count ...

its some thing like :-

# Answer
Share count statistics

> Allows your Drupal site to gather statistics on how many times your content (and other entity types) have been "shared" with social/sharing services like Twitter, Google+, Facebook, etc. Also provides an API for other modules to hook into and provide their own share counts.

Social Stats

> This is a statistics module. It provides data from various social media sites. The data which is saved per node. It includes data from:
>
> 1. Facebook : likes count, shares count, comments count & total count.
> 2. Twitter : tweets count.
> 3. LinkedIn : share count.
> 4. Google Plus : plus one count, share count & total count
> 5. Total Share Count : total across all available social networks
> 1 votes

---
Tags: 7
---


# Question
Title: How to use ctools_ajax_command_redirect with $_GET parameters
Is it possible to use ctools\_ajax\_command\_redirect with $\_GET Parameters ? I am only able to redirect it to an absolute path as of now ..

# Answer
> 1 votes
I finally figured it

Following is the sample usage with POST param param1 with value as value1

```
ctools_ajax_command_redirect('url_path_without_base_url',0,array('query'=>array('param1'=>'value1')));

```

---
Tags: 7, chaos-tool-suite
---


# Question
Title: Using Entity Registration, how can I create a view that shows all the events that a user has NOT registered for?
Using the Entity Registration module's built-in Views integration, I was easily able to create a view showing the events that the logged-in user has registered as attending.

Content type: Event Date field Registration field

I created a view of **registrations** with a relationship of **registration to node**.

Now, however, I would like to create a list of the content type **event** but only show those events for which the logged-in user has not registered.

I can add a relationship **node to registration**, but I don't know how to structure the filter to remove the events for which the logged-in user has registered.

# Answer
> 2 votes
I'm afraid it will be hard.

Seems like you are looking for something like this feature \- sadly, it is not implemented (yet?). Problem is, SQL does not support anti-joins in any reliable generic way, so most of generic solutions built on top of SQL databases can't do it, either. Materials I used to code similar case (or similar ones) are still to be found under this search: http://google.pl/search?q=sql+anti-join

Maybe there is a way to create view like that. If you only want it to work when view is filtered by one user, you could implement `hook_query_alter()`. Use `->hasTag()` to determine if query came from the view you want to alter, and then `->conditions()` to make sure it shows results for just one user (to avoid things getting messy). Then you can outer join appropriate table and (if it's our usual many-to-many intermediate table), only select rows where registration entry `->isNull()`.

---
Tags: views
---


# Question
Title: How can I give permission to authenticated users to edit the content type 'ABC'?
we have view and edit tab for any content
How can I have such a view and edit tab for authenticated user ?
I have given the following permissions to content of type 'ABC'
\- Create own content
\- Create new content
\- Edit own content
\- Edit any content
\- Delete own content
\- Delete any content
\- View published content
But still the authenticated user cannot edit the content of type 'ABC'?
How can I achieve it?

When I try to access node/205/edit page as an authenticated user

I get the access denied message

DNA image

# Answer
> 1 votes
Use Devel module, especially it's Node Acces tool:

> Devel Node Access (DNA)
>
> View the node access entries for the node(s) that are shown on a page. Essential for developers of node access modules and useful for site admins in debugging problems with those modules.

It will tell you exactly what permission is missing.

To debug for particular existing user, consider adding Masquerade to the mix:

> The masquerade module is designed as a tool for site designers and site administrators. It allows a user with the right permissions to switch users.

That way you will be able to see DNA report just as the exact user who encountered problem.

What you should see is 2 lists:

**If these look about right**

Go to *Home ⏩ Administration ⏩ Configuration ⏩ Content authoring* and make sure your user has the proper text format permissions:

---
Tags: 7, users
---


# Question
Title: Reorder the Basic page list in views .How?
I have created views to display basic pages in blocks.I what to reorder the list according to me .How to do?Plz help......

# Answer
In Drupal 7 you use **VIEWS SORT CRITERIA**

* If you want to sort based of **Content: Post date** OR **Content: Updated date** just use these fields in **VIEWS SORT CRITERIA**.
* If you want to sort based on your requirement then, just add one more extra field to basic page like weight.
* Edit your VIEW and just add this field in the **Views SORT CRITERIA** and sort is as per your requirement.
> 0 votes

---
Tags: views
---


# Question
Title: How to restrict particular user roles from Adding child pages to the particular books only.
I am using drupal 7. I want to restrict some users from adding book pages to the books.

I have several books on my site and each book has different authors. As i have given add book pages access to authors any author can add book pages to any book which i dont want.

I just needed to give add book pages access to each author bookwise. Is there any module available for this i am already using book access for editing the content but i didnt find for adding content restriction.

# Answer
All node access modules, including Book access, are whitelist only.

> Node access modules always GRANT access and never restrict it. (It is a whitelisting rather than a blacklisting system.) If you use two node access modules and one grants access while another does not, access is granted. Exceptions are the Deny access module, as well as the old Module Grants module through which it is possible to combine access grants across multiple modules in a more intuitive way. Without it, the displayed behaviour may appear backwards from what most people would assume, and it's the reason why it is tricky to get involved with multiple node access modules. It is possible to use multiple node access modules in harmony however if for example they are applied to different content types or are giving out different grant types.

This means **you need to deny access to books, generally, and then use Book access to grant it per book.** If you grant it via Drupal settings, you will grant it to all books, and grants are additive - so some people would be allowed, and some would be "doubly allowed", and no one will be denied.
> 0 votes

---
Tags: users, nodes
---


# Question
Title: How do I show a term's node count in grid format?
I've been looking around for instructions on how to show the node count for taxonomy terms, and, while I did find instructions on Views and node count for taxonomy terms, it wasn't exactly what I need. The terms and their counts do show up next to each other quite nicely (Ex: Term A(13), Term B(2), Term C(17), etc.). However, they only show up as an unformatted list.

I need them in a grid form. Although I did play with the settings for quite a while, I wasn't able to get it work, and didn't find anything else on the web that fixed the problem.

Any advice would be much appreciated!

# Answer
If you import the view proposed in that answer, you will get a table with 2 columns: term name on the left, number of nodes on the right. That's a block, not a page, but that's a good start for your needs, IMHO.

Read this to learn how to import views.
> 0 votes

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


# Question
Title: How can I use jCarousel with swipe event in drupal for touch screen?
In my project, I used the jCarousel module and View slideshow module for my items.When I tested with mobile devices,I saw there is a problem for navigation. I can't scroll well . So I would like to add some script for this problem.I already added some script for My View SLide Show from this website (https://gist.github.com/eristoddle/5011106). Fortunately , it works well with View Slideshow but it not works with jCarousel. I need to know which script is appropriate with my problem. Please let me know how can I do? Thanks in advanced.

# Answer
> 2 votes
You can use

On swipe you can trigger left and right navigation event.

Reference:

---
Tags: javascript
---


title: Change commerce price

text:
# Question
Title: Change commerce price
I've setup another commerce price field which I want to use instead of 'default' commerce\_price field (under certain conditions). **hook\_commerce\_product\_calculate\_sell\_price\_line\_item\_alter()** does the job on full product page but it doesn't work 'globally'. In shopping cart / order page price goes back to default commerce\_price field. Actually it's acting strange because when I add product to the shopping cart it shows amended price but it goes back to default price once page is refreshed...

p.s. I can't use Rules to change price.

# Answer
Unfortunately using rules is the only option to dynamically alter a product's price in Commerce 1.x. From the 2.0 roadmap:

> In Commerce 2.x, we should ensure that our modules define robust internal APIs that are then used by forms, Rules actions, etc. as opposed to embedding functionality into these systems' related callbacks. Most notably, we should seek to make price manipulation and price component management much easier as we open up the sell price calculation process to direct manipulation in module code **(as opposed to strictly using Rules)** when sell price pre-calculation is disabled.

emphasis mine.
> 2 votes

# Answer
For those people who don't want to use rules and hope to alter the price directly. Here is my solution:

```
//alter the price in list and single product page
function my_module_commerce_product_calculate_sell_price_line_item_alter($line_item){

    $price = 100; //1 dollar
    $line_item->commerce_unit_price[LANGUAGE_NONE]['0']['amount']=$price;

}

//alter the price in cart & order
function my_module_commerce_cart_line_item_refresh($line_item, $order_wrapper){

    $price = 100; //1 dollar
    $line_item->commerce_unit_price[LANGUAGE_NONE]['0']['amount']=$price;
    $line_item->commerce_unit_price[LANGUAGE_NONE]['0']['data']['components']['0']['price']['amount']=$price; //alter the base_price component

}

```
> 1 votes

# Answer
I've ended up amending quite few functions to get desired price change. Also use Domain access module. Example code :

```

function custom_module_commerce_product_calculate_sell_price_line_item_alter($line_item) {
  global $user;

  $oryginal_price = $line_item->commerce_unit_price['und'][0]['amount'];

  $product_id = $line_item->commerce_product['und'][0]['product_id'];

  $website = $_SERVER['SERVER_NAME'];

  if($website == 'website2.local') {
      $val = 5000;
  }
  elseif($website == 'website1.local') {
      $table = 'field_data_field_price_nnd';
      $price_field = 'field_price_nnd_amount';
  }
  else {
      return;
  }

  if($val)
    $line_item->commerce_unit_price['und'][0]['amount'] = $val;
}

type == 'product') {

  $product_id = $line_item->commerce_product['und'][0]['product_id'];

  $website = $_SERVER['SERVER_NAME'];

  if($website == 'website2.local') {
      $val = 5000;
  }
  elseif($website == 'website1.local') {
      $table = 'field_data_field_price_nnd';
      $price_field = 'field_price_nnd_amount';

  }
  else {
      return;
  }

  if($val) {
    $price = $val;

  if($line_item->commerce_unit_price[LANGUAGE_NONE][0]['data']['components'][1]['price']['amount']) {
      $price = $val + $line_item->commerce_unit_price[LANGUAGE_NONE][0]['data']['components'][1]['price']['amount'];
  }

  $qty = $line_item->quantity;
  $line_item->commerce_unit_price[LANGUAGE_NONE][0]['data']['components'][0]['price']['amount'] = $price;
  $line_item->commerce_unit_price[LANGUAGE_NONE][0]['amount'] = $price;
  $line_item->commerce_total[LANGUAGE_NONE][0]['data']['components'][0]['price']['amount'] = $qty*$price;
  $line_item->commerce_total[LANGUAGE_NONE][0]['amount'] = $qty*$price;
  commerce_line_item_save($line_item);
  entity_get_controller('commerce_line_item')->resetCache(array($line_item->line_item_id));

   }
 }
}

function custom_module_commerce_product_calculate_sell_price_line_item_alter($line_item) {
  global $user;

  $oryginal_price = $line_item->commerce_unit_price['und'][0]['amount'];

  $product_id = $line_item->commerce_product['und'][0]['product_id'];

  $website = $_SERVER['SERVER_NAME'];

  if($website == 'website2.local') {

      $val = 5000;
  }
  elseif($website == 'website1.local') {
      $table = 'field_data_field_price_nnd';
      $price_field = 'field_price_nnd_amount';
  }
  else {
      return;
  }

  if($val)
    $line_item->commerce_unit_price['und'][0]['amount'] = $val;
  // Reference the current shopping cart order in the line item if it isn't set.

}

```
> 1 votes

---
Tags: commerce
---


# Question
Title: Drupal_goto => POST $result as node Title
In order to be able to add a new node whenever a searched string is not found, I've added the following code in my theme directory as search-results.tpl.php.

```
<?php if ($search_results): ?>
  <h2><?php print t('Search results');?></h2>
  <ol class="search-results <?php print $module; ?>-results">
    <?php print $search_results; ?>
  </ol>
  <?php print $pager; ?>
<?php else: ?>
  <?php drupal_goto('node/add'); ?>
<?php endif; ?>

```

After clearing the cache, this works fine.

Is it possible to POST the searched string to the node/add section? For example, if I am looking for "car" and the string is not found, I should be redirected to node/add with "car" showed as node title.

# Answer
You add this line before your code:

`$search_term = arg(2);`

Send it in your drupal\_goto, but you need to specify which content type to add (here i chose "article"):

`<?php drupal_goto('node/add/article', array('query'=>array('title'=>$search_term))); ?>`

And hook your node form in a custom module (here I chose content type "Article") :

```
function MY_MODULE_form_node_form_alter(&$form, &$form_state, $form_id) {
  // Find the content type of the node we are editing.
  $content_type = $form['#node']->type;
  if ($content_type == 'article') {
    if(isset($_GET['title'])){
      $form['title']['#default_value'] = $_GET['title'];
    }
  }
}

```
> 2 votes

# Answer
There's a module for that: Prepopulate.

Well, actually this module will only handle the link, prepopulating the fields you declare in the link. So you will not have to alter any form, but you will still have to prepare the correct link with drupal\_goto().
> 0 votes

---
Tags: nodes
---


title: How to minify Javascript in D7

text:
# Question
Title: How to minify Javascript in D7
I'm on rackspace's cloud sites service, so I can't modify my server environment. I'm also running Drupal 7. I've spent the last couple days looking for a way to minify JS in Drupal 7 and it is my conclusion that one does not exist yet. Am I wrong? Or do I need to wait for a D7 release of http://drupal.org/project/advagg?

# Answer
You can use Minify module to do the same. Minify module minify the JavaScript using Google compiler. It also works with "Aggregate JavaScript files" so you can also get advantage of combining multiple JavaScript files which is default option in Drupal 7.

Minify module also minify HTML.
> 2 votes

# Answer
> List of modules in D7 that might provide similar functionality.
> http://drupal.org/project/core\_library
> http://drupal.org/project/agrcache

It is what reported in the project page for Advanced CSS/JS Aggregation, which is where your link takes to.
> 3 votes

---
Tags: javascript, css-js-aggregation
---


title: Why AJAX does not change field's value?

text:
# Question
Title: Why AJAX does not change field's value?
I wrote simple code:

```
function rah_cc_generate_form($form,$form_state){
    $form=array();

    $form['gen']=array(
        '#type' => 'fieldset',
        '#name' =>t('generate gift card code'),
        '#collapsible' => TRUE,
        '#collapsed' => false,
//        '#weight' => 5,

    );
    $form['gen']['code']=array(
            '#type' => 'textfield',
            '#title' => t('gift code'),
            //'#default_value' => '',
            '#prefix' => '<div id="gc-code">',
            '#suffix' => '</div>',
            '#size' => variable_get('rah_gc_code_size', 8),
            '#maxlength' => 20,
            //'#required' => TRUE,
    );
    $form['gen']['price']=array(
            '#type' => 'textfield',
            '#title' => t('price'),
            '#default_value' => 10000,
            '#size' => 10,
            '#maxlength' => 20,
            '#required' => TRUE,
    );

    $form['gen']['random']=array(
     '#type' => 'submit',
    '#value' => t('generate'),
    '#description' => t("if you want generate random use this plz"),
    //'#weight' => 1,
    //'#submit' => array('rah_cc_generate_random'), // If no javascript action.
    '#ajax' => array(
      'callback' => 'rah_cc_generate_ajax',
      'wrapper' => 'gc-code',
      'method' => 'replace',
      'effect' => 'fade',
      ),
   );

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

    return $form;

}
function rah_cc_generate_ajax(&$form,&$form_state){

    $form['gen']['code']['#value']=33;
  return $form['gen']['code'];

}

```

but it doesn't work: textfield is not replaced by the one that has value 33.

There is no JS error and AJAX request returns HTTP code 200.

# Answer
> 4 votes
There are several problems with your code:

1. Your AJAX callback should return a form element. Now it returns plain `33`.
2. All changes should be made inside form building function, in your case `rah_cc_generate_form`. Simply add condition to test `$form_state['triggering_element']` and perform action if it was your AJAX trigger. Do not alter things in AJAX handler, it's not what it is for. I know it's counter-intuitive, but that's the way it is.
3. Changing default value once there is some user input will have no effect. Maybe you should try to change appropriate entry in `$form_state['input']`? But that depends on your intentions.

---
Tags: forms, ajax
---


# Question
Title: Why Drupal changes the module (system table) bootstrap value after i set it with an SQL query?
I need to run some hooks very early in the boostrap like enhanced\_page\_cache does.

I copied the same hook\_update to set my module as available in Drupal bootstrap and alter its weight.

```
/**
 * Ensure the weight of the module is pretty high.
 */
 function MYMODULE_update_7000() {
   // Make sure this module is available on bootstrap.
   db_update('system')
    ->fields(array('bootstrap' => 1, 'weight' => 98))
    ->condition('type', 'module')
    ->condition('name', 'MYMODULE')
    ->execute();
  }

```

After the update the values are there, but if the caches are cleared, the module's bootstrap value on system table reverts back to 0.

Why is this happening?

How does the Enhanced\_page\_cache module does it and keeps the value intact?

Do i forget something?

Thanks

# Answer
> 1 votes
ok got it,

in system.module there is a function called `_system_update_bootstrap_status()`

this function changes bootstrap value to '1' for all modules that implement one (or more) of the hooks: 'boot', 'exit', 'watchdog', 'language\_init'

so i just needed to implement an empty hook\_boot() and my module is present in bootstrap.

---
Tags: 7, hooks, bootstrapping, updating
---


title: How to bring a third-party content?

text:
# Question
Title: How to bring a third-party content?
Drupal 7. There is a service, there will send the request, it returns an xml. With the handler present in human readable form. We bring a response variable. How to display the value of this variable on the page? I created a page with hook\_menu:

```
function mymodule_menu() {
  $items = array();
  $items['serch'] = array(
    'title' => 'Result',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_proc'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function mymodule_proc($parms){

}

```

In the FORM API I have not found a suitable element. If use it hook\_page\_alter, I don't know how apply to the content?

```
$page['content']['system_main']['pager']
$page['content']
$page['content']['system_main']

```

or something else....

# Answer
> 0 votes
You can use the #markup property to display arbitrary data.

The function signature for your drupal\_get\_form callbacks must be:

```
function mymodule_proc($form, $form_state) {}

```

Concerning the response object that you want to render, I would need more information in order to help you.

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


# Question
Title: How to remove the size attributes of all fields?
Size attributes just get in the way of responsive forms, and I realize most form fields can be overridden by CSS, but field types like input\[type="file"\] still do not behave well if a size attribute is set.

See this JSFiddle example.

Since field elements are classed out well, I'd much rather purely rely on CSS for field sizes. So, how can size attributes be removed from all fields?

# Answer
> 5 votes
For text fields the size attribute is forcibly added in `theme_textfield()`, so the only way would be to override that function in your theme and remove that bit of code:

```
function mytheme_textfield($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'text';

  // 'size' removed from this call
  element_set_attributes($element, array('id', 'name', 'value', 'maxlength'));

  // add the rest of the function...

```

Exactly the same thing goes for the file element (see `theme_file()`), and most likely for any other element type you need to do do this for.

# Answer
> 2 votes
You could do it with jQuery on the browser side like this, too:

```
$('input').removeAttr('size');

```

# Answer
> 0 votes
`input[type="file"]` does not have size attribute, see http://www.w3schools.com/tags/att\_input\_size.asp

For D6, just add next lines to `template.php` (copied from `includes/form.inc` and removed size):

```
function phptemplate_file($element) {
    _form_set_class($element, array('form-file'));
    return theme('form_element', $element, '<input type="file" name="'. $element['#name']
        .'"'. ($element['#attributes'] ? ' '. drupal_attributes($element['#attributes']) : '')
        .' id="'. $element['#id'] ."\" />\n");
}

```

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


title: add is null condtion in db_update

text:
# Question
Title: add is null condtion in db_update
I want to use db\_update with condition that a specify field is null ,how can I do it?

something like

```
->condition('used_date',  'isnull','=')

```

is this correct ,if not,what is the correct condition ?

# Answer
As per documentation, there is a method just for that: `->isNull()`

```
$query->isNull('myfield');
// Results in (myfield IS NULL)
$query->isNotNull('myfield');
// Results in (myfield IS NOT NULL)

```
> 4 votes

---
Tags: database
---


title: Secure webform inside non-secure page

text:
# Question
Title: Secure webform inside non-secure page
My Drupal 7 site uses both Webform and Secure Pages modules. I've created webform which is available as a block inserted to the bottom of another Drupal node. This node should be accessible using http protocol, but the submission of the form should be encrypted using https.

There is an option in the Secure pages (called "Secure forms") for entering form ID's, which should have https flag set to true. So I've enetered the form ID ("webform\_client\_form\_183") here and the result is, that the module generates correct form action (). But, when I submit the form (from let's say URL http://mysite.com/thepage), the form content isn't saved to the database and URL https://mysite.com/thepage is loaded to the browser instead. The form here is filled in with the data I've entered in previous step and submitting the form from https://mysite.com/thepage does finally the right thing and data are stored in the database.

What I should do to correctly submit (using https) the form from page located at http://... URL?

# Answer
You shouldn't really try. If form is served via HTTP, attacker already stolen your user's data using MiM attack to inject his own JS code into your site, so sending it via HTTPS is pointless at this moment.

If you need reliable security, always serve form using encryption. If you don't, don't waste resources on unneeded SSL processing.

See Transport Layer Protection Cheat Sheet for more details, as Clive suggested.
> 1 votes

---
Tags: webforms, ssl
---


title: How to theme webform component?

text:
# Question
Title: How to theme webform component?
I want to change the order of a webform component. This creation of a webform component:

```
$component = array(
      'name' => key($question_name),
      'form_key' => $key,
      'type' => $form_type,
      'mandatory' => 0,
      'weight' => $weight,
      'pid' => 0,
      'extra' => array(
          "items" => "1|1\n2|2\n3|3\n4|4",
          "multiple " => FALSE,
          "aslist" => FALSE,
          "description" => $question['description'],
        ),
);

```

Gives me the following display result:

1. Name of component
2. 1 - 4 radiobuttons
3. Descriptiontext

But I want to move the description text over the radiobuttons:

1. Name of component
2. Descriptiontext
3. 1 - 4 radiobuttons

How can I change the order of the output?

# Answer
What I was searching for was:

`function THEMENAME_webform_element($variables)`

https://drupal.org/node/1157306
> 0 votes

---
Tags: theming, forms, webforms
---


# Question
Title: Responsive/Fluid Views for Responsive/Fluid Website
I an creating a Responsive/Fluid website with Drupal. Everything is great, expect when I create a view with the view module, I cannot the view to become responsive/fluid like other images I have on the site.

What I have tried is to make the .views-field-field-images width 100%, which should make the image with in views responsive. However no luck!

Any help?

# Answer
Are you using a responsive base theme? If not, try a responsive theme like Omega. It is also possible that the order in which your CSS files being loaded, was set in a way that the base theme (assuming non responsive), overwrote what you have written. Make user that when you do drupal\_add\_css, you use proper weight and group value, to manage their load order.
> 0 votes

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


# Question
Title: is it good idea to add js file for every page?
I have some JS and CSS on my site that are very specific to some pages. From a Drupal perspective, it is good idea to add them using `drupal_add_js()` instead of `THEME.info`? Does such thing affect caching, or anything else Drupal-specific?

# Answer
This question is borderline one, it's one of these topics where art meets science of software development.

Either way, `drupal_add_js()` should be avoided. Always favour #attached property, and if possible, add libraries, not single JS files.

**For site-wide vs single page:** you probably have some kind of JS and CSS aggregation enabled. Using different sets of files is wasteful - it means that for every page your client needs to download another aggregated file. **Leaving the same set everywhere allows clients to use cached aggregated version** \- and this is (usually) the least time-consuming and least transfer-consuming way to go.

As Clive reminded, there are situations that are exceptional. Sometimes you need different versions of jQuery, or **conflicting sets of libraries**, and aggregating them can result in JS error, or create really big aggregated file. In situations like this you may not want to include all of them, or simply it might be impossible due to conflicts. Even then minimizing the number of "sets" is a good idea.

If you have a **really big script used only on one rarely used subpage**, some aggregation modules will allow you to exclude it from aggregation and always serve separately - a wise choice if you have 1kb of JS logic that you need in one place only, for example. **This part is an art of profiling, not really knowledge and recipes.**
> 7 votes

# Answer
This is a slightly complicated situation on a Drupal site, and it depends on whether you are using Javascript aggregation or not.

If you aren't, then the question isn't really Drupal specific. Each JS file will potentially result in a HTTP request, depending on cache headers and what your browser does. In general, you want to keep the number of requests low, and also try to transfer as few bytes as possible.

If you are using aggregation, then things get tricky. If you use per-page files, then you will have different aggregated files, which means that your users will end up making HTTP requests for them. In other words, this can defeat the effectiveness, somewhat, of file aggregation.

As with all things, proper profile on your site is the only way to tell whether it will make a difference for you.
> 4 votes

---
Tags: theming, javascript
---


# Question
Title: Display subscribe to group on access denied page
I am using Drupal 7.25 (I need to update to 7.26) and organic groups 7.x-2.4. I currently have public and private groups working. I have two users (admin and a normal user). I have a menu tab that opens the og list (/og-list) view which lists all groups (public and private).

When logged in as a normal user if I click on a public group it shows a subscribe to group link. That's great. However, if I click on a private group it gives me the Access denied page without a subscribe link.

I would like to have any normal user be able to click a private group and have it display a link to subscribe. Any help would be greatly appreciated!

# Answer
You have a couple of options.

Not sure how you have your group node page setup but what I have done is use a node view panel. In that panel I added the Field: Group (group\_group) in a region then set the formatter to "OG subscribe link". That will display the "Subscribe to group" link when a user clicks on the group they are not a member of. Since you are getting access denied I'm guessing your group node page is not setup that way.

Another option is to modify the og-list view and add the field "Content: Group". Then change its Formatter to "OG subscribe link". That will create a new column in the view that will display a link called "Subscribe to group" for groups you are not a member of and "Unsubscribe to group" for groups you are a member of.
> 0 votes

---
Tags: views, organic-groups
---


title: prevent submit in ajax call

text:
# Question
Title: prevent submit in ajax call
I have a form with 2 submit in it, one of them is a button to generate codes, everytimes I click on generate form\_submited called up and a record insert in db, how can I prevent form\_sumit in ajax triggering?

```
function rah_cc_generate_form($form,$form_state){
    $form=array();

    $form['gen']=array(
        '#type' => 'fieldset',
        '#name' =>t('generate gift card code'),
        '#collapsible' => TRUE,
        '#collapsed' => false,
//        '#weight' => 5,

    );
    $form['gen']['code']=array(
            '#type' => 'textfield',
            '#title' => t('gift code'),
            '#default_value' => '',
            '#prefix' => '<div id="gc-code">',
            '#suffix' => '</div>',
            '#size' => variable_get('rah_gc_code_size', 8),
            '#maxlength' => 20,
            //'#required' => TRUE,
    );
    $form['gen']['price']=array(
            '#type' => 'textfield',
            '#title' => t('price'),
            '#default_value' => 10000,
            '#size' => 10,
            '#maxlength' => 20,
            '#required' => TRUE,
    );
    $form['gen']['status'] = array(
  '#type' => 'checkbox',
  '#title' => t('status'),
    '#default_value' => 1,
);

    $form['gen']['random']=array(
     '#type' => 'submit',
    '#value' => t('generate'),
    '#description' => t("if you want generate random use this plz"),
    //'#weight' => 1,
    //'#submit' => array('rah_cc_generate_random'), // If no javascript action.
    '#ajax' => array(
      'callback' => 'rah_cc_generate_ajax',
      'wrapper' => 'gc-code',
      'method' => 'replace',
      'effect' => 'fade',
      ),
   );

    $form['gen']['save']=array(
        '#type' => 'submit',
        '#value' =>t('save'),
         );
    ym($form);
    return $form;

}
function rah_cc_generate_ajax(&$form,$form_state){

    //return $form['gen']['code']['#default_value']=33;
     $form['gen']['code']['#value']=rah_cc_generate();
     //$form_state['values']['code']['und'][0]['value']=44;
     return $form['gen']['code'];

}

```

**update** I use `'prevent'=> 'sumbit',` but not get answer :(

```
 $form['gen']['random']=array(
     '#type' => 'submit',
    '#value' => t('generate'),
    '#description' => t("if you want generate random use this plz"),
    //'#weight' => 1,
    //'#submit' => array('rah_cc_generate_random'), // If no javascript action.
    '#ajax' => array(
      'callback' => 'rah_cc_generate_ajax',
      'wrapper' => 'gc-code',
      'method' => 'replace',
      'effect' => 'fade',
      'prevent'=> 'sumbit',
      ),
   );

```

# Answer
$form\_state variable holds 'triggering\_element' element which indicates what button triggered (or also you can use #clicked\_button element), example (in ajax callback function):

```
function my_form_submit($form, &$form_state) {
  //dpm($form_state);
  if($form_state['triggering_element']['#value'] == 'MY_ELEMENT\'S_NAME') {
    //do_operation();
  }
}

```
> 6 votes

---
Tags: forms
---


# Question
Title: How to access field values from an entity reference field in a custom module?
I'm making a custom payment module for Commerce that references a Credit Card entity. I have the entity reference form field in there and working but I cannot pass on the selected Credit Card entity to the "message" field. If I could just print whatever the title of the entity reference they select, that would work, or if I could access one of the 5 fields in the entity itself, that would be ideal.

Here is my module: http://pastebin.com/373WDAzA and this is the error message I get:

> Warning: htmlspecialchars() expects parameter 1 to be string, array given in check\_plain() (line 1559 of C:\xampp\htdocs\includes\bootstrap.inc).

# Answer
> 0 votes
```
$form['card_on_file' ] = array(
  '#type' => 'entityreference',
  '#title' => t ('Credit Card'),
  '#era_entity_type' => 'node', // Mandatory
  '#era_bundles' => array(credit_card ), // Optional (Any bundle by default).
  '#era_cardinality' => 5, // Optional (1 By default).
  '#required' => TRUE,
) ;

```

the warning corresponds to this replace this code:

```
'#era_bundles' => array(credit_card ), // Optional (Any bundle by default).

```

with

```
'#era_bundles' => array('credit_card'),

```

Link: https://api.drupal.org/api/drupal/includes!common.inc/function/entity\_load/7

```
$ids = array();

```

get `$ids` from `$form_state['values']` of submit handler function.

use `entity_load('credit_card', $ids);`

# Answer
> 0 votes
Problem solved thanks to the #drupal-support IRC room. I did a `dpm($pane_values)` and saw that it was retrieving what I wanted, the Entity Label. I just changed the code so that it's

```
$pane_values['card_on_file'][0]['entity_label']

```

and presto!

---
Tags: commerce, entities
---


title: Colorbox images in grid

text:
# Question
Title: Colorbox images in grid
I installed colorbox module and I'm showing images as thumbnails. Each image is in on new line. Is it possible to set it that images will be in the grid similar as here?

I have exactly the same settings as here but don't see any settings to view images as grid, but I have a feeling I saw this somewhere else, but don't remember where.

thank you

# Answer
> 1 votes
You can use CSS rules to position the images like you want.

Another options would be to use views to display the images, which has built in support for displaying items in a grid.

If you want a more detailed answer, you should provide more info in your question.

# Answer
> -1 votes
This Drupal module is what solved my issue:

> The Grid Field Formatter module provides a simple way to override the display of multi-value fields to show as a grid/table with a certain number of columns.

---
Tags: 7, media
---


# Question
Title: Drop Tables After Backup Migrate Restore
I find myself using Backup and Migrate's Restore (from manual backups folder) when testing module sets or after a change to a project is problematic. I use Schema after the restore to check for extra tables left in the database during the restore process. Generally, orphaned extra tables that are no longer wanted, needed or an issue are tables from modules or entity/content type fields being prototyped/tested. Module tables left in the database cause PDO Exception errors if I attempt to reinstall same module or alternate dev version after a restore. Extra field tables can get quite numerous and chaotic when rapid prototyping.

**EXAMPLE** Match (107) Hide Extra (11) Tables in the database that are not present in the schema. This indicates previously installed modules that are disabled but not un-installed or modules that do not use the Schema API.

Schema report looks like:

* Match (107) Tables for which the schema and database agree.
* Extra () Tables in the database that are not present in the schema. This indicates previously installed modules that are disabled but not un-installed or modules that do not use the Schema API.

```
field_data_field_test_termsfruits   // fields for content types
field_data_field_test_code_and_api
field_data_field_test_drupal
field_revision_test_termsfruits
field_revision_test_terms_code_and_api
field_revision_test_terms_drupal
search_api_index                    // a module not being used
search_api_item
search_api_server
search_api_task

```

Seems that Backup and Migrate team is not ready to include drop tables options and the issue has been discussed in detail. I've also tried the Demonstration module which was great in D6 but just spits errors in D7 for me.

Aside from phpMyAdmin, MySQL GUI tools or command line to drop tables (and realizing security risk if permissions are compromised), what contributed modules or other PHP/API methods can I use from within the Drupal interface to drop specific tables?

# Answer
As far as the API goes there's `db_drop_table()`

```
db_drop_table('table_name');

```
> 0 votes

---
Tags: 7, entities, nodes, database, backups
---


title: Rebuild features on cache clear

text:
# Question
Title: Rebuild features on cache clear
I have a distro with many preinstalled features (Panopoly).

Since I have upgraded core to 7.24 I can see an additional setting at admin/structure/features/settings, see attachment.

On production, is it best to disable the "Rebuild features on cache clear"? This is active by default.

# Answer
Yes, it is best to disable this in production for the performance reasons mentioned.

I think the only times you would want to rebuild the feature list is when you are using the features and/or modules lists (as designed). Spending the resources to reload that when clearing cache for themeing purposes would be unnecessary.
> 5 votes

---
Tags: caching, features, distributions
---


# Question
Title: How to enable Views caching for all pages instead of only the first page?
**Problem**

I'm trying to cache my view (search specific). However doing so only caches a single page of results and stops me from changing pages either with the pager, or by manually changing the URL.

Has anyone else run into this problem? And if so how have you fixed it?

**Details & Thoughts**

The hyperlinks on the pager still look ok. It's just that using them only gives the first page of results so it seems to do nothing.

It seems like Drupal is only capable of caching a single page of results and then returns that for all queries.

For example: If I change the caching (signalling the cache needs to be rebuilt) then enter the URL for page 3 of views results, then it caches that instead of the first page and will only return that for all searches.

My Set-Up is:

* View Based On: Search API index.
* Caching: Search Specific | 1 Hour

And caching mechanism's I have running are:

* Memcached
* Authcache
* Varnish

I don't think it's related to Authcache. If I turn it off I get the same problem. (I presume view caching is separate and un-related to caching based on users. Also see the next point.)

I'm running Authcache Debug and it's telling me that it can't cache the view because of a client form token. (I have an exposed form on the views page which will block Authcache.)

# Answer
> 1 votes
While I haven't used a search view, I ran into a similar problem with pagers. Views caching has two parts out of the box, query and render. The render cache was interfering with the pager. I think setting the Views caching to Search Specific is setting both query and render in one swoop.

I would try changing it to Time Based and caching the query, but not the render. Varnish will then be able to correctly cache the various pages of the view.

---
Tags: 7, views, caching
---


# Question
Title: drupal add class to form-item if error on form to all forms
I just want to add class to .form-item if there is error on form i used the following code but its not working.

```
function semanticUI_form_element($variables) {
  if (isset($element['#parents']) && form_get_error($element)) {
    $attributes['class'][] = array('error1');
  }
  if(form_get_error($element)){
    $attributes['class'][] = array('error1');
  }

  if (!empty($element['#required'])) {
    $element['#attributes']['class'][] = 'test';
  }
}

```

Any help would be appreciated.

# Answer
If you copy the `theme_form_element()` function out of `includes/form.inc` and into your theme's `template.php` file, re-name it to match your theme, and change the initial setting of `$attributes['class']` accordingly:

```
  if (form_get_error($variables['element'])) {
    $attributes['class'] = array('form-item', 'da-error');
  } else {
    $attributes['class'] = array('form-item');
  }

```

...this will put a `da-error` class in the overall `<div>` wrapping this element.
> 2 votes

---
Tags: 7, theming
---


# Question
Title: Views Grouped Filters turns Radiobuttons into Select?
I have a grouped filter in a view with lets say 3 items. For the Widget i choose Radios and Allow multiple selections. For 3 Items everything works fine and i have some checkboxes. Wenn they are more then 3 items instead of checkboxes there is a select list! But i want to have checkboxes. Even Better Exposed Filters only shows select as an option for that filter. Whats wrong ?

# Answer
I came up with writing a simple hook:

```
 function  MY_MODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id)
  {
    if ($form['#id'] == 'MYFORMID') {
      $form['field_MY_VALUE_FIELD']['#theme'] = 'select_as_checkboxes';
    }
  }

```
> 1 votes

# Answer
The code that handle this conditional change between a multiselect and individual checkboxes is in `views_handler_filter.inc` in the function `group_form`:

```
    if (count($groups) < 5) {
      $form[$value]['#type'] = 'checkboxes';
    }
    else {
      $form[$value]['#type'] = 'select';
      $form[$value]['#size'] = 5;
      $form[$value]['#multiple'] = TRUE;
    }

```

Since it cannot be manipulated with any views options, the best way to handle this is to hook alter the form and just force it to always be checkboxes (or select if that's what you want).

This is suggested by the user "oll", but I don't see the need to change how the element is themed. You just need to change the type.
> 0 votes

# Answer
I have the same problem, but I can get up to four items. My workaround was to just add more grouped filters, making sure to use the OR grouping.
> -2 votes

---
Tags: views
---


# Question
Title: How do I add reCaptcha to a custom form?
I need to add a reCaptcha to my form; creating the form then adding the form ID to the reCaptcha settings did nothing.

# Answer
I added the following form item to my form.

```
$form['captcha'] = array(
  '#type' => 'captcha',
  '#captcha_type' => 'recaptcha/reCAPTCHA',
);

```

It's pretty simple but it may trip some others up so hopefully this post saves someone time.

If you want to use some other captcha method you have installed on your site you can easily replace #captcha\_type by going to /admin/config/people/captcha and using a tool like Firebug (or just view the page source and do some hunting) to view the options for the "Default challenge type" field on the captcha admin settings page. The values of each option is a valid option for the #captcha\_type.
> 9 votes

---
Tags: 7, forms, captcha
---


title: Why do I get a page without CSS styles?

text:
# Question
Title: Why do I get a page without CSS styles?
Why would the page at admin/people/permissions have very little information and appear like it doesn't have any CSS style applied?

>

# Answer
I have disabled the dev themer and all is better.
> 0 votes

---
Tags: theming
---


title: Sending HTML email with drupal_mail()

text:
# Question
Title: Sending HTML email with drupal_mail()
I'm trying to send HTML emails from a module and I'm using `drupal_mail()`.

It's not possible to send HTML email with just `drupal_mail()` (see here), and I've installed Mimemail. However, the email is still being stripped of all HTML tags.

Do I need to make any extra calls in the email template, or is there something else I've forgotten?

**Set-Up**

*Mail System*

* format() -- mimemail system
* mail() -- SMTP module

*Mimemail*

* Email Format: Filtered HTML (My filtered HTML allows `<p>` and `<br>` tags.
* Include all site stylesheets.

*SMTP module*

* Allow HTML formatted emails

drupal\_mail

```
tellafriend_mail($key, &$message, $params) {

  $message['headers']['MIME-Version'] = '1.0';
  $message['headers']['Content-Type'] = 'multipart/mixed;';
  $message['headers']['Content-Type'] = 'text/html;';
  $message['subject'] = t('This is a test email');

  $message['body'][] = t("This is a test email")."<p></p><p>".t("This should be a new paragraph.")."</p><p></p><p>".t("And a third paragraph.")."</p>";
  $message['params']['attachments'] = $params;
  }

```

# Answer
As it turns out HTML email was infact enabled. The problem was the stylesheets that the email was being bundled with.

If you head to `admin/config/system/mimemail` you can choose to either bundle the email with your website stylesheets, or set-up a mail.css in your default theme directory.

I suspect if you're using a sub-theme and haven't got mail.css it'll just use the original theme mail.css which is probably not what you want.
> 3 votes

---
Tags: 7, mimemail
---


# Question
Title: Can Entity Translate work on the node body?
**Problem**

I'm using Entity Translate for the multi-lingual parts of my site, this allows me to use the language switcher. (I've enabled it for content, and then on the content type I've enabled field translation).

However the node body is not translatable.

Do I need to create a field and use that as the body, or have I set-up entity translation badly?

# Answer
> 1 votes
Ah turns out you have to enable translation for the field once you've enabled translation for the content type.

Open up your content type, edit the field you want to make translatable then head down to the bottom of the page.

You should see something like:

**Field translation** Users may translate all occurrences of this field:

* *Body in Basic page*
* *Body in Article*
* *Body in Webform*
* *Body in Test Content*
* *Body in Upgrade & Search Token Product Display*
* *Body in Blog post/Article*
* *Body in Development Blog*

Click on "Enable translation" and you're good to go.

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


title: Drupal Database User 1 Permissions

text:
# Question
Title: Drupal Database User 1 Permissions
From the community documentation, create database permissions, the superuser/1 should have these permissions:

SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, LOCK TABLES, CREATE TEMPORARY TABLES

There is comment here about install.mysqt.txt that the docs may be incomplete or ambiguous. Also, my Cpanel configruation shows additional permission options that I am unfamiliar with as does the GUI program I am using for MySQL.

My question is, are there situations where modules for things like services, SOAP, REST, SPARQL, SSL, or other APIs and connecting technologies need to use the additional database permissions?

# Answer
Short answer: yes.

Long(er) answer: There are definitely modules that would make use of those MySQL permissions. Not to mention administrative functions like installing new modules, doing updates, etc.

'grant all' for your Drupal database user is the easiest/best way to do this. However, once a site is up and running, I would imagine that you could remove a LOT of those permissions.
> 0 votes

---
Tags: database, users
---


title: Dynamic Background based on field url

text:
# Question
Title: Dynamic Background based on field url
Lets say I have a music site that a user can add a youtube URL in a box and then the video will play.
Is it possible to have the background of that page change based on search parameters in the field.
So if a user puts in a Daft Punk video, could I have my site query a website with fan art and load the fan art as the background of that page?

EDIT: To elaborate more.

Popular media players (PLEX and XBMC) will often "srape" websites for information about tvshows, movies, and artists. They pull the content (biography, rating, fanart, etc.) from the different sites (imdb etc.) and display them in the media player.

I want to extend this functionality to my site.

Now this is where it could get complicated.

My website has an emfield that allows users to paste the URL's of different videos from youtube, vimeo and others that will display one video then create a playlist of the pending videos in the list.

Fortunately the emfield can also pull the artist and song title of the video from youtube. I want to use this information to then query a search on a website such as fanart.tv and pull an image or even corresponding artist information and display said information on my site as the corresponding song is playing.

In short:
1. URL is entered
2. Emfield displays video, artist, and song title
3. Somehow a search is performed on a website to locate that same artist and display fanart and other artist biography information
4. Listen and learn.

# Answer
> 0 votes
You can do this but its probably more of a jquery problem than a Drupal one since you're changing the background of the page based on an asynchronous web call. Rough idea of how this would look:

* attach an onsubmit handler to your form that would load the video from the url
* add your logic to find the artist from this url (?) and then find the appropriate image
* then modify the body background using this image, ex:

$('body').css('background-image', 'url(' + imageUrl + ')');

---
Tags: entities
---


# Question
Title: Views Refresh Results are Scrambled Syntax
On several beta builds recently that use Views, when I am configuring a new page or block view, when the results are refreshed manually or automatically I am getting a scramble of code/script/syntax garbage instead of a proper Drupal Views admin page with query results. I have a number of other modules installed and have been unable to determine where there might be a conflict and process of elimination has been more miss than hit. Returning to the main Views admin page and attempting to configure my primary view fine, and the rest of my beta site runs fine. Has anyone encountered view refresh/results during configuration that are just a scramble of syntax output? What solutions? Any known conflicts?

# Answer
Yes, I saw this problem recently on a Drupal 7 setup. The modules involved in my case were jQuery update + Calendar but the behaviour in views was the same. Setting jQuery update back to the default (I want to say it's 1.5, not sure) solved the issue with Views and Calendar for me.

Of course I needed jQuery 1.7 for a different purpose, so I had to change it back once the views were done and ready to be used. Not exactly ideal but it worked well enough. Everything functioned fine besides actually making changes to the views.

If you are using jQuery update give changing the jQuery version back a try.
> 0 votes

---
Tags: views
---


# Question
Title: How to programmatically print all comments from a given node?
I need to print comments belonging to a given node. So basically, get a node id then choose all the comments from a given node and print them. I know that I can print one comment (for example with id=12) using the following code:

```
<?php
$comment = _comment_load(12);
return theme('comment',$comment);
?>

```

Can anyone tell me how to do this?

# Answer
> 6 votes
If you are looking for a ready to use function, take a look at comment\_render().

Example use (say the node you want comments for has nid = 5):

```
<?php
  $node = node_load(5);
 print comment_render($node);
?>

```

Or else you can manually query the database (comments table) to get all comments that have a matching nid.

```
<?php
  $nid = 5;
  db_query('SELECT * FROM {comments} WHERE nid = %d', $nid);
?>

```

# Answer
> 3 votes
If you like to load the complete comment objects you can use this:

```
$result = db_select('comment')
  ->fields('comment', array('cid'))
  ->condition('nid', $node->nid, '=')
  ->execute();

$cids = $result->fetchCol();
$comments=comment_load_multiple($cids);

foreach($comments as $comment) {
  //do some stuff with the comment
  print $comment->comment_body ["und"][0] ["value"];
}

```

# Answer
> 1 votes
In Drupal 7 and onwards `comment_render` has been removed. Instead, you can load comments like this.

```
$result = db_select('comment')
                  ->fields('comment', array('name','subject'))
                  ->condition('nid', $node->nid, '=')
                  ->execute()
                  ->fetchAssoc();
foreach($result as $comment) {
   print $comment;
 }

```

---
Tags: 6, nodes, comments
---


title: Exposed Views 2 filter for path alias

text:
# Question
Title: Exposed Views 2 filter for path alias
I am surprised that I am not able to find an existing Views 2 filter for aliases (paths). Seems to be such a basic property to filter results by.

I know Views can filter by argument but I need it as an exposed filter.

Does anybody know of an existing module that does it -- or at least a snippet of code that would build such a filter?

# Answer
Views Path Filter might be what you're looking for. It lets you filter nodes by paths in a views filter. I don't know how well it works with exposed filters though.
> 1 votes

# Answer
Pathauto has a filter it uses with its admin page @ /admin/config/search/path. You might be able to repurpose its code with a custom views filter.
> 0 votes

---
Tags: 7, path-aliases, views
---


title: Managing Abusive/Report User

text:
# Question
Title: Managing Abusive/Report User
I have setup flags so a user can report another user as abusive/offensive. I need a way to manage to flags. I would like to be able the view all the users that have been flagged and and remove the flags. I have tried to do this with views but I could not find a way to remove the flag.

# Answer
Look at the answer in this question: Flag module views integration

It seems to be possible with relationships, though I would guess that this depends a little on your flag configuration.
> 0 votes

---
Tags: views, users, flags
---


# Question
Title: Help with a db_select() not returning results when it *should*
I'm having trouble figuring out why the `db_select()` is not returning any results. Long story short, if I pass the results of `$results->execute()` through a `foreach ($results as $result)`, I don't get any results. If I take the generated SQL and go directly to command line or phpMyAdmin (substituting manually for the placeholders) I get the expected result. I feel like I have to just be overlooking something - I'm hoping fresh eyes can point it out for me.

Here is the select:

```
$results = db_select('product_charges_override', 'pc');
$results->join('products', 'p', 'p.product_id = pc.product_id');
$results->fields('pc', array('uid', 'product_id', 'override_count', 'redemption_count', 'coupon_code'))
  ->fields('p', array('human_name'))
  ->condition('pc.coupon_code', $coupon_code);
$results->execute();

```

Here is the result of `dpq($results)`:

```
SELECT pc.uid AS uid, pc.product_id AS product_id, pc.override_count AS override_count, pc.redemption_count AS redemption_count, pc.coupon_code AS coupon_code, p.human_name AS human_name FROM {product_charges_override} pc INNER JOIN {products} p ON p.product_id = pc.product_id WHERE (pc.coupon_code = :db_condition_placeholder_0)

```

Here is the relevant Where statement from just `var_dump($results)`:

```
protected 'where' =>
  object(DatabaseCondition)[136]
    protected 'conditions' =>
      array
        '#conjunction' => string 'AND' (length=3)
        0 =>
          array
            'field' => string 'pc.coupon_code' (length=14)
            'value' => string 'ugd2pl8z92j9' (length=12)
            'operator' => string '=' (length=1)
    protected 'arguments' =>
      array
        ':db_condition_placeholder_0' => string 'ugd2pl8z92j9' (length=12)
    protected 'changed' => boolean false
    protected 'queryPlaceholderIdentifier' => string '52e7fdf78bbd25.63959182' (length=23)
    public 'stringVersion' => string ' (pc.coupon_code = :db_condition_placeholder_0) ' (length=48)

```

And, finally, the query as I run it from the command line (notice the '{' and '}' have been removed, as well as the placeholder replaced with the value from the 'where' object). Those are the **only** things I replaced from the results of `dpq()`.

```
SELECT pc.uid AS uid, pc.product_id AS product_id, pc.override_count AS override_count, pc.redemption_count AS redemption_count, p.human_name AS human_name FROM product_charges_override pc INNER JOIN products p ON p.product_id = pc.product_id WHERE (pc.coupon_code = 'ugd2pl8z92j9')

```

And an export from phpMyAdmin of the query results:

```
/**
 * Export to PHP Array plugin for PHPMyAdmin
 * @author Geoffray Warnants
 * @version 0.2b
 */

 //
 // Database "mats_theme"
 //

 // mats_theme.product_charges_override
 $product_charges_override = array(
       array('uid'=>null,'product_id'=>7,'override_count'=>5,'redemption_count'=>0,'human_name'=>'Fleet Forum Registration')
);

```

# Answer
> 0 votes
I'm not assigning `$results->execute()` to anything - that's why I can't iterate over the results. Answer was provided by a local mailing list that I sent this link to.

So, solution is `$results = $results->execute()`. Of course, the query should be renamed to something like, `$query`;

---
Tags: database
---


# Question
Title: 'Any' result set for Exposed Filter w/ limited list is not limited
I have an exposed filter for a taxonomy vocabulary. The filter settings are

* **Single Filter**
* *Operator:* **Is one of**
* *Limit list to selected items:* **On**
* *Selected vocabulary terms:* a subset of the full, flat (non-hierarchal) vocabulary
    + Assume selected terms `term1`, `term2`, `term3`
    + Assume non selected terms `non1`, `non2`, `non3`

The filters UI appears and is accurate, and it is functional when a filter is selected. However, when the `- Any -` option is selected, all objects from the vocabulary are displayed - all of the `term#` objects are displayed along with the `non#` objects.

I've tried adding a second (non-exposed) filter that does `is one of` for each of the `term#` terms. With this, the `- Any -` option is correct but none of the other selected filters in the drop down work.

**How do I get only the selected `term#` elements to show when the `- Any -` option is selected?**

# Answer
> 1 votes
For the second non-exposed filter change the operator to `is none of`and assign the terms accordingly (inverse to what you have now). If not otherwhise specified filters in views are `AND` filters.

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


# Question
Title: Block wrapping DIV disable with theme hook?
I've managed to suppress the wrapping markup for a few blocks using

block--block--1.tpl.php region--banner.tpl.php

but now it's getting messy as I have several blocks which require no additional wrpaping markup so I would ideally like to do this in a theme function with a switch case...but can't find any example that works...

function front\_preprocess\_block(&$vars, $hook) {

```
$to_delete = array('block-block-4');

//if(in_array($vars['block']->delta , $to_delete)) {
//  $vars['template_files'][0] = 'block-empty';
//}

print_r($vars);

```

}

I need to remove wrppaing DIV's for about 4 blocks onlys...ideas???

# Answer
> 1 votes
You can specify an additional variable in `hook_preprocess_block()` and check for that variable in `block.tpl.php file`, example:

```
function front_preprocess_block(&$vars, $hook) {
  //dpm($vars);
  $vars['must_be_removed'] = FALSE;
  if(/* CONDITION e.g. $vars['elements']['#block']->delta == 'MY_BLOCK_DELTA' */) {
    $vars['must_be_removed'] = TRUE;
  }
}

```

and `block.tpl.php` file;

```
<?php if($must_be_removed): ?>
  <?php print $content ?>
<?php else: ?>
<div id="<?php print $block_html_id; ?>" class="<?php print $classes; ?>"<?php print $attributes; ?>>

  <?php print render($title_prefix); ?>
<?php if ($block->subject): ?>
  <h2<?php print $title_attributes; ?>><span><?php print $block->subject ?></span></h2>
<?php endif;?>
  <?php print render($title_suffix); ?>

  <div class="content"<?php print $content_attributes; ?>>
    <?php print $content ?>
  </div>
</div>
<?php endif; ?>

```

---
Tags: theming, hooks
---


# Question
Title: Appending a hidden input value to a textarea value?
So basically what I need to do is append a hidden input value to the text-area without overriding the original texarea value on submit. What am I doing wrong? This is in the template.tpl file.

```
function hook_form_alter(&$form, &$form_state, $form_id) {
     if($form_id){
         $sCampaign = $form['submitted']['campaignstring']['#value'];//hidden value
         $sComments = $form['submitted']['Comments']['#value'];//comments textarea
         $sComments = $sCampaign."-".$sComments; // Appending them.

    }

}

```

I also tried:

```
function hook_form_alter(&$form, &$form_state, $form_id) {
         if($form_id){
             $form['#submit'][] = 'submit_string';
           }
    }

function submit_string($form, &$form_state){
    $sCampaign = $form['submitted']['campaignstring']['#value'];
    $sComments = $form['submitted']['Comments']['#value'];
    $sComments = $sCampaign."-".$sComments;

}

```

Newer try:

```
function THEME_form_alter(&$form, &$form_state, $form_id) {
//Appending Campaign String to comments
$form['submitted']['Comments']['#value'] = array('#value' => $form['submitted']['Comments']['#default_value'] .'/'. $form['submitted']['campaignstring']['#value'],
                );
}

function submitHandler($form, &$form_state){
    $campaingString = $form_state['values']['campaignstring'];
    $comments = $form_state['values']['Comments'];
    $comments = $comments."/////".$campaingString;

    drupal_set_message('Submitted');
    drupal_set_message($form_state['values']);
}

```

# Answer
Here is a little example (Additional information):

```
function my_form($form, &$form_state) {
  $form['name'] = array(
    '#title' > 'Name',
    '#type' => 'textfield'
  );

  $form['sec_name'] = array(
    '#title' > 'last name',
    '#type' => 'textfield'
  );

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

  return $form;
}

function my_form_submit($form, &$form_state) {
  $f_name = $form_state['values']['name'];
  $s_name = $form_state['values']['sec_name'];

  drupal_set_message('Hello ' . $f_name . ' ' . $s_name);
}

```
> 1 votes

# Answer
```
function submit_string($form, &$form_state){
    $sCampaign = $form_state['values']['campaignstring'];
    $sComments = $form_state['values']['Comments'];
    $sComments = $sCampaign."-".$sComments;
}

```

Your `hook_form_alter()` won't work the way you expect it to work. You need to test if the given $form\_id equals the form\_id of the form that you want to alter. For example:

```
function hook_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == "MY_FORM_ID"){
        $form['#submit'][] = 'submit_string';
    }
}

```

You could also use `hook_form_FORM_ID_alter()` like this:

```
hook_form_MY_FORM_ID_alter(&$form, $form_state) {
    $form['#submit'][] = 'submit_string';
}

```

Find out more here: Forms API - Modify Forms with hook\_form\_alter()
> 0 votes

---
Tags: forms
---


title: how to use hook_field_widget_form

text:
# Question
Title: how to use hook_field_widget_form
I am trying to understand how the addressfield module is using hook\_field\_widget\_form. When is it called and where are its parameters coming from? When I do a printout of its $instance parameter, I see that it has default values. Where are these set?

# Answer
> 0 votes
The hook is called by the Fields Widget API in order to collect information about defined widgets. Any module can define a field widget as long as it implements the necessary hooks.

Documentation about the hook itself can be found in the docs: hook\_field\_widget\_form().

Basically it provides widget specific Form API elements that collect the necessary data for a field. The default values are set in code (or wherever the module chose to define them) and should provide sensible defaults. In the case of the Addressfield module the default values are defined in the function addressfield\_default\_values in the main module file addressfield.module.

---
Tags: entities
---


title: Event Specific Webform Submissions

text:
# Question
Title: Event Specific Webform Submissions
I have a bunch of events that users should be allowed to register to. But I am trying to use one basic form that asks for the following fields:

```
First Name
Last Name
Phone Number
Email
Gender

```

I was wondering if there is a way to connect that form to a specific event. Is it possible to have a submissions field that is hidden from the user that auto populates with the node ID or something similar to that approach?

Any help would be much appreciated! Thank you!

# Answer
> 1 votes
I suggest you to use entityforms instead of webforms.

And then, you should enable entity tokens and Field default token modules.

Now you can add a text field to your entityform, which contains URL of the current page as the default value.

After that, you may hide that field by CSS.

# Answer
> 0 votes
I would say add an entity reference field to the webform that can reference the event nodes.

Then you could use the entity reference prepopulate module, which will allow you to add an extra parameter to links that point to the webform that will prepopulate the field.

You can decide what to do when you prepopulate the field, including hiding that field from the user.

---
Tags: 7, webforms
---


title: Taxonomy vs Content Types or Entities

text:
# Question
Title: Taxonomy vs Content Types or Entities
With all the power of D7 Views 3.x and modules like Node Reference and/or various entity reference modules, alongside flexibility of fieldable taxonomies, I have trouble deciding data structure scenarios for taxonomy vs content types. What are some use cases?

# Answer
I suggest you to check these 2 posts:

http://www.4sitestudios.com/blog/sep-13-2013/when-use-content-types-taxonomies-and-custom-entities-drupal

https://drupal.org/node/2075921
> 1 votes

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


title: Add View Block when editing Content

text:
# Question
Title: Add View Block when editing Content
I've got a content type called PartyGuest. That content type has an entity reference field for "Primary Guest", so if I'm inviting Bob and Jane to the party, Bob and Jane are both content nodes but I only want to send one invitation so I make Bob's "Primary Guest" value equal to Jane. That way I know that Bob should be included on Jane's invitation.

When I'm looking at Jane's node (or editing Jane's node), I would like to be able to see a list of everyone else who is on Jane's invitation.

I've created a View Block with a contextual filter so that it lists the names of all other PartyGuests where the Primary Guest is equal to the contextual filter value. That part works... sort of.

61 is Jane's nid. If I type "61" into the "Preview with Contextual Filters" box, then my results are exactly what I expect. It shows Bob in the list. However, if I change the Preview with Contextual Filters value to by "node/61" or "node/61/edit", then I get no results at all.

How do I make my context filter grab the value from the url?

I've set the Contextual Filter to provide a Default value and to pull it from the 2nd URL path component, but it doesn't seem to work. Even when I have it set this way, it only works if I put "61" into the Preview box, but does not work if I put "node/61" into the preview box.

I've also tried setting the Default value to be the Content Id from the URL with no luck.

What am I missing?

# Answer
> 1 votes
"Content Id from URL" is indeed what you want. The preview box doesn't care for the rest of the url (the `/node/*/edit` part) and takes everything entered there as an argument.

---
Tags: 7, views
---


title: File URI - Change domain name

text:
# Question
Title: File URI - Change domain name
Is it possible to change the domain name when creating urls to the image:

file\_create\_url($file-\>uri)

I need the images to say they're coming from another domain, but I can't change the base\_url, since we need to keep drupal accessible on origin.

Example

Origin: http://domain1.com/files...

When creating image urls, they will be http://domain2.com/files...

# Answer
Looking at file\_create\_url() I think it should be possible to pass in an absolute path, starting with `/files...` and then prefix the return value with your domain, protocol, whatever you need.

To handle that at a single location in code you can also use hook\_file\_url\_alter().

Is it possible that you're looking for the CDN module?
> 1 votes

---
Tags: media, uri
---


# Question
Title: How to remove the create prefix text when adding new content?
Tried a couple of attempts and no luck with function framework\_preprocess

```
function framework_preprocess_ask_a_question(&$vars, $hook) {
  if (arg(0) == 'node' && arg(1) == 'add' && arg(2) == 'ask_a_question') {
      $variables['title'] = 'Ask a new question';
   }
}

```

Content type is called "Ask a Question" want to change the title from "Create Ask a Question" to "Ask a new question" (removing the create text set by default)

# Answer
> 4 votes
You can use hook\_form\_FORM\_ID\_alter().

You could also use hook\_form\_BASE\_FORM\_ID\_alter() or hook\_form\_alter() if you preferred or it fit better with your other custom code and requirements.

You would do something like this in a custom module:

```
/**
 * Implements hook_node_FORM_ID_alter().
 */
function MODULENAME_form_ask_a_qustion_node_form_alter(&$form, &$form_state) {
  // Only change the title on the add form, not the edit form.
  if (empty($form['nid']['#value'])) {
    drupal_set_title('Ask a new question');
  }
}

```

Or if you want to do multiple content types:

```
/**
 * Implements hook_node_BASE_FORM_ID_alter().
 *
 * Alter all node forms.
 */
function MODULENAME_form_node_form_alter(&$form, &$form_state, $form_id) {
  // Only change the title on the add form, not the edit form.
  if (empty($form['nid']['#value'])) {
    $title = '';
    switch ($form_id) {
      case 'ask_a_qustion_node_form':
        $title = 'Ask a new question';
        break;
      case 'other node type_node_form':
        $title = 'Other title';
        break;
    }
    if ($title) {
      drupal_set_title($title);
    }
  }
}

```

There is also the node add title module that allows you to set the title of the add form per content type. At a quick glance over the code of that module though I see a few issues so I personally wouldn't use it at this stage, although I will open some issues to try to get them fixed.

---
Tags: nodes, theming
---


title: Displaying data from database

text:
# Question
Title: Displaying data from database
I am studying how to create a custom module in Drupal7, so far I have created a simple module that will accept subscribers by registering.

These are the fields I have for my database, and has finished the function that will accept user input.

**Table: simple\_subscribe**

```
sid , firstname, lastname, email

```

I then proceeded to create the function that will display all of the subscribers so far this is what I got

```
function subscription_view_form() {
  $result = db_query("SELECT * from subscribe");

  $record = $result->fetchAll();
  echo '<pre>';
  print_r($record);
  echo '</pre>';
}

```

I am using `print_r($record);` to display the information, but all it displays is the objects on top of the website, before the navigation

```
Array
(
    [0] => stdClass Object
        (
            [sid] => 1
            [firstname] => John
            [lastname] => Doe
            [email] => johndoe@gmale.com
        )

    [1] => stdClass Object
        (
            [sid] => 2
            [firstname] => Test
            [lastname] => Beta
            [email] => betatester@delta.com
        )

)

```

**edit**

I am using the hook\_menu() to display a form on /subscriptions but I can't output the subscribers inside the content area, I also wanted to list it in a table, I only did the `print_r($records)` to test if it is fetching the data. I wanted to know how to output it properly inside the content area not above it?

```
function subscription_menu() {
  $items[ 'subscriptions' ] = array(
    'title' => 'View the Subscribers',
    'description' => 'Subscription form available for subscribers',
    'page callback' => 'drupal_get_form',
    'page arguments' => array( 'subscription_view_form' ),
    'access arguments' => array( 'access content' ),
    'file' => 'subscription.pages.inc'
  );

  return $items;

```

# Answer
> 1 votes
I really think you should dive into Drupal's Examples Module to look at how a lot of the hooks and so forth you are (mis)using actually work.

But, quickly:

```
function subscription_menu() {

  $items=array();

  $items[ 'subscriptions' ] = array(
    'title' => 'View the Subscribers',
    'description' => 'Subscription form available for subscribers',
    'page callback' => 'subscription_records',
    'access arguments' => array( 'access content' ),
    'file' => 'subscription.pages.inc'
  );

  return $items;

}

```

and

```
function subscription_records() {

  $result = db_query('SELECT * FROM {subscribe}');
  $records = $result->fetchAll();

  $content = '<pre>' . print_r($records, TRUE) . '</pre>';

  return $content;

}

```

clean up most of the glaring misunderstandings.

However, you will still need to look into Render Arrays and Dynamic Queries to really clean up your code, as well as the Drupal Theming Guide with special attention to theme\_table() to create the page you seem to be after. And, of course, if you need user input, the Form API Reference is a must. But, once again, all of these are explained and demonstrated in the Examples Module.

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


title: How to convert underscores to hyphens?

text:
# Question
Title: How to convert underscores to hyphens?
I am currently working with Drupal 6. I just want to know how to convert all the underscores in the URL of my website to hyphens.

# Answer
> 2 votes
At admin/build/path/pathauto change the separator from underscore to hyphen and make sure the other punctuation settings are the way you like (the ones that say "Replace by separator").

Then at admin/build/path/delete\_bulk delete all the aliases that you want to change.

Then recreate them at admin/build/path/pathauto by checking "Bulk generate aliases for nodes that are not aliased" in Node paths, User paths etc. as needed.

---
Tags: uri
---


title: db_update add value to field

text:
# Question
Title: db_update add value to field
I want use `db_update` to update a field,instead of update a field with new value (replace) , I want add a value to last value, I know I can do it with mysql command

```
UPDATE `databasename`.`tablename` SET fieldB = fieldB + 1 WHERE fieldA='2';

```

but I use below code, It is not add to credit field, only replace it with $credit value, anybody know where is my problem and how can I achieve this job?

```
$cr_update_no = db_update('rah_cc_credit') // Table name no longer needs {}
                ->fields(array('uid' => $user->uid,'update_date'=>REQUEST_TIME,'last_code'=>$code ,'credit' => 'credit'+ $credit))
                ->condition('uid', $user->uid, '=')
                ->execute();

```

# Answer
The problem is way I used to update, for this job drupal has syntax, according to Update query with a dynamic expression in Drupal 7? I found my solution

```
$cr_update_no= db_update('rah_cc_credit') // Table name no longer needs {}
                ->fields(array('uid' => $user->uid,'update_date'=>REQUEST_TIME,'last_code'=>$code ))
                ->expression('credit', 'credit + :amount', array(':amount' => $credit))
                ->condition('uid', $user->uid, '=')
                ->execute();

```

I submit this answer maybe helpful for another in future.
> 3 votes

---
Tags: database
---


# Question
Title: How to pass a value from form(block) to the page and show this page?
I created a block with a form (elemnts: textfield and submit). Also have a page created by the hook\_menu. I want that when you click on submit in block, the value from textfield transmitted to a page that is created using the hook\_menu and show this page with data from textfield. In the future I plan to transfer some text in the html markup or array.

# Answer
Read about hook\_menu and wildcards. Here is an example:

```
function my_form($form, &$form_state) {
  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => 'Name',
  );

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

  return $form;
}

function my_form_submit($form, &$form_state) {
  $form_state['redirect'] = 'path/' . $form_state['values']['name'];
}

function MODULE_menu() {
  $items['path/%'] = array(
    'title' => 'TTITLE',
    'page callback' => 'my_page_callback',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function my_page_callback($var) {
 return 'HELLO ' . $var;
}

```
> 0 votes

---
Tags: 7, forms
---


title: Create Json from a view

text:
# Question
Title: Create Json from a view
I'm trying to create a json from Views, using Views Datasource.

The problem is that if I create a display "page", using Json as style, if I try to go to www.mysite.com/path/to/page the system doesn't return me the Json (as I see in the preview of the view) but an entire classic drupal page with the output of the json in the content region (so I've menus, regions, etc).

Is there a way to obtain the output as a simple json?

# Answer
> 3 votes
The right way is to *uncheck* the "Views API" flag in display settings.

---
Tags: 7, views
---


# Question
Title: Field available only when a value from a Hierarchical Select is chosen
I am using the Hierarchical Select module to allow users to first select a continent and then a country. I wish to enable a field only when a user selects *North America* (first selection) and *USA* (second selection).

I hope someone could explain how I achieve this.

# Answer
> 0 votes
I created a module that implemented the node\_validate function and from the values selected determined if child taxonomies existed when the form was submitted. If they did then obviously the user had not made a selection from the second drop down list.

This is the code I wrote.

```
function mp_admin_node_validate($node, $form, &$form_state) {
    if ($form["#form_id"]=="jobs_node_form") {
        $loc = taxonomy_get_children( $node->field_tax_regions[und][0][tid]);
        if ((count($loc)>0) && ($loc)) {
            form_set_error("field_tax_regions", t('Location region is required.'));
        }
    }
}

```

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


# Question
Title: "Undefined index: link path in menu_link_save() (line 3113 of /includes/menu.inc)"
I have a new Drupal installation; when I installed my first module, I got the following error:

> Undefined index: link path in menu\_link\_save() (line 3113 of /includes/menu.inc). error.

I have seen the line 3113 of menu.inc but I don't understand what happened. The error happen every time I install a custom module.

Does anybody know what the problem is?

This is the code I am using.

```
function froga_menu() {
  $items = array();
  $items['anunciantes'] = array(
    'title' => 'Editar perfil',
    'description' => 'Editar perfil - Anunciante',
    // 'parent' => array('anunciantes'),
    // 'page callback' => 'drupal_get_form',
    // 'page arguments' => array('form_editar_perfil'),
    'access callback' => TRUE,
    'type' => 'MENU_NORMAL_ITEM',
    'menu_name' => 'main-menu',
    'customized' => 1, // Must be 1 in order to not dispaly the link in any language
    'language'  => 'es', // language is required in order to make the item translatable
  );

  $mlid = menu_link_save($menu_item); // You don't need to receive it in a variable
  $ml = menu_link_load($mlid); // I'm loading $mlid just to display the result and verify it

  return $items;
}

```

# Answer
You are using the correct function (menu\_link\_save()), but you are passing it the wrong arguments, and you are calling it from the wrong hook.

The array key you can pass in `&$item` are described in the function documentation; the ones marked as *(required)* are required, and you need to pass them.

> * link\_path: (required) The path of the menu item, which should be normalized first by calling drupal\_get\_normal\_path() on it.
> * link\_title: (required) Title to appear in menu for the link.
> * menu\_name: (optional) The machine name of the menu for the link. Defaults to 'navigation'.
> * weight: (optional) Integer to determine position in menu. Default is 0.
> * expanded: (optional) Boolean that determines if the item is expanded.
> * options: (optional) An array of options, see l() for more.
> * mlid: (optional) Menu link identifier, the primary integer key for each menu link. Can be set to an existing value, or to 0 or NULL to insert a new link.
> * plid: (optional) The mlid of the parent.
> * router\_path: (optional) The path of the relevant router item.

`hook_menu()` is used to tell Drupal which menu paths the module is using, not for saving a menu link when the module is installed. For that there is `hook_install()` or, in alternative, `hook_enable()` which is called every time the module is enabled, even after the module is installed; in the case you use the latter, the code needs also to check the menu link is not already present. As side note, `hook_enable()` is not used from Drupal 8.
> 1 votes

---
Tags: routes
---


# Question
Title: How to redirect old url alias to new url alias?
Is there any way to redirect old URL alias to the new URL alias?

I want example.com/good-news to redirect to example.com/good-news-index, automatically.

# Answer
> 3 votes
You can use redirect module to redirect url from "old url" to "new url".

> This module allows you to specify a redirect from one path to another path or an external URL

There is also global redirect module which provide the same functionality.

> * Checks the current URL for an alias and does a 301 redirect to it if it is not being used.
> * Checks the current URL for a trailing slash, removes it if present and repeats check 1 with the new request.
> * Checks if the current URL is the same as the site\_frontpage and redirects to the frontpage if there is a match.
> * Checks if the Clean URLs feature is enabled and then checks the current URL is being accessed using the clean method rather than the
> 'unclean' method.
> * Checks access to the URL. If the user does not have access to the path, then no redirects are done. This helps avoid exposing private
> aliased node's.
> * Make sure the case of the URL being accessed is the same as the one set by the author/administrator. For example, if you set the alias
> "articles/cake-making" to node/123, then the user can access the
> alias with any combination of case.
> * Most of the above options are configurable in the settings page. In Drupal 5 you can access this after enabling the globalredirect\_admin
> module. In Drupal 6, the settings page is bundled into the module

# Answer
> 2 votes
In Drupal 6 their is one more module Path redirect, which adds one more option "Create a new alias. Redirect from old alias." in URL alias-\> Automated alias setting -\> General setting.

If this option is set, then whenever alias is changed/updated this module will redirect from old alias to new alias.

---
Tags: uri
---


# Question
Title: access denied when viewing profiles of other users
I am having a hard time finding out why non admins (and anonymous users) are having "access denied" errors when looking at Drupal-7 profiles of other users.

The "View user profiles" permission is checked.

My user's profile page is a panel, but the 'access denied' errors even if the profile is not a panel.

Any idea? Please help.

Additional Information:

Using a code inspired by Yuriy Babenko's answer, and filterning for uniqueness, I see the following pemissions are denied when user 163 views the profile of user 174 (goes to /user/174) :

`access administration menu`
`access administration pages`
`access all views`
`administer block classes`
`administer blocks`
`administer contexts`
`administer less`
`administer media`
`administer menu`
`administer user relationship`
`administer users`
`administer views`
`bypass node access`
`execute php code`
`view any private_notification content`
`view own unpublished content`
`view the administration theme`

I don't see anything related to user access...

The nice Access Denied Backtrace module gives the following backtrace, but how to interpret it?

```
Array
(
    [ 2: drupal_deliver_page()] => Array
        (
            [file] => includes/common.inc:2564
            [args] => Array
                (
                    [0] => 3
                    [1] =>
                )

        )

    [ 1: menu_execute_active_handler()] => Array
        (
            [file] => includes/menu.inc:532
            [args] => Array
                (
                )

        )

    [ 0: main()] => Array
        (
            [file] => index.php:21
            [args] => Array
                (
                    [q] => user/174
                )

        )

)

```

HOTFIX: Adding the following code before line 820 of user.module temporarily solved the issue:

```
if (arg(0) == 'user' && is_numeric(arg(1)) && is_null(arg(2)) &&
    $string == 'administer users' ) {
  return TRUE;
}

```

But how do I find why the 'administer users' permission to view other user profiles?

# Answer
> 1 votes
Impossible to say exactly without having access to your site, but something ON the profile page is causing this.

Do this (assuming you're on Drupal 7):

* Open /modules/user/user.module
* Scroll down to line 820 (which should be: `return isset($perm[$account->uid][$string]);`)
* Immediately above that line, add this code:

.

```
if (!isset($perm[$account->uid][$string])) {
  echo 'denied permission: ' . $string . '<br/>';
}

```
* Reload the page as a user that's getting Access Denied, and you'll get a printout of all permissions the current user got denied - one (or more) of them will be the culprit.

Don't forget to remove the code changes once you've found the issue.

# Answer
> 0 votes
This was a menu permission issue.

On my module's hook\_menu\_alter(), I printed the menu into the site's watchdog:

```
watchdog( 'fb_menu_alter', '<pre>'.print_r($items, true).'</pre>');

```

Looking at the results for the 'user' path, it was immediately clear that the access callback was old:

```
 [user/%user] => Array
    (
        [title] => My account
        [title callback] => user_page_title
        [title arguments] => Array
            (
                [0] => 1
            )

        [page callback] => user_view_page
        [page arguments] => Array
            (
                [0] => 1
            )

        [access callback] => privacypu_check_access
        [access arguments] => Array
            (
                [0] => 1
                [1] => profile
                [2] => access user profiles
            )

        [menu_name] => navigation
        [module] => user
    )

```

Disabling the privacypu\_profile module resolved the issue.

---
Tags: panels, users
---


title: What is admin_devel module in drupal?

text:
# Question
Title: What is admin_devel module in drupal?
THis module is separate from the devel module that gives ability to dpm() variables etc. What is it?

# Answer
> 2 votes
`admin_devel` is part of Administration Menu and provides administration and debugging functionality for site builders. It's quite a small module; in Drupal 7 it only has a function to rebuild all system menu links. It isn't tied to Devel in any particular way.

# Answer
> 5 votes
The admin\_devel module actually comes with the admin\_menu module.

It adds a debug function for javascript debugging (along the lines of dpm for php), which you can include and use.

It also adds a button you can press to rebuild system links, which is on the admin menu settings page.

This rebuilds menu item links that are handled by the drupal core system module.

---
Tags: debugging
---


# Question
Title: Use "date_views_filter_handler" filter handler for custom table field
How can I use "date\_views\_filter\_handler" defined in date module as filter handler for a column of integer type on custom table while exposing it to views.

# Answer
> 1 votes
I will not say this answer the question I asked but must say this answer worked the way I want.

Instead of using "date\_views\_filter\_handler" I used "date\_views\_filter\_handler\_simple" and it just worked like a charm.Here is what I did while exposing my custom table to views.

```
  $data['jh_report']['date_of_purchase'] = array(
    'title' => t('Date of purchase'),
    'help' => t('Date of last purchase for current month'),
    'field' => array(
      'handler' => 'views_handler_field_date',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort_date',
    ),
    'filter' => array(
      'handler' => 'date_views_filter_handler_simple',
    ),
  );

```

---
Tags: views
---