# Question
Title: unable to edit content created by user 1
In drupal 6 I have created an admin user with the permissions to add, edit and delte all kind of nodes. The problem is that I am unable to edit nodes through this newly created admin user which are created by user1. any idea ??

# Answer
I think, you did not assign "edit any \[contenttype\] content" permission to newly created admin user, so this user does not have access to edit content created by other user.

You can follow below step for configurations.

* Go to Administer -\> User management -\> Permission
* Assign "edit any \[contenttype\] content" permission to newly created admin role and save the permissions.

Kindly see that \[contenttype\] is content type in your website. If you want to allow newly created admin user to edit all content created by other user, you need to give permission for all content type.
> 0 votes

---
Tags: nodes
---


# Question
Title: view exposed filter ajax error coming for non administrator user
I have *event calendar module* which is perfectly working fine. For some other users (*non-admin* users) I have to give permission to access events posted by them (They have permission to view the calendar and add/modify/delete events).

So far everything is good. Now I added *exposed filter*(event status) which is working as expected while I logged in as *admin*. Only when I login as user with some other role, I'm getting:

```
An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /views/ajax
StatusText: OK

```

Why is this happening only to non-admin user? I thought bypassing access control can give me some hint if its permission issue so I gave *'Bypass views access control'* to that particular user role, still no luck. Any help greatly appreciated.

# Answer
Go to Views Ui Setting Tab on Advance and uncheck Javascript ... it's Work for me
> 0 votes

---
Tags: 7, ajax, views
---


# Question
Title: Apply formatting to tables generated by tablefield module
I am using the tablefield module to allow the user to create a "programme schedule" in a table format. The only issue I'm facing now is that the user would like to be able to apply text formatting like bold or italics to certain fields.

The only thing I can think of is styling through CSS, however, given the dynamic nature of this table, it does not seem very feasible. Is there any other table modules that could provide such functionality?

# Answer
I haven't installed the module, but from the code it looks like there's an option in the field settings called "Table cell processing" in which you can allow the user to select what Input Format they want. This makes use of Drupal's text formats (Admin \> Configuration \> Content Authoring \> Text formats). You could allow them to use HTML within the cell, or install some alternate Text Format module such as BBCode.
> 1 votes

---
Tags: theming
---


# Question
Title: printing drupal field in comment.tpl.php
I have disabled user pictures, and created a field in users instead because i feel i have more control of the user pictures, i.e. i can organize them on webhotel with tokens, and choose a certain picture style etc.

Now i want to use the field in the comment.tpl.php of the theme, so i printed following code `<?php echo render($content['field_profilbillede']); ?>` where the `<?php print $picture ?>` usually appear .. but nothing happends at all .. what did i do wrong?

Ps. i got the code from another post on stackoverflow.com so yes i have already searched for related posts.

Thanks

# Answer
> 0 votes
I'm not positive about this, but maybe try removing the `$content` portion and rendering the field directly?

`<?php echo render($field_profilbillede); ?>`

---
Tags: entities
---


# Question
Title: Programmatically validate required fields of node object
I want to know if a node object could pass the form submit. With the UI, if required fields are missing, you can't save the node.

I would like to load the node object programmaticly, and check if all required fields are set. Is there a easy way to check that ?

# Answer
> 2 votes
Passing form submit means passing the form's validate handlers. Once validation is passed, the node is written into database and no more validation will be done(not sure about this). That's why node\_save api function does not return anything.

It means that "Required" fields are to be validated only in the Form validator. You can however choose to even write a Node without "Required" fields filled in. For example to can choose to empty "Required" fields in hook\_presave(D7).

node\_load does not check if all fields are set or not. It simply creates a node object which is consistent and also calls various hooks. It saves us from portability issues if we were to write our own functions to read the database and build node object.

---
Tags: 6, forms
---


# Question
Title: "WHERE NOT IN ( SELECT... )" with SelectQuery?
Is it possible to add a `WHERE NOT IN (SELECT...)` clause to a `SelectQuery` object? I was looking at SelectQuery::condition(), and it doesn't seem to allow for this syntax:

```
public SelectQuery::condition($field, $value = NULL, $operator = NULL)

```

It only seems to allow for value comparison expressions. Is there another method that provides this syntax?

I'm looking at conditions on the order of thousands of values, so it seems inefficient to have a bunch of `AND value <> x` conditions.

# Answer
> 8 votes
What you're looking for is SelectQuery::exists(), unfortunately it doesn't seems to work with "common way" to build such clause:
Normally in a `EXISTS` clause you put a JOIN on tables outside of your sub query like this:

```
SELECT n.nid
FROM node n
WHERE EXISTS (
  SELECT NULL
  FROM users u
  WHERE u.uid = n.uid
  AND u.status = 0)

```

This returns the nodes of blocked users (yes it can be built easily without the `EXISTS` but it's for teaching purposes ;).

The problem here is that the `exists` condition doesn't support "outside linking", the `u.uid = n.uid` part so you have to build a completely independent query which is not very efficient IMHO.
In Drupal you will write this:

```
$query = db_select('node', 'n')
  ->fields('n', array('nid'));
$subquery = db_select('node', 'n2')
  ->fields('n2', array('nid'))
  ->join('users', 'u', 'n2.uid = u.uid'
  ->condition('u.status', 0);
$query->condition('', $subquery, 'EXISTS');
$result = $query->execute();

```

You can also use db\_query() like you used to do in Drupal 6 and of course SelectQuery::notExists() is available.

# Answer
> 2 votes
An easier way to use db\_select with a NOT IN subselect is just to use

$query-\>where

to add an arbitrary where condition.

e.g:

```
  // Count query for users without rid 3
  $query = db_select('users', 'u');
  $query->fields('u', array('uid'));
  $query->where('u.uid NOT IN(select uid from {users_roles} where rid = :rid)', array(':rid' => 3));
  $result = $query->countQuery()->execute()->fetchField();
  drupal_set_message($result);

```

# Answer
> 2 votes
Acutally, you **can** use SelectQuery::condition() for creating subselects like so:

```
$query = db_select('users', 'u')
  ->fields('u', array('uid'))
  ->condition('u.uid', db_select('users_roles', 'r')->fields('r', array('uid')), 'NOT IN');

```

If we print this query using the dpq() function of devel it will output:

```
SELECT u.uid AS uid
FROM
{users} u
WHERE  (u.uid NOT IN  (SELECT r.uid AS uid
FROM
{users_roles} r))

```

I hope this helps ;-)

# Answer
> 0 votes
I believe this would help you.

```
$query->where('n.nid NOT IN (:nids)', array(
    ':nids' => implode(',', $nids)
));

```

---
Tags: 7, database
---


title: Can't show gist code in Drupal blog

text:
# Question
Title: Can't show gist code in Drupal blog
I'm completely new to Drupal. I've installed Gist Input Filter. In blog, when I write `[gist:6351376]`, as said in the project page, it just shows as it is. Please help.

# Answer
Go to *Home \> Administration \> Configuration \> Content authoring \> Text formats*. Click *Configure* next to text format you are using for blog posts, probably Filtered HTML. On the *Enabled filters* list, check Gist. On the *Filter processing order*, drag it to the end, or at least to be after *Convert URLs into links* and *Limit allowed HTML tags* filters.
> 2 votes

---
Tags: nodes
---


# Question
Title: Expose a computed field (or external data) to Views
I want to add a virtual field to a "node", its content should be computed from other fields of this node (with the module of the same name or with a hook) AND it must be usable by Views filter and sorting.

Is this possible (using modules or PHP code) ?

# Answer
I found answser on this site: http://barcelona2012.drupaldays.org/sessions/displaying-external-data-fly-views-and-ctools

This simple module give a clear example on how to expose external data (webservice) to a views.
> 2 votes

# Answer
Use the computed field module. The advantage is that the field is saved in the database and can be manipulated by views without performance overhead. The field's value is updated whenever the field is saved.

The code for the computed field should preferrably be placed in your module, not in your database. Use the computed field hook \- here is a nice (tutorial).

Here are some code examples.
> 1 votes

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


# Question
Title: field_attach_form removes image field default value when submit
I need to get some fields of a node edit form, for that purpose I use field\_attach\_form() to get the fields that I want with the value of the node.

Here's an example of the code of my form function:

```
function my_form($form, &$form_state, $node_id, $fields) {
  $node = node_load($node_id);
  $node_form = $form;
  field_attach_form('node', $node, $node_form, $form_state);

  foreach ($fields as $field) {
    if ($field->show) {
      $form[$field->name] = array('#type' => 'fieldset', '#title' => t('Field'), '#tree' => TRUE,);
      $form[$field->name]['override'] = array('#type' => 'checkbox', '#title' => t('Override'),);
      $form[$field->name][$field->name] = $node_form[$field->name];
      $form[$field->name][$field->name]['#states'] = array(
        'enabled' => array(
          ':input[name="' . $field->name . '[override]"]' => array('checked' => TRUE)
        ),
      );
    }
  }

  return $form;
}

```

I just wrap every field (that I want to show) in a fieldset with a checkbox.

One of the field is an image type, when field\_attach\_form loads the field, it shows the image thumbnail and the image file name perfectly, but when I click submit (without edit the field content) the value of the field is empty. In fact, the image field is required so the validation fails.

When I remove the previous image and upload a new one, it works perfectly. Am I missing something?

# Answer
I found a workaround: I just have the fields twice, one enabled and the other disabled. With the checkbox I show one or another.

```
function my_form($form, &$form_state, $node_id, $fields) {
  $node = node_load($node_id);
  $node_form = $form;
  field_attach_form('node', $node, $node_form, $form_state);

  foreach ($fields as $field) {
    if ($field->show) {
      $form[$field->name] = array('#type' => 'fieldset', '#title' => t('Field'), '#tree' => TRUE,);

      $form[$field->name]['override'] = array('#type' => 'checkbox', '#title' => t('Override'),);

      $form[$field->name][$field->name] = $node_form[$field->name];
      $form[$field->name][$field->name]['#states'] = array(
        'visible' => array(
          ':input[name="' . $field->name . '[override]"]' => array('checked' => TRUE)
        ),
      );

      $form[$field->name][$field->name . 'disabled'] = $node_form[$field->name];
      $form[$field->name][$field->name . 'disabled']['#disabled'] = TRUE;
      $form[$field->name][$field->name . 'disabled']['#states'] = array(
        'visible' => array(
          ':input[name="' . $field->name . '[override]"]' => array('checked' => FALSE)
        ),
      );
    }
  }

  return $form;
}

```

