# Question
Title: How to provide default value with PHP code for a field in Views 3
So I'm trying to create a View, displayed in a Block, that will show a list of nodes that reference the same parent node as the node I'm currently in. The reference is a custom field using the References module. I'm on Drupal 7 with Views 3.

I figure I'll setup a Contextual Filter on my custom field (field\_ref\_photo\_gallery) and I need to provide a default value via PHP code.

How should I write that PHP code in the most Drupal 7-ish way?

Should I go with something like:

```
return node_load($nid)->field_ref_photo_gallery['und'][0]['value'];

```

(I'm not even sure that would work. I just threw that together in this post)

Or is there a field API function I should be calling?

# Answer
You can pass currently viewing nodes id in contextual filter without using any custom code.

In contextual filter settings, under **When the filter value is NOT in the URL** select **Provide default value** option. Then there is a dropdown will show. Then select **Content ID from URL**. See the image:
> 2 votes

# Answer
In views 3 the "Contextual Filters" is located in the "Advanced" field set. Adding contextual filters also known as arguments will help display the appropriate content. One may also use "Relationships" in conjunction to add more fields or filters to your view.
> 0 votes

# Answer
Try views\_php module to add custom PHP code on views filter.
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to make Views rows clickable with jQuery
I am trying to follow Jimajamma's instructions here to make my Views rows clickable.

My View class =

```
.clickable-row .views-row {
border:12px solid purple;
}

```

My js file shows ok in the page source here

I am not sure which field is meant by "as long as one field in your view is a **link**" - I have tried Content: Link, Content: Path and Content: Nid.

Result here \- purple border rows are not clickable.

Can anyone please suggest what I am missing?

# Answer
Please change your JS code to below given one and try again. It should be working.

```
Drupal.behaviors.clickableRowsOnViews = {
  attach: function() {

    jQuery('.clickable-row .views-row').each(function() {
      if (jQuery(this).find('a').length) {
        jQuery(this).click(function() {
          window.location = jQuery(this).find('a').attr('href');
          return false;
        });
      }
    });
  }
}

```
> 3 votes

# Answer
First of all, take a look on the javascript guide on drupal.org : https://drupal.org/node/756722 Here you can find Why you need to use the "Drupal" object and a good javascript pattern file.

Now an answer :

You using view, so you can display your results with a special class on your links for target them later in your javascript. ".clickable-row" Class are on the block, maybe you should attach this class on each row like this screen

Next, we can attach the special class on any field in field display setting like this:

Now when you render view, the link have a class we can use for target it with jQuery See the DOM and HTML render

Our view is ready ! Next Step, Javascript.

1) Include your javascript

Follow the documentation below to add it.

2) Javascript Content

I use a simple javascript canvas, i will use and explain it :

```
 /**
  * Javascript Drupal Bootstrap File
  */
(function ($, Drupal, window, document, undefined) {
    // Application global variable
    // You can share data only here
    var app = {};

    // InitApp
    // Bootstrap app configuration
    function initApp(){
        app.drupal          = Drupal.settings.your_module_namespace;
        app.$clickableRow   = $('.clickable-row');
    }

    // attachEvents
    // Here you bind all your jQuery event for example
    function attachEvents(){
        // On each clickable row, we apply our js feature
        app.$clickableRow.click(clickableRowFeature);
    }

    // Click event callback
    function clickableRowFeature(event){
        // Apply jQuery on current clicked element
        var $this   = $(this);
        // Get the url if exists
        var url     = $this.find('.useThisLink a').attr('href');
        if(url){
            // Redirect the user to url location
            window.location = url;
        }
    }
    // Here you can have others behaviors, "your_module_namespace" must be unique !
    // Behaviors can be called many time, if you don't want reboot your app
    // you can use an initialized variable
    Drupal.behaviors.your_module_namespace = {
        attach: function (context, settings) {
            if(!app.initialized){
                initApp();
                attachEvents();
                app.initialized = true;
            }
        }
    };
})(jQuery, Drupal, this, this.document);

```

This should be work if you have follow previous steps. A little extra, the code after work with your current view

```
 /**
 * Javascript Drupal Bootstrap File
 */
(function ($, Drupal, window, document, undefined) {
    // Application global variable
    // You can share data only here
    var app = {};

    // InitApp
    // Bootstrap app configuration
    function initApp(){
        app.drupal          = Drupal.settings.your_module_namespace;
        app.$clickableRow   = $('.clickable-row .views-row');
    }

    // attachEvents
    // Here you bind all your jQuery event for example
    function attachEvents(){
        app.$clickableRow.click(clickableRowFeature);
    }

    function clickableRowFeature(ev){
        var $this   = $(this);
        var url     = $this.find('.field-content a').attr('href');
        if(url){
            window.location = url;
        }
    }
    // Here you can have others behaviors, "your_module_namespace" must be unique !
    // Behaviors can be called many time, if you don't want reboot your app
    // you can use an initialized variable
    Drupal.behaviors.your_module_namespace = {
        attach: function (context, settings) {
            if(!app.initialized){
                initApp();
                attachEvents();
                app.initialized = true;
            }
        }
    };
})(jQuery, Drupal, this, this.document);

```

That's done !
> 3 votes

---
Tags: views, javascript
---


# Question
Title: How to display jQuery UI dialog in submit button's onclick and prevent form submission?
I'm using Drupal 7 and jQuery Update module set to jQuery version 1.8. I have a form. In it's definition I have:

```
$form['#attached']['library'] = array(
  array('system', 'ui.dialog'),
  array('aat_pc_product', 'product_form'),
);

```

In the behavior, I use:

```
if(!isFormValid) {
  $('<div>' + Drupal.t('Some fields was left blank even when not disabled. Either check "skip line" or fill missing data.') + '</div>').dialog({ modal: true });
}

return isFormValid;

```

Now, with good old `alert` it worked great. But when I try do use `dialog`, in chrome in my console I get:

> Uncaught TypeError: Object function (a,b){return new p.fn.init(a,b,c)} has no method 'curCSS' jquery.ui.position.min.js?v=1.8.7:13

In FireFox it fails in similar way:

> TypeError: c.curCSS is not a function ...his,"marginTop",true))||0,v=l+p+parseInt(c.curCSS(this,"marginRight",true))||0,w... jquery...v=1.8.7 (row 13)

Updating to dev version of jQuery Update and seelcting jQuery 1.9 or 1.10 does not help - it does not complain about `curCSS`, but about lack of `$.browser()` that was removed in jQuery 1.9, and deprecated long ago.

My question is: Am I doing something wrong, or it's a bug between jQuery Update and Drupal? And if it's a bug, is there any version of jQuery update without it?

Is there a way to update jQuery UI to make it match jQuery, without hacking jQuery Update module or updating directly in D:\UniServer\www\misc\ui ?

# Answer
> -1 votes
when c.curCSS is not a function error occures ,just do the following if any two js included check and remove .. after add this into script

```
jQuery.curCSS = jQuery.css;

```

---
Tags: forms, javascript
---


# Question
Title: Update cart on checkout page with tax rule
I have a tax rule which applies when a user uses Utah as shipping place.But it takes a review order page in between to make it work. Is it possible to update the cart on checkout page soon a user chooses Utah as state.

# Answer
> 2 votes
There is no way right now to show the update without custom code, though it could be done by adding AJAX functionality to the form like the shipping module does. You can see how it updates shipping rates when address data is entered, and if I'm not mistaken it even provides a hook for you to add additional AJAX commands to the response. You should be able to update the order at that time and update the cart contents checkout pane display, too.

---
Tags: commerce, ajax
---


# Question
Title: How do I add static html files to my Aegir install
I have Aegir install running on a rack space server. In addition to the Drupal sites I am running, I would also like to be able to create static websites and server them from the same server. What steps do I need to do to get this to work with Aegir.

I tried the following

1.create a new file within vhostd containing

