# Question
Title: How to display permanent arrows on the left/right of a carousel when using the Flexslider module?
I'm using the Flexslider module with Views and have a nice carousel running on my Drupal site.

The problem is that the design calls for permanent arrows on the left/right and the module only shows them when you hover over the carousel.

Is there an easy way to do this?

# Answer
> 0 votes
The following CSS will get you started:

```
.flexslider .flex-direction-nav a.flex-prev,
.flexslider .flex-direction-nav a.flex-next {
    display: block;
    opacity: 1;
}
.flexslider .flex-direction-nav a.flex-prev {
    left: 0;
}
.flexslider .flex-direction-nav a.flex-next {
    right: 0;
}

```

This will also help:

```
.flexslider .flex-direction-nav a:before {
    font-family: serif;
    content: "";
}

```

---
Tags: 7, javascript
---


# Question
Title: Conditional e-mails based on radio buttons Drupal Webform
I've built a form at http://dev.vies.dk/tilmelding. In the backend, it is easy to send e-mails to people filling out the form.

However, I need to send additional e-mails to other people based on some of the answers in the webform, namely the subjects they choose and the sex they have.

```
Subject         Female       Male
Soccer          mail@mail.dk mail@mail.dk
Handball        my@mail.dk   your@mail.dk
Kayak           mail@mail.dk mail@mail.dk
Dance           be@mail.dk   eb@mail.dk
Biking          sv@mail.dk   ls@mail.dk

```

Is there a hook, where this can be programmed, so I can achieve what I want?

# Answer
> 0 votes
Yes, you want to use hook\_mail\_alter() in a custom module. This will intercept the outgoing email from Drupal and allow you to add programming logic to the process. For example you could:

* Load the webform in question and view its results.
* alter the `to` value of the `$message` to meet your needs.

> 'to': The address or addresses the message will be sent to. The formatting of this string will be validated with the PHP e-mail validation filter.

---
Tags: webforms
---


# Question
Title: Can we use a hook_update_N for a module without hook_install?
I am working on a custom module which does not have an install file but nevertheless uses a lot of tables. The one who worked on it previously, created the database tables manually. Now I want to add more tables to it. I could run the query manually to get the job done but I wanted to use the 'Drupal' way to do that. So I was wondering if we could use a hook\_update\_N for a module without hook\_install?

# Answer
> 9 votes
No module needs to implement every hook. You can use hook\_update\_n() and not have a hook\_install() function just fine.

You'll probably at 1 point want to define hook\_schema() for these tables. An easy tool to get the "drupal" schema for **any** mysql table (already defined) in your mysql database is the Schema module.

> * Schema documentation: hyperlinked display of the schema's embedded documentation explaining what each table and field is for.
> * **Schema structure generation: the module examines the live database and creates Schema API data structures for all tables that match the live database.**
> * Schema comparison: the module compares the live database structure with the schema structure declared by all enabled modules, reporting on any missing or incorrect tables.
>
> **Note for MySQL users:** The Schema module requires MySQL 5. Prior versions of MySQL do not support the INFORMATION\_SCHEMA database that the Schema module uses to inspect the database.

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


title: User profile fields translatable

text:
# Question
Title: User profile fields translatable
How can I make user profile fields translatable?

I'd like to be able to translate some fields into other languages.

# Answer
If you are willing to use extra modules, instead of simple t() coding (as I do not believe this is possible for what you desire), install Profile2 and i18n Internationalization modules. Then, follow this guide in Profile translation and its documentation and that should set you straight.

Hope this helps.
> 2 votes

# Answer
If you create user profile with content profile you probably can use CCK translation module for this.
> 0 votes

---
Tags: 7, entities, users, i18n-l10n
---


title: Drupal 6 ubercart customise cart page

text:
# Question
Title: Drupal 6 ubercart customise cart page
I want to make a small modification to the ubercart cart page in my theme.

A typical item row on the cart page looks like this

`[remove button] [product image] [product title] [quantity field] [row total]`

All I want to do is move the `[remove button]` to the right hand side after `[quantity field]`.

How can I do this?

# Answer
> 2 votes
You need to alter the default Ubercart's theming of the shopping cart form and increase the weight of "Remove" column so it is pushed to the end.
Add the following code to your theme's `template.php` file.

```
/**
 * Themes the uc_cart_view_form().
 */
function phptemplate_uc_cart_view_form($form) {

  // Increase the weight of Remove column, so it goes to the end.
  $form['items']['#columns']['remove']['weight'] = 100;

  // The rest of the code is default Ubercart's code you can see in:
  // theme_uc_cart_view_form() function in uc_cart.module.
  drupal_add_css(drupal_get_path('module', 'uc_cart') .'/uc_cart.css');

  $output = '<div class="uc-default-submit">';
  $output .= drupal_render($form['update']);
  $output .= '</div>';
  unset($form['update']['#printed']);

  $output .= '<div id="cart-form-products">'
          . drupal_render($form['items']) .'</div>';

  foreach (element_children($form['items']) as $i) {
    foreach (array('title', 'options', 'remove', 'image', 'qty') as $column) {
      $form['items'][$i][$column]['#printed'] = TRUE;
    }
    $form['items'][$i]['#printed'] = TRUE;
  }

  // Add the continue shopping element and cart submit buttons.
  if (($type = variable_get('uc_continue_shopping_type', 'link')) != 'none') {
    // Render the continue shopping element into a variable.
    $cs_element = drupal_render($form['continue_shopping']);

    // Add the element with the appropriate markup based on the display type.
    if ($type == 'link') {
      $output .= '<div id="cart-form-buttons"><div id="continue-shopping-link">'
               . $cs_element .'</div>'. drupal_render($form) .'</div>';
    }
    elseif ($type == 'button') {
      $output .= '<div id="cart-form-buttons"><div id="update-checkout-buttons">'
               . drupal_render($form) .'</div><div id="continue-shopping-button">'
               . $cs_element .'</div></div>';
    }
  }
  else {
    $output .= '<div id="cart-form-buttons">'. drupal_render($form) .'</div>';
  }

  return $output;
}

```

---
Tags: 6, theming, ubercart
---


# Question
Title: Setting up responsive content within a responsive theme
I want to make a layout INSIDE the main content which is responsive. I've read through dozens of pages, watched several videos and still there is no clear path to acomplish resposive content. I started out with the latest Zen, but Display Suite and Panels let me place my fields in different grid layouts, but these grids end up not being responsive.

I now installed Omega, ending up having the same issue. So, which theme and which modules let me setup a responsive grid WITHIN the main content?

# Answer
If you are using Zen theme, best way(i hope so) to do responsive design is - Zen grids, First u need to install ruby gems, after you installed u need two more things, as root install sass and compass and ofc. zen-grids

```
gem install sass
gem install compass
gem install zen-grids

```

Then go to your theme folder, and write `compass watch` now all your css yo need to write in `sass` folder it will produce css in same files in your css folder. To do blocks responsive, in `Layouts` folder(ofc if you are using Zen sub theme) u will see `responsive-sidebars.scss` or similar, now u need to import `@import "zen";// Import Zen Grids with this statement.` and write **zen-grids** code in your `responsive-sidebars.scss`. Read more about Zen grids - *here*. *I hope it helps.*
> 1 votes

# Answer
I don't think you need get into zen grids just for responsive layout. Use Zen 5 responsive layout, and then put your content in the main content area as usual, and you have a responsive and adaptive website. Well, read up on responsive images.

I haven't tried this with Display Suite, but I assume it lets you set responsive columns. I use Panelizer with Extra Layouts, which are responsive.
> 0 votes

# Answer
If you're looking for the best way to use both Panels with a responsive design, you might be really interested in Adaptivetheme : it has a great Panels support, it is used by almost 50.000 sites (!), has subthemes and an extensive documentation.
> 0 votes

---
Tags: nodes, theming
---


title: Drupal 7 db_error() equivalent?

text:
# Question
Title: Drupal 7 db_error() equivalent?
I'm trying to figure out how to get the last database error after a query fails, and I'm having trouble finding the appropriate function. It seems up until Drupal 7 there was a `db_error()` function that would return the information.

How should I retrieve a database error in Drupal 7?

My code:

```
try {
    $q = db_query($q);
} catch (Exception $e) {
    $error = db_error(); // this is what I'd like to do
    $transaction->rollback();
    watchdog_exception('my_module', $e, t('Caught an error: ' . $error));
}

```

I'm aware that I can get some information from the exception, but I'd like to get it directly from the Drupal 7 API.

# Answer
> 7 votes
The Drupal 7 database API piggy-backs straight onto PDO. It doesn't define its own exceptions, or messages; it actually doesn't even attempt to handle any exceptions, it leaves them for the caller to handle directly.

The most descriptive error message you can get is in the exception object.

```
catch (\PDOException $e) {
  $error = $e->getMessage();

```

# Answer
> 1 votes
the Past Log module will log the exception for you, not sure if the db\_error is included like you need.

---
Tags: 7, database
---


# Question
Title: Notice: Undefined index: #value in element_validate_integer_positive()
I'm getting the error `Notice: Undefined index: #value in element_validate_integer_positive() (line 4190 of includes\form.inc)` after clicking the `Upload` or `Remove` of a `managed_file` even though the file is actually being stored in the correct directory.

Here's the relevant snippet:

```
$form['some_image'] = array(
    '#title' => t('Image'),
    '#type' => 'managed_file',
    '#description' => t('The uploaded image will be displayed on this page using the image style choosen below.'),
    '#default_value' => variable_get('some_image', ''),
    '#upload_location' => 'public://some_images/',
  );

```

I'm running the instance on XAMPP with PHP 5.3.6. Downgrading to PHP 5.2.9 didn't fix the problem as indicated in the other forums.

When I use Chrome to checkout the ajax request URL, I see the message that is also seen from looking at `file/ajax/image/file/form-wRaEJ-JRPqC7q6BSbp6Ccxi_9X1cpiaBzhwlIs9NFd0` that I found from `/admin/reports/dblog`

> Error message An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (512 MB) that this server supports.

Note that I'm only uploading a 100kb file.

Line 4190 of `includes/form.inc` is as follows:

```
function element_validate_integer_positive($element, &$form_state) {
  $value = $element['#value'];
  if ($value !== '' && (!is_numeric($value) || intval($value) != $value || $value <= 0)) {
    form_error($element, t('%name must be a positive integer.', array('%name' => $element['#title'])));
  }
}

```

**Update:** It turns out the problem is not just for the `managed_file`, but also for the form itself. Clicking the submit button shows the very same error.

Currently, my `hook_form_validate` is as follows:

```
function mymodule_form_validate($form, &$form_state) {
}

```

Removing it gives me a Drupal error that says it should be there. I think I'm missing an implementation some other hook, but I have no idea which.

What am I missing here?

# Answer
> 0 votes
It turns out the problem was coming from an entirely different field from the same form whose `#type` incorrectly valued with `numericfield`. I had to remove all my form fields and search which of them was causing the error.

It looks like the `managed_file` fields also trigger the validation for all the other fields in the same form when the `Upload` button is clicked.

# Answer
> 1 votes
It sounds that apache user doesn't have the permissions to write in the temp directory which is set in the Drupal's file system settings.

I'd suggest you to check first the status reports on `admin/reports/status`. If you have any problems with your installation, it would be listed there.

---
Tags: forms, ajax, files
---


# Question
Title: Drupal Commerce. Trigger shipping rules based on product field value
I'm really losing the will to live and hope somebody can help me.

I want to trigger a 'free shipping' rule based on a product field value, but for the life of me can not expose the free shipping field to rules.

I have read about bringing items into scope and have created a component which has access to the field. But when I attempt to add the component as a condition of my rule I am prompted to enter data selector - none of which seem to lead anywhere. I think it was wanting a product ID, which does not make any sense to me.

What am I doing wrong?

---

MORE BACKGROUND

I have tried two scenarios, one of which is to create a shipping rule,based on the conditions below. The other is to create a component, as described above

Condition1 - Entity has field \> Parameter: Entity: \[commerce-order\], Field: field\_free\_shipping

Condition2 - Date value is empty (also tried data comparison) \> However this does not lead me to the field stated in Condition1

# Answer
I eventually managed to get this working by dropping the idea of having custom fields and replacing them with taxonomy terms. For whatever reason (probably inexperience) I could not expose my custom fields to the rules module in order to trigger the shipping rules that I wanted.

By leveraging the Commerce Rules Extra module I was able first to trigger my shipping rules based on taxonomy terms instead of custom fields and secondly to define additional conditions for firing these rules with the help of the modules maintainer @MarcElbichon as discussed here https://drupal.org/node/2087815
> 2 votes

# Answer
I did this -

I used flat rate shipping module and created a flat rate called *free shipping* price 0. Then I edited the component to only apply to the circumstances required and it works really well.

See attached.

FWIW I used flat rate for free shipping and *commerce weight tariff* for the rest which works ace for me.
> 1 votes

---
Tags: 7, commerce
---


# Question
Title: How to show the uploaded managed_file in the edit page?
I am able to successfully upload files using `managed_file`. The file is saved in the correct directory and the record shows up in the `file_managed` table.

```
$form['image'] = array(
    '#title' => t('Image'),
    '#type' => 'managed_file',
    '#default_value' => (isset($foo->image->fid) ? $foo->image->fid : ''),
    '#upload_location' => 'public://foo_images/'
);

```

But when I edit the form, it still shows the `Upload` button, similar to the Create page before I have uploaded a file. How do I make the edit page look like I have already uploaded a file for that particular entity?

# Answer
Inspecting the `$foo` variable showed that I was supposed to use just `$foo->image` instead of `$foo->image->fid`.

Probably because I have the following lines in my `_form_submit`:

```
if (isset($form_state['values']['image'])) {
    $file = file_load($form_state['values']['image']);
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
    file_usage_add($file, 'foo', 'foo', $foo->tkid);

    $foo->image = $file->fid;
  }

```

Notice the part that says `$foo->image = $file->fid;`
> 0 votes

---
Tags: forms, files
---


# Question
Title: Commerce: How to manage line item fields for custom product type?
Drupal commerce works as follows:

When I add a product to the cart, system creates new line item (of type: product)

I have several product types. Could I achieve, that product line items would be specific for each product type?

What I would like to achieve is, that I can manage fields in line item type separately for each product type. For now, I can manage fields (or manage displays) only generally for all product types (When I go to Store -\> Configurations -\> Line item types -\> Product)

# Answer
> 3 votes
There's an open feature request for precisely what you want in the queue for Commerce Customizable Products. In the meantime, you need to create a new product display node type for each product type and use the settings for the Add to Cart form display formatter to use the pertinent line item type in its forms.

---
Tags: 7, commerce
---


title: How can users block other users

text:
# Question
Title: How can users block other users
In regards 7.x.

Say a user that has a role of (registered user) wants to block another user with the same role that is harassing them and they don't want to see any more posts or comments from the harassing user. But, I as the "Admin" don't want to Block either user. The user just wants to block the other harassing users comments or posts to be viewable by them....

For example: Other websites offer a way for a user to block someone that is harassing them. They can even block that harassing user from ever seeing their information/profiles/comments or posts.... But, that blocked user isn't blocked to everyone else, just blocked to that specific user from being able to see their information/profiles/comments or posts.

Is there a way to do that in drupal? What modules would I use to make that work? How can I make that work?

I am concerned that users could start harassing one another in posts and comments, there should be a way to mute users posts or comments from being viewable.

For example: Say I start a conversation with you and you don't like what I'm saying and you don't want to see those type of posts anymore from me. How can you block me from me posting such things on the drupal about you? So if there was a way to mute me, then my posts or comments would nolonger be visible by you but still visible by everyone else.

Is this possible?

# Answer
> 6 votes
I think best and easy approach would be using Flag module. You can create a Flag for user entity and grant authenticated users to flag other users, then you can check if the user is flagged as below.

```
$flag = flag_get_flag('ban_user') or die('no "ban_user" flag defined');

if ($flag->is_flagged($GLOBAL['user']->uid, $user->uid)) {
  // The optional second parameter to is_flagged(), which allows
  // us to ask if an item is flagged on behalf of a certain user. If this
  // parameter isn't provided, the check is made against the current user.
  print "This user has banned you!";
}

```

# Answer
> 1 votes
From memory, this has to be a custom solution. There was a useful article, however, here

# Answer
> 0 votes
You could use the Relation module. Create a many-to-many user-to-user relationship, call it "block\_user" and allow users to add relations.