It seems that the action *enabled* / *disabled* is buggy.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: How to setup a rule to redirect to shopping cart?
I am trying to create a rule that after a user creates an account they are sent to a Checkout page that will eventually have them pay via PayPal ( I am using the Commerce Module ).

My steps so far have 1. Created an event "After saving a new user account" 2. Leave Condition blank. 3. Select Action of Complete Checkout For an Order

At step three it asks for a Data Selector: "Select data of the type Commerce Order." and I have no idea where to go from here.

# Answer
> 0 votes
I think you're probably missing a step, if I was integrating this I would create a product called Subscription (or something similar)

Your rule actions should be something like:

1. Add product Subscription to cart
2. Go to checkout

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


# Question
Title: An illegal choice has been detected. Please contact the site administrator in drop down list
when i am selecting values from dropdown list the corresponding values showing first time. but when i am again selecting the another value its not showing value instead of the error msg displaying **An illegal choice has been detected. Please contact the site administrator.** can anyone suggest me where i did wrong in the following code

```
<?php

function form_test_menu()
{
  $items['mark_entry'] = array(
    'title' => 'Mark Entry',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('form_test_form'),
    'access callback' => TRUE,
    );
  return $items;
}

function form_test_form($form,&$form_submit)
{

$dept = $_POST['dept'];
$batch = $_POST['batch'];
$month = $_POST['Month'];
$year = $_POST['Year'];
$semester = $_POST['semester'];

$query = db_select('student_master');
$query->fields('student_master', array('reg_no','name','dob','dept_code','degree','batch_year'));
$query->condition('dept_code',$dept,'=') AND $query->condition('batch_year',$batch,'=');
$results = $query->execute();
 $options = array();

foreach($results as $student_result)
{
$options[$student_result->reg_no]=t($student_result->reg_no);
}

  $form['roll']= array(
  '#type' => 'select',
  '#title' => t('Registration Number'),
  '#options' =>$options,
  '#required' => TRUE,
  '#ajax' => array('callback' =>       '_ajaxfunction','wrapper' => 'subjectsdiv'),);

 $form['month'] = array('#title' => t('month'),
    '#type' => 'hidden',
    '#value' => $month,
'#required' => TRUE,);

 $form['year'] = array('#title' => t('year'),
    '#type' => 'hidden',
    '#value' => $year,
'#required' => TRUE,);

 $form['semester'] = array('#title' => t('semester'),
    '#type' => 'hidden',
    '#value' => $semester,
'#required' => TRUE,);

 $form['subjects'] = array('#prefix' => '<div id="subjectsdiv">','#suffix' => '</div>');

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

return $form;
}

function _ajaxfunction($form, $form_state)

{

$key = !empty($form_state['values']['roll']) ? $form_state['values']['roll'] : 1;

$month = !empty($form_state['values']['month']) ? $form_state['values']['month'] : 1;

$year = !empty($form_state['values']['year']) ? $form_state['values']['year'] : 1;

$semester = !empty($form_state['values']['semester']) ? $form_state['values']['semester'] : 1;

$query1 = db_select('semester_appear');
$query1->fields('semester_appear',array('subject_code'));
$query1->condition('reg_no',$key,'=') AND $query1->condition('semester_appear',$semester,'=')AND $query1->condition('month',$month,'=') AND $query1->condition('year',$year,'=');
$query1->orderBy('sub_serial_no','ASC');
$results = $query1->execute();

while ($record_res = $results->fetchAssoc())
{

$subject_name = $record_res['subject_code'];

$query = db_select('subject');
$query->fields('subject', array('subject_name','subject_code'));
$query->condition('subject_code',$subject_name,'=') ;
$subject_results = $query->execute();

foreach($subject_results as $sub_result)
{
$options[$sub_result->subject_code]=t($sub_result->subject_name);
}

  $form['subjects']['name']= array(
    '#type' => 'select',
    '#title' => t('Please Select Subject'),
    '#options' => $options,
'#required' => TRUE,);

$form['subjects']['inter'] = array(
  '#type' => 'textfield',
  '#title' => t('Internal Marks'),
  '#size' => 60,
  '#maxlength' => 128,
  '#required' => TRUE,);

$form['subjects']['exter'] = array(
  '#type' => 'textfield',
  '#title' => t('External Marks'),
  '#size' => 60,
  '#maxlength' => 128,
  '#required' => TRUE,);

}

return $form['subjects'];
}

```

# Answer
check for details in watchdog under `form` to get an indication of which form element is causing the grief - in your case it will be the 'roll' or subject name field (possibly both!)

if you are updating the option array and removing the currently set option, then you have 2 choices:

in your form builder, either

```
unset($form_state['input']['roll']);

```

or

```
$options[$form_state['values']['roll']]
 = "the option i'm trying to get rid of";

```

the first option just discards the earlier selection, the latter option keeps it available (probably the first option is *generally* preferable)

additional: I've discovered I can also cause this error by messing my ajax call back so that the options are updated ok, but the form element in the browser isn't updated. In this case you will notice your options are not updating. You then need to double check your callbacks and div id's etc.

hth
> 1 votes

---
Tags: ajax
---


# Question
Title: Translating a site where default is in two languages
Drupal is written in English. We have created some custom modules where the strings in the module are written in French. These are passed through the t() so can be translated.

I am a little confused how I can show my site in both French and English when the default site language English is in both language. Please could you point me in the correct direction?

# Answer
> 2 votes
When you pass string through t() without specifying a langcode, then it will default back to English. So, if string is a French word, it will be handled as an English word.

Two options:

# Answer
> 0 votes
I'm not sure from your question whether you have successfully got your site working in both English & French, just in case, have you reviewed everything at https://localize.drupal.org/translate/languages/fr

It is normal practice that if you're writing custom modules which will be used across multiple languages, the strings in the module are written in English, as you point out that Drupal is written in English, then provide a translation using po files

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


# Question
Title: What is the suggested workflow for migrating (CMI) configuration from dev -> stage -> production?
We had a drupalcamp a few months back and someone asked about managing deployments with the new config (CMI) system. One possible ideal workflow would involve keeping the config in version control and still being able to migrate configuration between team members.

The best that we in the room were able to figure out (partially based on the presentation at DrupalCon Portland) was:

* Tell version control to ignore active config directory.
* Copy all Configuration over to staging directory and commit to version control.

And use settings.php to reverse active/staging directory between the 2 environments. However, while figuring out a deployment workflow from one server to the next was complex but doable, what is the suggested workflow from multiple local environments (ie multiple developers) into dev (or between each other) - A possible issue would be every team member would be sharing the same or similar environment so how do changes on one teammate's machine come over?

# Answer
> 19 votes
After talking a bit with CMI maintainers, the discussion on what's the best approach isn't finished but the following is what makes the most sense at the moment.

Trying to keep it terse for now, will try to expand based on questions/when the referenced issue is resolved with an official answer.

**So, first, the facts...**

* As already mentioned, there's the active and staging directory. Active is fully managed by Drupal, making changes directly in there (direct or indirect by switching to a different location) is not supported.
* Staging is where Drupal looks for configuration to import and doe otherwise not care about it.
* The import process is important, configuration changes can affect a site in a certain way and needs to be checked for validity. You can't change the field type of a text field to an entity reference, for example, that just doesn't work.
* The config import always needs to run on *all* configuration, you can't import a single view or node type. It was tried, but trying to cope with dependencies, removes/renames and so on resulted in an very complicated system and it didn't work.
* The only way to re-install default configuration, is to re-install that module. Which means that it would first try to *remove* all configuration (like fields). So that's not really an option. Manual, specific changes in update functions are possible but too tedious for this I think.
* As the features module describes, it will be focused on providing re-usable functionality, not continuous deployments of configuration. This is what it was designed for in the first place.

Given that, the recommendation right now is to put the staging directory into version control. Each developer has then full control over what he puts there, either by copying the whole active directory over, or just a specific configuration file. The staging directory changes are then committed, pushed to production and the configuration import is run (in the UI or with drush).

# Answer
> 4 votes
Great answered so far. Thanks you all!

We started a Drupal 8 project recently and implemented the following workflow.

We have three folders active, staging and export. Developers dump their to export. I don´t want to keep it in stageing. I thinks its easier to work with when the shared configuration is not directly stored in the staging folder. It´s just a felling i have no hard facts on this ...

Our current drupal 8 project template is available on github. I also wrote some handy drush commands to speed up the devleoper worflow. No manual copying from active to export required.

# Answer
> 2 votes
I haven't tried this yet, but my plan is to create a custom module that contains "default" config files containing only the configuration I care about. I believe other modules can contain configs that override other modules. (If not this should be made possible).

I think you must leave the config folder alone. Ignore it. It is auto generated on install from all of the individual modules' configuration files. The path is long and random. If you kept all of that in a repo, you would need a separate repo and you would be carrying along with it tons of default, unneeded config files.

Putting config in a custom module makes it a part of you main codebase.

The deploy process would be:

1. Git pull or whatever to get new files.
2. Clear caches.
3. Reset default config. (From your custom module's files)

You can create custom modules (with it's own config) for each environment if you want.

# Answer
> 2 votes
***Note:*** *I appreciate that this isn't an answer in the strictest sense in relation to the question, but I've put it here anyway and I'll revisit and edit/delete once Features has an 8.x release and the dust has settled a bit more. This was just too big for a comment and I wanted to get my £0.02 in :-)*

As a massive fan of Features, I'd suggest keeping an eye on the Features module's D8 incarnation.

*Taken from the project page*

> 3.x version of Features is planned for Drupal 8 to integrate with the new configuration management system. If you simply need to export simple site configuration, the D8 configuration management system should be used instead of Features. You will use Features in D8 to export bundled functionality (like a "photo gallery feature").

The way I *kinda* see it is that this idea makes it easier for dev *teams* to work on smaller parts of a site. I'm not going to go into a workflow yet though as there are still too many unknown variables, but I can't see it being THAT much different from a current Features deployment procedure.

I can't help but think yes, CMI is awesome; but most of my sites will still end up with Features modules (albeit a smaller amount due to not having to export EVERY content type, permission etc)

---
Tags: migrations, 8, version-control
---


# Question
Title: How to enable a payment method as soon as an order is saved in Drupal commerce programmatically?
I am trying to create a membership site using Drupal commerce. I have created a custom form that collects all the billing details of the user and the membership type and then on submit creates and saves a Drupal commerce order (products have already been created).

Now I want to activate the payment system for the order as soon the order is saved but I have not been able to do so. All of this should be happening in the backend and I do not want to redirect the user to a payment page. How do we do that?

# Answer
To get it to go onto the review page you can do.

```
$order = commerce_order_new($uid, 'checkout_review');

```

When creating your order that sets the status to checkout\_review.

Then you can use the following to driect yourself to the page

```
drupal_goto('checkout/' . $order->order_id. '/review');

```

As the status has been set you go to the review page. I did something similar recently and it is working well.
> 2 votes

---
Tags: 7, commerce, payment-gateways
---


title: Create form without JavaScript

text:
# Question
Title: Create form without JavaScript
I'm quite new in Drupal and I have to create a register form with dropdown lists like (Country-\>Province-\>City) but I can not use javascript, jquery or ajax due to accessibility issues. Is there any way to create it?

Some tips are welcome!

# Answer
No, not really. JavaScript is the only way to have content (including forms) change on a page without relaod. Now you have two ways to go around it:

1. Make all choices available in all 3 downloads and only hide unneeded ones using JavaScript. That way if someone will not have JS enabled, he will see all choices and will be able to make his selection. Don't forget to test if his selection is sane on the server side!
2. Use multi-step form. See this question and accepted answer. That way you will be able to ask one thing at a time, serving new steps using good old HTTP.
> 0 votes

---
Tags: forms
---


# Question
Title: Updated search index display, but old index is still being used
I updated the search index display for my content type (eg, from admin/structure/types/manage/page/display/search\_index), but the old index is still being used.

How can I fix this?

# Answer
When you save the settings for the search index display, nodes are not marked as needing to be reindexed. You can either reindex the full site, or add in your own submit handler to mark them as dirty:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_field_ui_display_overview_form_alter(&$form, $form_state) {
  if ($form['#view_mode'] == 'search_index' && module_exists('search')) {
    $form["#submit"][] = 'MYMODULE_mark_search_index_dirty';
  }
}

function MYMODULE_mark_search_index_dirty($form, &$form_state) {
  $entity_type = $form["#entity_type"];

  $query = new EntityFieldQuery();

  $query->entityCondition('entity_type', $entity_type, '=');

  if (!empty($form["#bundle"])) {
    $query->entityCondition('bundle', $form["#bundle"]);
  }

  $entities = $query->execute();

  $sids = array_keys($entities[$entity_type]);

  $num = db_update('search_dataset')
    ->fields(array('reindex' => REQUEST_TIME))
    ->condition('type', $entity_type)
    ->condition('sid', $sids, 'IN')
    ->execute();

  if ($num > 0) {
    drupal_set_message(format_plural($num,
      '1 item needs to be indexed.',
      '@count items needs to be indexed.'));
  }
}

```

This will alter the form used to edit the display settings. It checks to see if you are on the tab for changing the display of the search index view mode, and also have the Search module enabled. If so, it adds on a new submit handler.

The submit hanlder does an EntityFieldQuery to get all of the entity IDs for the type/bundle pair specified by the `$form`. It used EFQ instead of `db_query()` to be entity-type agnostic.

Then, based off of the code for `search_touch_node()` (which is called from node-related insert and update update hooks), it updates the search index to mark those entities as needing to be reindexed. This will leave the old indexed data in place, and subsequent cron runs will reindex.

If you want to remove those from the index until reindexing, then you can replace the query with a loop like:

```
foreach ($sids as $sid) {
  search_reindex($sid, $entity_type);
}

$num = count($sids);

```
> 0 votes

---
Tags: search
---


# Question
Title: Commerce product options on product basis
I am using Drupal Commerce and I would like to create product attributes. So customer can adjust some attributes before he would buy an item.

I know, that there are some commerce modules, that enable attributes / options of product. But I cannot find such module, that would enable setting attribute options separately for each product.

I have found Pricing Attributes module, but I can set options only globally, not separately for each product. I can set separately only price and enable/disable options. But I am not able to add new options.

Is it possible to add new attributes options to product using UI with some commerce module? If not, can anybody help to find documentation or API, how could I set product options programatically by myself without existing attribute modules?

# Answer
> 5 votes
Drupal Commerce generally conceives of attributes as those things about a product that a customer might specify on the Add to Cart form to drill down to a particular SKU, i.e. a particular variation in a group of products. From this perspective, you wouldn't have the ability to randomly add options to a product for selection on the Add to Cart form; you'd define attributes as fields on your product type and create a unique product for each potential variation.

You can use line item fields and expose them to the Add to Cart form, allowing the customer to enrich the line item with additional information required for fulfilling the product that do not affect the SKU. There are videos showing both of these different features in our video library:

http://www.drupalcommerce.org/videos

Finally, I met Joshua Needham at BADCamp, and I believe he intends to put some time into the Commerce Product Options module. This was a suite of modules initially developed by hunziker and then left on its own for a year or two. If Joshua is able to get commit access, I'd expect to see some work in there that allowed for product by product configurable bundles of options that are exposed through the line item form. I'd pull up a link for that but drupal.org is down atm. : )

# Answer
> 1 votes
You should check the commerce Kickstart module which includes drupal core itself.It has attributes settings in it for each product. You should try that on simplytestme site

---
Tags: 7, commerce
---


title: How to detect devel user switch

text:
# Question
Title: How to detect devel user switch
I need to detect if I'm currently browsing the site as a different user, having used the devel user switch module.

The LDAP module I have triggers some profile updates on every login, based on some server variables set from AD/SSO. But by using devel switch, it's writing MY user details, to the profile of the person I've switched to.

I need a way of detecting it, so I can prevent the profile write.

I've had a look through the devel API here but can't see that anything is set when running as another user.

Running D7.

# Answer
> 2 votes
The Devel switch feature passes the login straight to the user module in `devel_switch_user()`; it doesn't give other modules the chance to intervene, and doesn't provide any context that would let you know how the login has been instigated.

I guess as a simple low-tech solution you could patch that function and set a session var before it invokes the login, something like

```
...
if (!$old_uid) {
  // Switch from anonymous to authorized.
  drupal_session_regenerate();
}

$_SESSION['login_from_devel_switch'] = TRUE;

$edit = array();
user_module_invoke('login', $edit, $user);
...

```

Then you can check for the existence of that session var wherever you need to prevent the profile from writing.

---
Tags: debugging
---


title: Validating node creation / edit form

text:
# Question
Title: Validating node creation / edit form
I'm using form\_alter to play with the node form for a specific content type. This content type has many different fields and I'm also using Field Collection module to organize all these fields & logic, if that makes any difference.

Apparently, there are some incompatibilities between the Field Collection & Field Dependencies modules so I thought I might be able to build a similar field dependency functionality with my own module.

I've created a validation function for the form. My problem is that I'm trying to access $form\_state values that users insert in the form in order to validate these values but I think I'm doing something totally wrong here:

```
function _mymodule_my_validation_function($form, &$form_state){
    $short_field_name = $form_state['values']['long_field_name'];
    if (empty($short_field_name) || $$short_field_name == '') {
        form_set_error('error','That field cannot be empty!');
    }
}

```

Unfortunately this validation script doesn't work. To be more exact, I

```
dpm($form_state);

```

in my form\_alter and $form\_state doesn't even contain 'values' (shouldn't it be present but empty?).

Is there a different best practice for validation node form fields instead of dealing with the $form\_state\['values'\] array?

Also, I need to be able to see the values submitted by users each time the node form is submitted. Currently, I dpm($form) in my form\_alter function and everything is returned on the node/%/edit page as expected. But how can I catch submitted values on the node/% page after submitting the node form??

**Update:** When I call dpm($form\_state) within my validation function I get what I need if the form doesn't validate (as we still are on the same node edit page). But how can I receive the (new/changed) values that users entered in the form fields in case the form is submitted successfully and user is directed to content list page?

# Answer
**For custom forms**
The preferred way is to call hook\_form\_validate for hook\_form but you can use `$form['#validate'][] = 'custom_validate_function'` to call validate function

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

$form = array();

// write your custom fields here..........
return $form;

}

function hook_form_validate($form, &$form_state) {
 $short_field_name = $form_state['values']['long_field_name']['und'][0]['value'];
    if (empty($short_field_name) || $short_field_name == '') {
        form_set_error('long_field_name','That field cannot be empty!');
    }

}

```

**For built in forms by creating content type**

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

function form_1_validate($form, &$form_state) {

$short_field_name = $form_state['values']['long_field_name']['und'][0]['value'];
    if (empty($short_field_name) || $short_field_name == '') {
        form_set_error('long_field_name','That field cannot be empty!');

}
}

function form_1_submit($form, &$form_state) {

//To get the user selected or user submitted values you should look into code below
$field_name_values = $form_state['values']['field_name'];

}

```
> 0 votes

---
Tags: nodes, forms, debugging
---


title: Hiding menu item

text:
# Question
Title: Hiding menu item
I have a "person" content type, and then I have a directory of people, which has a "Directory" menu item.

When I view John Doe's page, I would like "John Doe" menu item appear under "Directory", so that the menu looks like this:

```
> Directory
    - John Doe (selected)

```

**But** when I go to Directory page, I would *not* like John Doe to appear under it, so the menu looks like this:

```
> Directory (selected)

```

Is there any way to achieve it, preferably "native" Drupal way?

Thank you in advance!

# Answer
I would suggest using the Menu Position module and create a menu position rule specifying that all of your nodes of content-type "person" go under the Directory menu item.

Then you wont need to add all of your person nodes to the menu.

**OR**

You can edit you menu and disable all of the person menu items under Directory.
> 1 votes

---
Tags: routes
---


# Question
Title: Resize & Crop Image Style Lowers Resolution
Whenever I try to implement a "resize & crop" image style on the display of a node in Drupal 7, the image also comes out with a lower resolution than the original file. Any idea why this might be happening or how I can get it to stop?

Thank you.

# Answer
> 4 votes
The jpeg quality is defined at 75%, this can be changed at /admin/config/media/image-toolkit

---
Tags: media, entities
---


# Question
Title: Setting up the private file directory (nginx)
**Problem**

I'm trying to set-up a private file directory for Drupal on an LEMP stack (Ubuntu 12.04, nginx, MySQL, PHP), I wasn't 100% sure about the permissions or set-up so I thought I'd ask, how should you do it?

**So Far**

It needs to be a folder which is writable by the webserver but not accessible from the web.

Example:

Location: drupal\_root/privatefiles

Permission: `chgrp 775 www-data privatefiles`

Nginx config: (goes into `/etc/nginx/sites-available/mysite`):

```
server {
         listen 8080;
           root /srv/www/mysite/public;

           location ^~ /privatefiles {
             internal;
           }

        ...
        }

```

Would that be enough? It recommends on the official page to have the folder outside the Drupal root. What difference would this make?

# Answer
Have a look at Perusio's config, it has all the information and explanation you need. Here is a quote from it:

> This config assumes that private files are stored under a directory named private. I suggest `sites/default/files/private` or `sites/<sitename>/files/private` but can be anywhere inside the site root as long as you keep the top level directory name private. (...) Example: Calling the top level private files directory protected instead of private.
>
> ```
> location ^~ /sites/default/files/protected {
>   internal;
> }
>
> ```
>
> Now any attempt to access the files under this directory directly will return a 404.

...

> The usual practice involves setting up a directory outside of files directory and giving write permissions to the web server user. (...) I think it to be less advisable, in the sense that now **there's another directory that is writable by the server.**
>
> I prefer to use a directory under files, which is the only one that is writable by the web server, and use the above location (protected or private) to block access by the client to it.

In short, marking it as internal is enough.
> 1 votes

---
Tags: 7, files
---


title: Can't save data in hook_node_update()

text:
# Question
Title: Can't save data in hook_node_update()
I have a node type with two field\_collection fields. When I save the node I need to write the entity\_id of the first field\_collection into the secondo field\_collection. This is my code:

```
function mymodule_node_update($node){
    $entity_id = $node->field_collection_1['und'][0]['value'];
    $entiry_array = entity_load('field_collection_item',array(entity_id));
    $entity = array_shift($entity_array);

    if (empty($entity->field_reference['und'][0]['value'])) {
        $entity->field_reference['und'][0]['value'] = $node->field_collection_2['und'][0]['value'];
        $entity->save();
    }
}

```

There are 2 problems there: 1) in hook\_node\_update() data is not committed yet https://drupal.org/node/1677830 2) $entity-\>save() triggers again hook\_node\_update() (and in my opinion it shouldn't)

So at the end in $node-\>field\_collection\_1 I have the right id $node-\>field\_collection\_2 would have, but due to recursive call to hook\_node\_update() and the fact that in hook\_node\_update() data is not committed to database yet field\_collection\_2 entity and all changes made to the node vanish.

Can someone suggest me a possible solution?

Thank you

# Answer
hook\_node\_presave($node)

> Act on a node being inserted or updated.
>
> This hook is invoked from node\_save() before the node is saved to the database. Parameters
>
> $node: The node that is being inserted or updated.

```
function hook_node_presave($node) {

if ($node->type == 'your_node_type') {
// you can write your desired code here

}

}

```
> 5 votes

# Answer
If you want to guarantee that everything including access rights is written to the database, you can register a shutdown function in one of the node hooks. You do that with drupal\_register\_shutdown\_function passing in an arbitrary function name and the arguments. Here's how it might look for your case in hook\_node\_update:

```
function mymodule_node_update($node) {
  // only register shutdown for node of the right type
  // let's assume the node content type is 'foobar'
  if ($node->type == 'foobar') {
    drupal_register_shutdown_function('node_voodoo_on_shutdown', $node);
  }
}

function node_voodoo_on_shutdown($node) {
    $entity_id = $node->field_collection_1['und'][0]['value'];
    $entity = entity_load_single('field_collection_item',entity_id);

    if (empty($entity->field_reference['und'][0]['value'])) {
        $entity->field_reference['und'][0]['value'] = $node->field_collection_2['und'][0]['value'];
        $entity->save();
    }
}

```
> 0 votes

---
Tags: hooks, entities, nodes
---


# Question
Title: (search) form without redirect or submit handler
Use case: Search field e.g. in the header, that leads to a url with GET query string.

The usual flow of forms built with Drupal 7 form API is like this:

* User visits a page with the form.
* User submits, $\_POST or $\_GET
* Validate + submit handlers are called
* Redirect to a new page.

What i would like instead:

* User visits page with the form, that was built with form API.
* User submits, resulting in a $\_GET request, e.g. example.com/search?query=foo+bar.
* The page example.com/search?query=foo+bar is served, without thinking about form API.

So, I want to use form API to build the form HTML (cause it's convenient), but not any submit magic.

Ideas?
Maybe I could find an example in existing modules, but I am looking for a "big picture" or documentation.

# Answer
> 3 votes
Not sure what you're exactly asking but everything should be well documented on Form API

I've recently done a form like this so I can give you an example of a GET method form:

```
/**
 * Form function for iwm_collections_search_form block
 */
function mymodule_search_form($form, &$form_state) {
  $form['#action'] = url(MYMODULE_SEARCH_PATH);
  $form['#method'] = 'get';
  $form['#attributes'] = array('class' => array('form-main'));
  $form['#after_build'][] = 'mymodule_search_form_after_build';
  $form['query'] = array(
    '#type' => 'textfield',
    '#title' => t('Keywords'),
    '#default_value' => '',
    '#size' => 30,
  );

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

  return $form;
}

```

You need an `#after_build` function to remove the unnecessary hidden fields so that it doesn't clutter the address bar:

```
/**
 * After build callback for mymodule_search_form
 */
function mymodule_search_form_after_build($form) {
  unset($form['form_token']);
  unset($form['form_build_id']);
  unset($form['form_id']);
  return $form;
}

```

No javascript, no submit handlers, easy.

# Answer
> 1 votes
If you don't want to build a submit function that simply does a `drupal_goto`, you can set a dummy submit button and **with Javascript**, *preventDefault* its action, and then do whatever you want as a query.

---
Tags: forms, search
---


# Question
Title: How to add custom CSS per media query in Omega 3 theme?
My Omega 3 theme has the following layouts in the grid settings:

Narrow layout: all and (min-width: 740px) and (min-device-width: 740px), (max-device-width: 800px) and (min-width: 740px) and (orientation:landscape)

Normal layout: all and (min-width: 980px) and (min-device-width: 980px), all and (max-device-width: 1024px) and (min-width: 1024px) and (orientation:landscape)

Wide Layout: all and (min-width: 1220px)

I need to add some custom CSS within each media query. At the moment ive added them within my existing custom CSS file by copying the media query and adding an @import.

```
@media all and (max-width: 739px) {
    //styles
}

@media all and (min-width: 740px) and (min-device-width: 740px),
(max-device-width: 800px) and (min-width: 740px) and (orientation:landscape) {
    //styles
}

@media all and (min-width: 980px) and (min-device-width: 980px),
all and (max-device-width: 1024px) and (min-width: 1024px) and (orientation:landscape) {
    //styles
}

@media all and (min-width: 1220px) {
    //styles
}

```

Is there a better practice way of doing this / what are the other ways? Is there a way that integrates with the theme more fully?

# Answer
> 0 votes
Part of the magic of Omega3 is that it does that for you!

Omega will always load the global.css file. If you are in a mobile layout (too narrow for a grid), that is the only file that loads. When you increase the browsers width to narrow, then omega 3 dynamically loads:

global.css
SUBTHEME-alpha-default.css (loads for all non-mobile-layouts)
SUBTHEME-alpha-default-narrow.css

If you keep increasing your browsers width to the normal layout, then these css files are loaded:

global.css
SUBTHEME-alpha-default.css
SUBTHEME-alpha-default-narrow.css
SUBTHEME-alpha-default-normal.css

Note that any CSS definitions you have in SUBTHEME-alpha-default-normal.css will override definitions in global.css, SUBTHEME-alpha-default.css, and SUBTHEME-alpha-default-narrow.css

To answer your question then, custom CSS for the narrow layout should go in SUBTHEME-alpha-default-narrow.css, custom CSS for the normal layout goes in SUBTHEME-alpha-default-normal.css, and custom CSS for the wide layout goes in SUBTHEME-alpha-default-wide.css. Just put it in and let Omega3 do the rest!

See https://groups.drupal.org/node/156719 for more info

---
Tags: theming
---


# Question
Title: How do I update jQuery to the latest version I can download?
I'm using Drupal 7, which uses jQuery 1.4 as default? How can I update it to the latest version (currently 1.7)?

# Answer
> 44 votes
One way is to install **the dev version** of jQuery Update, which gives you the option to use jQuery 1.7 (by visiting the settings page at http://mysite.com/admin/config/development/jquery\_update).

Beware though, currently it's known to break JavaScript elsewhere in the site (for example the widget dropdown on a Manage Fields page will no longer work). If you're prepared to fix up that, and any other small annoyances, this is probably your best bet. You should also note that using the dev version of a module isn't without risks, as the chances of it having bugs is a lot higher than using a specific release.

If you want to do it manually then you'll have a lot of core javascript code to rewrite to make your site work as expected; jQuery changed an awful lot between version 1.4/1.5 and 1.7 so a lot of the core Drupal javascript code simply won't work with it.

If you want to just drop in a version of jQuery 1.7 then you could probably implement `hook_js_alter()`, unset the core jQuery file, and add your own in it's place:

```
function MYMODULE_js_alter(&$js) {
  $path = drupal_get_path('module', 'MYMODULE') . '/path/to/jquery.1.7.js';

  // Copy the current jQuery file settings and change
  $js[$path] = $js['misc/jquery.js'];

  // Update necessary settings
  $js[$path]['version'] = 1.7;
  $js[$path]['data'] = $path;

  // Finally remove the original jQuery
  unset($js['misc/jquery.js']);
}

```

Once you've done that, open up Developer Tools/Firebug and you'll see all the changes you're going to need to make to get the rest of the site JS to work :)

**UPDATE**

The latest version of jQuery update (7.x-2.3 at time of writing) will now allow you to update jQuery to v1.8. Very cool.

The jQuery Multi module is another option, thanks to goron for pointing that out in the comments. As he also notes, this module has a stable release and won't break any existing javascript.

# Answer
> 4 votes
You should also consider to use the jquery multi module which allows you to use more than one version of jquery. Great module, I'm using it for Druapl 7 and 6 on all of my projects.

# Answer
> 2 votes
Inspired by hook\_js\_alter documentation, the following works. You can place it in your theme's template.php. This requires that you use a different admin theme to avoid conflict with Drupal core, and it assumes that jquery-1.8.3.min.js is located in a folder called 'js' within the theme (adjust to suit).

````
function [theme_machine_name]_js_alter(&$javascript) {

  $javascript['misc/jquery.js']['data'] = drupal_get_path('theme', '[theme_machine_name]') .
    '/js/jquery-1.8.3.min.js';

  $javascript['misc/jquery.js']['version'] = '1.8.3';

}

````

# Answer
> 0 votes
I'm not sure what your purpose is here, but when I needed a specific version for custom module development I have been able to do so by using jQuery.noConflict.

It is some extra work compared to the jquery\_update module (which the OP doesn't seem to mind), but it does mean that you don't have to worry about whether you're going to mess up your whole drupal installation.

---
Tags: javascript
---


# Question
Title: drupal_add_js and drupal_flush_all_caches
I was trying to call `drupal_add_js` in the callback of a button. It seems, even with after\_build, that this can be done successfully only you are working without cached data.

So, before i start the page, i run `drupal_flush_all_caches`, and the javascript is successfully added to the page.

The problem is I want to get some user input data from a form, pass to the javascript and exibit the result. The way i'm trying to do, it is getting a string that contains the processed values and concatenating with another string that contains the other part of the javascript (probably this is not a good practice), and calling this string with `drupal_add_js`. But, when if i call `drupal_flush_all_caches`, the form will be reset and i will not be able to get the data.

So, my questions are: How can i pass values from a form to a javascript?

Do i need to flush all caches every time to use `drupal_add_js`?

Is there different solutions to deal with this during development and production?

---

Thanks for the help guys. I found some answers: How can i pass values from a form to a javascript? I had to name my variable as `Drupal.settings.myModule.myVar` in the javascript code. This way i can pass variables from php code to javascript. If you want to modify the javascript code you really need to flush caches. Until now, i have not found nothing about differences between production and development best pratices.

# Answer
> 1 votes
Is there any problem with writing a menu callback that does this, and processing in PHP?

If you must use JavaScript for the processing, why not intercept the user's value in JavaScript and never "really" submit the form?

# Answer
> 1 votes
I think you can add the javascript using Drupal.behaviors. This will ensure that the javascript code gets reloaded even if the page is cached.

---
Tags: 7, forms, javascript, performance
---


# Question
Title: set a entity reference field programmatically
I have a node form, with an entity reference field.

I'm trying to hide the reference field from the node form and automatically reference an entity created by the node author.

Im using code like the following to fetch the entity to be referenced.

```
  $query = new EntityFieldQuery();
  global $user;
  $query->entityCondition('entity_type', 'node_ref');
  $query->fieldCondition('cmp_ref', 'target_id', $user->uid);
  $result = $query->execute();
  $storeids = array();
  foreach ($result as $ref) {
   foreach ($ref as $ref_id){
    $refids[] = $ref_id->id;
   }
  }
  $entity = entity_load('node_ref',$refids);
  foreach ($entity as $ref) {
    $ref_id = $ref->id;
  }
  return $ref_id;

```

I think its a long way of doing it but I just modified some code I found in a module.

Now upon save of the node I would like the entity reference field to reference $ref\_id

So something like

```
  $node->entity_reference_field[$node->language][]['target_id'] = $ref_id;

```

How do I call this on node submit? If I unset the field on the node form will the value still be set?

Thanks for any help

# Answer
> 7 votes
In case entityreference prepopulate is not a viable option, I always use an EntityMetadataWrapper to set field values.

```
function mymodule_node_ref_presave($node_ref) {
    global $user;
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node_ref');
    $query->fieldCondition('cmp_ref', 'target_id', $user->uid);
    $result = $query->execute();
    // A more efficient way to grab entity ids from a EFQ
    if($result['node_ref']){
      $ref_ids = array_keys($result['node_ref']);
    }
    if ($ref_ids){
      // Load the entity w/ metadata wrapper to set field more transparently
      $node_ref_wrapper = entity_metadata_wrapper('node', $node_ref);
      $node_ref_wrapper->entity_reference_field->set($ref_ids);
      // Because this operation is going to execute a save anyways,
      // we don't need to do $wrapper->save()
    }
}

```

# Answer
> 2 votes
You can use the module Entity reference prepopulate. It's doing exactly what you need - hide the field if you want, fill it with values from the address/callback function or you can write your own pre populate plugin. It's even integrate with the OG module.

---
Tags: entities
---


# Question
Title: Drupal 7 Commerce - How do you style the Please wait loading message/icon when you select an attribute?
I'm trying to style the please wait loader icon when you select an attribute for a product in drupal 7 commerce. I'm using chrome and i can't figure out a way to right click inspect element fast enough as it loads to fast. Or is there another way to expose this? I just need the HTML and classes associated with it.

# Answer
For example:

```
/* Custom ajax throbber style */
.ajax-progress .throbber {
  /* New icon */
  background: transparent url(../images/ajax-loader.gif) no-repeat 0px 0px;
  /* icon is 15px square */
  height: 15px;
  width: 15px;
  /* Alignment, may tweak to suit */
  float: left; /* LTR */
  clear:both;
  margin: 2px 2px 8px 2px;
}
.ajax-progress-throbber .message {
  /* Hide the "please wait" msg */
  display: none;
}

```
> 1 votes

---
Tags: 7, theming, commerce
---


# Question
Title: How to override a function that displays the user login block?
I'm trying to override the function user\_login\_block so that the links do not appear. I'm doing it by declaring two functions, but nothing seems to work. Here is the code:

```
function bartik_modificado_theme() {
return array(
'user-login-block'=>array('arguments'=>array('form'=>NULL)));
}

```

As I'm trying to modify the theme bartik, I put this function (also in the template.php):

```
function bartik_modificado_user_login_block($form) {
unset($form['links']['#markkup']);
return drupal_render($form);
}

```

I'm new to drupal and I simply don't know why this isn't working. I am simply unsetting one of the variables in the original user\_login\_block function. I also tried copying the entire function and edited it, but nothing happened. Can someone point out what I'm missing please?

I've been playing around with the code and now I see I made two mistakes: first, the form id in the first piece of code I posted is 'user\_login\_block' with underscores, not dashes, and second, the variable I want to change is `$form['links']['#markup']`with one k, not two. But now the page stays forever loading until it gives me an error of maximum execution time. I'm thinking this is because I'm using drupal\_render. ¿What function must I use to render the form, or still I ask what is going on? Please help.

This is the code updated:

```
function bartik_modificado_theme() {
return array(
'user_login_block'=>array('arguments'=>array('form'=>NULL)));
}

```

And the call to the block function:

```
function bartik_modificado_user_login_block($form) {
unset($form['links']['#markup']);
$form['submit']['#value']=t('ir');
//$output.=drupal_render($form);
return drupal_render($form);
}

```

# Answer
In Drupal 7, we use `variables` array keys instead of `arguments` key.

In `bartik_modificado_theme` function, we should use `render element` as `form`.

> render element: (required if "variables" not present) A string that is the name of the sole renderable element to pass to the theme function. The string represents the name of the "variable" that will hold the renderable array inside any optional preprocess or process functions."

Code snippets in `template.php` in theme directory.

```
/**
 * Implements hook_theme
 */

function themename_theme() {

  return array(
    'user_login_block'=> array(
        'render element' => 'form',
        'template' => 'user-login-block',
      )
    );
}

```

I have created new `tpl` file `user-login-block.tpl.php` in theme directory.

Code snippets in `user-login-block.tpl.php` file.

```
unset($form['links']['#markup']);
print drupal_render_children($form);

?>

```
> -1 votes

---
Tags: blocks, theming, users
---


# Question
Title: Is it possible to display a content type (availability calendars) inside a Forms API form?
I read how FAPI is very flexible. Well I started using it and after a few minor issues I have it working for a good deal of a multi-part form. (Using #state and fieldset) Now I want to embed an Availability Calendar in the form and I can not figure out if it is possible. The newest Availability Calendar is based on entities and fields. My FAPI/module form is just that, a straight forward form. To expose an Availability Calendar I have to create a content type. So I am stuck with a content type instance and my own form module, trying to figure out if I can merge the 2.

I'd *really* like to keep the calendar inside the form in its own collapsible section (via fieldsets), only exposed in the UI when the user has selected other info. This means I either embed Calendar inside a form, or possibly a form inside the Content Type.

Any pointers ? Am I missing something to glue these parts together? I considered EntityForms but it doesn't seem flexible enough to make nicer forms. (radios?) My only solution may mean splitting Avail Calendar off on its own page and make it part of a series in a multi-part form.

I don't mind writing php, I am likely going to modify Availability Calendar booking formlet.

# Answer
> 0 votes
To add a form inside already existing form you can try out the following:

```
$form['another_form'] = array(
'#markup' => drupal_get_form($form_id);
);

```

---
Tags: forms, nodes, datetime
---


title: Is there a module to modify messages?

text:
# Question
Title: Is there a module to modify messages?
I am looking out to change the message displayed after user registration submits the user details. Is there a module to achieve it, or do we need to hard code the message to display?

# Answer
Sounds like you're looking for String Overrides. It will work with any string that is handled in the proper manner (ie, it is run through `t()`), not just messages.
> 4 votes

# Answer
I think what you're probably looking for is a way to redirect the user to a custom page after they register. Check out the Logintoboggan module which gives you the option of where to send the user after they register.
> 1 votes

---
Tags: 7
---


# Question
Title: View that uses both taxonomy terms and title(or nid) in contextual filters
Is it possible to create a view that uses both taxonomy terms and the node title or nid as contextual filters?

Ideally this would mean that you could have one view that just handled the taxonomy terms eg. the `parent-taxonomy-term/child-taxonomy-term` view would display all the nodes matching those taxonomy terms and `parent-taxonomy-term/child-taxonomy-term/node-title` would display a different view with more information on the specific node returned.

Is such a view possible and if so how would i set it up (all my experiments at this have failed)?

The reason I require this is that I wish a view of the same node to be accessible via a number of different taxonomies. I am creating a store where users can see the same gold diamond ring by navigating on the main dropdown menu via 'Jewellery \> Rings', 'Gemstones \> Diamond' or 'Metal \> Gold'. While the user is navigating in this way the breadcrumb trail and url are looking good 'jewellery/rings' etc. But when a product is clicked on and its node is viewed it has its own url that can only fit the pattern of one of the taxonomies. So the breadcrumb trail would suddenly change when getting to the product via another taxonomy.

# Answer
I wasn't able to find a neat solution to this problem.

What I ended up doing was manually creating a page view from each taxonomy e.g. `metals/gold/%` and passed it the node title through contextual filters. This meant I was able to create a view of the correct product and the Easy Breadcrumb trail still looked good and a single product may exist in multiple breadcrumb trails. This works but isn't an elegant solution.

It would be great to find a solution to this that didn't need manual creation of page views. So any further thoughts on this are appreciated.
> 0 votes

---
Tags: 7, views
---


title: Ordering Users for use in view

text:
# Question
Title: Ordering Users for use in view
I have a view that displays data for each user. Now I would like to be able to order the users.

One solution would be to add a new field called something like `field_weight` to the user content type and then use this field to sort the view, but preferably I would like to do this through drag and drop from the `admin/people` configuration page.

I installed the weight module, but it doesn't seem to support setting the weight for a user.

Is there a module that can do this?

# Answer
If I haven't misunderstood your question and you're using `Views`, you could simply sort the view by your `weight_field` and then just assign the right weight parameter to the user.

If you prefer some kind of drag and drop functionality (which in my opinion is easier to manage than weight) you could use Draggable Views, this module will allow you to have a view where you can order your users display, a good tutorial I used as a first timer is this.
> 1 votes

---
Tags: 7, users, views
---


# Question
Title: jquery.cookie.js is loaded only for authenticated users, by jQuery update module
jquery.cookie.js is loaded only for authenticated users and i cannot really figure out why. The page caching is disabled.

Any thoughts?

# Answer
> 13 votes
The `jQuery.cookie` library is not always included, it depends the user state and the visiting page.

For example, the login form includes this library by attaching (`#attached`) it to the form.

What you could do is include it yourself in a custom module or in your theme.

```
// hook_init()
function YOURMODULE_init()
{
     drupal_add_library('system', 'jquery.cookie');
}

// or in theme preprocess
function YOURTHEME_preprocess_page(&$vars)
{
     drupal_add_library('system', 'jquery.cookie');
}

```

---
Tags: 7, javascript, cookies
---


# Question
Title: What would make all content of a certain type return a 404 on the node page?
When trying to view/edit nodes of Content Type X, drupal returns a 404 - Not Found. All other content on the site (content of other node types) seems unaffected.

To eliminate other issues with clean URLs, path or path auto, I'm using the `q` param to access the nodes (`example.com?q=node/123`, `example.com?q=node/123/edit`), so it's not something silly like that (not likely anyway since all of the other site content renders fine at the expected URLS).

To be clear, drupal seems completely unaware of these nodes. Filtering by this content type on the `admin/content/node` page returns "No posts available". However, I happen to have a Views Bulk Operation view that modifies a CCK field for these nodes and that page *does* show all of them with the proper titles and everything. Trying to modify that CCK field with the VBO has no effect though (the field is not updated).

**What I was doing before this happened:**
I recently installed a new theme. Unfortunately, I can't confirm or deny that this started happening as a direct result of the theme. I would expect any error caused by this to result in 500 errors anyway. Or possibly 403 errors because I do use `drupal_access_denied()` in some custom modules - but not `drupal_not_found()`.

**What I have looked into while troubleshooting:**

* The node table looks fine. The rows referring to these nodes remain and appear unchanged.
* All of the CCK tables (`content_type_x`, `content_node_field`, `content_field_abc`, etc) look fine.
* The `menu_router` table rows for `node/%`, and `node/%/edit` are fine (but like I said, this is just one content type and I would think that something wrong with those rows would break all content types). (All of these database checks seem unlikely anyway since I haven't touched the DB directly or modified much of anything recently.)
* I have rebuilt the permissions on site content (`/admin/content/node-settings/rebuild`).
* The watchdog table records the 404, but nothing else.
* The Status Report page is all green.

I realize that this is a pretty esoteric question, but I'm hoping something in the above rings a bell with someone.

This site is (still) running on Drupal 6.

# Answer
> 2 votes
The author of the nodes in question (just happened to be the same author for all of the nodes in this content type) was missing from the `user` table. To be clear, the user was not properly deleted - the row was simply removed from the database.

I'm guessing that this caused the `db_fetch_object()` function to fail within `node_load()` when it tried to JOIN the `user` table on the nonexistant `uid`:

```
$node = db_fetch_object(db_query('SELECT ' . $fields . ' FROM {node} n INNER JOIN {users} u ON u.uid = n.uid INNER JOIN {node_revisions} r ON r.vid = n.vid WHERE ' . $cond, $arguments));

```

But it failed completely silently - I that's guess because this scenario would never happen if the user had been deleted properly (Drupal 6 automatically sets the Author of all content created by a deleted user to Anonymous (uid == 0).

Lot's of red herrings while troubleshooting, but maybe this will help someone in the future that doesn't realize they're using a half-sanitized database.

---
Tags: 6, nodes
---


# Question
Title: How to add a tooltip popup containing social share widgets in a views table
I have a views table containing a number of columns, one contains a small icon. I would like to have a tool tip open (containing the usual share widgets: twitter & facebook) when the image is clicked.

Could anyone suggest a way to achieve this?

# Answer
There are a lots of modules providing tooltip functionality.

If you are familar with php coding:
1. Install Views PHP (https://drupal.org/project/views\_php)
2. Install BeatuyTips (https://drupal.org/project/beautytips)
3. Create a PHP-field in your view and add the following code (Best is to include in your own module)

```

function render_socials($data = NULL){

  //if the links and icons are displayed inside the view, you can use $data

  $output .= l(theme('image', array('path' => 'PATH_TO_SOCIAL_ICON')), 'LINK_TO_SOCIAL_PROFILE', array('attributes' => array('class' => array('a.row-' . $data->nid . '-socials-popup')), 'html' => TRUE));
  $output .= l(theme('image', array('path' => 'PATH_TO_SECOND_SOCIAL_ICON')), 'LINK_TO_SOCIAL_PROFILE', array('attributes' => array('class' => array('a.row-' . $data->nid . '-socials-popup')), 'html' => TRUE));
  $output .= l(theme('image', array('path' => 'PATH_TO_THIRD_SOCIAL_ICON')), 'LINK_TO_SOCIAL_PROFILE', array('attributes' => array('class' => array('a.row-' . $data->nid . '-socials-popup')), 'html' => TRUE));
  $output .= l(theme('image', array('path' => 'PATH_TO_ANYOTHER_SOCIAL_ICON')), 'LINK_TO_SOCIAL_PROFILE', array('attributes' => array('class' => array('a.row-' . $data->nid . '-socials-popup')), 'html' => TRUE));
 }

$options['socials_' . $data->nid] = array(
         'cssSelect' => 'a.row-' . $data->nid . '-socials-popup',
         'text' => _render_socials($data),
         'trigger' => array(0 => 'mouseover', 1 => 'click'),
         'width' => 350,
       );
 print beautytips_add_beautytips($options);

```
> 0 votes

---
Tags: views, entities, tooltips
---


title: Page Argument in Title

text:
# Question
Title: Page Argument in Title
How can I have the page argument appear in the page title?

```
    $items['path/path/%'] = array(
    'title'            => t('Dynamic Title %1'),
    'page callback'    => 'pagecallback',
    'page arguments' => array(2),
     'type'             => MENU_CALLBACK,
    'access arguments' => array('access content'),
  );

```

Is there some kind of text replacement or something you can use in there, or is what I'm asking impossible?

# Answer
> 4 votes
You can use a `title callback` function along with `title arguments`:

```
$items['path/path/%'] = array(
  'title callback' => 'MYMODULE_page_title',
  'title arguments' => array(2),
  'page callback'    => 'pagecallback',
  'page arguments' => array(2),
  'type'             => MENU_CALLBACK,
  'access arguments' => array('access content'),
);

function MYMODULE_page_title($arg) {
  return t('Arg is: @arg', array('@arg' => $arg));
}

```

The default `title callback` is `t()`, so if you just need the argument to be passed straight through as the title you can get away with just using `title arguments`.

See `hook_menu()` for more details.

---
Tags: routes
---


# Question
Title: Fivestar being cached for anonymous users!
On enabling caching for anonymous users, it appears that the fivestar votes are also being cached, which is super-weird.

On disabling caching for anonymous users, things work great.

We use memcache, could that be a problem? Any suggestions about how I should go about this?

From **https://drupal.org/node/285855**

> "When "Caching mode" is enabled (admin/settings/performance), anonymous users don't see changes in rating. Every anonymous user see rating as it was when first anonymous user visited node.
>
> When cache is disabled anonymous users see rating correctly.
>
> Is there some way how to use Drupal caching and at same time make fivestar working for anonymous users?"

**Fix -:**

> "Change caching time to 1-5 minutes, will make it seem that as the amount of time it took for his vote to register."

Is this the only possible fix?

# Answer
Rather than rendering the Voting widget with the rest of the page, I would add a delayed (ie. on page-load) AJAX request for every widget which would do a back-end call, render the widget (without pulling in a cached version) for the appropriate node/piece of content, and inject it back into the DOM.
> 2 votes

---
Tags: rating, caching
---


# Question
Title: How to install drush on a restricted shell access account? Media Temple shared environment
I'm working with a client that has a media temple server (gs)-gridserver. its a shared environment, but i do have access to the shell.

How would i go about installing drush for an account like this?

# Answer
> 5 votes
1. Place drush into your home (~) folder under something like `~/drush/`
2. Create or edit `~/.bash_profile` and add the following: `alias drush='~/drush/drush'`; this creates an alias called 'drush' that will execute drush's main file.
3. If you need to specify which version of PHP to use, add `export DRUSH_PHP=/path/to/php`.
4. Run `source ~/.bash_profile` to reload the `.bash_profile` file.

At this point you should be able to use the `drush` command.

In unrelated news: if you can, move your client off MediaTemple. Their database servers are in a physically different location from their web servers, which is an absolute nightmare for applications with a ton of database queries (read: Drupal).

---
Tags: drush
---


title: Customer render $scripts and $styles

text:
# Question
Title: Customer render $scripts and $styles
Short of replacing html.tpl.php and calling drupal\_get\_js/drupal\_get\_css functions and tweaking the output as required...

How else can I drop some of the JS or CSS that drupal (D7) seems to include in the resulting markup??

The ajaxPageState object is quite confusing I would rather start from minimal markup and stuff and build from what I know.

Any ideas/???

# Answer
You can do this with some alter hooks in your themes template file.

```
/**
 * Implements hook_css_alter().
 */
function YOURTHEME_css_alter(&$css) {
  // Remove stylesheets not required
  unset($css['sites/default/themes/YOURTHEME/css/STYLESHEET.css']);
}

/**
 * Implements hook_js_alter().
 */
function YOURTHEME_js_alter(&$js) {
  // Remove scripts not required
  unset($js['sites/default/themes/YOURTHEME/js/SCRIPT.js']);
}

```
> 0 votes

# Answer
You would like to check Mothership theme, which does exactly what you want.
> 0 votes

---
Tags: theming
---


# Question
Title: How to solve "This version is not compatible with Drupal 7.x and should be replaced" error?
I keep getting, "This version is not compatible with Drupal 7.x and should be replaced." error. Could you please look at the content of my .info file and tell me what is wrong with it:

```
name = jeanb
description = sub-theme based on Bartik.
base theme = bartik
engine = phptemplate

stylesheets[all][] = css/jeanb.css

regions[header] = Header
regions[help] = Help
regions[page_top] = Page top
regions[page_bottom] = Page bottom
regions[highlighted] = Highlighted

regions[featured] = Featured
regions[content] = Content
regions[sidebar_first] = Sidebar first
regions[sidebar_second] = Sidebar second

regions[triptych_first] = Triptych first
regions[triptych_middle] = Triptych middle
regions[triptych_last] = Triptych last

regions[footer_firstcolumn] = Footer first column
regions[footer_secondcolumn] = Footer second column
regions[footer_thirdcolumn] = Footer third column
regions[footer_fourthcolumn] = Footer fourth column
regions[footer] = Footer

settings[shortcut_module_link] = 0

; Information added by drupal.org packaging script on 2013-04-03
version = "7.22"
project = "drupal"
datestamp = "1365027012"

```

Thank you!

# Answer
As per Writing theme .info files, `core` is a required key. You just need to add

```
core = 7.x

```

to make your theme compatible with Drupal 7.
> 14 votes

# Answer
You have to include this:

regions\[content\] = Content

This is new in Drupal 7, now content is a block.
> 7 votes

---
Tags: .info
---


# Question
Title: Add a 'Buy-it-Now' button to an ApacheSolr View
So I have built a View that uses Apache Solr to display products on my Ubercart site from the Solr index. Swell. Now Ubercart typically lets me add a 'Buy-it-Now'/ Add to Cart button as a field in most views but for some reason in this view that is not possible.

How do I add a 'Buy-it-Now'/ Add to Cart field to this view?

# Answer
> 0 votes
Okay so I was not able to try out gj. 's answer because I figured this out using the Views Field View module.

I created a sub view called 'Buy it now Button'. This view displays just a buy it now button field with one result that takes a contextual filter with Node ID as an argument. I added the view 'Buy it now Button' as a field in my faceted search view and everything works fine.

The only thing extra to note was that I had to add an invisible Node ID field to the search view which I could then pass as an argument to the View Field (conditional arguments are supported by Views Field View)

# Answer
> 0 votes
You can use one of the hooks provided by apache solr to alter your search results : `hook_apachesolr_process_results`

and you could append 'Buy it Now' button as well by using `hook_theme()`

Apache solr hooks

---
Tags: ubercart, search, views
---


# Question
Title: Update module with Drush + commit with Git
What's the best way to update a module and commit with git?

Currently I'd use `drush pm-updatecode` then inspect with `git status`. The problem then is there are many files that have changed, been added or been deleted. Then performing an `add` or `rm` on the right files seems a bit cumbersome.

Would it be better to first do `rm` on the module, commit, then `drush dl`, `add`, `commit`?

# Answer
> 7 votes
`git add -A` is the simple answer you are looking for. It will add all of the files anywhere inside the current working directory, including any new files that were provided or removed pm-updatecode. (Note: `git add .` behaves similarly to `git add -A`, except that it will not include removed files in the commit.)

There is one inconvenience with `git add -A`, though, and that is that if you have any stray files in the way, they will be added to the repository as well (obviously enough). You can get around this problem by listing the files that should never be committed in a .gitignore file, or simply use `git reset HEAD unwantedfile` prior to `git commit`, as recommended by `git status`.

`drush` will manage this for you with the --version-control=svn option, but as you may surmise, this is only useful when you project is checked in to svn. As of yet, no one has written --version-control=git. This was discussed in http://drupal.org/node/797190, but closed "won't implement". There are some other good git commands to try in that thread as well.

# Answer
> 1 votes
If you are updating the Views module for example, you can do the following:

```
drush up views
git add /sites/all/modules/views
git commit -m 'views update'

```

This way only the changes in your views folder will be added to staging before commit.

# Answer
> -1 votes
```
git rm -r module
drush dl module
git add module
git commit -m "Upgrading module"
git push origin master

```

---
Tags: drush, version-control
---


# Question
Title: How do you output and modify the Content:Path variable using field:PHP global?
I'm trying to modify the content:path variable using PHP field in Views for Drupal 7. The $data and the $row-\>path gives a blank result. Anyone know why?

It seems that I can grab it via the $views variable, but i have to dig deep into it in order to find it. Is there an easier to to access the content:path field via PHP in views?

# Answer
To get the content id path data I had to get it from the $view variable:

```
$view->style_plugin->render_tokens[0]['path']

```

As seen below the $row-\>path data is NULL for some reason. Same goes for $data variable as that doesn't have any data at all.
> 0 votes

---
Tags: entities, views
---


title: Custom HTML link is not working

text:
# Question
Title: Custom HTML link is not working
I have used a custom html link More search results to link to the homepage. When clicking the link,I am taken to this url`http://localhost/homepage` instead of the correct one `localhost/cars/homepage` What am I doing wrong? thanks

# Answer
Your site is installed in the /cars folder, but you're pointing to the root of the server by using the forward slash at the front of your HREF. You should use Drupal's `l()` function to generate a proper link:

`<?php echo l(t('Homepage'), 'homepage'); ?>`
> 1 votes

---
Tags: theming
---


# Question
Title: Drupal PHP views - how to reference nested braket array variables?
I did a dpm() on the path variable i have and I'm running into the issue of figuring out how to reference this variable. When I do a print\_r() on the variable it shows that its \[\[path\]\]

I'm not sure how to reference that. I thought it might be $var\[\['path'\]\] but that doesnt work.

# Answer
> 1 votes
You're almost there, since the square brackets are part of the string they need to go inside the quotes, e.g.

```
$var['[path]']

```

---
Tags: 7, views
---


# Question
Title: Drupal Less cache keeps generating cache file that does allow access to the apache server
How do I ensure that auto-generated css cache files (related to the Less module) are being generated with the permissions necessary for the server to access.

Currently, whenever I clear all caches (with `drush cc all`), I lose all of my site's css styles and get the following error:

> LESS could not create a directory in sites/default/files/less/52741f7e343834.56376384/sites/all/themes/my\_custom\_theme/css

When I go to look at the permissions (`ls -l`) for the files in `sites/default/files/less`, the directory `52741f7e343834.56376384` (which I assume is the new cache file the server is trying to create the other stuff in) it has the wrong ownership `<correct-user>:<correct-user>`, rather than `<correct-user>:apache` (it's centos, so that's the apache server group). All the other cache directories have the correct owner permissions.

So how do I ensure that the system is creating these cache files properly such that I don't have to set the file ownership every time I clear the cache to get my styles back?

This is a new problem for my site and I suspect it is because I updated the Less module for Drupal 6 and added the lessphp library to my site (though perhaps I am mistaken).

# Answer
> 1 votes
I do three things.

1. I put myself in the apache group.
2. Set my umask and the httpd process to 0022
3. chmod sites/default/files to 2775

The first step lets me write to the directory. The second step makes sure that files I create have group write permission, and that apache does the same. The third step tells the OS to always use the group of the directory owner.

You should then be able to drush cc all and have Apache create the LESS files.

For your initial fix, you may have to fix up the perms recursively. Eg,

```
chown -R apache.apache docroot/sites/default/files/
find docroot/sites/default/files/ -type d -exec chmod 2775 {} \;
find docroot/sites/default/files/ -type f -exec chmod 664 {} \;

```

I would also suggest reading Securing file permissions and ownership. The comments have a good duscussion about the setgid bit and potential downfalls.

---
Tags: 6, caching, files, theming
---


title: custom template file based on form type

text:
# Question
Title: custom template file based on form type
I'm using Omega's sub-theme *creativpink*. I put my site on web for testing purpose. Basically I want to customize page-user-reset page (*user-pass-reset* is form id). Now I click *Request new password* link enter my mail id to send password reset link. When I click on that link from my mail it redirects to page-user-reset page and it shows the following information:

`## Site Name

* Home

### Reset password

* This is a one-time login for *username* and will expire on Fri, 11/01/2013 - 20:41.
* Click on this button to log in to the site and change your password.
* This login can be used only once.
Login(button)`

`Powered by Drupal`

Currently it includes header, breadcrum, content and footer regions. But I want only content region and the *user password reset* form inside content region. So I would like to write a template file based on this *user-pass-reset* form. Guide me what I want to do this? Thanks in advance.

# Answer
> 0 votes
You should be able to create a `page--user--reset.tpl.php` template in your theme directory alongside any other page reset templates and just include the `content` region inside there. More information about template and theme hook suggestions can be found here (or at least after drupal.org comes back from its upgrade :) but the basic idea is to override the internal path of `user/reset/../..` and Drupal is smart enough to ignore the rest of the path and just use the template given the base here.

# Answer
> 0 votes
Yes, it's worked for me. Also I referred to the Change templates based on path alias link here. I did some modification to my `MYTHEME_preprocess_user_reset_page()`:

```
function MYTHEME_preprocess_user_reset_page() {
  $alias_parts = explode('/', drupal_get_path_alias());
  // dpm($alias_parts);
  if (count($alias_parts) && $alias_parts[1] == 'reset') {
    $vars['theme_hook_suggestions'][] = 'page__user__reset';
  }
}

```

Then in `page--user--reset.tpl.php` file I include only title and content of the page. Thank you so much and Clive too.

---
Tags: theming
---


# Question
Title: how to use Profile information for payments
I am using the customer\_profile\_type\_ui as a way of displaying different checkout pages for different types of purchases. (this is the exact scenario which the readme file described as its use, and I followed it). But now I have an issue: payments. I am using the Authorize.net contrib, and it says in its home page -

> The Payment checkout pane must come after the Billing information checkout pane for Drupal Commerce to be able to populate the order used to generate transactions with a billing address before this module attempts to process payment.

When you follow the profile\_type\_ui readme, it says to use rules to disable all panes (which would include 'billing information' and then enable the appropriate profile pane. I followed this advice, because the billing pane didn't have all the fields I wanted.

When I looked at the email invoice (developer email), it did not have values for the billing information, as expected (or shipping, but I'm selling memberships, so we wont be using shipping).

The only possible thing I saw was a checkbox on the billing page settings page which said

> Enable profile copying on this checkout pane, helping customers avoid having to enter the same address twice.

but it didn't do anything. Any ideas?

# Answer
> 0 votes
It sounds like you're using a custom module with instructions that run counter to the Authorize.Net instructions. Is that what you mean by customer\_profile\_type\_ui? I assume that isn't part of the core Commerce Customer module, so a link would be helpful, but honestly it looks like you've already answered your own question.

I don't really get why you'd disable the core Billing information checkout pane for having insufficient fields. If you add a field to your billing customer profile type, it will show up in the checkout form. What else would you need to do besides that?

---
Tags: commerce
---


title: Keep locations in drupal

text:
# Question
Title: Keep locations in drupal
I have created a form where customers select two fields for a transportation. From `origin` to `destination`. My list of geographical locations could be close to 5,000 records. What is the best way to keep this location in the database? Taxonomy or store as a list for selection on each field?

Any recommendation is more than welcome. I'd need to store something like this:

El Salvador SVCSC Cara Sucia Cara Sucia, SV SVCSC|Cara Sucia, SV

El Salvador SVCNG Chalatenango Chalatenango, SV SVCNG|Chalatenango, SV

An important point is that I need users to select this with autocomplete like any airline website does (Kayak, Hipmunk, etc).

# Answer
> 1 votes
You should create a content type Locations

and add the following as form fields 1.cities 2.states(Provinces) 3.countries

Use two modules

1. Entity Reference
Use a field entity reference in your custom form for origin and destination with content type locations
2. Tokens 3. Auto nodetitle
By installing the tokens and auto node title you can set the title for locations as per your needs like \[field:cities\]|\[field:province\]|\[field:country\] in the edit link of content type locations

the title u set for the content type will be used in the origin and destination field . You can set your field as autocomplete as well as follows:

```
function module_name_menu() {
  $items['location/autocomplete'] = array(
    'page callback' => '_module_name_autocomplete',
    'access arguments' => array('access location autocomplete'),
    'type' => MENU_CALLBACK
  );
  return $items;
}

function module_name_form() {
  $form = array();

  $form['origin'] = array(
    '#title' => t('origin'),
    '#type' => 'textfield',
    '#autocomplete_path' => 'location/autocomplete',
   );

  $form['destination'] = array(
    '#title' => t('destination'),
    '#type' => 'textfield',
    '#autocomplete_path' => 'location/autocomplete',
   );

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

  return $form;
}

function _module_name_autocomplete($string) {
  $matches = array();

  $query = db_select('locations', 'loc');
     ->fields('loc', array('title'))
    ->condition('c.title', '%' . db_like($string) . '%', 'LIKE')
    ->range(0, 10)
    ->execute();

  // add matches to $matches
  foreach ($return as $row) {
    $matches[$row->title] = check_plain($row->title);
  }

  // return for JS
  drupal_json_output($matches);
}

```

---
Tags: taxonomy-terms
---


# Question
Title: Generated: not cached yet (either no one has visited the page recently, or something is preventing the cache from being generated).
I just spin a test Drupal7 site and having some issue w/ getting boost module to work(

```
$ cat /etc/redhat-release
Scientific Linux release 6.4 (Carbon)
$ uname -a
Linux XXX.XXXXX.XXX 2.6.32-358.23.2.el6.x86_64 #1 SMP Wed Oct 16 11:13:47 CDT 2013 x86_64 x86_64 x86_64 GNU/Linux
$ rpm -q drupal7 php php-pecl-apc
drupal7-7.23-3.el6.noarch
php-5.3.3-23.el6_4.x86_64
php-pecl-apc-3.1.9-2.el6.x86_64
$ drush -r /usr/share/drupal7/ -l alexustest pm-list | grep '(boost)'
Performance and scalability  Boost (boost)                                  Module  Enabled        7.x-1.0-beta2
$

```

this is what I get via "Boost: Pages cache status" block:

> File: cache/normal/alexustest/\_.html
>
> Generated: not cached yet (either no one has visited the page recently, or something is preventing the cache from being generated).

I'm not sure what I am doing wrong. Can someone help me?

# Answer
> 1 votes
Please logout, visit same page as anoymous user then login and visit again. I think you can see cached page message.

---
Tags: caching, proxies
---


# Question
Title: Can Drupal Commerce and Ubercart be installed on the same site?
Can Drupal Commerce and Ubercart be installed on the same site or will they conflict with eachother?

# Answer
> 2 votes
These two modules define the same menu entries - so you can use only one of them.

# Answer
> 0 votes
Nope, they can be installed together. In admin menu there will be two tabs Store etc. Maybe there are some conflicts but I have not noticed yet.

---
Tags: 7, commerce, ubercart
---


# Question
Title: How to send user to the billing information page immediately after logging in?
I am creating a subscription site using Drupal commerce. My site uses logintoboggan to login a user after creating an account. I am planning to create an order programmatically and then redirect the user to the page where they can enter their credit card information and billing information. I have not figured out how to redirect them to that page yet. Any help would be appreciated.

# Answer
Check out Login Destination module - it allows you to define destination rules for logging in/registering users and even use PHP snippets for custom conditions.
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: Quickest Way To Create a Pre-Register Form
I'm looking to allow users to "Pre Register" for a new site (actually I'll use this for a standard 'template' process), I want to get users to sign up so I can keep them informed of news, updates etc on launch and want to get this function installed quickly. I'm not really want to 'hack' template.php at this stage (later maybe with ongoing development) so just need a really simple approach which will sign them up, subscribe to a newsletter and give registrants the normal 'subscribe/'unsubscribe' from within email contents. I have two roles, so can code the layout with simple "Sign Up" links going to relevant registration forms. In your opinion, what would be the best approach, maybe I should use a Rules structure (and tie in things like Coupon Codes/incentives) or would you suggest a different process?

PS:
Just like to add, that I use a process for pre-registration users to sign as up as such: 1st level - as a 'temp' role, then the user cannot go any further until they join one of either 2 roles (one free, one paid for services).

In following the accepted response below, I'll set the Notify up for a 'temp 'user then the user can choice on 'launch' the Role route they wish to sign up for. Hope that helps readers. (-:

# Answer
What you suggest (using Rules for this) is far too complicated for me.

To do this with the minimum hassle, I would just set up a standard Drupal site and create a fixed front-page that says: "Pre-register for my great new site." Configure permissions so that if the logged in user doesn't have admin permissions, all he/she is allowed to see is this fixed front page.

Then use String Overrides to replace the text "Create new account" in the login box with the text: "Click here to pre-register". I.e. the by "pre-registering", the user really creates a standard account on the site.

Then auto-subscribe everyone that pre-registers to a newsletter (for a newsletter module you can, for example, use Notify). This will let you post updates on the site about the ongoing development, etc. that *also* are automatically sent to those who've pregistered as a digest newsletter e-mail. (Notify let you auto-subscribe new users and also has a master switch to make subscribing and unsubscribing a breeze).

Later, when you've done setting up the site, you can ask the user to confirm his/her committment by ticking some field in the user profile, and silently convert those that confirm to regular users by given additional access permissions (and delete the rest).

Disclosure: I am the maintainer of Notify.
> 2 votes

---
Tags: users
---


# Question
Title: How can I make a view that shows users all the who have flagged a single user?
**Background**

I want to add a tab to the user profile that shows the logged in user which other users have viewed his/her profile. I want to control this list in Views.

Until recently, I have been using the User Visits module. However, this module does not integrate with Views and is no longer actively maintained.

I started building this using Views, Rules, and Flag. Specifically, I created a flag **Viewed profile**, and then made a Rule to automatically flag a profile when a user visits another user's profile.

I then created a view of users with two displays.

**My View**

The first display, *Profiles I visited*, has a relationship to the **Viewed profile** flag and simply lists all profiles flagged (visited) by the current user. Easy.

Now I want to create a second display, *Users who have visited me*. In this case, I want to display all the users who have flagged the current user. However, I can't figure out how to do this.

I can add a relationship, *Flags (by any user)*, but there could quickly be 10,000+ such flags on my site, so I am worried about the performance implications of loading all the flags like that. Also, even if I load all the flags, I don't see how to easily filter them to users who have flagged the current user.

Instead, it seems like it would be easier to create a second flag, **User who viewed me**, and attach both flags (**Viewed profile** and **User who viewed me**) with a rule at the same time when a user visits a profile. However, this seems like unnecessary duplication of information to me, since both flags link the same two users at the same time. Is there a more elegant way to display this data in Views that will not lead to performance issues down the line?

# Answer
> 0 votes
1. Add a relationship, **Flags: User's flaggings** for your flag. Uncheck *Include only users who have flagged content.*
2. Add a contextual filter, **Flags: Content ID** and set *Provide default value* to *User ID from logged in user*.

This was not intuitive, but it appears to do the trick.

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


# Question
Title: Drupal 7 dpm an object, but not sure how to render a recursion variable?
In Drupal 7 Views php. I'm trying to render and string replace the content:path field by using a global PHP views field. The issue I'm having is i'm not sure how to reference the content:path field as $row-\>path shows a NULL value. I can see that the content:path variable exists in the $view object, but it shows **recursion**. How would one render a recursion value to show up when I do a print?

# Answer
> -1 votes
you just need to dpm() or print\_r() the recursion variable. Basically for the listed recursion variable that krumo displays, you just put in that variable inside dpm() to view inside the recursion variable. If you don't do this and just dpm() the parent of it, you'll get that recursion infinity sign. hope that makes sense.

---
Tags: 7, views
---