```
<VirtualHost *:80>
DocumentRoot /var/www/vhosts/mysite
ServerName mysite.mydomain.com

# Other directives here

</VirtualHost>

```
1. add html file to var/www/vhosts/mysite 3 restart apache ? (actually i'm not sure how to do this form aegir)

# Answer
> 1 votes
Your static websites cannot be managed by Aegir, so you should setup them separately on your server.

If you really need to restart apache from Aegir interface, just run 'Verify' task for any of the websites installed (hostmaster will work too). On verify, Aegir runs 'apache2ctl graceful' which effectively restarts apache.

---
Tags: .htaccess, aegir
---


# Question
Title: How do I create a "platform" and "site" from CLI, using the drush extension provision
I'm trying to figure out how to use Provision to create new sites from the CLI.

I tried looking at what commands Aegir normally passes to Provision when setting up a new platform and then a new site on that platform, but I haven't succesfully made it work from CLI.

# Answer
> 0 votes
There is a good article on this question in Aegir official documentation here: http://community.aegirproject.org/content/manage-your-aegir-system-command-line

---
Tags: drush
---


title: Drupal 7 Exposed Filter Display Text

text:
# Question
Title: Drupal 7 Exposed Filter Display Text
I have an exposed filter in drupal, but some text is not displaying as expected. One list displays exactly as I want and that is the Acoustic Guitars as shown in the picture, but I cannot for the life of me figure out why the other filters are not displaying like the Acoustic Guitars. Here is the picture, does anyone know what settings I would need to change to get this to display the description instead of the category like the Acoustic Guitars list?

# Answer
I'ts in your content type. You might have mistaken the label with the value, or not used the label at all. Open the content type, edit each field and change the allowed values as described above the textarea.

If I'm not mistaken it is

```
Label|value

```
> 0 votes

---
Tags: views
---


# Question
Title: Having trouble making Views treat external content as nodes/entities
I have created a module by customizing FlyViews module to fetch data from a third party API and render via a **View**. I have been successful in showing the data on a page but the data has merely one style, that is, **fields**. Now I want to render that content as nodes of a specific content type. That content type will be configured in the module's configuration page. Once I mention a content type, the content should be rendered as nodes of that type.

Even a hardcoded solution will work for me, but it would be nice if I could select the **Show** option (on Views configuration page) as **Content**, just as I can do for a regular View.

**Edit**

I have implemented the custom row plugin which is now visible in Views UI as **Show** option under **Format**. Selecting the option and saving shows the output from my plugin's `render()` method. This is as far as I could get without help. Any ideas how can I manipulate `render()` to actually render the external content as nodes/entities?

# Answer
Finally did it!

To achieve the result mentioned in the question, one can do the following:

1. Create a module implementing Views `row` plugin. To do so,
    1. Implement `hook_views_plugins()` mentioning your `row` plugin. For help, see hook\_views\_plugins() documentation and its implementation in Views core class views\_views\_plugins.
    2. Implement the `row` plugin handler class. Create just a prototype for now.
    3. Mention the `row` plugin handler class in `module.info` file.
2. In your plugin handler class,
    1. override `option_definition()` and `options_form()` methods to present the user with a text field to input node id of the node to clone. You may use `entity_autocomplete` field for the purpose. (*If you wish to ask for a content type instead, you can use a content type drop down. I wish to use an existing node with tokens to replace with external content*). Overrid `validate()` method if you wish to validate the input. For help, see Views core class `views_plugin_row_node_view`.
    2. Overrid `render()` method to *load the node by id* or *create the node by content type*, build the node view using `node_view()` function, and return the rendered HTML using `drupal_render()` function. See `views_plugin_row_node_view::render()` for reference.
> 2 votes

# Answer
I would probably not go down the the road of using Views (or Ctools) plugins at all here. (And I'm a big fan as well as proponent of Ctools and it's plugin architecture.)

I would create a new entity type, or a dummy content type of a node, and then take over the loading of said entity/content type with hook\_entity\_load.

Why integrate with Views only, when you can integrate with Core instead, possibly even with less effort?
> 2 votes

---
Tags: views
---


title: Show or hide custom data set

text:
# Question
Title: Show or hide custom data set
I'm using CIVCRM module in Drupal, and I have created multiple custom data sets for Drupal registration form.

Now problem is that I have 4 membership levels and each level have custom data set so I need to hide other data set and show only those related to selected member level.

Is there a way to do that through administration.

Thanks in advance.

# Answer
> 2 votes
Some forms in CiviCRM (ex: contribution/membership) may have some show/hide options, for, say, organisational memberships, but in general, it's not possible to do it using the admin interface, and doing it programmatically with jQuery is recommended.

Another option, is to use the webform and webform\_civicrm Drupal modules to create a custom form. The latest version of webform\_civicrm makes it possible to pretty much rewrite most of the contribution/membership forms. Webform has ways to show/hide fields conditionally.

If you want to do it the jQuery way, depending on whether it is a Drupal form (ex: user registration form), or a CiviCRM form (contribution/membership form), you can put the javascript snippet in your Drupal theme, or in a CiviCRM template.

For example, if it's a Drupal form, you can put it in the equivalent of sites/example.org/themes/mytheme/js/custom.js :

```
/**
 * Show/hide the appropriate custom fields for a membership level.
 */
Drupal.behaviors.myThemeToggleMembershipFields = {
  attach: function (context, settings) {
    $('#my_membership_type_input').change(function() {
      var v = $(this).val();

      if (v == 1) {
        $('..fields for type 1..').show();
        $('.. other fields..').hide();
      }
      else if (v == 2) {
        // etc.
      }
    });
  }
})(jQuery);

```

---
Tags: 7, users, civicrm
---


# Question
Title: Filter a view basing on current user's roles
Using Drupal 7, Views 3 and the Node Reference module, I'm using a view to populate a node reference field on a custom content type. (So it's a view of "Reference" display type.)

I want to filter this view to show (and allow users to select) only:

1. published content (OK)
2. content of a certain type (OK)
3. only nodes created by the current user (OK)
4. OR if the current user is admin or some other role, bypass the previous filter (3) and show all nodes (but still respect filters 1 and 2) (*not* OK)

Filters 1 and 2 are always mandatory; then either filter 3 OR 4 must also be mandatory. I know I can rearrange filters into filter groups to make this work. The problem is that I cannot find a way to build filter 4.

For filter 3, I had to bring in a Relationship of type "Content: Author", which made a lot of new filters appear, including the "User: Current" that I used for filter 3 (node author == current user).

For filter 4, I need to filter based on the role of the current *user* (*not* author), and I cannot find how to do that.

In the filters list there's a new "User: Roles" filter available, but it only refers to the "Content: Author" relationship, so it only checks the *node author*'s roles. That's not what I need: I need to check the *current user*'s roles.

I'm guessing I have to add a new Relationship to bring in the current user data (something like "User: current"), and then filter on that data, but I cannot find that in the Add Relationship screen.

Any idea how to do that?

# Answer
Following @Jimajamma's suggestion, this is what I used. I adapted his code slightly for Drupal 7 and to allow for other roles than Administrators full access to the results.

In the View, add a *Author: Uid* contextual filter and use the following settings.

#### WHEN THE FILTER VALUE IS NOT AVAILABLE

* Provide default value
* Type: PHP Code

```
global $user;

if (in_array('administrator', $user->roles) || in_array('editor', $user->roles)) {
  return -1;
}

return $user->uid;

```

#### WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED

* Specify validation criteria
* Validator: PHP Code

```
return ($argument != -1);

```
* Action to take if filter value does not validate: Display all results for the specified field
(This is what gives administrator users access to all results.)

That's it!

Compared to my initial settings, the *Content: Author* relationship isn't anymore needed, neither is the *Author* filter (which was brought in by the relationship).

Apparently, for Drupal 6, the condition in the first PHP snippet should rather be `if (in_array('super user', array_values($user->roles)))`.
> 8 votes

# Answer
You need to add a **Contextual Filter** to filter based on the currently logged in user.

1. Add a contextual filter for "User: Uid"
2. Select "Provide a default value"
3. Choose Type: "User ID from logged in user"

You would also need to clone a new view display to show all nodes for specific roles, configured by Page Settings: Access \> Role. Then choose Administrator and any other roles who should see all nodes.

You cannot OR a filter like a sort, and you would be displaying the view two different ways with filtered content and all content, so I would create two displays of this view.
> 3 votes

---
Tags: 7, views
---


# Question
Title: How to create a drush command without drupal?
I'm attempting to create a drush command for use outside of a Drupal install. It's basically a script to make a copy of a distribution starter kit and do some string replacing. I'm following the sandwich example.

I'm running into two issues...

1) I created mycommandfile.drush.inc in a new folder. If I try to run the command it says the drush command cannot be found. So I copied the file to my /.drush folder and it finds the command. Any idea why that would be the case?

2) The second issue is that with the file in the /.drush folder it is telling me that I need a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command. In my command declaration I have 'bootstrap' =\> DRUSH\_BOOTSTRAP\_DRUSH.

# Answer
> 6 votes
1) Drush only searches certain folders for Drush commandfiles. Run with `--include=/path/to/your/drushcommands`, or set `$options['include'][] = '/path/to/your/drushcommands'`; in your drushrc.php if you'd like to use a directory other than `$HOME/.drush`.

2) If you have in fact set your bootstrap to DRUSH\_BOOTSTRAP\_DRUSH, then you should not be getting that message. Maybe there is something wrong with your commandfile definition; can't guess what it might be from the information provided, though.

For a quick start on writing a new Drush command, see the drushify project. It will create a template for you very quickly. Perhaps you could compare the template drushify creates with the commandfile you put together.

---
Tags: drush
---


# Question
Title: Drupal site that points to a non-drupal .html page
I'd like to configure my Drupal 6's site's front page to be "foo/index.htm", a hand-coded html file. But when I put that relative URL into Home › Administer › Site configuration › Default Front Page, it complains "The path 'foo/index.htm' is either invalid or you do not have access to it." It's a unix filesystem and everything is world-read, and the directories are world-execute. What could be the problem here?

# Answer
The issue is the path in question here must be a valid Drupal path, not a Unix path/filename. I'd suggest investigating hook\_menu() as a first step of learning about Drupal paths, callbacks and so forth.
> 2 votes

# Answer
The code that is causing that error is part of the form validation handler for the form you are submitting. (See system\_site\_information\_settings\_validate().)

```
// Validate front page path.
if (!drupal_valid_path($form_state['values']['site_frontpage'])) {
  form_set_error('site_frontpage', t("The path '%path' is either invalid or you do not have access to it.", array('%path' => $form_state['values']['site_frontpage'])));
}

```

drupal\_valid\_path() considers the passed path valid if:

* It is `<front>`
* It is considered external, i.e. an absolute path starting with the protocol string
* It is a path defined from a module

Notice that the form validation handler doesn't check the value for the front page path is a relative path, but drupal\_is\_front\_page() contains the following code.

```
$is_front_page = ($_GET['q'] == variable_get('site_frontpage', 'node'));

```

This means the path for the front page needs to be relative.
> 1 votes

# Answer
I would actually look at modifying the `.htaccess` file to serve your HTML file instead of Drupal's `index.php` when someone attempts to visit your homepage.

If you look at the `.htaccess` file provided by Drupal, it only serves `index.php` when a file or directory does not exist on the server (lines 109-113). You can put a new rule right before that and tell Apache that rule should be the last rule run (which will skip any remaining rules if the conditions are matched). I think the following should work (based on the answer Htaccess rule to redirect domain to index.html):

```
RewriteRule ^$ foo/index.html [L]

```

As long as that rule runs before the Drupal rule that routes all traffic through `index.php`, it should serve your homepage instead of the default Drupal homepage. This will work as long as your homepage has a URL like `http://www.MYDOMAIN.com/` and the user doesn't type anything else (like `index.php` or `index.html`). You'll also need to make sure that all links to the homepage inside Drupal point to the correct URL (for example, the logo link, etc).

Also, because this is a modification to the `.htaccess` file, you'll need to make sure to copy the change over to the new `.htaccess` file when doing Drupal core updates.
> 1 votes

# Answer
1. Use Front Page module, in the configuration page, 'Home links' tab, set to 'xxx.html'.
2. Done.
> 0 votes

---
Tags: nodes
---


# Question
Title: Mixing attributes and line item fields in Drupal Commerce Add To Cart form
I am currently working on a Drupal Commerce site that offers highly customizable products with multiple attributes. I am at the stage where i am trying to theme my add to cart form, and am a bit lost.

In my theme, I have created a hook\_form\_alter, and check for my add to cart form. The $form variable has 2 groups of form fields:

```
$form['attributes']        // Contains 'Attr_1', and 'Attr_2'.
$form['line_item_fields']  // Contains 'Attr_1_c1', 'Attr_1_c2', 'Attr_2_c1', 'Attr_2_c2'

```

So each attribute has 2 customization options specific to that attribute. I would like to output my form like so:

```
Attribute 1: (Select Box)
    Customization 1: (input)   // Attr_1_c1
    Customization 2: (input)   // Attr_1_c2

Attribute 2: (Select Box)
    Customization 1: (input)   // Attr_2_c1
    Customization 2: (input)   // Attr_2_c2

```

Thus grouping the proper customization line\_item\_fields with the proper attributes. However, since attributes are already grouped in the $form variable, and are separate from the line\_item\_fields, I am not sure how to do this. Any thoughts on the best way to proceed?