Whether you use relation or flag (see heshanlk's answer): If you do not want to write code, you could replace the default comments with a view in a block. See How to display comments of current node in a view, and just add another filter for the relation or flag. You will be filtering with two contexts: the current node, AND the current user.

---
Tags: comments, users, blocks
---


# Question
Title: List related nodes through the same referenced node?
I have two node types: book, author.

There is a node reference field in book which references a single author.

On a book node, I would like to display a list of the same author's books, which I don't know how.

It seems to me the solution will involve EVA, contextual filter and relationships.

I can list all the author's books in an author node using EVA and contextual filter. But it uses author's node ID, which is in the url. I don't think I can pass the referenced author's Nid in a book's url. Or can I?

I'm only 5 days into drupal, and don't know a thing about relationships, can someone help me get my head around this? thanks in advance!

\[D7\]

# Answer
> 1 votes
I can't believe I just did it myself, though not sure if it's the best way.

First add a relationship, Content: Author (field\_reference\_author), give it a name: field\_reference\_author

Then add a relationship, Content: Author (field\_reference\_author) - reverse, set RELATIONSHIP to the field\_reference\_author, give it a name: field\_reference\_author\_reverse

Set each displaying field to use relationship: field\_reference\_author\_reverse

Add contextual filter, Content: Nid , without any relationship, Provide default value :content ID from url.

To exclude the node that is containing the related nodes list, from the list, just add contextual filter: Content: Nid , with relationship: field\_reference\_author\_reverse, Provide default value :content ID from url.

And it's done!

---
Tags: nodes, views
---


# Question
Title: How to write inner subquery in db_select() method?
How can I write a subquery in Drupal 7? My query is the following:

```
SELECT N.nid AS n_nid
FROM   workflow_node WN
LEFT OUTER JOIN node N
ON WN.nid = N.tnid
WHERE ( WN.sid IN (SELECT WT.sid
  FROM (SELECT sid,
    Concat(',', roles, ',') AS role_stamp
    FROM workflow_transitions) AS WT
  WHERE  role_stamp LIKE '%5%')
AND N.language = "en" )

```

# Answer
> 5 votes
You can assign your sub query to a new variable say subquery and pass it to the db\_select using

```
$query->condition('WN.sid', $subquery, 'IN');

```

You can know more about this by visiting this page.

---
Tags: 7, database
---


# Question
Title: Have to delete cron_last every time for cron.php to work
I am having trouble running cron.php. For testing, I am just running it from the browser (my\_domain/my\_site/cron.php.) Basically, if I go into the database and delete cron\_last from the variable, it works fine, for one iteration, but the next time I try to run it, it doesn't work (until I delete the cron\_last value again)

I put watchdog statement in cron.php. From that I could see that it runs until it hits `drupal_cron_run`. That statement doesn't execute correctly.

`drupal_cron_run` in in common.inc, so I put more watchdog statements in there. It fails to run past `module_invoke_all('cron')`.

`module_invoke_all` is in module.inc, so I looked in there, but now I'm stuck. Any ideas?

# Answer
Basically, you can't delete it with your code - it's set up after last cron hook finishes, so no matter what you do inside Drupal, it'll be set. If the last line that gets executed is `module_invoke_all('cron')` (in Drupal 6) or `module_invoke_all('cron_queue_info');` (in Drupal 7 real cron tasks are wrapped in `try catch` so this is the only really risky point), or if your server logs timeouts, it's probably a faulty module that fails to execute it's hook\_cron, or too many modules defining it, so at some point it times out.

I see two ways to deal with it:

1. Use Elysia Cron and with it's GUI manually run cron tasks you need to test. That way even if single task will fail, other will get executed. they will be executed one at a time, if you set it up correctly, so less risk of a timeout. And you will be able to test which hook, exactly, fails to execute. Then simply uninstall faulty module, or fix it, and you'll be OK.
2. In MySQL, create a trigger that will delete cron\_last value for you. PostgreSQL supports triggers too, and most of RDBMS support them or something similar to them. It will not solve your problem, but it's way faster than point 1. and it will get you going if all you need is *quick* and dirty hack.
> 0 votes

---
Tags: cron
---


title: Why Static Block id is getting changed?

text:
# Question
Title: Why Static Block id is getting changed?
I have sidebar block which has id "block-block-11--2". After including this statement in the node template

```
<div class="top-menu wrapper">
 <div class='search-wrapper'>";
 $search_block  = module_invoke("views","block_view","-exp-category_wise_search-page");
 print render($search_block['content']);
 </div>
</div>

```

all css of tat id is messed up, because id of that block has been changed to block-block-11. If I comment that code in node template the previous block id comes properly and all css works fine with that.Those two are entirely different blocks.

**NOTE I am not trying to place same blocks at two place.**

What is the issue over here? Thanks in advance.

# Answer
The issue is you're not using things correctly. You should never call blocks directly from templates. Use regions in templates and add blocks to them from GUI, or you can expect IDs to get messed up. Block IDs are based on the order blocks are prepared for display (see implementation of `drupal_html_id` function), and each time you mess up with the block display mechanism, and go around it, their numbers may change.

If you call block directly because you need to place a block in two places, see answers to Place a block in multiple regions question. Or, if it's a Views block, simply clone block display.

To reliably style a block, you can use Block Class module to assign a class that will not change the way ID does. Alternatively, you can use answers to How to add id to a block to manually override IDs - just be careful to keep them unique if you want JavaScript to continue to work.

---

Note that not only IDs will get messed up when you call block directly, but also things like permissions and cache settings may get compromised.
> 2 votes

---
Tags: 7, blocks
---


# Question
Title: drush installing drupal through root ssh is causing 500 internal server error
I have installed the drupal 7 using the root ssh user. The overall installation process seems ok within ssh. I have even downloaded and enabled the modules through drush. But when I tried to open the site on browser its throwing 500 internal server error.

I used the same process with out any errors when I grant a jailed shell access to the hosting account and login through their cpanel id in ssh.

But for the ease I want to install drupal through root ssh so I don't have to open multiple putty windows to manage multiple accounts.

# Answer
> 0 votes
Thanks to Matt C from Known Host who helped me resolving this issue. Sharing his reply below so others can be benefited.

> I've run the fix permissions script and it looks like all files and directories are set as they should be. You can find the script in /public\_html/fixperms.sh. I've also provided you with a link for fixpermissions:
>
> http://boomshadow.net/tech/fixes/fixperms-script/

---
Tags: drush, installation
---


title: node_load is not working

text:
# Question
Title: node_load is not working
I am creating a import script, which is importing node into Drupal website from external database.

Node is inserting properly. I have added condition that node exist into Drupal website or not and I am getting the correct nid with this condition.

When I am using `node_load` to load the existing node, its showing empty result.

I also checked node\_load get blank, but did not get any satisfied answer.

Please forgive me if this question is duplicate.

Code Snippets:

```
$pricelist_query = db_query("select * from abshop_import.abshop_import_price where (result != 'I' and  result != 'O' and result != 'D') or result is NUll limit 0, 50");

$message = '';

while ($pricelist_object = db_fetch_object($pricelist_query)) {

    $product = db_fetch_object(db_query("select * from abshop_import.abshop_import_antibodies where (result != 'I' or result is NUll) and sku_model='%s'", $pricelist_object -> sku_model));

    if (!empty($product)) {

    $product_object = db_fetch_object(db_query("select nid from {content_field_pr_man_prd_numb} where field_pr_man_prd_numb_value='" . $product -> field_pr_man_prd_numb_value . "'"));

        //If product is primary antibodies
        if ($product -> primary_or_secondary == 'P' || $product -> primary_or_secondary == 'p') {

        //If there is no existing product
            if (empty($product_object)) {

                $node = new STDCLASS;
                $node -> type = 'primary_antibodies';

                //setting language of the node
                $node -> language = 'en';

                //setting the author of the node
                $node -> uid = $product -> uid;

            } else {

                $nid = $product_object -> nid;

                $node = node_load($nid, NULL, TRUE);

                print $product_object -> nid . "===>";

                print_r($node);

            }

            $node -> shippable = 1;

            $node -> model = $product -> sku_model;

            //Setting title of the product
            $node -> title = $product -> title;
            //Setting body of the product
            $node -> body = $product -> body_teaser;
            //Setting teaser of the product
            $node -> teaser = $product -> body_teaser;

            $node -> weight = $product -> uc_products_weight;
            $node -> weight_units = $product -> uc_products_weight_units;

        }

        //If product is primary antibodies
        elseif ($product -> primary_or_secondary == 'S' || $product -> primary_or_secondary == 's') {

            //If there is no existing product
            if (empty($product_object)) {

                $node = new STDCLASS;

                $node -> type = 'secondary_antibodies';
                //setting language of the node
                $node -> language = 'en';

                //setting the author of the node
                $node -> uid = $product -> uid;

            } else {

                $nid = $product_object -> nid;

                $node = node_load(array('nid' => $nid), NULL, TRUE);

                print $product_object -> nid . "===>";

                $n = node_load(array('nid' => $nid), NULL, TRUE);
                print_r($n);

            }

            $node -> model = $product -> sku_model;

            $node -> shippable = 1;

            //Setting title of the product
            $node -> title = $product -> title;
            //Setting body of the product
            $node -> body = $product -> body_teaser;
            //Setting teaser of the product
            $node -> teaser = $product -> body_teaser;

            $node -> weight = $product -> uc_products_weight;
            $node -> weight_units = $product -> uc_products_weight_units;

        }

        if ($node = node_submit($node)) {

            print_r($node);
            die ;

            node_save($node);
        }

        node_load(FALSE, NULL, TRUE);

}

```

}

Thanks in advance.

# Answer
> 1 votes
After perform R&D, I found that `uid` of the node was not matching with `uid` in `{users}` table, which mean there is no existing user which is author of the node.

As I am importing the node from external database and it was importing properly previously, so I did not noticed the same.

Now, when I changed the `uid` of the node, everything starts working properly.

---
Tags: nodes, 6
---


# Question
Title: db_select usage in class and returned object
I'd like to use db\_select in a static public function of a certain class. The query should be a base query, which may then be customized in the calling function. Returning the result sets seems to work, but I'd like to return the drupal db\_select-object for further usage. Here is some example code:

```
class foo{
 public static function get_query() {
  $query = db_select('bar', 'b');
  return $query;
 }
}
function test() {
  $qobj = foo::get_query();
  $qobj->fields('b', array('id', 'name'));
  $result = $qobj->execute();
  ...
}

```

The returned object seems not to be a db\_select object, which can be edited further more. Do I have to create a dummy db\_select and pass the reference of this object to the static function.

Thank you.

Sven

# Answer
There's no such class as `db_select`, but your code will return a valid `SelectQuery`.

```
class foo{
 public static function get_query() {
  $query = db_select('bar', 'b');
  return $query;
 }
}
function test() {
  $qobj = foo::get_query();

  // Get type of object
  dpm(get_class($qobj));

  // Alter the query string and make sure it has been altered
  $qobj->fields('b');
  dpm((string) $qobj);

}
test();

```

The first Devel output for the above is `SelectQuery`, as expected. The second is the following query string:

```
SELECT b.*
FROM
{bar} b

```

Now add another function to the mix:

```
function test2() {
  $qobj = foo::get_query();
  $qobj->fields('b', array('x'));
  dpm((string) $qobj);
}

```

Run that in the same page request, and you get this query string

```
SELECT b.x AS x
FROM
{bar} b

```

So your code works exactly as you've specified that it should do.

If you're expecting something else to happen, it would be a good idea to detail that in the question.
> 2 votes

---
Tags: database
---


# Question
Title: Comment form is not working with ctools popup
I want to display a comment form in popup in drupal 7 website.

I have created a custom module to display comment form in ctools modal and added a link in the views page. Comment form is displaying correctly in ctools modal but comment is not saving when submitting the form.

When we submit the comment form, it does not display any error and redirect to comment form.

I am also using Ajax comments module in the site.

Code snippets for the ctools

```
/**
 * Implements hook_menu().
 */
function custom_feature_menu() {

  $items = array();

  $items['modal/%ctools_js/comment-popup/%'] = array(
    'title' => t('Comment Block'),
    'page callback' => 'custom_feature_comment_callback',
    'page arguments' => array(1, 3),
    'access callback' => TRUE,
  );

  return $items;

}

/**
 * Callback for
 */
function custom_feature_comment_callback($js = NULL, $nid = NULL) {

  $node = node_load($nid);
  // setting these defaults is needed, otherwise warnings result in dblog

  if (!$js) {
    return drupal_get_form('comment_node_'.$node->type.'_form', (object)$edit);
  }

  $form_id = 'comment_node_' . $node->type . '_form';

  ctools_include('modal');
  ctools_include('ajax');

  $comment = (object) array('nid' => $node->nid);

  $form_state = array(
    'title' => 'Write a Reivew (' . $node->title . ')',
    'ajax' => true,
  );

  $form_state['build_info']['args'] = array($comment);

  $commands = ctools_modal_form_wrapper($form_id, $form_state);

  if (!empty($form_state['executed'])) {

    $commands = array();

    $commands[] = ctools_modal_command_dismiss(t('Your comment has been saved.'));
    $commands = ctools_ajax_command_reload();
  }

  //If form is submittedd
  print ajax_render($commands);

}

```

I have searched in google and follow the below reference but comment form is not saving comment.

Thanks in advance.

# Answer
> 1 votes
I have found the issue. There is `#action` property in comment form which was redirecting to same form when we submit comment form. So, it seems that comment form is not working properly.

I have set up a `global` variable to remove `#action` property of the comment form if comment form is displaying in ctools popup.

```
/**
 * Callback for
 */
function custom_feature_comment_callback($js = NULL, $nid = NULL) {

  $node = node_load($nid);
  // setting these defaults is needed, otherwise warnings result in dblog

  global $comment_popup;
  $comment_popup = 1;

  if (!$js) {
    return drupal_get_form('comment_node_'.$node->type.'_form', (object)$edit);
  }

  $form_id = 'comment_node_' . $node->type . '_form';

  ctools_include('modal');
  ctools_include('ajax');

  $comment = (object) array('nid' => $node->nid);

  $form_state = array(
    'title' => 'Write a Reivew (' . $node->title . ')',
    'ajax' => true,
    're_render' => FALSE,
    'no_redirect' => TRUE,
  );

  $form_state['build_info']['args'] = array($comment);

  $commands = ctools_modal_form_wrapper($form_id, $form_state);

  if (!empty($form_state['executed']) || !empty($form_state['ajax_commands'])) {

    $commands = array();

    $commands[] = ctools_modal_command_dismiss(t('Your comment has been saved.'));
    $commands[] = ctools_ajax_command_reload();
  }

  //If form is submittedd
  return ajax_deliver(array('#type' => 'ajax', '#commands' => $commands));

}

function custom_feature_form_alter(&$form, &$form_state, $form_id ) {

  if ($form_id == 'comment_node_article_form') {

    global $comment_popup;

    if ($comment_popup == 1) {

      $comment = $form_state['comment'];

      // If not replying to a comment, use our dedicated page callback for new
      // comments on nodes.
      if (empty($comment->cid) && empty($comment->pid)) {
        // Change the action to call our function.
        $form['#action'] = url('modal/nojs/comment-popup/' . $comment->nid);
      }

      $comment_popup = 0;
    }
  }

}

```

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


# Question
Title: How does Drupal generate form ID for a form?
Following is the code snippet I used to generate a the User Profile edit form:

`print drupal_render(drupal_get_form('user_profile_form'));`

However, I could not find the declaration of the `'user_profile_form' form id` anywhere in the Drupal system. So I assumed that it is generated dynamically, but I am not sure.

So, If it is already defined, Where is it defined? and if it is generated dynamically then how does Drupal generates these Form IDs.

# Answer
`user_profile_form` is defined in `user.pages.inc` file in `user` module directory.

The id of the form is the function name which generate the structure of the form in Drupal System. When we call `drupal_get_form`, it call function name to build the form array.

There is a function `drupal_prepare_form` in `form.inc` in `includes` directory of the Drupal root.

> `drupal_prepare_form` function prepares a structure of the form array and adds required elements, executes any `hook_form_alter` functions and optionally inserts a validation token to prevent tampering.

Code Snippets to generate form id:

```
if (!isset($form['#id'])) {
    $form['#id'] = drupal_html_id($form_id);
  }

```
> 5 votes

---
Tags: 7, forms
---


# Question
Title: Make GMAP api aware that the gmap has been resized
I'm using jquery and css to toggle my gmap between full screen and normal size. However, since the original height is 200px, when I press the full screen button, it only draws 200px of the map and the rest is covered with a gray color. Is there a way to "let the GMap api know" that the map is resized so that it will draw the rest of the map and center the location selected to the new size?

# Answer
> 0 votes
With regular GMaps API, you would need to reinitialize the map or trigger the resize event to start recalculation/replotting the map.

However, this seems to be a common problem for several users of GMap module and there were no direct answers    .

This is one of the workarounds:

1. Go to `admin/config/services/gmap` and check `collapsehack`. This feature is supposed to be used when the map is in Drupal's collapsible fieldsets, but what it does is that it triggers map resizing on hash change. You can see this in the source code of `gmap/gmap.js`.
2. In your trigger add any hashchange - such as `#open-map` and `#close-map`.

Here's an example node content. JS/CSS are injected there just to give you an idea:

```
[gmap markers=blue::41.902277040963696,-87.6708984375 |zoom=5 |center=42.94033923363183,-88.857421875 |width=300px |height=200px |control=Small |type=Map]

<p><a id="toggle" href="#open-map">Toggle gmap size</a></p>

<style>
.gmap-control.open {
  width: 640px!important;
  height: 480px!important;
}
</style>
<script>
jQuery.noConflict();
jQuery(document).ready(function($) {
  $('#toggle').click(function() {
    if ($('.gmap-control').hasClass('open')) {
      $(this).attr('href', '#close-map');
    }
    else {
      $(this).attr('href', '#open-map');
    }
    $('.gmap-control').toggleClass('open');
  });
});
</script>

```

I tested this and it worked perfectly.

---
Tags: 7, theming, location, google-maps
---


# Question
Title: How do you programatically create decimal fields in Drupal forms?
I simply need to be able to have a text field and validate if input is a decimal number like 100.00, 0.1, 10.6, etc.

I'm using Drupal 7.

Updated question to indicate 'programatic' solution (using Form API).

# Answer
> 8 votes
I can't think of a better solution than to use a standard textfield with the `element_validate_number()` validator:

```
$form['element'] = array(
  '#type' => 'textfield',
  '#title' => t('Title'),
  '#element_validate' => array('element_validate_number'),
);

```

If you need something more complicated than the `is_numeric()` that gets run by `element_validate_number()` you just need to provide your own validation function, or if you want to mess with the widget itself then create your own element type using `hook_element_info()`

# Answer
> 1 votes
Under Strucuture-\>content\_type-\>manage fields : There is **field type** called Decimal where you can get a textfield having only decimal numbers allowed with validation.

for programmatically adding decimal field you can ,

```
$field = array(
    'field_name' => abc_decimal,
    'type' => 'number_decimal',
);

```

---
Tags: forms
---


title: Enter object with dsm

text:
# Question
Title: Enter object with dsm
i am actualy trying to read a field value in my panelized node.

I want to recieve the data in the red marked field, as u can see in my screenshot.

I tried to following:

```
<?php print_r($display->context['panelizer']['data']['field_centerpage_layout'][0]['value']); ?>

```

But I recieve this Error:

Fatal error: Cannot use object of type ctools\_context as array in C:\seu\xampp\htdocs\iptp\sites\all\themes\mytheme\plugins\layouts\he\_two\_70\_30\he-two-70-30.tpl.php on line 29

I would be thankful for any kind of help :-)

# Answer
> 1 votes
As you can see from your Krumo output (plus the very descriptive error message), `data` is an object, not an array. I'd imagine `$display->context['panelizer']` is also an object but it's hard to say as you haven't mentioned in your question how that's populated. You should use either

```
$display->context['panelizer']['data']->field_centerpage_layout[0]['value']

```

or

```
$display->context['panelizer']->data->field_centerpage_layout[0]['value']

```

Probably the second one.

---
Tags: 7
---


# Question
Title: User picture on multi site / multi database setup
I have an unusual problem that doesn't appear to have a workable solution....

We have a multi-site setup that has a shared database for taxonomy and the users tables and it's related tables.

Each site then has it's own core database with content, permissions and file\_managed.

We would like to keep the file managed table unique to each site, as the amount of images and video's expected will be significant over time.

This leaves us with one small issue in that the "picture" field in the user table is referring to a FID from the file\_managed table. If I set my profile picture when on site 1, it works great. If I visit site 2, the same user table will return a FID from that site, which could and usually would be a completely different picture.

Has anyone had any experience in getting around this situation? We don't want to go down separate users for each site, and we don't want to have one file table for all sites.

Ideally I'd like to be able to hard code a url for the "picture" field in the user table, but I'm not sure if this is possible?

Any help is very much appreciated.

# Answer
> 1 votes
What I would do is:

1. Use `hook_form_alter` to add non-managed file upload to profile edit page.
2. Configure Drupal or webserver so that directory for these files was common, or so that all pictures would get uploaded to the "main" site's folder.
3. To a profile, I would add a link field. Configure it to be shared between sites, too.
4. In a submit handler (again, added using `hook_form_alter`) I would populate this field with the URL to uploaded image.

---
Tags: users, files, multi-sites
---


# Question
Title: How to login into Drupal using Google Apps username and password?
We are looking for a way using which users can login into Drupal site using their Google Apps account user name and password. We use 'Google Apps for Education' and we do not want maintain separate username and password for our Drupal site.

We would also like to limit access to certain users having Google Apps accounts. Something like filtering or pre-approved account list. And, users' account should be created automatically when they login for the first time, and they should not need to fill any additional account information in Drupal, it should be directly pulled from Google Apps account.

Is there any module for Drupal 7 that provides this functionality? I have already tried OAuth, Loginza.ru, OpenID etc. like approaches and these are not what we are looking for.

If there is no such module, how shall I proceed with writing a custom module for the same?

# Answer
To integrate your Drupal 7 site with Google Apps, you need to:

1. Enable the OpenID module on your drupal site
2. Enable the Federated Login Service using your Google Apps control panel at http://www.google.com/a/cpanel/yourdomain.com/SetupIdp
3. Add an X-XRDS-Location header at yourdomain.com/openid For example, if yourdomain.com is a PHP site, upload this as /openid/index.php

```
<?php
header('X-XRDS-Location: https://www.google.com/accounts/o8/site-xrds?ns=2&hd=yourdomain.com');
?>

```
4. Go to your drupal site's login page. You'll see a new 'login with open id' link. Click it. Enter: https://google.com/accounts/o8/site-xrds?hd=yourdomain.com and click submit
5. The first time you do this, you'll be asked if you want to allow your site to authenticate. Click yes.
6. Subsequently, if you try to login using the above URL and you are logged in to Google Apps, you'll be logged in directly.
> 4 votes

# Answer
You shouldn't need to write a custom module from scratch there's plenty of code to get you started.
> 3 votes