# Answer
> 3 votes
You may find it easier to organize the form elements in a form template.

e.g

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state{
  $form['#theme'] = array('commerce_add_to_cart_form');
}

/**
 * Implements hook_theme().
 */
function MYMODULE_theme($existing, $type, $theme, $path){
  return array(
    'commerce_add_to_cart_form' => array(
      'render element' => 'form',
      'template' => 'form--commerce_add_to_cart',
      'path' => $path . '/templates',
    ),
  );
}

```

Then you can use a file in

```
MYTHEME/templates/form--commerce_add_to_cart.tpl.php

```

and in the template file

```
print drupal_render($form['element_name']);
// or
print drupal_render_children($form['element_name']);

```

to specify exactly where to render each form element.

---
Tags: theming, forms, commerce
---


# Question
Title: updating field value of a content type with query
I have a problem, may you guys can help me :)

I have content type called book, and it has field called stock. Instead of using node\_save() I want to update value of book stock using manual query. I have this query, if I run from MySQL client (heidisql ex) the value of book stock has changed already, but if I open the node of book nothing happen. Please help me guys..

node\_save() method:

```
$node = node_load($id); // $id -> node id (nid)
$node->field_stock_value[$node->language][0]['value'] = "whatever";
node_save($node);

```

my query:

```
db_query("update field_data_field_stock b left join field_revision_field_stock rb on b.revision_id = rb.revision_id set b.field_stock_value = '{$stock}', rb.field_stock_value = '{$stock}' where b.entity_id = {$nid}");

```

I want to use query instead node\_save() because I want to perform batch set for updating node, and you know, node\_save() is really weight.

thank you before, happy new year guys.. :D

# Answer
Why not you use field API field\_attach\_update() instead, it can save the node\_save() process.

For example take this.

```
  $node = new stdClass();
  $node->id = $id_value;          // node id
  $node->type = $bundle_value;  // aka content type

  $node->field_fieldname[LANGUAGE_NONE][0]['value'] = 'some value';
  field_attach_update('node', $node);

```

Reference: http://www.urbaninsight.com/2011/10/24/saving-nodes-fields-without-saving-node-itself
> 6 votes

# Answer
I've captured mysql query log (as mentioned here: https://stackoverflow.com/questions/6479107/how-to-enable-mysql-query-log ) after editing a node( of type job vacancy). I want to mention how a cck field like "designation" is getting updated in the tables(I've not created new revision though):

```
-------------------------------------------
DELETE FROM field_data_field_designation
WHERE  (entity_type = 'node') AND (entity_id = '599') AND (language IN  ('und'))

-------------------------------------------
DELETE FROM field_revision_field_designation
WHERE  (entity_type = 'node') AND (entity_id = '599') AND (revision_id = '636') AND (language IN  ('und'))

-------------------------------------------
INSERT INTO field_data_field_designation (entity_type, entity_id, revision_id, bundle, delta, language, field_designation_tid) VALUES ('node', '599', '636', 'job_vacancy', '0', 'und', '4641'), ('node', '599', '636', 'job_vacancy', '1', 'und', '4642'), ('node', '599', '636', 'job_vacancy', '2', 'und', '4643'), ('node', '599', '636', 'job_vacancy', '3', 'und', '4644'), ('node', '599', '636', 'job_vacancy', '4', 'und', '4645'), ('node', '599', '636', 'job_vacancy', '5', 'und', '4646'), ('node', '599', '636', 'job_vacancy', '6', 'und', '4647'), ('node', '599', '636', 'job_vacancy', '7', 'und', '4648'), ('node', '599', '636', 'job_vacancy', '8', 'und', '4649'), ('node', '599', '636', 'job_vacancy', '9', 'und', '4650')

-------------------------------------------
INSERT INTO field_revision_field_designation (entity_type, entity_id, revision_id, bundle, delta, language, field_designation_tid) VALUES ('node', '599', '636', 'job_vacancy', '0', 'und', '4641'), ('node', '599', '636', 'job_vacancy', '1', 'und', '4642'), ('node', '599', '636', 'job_vacancy', '2', 'und', '4643'), ('node', '599', '636', 'job_vacancy', '3', 'und', '4644'), ('node', '599', '636', 'job_vacancy', '4', 'und', '4645'), ('node', '599', '636', 'job_vacancy', '5', 'und', '4646'), ('node', '599', '636', 'job_vacancy', '6', 'und', '4647'), ('node', '599', '636', 'job_vacancy', '7', 'und', '4648'), ('node', '599', '636', 'job_vacancy', '8', 'und', '4649'), ('node', '599', '636', 'job_vacancy', '9', 'und', '4650')

```

We can see that it is deleting the latest revision and inserting back into with new values with the same revision id(I'm not sure about the logic though).

So you need to update both field\_data and the field\_revision tables with the same values on specific(latest) revision on given nid. I'm not sure how it'd update if I had created new revision while saving the node.
> 0 votes

---
Tags: nodes, database
---


title: Switching multiple DB and mysql_close

text:
# Question
Title: Switching multiple DB and mysql_close
Do we need to call `mysql_close();` before switching the database using `db_set_active('sharedb');`?

# Answer
No, you should not call any mysql functions at all. You don't mention the drupal version, but in 6, it's likely that you're actually using the mysqli extension and in 7, you're using PDO.

I don't think that a handful open database connections is going to be a problem, they will be automatically closed by the end of the request. So unless you have a long-running process or more than a handful connections you need to make, I wouldn't worry.

If you have either of those, then you might need to care about this, if you're on 7.x, there's an API for this: Database::closeConnection().

On 6.x, you're not so lucky, while you could check global $db\_type (see db\_set\_active()), and call the right function, you also need to pass global $active\_db to the function to close the right connection and you can't update $db\_conns in db\_set\_active(), so that will not know that you closed the connection and you can't re-open the connection again.
> 1 votes

---
Tags: database
---


title: Add inline widget to product display

text:
# Question
Title: Add inline widget to product display
I am trying to integrate our Drupal 7 Commerce install with Digital River's where-to-buy widget.

All I need to do is add a little JS to the product page, with a script variable set to the product sku. On page load, this inline JS runs and adds a button that when clicked will pop-up a lightbox with where-to-buy information. This script has a variable that requires a SKU to be entered. If I add the snippet to my node-template it works fine.

HOWEVER, I have several products on each product display, and I have 2 product attributes that can be selected. This, of course, refreshes the node/entity field values in my page, like the title, a product image and so forth. This will not refresh the sku parameter of my javascript snippet though, so my WTB button does not update. IE, if I did something like this:

```
<script type="text/javascript">
          pswtb.loader.show({
            widgetConfigurationId: "3a4acc53-216e-48da-8e92-bfaeb58168a7",
            sku: "US_<?php print trim($content['product:sku']['#markup']) ?>"
          });
        </script>

```

I discovered that it would initially load but the product:sku wouldn't change as I selected a new attribute.

So, I also discovered that my values *would* update if they were displayed via the render() function. So, if I just did this:

```
<?php print render($content['product:sku']) ?>

```

I would get an element that updates 'properly' when a product attribute is selected. It does, however come with a lot of div's wrapping it, so I can't use it as a parameter in my script,and I didn't want to override the 'sku' field template because I need that sku elsewhere on the page, and even overriding the template, I would still get a wrapper around it.

Ok, so my next attempt was to create a 'virtual' field, using the virtual\_field module. This just lets you have a dummy field that doesn't get stored anywhere but still lets you create custom templates and specify display formatters. I created a dummy field that just contains the product sku.

Using this, I created a custom field template (field--field-product-wtb.tpl.php) for this virtual field like so:

```
this will update: <?php print render($item); ?>
but this gets stripped out:
<script type="text/javascript">
   pswtb.loader.show({
     widgetConfigurationId: "3a4acc53-216e-48da-8e92-bfaeb58168a7",
     sku: "US_<?php print render($item); ?>"
   });
</script>

```

And then in my node template, I just do this:

```
<?php print render($content['product:field_product_wtb']) ?>

```

It works on initial load, and when a product attribute is selected, the sku does change (the 'this will update' part) but the entire script tag gets stripped out and my button disappears. I guess because it gets filtered via some xss protection, but I haven't tracked it down. As near as I can tell, this is because when content on a page is updated via ajax, the HTML returned from a tpl file is sanitized and things like script tags are filtered out.

Now I'm at a loss as to how to get this to work.

# Answer
You could probably do something like this:

1. Add hidden form element with product SKU
2. Read the SKU in a JavaScript Drupal.behavior

The key is making the SKU available in the DOM and using Drupal.behaviors to read it, as they run / are reattached after the AJAX form update.

i.e:

```
/**
 * Implements hook_form_FORM_ID_alter
 */
function MYMODULE_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state){

  // Add a hidden SKU element to the add to cart form
  if (isset($form_state['default_product']->sku)){
    $form['product_sku'] = array(
      '#type' => 'hidden',
      '#value' => $form_state['default_product']->sku,
    );
  }

}

```

Then in your JS file

```
(function ($) {

  Drupal.behaviors.pswtb_loader = {
    attach: function (context, settings) {
     if($('input[name=product_sku]').length > 0){
       pswtb.loader.show({
         widgetConfigurationId: "3a4acc53-216e-48da-8e92-bfaeb58168a7",
         sku: "US_" +  $('input[name=product_sku]').val();
       });
     }
    }
  };

})(jQuery);

```
> 0 votes

---
Tags: theming, commerce, javascript
---


# Question
Title: What module will show me all sql queries being run on the loaded page?
My site is running slow and I suspect its a module, but not sure which one. Is there a module that can display all the sql queries being run on a loaded page? If there isn't maybe there is a command line tool that others use to monitor this data?

# Answer
> 5 votes
There is better query log we can get from mysql log( more here: https://stackoverflow.com/questions/6479107/how-to-enable-mysql-query-log )

It shows real mysql queries with real values while the Devel's log shows placeholders.

So to get log of a page shutdown Mysql server, add the "log=" line in my.ini and restart the server then do the page load and then again stop the server and comment the log command.

# Answer
> 14 votes
The Devel module has a query log option, which when enabled will show every query that's been run for a request at the footer of the page.

You can enable it at admin/config/development/devel once the module's installed.

---
Tags: performance, database
---


# Question
Title: Create a node type that acts like a PHP page?
Drupal 7.24, fresh installation

I'm fairly new to Drupal and I'm trying to figure out if it's possible to create a node type that acts like a PHP page. I have a code library that needs certain files required once in a node type that displays output.

I've tried using Full HTML and also created a new text format that had all vanilla Drupal options unchecked and the PHP snippets do not function.

I'm sure I'm mixing up terms and I hope you understand what I'm going for, like I said I'm fairly new. Do I need to look for a different text format?

Thanks for your time, and Happy New Year!

# Answer
First, you will need to enable the "PHP filter" core module in admin/modules. I think you did.

Then, you'll need to configure the newly added text format in admin/config/content/formats and assign some role to that text format. Note that you can also do this from admin/people/permissions.

Useless to say you'll need to be very conservative here and only allow this text format to - very - trusted users (roles).

Finally, in your node content, select the "PHP code" text format and type your code (including tags).
> 2 votes

---
Tags: nodes
---


# Question
Title: Is block weight ignored when setting content in hook_block_list_alter()?
I am using hook\_block\_list\_alter and hook\_block\_view\_alter to force caching upon a block provided by nice\_menus, which has bad performance when used with my HUGE taxonomy menu. Here is an abstract of my code:

```
/**
 * Performance hack for nice_menus
 * Force the nice menu blocks to be cached globally.
 * Note that the same menu will be displayed for all users on all pages where the block is enabled.
 */
function mymodule_block_view_alter(&$data, $block) {
  $deltas = variable_get('mymodule_nice_menus_performance_hack_deltas',array());

  if ($block->module == 'nice_menus' && in_array($block->delta,$deltas)) {
    // if we are here, then the block has been rendered. set the cache.
    cache_set('mymodule_nice_menu_'.$block->delta.'_data', $data, 'cache_block', CACHE_TEMPORARY);
    cache_set('mymodule_nice_menu_'.$block->delta.'_block', $block, 'cache_block', CACHE_TEMPORARY);
  }
}

function mymodule_block_list_alter(&$blocks) {
  $deltas = variable_get('mymodule_nice_menus_performance_hack_deltas',array());

  foreach($blocks as &$block) {
    if ($block->module == 'nice_menus' && in_array($block->delta,$deltas)) {
      $cached_data = cache_get('mymodule_nice_menu_'.$block->delta.'_data', 'cache_block');
      $cached_block = cache_get('mymodule_nice_menu_'.$block->delta.'_block', 'cache_block');
      if (!empty($cached_data) && !empty($cached_block)) {
        $block = $cached_block->data;
        $block->content = $cached_data->data['content'];
        $block->subject = $cached_data->data['subject'];
      } // else just don't set anything, and nice_menus will recreate it!
    }
  }
  dpm($blocks);
}