# Answer
I have played with the Janrain Engage (formerly RPX) module using the janrain.com service. The pricing is pretty low if you don't have a massive user base. For Google, it will give you the user's email and full name (https://rpxnow.com/docs/providers)
> 2 votes

# Answer
For anyone with a simple use case (just let users login via Google), look at the Google Identity Toolkit (GITkit) module:

> This module allows users to login / register on a Drupal website using their Google login credentials via the Google Identity Toolkit API available on http://code.google.com/apis/identitytoolkit
> 1 votes

---
Tags: 7, users
---


# Question
Title: how to set value of autocomplete field and trigger search event with jquery
I am setting the value of an autocomplete field from a jquery event:

```
$('input#edit-myfield').val(mynewvaluethatIwant)

```

That works, but the associated drupal autocomplete search does not fire.

My use case is I have a working autocomplete, but as well as typing a few letter into the field, I want to give users the option of clicking a link to populate the field.

My automcomplete field AJAX handler runs several commands as part of its response, so I'm just wanting to fool the form into thinking the user has entered the value.

# Answer
I was figuring this alternative out while hargobind was working on his alternative solution (thanks for you efforts hargobind!).

It seems necessary to add in a delay, of around 300-1000ms in order to trigger the correct events.

My final code is this, which recursively polls the input until Drupal removes the "disabled" class:

```
        var $f = $('input#edit-contact-id');
        var new_value = contact_name;

        $f.val(new_value).trigger('select');
        blur = function() {
            if ($f.hasClass('progress-disabled')) {setTimeout(blur, 50);}
            else {$f.trigger('blur');}
        };
        blur();

```
> 0 votes

# Answer
Looking in `misc/autocomplete.js`, there's a function called `populatePopup()` (Drupal.jsAC.prototype.populatePopup). Since that function is bundled into the jSAC object, we can't call it directly. Instead, let's simulate the event that calls it which is found in the `onkeyup()` function.

```
<script>
/**
 *  Fill an input field and then display the autocomplete popup.
 *
 *  @param $field
 *    This is a jQuery field reference -- e.g. $('#my-input-field')
 *  @param searchVal
 *    The text to place into the input field
 */
function ShowAutoComplete($field, searchVal) {
  var e = $.Event('keyup'); // Create an event to trigger
  e.which = 32; // Add the keyCode (32 is a space, but it shouldn't matter)

  // Set the field value, focus on the field, then trigger the event
  $field.val(searchVal).focus().trigger(e);
}
</script>

```

FYI, I used this post as a reference to figure out how to fire the *keyup* event.
> 1 votes

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


# Question
Title: Add profile name field into the user page
I have overwritten the user-profile-form with hook\_form\_alter.

Right now there are additional fields in the user-profile-form, so the user can add more information about him/her and these fields will be visible in **/user/%** page.

I'm wondering is it possible to add more details in **/user/%** without using the user-profile-form?

Let's say to display a field "Profile of \[name\_of\_the\_user\]", so anyone who enters the user profile (Example John) in the top of the page will be displayed "Profile of John".

Is there any hook for that?

# Answer
You can print the user name when a user is logged in using something like this...

```
<?php print t('Profile of '); print l($user->name,'user'); ?>

```

Which will display "Profile of John Smith". (This will only print the name of the user that is currently logged in)

When viewing another users profile, their name is printed as the page title. I haven't tried this myself, but you could just print the title again, with the additional text around it.

To do this...

```
<div><p>Profile of <?php print $title; ?></p></div>

```

Should do the trick, as long as it is only printed on the /user page. You should add the code to your custom user-profile.tpl.php. This will print the name of the users page you are looking at, instead of the currently logged in user.
> 2 votes

---
Tags: users
---


title: Set wysiwyg's value with javascript

text:
# Question
Title: Set wysiwyg's value with javascript
How do I set a WYSIWYG's value with javascript? does the WYSIWYG module provide an api for this?

I don't know which editor user is using, so I can't use the api of editors.

# Answer
> 2 votes
The following code worked perfectly fine for me,

```
(function($) {
    $(document).ready(function() {
      $("#edit-body-und-0-value").val('this is a test content.');
    });
})(jQuery);

```

I have placed this code is test.js file. 'edit-body-und-0-value' is the ID of the textarea.

I have installed WYSIWYG module and placed CKEditor under sites/all/libraries/ckeditor folder. Although it doesn't matter if you are using CKEditor or any other editor because we are mainly referring to ID of our textarea.

---
Tags: 7, wysiwyg
---


title: how to display $page array?

text:
# Question
Title: how to display $page array?
How to display the entire $page array like shown below? I have devel module installed and have tried "dsm($page)" but that just shows the word "Array".

# Answer
> 1 votes
You can try dsm($page) in page.tpl.php of your theme to see the contents of $page array.

As mentioned by Clive, context really matters. If you will try to print $page array when it has no elements then it will display word Array.

---
Tags: 7, theming
---


# Question
Title: Remove terms from taxonomy vocabulary for node type
I have two node types that share a taxonomy vocabulary. I'll call them type1 and type2. type2 uses two terms from the vocabulary that type1 does not. Both type1 and type2 have views that allow filtering by the taxonomy terms. I need to have the two terms that type2 uses not show in the view for type1. Any ideas?

\[EDIT\] The terms are in a dropdown menu.

# Answer
> 0 votes
I found an option in the settings for the Views filter called "Limit list to selected items" I checked that and selected all the ones I wanted to show up in the list of terms by the operator settings. That made the ones I didn't want not show up.

---
Tags: taxonomy-terms
---


# Question
Title: Autofill fields on profile form based on previous fields
I have a particularly long user profile form on my client's site. Some of those fields can be autofilled using information already entered (such as spouse last name). The filling out needs to be done dynamically on the page. How can I do this?

\[Edit\] Adding code for a problem that I experienced (anonymized):

```
function foo_profile_autofill_form_profile_node_form_alter (&$form, &$form_state){
    foreach(array('field_first_name', 'field_last_name',
            'field_spouse_first_name','field_spouse_last_name') as $fieldName){
            $form[$fieldName]['#attributes']['class'][] = "combname";
    }

    drupal_add_js(drupal_get_path('module', 'foo_profile_autofill').'/foo_profile_autofill.js');

```

}

# Answer
You will have to use JavaScript to dynamically copy information from those fields. Depending on the structure of your form, you could also use a `form_alter()` to assign `data-` attributes to fields, which will reduce the number of lines of JS and make maintaining easier.

Here's sample code that should explain the idea::

**JS:**

```
$('input[data-sync]').change(function() {
  // Including the selector in data-attribute of the field will allow you
  // to have both - IDs and classes out of the box. This means you can
  // change the values of multiple fields, after only one change.
  $($(this).attr('data-sync-target')).val($(this).val());
});

```

**`hook_form_alter()`:**

```
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'your-form-id':
      $form['some_field']['#attributes'] = array(
        'data-sync' => TRUE,
        // You would use this to target an element with ID.
        'data-sync-target' => '#target-element-id',
        // OR you can use this to target multiple elements with this class.
        'data-sync-target' => '.target-element-class',
      );
      // If necessary, you can add custom CSS classes to elements like so:
      $form['some_field']['#attributes']['class'][] = 'your-special-class';
      break;
  }
}

```
> 1 votes

---
Tags: 6, javascript, users
---


# Question
Title: Varnish/Drupal caching for logged in users
**Problem**

Varnish is caching pages when I go onto my website anonymously.

I have "Cache Pages for anonymous users" turned on so this is expected.

But when I login it continues to load the cached page for the pages I visited when I was logged out, so the user specific menu never shows and the login button continues to show even though I'm logged in.

I though Varnish didn't work for logged in users and I'm using the default drupal caching system which I thought didn't work for logged in users? How can I prevent this?

**Server Set-Up**

LEMP Stack - Ubuntu Server 12.04

APC + Memcached

Varnish

**Drupal Caching Settings:**

Cache pages for anonymous users -\> enabled

Minimum cache lifetime -\> 0

Expiration of cached pages -\> 6 hours

**Varnish Module Settings:**

Varnish cache clearing: Drupal default

I installed Varnish using this guide and this Varnish config file: http://andrewdunkle.com/how-install-varnish-drupal-7

**Browser Caching**

I disabled browser caching in Firefox and I still get Varnish cache hits on my homepage however now the menu loads correctly. What does this imply?

# Answer
> 7 votes
You have two options:

**Solution 1: Disallow caching in the browser**

In order to prevent a browser from storing and reusing a page, you have to make sure that `Cache-Control:no-cache, must-revalidate, post-check=0, pre-check=0` is on the respective (HTML) pages.

You can force this header in `sub vcl_deliver`. Just make sure that you do not put that header on static assets (like images, CSS and JavaScript files):

```
sub vcl_deliver {
  set req.http.Cache-Control = "no-cache, must-revalidate, post-check=0, pre-check=0";
}

```

**Solution 2: Ensure that Vary: Cookie is on the response**

If you want to force the browser to invalidate its cache whenever the cookies change (i.e. a session is opened), you have to ensure that the `Vary: Cookie` header is on the response.

```
sub vcl_deliver {
  if (resp.http.Vary !~ "Cookie") {
    set resp.http.Vary = resp.http.Vary + ", Cookie";
    set resp.http.Vary = regsub(resp.http.Vary, "^,\s*", "");
  }
}

```

Again, the cache is more effective if you restrict this fragment the page / filetypes which have different contents depending on whether a user is logged in or not.

Safari (at least v5 which is the last one for Windows and the one on iPad 1 and some older iPhones) has a nasty bug. I recommend to add the following snipped in order to deactivate the Safari browser cache:

```
sub vcl_deliver {
  if (resp.http.X-Generator ~ "Drupal" && req.http.user-agent ~ "Safari" && req.http.user-agent !~ "Chrome") {
    set resp.http.Cache-Control = "no-cache, must-revalidate, post-check=0, pre-check=0";
  }
}

```

Note: This is a little bit different from the solutions proposed in the comments of the bug report. By placing the snipped into `vcl_deliver` instead of `vcl_fetch` we avoid having to separate the bins. Also note that by matching on `X-Generator ~ "Drupal"` we avoid disabling the browser cache for static assets.

Today (November 2013) I reproduced this misbehavior on Safari 5.1.1 (Windows), 6.1 (Mac OS X 10.8 / Mountain Lion) and 7.0 (iOS 7).

# Answer
> 1 votes
I choose to use the second option. I added the snippet to my Vanish config file:

`/etc/varnish/default.vcl`

I added it as it's own standalone snippet as opposed to putting the if function inside the already existing `sub vcl_deliver`.

---
Tags: 7, caching, proxies
---


# Question
Title: Migration to localhost causes 404 errors
I'm trying to copy my site on my computer.

I've successfully downloaded and setup all the things. My site localhost URL is **http://localhost/rich/** and when I run this URL, it opens my site homepage perfectly; after this, any clickable link gives me a 404 error page.

When I run this URL **http://localhost/rich/user** on my localhost, it gives me the following error:

> Not Found
>
> The requested URL /index.php was not found on this server.

Can anyone tell me what is wrong? What should I do it to fix it?

# Answer
Recently had simmilar issue. If your Drupal site were set up with clean url-s , you might want to change

```
#   RewriteBase /

```

in .htaccess file

* Try comment it out.
* If commented, try to uncomment it.
* Try to add subdirectory in that declaration, if drupal is installed
under any

Of course, check mod\_rewrite as was suggested by optimusprime619
> 1 votes

# Answer
I had the same problem recently and I checked the following to make it work:

1. Make sure rewrite module is enabled
2. Make sure in apache you have override all in order that your .htaccess works.
3. Look for any modifications in your .htaccess that might been conflicting with your new environment, especially those one related to force https. What I ended doing it is to copy the .htaccess from a new drupal project.
4. Make sure that in settings.php your base\_url is commented or properly set it to your current environment
5. if you are using a mac, verify that in /etc/apache2/users/nameuser.conf you change AllowOverride none to AllowOverride all

I had that problem recently and suggestion number 5 is what it worked for me
> 1 votes