```

Now my problem is, that whenever `$block->content` is set, the block's weight is ignored, and it is rendered as the first block in the region, even though `$block->weight` was set to the correct value.

What causes this, and how does one enforce the weight?

# Answer
> 1 votes
**Symptoms:** When the block is not loaded from cache, but from the database, the ordering works fine. When loading from cache, the weight is ignored.

**Diagnosis:** The block module uses SQL to order the blocks:

```
function _block_load_blocks() {
  global $theme_key;

  $query = db_select('block', 'b');
  $result = $query
    ->fields('b')
    ->condition('b.theme', $theme_key)
    ->condition('b.status', 1)
    ->orderBy('b.region')
    ->orderBy('b.weight')
    ->orderBy('b.module')
    ->addTag('block_load')
    ->addTag('translatable')
    ->execute();

// ...

```

After that, it ignores the weight value, and relies on the order of php array keys (order in which `foreach` iterates) when rendering:

```
function _block_get_renderable_array($list = array()) {
  $weight = 0;
  $build = array();
  foreach ($list as $key => $block) {
    $build[$key] = $block->content;
    unset($block->content);

// ...

    $build[$key] += array(
      '#block' => $block,
      '#weight' => ++$weight, // HERE LIES THE MADNESS!
    );
    $build[$key]['#theme_wrappers'][] ='block';
  }
  $build['#sorted'] = TRUE;
  return $build;
}

```

**Strategy:** Either hack the blocks module (DON'T) or find a workaround. I looked through the block.module and found (using lots of dpm()) where the order of array keys are being reversed:

```
function _block_render_blocks($region_blocks) {

// ...

  foreach ($region_blocks as $key => $block) {
    // Render the block content if it has not been created already.
    if (!isset($block->content)) {
      // Erase the block from the static array - we'll put it back if it has
      // content.
      unset($region_blocks[$key]); // THIS IS WHY THE ORDER OF KEYS CHANGE

// ...

      if (isset($block->content) && $block->content) {

// ...

        $region_blocks["{$block->module}_{$block->delta}"] = $block; // THIS IS WHY THE ORDER OF KEYS CHANGE
      }
    }
  }

  return $region_blocks;
}

```

**Workaround:** Manually sort the render array in a hook\_page\_alter(&$page) implementation.

```
function mymodule_page_alter(&$page) {
  if (!empty($page['sidebar_first']['my_block_1'])) {
    $page['sidebar_first']['my_block_1']['#weight'] = -1; // move it to the top
    $page['sidebar_first']['#sorted'] = FALSE; // indicate that it still needs to be sorted before rendering
  }
}

```

I only have two blocks in sidebar\_first, of which the bottom one is cached. So I only need to lift the other block ('my\_block1') above the cached block. A more sophisticated approach will be to query the weights from the block table again.

I'm not sure whether I should consider this to be a bug in the block module. It is a shortcoming, but it's only exposed because of my custom caching hack.

---
Tags: 7, blocks
---


# Question
Title: How do I preserve GIF animation with the image field and image styles?
Currently, when I upload animated GIFs to image fields, image styles breaks the animation as part of the crop/resize sequence.

I'd love to be able to preserve animation while also taking advantage of image styles. Is there a way to achieve this?

# Answer
It is possible, there already is some discussion:
> 3 votes

---
Tags: media
---


title: Auto Assign User to Node

text:
# Question
Title: Auto Assign User to Node
I am working on a site that is a directory of all track and field clubs (trackandfieldclubs.com). A user can create an account and add their club if it is not listed. However, nearly all the clubs have been listed by me to give the site some value. After all, what good would the site be if no track and field club were listed? The problem is that I want a user who's club is already listed to become the author of their club's node. Right now I have implemented a rather archaic system to do this where a user first creates an account, then fills out a web form (http://trackandfieldclubs.com/form/request-edit-existing-club) telling me their club name and username. I then login as an admin and change the node's author. Is there a better way to do this? Can this process be automated? Thanks in advanced!

# Answer
You can create a simple module, implementing hook\_form\_alter, add additional form submit action which checks the submitted values on your form, looks up if there is node matching them and finally loads and updates the node accordingly.

Alternatively, you can add the Existing Club Name field to registration, implement hook\_user\_insert, and do the same logic as described above. This would save you unnecessary web form and improve the user experience greatly.

EDIT: Now that I think of it, it might be possible to achieve this using Rules module (https://drupal.org/project/rules) without coding. You add the field to the registration, create a rule, on event when user is created. Then iterate over all nodes of the Club content type (this should be possible with rules) and do a string comparison on each, to find the corresponding club. If the string comparison matches, you can easily change the node author. Please note that this solution is rather slow (and definitely not "right"), users could experience slow registration times.

Alternatively, you could change the rule event from user registration to form submission (which you have already) and therefore this (possibly) slow processing would not affect all users.

Also, I havent tried it, it's just an idea, but you should definitely try it.
> 1 votes

---
Tags: nodes, users
---


# Question
Title: Automate the creation of settings.php and files directory
I am using Drush make files and Drupal Installation profiles to streamline the creation of new Drupal websites (which are created in the sites directory of my Mac).

Everything is working fine. The Drush make file automatically downloads Drupal and all the modules I normally use on each site.

However, for each new Drupal website, I have to create a `files directory` and a `settings.php` file and then set them to writeable.

Is there any way I can automate this process, so these files are created when Drush downloads the files for the Drupal website?

# Answer
Try using the `drush site-install` command. Name your installation profile with the command argument.
> 2 votes

# Answer
I use Aegir (http://www.aegirproject.org) for managing my multisites, it not that hard to setup and provides various benefits, automated creating of settings.php and files/ directory being part of them. It also provides you web interface for managing your webistes, creating backups, restoring them, managing versions and migrations...

EDIT: It also supports make files.
> 0 votes

---
Tags: drush, installation-profiles
---


title: Manually selecting content for a view

text:
# Question
Title: Manually selecting content for a view
is it possible to manually select content for a view? I'd like to create a *related content* view but I want to add the links manually for every article, not using taxonomy.

Is it possible? Is their a certain module that exists?

Thanks for any help

# Answer
You can use References module (https://drupal.org/project/references) and create Node Reference field, which will allow multiple values.

Steps:

* Create the node reference field
* Add Node:nid to the views contextual filters to know which node you are on
* Add related content field to the views Relationships to filter out the correct related nodes
> 4 votes

---
Tags: views
---


# Question
Title: Multi language with different layout drupal 6
I have a multilingual site with English and Spanish. I need to change the Layout(theme) of my English pages but no chnage in spanish pages. Can we have separate tpl file based on Language? Any help will be appreciatable

# Answer
> 0 votes
John,

This question has already been answered here: Page template suggestion per language?

Cheers,

---
Tags: i18n-l10n
---


title: Form submit not firing

text:
# Question
Title: Form submit not firing
For some reason I am unable to get into my form\_submit function. I have attempted to add a custom handler to the #submit to force the form to submit to it however I haven't gotten any where. Any advice on what I'm doing wrong would be appreciated.

```
function cheo_whiteboard_admin_form(){

 if(user_access('administer')){
   $form['admin_menu'] = array(
    '#type' => 'fieldset',
    '#title' => t( 'Admin Menu' ),
   );
$form['admin_menu']['admin_menu_archive'] = array(
  '#type' => 'submit',
  '#value' => 'Archive Search',
  // '#submit' => array('cheo_whiteboard_admin_form_submit'),
);

$form['admin_menu']['search_date'] = array(
  '#type' =>'date_popup',

);

$form['admin_menu']['special_instructions'] = array(
  '#title' => 'Special Instructions:',
  '#type' => 'textfield',
  '#size' => 75,
);
$form['admin_menu']['staffing_officer'] = array(
  '#title' => 'Staffing Office Status:',
  '#type' => 'textfield',
  '#size' => 75,
);

 $form['#submit'][]='cheo_whiteboard_admin_form_submit';

return $form;
}

  function cheo_whiteboard_admin_form_submit($form, &$form_state){
    dpm($form);
}

```

# Answer
> 0 votes
You are checking for user access within the form builder function. Make sure that control is going to the actual form by adding a dpm. It is better to check permissions at the menu definition level unless you have a better reason not to do so.

Next try `$form['#submit']='cheo_whiteboard_admin_form_submit';`

This makes sure that `cheo_whiteboard_admin_form_submit` is the only form handler function and hence easier for you to debug.

---
Tags: forms
---


title: OpenCalais is not autotagging content

text:
# Question
Title: OpenCalais is not autotagging content
I'm using the following modules versions on Drupal 7.

* OpenCalais 7.x-1.0-alpha2+22-dev
* Feeds 7.x-2.0-alpha8

I have a *Feed* that is creating my content correctly into the *Feed Item* content type. When I click on the edit tab, I can see that OpenCalais is suggesting tags. But it does not 'autotag' the content and requires me to actually click the tag before it gets added to the autocomplete textbox. This kind of defeats the purpose. According to this http://www.lullabot.com/blog/article/introduction-calais, it is supposed to do this out of the box. the only different I see is that this is for Drupal 7. I have also installed RDFx just in case it had that requirement for the D7 version.

How can I get OpenCalais to input the suggested tag into the field automatically?

# Answer
I believe you did not configure the Calais module correctly.

Go to admin/settings/calais/calais-node, expand the fieldset of your content type and pick either "Apply all suggested terms on every update" or "Apply all suggested terms on creation ONLY" from "Calais Processing:" field. This way, the tags will be applied automatically.
> 0 votes

---
Tags: 7, taxonomy-terms
---


title: Creating menus from terms

text:
# Question
Title: Creating menus from terms
i want to make a complicated tabs block for terms (i usually views and quick tabs for this and it works great) . in this block i want a main tabs bar when i click on one of it it shows the content that have that term or any of its chlidren term, also i want a second tabs bar to show, if the main term have any children term and put in that bar the lev.1 children for the main term ,so if i click on it it shows the term's content and any of its children term content to ,i hope i described it well , check the image for more understanding

my question is : is that possible using views or any other modules or should i create my own module -which i allready started creating but its taking a long time - ??

thanks in advance

# Answer
> 0 votes
If I understand your question, I think you want the Taxonomy Menu module:

> * Custom Menu per vocabulary
> * Uses the default taxonomy term path or custom paths
> * Integrate with Views
> * Integrate with Pathauto: use URL/path aliases
> * Does not interfere with other menu modules

However, the last time I did this, I wrote my own module. Essentially, I wired up taxonomy hooks to call `menu_link_save()` for new terms, and `menu_link_delete()` when terms were deleted. This is a rather complicated process. If you go this route, I would study the submit handlers for the menu module to see how everything works. You also need to study the taxonomy API to see how to walk trees when you have a hierarchical vocabulary.

---
Tags: views, 7, blocks
---


# Question
Title: Create a new template view for a specific vocabulary name
I'm in need of some help for my Drupal 7 site. Right now I am using the stock taxonomy view (/taxonomy/term/%) that came with views to display a listing of some specific nodes. It works great.

Now I would like to create another page that will display a different view listing of nodes under a different vocabulary term. I'd like to template to be different also.

I'm having trouble wrapping my head around how to best do this. I am using Panels for some of my pages so could I use that? I've tried to activate the panels page that overrides the taxonomy, but I can't because I am using views already to generate a page. Can I clone my current view and set a filter for a specific vocabulary and use that?

# Answer
> 0 votes
I ended up using the Taxonomy Views Switcher module which allowed me to create a new views page. It's not the best solution, but for me it works.

---
Tags: 7, views, taxonomy-terms, panels
---


title: Group Views' Output

text:
# Question
Title: Group Views' Output
I'm using Drupal Views for an event calendar. I simply print the output as a table now: http://quaaoutlodge.com/myspecial-myevents

Now what I would like to do: I want to have items grouped an ordered by month i.e. I want to have a group of

`January 2014` a underneath it `Test Event 1` and `My Test Event2` and there would be another group for `December` that would contain the `New Year's Eve` event, ow can I do this?

Thanks!

# Answer
> 3 votes
All you need to do is set the grouping field in the format settings.

---
Tags: views
---


# Question
Title: Only ONE CSS File for Visitors (and more for Admins)
So I just started creating a theme for my first big drupal project, and instantly had to quietly cry in a corner, as I saw how many css files Commerce Kickstart 2 and Omega4 are serving by default.

**My plan** is to essentially reduce the number of CSS files served to only one, perhaps two (depending on the current page), for the minimum amount of http-requests, without having to manually exclude them all in the theme settings file (which would be an unreliable solution, as new CSS files may get added upon installment of a new module). In addition, exceptions will have to be handled depending on a user role; so visitors should really only get one or two css files, whereas admins shall be served with all CSS files, that are required for the control panel overlay, as well.

Thus **my question:** Is there a way for me to easily smack those fancy admin- and maintenance-related CSS files back in, only to be loaded for admins?

Basically I want regular visitors to only load my `global.css` file, whereas admins also get the CSS files of the basetheme as well as `commerce_kickstart_menus.css`. (For some reason, `toolbar_megamenu.css` already gets served to admins only.)

Any help or hints as how I could go about this would be super-appreciated!

# Answer
> 2 votes
You can achieve this by extending a hook\_css\_alter in your template.php for module file.

```
function hook_css_alter(&$css) {
  global $user;  //  Use this object to check current user roles

  //  The $css variable is an array of all of the css files that will be loaded
}

```

---
Tags: theming, commerce
---


# Question
Title: Configuring View output with multiple related nodes
Real world: Our not-for-profit holds monthly meetings. At each meeting, zero, one, or two people can present.

My site has:

* Content type Presenter with fields Name and Description
* Content type Meeting with field Date, Topic, and Node Reference (which will allow a maximum of two entries)

I created a View to show the meeting information. What I would like to see is this:

```
Meeting Date
Meeting Topic
Presenter 1 Name
Presenter 1 Description
Presenter 2 Name
Presenter 2 Description

```

What I am currently seeing is this:

```
Meeting Date
Meeting Topic
Presenter 1 Name
Presenter 1 Description
Meeting Date
Meeting Topic
Presenter 2 Name
Presenter 2 Description

```

I have tried several things to fixed this: Grouping, SQL Distinct (via Advanced-\>Other-\>Query Settings), and others, but so far, nothing has worked. This seems like something which should be easy to do - but I have yet to find the proper incantation.

Please help.

# Answer
> 1 votes
Have you tried grouping by the node id (the same node id used in the node reference)?

---
Tags: views
---


# Question
Title: apply condition to pages created by user roles
```
if(isset($node) && $node->type == 'page') {
}

```

In the above code, I need add one more condition, so that it get applied on those pages which was created by users having user role "EDITOR"
Please help.

# Answer
> -1 votes
```
if(isset($node) && $node->type == 'page') {
  if($node->uid) {
    $node_author = user_load($node->uid);
    if(is_object($node_author)) {
      if(in_array("editor",$node_author->roles)) {
        // This is the condition to match the current node author belongs to editor role.
      }
    }
  }
}

```

---
Tags: theming, nodes, users
---


# Question
Title: How to use CSS preprocessor LESS.js with Drupal 7?
I would like to use LESS, the CSS preprocessor, with Drupal 7 projects.

What are the required steps to use LESS in Drupal?

# Answer
> 7 votes
There is the LESS CSS Preprocessor module for drupal.

# Answer
> 2 votes
Note that the mentioned module doesn't use the normal Ruby compiler but a PHP compiler with some differences.

You could also make use of the LESS .js compiler while developing. Just include the .js file supplied by LESS, as explained on their website.

# Answer
> 2 votes
Be careful using any LESS modules for Drupal. One error in your less file could bring your whole site down. And it can make debugging a pain in the rear.

Many people, myself included, recommend isolating LESS from Drupal by using a LESS compiler to watch your less files, and compile to pure CSS files that you can deploy to your staging and production servers.

less.js running on node.js works great for my workflow in Ubuntu. The answer above details how to do this.

For Mac, try: http://incident57.com/less/

For Windows, try: http://winless.org/

# Answer
> -1 votes
Introducing LESS support in Drupal 7 would be a great idea when combine with Bootstrap and Font Awesome. A helper module named "TWBS LESS". The goal of TWBS LESS is to provide a handy support for LESS and act as the helper module for on going Drupal-Bootstrap-Remix development. http://edin.no-ip.com/blog/hswong3i/announcing-twbs-less-simple-less-support-drupal-7

---
Tags: 7, theming
---


# Question
Title: How to set up Authcache module with Varnish and ESI?
I am trying to set up Drupal 7 with Authcache beta 2 and Varnish 3.0 but I can't get the ESI blocks working. Varnish it self seems to work well.

I am using the example.vcl from `sites/all/modules/authcache/modules/authcache_varnish/` but on the *Authcache ESI status debug page* I get the following messages:

```
ERROR: Request Header   HTTP header X-Authcache-Do-ESI is not on primary request.
Please make sure that the reverse proxy software (varnish) is configured according to the requirements of authcache_esi / authcache_varnish.

OK  ESI Tag Tag successfully substituted by reverse proxy.

ERROR: ESI Subrequest Header    HTTP header X-Authcache is not on ESI subrequest.
Please make sure that the reverse proxy software (varnish) is configured according to the requirements of authcache.

```

The second problem is that even if I configure some blocks on the blocks setting page to load via ESI and AJAX, this block do not show up at `admin/config/system/authcache/p13n` and `admin/config/system/authcache/p13n/frontcontroller`.

There for it does not surprise that watchdog gives the error message (for each block):

```
Failed to find url generator for route frag/block/block-25

```

EDIT: My setting.php is set up as follows:

```
$conf['reverse_proxy'] = TRUE;
$conf['reverse_proxy_addresses'] = array('127.0.0.1');
/**
 * Add Varnish as the page cache handler.
 */
$conf['cache_backends'][] = 'sites/all/modules/varnish/varnish.cache.inc';
$conf['cache_backends'][] = 'sites/all/modules/authcache/authcache.cache.inc';
$conf['cache_backends'][] = 'sites/all/modules/authcache/modules/authcache_builtin/authcache_builtin.cache.inc';
$conf['cache_class_cache_page'] = 'VarnishCache';
// Drupal 7 does not cache pages when we invoke hooks during bootstrap.
// This needs to be disabled.
$conf['page_cache_invoke_hooks'] = FALSE;

```

I didn't find any documentations so what am I supposed to do?

# Answer
> 0 votes
When using this file I had to scroll down to line 142 and change this:

```
  if (req.restarts == 0 && server.identity !~ "^/tmp/vtc.") {
    unset req.http.X-Authcache-Do-ESI;
    unset req.http.X-Authcache-Get-Key;
    unset req.http.X-Authcache-Key-CID;
    unset req.http.X-Authcache-Key;
  }

```

into this:

```
  if (req.restarts == 0 && server.identity !~ "^/tmp/vtc.") {
    unset req.http.X-Authcache-Do-ESI;
    unset req.http.X-Authcache-Get-Key;
    unset req.http.X-Authcache-Key-CID;
    unset req.http.X-Authcache-Key;
  }

  set req.http.X-Authcache = 1; // Added by me
  set req.http.X-Authcache-Do-ESI = 1; // Added by me

```

I'm not sure why those headers are not added but instead removed in the default version, since the module seems to require them to be present in the first incoming request. However, given the nature of those headers, they seem to make more sense when returned from the backend to Varnish than the opposite. znerol might have a good answer for you (and for me) why they are required in the first request.

I also wanna say thank you znerol for this amazing module and for the ongoing documentation work.

---
Tags: 7, proxies
---


# Question
Title: How to migrate user passwords from D6 to D7 site using salt module?
I need to migrate the user passwords from Drupal 6 site to Drupal 7 Website. I am using the migrate\_d2d module for performing the migrations. But the problem I am facing is that the Drupal 6 site uses the salt module which appends an internal string to the users passwords before it is being saved to the database. So migrating the passwords as such doesn't work.

Can any one tell me if there is some way to migrate the user passwords in this case or its not possible??

# Answer
It is not possible - both Drupal version stores user passwords in a way that was considered pretty secure when the major version was released. But these ways are incompatible. And by design you cannot recover passwords - it's a one way algorithm. Well, there are ways to hack passwords from D6 now (that's why it was changed in D7) but they are CPU-intensive, and in some countries attempts are outright illegal.

The best you can do is to use `_user_mail_notify($op, $account, $language = NULL)` \- Set `$op` to `'password_reset'` and call it inside `foreach` over all accounts after migration. That way all users will get an email saying they need to reset their password, with one-time link to do that. Probably there is already a module for that, too, but I couldn't find it.
> 2 votes

---
Tags: migrations
---


# Question
Title: How to load a view's ajax when the view is programmatically loaded
I am embedding a (calendar) view withing another view by using the following code (in a theme)..

```
        <div class="calendar-calendar">
          <?php echo views_embed_view('event_calendar', 'year_plan'); ?>
        </div>

```

The calendar itself is loading perfectly, however, it does have "Prev" and "Next" year links, which increment the year. When you click on them, they navigate to a new page, with JUST this calendar view displayed.

I'd like them to navigate the years using the ajax it uses when I load the view without embedding. Is it possible to load the ajax associated with these navigation links programmatically?

# Answer
> 3 votes
You have to enable ajax in the views. Probably you have to do it in both parent and child view.

To do so : go to `Advanced -> Use Ajax`

---
Tags: views
---


# Question
Title: Field Collection Value field is not deleting correctly(using programmatically)
I installed the Field ollection module in a Drupal 7 site and I added a multi-field (unlimited) field collection with three items.

I need to programmatically delete the field collection.

I used the following code, which does not work.

```
$field_collection_delete = $node->field_accommodation['und'][$j]['value'];
entity_delete_multiple('field_collection_item', array($field_collection_delete));

```

The value in the field collection item is deleted from the database, but the field collection field I added in the content type is still in the database.

I need to delete that too.

>

What code do I need to use to make it happen?

# Answer
You need to unset the field from node first!

```
unset($node->field_accommodation['und'][$j]);

```
> 1 votes

# Answer
You should delete field collections by calling `$field_collection->delete();` This handles a few other things for you such as deleting the parent entity.
> 0 votes

---
Tags: 7, entities
---


title: How do I set the node title?

text:
# Question
Title: How do I set the node title?
I need to specify node titles when the node is created. I am hiding the title field from users and have everything working to generate the correct title but I can't seem to get that title into the node's title field. How do I get my title where it needs to go?

# Answer
> 1 votes
Perhaps you can insert that generated title with hook\_node\_presave

# Answer
> 1 votes
You can use Auto Entity Label to set the title, it supports the use of tokens so you can add any field that is attached to the node to the title. You can also hide the title so the user cannot edit it if required.

---
Tags: nodes
---


title: Can't add custom.tpl to my module

text:
# Question
Title: Can't add custom.tpl to my module
I create a custom module that included hook\_menu and hook\_block\_info and ... i wanna add a tpl to this module . here is my code :

```
        function hookmenu_menu() {
            $items['hookmenu'] = array(
                'title' => 'Soheil',
                'page callback' => 'hook',
                'type' => MENU_NORMAL_ITEM,
                'page callback' => 'myhook_page',
                'access arguments' =>array('administer content'),
            );
            return $items;
        }

        /*
         * page callback
         */
        function myhook_page(){

            return theme('my_custom_template');
        }

    /*
 * Implement hook_theme().
 */
function custom_example_theme(){
    return array(
        'my_custom_template' => array(

            'template' => 'custom-page',
        ),
    );
}

```

and i created a `custom-page.tpl` and wrote hello world .
result : i can see my page but i can't see hello world

thx

# Answer
Your file needs to be named

custom-page.tpl.php

Note the .php extension. You might need to clear the caches to make that change show up

You also need either a `variables` or `render element` property as outlined in the docs
> 2 votes

---
Tags: routes, theming
---


# Question
Title: How to hide product in drupal commerce with rules
I have a Drupal site with drupal commerce on it and I created a **product with 2 price field**.

If a user have role 'simple user' he sees the default price.
If user have role 'friend user' he sees the second price value.

I already create this rule but now I'm trying to filter the product in this way:

**If user have role 'friend user' and the product don't have the second price hide it** to him. I'm not seeing any option in rule to hide a content.

How can I achieve this content filter?

# Answer
> 0 votes
I believe there is not out of the box or ready to use solution. You should create a custom rule and trigger it when the product is being viewed.

---
Tags: commerce, rules
---


# Question
Title: how to get the value of list field type (check boxes)
```
$node=node_load(18);
$logo_img = file_create_url($node->field_site_logo[$node->language][0]['uri']); //origional image path
$show_logo = $node->field_options_site_logo['value']; //original image path
if(isset($logo_img)) {
  $web_logo = theme('image_style', array('path' => $node->field_site_logo[$node->language][0]['uri'], 'style_name' => 'site_logo'));
  print $web_logo;
}

```

I created CMS option of uploading site logo. I also added an option of show/hide this logo (form in node 18). Using the above code, I am able to load the image but don't know how to hide it if this option is not selected. I just want to know how to get the value of this check box. I can write the condition to show or hide this. Please help. Also, please let me know how to include alt option to the above image.

# Answer
Where do you put this PHP code? If it's in the page.tpl.php, then you can use the `$logo`variable to display the field or not.

Otherwise, this configuration is available in your theme. So you need to get your theme configuration, with theme\_get\_setting. You should have a variable 'toggle\_logo' or something like this. The full code would be

```
$test = theme_get_setting("toggle_logo");
if($test) {
   //Put your code here
}

```

If you're using different theme, or you need to get this value for a specific theme, then you need to pass your theme name as second parameter of the function, for example:

```
$test = theme_get_setting("toggle_logo", "my_custom_theme");

```

\[EDIT FULL ANSWER\]

So you just need to check the value of the field field\_options\_site\_logo before outputing the image:

```
$node=node_load(18);
if(isset($node->field_options_site_logo['und'][0]['value']) && $node->field_options_site_logo['und'][0]['value'] == 'yes') {
  $logo_img = file_create_url($node->field_site_logo[$node->language][0]['uri']); //origional image path
  $show_logo = $node->field_options_site_logo['value']; //original image path
  if(isset($logo_img)) {
    $web_logo = theme('image_style', array('path' => $node->field_site_logo[$node->language][0]['uri'], 'style_name' => 'site_logo'));
    print $web_logo;
  }
}

```
> 0 votes

---
Tags: theming, forms
---


# Question
Title: Using Views as a report in a custom module
I'm new-ish to module development. I just need to be pointed in the right direction.

I have a custom module that I think would benefit from a report. The report should show up in the admin reports menu. (I already know how to use hook\_menu to display "Hello world!" as a report in the reports menu.)

It seems to me that the easiest way to compile the data for the report would be to use Views. But where do I go from here? How do I programatically use a View as one of the reports my module provides? (Or am I wrong in assuming that this can be done or is a good way of doing things?)

To be clear: I am not talking about my module providing a default view that shows up in the views menu, but using the data from a View as a report.

What I want is the same result as this idea, but programatically in my module.

# Answer
views\_get\_view\_result is the API you should use to query an existing View and process the results in your module.
> 1 votes

---
Tags: views, routes, log-messages
---


# Question
Title: Using Drupal Default jQuery only on node form?
I need to use the jQuery 2.0 in my drupal 7 site, so i have unset two drupal jQuery files and added the latest version of jQuery using this code in my template.php file so it will not affect the views or other core parts(uses Seven theme):

```
function mytheme_js_alter(&$js){
    unset($js['misc/jquery.js']);
    unset($js['misc/jquery.once.js']);
    drupal_add_js('http://code.jquery.com/jquery-2.0.0.min.js');
}

```

Everything goes fine but just found that it breaks the tagging auto-complete feature, to solve this problem i wish to remove the jQuery 2.0 and add the `jquery.js` and `jquery.once.js` file again only when the page is a form that has a ID `news_node_form` so i made some change with no luck:

```
function mytheme_js_alter(&$js){
    unset($js['misc/jquery.js']);
    unset($js['misc/jquery.once.js']);
    drupal_add_js('http://code.jquery.com/jquery-2.0.0.min.js');

    function mytheme_form_news_node_form_alter(&$form, &$form_state, $form_id){
        drupal_add_js('http://127.0.0.1/drupal7/misc/jquery.js?v=1.4.4');
        drupal_add_js('http://127.0.0.1/drupal7/misc/jquery.once.js?v=1.2');
        unset('http://code.jquery.com/jquery-2.0.0.min.js');
    }

```

}

Any idea how to solve this problem?

# Answer
You cannot use an updated/upgraded version of jQuery 'just like that' with Drupal. Believe me, it might look everything is working fine, but eventually its gonna break.

As Suggested by Motot, you can use https://drupal.org/project/jquery\_update module to use an updated version of jQuery. But I don't think the even the dev version of jquery\_update module supports 2.0

What you can do is, use jQuery's no-conflict feature. Here is a detailed documentation on using different JS libraries along side jQuery https://drupal.org/node/1058168 (You want to use jQuery 1.x & 2.0)

And yes, there is a module for that as well - https://drupal.org/project/jqmulti
> 1 votes

---
Tags: forms, theming, javascript, taxonomy-terms
---


# Question
Title: Why would !order-summary token be available/unavailable depending on payment method?
I'm trying to use a payment gateway module (Icepay for Drupal Commerce), but I noticed that the payment method I choose in checkout influences the availability of order tokens.

I have Commerce Message configured with an email using the !order-summary token (like Commerce Kickstart does). When I choose commerce\_payment\_example's payment on checkout, the email contains the expected line items and total price provided by !order-summary. When I choose Icepay, this part remains empty in the email.

Could the payment method influence the availability of tokens? Is there something the payment module needs to implement for that, or should I be looking at other causes?