# Answer
You may need to turn off clean URLs. To access the clean URLs settings page (when clean URLs aren't working) go to yoursite/?q=admin/config/search/clean-urls. Turn off clean URLs here.

Once you can click on the links in your site, you can then figure out what you need to do on your local machine to get clean URLs working.
> 1 votes

# Answer
Please check if there's been any modification done to the *.htaccess* file in your drupal to suit the Dev environment. Also i'd suggest checking to ensure the `rewrite module` / `mod_rewrite` is enabled in your local web server.
> 0 votes

---
Tags: migrations
---


title: custom block tpl with custom module

text:
# Question
Title: custom block tpl with custom module
I have created a block-custom.tpl.php, the following is the code inside:

```
<strong>Hello World</strong>
<p>Subject:<?php print $block->subject ?></p>
<p>Content:<?php print $block->content ?></p>

```

My custom module code:

```
        function custom_block_info() {
          $blocks['my-block-id'] = array(
            'info' => t('Block Name'),
          );
          return $blocks;
        }

        /**
         * Implementation of hook_block_view().
         */
        function custom_block_view($delta='') {
          $block = array();
          switch ($delta) {
            case 'my-block-id':
              $block['subject'] = t('Block Name');
              $block['content'] = custom_contents();
              break;
          }
          return $block;
        }

        /**
         * custom html block
         * @return string
         */
        function custom_contents() {
          return '
            </p><div class="body">
              Hello World, this is a example custom Block
            </div><p>
          ';
        }

```

I placed the tpl file in /module/block/ directory

I followed the tutorial of the following web page (I know it is for Drupal 6) http://eureka.ykyuen.info/2010/11/11/drupal-customize-block-template-file/

Of course, the result is nothing, anything I am missing? How to override the block.tpl.php?

# Answer
You have to put your code into an custom module. Creating Drupal 7.x modules should get you going. You should never change code of core. This will be lost (or at least causes tidious manual work) the next time you update drupal.
> 1 votes

# Answer
I think you may losing a hook:

function custom\_theme(){

}
> -3 votes

---
Tags: 7, blocks
---


# Question
Title: Place two text fields within a single <div> class
I have assigned class names to both user name & password text fields in user login block separately like this and it's working.

```
function mymodule_form_alter(&$form, &$form_state, $form_id, $element) {
   if ( TRUE === in_array( $form_id, array( 'user_login', 'user_login_block') ) ) {
       $form['name']['#attributes']['class'] = array('mgnB10', 'fntXL', 'drkFg1');
       $form['pass']['#attributes']['class'] = array('fntXL', 'drkFg1');
   }
}

```

I want to include these fields inside a single '' and assign class name for design purpose, like this.

```
<div class="class-name">
  username field
  password field
</div>

```

I am using the following code but I didn't get the expected output.

```
function mymodule_form_alter(&$form, &$form_state, $form_id, $element) {
   if ( TRUE === in_array( $form_id, array( 'user_login', 'user_login_block') ) ) {
       $form['user_login']['#attributes']['class'] = array('#prefix' => 'myclass');
       $form['name']['#attributes']['class'] = array('mgnB10', 'fntXL', 'drkFg1');
       $form['pass']['#attributes']['class'] = array('fntXL', 'drkFg1');
       $form['user_login'] = array('#suffix' => '</div>');
   }
}

```

# Answer
Hope this will help you,

In Drupal 7 you can achieve it by using the *#prefix* and *#suffix* properties in `hook_form_alter()`.

```
   /**
    * Implements hook_form_alter().
    */
    function hook_form_alter(&$form, &$form_state, $form_id) {
      switch ($form_id) {
        case 'user_login':
        case 'user_login_block':
          $form['name']['#prefix'] = '<div class="username-password-wrapper">';
          $form['pass']['#suffix'] = '</div>';
          break;
      }
    }

```
> 2 votes

# Answer
Instead of doing this programmatically, you can use the Field Group module, which allows you to group fields using the *Manage Fields* tab in the UI.

`<div>` can be selected as the group type.
> 0 votes

---
Tags: users, forms
---


# Question
Title: How to avoid calling FieldCollectionItemEntity::deleteRevision
Sorry about the confusing name. I have the following problem. I have a migration for a content type that has a multivalue field-collection-item (~50 items there in average per content). The migration is fairly quick, 150 items/min. However the migration-update is very slow, 10 items/min. I've checked with xhprof and 95% of the time it spends inside `FieldCollectionItemEntity::deleteRevision` \- basically deleting the old field collection items when re-populating the node with the new ones.

The content type has the revisions turned off, so the number of related revisions should be 1 all the time, not more. Is there any smart way to avoid this massive time that it takes?

I'm wondering if the Entity API has a queue system to save these delete operations for later. Or somehow removing revisions completely?

Thanks you

# Answer
> 2 votes
Copy and Paste your own version of the `FieldCollectionItemEntity` class file and call it like `FieldCollectionItemEntity2`. Then simply like have `FieldCollectionItemEntity::deleteRevision` return or do a NO-OP. Use the new class in your migration instead of the default one you're using now.

For when the migration completes; implement like a PostImport() function to delete all but the most recent revision.

To my knowledge there is no Queue of revision items. A node/entity Save (and revisioning) I thought is done in a sql `transaction` statement.

---
Tags: migrations, entities
---


title: Drupal Auction module - Mails not send

text:
# Question
Title: Drupal Auction module - Mails not send
I'm using the Auction module now. The Auction works fine, but there are no emails sent to users when they place a bid. When you insert your bid

> Unable to send e-mail. Contact the site administrator if the problem persists.

When I create an account, then i get a email with instructions. Only by the Auction module the mails will not sent. I saw one topic:

Drupal node 1945662

But there was no good answer for me. I used this module auction

# Answer
> 0 votes
Did you look at Debugging your Email on a development server? Have you looked at the Rules module and the Auction Rules to see if their firing (it sounds like they are)? Did you create hook\_mail\_alter() to see what email drupal thinks it's sending?

Does your "Create Account" email message fully validate as an email sent from a valid domain, etc.

It's email -- there are no easy answers :)

---
Tags: 7, emails
---


# Question
Title: Character counter for textarea in webform
I am relatively new to drupal. I have webform module and webform validation module installed. I was able to limit the number of characters in webform textarea using webform validation. However, this module does not support character counter for the fields. I have looked at this solution http://drupal.org/node/1459650#comment-5699952 which using maxlength module, but it is very unclear . I am planning to write a module implement hook\_webform\_component\_info\_alter(&$components) to add jquery or javascript on to the webform textarea field. Is this a correct way. If so or If not how would i do that?

# Answer
For webforms use the Webform Countdown module instead of maxlength. Here is a quote about it (from the module's project page):

> Provides a textarea component for Drupal webforms with a configurable, twitter-style dynamic word or character count.
> 1 votes

---
Tags: 7
---


# Question
Title: Force Field Required based on Widget Type
I'm using the GeoField module to geocode fields for mapping on my site. There is an issue with the current stable release of this module.

If Widget Type is "Geocode from another field" this field must be marked REQUIRED or GeoField will create this error:

```
Notice: Undefined index: default_value in geofield_field_presave()

```

Is there a way in Drupal 7 that based on the widget type you can FORCE the required option for a field? This would be a solution to this problem. Thanks!

# Answer
> 0 votes
you can group them together with field group, and then mark that group as required.

but the manual work in the Field UI is neede here ..

---
Tags: location
---


# Question
Title: Override and add a link to a themed table
Using a custom module, I'm trying to add "Schedule" links to each of the rows of the table on node/%nid/revisions, but can't seem to figure it out. Do I have to override the entire function node\_revision\_overview in node/node.pages.inc?

There is another table I would like to this to as well. So in general, I thought this would be a good excercise to learn Drupal theming.

Any help is appreciated.

# Answer
> 0 votes
yes copy the whole function to one of your own and add the operation. this is not dynamic.

for the other table, if you use an entity you could add the operation via the entitycontroller, only found this for d8 in the rush .. Custom entity operation links

for the d7 way http://drupalcontrib.org/api/drupal/contributions!entity!includes!entity.ui.inc/class/EntityDefaultUIController/7

---
Tags: 7, navigation, theming
---


# Question
Title: custom display of taxonomy list in views
I'm using a "Content:All Taxonomy Fields" field in a View. Works great, but-

Can I change the display of taxonomy field lists without custom code? The vocabulary has an image field I've added...I'd love to show the image instead of the name when listed.

Thanks!

# Answer
> 1 votes
If I understand well your question, you'd like to add the image associated to a term in your view ? If so, in the view go to advanced (right sidebar) =\> Relationships. choose "Content: Taxonomy terms on node", then in "add fiels" you should be able to add any field of your terms, like name, description or image...

To Avoid duplicate output, go to "advanced =\> Query settings" and check "Distinct".

In case you have duplicate output anyway, you can try this other solution :

Add a content-\> Nid field (Exclude from display).

Add a global php field. In output code, write something inspired from that, with your own details.

```
<?php
$q = "SELECT tid, filename FROM `taxonomy_term_data` INNER JOIN `field_data_field_tags` ";
$q.= "ON `taxonomy_term_data`.tid = `field_data_field_tags`.field_tags_tid ";
$q.= "INNER JOIN `field_data_field_img` ON `taxonomy_term_data`.tid = `field_data_field_img`.entity_id";
$q.= "INNER JOIN `file_managed` ON `file_managed`.fid = `field_data_field_img`.field_img_fid ";
$q.= "WHERE `entity_id` = ".$row -> nid;
$m = db_query($q);
while ($s = $m -> fetchObject()) {
  $img = "path_to_img_folder". $s -> filename;
  $tid = $s -> tid;
  echo "<a href='my_absolute_path/taxonomy/term/".$tid."'>".$img."</a>";
}
?>

```

You'll have then all your taxonomy images displayed in the same row. You may use the style settings to wrap the output with some classes. You'll have also to go to "advanced =\> Query settings" and check "Distinct". Hope it helps.

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


# Question
Title: Module that allows access to node based on roles
Is there a module that lets me simply select the roles that can have access to a node as I create it?

For example, I have a role named "BUG", I want BUG to be able to access node/5, but not any other role (including authenticated users).

I've been looking and looking and can't find anything.

# Answer
> 3 votes
Drupal offers a wide selection of node access modules.

Many (but not all) of these offer role based access control.

While still only in beta for D7, Content Access is a module I personally use for role based node access control. I regard it as stable for role based access control. However *do not* use it for lower resolution (user based) access control, as this mode is not yet stable.

> This module allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.

One of the advantages by this module is that it is fairly straightforward to control access to individual nodes by role.

---
Tags: 7
---


# Question
Title: How to overcome "Add new date link" issues in the 7.x-3.4 Calendar?
**Solved** See my solution in the answer below.

I am having an issue with the 7.x-3.4 Calendar, and would like to know if anyone has a solution, or suggested solution, to this issue.

Background: I have created a new content type of "Booking", and have created a new Calendar View that displays only dates of this content type. The Calendar works fine, and if I add new content through my Administrator option of "Add content", I can define my date, taxonomy terms and specific information (such as the Point of Contact (POC) name and email address) without an issue. These display perfectly on my newly created calendar, with a coloured stripe dependant on the taxonomy term selected (just for interest, the taxonomy term defines which room they would like to book). From here however, I have this issue:

In the page to edit the view for the calendar, I select Format \> Show \> Settings, and get the "Month: Row style options" page. When I select a content type in the "Add new date link" dropdown box, I do not get an "Add" link on my Calendar. (I have tried all the different types of content, including a content type that all authenticated users are able to, and actively do, create new content within. I have edited the permissions to allow all authenticated users to create content of content type "Booking". As a point of interest, I also use OG, however have not defined an OG "Group" to this content type, and do not plan to align this content type or calendar with any form of OG functionality in the future. I thought it pertinent to mention this in case here is where my problem lies)

I would greatly appreciate any feedback or thoughts anyone has, please do not hesitate to ask for any more information that you feel you may need!

# Answer
OK, so I have fixed this with a custom work around. There are many modules that I am using that may be interfering with the permissions to add a new date, and be limiting what can be displayed in the view. No matter, here is how I solved it:

First of all, set up the modules and permissions as following:

Go to admin \> modules, and find the PHP Filter module, ensure it is enabled:

Next, go into the permissions and find the following:

Ensure that the last option, "Administrator", is selected.

Next, go to the view where you would like to add the "Create Booking" (or whatever content type it is you are after.) From here, create a new header of type "Global: Text area"

What I chose to do next was create a link to a new view, and on this view I expose the form to add the new date/event. If you want to embed the create form here, then skip the next step, however I find doing it this way leaves the current calendar in it's original state, and by clicking the about to be created "+ Add Event" link, you will be taken to a new view that contains the calendar and the exposed form.

Now, select "Full HTML" as the Text format, and place the following code in the text box. This will create a link to a new view, which we will make next. The two lines below are simply coloured text that I will use as a legend for the calendar.

```
<a href="/calendar/create_booking">+ Create Booking</a>

```

When we next create the view containing the form to add the new date/event, if you chose to use a different path, come back here and change "/calendar/create\_booking" to your preferred path.

Now, apply changes and save the view. Go back to your Admin \> Structure \> Views page, and locate the view of your current calendar. Now, on the "Operations" dropdown, select "Clone View"

Rename the newly created view (I called mine "Create {Your Old View Name Here}"). Now, open up the "Edit" option for this view and create a new Header of type "Global Text Area" as before. This time, we want the Text Format to be "PHP Code" and to place the following code in your text area:

```
<?php
  module_load_include('inc', 'node', 'node.pages');
  $node_form = node_add('node_type');
  print drupal_render($node_form);
?>

```

Remember to change **'node\_type'** to your desired content type. Save the Header, and return to the last screen. Now simply change your path to what you wish:

And now finally, go back to your original Calendar view, edit the header to contain the correct path in the link we made, and you're finished! The form is now exposed for users to create a new event/date. Ensure that you set the appropriate permissions for users to be able to create this content type, and remember that their view of the **create** form will be much simpler than yours.

Hope this helped you if you had the same issue as me!
> 1 votes

---
Tags: 7, datetime
---


# Question
Title: Determine available Entities entity_metadata_wrapper value() methods
I'm struggling to determine which entity\_metadata\_wrapper methods are available for a given field. For instance:

```
<?php
  $fields = entity_metadata_wrapper('node', $nid);
  $body = $fields->body->value->value();
  $title = $fields->title->value();
  $type = $fields->type->value();
?>

```

$body has a different method, where you have to do a -\>value-\>value() for it to work right.

In my situation I'm trying to get the type of the node in Human readable form: "Custom Type" vs. "custom\_type". I'm wondering if there is some kind of value() method that returns the human readable version. print\_r($fields) avails me not.

**Edit:** To get the Human readable node type I ended up just using node\_type\_load. It seems like there should be a more efficient way of doing this using the Entity API, but I can't figure it out.

# Answer
> 6 votes
i think the wrapper doesnt provide the type label, at least i havent found it. One way to find the label :

```
$info = entity_get_info($fields->type());
echo $info['label'];

```

To learn more about available fields, try $fields-\>getPropertyInfo().

The diference of the body field is in the fact it is formatted, so the "first" value() function returns the object which allows you to retreive other metadata about the field. The difference can be spotted in the result of the aforementioned getPropertyInfo. While a "plain text" field is set to a callback function "entity\_metadata\_field\_property\_get", which returns the value immiediately, the body will have something like "entity\_metadata\_field\_verbatim\_get" which returns the whole array of the field.

according to the docs, you can also use value() on the wrapper itself and that will allow you to see what there is (so print\_r($fields-\>value()); or dpm() the same will help :)

# Answer
> 0 votes
It is possible to query a wrapper for all available fields:

```
$fields->getPropertyInfo();

```

---
Tags: entities
---


# Question
Title: How can I programmatically create a select input whose values come from a foreign key using Form API?
I have Table A who has a foreign key referring to Table B. I want my form associated with Table A to have a select field whose values will come from Table B. I want the select field to have options with key-value pairs coming from Table B.

Both Table A and Table B contain entities of different types.

I'm currently looking for programmatic solutions that use Entity Reference, but without having to go through adding a new field from `Administration` \> `Structure` \> `<entity type>`.

# Answer
I went with this solution that uses `entity_load` then adding the loaded entities as options to the select field for now:

```
$foreign_entity_items = entity_load('foreign_entity');
$foreign_entity_options = array();
foreach ($foreign_entity_items as $foreign_entity_item) {
    $foreign_entity_options[$foreign_entity_item->some_field] = $foreign_entity_item->some_other_field;
}

$form['some_form_element'] = array(
    '#title' => t('Some title'),
    '#type' => 'select',
    '#required' => TRUE,
    '#options' => $foreign_entity_options
);

```
> 0 votes

---
Tags: forms
---


# Question
Title: How to block (or redirect) external image source?
Users can add images to content. They're supposed to be uploading them to the site, but occasionally people will reference an image hosted elsewhere in the src='...'.

What is the best way to prevent these images from working (or even better, redirecting to a "This image is blocked" image)? I imagined using a hook of some sort to modify the content, or possibly a module that adds a filter to weed out these images. But it seems like a situation I could be overthinking.

Any suggestions?

# Answer
I presume you are allowing the uploading and embedding of images via the WYSIWYG. That being the case you need to write a text filter and apply it to the text format the users are allowed to use (Filtered HTML for example). http://local.example.com/admin/config/content/formats/filtered\_html

Have a look at the Examples module for how to do that.

```
filter_example  Defining an input filter

```

If you're not allowing them to upload and embed via the WYSIWYG (but uploading via a field for example) you could simply remove `img` from the permitted tags in your **Limit allowed HTML tags** filter.
> 0 votes

---
Tags: media
---


title: Drupal 7 auction module or something

text:
# Question
Title: Drupal 7 auction module or something
I'm search for a few days now. But I cannot find a good auction module for Drupal 7. **I have try the module: uc\_auction but the highest bid did not save in my shopping card only my sell price.** I have no idea of there is an other option for een auction system but I cannot find him.

Who have a suggestion for me? I'm using the module Ubercart for my website now.

# Answer
> 1 votes
Auction module provides auction functionality. Commerce integration is an option.

> Structure: Auctions are entities with start / end date, starting price, minimum price and instant buy price. Auction content type with auction reference field is created upon installation.

or

Commerce Auction module lets you create auction/reverse auction websites using drupal commerce. see the Demo

Features

* Allows creating auctions and reverse auctions using drupal commerce
* Automatic auction timeout extension
* Automatically adds auctioned product to the winner's shopping cart
* By default disables remove and edit quantity fields of auctioned products in shopping cart
* Global and per-auction bid limits (like uc\_auction)
* Lists bids using views

>

---
Tags: 7, ubercart
---


# Question
Title: How to use taxonomy vocabulary with terms and children using views module
I have a problem with Views and Taxonomy and maybe can found the solution here. I have a vocabulary with 15 terms and each term have a few childs. I want to show that with a jump menu using views but the result is awful because I have a list with terms and childs but losing the hierarchical order. Please, check it here (http://cubarecipes.org/restaurants-guide), right column, Cuba Restaurants guide block. Thanks in advance, Alex

# Answer
> 1 votes
You are probably looking for the Simple Hierarchical Select module.

From the module's page:

> Simple hierarchical select defines a new form widget for taxonomy fields to select a term by "browsing" through the vocabularies hierarchy. The widget is available in node forms and as Views exposed filter.
>
> This module has been inspired by Hierarchical select but is much simpler (hence the name ;) ).
>
> Unlike Hierarchical select this module provides a simple widget for taxonomy terms only. **As an addition Simple hierachical select works as Views exposed filter.**

The Hierarchical Select module is still in development for D7 and the Views integration has not been ported, so SHS is the best choice at the moment.

# Answer
> 1 votes
A simple solution is the Taxonomy Menu module, this will automatically turn Taxonomy terms into a menu with heirarchy, you can view the trial site for it here for Drupal 7.

Another useful thing that may help tidy up your menu is Taxonomy Menu Trails, which will allow you to hover and access nested terms.

Hope this helps!

# Answer
> 1 votes
You can follow the below step:

* Add relationship 'Taxonomy term: Parent term' in your views.
* Add 'Taxonomy term: Name' field in views and set 'Relationship' as parent which you have added in your views.
* Click on "settings" of jump menu and it will open "settings" form in popup.
* select parent field from the drop down "Grouping field Nr.1" in popup window and save the form.

Kindly see that there would not be link to parent term in jump menu and you can find the duplicate parent term in views, which you need to filter.

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


# Question
Title: How to create db table while installing a module?
I want to create a table in Drupal while installing a module (custom module which is crated by me). I tried in the below way, but I could not able to create a table in Drupal db. what am I missing, what else I have to do?

```
function custom_agent_handler_install() {

if (!db_table_exists('demo_score')) {
  $demo_score_schema = array(
    'description' => 'To store unique number and other details.',
    'fields' => array(
      'score'    => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE),
      'timestamp' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => '0'),
    ),
  );

return $demo_score;
}

}

```

# Answer
You should implements `hook_schema()` in your `modulename.install` file. In druapl 7, you do not need to use `hook_install` to create database table.

> A Drupal schema definition is an array structure representing one or more tables and their related keys and indexes. A schema is defined by `hook_schema()` which must live in your `module's .install` file.

Code Snippets:

```
/**
 * Implements hook_schema()
 */

function custom_travel_api_schema() {

  $schema['custom_booking'] = array(
    'description' => 'To store the booking flight.',
    'fields' => array(
      'bid' => array(
       'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'description' => 'The booking id.',
      ),
      'source' => array(
        'type' => 'varchar',
        'length' => '255',
        'description' => 'The source city for the booking.',
      ),
      'destination' => array(
        'type' => 'varchar',
        'length' => '255',
        'description' => 'The destination city for the booking.',
      ),
      'bdate' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The date of the booking',
      ),
      'amount' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The amount of the booking',
      ),
      'status' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The status of the booking(0 -> In process, 1 -> completed)',
      ),
      'uid' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The user id of the booking',
      ),
    ),
    'primary key' => array('bid'),
  );

  return $schema;

}

```

You can check this for more reference.
> 3 votes

# Answer
BY the way, you are using $demo\_score\_schema and you are returning $users\_score\_schema.

Try this example:

```
function hook_schema() {
  $schema['node'] = array(

    // Example (partial) specification for table "node".
    'description' => 'The base table for nodes.',
    'fields' => array(
      'nid' => array(
        'description' => 'The primary identifier for a node.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'vid' => array(
        'description' => 'The current {node_revision}.vid version identifier.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'type' => array(
        'description' => 'The {node_type} of this node.',
        'type' => 'varchar',
        'length' => 32,
        'not null' => TRUE,
        'default' => '',
      ),
      'title' => array(
        'description' => 'The title of this node, always treated as non-markup plain text.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
    ),
    'indexes' => array(
      'node_changed' => array('changed'),
      'node_created' => array('created'),
    ),
    'unique keys' => array(
      'nid_vid' => array('nid', 'vid'),
      'vid' => array('vid'),
    ),
    'foreign keys' => array(
      'node_revision' => array(
        'table' => 'node_revision',
        'columns' => array('vid' => 'vid'),
      ),
      'node_author' => array(
        'table' => 'users',
        'columns' => array('uid' => 'uid'),
      ),
    ),
    'primary key' => array('nid'),
  );
  return $schema;
}

```

https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook\_schema/7
> 0 votes

---
Tags: database
---


# Question
Title: How to Disable new terms (free tagging) with Taxonomies?
I have a "term reference" field, in a form that uses an auto-complete widget. I want to limit user input to terms in the vocabulary only, and output a message when a user tries to enter a non existing term.

I found the Content taxonomy module. However this does not work with forms that contain a field collection or a field group.

There is also a contributed patch 1078878-DisableAutoCreation-D7-UTF-8.patch. But I was wondering whether there was a simpler/cleaner solution like a module or maybe I missed an already existing way of doing it with latest drupal and taxonomy versions.

# Answer
There seem to be two possible solutions which are mentioned here http://fooninja.net/2012/08/03/drupal-autocomplete-term-widget-disable-creation/ and you have also mentioned them in your question.

Excerpt from the post,

> There are in fact two solutions. One is the Content Taxonomy module. However, I didn’t feel like installing yet another module for such a simple thing. The second solution is patching the core taxonomy module:
>
> A kind soul on the Drupal forum, j.stuyts, posted a small patch that adds an option to disallow autocreation. All you need to do is download the patch (1078878-DisableAutoCreation-D7-UTF-8.patch) to the Drupal 7 root directory and run.
>
> If you then go to Structure » Content types » \[Your content type\] and edit a Term reference field that uses the Autocomplete term widget, you’ll see a new option at the bottom: “Allow autocreation of new terms” (checked by default).

Although hacking in core is never recommended but you can use patch till the time you get better solution.
> 4 votes

# Answer
There is already an issue created about the problem with field collection module, and it should have been fixed in dev version of the Content Taxonomy module. Please try the latest dev version and if the problem persists, you can re-open and follow the issue at: http://drupal.org/node/1320976
> 1 votes

---
Tags: ajax, taxonomy-terms
---


title: Multiple join query

text:
# Question
Title: Multiple join query
i have a custom module and am using some queries inside, but am not getting the proper output

```
 $query = db_select('node', 'N_en')->extend('PagerDefault');
 $query->addField('N_en', 'nid', 'en_nid');
 $query->addField('N_en', 'title', 'en_title');
 $query->addField('N_en', 'type', 'en_type');
 $query->addField('N_ar', 'nid', 'ar_nid');
 $query->addField('N_ar', 'title', 'ar_title');
 $query->addField('N_fr', 'nid', 'fr_nid');
 $query->addField('N_fr', 'title', 'fr_title');
 $query->addField('N_de', 'nid', 'de_nid');
 $query->addField('N_de', 'title', 'de_title');

 $query->leftJoin('node', 'N_ar', 'N_en.nid=N_ar.tnid AND N_ar.language=:lang', array(':lang' => 'ar'));
 $query->leftJoin('node', 'N_fr', 'N_en.nid=N_fr.tnid AND N_fr.language=:lang', array(':lang' => 'fr'));
 $query->leftJoin('node', 'N_de', 'N_en.nid=N_de.tnid AND N_de.language=:lang', array(':lang' => 'de'));

 $query->where("N_en.status = 1  AND  N_en.type NOT IN ('catering', 'mobile','news','webform')
    AND N_en.tnid != 0  AND N_en.language = 'en' " );

$bool = $query->execute();

```

Am not getting the correct output. Arabic title is coming for French and German.

```
stdClass Object
(
   [en_nid] => 18
   [en_title] => About Us
   [en_type] => about_us
   [ar_nid] => 1693
   [ar_title] => Arabic About us
   [fr_nid] => 1693
   [fr_title] => Arabic About us
   [de_nid] => 1693
   [de_title] => Arabic About us
)
stdClass Object
(
   [en_nid] => 133
   [en_title] => Awards and Achievements
   [en_type] => about_us
   [ar_nid] => 1708
   [ar_title] => Arabic test
   [fr_nid] => 1708
   [fr_title] =>Arabic test
   [de_nid] => 1708
   [de_title] =>Arabic test
 )

```

# Answer
I would suspect that query placeholders get overridden. All thou not pretty and most likely theres different method for adding dynamic replacements, try this.

```
$query->leftJoin('node', 'N_ar', 'N_en.nid=N_ar.tnid AND N_ar.language=:lang_ar', array(':lang_ar' => 'ar'));
$query->leftJoin('node', 'N_fr', 'N_en.nid=N_fr.tnid AND N_fr.language=:lang_fr', array(':lang_fr' => 'fr'));
$query->leftJoin('node', 'N_de', 'N_en.nid=N_de.tnid AND N_de.language=:lang_de', array(':lang_de' => 'de'));

```
> 4 votes

# Answer
Debugging queries is fortunately very easy. After building your query, before executing, use this:

```
drupal_set_message((string) $query);

```

You can then compare that with the query string you're expecting it to produce, and find the problem quickly.
> 2 votes

---
Tags: 7, database
---


# Question
Title: Log out URL returns 503, redirects to path with double slash
When users access /user/logout they receive a "Page Not Found" error, and the URL they are forwarded to looks like this:

https://wwws.site.com/dir/site\_name//dir/site\_name/

Why is this redirect happening and how do I change the logout path so that it wouldn't create the double slash?

# Answer
> 0 votes
You should use URL() to create logout url. For example,

url('user/logout')

---
Tags: users
---


title: Create menu for contextual view page

text:
# Question
Title: Create menu for contextual view page
I have a series of pages created through Views, all the view pages are relative to one piece of content. The content paths I have created are

```
 - mycontent/[nid]/overview
 - mycontent/[nid]/members
 - mycontent/[nid]/content

```

Not that whats inside the view is particularly important but in this example, the first one shows the basic information about the node, the second shows everyone who is referenced by an entity reference, and the third shows all nodes connected by an entity reference.

I have created a new menu called 'mycontent-submenu' which I want to fill with links of:

```
 - Overview
 - Members
 - Content

```

Obviously you cannot use the Views module's menu ability to provide this as a menu item (unless you want to use it as a tab, which unfortunately I don't). In a more general term, the first question would be, how can I put these pages into a proper Menu (ie, not a tab)?

I already know of 1 way in which to solve this, which is to use Menu Views, with that I made a view for each of the Overview, Members and Content page, set the limit to 1, applied a 'null' contextual filter, and forced the output of the view to be re-written as 'mycontent/!1/overview'. Which works, but its a little hacky for my liking, plus you're querying the database a lot, I've done it before and it ended up increase the page load time if you have multiple menu items.

What I want to try to do right now is try to make a menu item programmatically in my own custom module, but I don't know what I'm doing wrong. My current code is:

```
function mymodule_menu() {
  $items['mycontent/%nid/overview'] = array(
    'title' => 'Overview',
    'description' => 'View the item',
    'menu_name' => 'menu-mycontent-submenu',
    'page callback' => views_page('individual_item', 'item_overview'),
    'page arguments' => array(1),
    'access callback' => TRUE,
    'expanded' => TRUE,
  );

  $items['mycontent/%nid/members'] = array(
    'title' => 'Members',
    'description' => 'Item members',
    'menu_name' => 'menu-mycontent-submenu',
    'page callback' => views_page('individual_item', 'item_members'),
    'page arguments' => array(1),
    'access callback' => TRUE,
    'expanded' => TRUE,
  );

  $items['mycontent/%nid/content'] = array(
    'title' => 'Content',
    'description' => 'All the Content for this item',
    'menu_name' => 'menu-mycontent-submenu',
    'page callback' => views_page('individual_item', 'item_content'),
    'page arguments' => array(1),
    'access callback' => TRUE,
    'expanded' => TRUE,
  );
}

```

As far as I can tell, I've researched how you call a view within a page callback, which is views\_page, and I've declared that I want my links to go into the right menu structure, but nothing actually appears. Is this block of code correct for what I want to do.

# Answer
you need to return $items at the end
> 2 votes

# Answer
You are missing the return in your function:

```
function mymodule_menu() {

  $items['mycontent/%nid/overview'] = array(
    'title' => 'Overview',
    'description' => 'View the item',
    'menu_name' => 'menu-mycontent-submenu',
    'page callback' => views_page('individual_item', 'item_overview'),
    'page arguments' => array(1),
    'access callback' => TRUE,
    'expanded' => TRUE,
  );

  $items['mycontent/%nid/members'] = array(
    'title' => 'Members',
    'description' => 'Item members',
    'menu_name' => 'menu-mycontent-submenu',
    'page callback' => views_page('individual_item', 'item_members'),
    'page arguments' => array(1),
    'access callback' => TRUE,
    'expanded' => TRUE,
  );

  $items['mycontent/%nid/content'] = array(
    'title' => 'Content',
    'description' => 'All the Content for this item',
    'menu_name' => 'menu-mycontent-submenu',
    'page callback' => views_page('individual_item', 'item_content'),
    'page arguments' => array(1),
    'access callback' => TRUE,
    'expanded' => TRUE,
  );

  return $items; // <--- WHAT YOU ARE MISSING

}

```
> 2 votes

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