# Answer
Of course I find the issue after posting the bounty :s

This Commerce Message issue explains that the problem is that some payment methods need to do a postback, which is executed as anonymous user. This apparently means that the view which returns the order summary (commerce\_cart\_summary) is also executed as anonymous and returns no results, so the token remains empty. The commerce\_payment\_example method does not have this problem because it doesn't rely on any external feedback.

The workaround to disable SQL rewriting in the commerce\_cart\_summary view works (I haven't tested the patch yet).
> 1 votes

---
Tags: commerce
---


title: Migration only doing one row at a time?

text:
# Question
Title: Migration only doing one row at a time?
I have a migration class set up that takes from an XML source ID list that points to individual XML files with data which is then imported into nodes. The migration works but only one at a time. There are no errors in the messages for migration, apache error log, syslog, and doing drupal\_debug in all steps of the migration only shows that the migration goes through one row then stops.

Is there any common issue that might be causing this behavior?

# Answer
The issue was a standard PHP issue in a function that was being called during the batch operation. In this case, the error does not matter, what matters is that I could not see anywhere that the error was happening.

Running migrations via the Migrate UI will not show errors, in some cases, anywhere. To better troubleshoot it is recommended that migrations are run via Drush. Running my migration through Drush I was able to see where the import was failing and why.
> 0 votes

---
Tags: migrations
---


# Question
Title: Any easy way to create Login page in Drupal 7
Most of the tuts I found want me to edit the `code` in `template` but I am not sure about editing the code, so, thought of asking is there any easy way to create Login Form in Drupal 7.

I don't want to show `login block` to everyone, and want to put it in some Page and visit it via `uri` like `http://localhost/login` then only the login page should show.

So, far I have made a `Page` called `login` gave it a `title` with empty `body`, Configured `user-login block` to be shown in `content` area and be displayed only in `login` page. So far so good, it looks cool, but the thing is: after logging in I can see the same login page as `Blank Page`. I did something like the `login page` would only be accessible by `anonymous users` but no luck.

My quest is either I should be able to `redirect` the users to main page after logging in, or have a separate `login page` instead of using the block which came by default with D7 installation. Any ideas ???

# Answer
One easy possible way to do this is you can create a node with no content and assign a url "/login" to that node and then assign login block to content region for that page only.
> 2 votes

# Answer
I entered the login as a menu-item but visible for all (just not as obtrusive as the login block). Just create a "Login" list item in your main menu (admin-interface: structure-\>menus-\>main menu-\>list links-\>add link) with path the (system) page "user/login". It will be visible for users who are not logged in, and disappear when they are. If you also enter a similar (with same weight) list-item "Logout" with path "user/logout" that will only be visible for logged-in users, and now they can easily logout as well...

You can now remove the login block that is default on your homepage.
> 0 votes

# Answer
Consider using either the Luxe or LoginToboggan modules, as they do exactly what you're looking for.
> 0 votes

# Answer
By default Drupal have a separate user login page. You can access it by using this url:

> http://yoursite.com/user/login OR http://yoursite.com/user

There is no need to create separate user login page.

To redirect the user to specific page after login, you can consider LoginToboggan, Login Destination or Login Redirect module.
> 0 votes

---
Tags: 7, users, redirection
---


# Question
Title: How change "user menu" to current username
I'm looking for a way to change the label "user menu" to be the current user's username. I am using the default Drupal 7 theme, Bartik, if that makes any difference.

# Answer
> 7 votes
You could do that with hook\_preprocess\_block

e.g, in template.php

```
function MYTHEME_preprocess_block(&$vars){

  global $user;
  $block =& $vars['block'];

  if ($block->module == 'system' && $block->delta == 'user-menu') {
    if (user_is_logged_in()) {
      $block->subject = check_plain($user->name);
    }
  }

}

```

Clear theme registry cache after adding new preprocess function.

# Answer
> 1 votes
You could use the Menu Token module along with the Token module to achieve this.

> Menu Token module provides tokens, that could be used in title or in path of menu items (links).

A detailed step by step procedure to achieve the use case can be found at the answer here.

# Answer
> 1 votes
No need for Menu Token; as long as you have the Token module enabled, just set the User Menu Block title to `[current-user:name]`

---
Tags: theming
---


# Question
Title: Can contextual drop-down menu replace menu tabs?
When I am viewing stuff I have admin rights to the tabbed menu with stuff like 'View | Edit | Outline | etc ' takes up too much space.

Is there a way to switch drop down menus similar to those used for blocks?

# Answer
> 1 votes
Contextual tabs module used in Open Atrium distribution seems to be exactly for that:

> Moves the normal Drupal primary tabs into a drop-down "contextual links" menu to the right of the node title.

Screenshot:

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


# Question
Title: How can I change the shipping rate basing on what the cart contains?
I have configured my client's online vineyard store to display a flat rate up to £50 and free shipping thereafter. However, they are now selling *Vineyard Tour* vouchers which are free to ship.

I am trying to set up a condition whereby:

* If the cart only contains a vineyard tour voucher or if the order is over £50 make the shipping rate free
* If the cart contains any other product (as well as a voucher) and is less than £50 standard shipping rate of £8.50.

# Answer
> 0 votes
You can use a combination of the modules Rules Bonus Pack, Conditional Rules, and Commerce Rules Extra to create condition loops to compare a data value and set the shipping type in the actions.

```
Ex:
Event = When calculating shipping

Condition = If cart contains item of type X

Action = add IF > Order total is greater than $50 > Add line-item: Free shipping

     add ELSE > Add line-item: Standard shipping

```

---
Tags: commerce
---


title: Limit drush sync paths?

text:
# Question
Title: Limit drush sync paths?
I have 3 drush-aliased sites: @DEV, @STAGE & @PROD

rsync & sql-sync all work between them. At the moment, that's both directions, between any two sites.

I want to limit the sync paths to only allow sync in the following cases:

* (1) @DEV -\> @STAGE, files & db
* (2) @STAGE -\> @PROD, files & db
* (3) @PROD -\> @DEV, db ONLY

How do I limit drush sync to allow only those three cases of sync, preventing all others?

# Answer
> 3 votes
You can do this with a policy file. See examples/policy.drush.inc.

In the example policy file, specific named destinations are rejected. To increase the stability of the system, you could reverse this test to reject any destination except for known good targets, or perhaps some combination -- for example, you could reject sql-sync to any remote destination except @stage.

You probably should not allow sql-sync to @prod, but of course it's up to your policy to decide that. For moving configuration stored in the database, see ctools\_export\_bonus.

---
Tags: drush, staging
---


# Question
Title: Node reference shows as empty to anonymous users
I'm sure this is a simple configuration issue, but (I think) I've looked everywhere and I can't see what's wrong...

I have a content type "Sponsor" that is basically just a name (title) and a logo (image field). I created a few sponsors for my tests.

I also have another content type ("City") with two node reference fields, both of which allow to pick an unlimited number of sponsors (nodes). (I use two fields because one should display the sponsors logos, while the other should only display the name of the sponsors.)

On "Manage display" (for the City content type), the first node reference field format is "rendered node", while the second is "Title (no link)".

So when I visit a "City" page, I should see two lists of sponsors (one with logo, the other one without).

It works for me (admin), **but** for anonymous users, the sponsors simply don't show up. They are published, though, and anonymous users can access the sponsors pages (and see the logo as well as the title). But when they are referenced through the "City" nodes, the sponsors somehow become invisible (not rendered).

What am I missing here?

Weird thing is, I have another page where I use Views to output the list of sponsors for a city: in that View, the sponsors are still invisible (nor anonymous users, not admin), **but** the list elements (containing each sponsor) are indeed rendered --so anonymous users see empty bullet points and it matches the number of sponsors that *should* be visible there.

Note: I also use Panels to display the city. But the problem is still there when I disable the node template Panel, so it's not that...

# Answer
Found it!

I'm using Organic Groups on this site, and I didn't realize that you could grant access permission (view/edit) on a *field* level (contrary to the base Drupal permissions system, which works only with content types). Since it doesn't show up on the "normal" Permissions page, it's easy to miss. (It's in configuration \> Organic groups \> OG permissions overview).

So it was indeed a simple configuration issue.
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: Sanitized text input for EntityMetadataWrapper set()
Through searching, I've found plenty of examples using the EntityMetadataWrapper `set()` function to update entity fields, and have implemented it successfully in my module. However, I haven't been able to find much in the way of documentation / best practices on the different array options you can pass to `set()`. I want to make sure the way I'm updating data won't cause unforeseen issues later on.

I am doing a straightforward update of text field values in a form submit callback:

```
function hook_FORM_ID_submit(&$form, &$form_state) {
  // Get the node.
  $node = node_load($form_state['nid']);

  // Create entity metadata wrapper to get and set values easily.
  $node_wrapper = entity_metadata_wrapper('node', $node, array('bundle', $node->type));

  // Set fields
  $node_wrapper->field_quip->set(array("value" => $form_state['values']['field_quip']['value']));
  $node_wrapper->field_short_sentence_summary->set(array("value" => $form_state['values']['field_short_sentence_summary']['value']));

  // Save node.
  $node_wrapper->save();
}

```

I am passing `set()` an array with only one key: `value`. This seems to be working fine. However, I notice that when I call `value()` on that same field before I set a new value, it returns an array with three keys:

```
$original_value = $node_wrapper->field_quip->value();

// Output of $original_value:
// Array (
//   'value' => '<p>The original value</p>',
//   'format' => 'general',
//   'safe_value' => '<p>The original safe value</p>',
// )

```

The way I am current setting fields, I lose the sanitized value. Will this come back to bite me? Should I be running `check_markup()` on the value and passing `format` and `safe_value` to `set()`, rather than an array with just `value`? I might be splitting hairs here, but I want to make sure I do things right.

# Answer
It turns out that if you *just* set the `value`, Drupal will not display your HTML without converting your tags to entities. So the value `<p>Foo bar</p>` will be displayed literally in Views (and other areas) as `<p>Foo bar</p>`.

Rather than attempt to create a sanitized `safe_value` myself before calling `set()`, I found that if I passed a `format` value, Drupal will take care of the sanitization for me with the filter settings defined for that format.

So the correct syntax is:

```
$quip = array(
  "value"  => $form_state['values']['field_quip']['value'],
  // Change to match the text format of your field.
  "format" => "general"
);
$node_wrapper->field_quip->set($quip);

```
> 6 votes

---
Tags: 7, entities, security
---


# Question
Title: Drupal Field Hierarchy or Fields By Selection
Is there any modules that support a hierarchy for fields? Nodes and fieldable entities in drupal seem so monolithic. For example customers could be categorized into three categories:

Customer A Customer B Customer C

When customer A is selected then I only want specific fields shown according to that selection, and would be different for B and C.

I know I can do this via a hook\_form\_alter using the ajax callback attribute but wasn't sure if there was something already created for this. I seen the hierarchy module but seems to be specific towards taxonomy.

# Answer
> 1 votes
I think the Conditional Fields module could provide a solution for you.

> Define dependencies between fields based on their states and values.
>
> Conditional Fields for Drupal 7 is an user interface to the new States API, plus the ability to modify fields appearance and behavior on certain conditions when viewing content.

---
Tags: entities
---


title: Exporting a block/module?

text:
# Question
Title: Exporting a block/module?
I'm working on migrating a theme from Drupal 6 to 7 but my dev site doesn't have a block used on the old one. I need to export the block from the old one to the dev one, but I can't figure out how. Help please.

# Answer
> 0 votes
You can not export Drupal core blocks directly. You can can either write it in a custom module, see http://fourkitchens.com/blog/2012/07/18/building-custom-blocks-drupal-7.

Or, you could recreate it using boxes: https://drupal.org/project/boxes, which can be exported using Features.

> Boxes module is a reimplementation of the custom blocks (boxes) that the core block module provides. It is a proof of concept for what a re-worked block module could do.
>
> The module assumes that custom blocks are configuration, and not content. This means that it is a reasonable action to ask for all blocks at one time, this is in fact exactly what the core block module does.
>
> Boxes provides an inline interface for editing blocks, allowing you to change the contents of blocks without going to an admin page.
>
> Boxes provides exportables for its blocks via the (required) Chaos tools module. This allows modules to provide blocks in code that can be overwritten in the UI.

Or, you could copy and paste the block contents into a new block too.

---
Tags: 7, theming, importing-exporting
---


title: What modules are used by Open Atrium 2?

text:
# Question
Title: What modules are used by Open Atrium 2?
I am looking for a list of the modules in the standard Open Atrium 2 install, something similar to those posted for Drupal Commons and Acquia Commons like:

https://drupal.org/node/2160755 https://docs.acquia.com/commons/module

Is one available? Where is it?

Thanks!

# Answer
> 1 votes
There's a set of drush make files in the project directory. Those list the various dependencies.

# Answer
> 0 votes
Install it locally and via drush do `drush pml` and it will tell you all installed modules. Not every distribution lists dependencies, they assume you can track it down. It's dependant on their own OA\_\* modules (and their dependencies) and the Panpoly distribution. http://drupalcode.org/project/openatrium.git/blob/HEAD:/drupal-org.make

You could always make a support request and supply the list yourself to their Project Issue Queue and help the project documentation along after you checkout `pml` via drush.

---
Tags: distributions
---


title: Manual crop not working in Chrome

text:
# Question
Title: Manual crop not working in Chrome
Is anyone using manualcrop https://drupal.org/project/manualcrop? It works fine in Firefox but doesn't work in Chrome.

Using Drupal 7.

Thanks!

# Answer
There's an issue queue going on drupal.org for this - https://drupal.org/node/2093533

It looks like the module maintainer may have fixed the chrome issue with the latest dev version
> 0 votes

---
Tags: media
---


# Question
Title: How can i publish my content with Schedule
I want to publish some content in a day, not all of unpublish content at once.

for example I have 20 unpublish content and i want to publish 2 random content in a day at 13:00.

How can I resolve this?

# Answer
> 2 votes
If you aren't concerned with the "random content" portion of your question you could use the scheduler module to accomplish the task - https://drupal.org/project/scheduler which would allow you to set specific times during the day when you wanted content to be published.

If you do want it to be randomized though, you're going to need to use rules - https://drupal.org/project/rules and VBO - https://drupal.org/project/views\_bulk\_operations.

(I'm assuming Drupal 7)

1. Create a view.
2. Under Fields add a "Bulk Operations: Content" field. Set the number of entities to your desired number (in this case 2.) Set it to publish content, Enqueue the operation instead of executing it directly.
3. Under Filter Criteria set it to "Content: Published (No)."
4. Under Sort Criteria set it to "Global: Random (asc)"
5. Under Pager set to "Display a specified number of items" and choose the number of desired items (in this case 2)
6. Save your view.
7. Now to go Rules configuration.
8. If you are only running cron once every 24 hours (at 13:00) you could trigger this on cron run, otherwise you'll need to set up some additional steps. Assuming the 24 hour cron, set your rule to execute when "Cron maintenance tasks are performed".
9. Under actions click add action then select "Load a list of entity objects from a VBO View." Select the view you just created from the value dropdown. Click save.
10. Then under actions click add loop. Default variable name at the bottom should be "list\_item." Click save.
11. Now click the add action button horizontal to the loop you just created. Select node publish content. For the "data selector" field use list\_item from the loop above. Click save.
12. Run cron to test.

2 random pieces of content should publish.

---
Tags: nodes, rules
---


# Question
Title: How can I redirect user/*/edit to another page based on user content?
I have a site with the following relationship: for every user, there is one corresponding (node) profile. For the user/\*/edit, I would like the user to actually edit their profile node, not the user account. I've thought about preprocessing the page template to make something available in order to then re-write the secondary menu in the template - but which variable can I use? It's not available in the $user array.

# Answer
In this case, I added an entity reference field to both the the user and profile node. In the page template, I can user\_load() the uid of the logged-in user and have the entity reference available for theming.
> 0 votes

# Answer
So in broad strokes, basically what you want to do is grab the user's uid and then open for editing the corresponding profile type node owned by that user.

So, if you have that user's uid in `$uid`, it would be something along these lines:

```
$nid = db_select('node', 'n')
        ->condition('n.type', 'YOUR_PROFILE_NODE_TYPE')
        ->condition('n.uid', $uid)
        ->fields('n', array('nid'))
        ->execute()->fetchField();

```

which, if I've not typo'ed anything will set `$nid` to the node id of the node of type YOUR\_PROFILE\_NODE\_TYPE that is owned by `$uid`.

If there is only one, that's the node we are looking for.

So, now you just need to create a link to `node/$nid/edit` and you're all set. (Somewhat obviously, you want to present this link only to admins and the user who owns the profile.)

So, where do you put all of this?

Of course, you could preprocess this into a variable that's used in a page template, but you could also create a new menu item as well, eg `user/#/edit-profile` that grabs the user id out of the second argument and then does all of the above to grab the actual nid and then presents the node edit form, but now we are getting past the broad strokes :) (But hook\_menu() is the place to look, with `user.module` a great starting point for example code for `user/#/edit` to modify)
> 0 votes

# Answer
Consider making a new solution based on Profile2, otherwise spice you current solution up with the Rules module. :)
> 0 votes

---
Tags: users, theming
---


# Question
Title: Cannot modify header information following page not found error
I see a lot of these in my dblog;

> Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/includes/bootstrap.inc:1368) in drupal\_send\_headers() (line 1220 of /var/www/html/includes/bootstrap.inc).

or

> Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/includes/common.inc:2700) in drupal\_send\_headers() (line 1220 of /var/www/html/includes/bootstrap.inc).

and

> Warning: ini\_set(): Cannot change zlib.output\_compression - headers already sent in drupal\_serve\_page\_from\_cache() (line 1357 of /var/www/html/includes/bootstrap.inc).

This happens after a page not found error of a comment that had been deleted. Even though this does not generate any problem, having them filling up my dblog annoys me. Any help will be appreciated.

Thank you

Edit: Fixed it temporarily by adding a redirect.

# Answer
Views specifically has a bug that can cause this, as well -- see my response in Warning: Cannot modify header information - headers already sent as well as the issue and patch in #16 here.
> 0 votes

# Answer
Please note that there are a lot of things that can cause this, and it's very hard to say what goes wrong depending on your system. But the following seems the most plausible:

The page is deleted, so drupal immediately serves a cached 404 page (with 404 header). Some other module which perhaps invokes a wrong hook, then tries to alter the output or output header. Which it can't because the page is already compiled.

You could try to read the headers of a regular page and one of a 404 page to find out what header is missing (and thus what module might be causing it) I use Fiddler to post such requests and read the server's response, but there are plenty of other tools. You could also try to read the issue queues of the modules you use, try to find if someone else ran into this problem earlier.

As a last resort you could start disabling your modules and try to find when it stops. Or use 'find in files' to see if there are modules calling 'drupal\_send\_headers'.

But then again, it might not even be a module...

Please note that a theme is also capable of editing output, and thus might be causing this.
> 2 votes

---
Tags: 7
---


title: Complicated views

text:
# Question
Title: Complicated views
I am working on a database system with Drupal 7. I have node types employee, experience etc. With relationship (reference entity), each employ may have zero or more records in experience. Experience node type has a date field (with start and end date) and what I want is to

1. Calculate a **duration** or each experience record from stat and end date.
2. Calculate total experience (sum of **durations**)
3. Display total experience (that is sum of the durations) in view of employee with other fields of employee

Example;

Employee VIEW
E\_code, Ename, total experience
1 xyz 2 years and 3 months
2 nmn 6 months
3 abc 1 year 7 months

Employees records
Ecode, Ename, Ephone, etc.
1 xyz 5458254 etc
2 nmn 59457495 etc
3 abc 45749 etc
. . . . .and so on

Experience records
E\_code, exp\_date
1 01/01/2010 to 01/03/2011
2 01/01/2011 to 30/06/2011
1 01/06/2012 to 30/09/2013
. . . . and so on

How to bring total experience of each employee in the Employee table View?

Another question how we refer node field i.e. exp date for global math expression or computed field? In other view i have date field and need subtract that from current date (now?) I thought the global math expression can do that by joint\_Date - Now. But not sure. Note I don't need to save this duration in field it should appears in view on go.

Thanks in advance.

# Answer
> 0 votes
Hope this will help you, you can use computed\_field for calculating the field or you can use the Views Calc.

---
Tags: views
---