# Question
Title: load custom CSS/JS for each CKEditor instance on page
I would like to find out the best way to load custom CSS/JS for each textarea with CKEditor. For me, each Content Type has different CSS/JS and I would like to load them with the CKEditor on that particular page.

How do I hook into the CKEditor module to do just that?

P.S CKEditor is an independent module and not part of WYSIWYG Drupal Setup.

# Answer
> 0 votes
use `hook_page_build` to add or remove css or js files to the page based on the url. See the examples module for developers on how to add/remove js or css and to examples of render arrays.

your question is not so much about the CKeditor module or WYSIWYG module -- just how to customize css and js on specific criteria such as the page url.

---
Tags: wysiwyg
---


# Question
Title: Need to enter title before I make blog entry
I have installed the Organic groups to make a multi-blog site. The problem is that when I try to create a blog entry, I only get a "Title"-field, which I need to save, and then edit the entry to enter the body text.

Any ideas how to fix this so I get the full blog entry fields when I click "Add content".

This is how it looks like now:

# Answer
Seems like an issue with the OG field permissions `Configuration\Organic Groups\OG field permission overview`.

Edit the node type and check the 'Edit Body field' and 'View Body field'.
> 0 votes

---
Tags: organic-groups, nodes
---


# Question
Title: How to get newly created node ID after Feeds importing?
I programmatically executed feeds importer to create new nodes. I have to set some fields programmatically after importing. I check the hooks in feeds.api.php, and didn't find a solution. Is there any way that I can get the newly created node ID by the importer? Thanks

# Answer
I found the solution. Use $entity NOT $entity\_id in hook\_feeds\_after\_save.
> -1 votes

---
Tags: nodes, feeds, importing-exporting
---


# Question
Title: Catchable fatal error: Object of class stdClass could not be converted to string includes/theme.inc on line 2742
I did noting ,when try to clear cache I see this error **Catchable fatal error: Object of class stdClass could not be converted to string includes/theme.inc on line 2742**

```
foreach (array_keys($regions) as $region) {
    // Assign region to a region variable.
    $region_content = drupal_get_region_content($region);
//  $tmp = (array) $variables[$region];
    //ym(empty($tmp));
//  if(empty($tmp))
    isset($variables[$region]) ? $variables[$region] .= $region_content : $variables[$region] = $region_content;

```

I google this error but didn't find anything, anybody know what is the reason of this error and how can I resolve it?

# Answer
> 2 votes
Clearing your cache goes through all of your code looking for hooks, so something you have installed or updated or written since the last time you cleared cache has this error.

The error technically means that you are trying to use the wrong **type** of variable in a particular function. In my limited experience, this usually means you have passed the wrong type of variable to the function before it.

In your case, it looks like you are trying to add a stdClass object `$region_content` to a string, which is why it is trying to convert it. You will likely need to dig into $region\_content to find the markup you are looking for before adding it to your string.

---
Tags: theming
---


title: styling webform into 2 columns

text:
# Question
Title: styling webform into 2 columns
I am looking to style a webform that I have with the drupal webform module, but i am having a little bit of an issue. I would like to style the form into 2 columns and I am assuming the best way to go about this would be to throw the content into 2 div separate div tags. I have looked around and came across How do I theme a webform?.

I am using the following line in my file.

```
<?php print drupal_render($form['submitted']['name']);`

```

Unfortunately, no matter what I try, I can't seem to get the new webform-form-nodeid.tpl.php to work. They say the file should be created as webform-form-36.tpl.php (where 36 is the node ID, in my case) and that I should put it in my custom theme directory. I have done this and had no luck. I have also tried placing it in the template directory for the webform module, but it didn't work.

Does anyone have any idea on how to help me?

I also found that Drupal 7 looks for two hyphens instead of one. I tried renaming the template file webform-form--36.tpl.php, but it didn't have any effect.

I was able to specify the specific node by changing the filename to node--36.tpl.php, but I still feel like there should be a way doing this with the webform name included. Does anyone have any idea?

Please note that I know I was using 36. I have since then changed to 102.

>

# Answer
What I did for one of my client in order to get the webform in two columbns, was to create two "Fieldset", containing the fields for column 1 and column 2.

Then with css, I added to my webform this property :

`.webform-component-fieldset {width:50%; float:left;}`

Of course, there are other ways of doing it, like `display:inline-block`, and maybe you need to be more precise with the css so you don't mess up other webforms.

And if you don't want the title of the fieldsets, you can do a simple:

`.webform-component-fieldset legend {display:none;}`

I think that's the easiest way of doing it.
> 4 votes

# Answer
This could probably be used for any theme generated output.

This is using the Devel module.

Find the hook required:

```
/**
 * Implements hook_preprocess().
 */
function YOURTHEME_preprocess(&$variables, $hook) {
  dpm($hook);
}

```

For web forms hook = webform\_form

Implement this function:

```
/**
 * Implementation of hook_preprocess_HOOK().
 */
function YOURTHEME_preprocess_webform_form(&$variables) {
  dpm($variables);
}

```

In variables you will find the key "`theme_hook_suggestions`".

Add what you would like your template to be called (use underscores).

Eg:

```
$variables['theme_hook_suggestions'][] = 'webform_form_' . $variables['nid'];

```

Find the default theme output in the Webform module:

**all/modules/webform/templates/webform-form.tpl.php**

Copy this to your theme directory ( I used folders to keep it organised).

**all/themes/YOURTHEME/templates/webform/webform-form.tpl.php**

Rename file to your suggestion (convert underscores to dashes):

**all/themes/YOURTHEME/templates/webform/webform-form-NID.tpl.php**

Flush Caches

Breakup the form as needed (using twitter bootstrap v3 classes for columns in the example below):

```
<?php
  // Print out the progress bar at the top of the page
print drupal_render($form['progressbar']);

  // Print out the preview message if on the preview page.
if (isset($form['preview_message'])) {
  print '<div class="messages warning">';
  print drupal_render($form['preview_message']);
  print '</div>';
}

?>

<!-- Left Column -->
<div class='col-sm-6'>
  <?php print drupal_render($form['submitted']['contactus_first_name']); ?>
  <?php print drupal_render($form['submitted']['contactus_last_name']); ?>
  <?php print drupal_render($form['submitted']['contactus_email']); ?>
  <?php print drupal_render($form['submitted']['contactus_contact_number']); ?>
</div>

<!-- Right Column -->
<div class='col-sm-6'>
  <?php print drupal_render($form['submitted']['contactus_today_i_would_like_to']); ?>
  <?php print drupal_render($form['submitted']['contactus_message']); ?>
</div>

<!--Rest of the form-->
<div class='col-xs-12'>
  <?php print drupal_render($form['submitted']); ?>
  <?php print drupal_render_children($form); ?>
</div>

```
> 2 votes

# Answer
have you seen the community documentation about theming webforms with a preprocess function? https://drupal.org/node/1157306

example to reformat some elements to be on one line:

```
function garland_preprocess_webform_form(&$vars) {
  drupal_add_css(drupal_get_path('module', 'webform') . '/css/webform.css');
  drupal_add_js(drupal_get_path('module', 'webform') . '/js/webform.js');
  $vars['form']['submitted']['name']['#prefix'] = '<table border="0"><tbody style="border: 0px;"><tr><td>';
  $vars['form']['submitted']['name']['#suffix'] = '</td>';
  $vars['form']['submitted']['phone']['#prefix'] = '<td>';
  $vars['form']['submitted']['phone']['#suffix'] = '</td>';
  $vars['form']['submitted']['city']['#prefix'] = '<td>';
  $vars['form']['submitted']['city']['#suffix'] = '</td></tr></tbody></table>';
  if (isset($vars['form']['details']['nid']['#value'])) {
    $vars['nid'] = $vars['form']['details']['nid']['#value'];
  }
  elseif (isset($vars['form']['submission']['#value'])) {
    $vars['nid'] = $vars['form']['submission']['#value']->nid;
  }
}

```
> 1 votes

---
Tags: 7, theming, webforms
---


title: Open poll results in popup / overlay

text:
# Question
Title: Open poll results in popup / overlay
I'm using the Poll module in Drupal core (also using Poll blocks and Ajax poll).

As designed, when I vote I'm taken to the results page, but I'm wondering if it's possible to display the results as a popup on the front page, where the poll block is.

I searched a bit and I know something similar can be done with lightbox2, colorbox, colorbox node, etc., but these solutions require that I assign a class or rel attribute to an anchor tag, and then open whatever URL I enter as a popup. However, the poll calls the results page on clicking the submit button. Is there a way I can change this to accomplish what I need?

# Answer
Please check answer. I think this may help you toy solve your problem.

**ANSWER LINK**
> 1 votes

---
Tags: 7, polls
---


# Question
Title: How to populate an autocomplete using a web service?
I want to populate a form field, an **autocomplete** widget, with values from an external REST web service without actually importing the data to my database first (on-the-fly).

How do I do that? Is there a module for that or do I need to create one myself?

# Answer
> 3 votes
There is not, as far as I can tell, a module that addresses this currently, though it wouldn't be terribly hard to build with some time on google.

But since you don't intend to harvest the responses from the API a javascript/jQuery solution may be the easiest route. Any time I build a new site I set up a module to house custom functionality in that is specific to the site, I suggest you throw together a .module and .info file and add your js that way, Drupal documentation on putting together a custom module is pretty extensive.

If this helps:

```
$("input#autofill").autocomplete({
        source: function (request, response) {
            var term = request.term;
            var restUrl = 'http://myRestService.com/search/'+term;

            $.getJSON(restUrl, function (data) {
                var items = [];
                $.each(data.results, function (key, val) {
                    var item = {
                        label: val.Label,
                        value: val.Value
                    };
                    items.push(item);
                });

                response(items);
            });
        }
    });

```

---
Tags: ajax, 8
---


# Question
Title: Adding a webform to a different content type
I have an "event" content type. Now I want to add a Webform to it so that people can request purchasing and availability information.

I checked my event content type in `admin/config/content/webform` under `Webform-enabled content types` but how can I now add the form to my existing content?

# Answer
> 1 votes
Your webform is empty. You need add some fields to the webform. You can add webform to any "event" node. Try this: go to your\_host/node/node\_id/webform and you can see wizard for webform elements!

---
Tags: forms, nodes, webforms
---


# Question
Title: Module invoke webform redirecting validation
On one page I have this code, that loads my Webform:

```
$block = module_invoke('webform', 'block_view', '660');
print render($block['content']);

```

But when I click on submit button, validation leads me to another page (webform page). How can I stay on current page, where webform is loaded?

# Answer
> 1 votes
Go to `admin/block` and edit your webform block and check "`Show all webform pages in block`" and all errors display in block not in node.

This should resolved the problem, however you can check more about this problem here: https://www.drupal.org/node/1308806

---
Tags: webforms
---


title: Upgrading from 5.3 to current

text:
# Question
Title: Upgrading from 5.3 to current
Is there a reasonable upgrade path from drupal 5.3 to the current version or should I just rebuild the site from scratch? It's a pretty small site, but it does have a few custom content types, and use tac\_lite for role-based security.

These are the modules I have installed:

```
tac_lite
filebrowser
private_upload
role_weights
site_user_list
user_import
cck
views
imagefield
imagecache
token
pathauto
path_access
marksmarty
devel
admin_menu

```

# Answer
Nope, there is none. No matter if by "current" you mean 7.x or 8.x, skipping 6 is too much gap, and even upgrades from 6 to 7 are known not to be painless and safe.

You may try to rebuild site's structure from scratch, and then use Drupal-to-Drupal data migration module to import your data:

> migrate\_d2d provides a framework based on the Migrate API for migrating content from Drupal 5, Drupal 6, or Drupal 7 sites into the Drupal 7 site where it is installed. As of 7.x-2.1-beta1, it requires Migrate 7.x-2.6-beta1 or later.
> 1 votes

# Answer
If you want to upgrade drupal 5.x to drupal 7.x then you have to updgrade it in two steps.

1. Upgrade drupal 5.x to drupal 6.x.
2. and then upgrade drupal 6.x to drupal 7.x.

I have done up-gradation of a drupal website from 5.x to 7.x alongwith thousands of nodes migrated successfully to new one.

Drupal upgrade steps are listed in this link https://www.drupal.org/node/570162. I have followed these steps to make migrate successful. Currently site is running without any error.

Remember, there are some things which are included in core when you upgrade from drupal 5 to 6. Key point is you follow these 20 steps to make it functional.
> 0 votes

---
Tags: upgrading
---


title: Upgrade a large site

text:
# Question
Title: Upgrade a large site
We are running a middle sized Drupal 6 site (about 10k nodes plus comments, 200k user accounts), which is using many additional modules like OG, Views, CCK, Messaging, Notifications, CKEditor, Syntaxhighlighter, Pathauto, Token, Captcha, User Relationships, Fivestart, XML Sitemap. In addition, there are about 10 custom modules, most of them rather simple.

We now wonder how to upgrade to D7? We evaluated the following strategies, which don't seem to work:

1. **Start from scratch with a blank D7 installation**, configure it, set up all modules as we need them and migrate the existing content. The problem is about migrating existing content. When we set up the site, we need to create things like node types, roles, taxonomies, but when we migrate the content, the IDs of those entities might differ. It seems to be a very error prone approach.
2. **Use official upgrade procedure**. If we are not mistaken, the idea of the official upgrade procedure is disable all third party modules, replace core with D7, run update procedure, upload D7 version of modules, enable them and run their update and hope everything goes well. Problem here is that a lot of the modules we are using are moved to core or work now differently, but we still reference their functions in our theme all over the place. This again is very error prone. Also, the database contains afterwards many unused tables, but it is very hard to tell if we really need them.

What other options do we have? Personally, I would prefer to follow strategy 1, but we can't figure out how to migrate content.

# Answer
> 1 votes
Although both methods are valid, #2 can be painful if you have a lof of custom code in your app. I would consider option #1. Migration is quite straightforward using migrate module.

There *is* a little more overhead than doing a straight-up upgrade but the process is very well documented and well integrated with Drush. With migrate you can even have roll-backs and migration reports out of the box, all scriptable and quite easily automated.

I have done some pretty large migrations myself with this module and it works like a charm once in place.

PS: No worry for your entity id's, migrate uses the same nid when it imports the nodes.

# Answer
> 0 votes
I have done upgradation of a drupal website from 6.x to 7.x alongwith thousands of nodes migrated successfully to new one.

Drupal upgrade steps are listed in this link https://www.drupal.org/node/570162. I have followed these steps to make migrate successful. Currently site is running without any error.

---
Tags: 7, upgrading
---


title: Correct way of upgrading with huge data

text:
# Question
Title: Correct way of upgrading with huge data
I have a Drupal 6 site that contains hundred of thousands of node and bunch of custom and contributed modules. My problem now is how can I upgrade this correctly in Drupal 7. I tried to steps presented in DrupalCon Denver which is a good steps for me, but I have a problem in converting the data when running update.php which stops the process.

Is there any good way to handle this case?

# Answer
Option 1:

1. Inventory your 3rd party modules as well as your custom modules. Identify those modules that has a Drupal 7 version or if it's included in Drupal 7 core.
2. Update the Drupal 6 core.
3. Update the contrib modules and themes.
4. Disable contrib modules.
5. When everything is up-to-date and contrib modules are disabled, run update.php. This process will take time depending on how big is your database.
6. Enable your modules and start fixing some API that is not supported by Drupal 7. Use coder module to assist you.
7. Check, check, check.

Option 2:

1. Build from scratch.
2. Use migrate module to migrate you Drupal 6 db to Drupal 7.
> 6 votes

# Answer
I have done upgrade of a Drupal website from 6.x to 7.x along with thousands of nodes migrated successfully to new one.

Drupal upgrade steps are listed in this link https://www.drupal.org/node/570162. I have followed these steps to make migrate successful.
> 0 votes

---
Tags: 7, nodes, updating
---


# Question
Title: Organic groups automatic audience selection
I am working with organic groups. Within each group, permitted users are allowed to create their own pages.

**What my problem is that I need to set the audience for a new page automatically as the group the user is currently in.** This is so that the user cannot manually change the group the post should go into but instead it's automatically and permanently set ( unless an administrator changes it ).

Does anyone know of a way that I might accomplish that?

# Answer
You can use the prepopulate module to pass the group's gid to the node add form.
For example, the link will looks something like this:

```
node/add/discussion?edit[group_audience][und]=4

```

You could then hide the group selection box with css so the user cannot change it. For a more robust solution you would code a form hook. Here is an example.
> 1 votes

# Answer
I like the idea of using a Rule and have gotten it to work using the following Rule config: Event=Before Saving Content, Condition=Content is of a Certain Type, Action: Entity=Node, Group=Site:Current-group - YES - works like a charm!
> 1 votes

# Answer
I know this is an old thread, but I found this in my own search.

I'm new to this, but I think this is going to work for me.

NEW "RULE"

Event = Before Saving New Content --- Node/Content type Action = Data/set data value/node:og-group-ref:0 (Groups Audience)
> 0 votes

# Answer
With Drupal 7, you don't need the Prepopulate module.

You can just use this `node/add/blog?og_group_ref=1` where 1 is the group ID.
> -1 votes

---
Tags: organic-groups
---


title: add a menu to a user menu

text:
# Question
Title: add a menu to a user menu
I'm defined a menu with a hook\_menu, but he appears in navigation menu. how do I put in the user menu?

```
$items['budget/view'] = array(
    'title'             => t('Ver gastos'),
    'description'       => 'Veja quanto é que anda a gastar',
    'page callback'     => 'page_budget_view',
    'page arguments'    => array(2,3),
    'access callback'   => ($user->uid > 0),
);

```

# Answer
> 1 votes
You can use `'menu_name' => 'primary-links';` in your code and of course you have to alter the `primary-links` to the menu of your choice.

```
$items['budget/view'] = array(
  'title'             => t('Ver gastos'),
  'description'       => 'Veja quanto é que anda a gastar',
  'page callback'     => 'page_budget_view',
  'page arguments'    => array(2,3),
  'access callback'   => ($user->uid > 0),
  'menu_name'         => 'primary-links',
);

```

# Answer
> 0 votes
For user menu you should use this

```
'menu_name' => 'user-menu',

```

---
Tags: 7, routes
---


# Question
Title: How to make sure my behavior is triggered before AJAX?
I have a form elements that looks like this:

```
  $form['properties'][$property->idProperty] = array(
    '#title' => $property->Label,
    '#ajax' => array(
      'callback' => 'mymodule_filter_ajax',
      'wrapper' => 'mymodule-filter-result',
      'method' => 'replace',
      'effect' => 'fade',
    ),
    '#attributes' => array(
      'autocomplete' => 'off',
      'class' => array('exclusive'),
      'exclusivity_group' => array ( $property->ExclusivityGroup )
    ),
  );

```

The point of it is to have only one element from each group used at a time. To enforce that exclusivity, I created behavior like this:

```
(function($) {
  Drupal.behaviors.behavior_name = {
    attach: function (context, settings) {

      $('select.exclusive', context).on('change', function(){
        // Make all not selected
        $("[exclusivity_group='"+$(this).attr('exclusivity_group')+"']").not(this).find("option").attr('selected', false);
        // select "all"
        $("[exclusivity_group='"+$(this).attr('exclusivity_group')+"']").not(this).find("option[value='all']").attr('selected', true);
      });
    }
  };
})(jQuery);

```

*Note that both code blocks above are simplified, please don't criticize it too much as this is not actual code I'm using posted verbatim.*

How can I make sure my behavior acts before AJAX? If it happens to act after AJAX, I may end up with two fields set to something other than *'all'*, and that's specifically what I wanted to avoid. I may use `$triggering_element` to detect if it was one of "exclusive" fields, and I probably will, even if only as a secondary precaution, but I would strongly prefer to have things happening right in the JavaScript part.

---

I tried using this answer, but I don't think I understand how it works. I tried:

```
  $('select.exclusive', context).each(function(){
    console.log($(this).attr('id'));
    Drupal.ajax[$(this).attr('id')].options.beforeSubmit = function (form_values, element, options) {
      console.log(element.html());
    };
  });

```

First `console.log` returns IDs as expected. And it works, `beforeSend` is, indeed, changed as it should, it's function gets executed when needed. Sadly `console.log(element.html());` returns content of a whole form, not the triggering element of AJAX, so I'm not able to safely enforce exclusiveness - I don't know which element was changed last, so no way to select *other* elements.

# Answer
I got it working now. The way to do it was:

* Get all elements that are in "exclusive" groups using classes, `.each` over them
* For each element, change `beforeSubmit` using `$(this).attr('id')` as index for `ajax` table
* Because I was not able to get `element` to point to a specific element (it always pointed to entire form), I used helper variable at the beginning of `.each` loop.

Resulting code is like this:

```
(function($) {
  Drupal.behaviors.behavior_name = {
    attach: function (context, settings) {

      $('select.exclusive', context).each(function(){
        var triggering_element = $(this);
        Drupal.ajax[$(this).attr('id')].options.beforeSubmit = function (form_values, element, options) {
          // Make all not selected
          $("[exclusivity_group='"+triggering_element.attr('exclusivity_group')+"']").not(triggering_element).find("option").attr('selected', false);
          // select "all"
          $("[exclusivity_group='"+triggering_element.attr('exclusivity_group')+"']").not(triggering_element).find("option[value='all']").attr('selected', true);

        };
      });
    }
  };
})(jQuery);

```
> 1 votes

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


title: Enable Node menu automatically

text:
# Question
Title: Enable Node menu automatically
I have a need to automatically create an Article node type each time a Basic-Page node type is created - I am using Rules successfully to achieve that effect.

My problem is a Menu link also needs to be created for each Article node created. This means the **Provide a menu link** checkbox needs to be automatically enabled in the process of creating each Article node - but it isn't.

The image above shows the checkbox I'm trying to automatically enable.

When creating an Article node directly, i:e not using Rules to create the new Article node, the box is checked and things work as normal.

**I really need to find a solution which will enable the checkbox as I auto create my node types.**

# Answer
> 0 votes
I don't think that it's possible through the UI. But here is how I would do programmatically:

```
function mymodule_node_presave($node) {
  if ($node->type == 'article') {
    $node->menu['enabled'] = 1;
  }
}

```

It would make your "Provide a menu link" checkbox as checked automatically.

You can also set all these values if you need to:

EDIT: I'm so sorry I forgot the node\_save line in the code. Here is the correction:

```
function mymodule_node_presave($node) {
  if ($node->type == 'article') {
    $node->menu['enabled'] = 1;
    node_save($node);
  }
}

```

---
Tags: 7, routes, rules
---


# Question
Title: Synchronize users strategy for Drupal 7?
I am trying to think of a logical way to integrate another system's users with Drupal's. The actual integration is between Drupal and WHMCS. WHMCS has its own API so you can do things like getUser(emailAddress). What should be my strategy? Is there an easy way to make Drupal completely ignore the local "users" table and rather use another source for authentication? Perhaps auto-creating an entry on the Drupal side for non-existing users and automatically making users inactive that no longer exist on WHMCS's side?

*UPDATE*

I tried the suggested authorization providers suggested, but it seems my problem is the other way around. I don't want other sites to be authenticated using my drupal site's login details. What I actually want to do is use an installation of WHMCS, and use that as the authorized users list. In other words, when a user tries to log in using their whmcs details, it must log them into the drupal site. If they change their e-mail address on the drupal site, it must update it on the whmcs site. I know how write the api implemtation, I just don't know what I must use to do the groundwork. I would imagine there is already some kind of middleware that does the bulk of the work, and then I just have to code the implementation that does the lookup of a user, the call to update the details etc.

Is there something available that will allow me to easily integrate with a JSON Api like WHMCS?

# Answer
I don't know anything about WHMCS but there seem to be a lot of apps around LDAP connectivity that you can get for it.

The LDAP project for Drupal works well for me for authorization, both with Drupal as the host and with Drupal as the client.
> 2 votes

# Answer
Using Drupal OpenID-Single-Sign on (OMniauth) which very common method for the big organisation who manage a number of drupal/websites. more on that please refer to Comparison of Single Sign On (SSO) Modules
> 1 votes

# Answer
I would suggest to look this one. https://api.drupal.org/api/drupal/modules%21user%21user.module/function/user\_external\_login\_register/7

Drupal 7 - Login with external Database

And changing from drupal to other way.. https://api.drupal.org/api/drupal/modules!user!user.api.php/function/hook\_user\_presave/7
> 1 votes

---
Tags: users
---


# Question
Title: Commerce order either stays as pending or grants double to customer
I have 2 rules to handle orders of `credits` on my site.

* The first rule changes the order status to `Completed` if the order is no longer a cart.
* The second rule grants credits to the order owner using a loop.

The problem is that the credits are granted twice.

* In the user's orders page, the order appears twice with the same ID. But it only appears once in the admin orders page.
* If I omit the first rule and change the order status manually it works fine. In this case, it is still using the same loop. Can anyone think why this might be? Here are the rules:

`{ "rules_order_paid_in_full_order_state_to_completed" : {
 "LABEL" : "Order paid in full: Order state to Completed",
 "PLUGIN" : "reaction rule",
 "WEIGHT" : "1",
 "ACTIVE" : false,
 "OWNER" : "rules",
 "REQUIRES" : [ "commerce_cart", "commerce_order", "commerce_payment" ],
 "ON" : { "commerce_payment_order_paid_in_full" : [] },
 "IF" : [
 { "NOT commerce_order_is_cart" : { "commerce_order" : [ "commerce_order" ] } }
 ],
 "DO" : [
 { "commerce_order_update_status" : { "commerce_order" : [ "commerce_order" ], "order_status" : "completed" } }
 ]
 }
}`

`{ "rules_grant_credits" : {
 "LABEL" : "Grant Credits on Completion",
 "PLUGIN" : "reaction rule",
 "OWNER" : "rules",
 "TAGS" : [ "Checkout", "commerce", "credits" ],
 "REQUIRES" : [ "rules", "entity" ],
 "ON" : { "commerce_order_update" : [] },
 "IF" : [
 { "data_is" : { "data" : [ "commerce-order:state" ], "value" : "completed" } }
 ],
 "DO" : [
 { "LOOP" : {
 "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
 "ITEM" : { "line_item" : "Line Item" },
 "DO" : [
 { "component_rules_grant_credits_if_product_is_credits" : { "line_item" : [ "line_item" ] } }
 ]
 }
 }
 ]
 }
}`

# Answer
> 1 votes
I seem to have fixed it by changing the weight of the second rule. I made the weight 10. I'm guessing that having the weight on default (0) was causing the double triggering.

---
Tags: rules, commerce
---


# Question
Title: How can I tell that my hook_nodeapi function is being called by cron and not a user?
I am attempting to filter the viewing of node/cck fields attached to the nodes, so I have written a custom hook\_nodeapi function and I am editing the field values if the user doesn't have permissions (redacting them). The problem is, that when cron runs and apachesolr attempts to index the same content, cron doesn't have "the permissions" associated and so ends up indexing redacted content.

I need a simple test that returns a boolean if a function is being called by cron. Any ideas? I have started looking through cron code (Drupal 6) and it looks like bootstrap sets up cron with default anonymous user account details...

# Answer
> 5 votes
How is cron being executed? If done via crontab like

```
0 1 * * *   /usr/bin/wget -O - -q -t 1 http://my.site.com/cron.php

```

then I suspect that

```
function hook_whatever () {
  global $user;

  if (strpos(request_uri(), "/cron.php") === 0 && $user->uid == 0) {
    // from crontab
  } else {
    // from somewhere else
  }
}

```

would work.

Manually running from one of the admin pages may be trickier, but taking out the `$user->uid` check may suffice in that case.

# Answer
> 2 votes
It occurs to me that the issue may not be so much cron but the apachsolr indexing itself.

Having a look in the code here it seems that you may have a couple of options.

Exclude your module from apachesolr indexing. I'm not sure where the UI is for this, but it looks like you can specifically not get called when content is being indexed.

Or you can put some custom code in your nodeapi hook which checks for op '`update index`'.

Or you can check for $node-\>build\_mode == NODE\_BUILD\_SEARCH\_INDEX in your `nodeapi op = view` hook.

The only time you will have an issue is if you are putting things into `nodeapi op = load`, but for the purposes you describe `op = view` may be a better match.

# Answer
> 0 votes
You can determine whether your function is run via cron by checking if `drupal_cron_run` is in your `debug_backtrace`.

That's an awful solution, so don't do it if some other solution comes up.

# Answer
> 0 votes
In Drupal 7, the code below is how cron checks to see if a valid cron key is being used. I don't think this would render a false access grant if cron were being run concurrent to the request because the $\_GET variable is a superglobal only accessible to that script. Correct me if I'm wrong.

```
if (isset($_GET['cron_key']) && variable_get('cron_key', 'drupal') == $_GET['cron_key']) {
  //do my fancy cron stuff here
}

```

---
Tags: 6, search, cron, nodes
---


# Question
Title: Dropdown SubMenus Based on Roles Stopped Working
My site has a menu/top nav of course and I have various dropdown/sub menus. Yesterday it was all working fine. If you are an **anonymous** user, you see a particular menu item, that has a particular dropdown. If an **authenticated** user, you see another menu.

Today, I looked at the page, first as an anonymous users, the top level menus are there, **but** when I hover the dropdown menus items do not appear. I then logged in and same thing, the top level is there, but the hover does not display the submenus at all.

**I then logged in as the admin** and **can see** the top level menu and on hover, all the submenus appear. So natural thought, something happened with the permissions settings, but I checked everything "**seems**" fine. The only changes between today and yesterday afternoon where several updates to a stylesheet and I did add/install several modules *\[webform, token, date, calendar geolocation\]*, I have not done anything to turn off the menu. The top level is checked to **show as expanded** and of course, they show and function correctly when I am logged in as the **ADMIN**.

*To explain my setup*: where needed, I created two top menus for "speakers" for example: speakers -\>one -\>two (permissions set to display for anonymous users) speakers -\>five -\>twelve (permissions set to display for anonymous users)

In the above example, anonymous user goes to page, hovers over speakers menu item, and should see in the dropdown \[submenu items one and two\] and this has been working for weeks now. Same would apply for the authenticated user hovering over the second "speakers" and seeing \[five and twelve in the submenu\].

How do I debug this scenario to find out what is wrong? I've been doing this long enough to know it is probably something I have done, but after checking permissions, checking menu visibility - oh I am also using the "**Menu Per role"** module that has been in place for weeks, I would like some insight on how to attack this problem.

Any suggestions would be greatly appreciated.

# Answer
just posting my solution for those who may come after.

As I stated above, I did suspect that it was something I had or had not done to cause this issue. Knowing for certain that the only changes made were related to stylesheet updates, which I knew could not cause this problem, and loading of new modules, I decided I would have to uninstall them one-by-one, but before doing that, I went over the modules I installed yesterday **\[just a note: the reason I didn't see this issue yesterday was because the correct display had been cached\]** and thought about the problem and which module would most relate to that problem, so I started with jquery\_update. \[jquery/javascript typically used for these types of effects, hover onClick, etc.\]

I installed jquery\_update yesterday. I did change the admin display option to version 1.7, but I left the working option at 1.10. I disabled the module, refreshed my page and the submenus did appear on hover.

I was going to uninstall the module completely, then decided to set the working version back to 1.8 and the dropdown on hover continued to work.

I have not had time to really look, but the original developer set up the site with an older theme and I bet there is a conflict in the version used in the theme he/she chose and the most recent version of jquery.

Hopefully this will save someone a few hours of their life.

I do still love Drupal.
> 1 votes

---
Tags: navigation
---


# Question
Title: Views Display for a query that doesn't display view content to user
I need a views display type that will not output content to the user.

Essentially, I've got a view that simply performs a query, and I get the results of the query with views\_get\_view\_result() and then emails the results of the query to a user with a spreadsheet.

It's being run during cron, so I have to turn off access checks for access, or the query displays no results.

Though I could use an alternate access check that ensures the view is being run during cron. Any ideas, Drupalers?

# Answer
> 0 votes
Alright. So here's what I did. I installed Views Access Callback, then created a callback function that checks for the cron key.

The funny thing is, this disables the page URL access for me as user #1, even though I have "access all views" permission, and "Disable SQL rewriting" under Advanced -\> Query Settings is turned on, which I would think bypassess access checks, but views\_get\_view\_result() is getting results from the view even when my access function returns false. That's acceptable for me. I need to disable access via a URL.

Here's my implementation

```
/**
 * Implements hook_views_access_callbacks()
 */
function mycustommodule_rules_views_access_callbacks() {
  $callbacks['mycustommodule_rules_is_cron_view_access'] = t('Is function run from cron');
  return $callbacks;
}

function mycustommodule_rules_is_cron_view_access() {
  if (isset($_GET['cron_key']) && variable_get('cron_key', 'drupal') == $_GET['cron_key']) {
    return TRUE;
  }
  else {
    return FALSE;
  }
}

```

---
Tags: 7, views, cron
---


# Question
Title: Commerce Kickstart Facet Displays Item Count Even With Option Disabled
I'm using Kickstart2.

I imported a new set of Categories and Collections using a Taxonomy Feed Importer. Seemed to work OK but now, the facet display -always- shows the item count for -all- search vocabularies, even though I have that option disabled in each search field eg.

admin/config/search/facetapi/search\_api%2540product\_display/block/field\_category/edit

I can't see how the Feed Import would cause this so maybe that's a red herring, but regardless, this worked properly -before- my import and now I can't turn this item count off.

Any idea how to get rid of these?

>

# Answer
You have to configure the settings under vocabulary, go to `admin/structure/taxonomy/product_category/edit` and then uncheck the **Display number of items** that's it, it will not show you the count anymore.

>
> 0 votes

---
Tags: 7, commerce, search
---


title: Form has no <form> tags

text:
# Question
Title: Form has no <form> tags
My form is outputting but has no form tags and is therefore not submitting. I have tried the following:-

In the module... 'page callback' =\> "drupal\_get\_form",

```
function pd_cd_form(){...

```

From within the callback function... drupal\_get\_form(pd\_cd\_form); }

```
function pd_cd_form(){...

```

Is there something wrong with the naming of my functions? I cannot understand how the form is being produced but with no tags.

# Answer
> 1 votes
This could be a number of things. The way drupal produces a form usually starts with the menu system. You would declare the form in something like:

```
function your_module_menu() {
  $items['your/path'] = array(
    'title' => 'Your Title',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('your_module_formname_form'),
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

```

Then you create the actual form (which from what it sounds like seems to work), inside your function:

```
function your_module_formname_form($form) {
  $form['whatever'] = array();
  return system_settings_form($form);
}

```

and now when you go to your/path, you should see the form you created with a submit button and a default submit handler.

Things to check include whether your form array is properly structured, whether you are trying to override any of the submit mechanism and whether the chain from the menu to the form is uninterrupted and uses the attributes you meant to use.

---
Tags: forms
---


# Question
Title: Drush 6 installed on a centos server. How do i find out where its installed and upgrade it?
how do i find where is drush installed? its currently on drush 6 and looking to update it to drush 7 for drupal 8. Whats an easy way to find where its installed and update it?

# Answer
> 0 votes
Use `which drush` to get the installation path of Drush on CentOS:

> cat which drush | grep SCRIPT\_PATH -m1

`which drush` will return the path to the drush shell script, which is a readable text file. The SCRIPT\_PATH variable in this shell script contains a path to the drush.php file. In the directory, other than this file rest are the files of drush library.

Example:

```
cat `which drush` | grep SCRIPT_PATH -m1
SCRIPT_PATH=/usr/share/pear/drush/drush.php

```

To **upgrade** a drush check this: https://www.drupal.org/node/901828
Also check this one (including comments): https://www.drupal.org/node/1248790

References:
Installing Drush On Any Linux Based Server Out There
Install Drush on CentOS (with H-Sphere)

---
Tags: drush, installation
---


# Question
Title: Subscriptions template: test for imagefield
I send digest newsletters with the subscription module (using the templates that comes with the module), sometimes containing a small image before the teasertext (positioned with tables/row/column). This is all working well.

However in case there is no image available (because there is no teaser image uploaded to the applicable field or the contentitem doesn't even have a image field with that name) I get an ugly image outline in most email clients. I would like to test if there is an image available and if not, not adding the first ... leaving only the teaser text.

Can someone explain which "template" code must be used in order to achieve this?

Code used so far:

```
    Your subscriptions on [site:name] notify you of the following changes since the previous digest:<br />

    {{[subs:items:count]#<img src="http://@mydomain@/Newsletter/fine-line.jpg" width="580" height="18"><br />
    #1 of [subs:items:count] {{[subs:items:index:#0:subs:is-new]?(new):}}{{[subs:items:index:#0:subs:is-updated]?(updated):}}{{[subs:items:index:#0:subs:is-old]?(commented): <b>[subs:items:index:#0:as-node:title]</b>}}

    <table border="0" width="100%" padding="5">
        <tr>
            <td valign="top"><img src="[subs:items:index:#0:as-node:field_news_image]" alt="teaser image" width="100" /></td>
            <td style="font-family: Calibri, Arial, Helvetica, sans-serif;" valign="top" align="left">[subs:items:index:#0:as-node:summary]</td>
        </tr>
    </table>
    Read more: [subs:items:index:#0:as-node:url]<br />
    }}

```

# Answer
> 0 votes
If you can use php in the template (?) I would just wrap the cell containing the image in an if statement, something like this:

```
Your subscriptions on [site:name] notify you of the following changes since the previous digest:<br />

{{[subs:items:count]#<img src="http://@mydomain@/Newsletter/fine-line.jpg" width="580" height="18"><br />
#1 of [subs:items:count] {{[subs:items:index:#0:subs:is-new]?(new):}}{{[subs:items:index:#0:subs:is-updated]?(updated):}}{{[subs:items:index:#0:subs:is-old]?(commented): <b>[subs:items:index:#0:as-node:title]</b>}}

<table border="0" width="100%" padding="5">
    <tr>

        <?php if(**code to determine if image exists**): ?>
        <td valign="top"><img src="[subs:items:index:#0:as-node:field_news_image]" alt="teaser image" width="100" /></td>
        <?php endif ?>

        <td style="font-family: Calibri, Arial, Helvetica, sans-serif;" valign="top" align="left">[subs:items:index:#0:as-node:summary]</td>
    </tr>
</table>
Read more: [subs:items:index:#0:as-node:url]<br />
}}

```

That way if there's no image it just won't print the cell at all and the other cell will take the entire width of the table.

If you can't use php in the template then I'm not sure how you could deal with it except perhaps by merging the two cells like this:

```
<td style="font-family: Calibri, Arial, Helvetica, sans-serif;" valign="top">
  <img src="[subs:items:index:#0:as-node:field_news_image]" alt="teaser image" width="100" />[subs:items:index:#0:as-node:summary]
</td>

```

# Answer
> 0 votes
Fixed it!

```
{{[subs:items:index:#0:as-node:field_news_image]==?:<td valign="top"><img src="[subs:items:index:#0:as-node:field_news_image]" width="100" /></td>}}

```

the part between ? and : is empty like the image I would test for.

---
Tags: theming, notifications
---


# Question
Title: Organic Groups Vocabulary - Dynamically Load Terms
I've recently installed OG Vocabulary and have been kicking the tires for the last day or so. It'll do what I need it to do, that is, provide segregated group taxonomies. However, it seems to me that the workflow is less than ideal.

I have a content type named *Event*. It has 2 OG fields:

**og\_group\_ref** \- Allows the user to associate content to a group

**og\_vocabulary** \- Contains select lists of vocabularies based on which groups the user belongs to, and whether those groups have referenced vocabularies.

When creating a new *Event*, if a user belongs to multiple groups with taxonomies on that node, the user is shown a og\_vocabulary field for every group. This allows a user to associate the Event to "Group A", but select terms from "Group B".

After a new *Event* is created and associated to a group, if a user goes back to edit that group, only vocabularies related to the group they've associated to the node show up. If the user changes the group to which the content belongs, they must save that content then edit the content again in order for the correct og\_vocabulary field to show up. I'd like to be able to skip having to go back in and edit the node after changing the referenced group.

Is it possible to dynamically load the correct og\_vocabulary field based on the value of og\_group\_ref?

I've been mucking around with AJAX to accomplish this, but I'm wondering if there's a better way to accomplish this. It's possible that this functionality is built in and I'm missing something.

I'm using D7, by the way.

Thanks for any help!

# Answer
I recently encountered the same issue and the way I got around it was to use a hook\_form\_alter to use the appropriate taxonomy from the pre-populated selection of og\_group\_ref via a db\_select on the taxonomy\_term\_data table.

I used entity\_reference\_prepopulate to set up the link to create group content for the group. Seems hacky to me and would like to know if others were able to get it to work like the OP had wanted it. Here is an excerpt of my hook\_form\_alter.

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  // ... get gid from context
  // ... i used request_uri() to get the uri and parsed out the gid
  // there may be less hacky ways of doing this.
  $query = 'SELECT tdata.tid, tdata.name FROM (SELECT vid from {og_vocab_relation} where gid=:groupid) og left join {taxonomy_term_data} tdata on (og.vid=tdata.vid)';
  $query_params = array(':groupid' => $gid);
  $taxi_terms = db_query($query, $query_params);
  $options = array();
  $options['_none'] = '- None -';
  foreach($taxi_terms as $taxi_term) {
    $options[$taxi_term->tid] = $taxi_term->name;
  }
  $form['og_vocabulary'] =  array(
    '#title' => 'Projects',
    '#type' => 'select',
    '#multiple' => TRUE,
    '#options' => $options
  );
}

```
> 0 votes

---
Tags: taxonomy-terms, organic-groups
---


title: Line item should change the price

text:
# Question
Title: Line item should change the price
I have this problem in Drupal Commerce: a line item should change the price of my product, that is based on customizing the users (ex. product base $10 with customization $12, customization is line items).

This is possible working on Rules, but you only see final price after you add the product on cart, I should instead see the price change in ajax so the users see final process before add to cart.

I've not found solutions online. The basic scenario is like this:

* You buy a shirt based =$10
* The user customizes the shirt with your name and = $12
* The user customizes name and logo = $14

I am working with Kickstart 2.0

# Answer
The functionality you're looking for doesn't exist at the moment. I'd describe it as wanting line item field value changes to trigger a refresh of the Add to Cart form and the injected product fields. You can follow this feature request, though I'm not sure it's likely to be addressed soon:

https://www.drupal.org/node/1541886
> 1 votes

# Answer
So you have fixed prices and a set of fields per kind of price? Ha! You could setup a line item type per product:

https://www.drupal.org/sandbox/malberts/1947762

And then create three products:

1. Shirt, Price $10
2. Shirt + Name, Price $12, custom line item type: Name
3. Shirt + Name + Logo, Price $14, custom line item type: Name + Logo

Then create one Product Display node and attach those three products to the display node.

In theory, that should work. Let me know how the "in practice" goes.

EDIT: Here's how to do it, step by step in a video:

http://youtu.be/eaF\_FjnQ8NM

Josh
> 0 votes

---
Tags: ajax, commerce
---


# Question
Title: Remove drupal parameters from form submitted via GET
I have form which is submitted via GET method. The problem is that after submit the URL looks very bad, with lots of parameters like **form\_build\_id** & **form\_token**. How can I get rid of them? Thanks

# Answer
> 6 votes
I ended up doing this:

```
$form = drupal_get_form('my_form_id');
unset($form['form_build_id']);
unset($form['form_id']);
unset($form['form_token']);

```

# Answer
> 3 votes
These values shouldn't be needed for GET forms, but might be. Using POST instead is not a suitable fix, that has other side effects.

According to the specs:

* GET should be used to change the content of the page displayed
* POST should be used to pass data or instructions to the server

A POST request should therefore be treated with care, as you might use it for something like adding an answer to a question. You don't want to accidentally send that answer twice, or it will show on the site twice - that's why browsers will warn you when you reload a page that you sent POSTDATA to. You also don't want another site to pretend to be you and answer a question on your behalf (that's called XSRF or cross-site request forgery).

These variables are included to protect against these dangers of POST, but they are not necessary if you are doing a (read-only) GET request. Other advantages of using GET at that the response can be cached, bookmarked and indexed by search engines.

A final warning: although you're not meant to change anything as the result of a GET request, there's nothing stopping you from doing so. That's probably why Drupal includes this protection.

# Answer
> 2 votes
Following what views does with the views\_exposed\_form you can easily do this to hide form\_build\_id form\_token and form\_id. Considering views is one of the top contrib modules I would say this is pretty safe:

```
/**
 * Implement hook_form_alter for the exposed form.
 *
 * Since the exposed form is a GET form, we don't want it to send a wide
 * variety of information.
 */
function MYMODULE_form_MY_FORM_ID_alter(&$form, &$form_state) {
  $form['form_build_id']['#access'] = FALSE;
  $form['form_token']['#access'] = FALSE;
  $form['form_id']['#access'] = FALSE;
}

```

See views.module and views\_exposed\_form() and views\_form\_views\_exposed\_form\_alter()

# Answer
> 0 votes
Following worked for me...

```
function mymodule_form(&$form_state){
  // Form fields go here....
  // Then...
  $form['#token'] = false;
  // You have to call it in after_build
  $form['#after_build'] = array('_unset_form_elements');
  return $form;
}

function _unset_form_elements($form){
  unset($form['#build_id'], $form['form_build_id'], $form['form_id']);
  return $form;
}

```

---
Tags: 7, forms
---


title: How to get a form to submit:

text:
# Question
Title: How to get a form to submit:
a possibly stupid question. Why won't this form submit?

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

```

if I add the following

```
$form['#submit'][] = 'my_form_submit';

```

and a submit function:

```
function my_form_submit($form, &$form_state){
  dd('Submit ran');
}

```

The debug statement is never called. What am I doing wrong?

# Answer
Actually the submit handler name should be the form function name with `_submit`.

So in this case: `my_form()` returns the form, and `my_form_submit($form, &$form_state)` is automatically the submit handler. This also works for `_validate`.

See the Examples project for some working code. It has a submodule called form\_example.
> 4 votes

# Answer
I think the standard way to do it is to put it in an 'actions' container and then add the '#submit' to that. try this snippet instead of your code above.

```
$form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#weight' => 5,
    '#submit' => array('my_form_submit'),
  );

```

notice how the button gets the `#submit`... not the form. Forms do have a default submit handler, which I think is `myformname_submit` but I always do it explicitly anyway. Also, I've seen DD fail on occasion due to random permissions problems. Maybe try DPM, watchdog, KPM or something that writes to the screen rather than a log file.
> 3 votes

# Answer
The code you have pasted looks fine, so why doesn't it work? It's hard to say exactly, but some possibilities are:

* The submit handler is called but you are tracking the wrong file or there is an error with the `dd` function.
* The form is not loaded on the page that is rendered on display.
* The submit handler is in a include file not loaded when the form is processed.
* Typos in the actual code (mis name of function names).

This is some guesses, like I said what you have looks fine. One comment though. You don't have to add the submit handler if you name it `FORM_NAME_submit`, Drupal will by default add those to the functions called on submit.
> 3 votes

# Answer
The problem here isn't the array, but the way that I invoke the form. I just needed to call my form callback using `drupal_get_form('my_form_callback');` Thanks to all for the help!
> 0 votes

# Answer
I had a lot of issues getting this working. I tried all suggestions in here, including swapping from drupal\_build\_form to drupal\_get\_form, using $form\['submit'\]\['#submit'\] vs $form\['#submit'\], and even just using a link that linked to current\_path() as a #markup element. All of these attempts failed.

What did work was the following:

```
  $reset_button_text = t('Reset filters');
  // Before building the form check the query parameters for the reset op and use a goto to stop the form and "reset" it.
  $query_params = drupal_get_query_parameters();
  if (isset($query_params['op']) && $query_params['op'] == $reset_button_text) {
    drupal_goto(current_path());
  }

  // Form declaration goes here..
  // ....
  // ....
  $form['#method'] = 'get';
  // Reset button just resets the filters.
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['reset'] =  array('#type' => 'submit', '#value' => $reset_button_text);
  $form['actions']['submit'] = array('#type' => 'submit', '#value' => t('Apply filters'));

```

This seems like a massive hack and only works because I have the form as a sort of filter form for a custom EntityFieldQuery (which outputs some other markup) on the same page. However, it works a charm for me :)
> 0 votes

---
Tags: 7, forms
---


title: Image does not load

text:
# Question
Title: Image does not load
I bought a theme from themebrain site and installed it. Some of the images for the theme are stored inside /sites/default/files/customs/. So in image tags, I refer to the source location as "sites/default/files/customs/xxx.png". However, those image are not loading. I changed the directory permission recursively to 777, but that does not resolve the issue either. But images inside /sites/all/themes/tb\_travel/ load just fine though. If anyone could guide me to right direction, I would highly appreciate it.

# Answer
Make sure the image tags have an absolute path "/sites/default/files/customs/xxx.png" and not relative, "sites/default/files/customs/xxx.png". I've palm-to-faced many times because of that.

For example:"/node/123/sites/default/files/customs/palm-to-face.png" won't load!
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Save and Retrieve Admin Settings from the database
I created a config form in the admin/config page. (Just a link field that needs to be saved for later retrieval) Im confused as to how to save and retrieve the form data.

When creating a custom form in a block I have been successful using:

```
variable_get('link_title', '')

```

However when creating a custom form it seems to require a different way. I attempted to save the data in hook\_form\_submit. However Im not sure how to retrieve when you return to the form at a later date.

```
function read_more_news_admin_form($form, &$form_state) {
        $form = array();
        $form['link_container'] = array(
            '#type' => 'container',
            '#attributes' => array('class' => array('some-class')),
            '#tree' => TRUE,
        );
        $form['link_container']['link'] = array(
            '#type' => 'link_field',
            '#field_name' => 'link_field',
            '#language' => 'und',
            '#field_parents' => array(),
            '#delta' => 0,
            '#default_value' => array(
                'title' => variable_get('link_title', ''),
                'url' => variable_get('link_url', ''),
            ),
        );
        return system_settings_form($form);
    }

    function read_more_news_form_submit($form_id, $form_values) {
      drupal_write_record('readmorelink', $form_state['values']);
    }

```

# Answer
> 2 votes
I don't know how system\_settings\_form will handle form elements of which the parent element has the tree property set. So it is best to go with a submit handler and do it yourself.

```
function read_more_news_admin_form($form, &$form_state) {
  $form = array();
  $form['link_container'] = array(
    '#type' => 'container',
    '#attributes' => array('class' => array('some-class')),
    '#tree' => TRUE,
  );
  $form['link_container']['link'] = array(
    '#type' => 'link_field',
    '#field_name' => 'link_field',
    '#language' => 'und',
    '#field_parents' => array(),
    '#delta' => 0,
    '#default_value' => array(
      'title' => variable_get('link_title', ''),
      'url' => variable_get('link_url', ''),
    ),
  );
  $form['submit'] = array('#type' => 'submit', '#value' => t('Submit'));
  return $form;
}

function read_more_news_admin_form_submit(&$form, &$form_state) {
  variable_set('link_title', $form_state['values']['link_container']['link']['title']);
  variable_set('link_url', $form_state['values']['link_container']['link']['url']);
  //drupal_write_record('readmorelink', $form_state['values']);
}

```

# Answer
> 1 votes
You don't need to use a separate submit handler if you are using `system_settings_form()` unless you need to do something out of the ordinary.

Setting the `#default_value` of each element with `variable_get` will retain the settings of your form. `variable_get` will check if the variable exists and use the stored variable if there is one, otherwise it will use the 2nd argument in the call.

A basic working example would be like this:

```
function HOOK_admin_form($node, &$form_state) {
  $form['MODULE_ELEMENT'] = array(
    '#type' => 'textfield',
    '#default_value' => variable_get('MODULE_ELEMENT', 'value'),
    '#title' => t('title'),
    '#required' => TRUE,
  );

  $form['MODULE_ELEMENT2'] = array(
    '#type' => 'textfield',
    '#default_value' => variable_get('MODULE_ELEMENT2', 'value'),
    '#title' => t('title'),
    '#required' => TRUE,
  );

  return system_settings_form($form);
}

```

---
Tags: forms
---


# Question
Title: Views Block: one node latest of several categories
Is it possible to do with the views I had one recent node of the 5 categories? example: \- Category 1 (20 node) \- Category 2 (10 node) \- Category 3 (5 node) \- Category 4 (17 node) \- Category 5 (2 node)

VIEWS BLOCK:

* Newest node (category 1) only one!
* Newest node (category 2) only one!
* Newest node (category 3) only one!
* Newest node (category 4) only one!
* Newest node (category 5) only one!

# Answer
> 0 votes
Install Views Aggregator Plus.

Create a view with fields category (hidden if you like), and title. Sort first by category, and secondly by post date descending.

Set the format of the view to 'Table with aggregation options'. In the settings for that format, select 'Apply group function' for category, and in the dropdown that appears select 'Group and Compress'.

Remove the pager and display all items.

# Answer
> 0 votes
You can create a normal view first listing only the newest item (see Pager settings). Then, create a contextual filter for the category so that you can call the view with different category ids.

Now, you'll the Views Field View module, it enables you to add other views as fields. Add a View Field Views field for each category to your block display.

---
Tags: views, nodes
---


# Question
Title: How to stop the jquery element being added on ajax requests
I've added a toggle for my superfish menu, it works fine but for every ajax load or colorbox trigger the span is created multiple times. How to fix it???

```
(function ($){
Drupal.behaviors.customjs  = {
attach: function (context, settings) {
$(document).ready(function(){

$("#superfish-1").before("<span class='toggle'>Menu</span>");
$('#superfish-1').toggle();
 });

```

# Answer
The better way would be to use the **context of the behaviour along with .once()** as mentioned here ( https://www.drupal.org/node/1667874 ), something like below:

```
(function ($){
  Drupal.behaviors.customjs  = {
    attach: function (context, settings) {
      // Add context along with .once something like below.
      $("#superfish-1", context).once("CLASS-NAME").before("<span class='toggle'>Menu</span>");
    }
  }
})(jQuery);

```
> 3 votes

# Answer
First, don't use `$(document).ready` in behavior. It should not be needed to make behavior work when things are ready, and second, usually it will be executed immediately if page was ready in the past - not what you want.

Second thing is to always use context in top level `$(` selectors. And use `once()` to be sure.

So your code after changes could look like this:

```
(function ($){
  Drupal.behaviors.customjs  = {
    attach: function (context, settings) {
      $("#superfish-1", context).once("customjs-before").before("<span class='toggle'>Menu</span>");
      $("#superfish-1", context).once("customjs-toggle").toggle();
    }
  };
})(jQuery);

```
> 2 votes

# Answer
Add jQuery once to your menu wrapper http://codekarate.com/blog/drupal-7-prevent-duplicating-javascript-behaviors
> 1 votes

---
Tags: 7, javascript, navigation
---


# Question
Title: Custom menu is not expanded when the parent menu is selected
I have a Drupal 6.26 site with a custom menu like so:

```
-Category 1
--Page
--Page
-Category 2
--Page
--Page
...

```

All Category pages are genrated by a view (e.g. `sitename.com/intranet/category`)

All pages that are children of each category are nodes.

My primary problem is, when a category page is selected, the menu it's associated with doesn't expand. The site owner doesn't want the menus expanded by default.

A secondary problem is the menu won't expand when one of the child pages is selected **unless** it has the path `/intranet/category/*`, which is not always desired.

Hopefully a bit of code can solve this issue.

# Answer
Five lines of code placed in a views template file solved the issue:

```
 <?php
    $path = drupal_get_path_alias(check_plain($_GET['q']));
    $menu_item = menu_get_item($path);
    $menu_item['href'] = $path;
    if($path && $menu_item) {
      menu_set_item(NULL, $menu_item);
    }
  ?>

```
> 0 votes

---
Tags: 6, navigation
---


# Question
Title: Display Suite layouts not working for field collections Edit\Add forms
Even though I have the Display Suite Forms module enabled and applied a layout to this specific field collection, it does nothing for the edit/add forms. If I apply a layout using manage display it works when viewing the appropiate view mode (for example the full view mode).

Does anybody have any idea or hints where I could start looking?

# Answer
> 1 votes
Just had a similar problem with ds and heartbeat module. Maybe my solutions also works for this problem. Just enable the needed submodules in ds - that fixed the problem.

---
Tags: entities, display-suite
---


# Question
Title: How can I send an e-mail to the admin when use of a view results in an error?
I have a large number of complicated views on a site, some of which, when searched with certain options or by certain users, give the following error:

> An illegal choice has been detected. Please contact the site administrator.

Is it possible to somehow catch this error and email the admin? Ideally, I would be able to include the URL of the view causing the problem and the UID of the user accessing the view for troubleshooting purposes.

# Answer
> 3 votes
You are describing `hook_watchdog(array $log_entry)`:

> This hook allows modules to route log events to **custom destinations, such as** SMS, **Email**, pager, syslog, ...etc.

emphasis mine.

Inside it, you can use `$log_entry` array to get UID and request URL, and you can also use `global $user`, and you can call `current_path()`, so both your requirements seems doable.

`$log_entry` array is defined as:

> $log\_entry: An associative array containing the following keys:
>
> * **type**: The type of message for this entry.
> * **user**: The user object for the user who was logged in when the event happened.
> * **uid**: The user ID for the user who was logged in when the event happened.
> * **request\_uri**: The request URI for the page the event happened in.
> * **referer**: The page that referred the user to the page where the event occurred.
> * **ip**: The IP address where the request for the page came from.
> * **timestamp**: The UNIX timestamp of the date/time the event occurred.
> * **severity**: The severity of the message; one of the following values as defined in RFC 3164:
>
> + WATCHDOG\_EMERGENCY: Emergency, system is unusable.
>     + WATCHDOG\_ALERT: Alert, action must be taken immediately.
>     + WATCHDOG\_CRITICAL: Critical conditions.
>     + WATCHDOG\_ERROR: Error conditions.
>     + WATCHDOG\_WARNING: Warning conditions.
>     + WATCHDOG\_NOTICE: Normal but significant conditions.
>     + WATCHDOG\_INFO: Informational messages.
>     + WATCHDOG\_DEBUG: Debug-level messages.
> * **link**: An optional link provided by the module that called the watchdog() function.
> * **message**: The text of the message to be logged. Variables in the message are indicated by using placeholder strings alongside the variables argument to declare the value of the placeholders. See t() for documentation on how the message and variable parameters interact.
> * **variables**: An array of variables to be inserted into the message on display. Will be NULL or missing if a message is already translated or if the message is not possible to translate.

There is no way I know to get form ID of a form that created your error, I don't think it is in `['variables']`, so the best you can do is to parse `['message']` for "illegal choice", and test `['request_uri']` and `['referer']` for pages that are your suspects.

---
Tags: views, debugging
---


# Question
Title: What is the best way to run HTTPS for drupal commerce
I have seen the module Secure Pages, and also found Custom SSL redirect and read all the issues related to this and Commerce, but most seem out dated.

Can anyone say as of this point what is the best way to run the site on http and the checkout (anonymous users) with https?

# Answer
> 0 votes
If you have control over your hosting, the easiest is to serve everything on https, this will make the whole setup easy and if used in combination with SPDY \- and PFS \- you get both speed and SEO improvements.

# Answer
> 0 votes
It's hard to say what's 'best', it depends what you mean by that.

If you're just looking for a working solution, the dev version of Secure Pages along with the core patches it recommends works great.

Best thing you can do is install the various options you've identified, do your testing as normal, and ask a more specific question if the modules do something you don't expect.

---
Tags: commerce, ssl
---


title: Drupal content update to Facebook page

text:
# Question
Title: Drupal content update to Facebook page
When I publish content – for instace an article – on a Drupal site, I'd like Drupal to push a status update with a link to the article to a Facebook company page.

I know there are a lot of Drupal modules that offer Facebook integration, but does any of them offer this particular functionality? Or is perhaps the best way to go to generate an RSS feed and use a third-part app like http://twitterfeed.com/ to push it to Facebook?

The site in question is a Drupal 6 site.

# Answer
> 0 votes
The Drupal for Facebook module gives you integration on a number of levels, including (with some extra work) automatic push to a Facebook page you have access to.

However, you might get better results by letting visitors to your website post references to their own timeline using something like ShareThis. This will use your audience as multipliers of your message, not just on Facebook but on other social media sites as well.

---
Tags: social-network
---


title: Add a user/author field formatter

text:
# Question
Title: Add a user/author field formatter
i have a site where I use display suite for custom page display. And all works. Now I need to add a custom field formatter for the "Author" field, but I don't find how to link "author" to a new field formatter.

I know that I need to use hook\_field\_formatter\_info() but I don't understand which is the right value for "field types". I have tried with "user", "user\_reference", "text","author" but nothing.

I have tried to see how Display Suite define its fields formatter, but for this field the module use "2" for this value:

```
$fields['node']['author'] = array(
    'title' => t('Author'),
    'field_type' => DS_FIELD_TYPE_FUNCTION,
    'function' => 'ds_render_author_field',
    'properties' => array(
      'formatters' => array(
        'author' => t('Author'),
        'author_linked' => t('Author linked to profile')
      ),
    ),
  );

```

where

```
define('DS_FIELD_TYPE_FUNCTION', 2);

```

So how can I add one new field formatter for the author field ?

Thanks.

# Answer
> 0 votes
I have found the solution: I have to create a new display suite formatter because that page use ds for the display.

I have read this:

Creating custom display suite fields or how I learned to stop worrying and use hook\_ds\_fields\_info()

and I have created my formatter. All works. Thanks for all to all.

---
Tags: 7, entities
---


title: Hide menu item in specific block/region

text:
# Question
Title: Hide menu item in specific block/region
I have two instances of main\_menu on a page. One is in the header, using superfish. The other is in the sidebar, using menu\_block.

I want to hide a menu item in the sidebar and show it in the header. Is this possible?

Could you use template.php to target a block/region?

For example:

```
function my_theme_preprocess_block(&$variables) {
  if ($variables['region'] == 'content' && $variables['block']->module == 'menu_block') {
    // What would go in here?
  }
}

```

Any help would be greatly appreciated.

Thanks,

Steve

# Answer
If I were you, I'd rather do this in my **module** code to access the links data:

```
function mymodule_block_view_alter(&$data, $block) {
  if($block->title == 'myblocktitle') {
    $data['content']['#content'][idofthenodelink]['#access'] = false;
  }
}

```

And your link will no longer be accessible.

Here is the `dpm($data['content']['#content'])` after the operation:
> 1 votes

# Answer
It depends on your theme. I have seen some that hardcode the main menu into the template (bad style, but if so, you'll have to find the template and delete the section). More likely, you will see Main Menu in your "admin/appearance/settings" as an option that you can turn off for Global Display.

Then, if you want to add it in any other block, you can do so manually.
> 0 votes

---
Tags: 7, routes, navigation, blocks
---


# Question
Title: Drupal form elements in html table, label (title) rendering
How to place title/label in other cell of the html table

I have:

```
function hook_theme() {
  return array(
    'hook_form_table' => array(
      // The renderable element is the form.
      'render element' => 'form',
    ),
  );
}

function hook_form_table_form($form = array(), &$form_state) {

    $form['#theme']= 'hook_form_table';
    $selected_two="";
    $options_second=array("a");
    $form['carmodel'] = array('#type' => 'select',
        '#options' => $options_second,
        '#default_value' => $selected_two,
        '#required' => TRUE, '#title' => t('Car model:'),
        '#validated' => true,
        '#prefix' => '<div id="replace_carmodel_div">',
        '#suffix' => '</div>',
    );

    $options_euro=array("Euro 3,4","Euro 5" );

    $form['euro'] = array('#type' => 'select',
        '#options' => $options_euro,
        '#default_value' => $selected_two,
        '#required' => TRUE,
         '#title' => t('Euro type:'),
        '#validated' => true,
     );

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

  return $form;
}

function theme_hook_form_table(&$variables) {
    $form = $variables['form'];
    $content = '<h2>' . t('Please enter your information below') . '</h2>';
    $content.="<table>";
    $content.="<tr>";
    $content.="<td>";
    $content.=$form['carmodel']['#title'];
    $form['carmodel']["#type"]="";

    $content.="</td>";
    $content.="<td>";
    $form['carmodel']['#title']="";
    $form['carmodel']['#required']="";
    $content .= drupal_render($form['carmodel']);
    $content.="</td>";
    $content.="<td>";
     $content.="hire want euro type  with * and label and all";
    $content.="</td>";
    $content.="<td>";

    $content .= drupal_render($form['euro']);
    $content.="</td>";
    $content.="</tr>";
    $content.="</table>";
  return $content;
}

```

This give me a table but labels is on top: How to render label to put it like this:

# Answer
My not nice solution is

```
function drupal_render_label($field){
    $result= "<div class=\"form-item form-type-".$field['#type']." form-item-".$field['#name']."\">";
    $result.= "<label for=\"edit-".$field['#name']."\">".$field['#title'];
    if ($field['#required']==true){
       $result.= "<span class=\"form-required\" title=\"This field is required.\">*</span>";
    }
    $result.="</label>";
    $result.="</div>";
    return $result;
}

```

and then:

```
  $content.="<td>";
  $content.=drupal_render_label($form['carmodel']);
  $content.="</td>";

```

Anyone have sth better?
> 0 votes

---
Tags: forms
---


# Question
Title: Why does "my blog" menu link disappear when I use a view with the path blog/%?
When I create a view with the path blog/%, the menu link "My blog" disappear from the main menu but still exists in the database. The view works exactly as expected when I go to /blogs and click the nav link at the bottom of the article.

**Already tried without success** (logged in as administrator)

1) Change view access to:

* none
* permission: view published content
* permission: blog entry:
* create new content role: authenticated users

2) Add/Remove the view filter: status published

3) Create a new menu link using Menu Token module but this link disappears too (but still exists in the db).

4) Enable/disable Menu Token and Menu item visibility modules, just to check if there is a conflict somewhere but it doesn't change anything.

Versions:

* Drupal 7.31
* Blog 7.31
* Views 7.x-3.8.
* Menu Token 7.x-1.0-beta5
* Menu item visibility 7.x-1.0-beta1

# Answer
The path that the blog module uses is blog/%user .

If you go to blog/1 you will see all posts made by the user with uid equals 1.

So, when you create a views:view that defines the path blog/%, it overrides the default path previously defined by blog and uses the views path.
> 1 votes

---
Tags: routes, navigation
---


# Question
Title: How to show thumbnail preview in node display for uploaded video in file field
I am using a file field and media module in a custom content type to upload video files. The videos play fine. The preview image for each video is a gray box. How can I display a preview image or thumbnail for each video in place of the gray box in the node display?

Update: the preview image does not have to be auto-generated from the video; I would be OK with adding an field for an image to upload along with the video.

# Answer
Go to your content type \>\> *MANAGE DISPLAY* settings and set FORMAT as Rendered file and view mode: perview
> 1 votes

# Answer
This depends on how you are displaying the video. From your question I gather that it's from the node view. The first comment from Djouuuuh is correct, but this is very time consuming and understandably may not be an option for you. So I'll tell you how you can make it work in a smaller time frame with some templating.

First you need to make sure the video field and the thumbnail for the video are available to the display. If you have a thumbnail field that gets populated automatically or uploaded to manually then all you have to do is add that to the display.

Go to admin/structure/types/*type*/manage/display and make sure the display you are trying to edit has both fields. If your thumbnail field is on the video entity then all you would need is the video field. Also, install and enable the devel module so you can test your displays.

In your node--*type*.tpl.php template you would need to first test that you have the data available to you, so write at the top of the document, flush cache, flush browser cache, and reload the node page. Click through the message printed at the top to make sure you have the data you need.

If the data is there, then you can start doing some templating to get the node to look how you want with the preview. One quick solution I can think of is to utilize HTML5's tag with the placeholder attribute.

Something like this:

```
<?php
  if (isset($content['video_field'])) { $video = $content['video_field']['und'][0]['link_to_video_file']; }
  if (isset($content['video_field']['und'][0]['thumbnail']['link_to_thumbnail_file'])) { $thumbnail = $content$content['video_field']['und'][0]['thumbnail']['link_to_thumbnail_file']; }
?>
<div class="video-wrapper">
  <video src="<?php if (isset($video)) { print $video; } ?>" poster="<?php if(isset($thumbnail)) { print $thumbnail; }?>"></video>
</div>

```

There are other attributes in addition to poster you can use with the tag to embed controls, timers, multiple video file type sources, etc.
> 1 votes

---
Tags: files, entities
---


title: Show user content in taxonomy term page

text:
# Question
Title: Show user content in taxonomy term page
I'm using References module to use User Reference field in Taxonomy Term page. I have added new Term called "Matt's books" with user Matt set in User Reference field (field\_user).

User Matt has created multiple nodes. When I open Taxnomy Term page called "Matt's books" I need to have listed all nodes which Matt has been created.

I have made View block to show nodes (content type Books).
I added Relationship **Content: Author** and set it to Require.
Then I added another **Relationship User: User (field\_user) - reverse** and set this also to Required.

At this point my View block is showing Book nodes from all users when I'm in Matt's book Taxonomy Term page.

Here is my issue: How can I show nodes **only** from user who is used in User Relationship field (field\_user) in current Taxonomy Term?

If I set Contextual Filter **Taxonomy term: User (field\_user)** and set *When value is not available* to display "No results find" it does not show nothing att all in Taxonomy Term pages.

So my View should work like this for example: In "Matt's books" Taxonomy Term page it shows only content from user Matt - because he is in User Relationship field (field\_user) of this Taxonomy Term page.

Here is my View exported:

```
$view = new view();
$view->name = 'books';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Books';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Books';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '5';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Content: Author */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'node';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
$handler->display->display_options['relationships']['uid']['required'] = TRUE;
/* Relationship: User: User (field_user) - reverse */
$handler->display->display_options['relationships']['reverse_field_user_taxonomy_term']['id'] = 'reverse_field_user_taxonomy_term';
$handler->display->display_options['relationships']['reverse_field_user_taxonomy_term']['table'] = 'users';
$handler->display->display_options['relationships']['reverse_field_user_taxonomy_term']['field'] = 'reverse_field_user_taxonomy_term';
$handler->display->display_options['relationships']['reverse_field_user_taxonomy_term']['relationship'] = 'uid';
$handler->display->display_options['relationships']['reverse_field_user_taxonomy_term']['required'] = TRUE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'books' => 'books',
);

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');

```

# Answer
> 0 votes
I'm having trouble finding the reason for wanting to have your term page have a separate block to display the same content with a filter of the author of the node being the same as the referenced user on the term. Would you mind explaining your reasoning? I'm purely just curious for the use-case.

Anyway, if you want to do this in views here are the steps:

1. Create view block and set it to display content of type book
2. Add a relationship for Content: Author and check "require"
3. Add another **required** relationship for "User: User (field\_user) - reverse" BUT MAKE SURE YOU USE THE PREVIOUS RELATIONSHIP YOU CREATED so it will look like

> (author) User: User (field\_user) - reverse

I believe the last step is the one you didn't do correctly. It's important you have the two relationships be required and the second relationship uses the first.

Then you can add the fields you want to display.

image1 image2

I recreated the view and exported (though I did use different field names so do not just import this view).

```
$view = new view();
$view->name = 'book_view';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'book view';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'book view';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '5';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Content: Author */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'node';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
$handler->display->display_options['relationships']['uid']['required'] = TRUE;
/* Relationship: User: book author (field_book_author) - reverse */
$handler->display->display_options['relationships']['reverse_field_book_author_taxonomy_term']['id'] = 'reverse_field_book_author_taxonomy_term';
$handler->display->display_options['relationships']['reverse_field_book_author_taxonomy_term']['table'] = 'users';
$handler->display->display_options['relationships']['reverse_field_book_author_taxonomy_term']['field'] = 'reverse_field_book_author_taxonomy_term';
$handler->display->display_options['relationships']['reverse_field_book_author_taxonomy_term']['relationship'] = 'uid';
$handler->display->display_options['relationships']['reverse_field_book_author_taxonomy_term']['required'] = TRUE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'book' => 'book',
);

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');

```

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


# Question
Title: Commerce Kickstart: How To Add Sort Fields To Search API?
I've been playing with the Search API and I can add new Facet Displays and filters, but no matter what I try I can't get any fields other than Price, Latest and Title to appear as Sort options. What's the 'trick'?

# Answer
For other travelers, the answer is that it's a bug with a patch that has not been made part of the official distribution as of 26 Sep 2014. See #6 for the patch.

https://www.drupal.org/node/2202093
> 1 votes

---
Tags: search, commerce
---


# Question
Title: Required field set via hook_form_alter not fully working in Commerce Checkout form
I created a hook function to make a field **required** and **visible**. The targeted form is the Checkout Billing Form at: example.com/en/checkout/35

I have to mention that the site is build with the Commerce Kickstart distribution.

```
        <?php
    function MyModule_form_alter(&$form, &$form_state, $form_id) {
            if ($form_id == 'commerce_checkout_form_checkout') {
                    $form['customer_profile_billing']['field_cif_nif_id']['#states'] = array(
                      // This #states rule says that the "field_cif_nif_id" fieldset should only
                      // be VISIBLE and REQUIRED if the "field_dispongo_de_" form element is set to "CIF/NIF/ID".
                              'visible' => array(
                                    '#edit-customer-profile-billing-field-dispongo-de-und' => array('value' => t('CIF/NIF/ID')),
                            ),'required' => array(
                                    '#edit-customer-profile-billing-field-dispongo-de-und' => array('value' => t('CIF/NIF/ID')),
                            ),
                    );

                   $form_state['rebuild'] = TRUE; //THIS LINE IS NOT WORKING
      }
    }
    ?>

```

The function seems to work fine since the fied is marked with the red asterisk \*, but it is not really working since the form is sent and saved even if the required field is empty.

I think the problem is not in the function but in its relation with the Commerce Checkout form provided by Drupal Commerce or Commerce Kickstart.

# Answer
> 1 votes
Using `required` along with `#states` will add the required indicator to the element, But there will be **no** client or server side validation involved. So to make the field as required you would have to add the custom validation to the form and there you can validate the field something like below:

```
/**
 * Implements hook_form_alter().
 */
function MODULE-NAME_form_alter(&$form, &$form_state, $form_id) {
  // Check if the form is commerce checkout form.
  if ($form_id == 'commerce_checkout_form_checkout') {
    // Add the custom validation function to the form.
    $form['buttons']['continue']['#validate'][] = 'mymodule_custom_validate_required_field';
  }
}

/**
 * Callback handling the custom validation.
 */
function mymodule_custom_validate_required_field($form, &$form_state) {
  // Check if the field you want to validate exists in the form.
  // replace 'field_dispongo_de_' with the name of field you want to validate.
  if ((isset($form_state['values']['field_dispongo_de_'])) && (empty($form_state['values']['field_dispongo_de_']))) {
    form_set_error('field_dispongo_de_', 'Field cannot be left blank');
  }
}

```

---

**Alternate way:**

Since its a commerce checkout form so we can add the custom validation using hook\_commerce\_checkout\_pane\_info and commerce\_checkout\_form\_validate as discussed here: Adding validation to commerce pane form

---
Tags: entities, commerce
---


# Question
Title: add class to book navigation block links
I use navigation block generated by block module. Tha block is displayes on all pages that belongs to book. I would like to add custom class to all links inside navigation block. I found that the block is generated by code here\>

https://api.drupal.org/api/drupal/modules!book!book.module/function/book\_block\_view/7

But I am unable to figure out how to alter links. Any help appreciated. Thank you.

# Answer
> 0 votes
Give a try to Block class module: Block Class allows users to add classes to any block through the block's configuration interface. By adding a very short snippet of PHP to a theme's block.tpl.php file, classes can be added to the parent `<div class="block ...">` element of a block.

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


# Question
Title: What are some php cache related modules for drupal 7?
i just updated my server to php 5.5 and been reading about apc and opcache, and I'm not to sure which one to use or what modules support this feature. What are some modules or modifications to drupal 7 that take full capabilities of these php caching mechanisms? Am i correct that opcache is superseded by opcache for php 5.5?

# Answer
For opcode caching APC, Zend Optimizer, and OpCache are totally transparent to the application. If you have them installed and enabled, Drupal will use them whether you like it or not. There are some configuration tricks you can do to use them better, but this is really system specific. For example, to help save memory, some users will filter out .admin.inc files from APC so they never get cached.

I am using OpCache on my PHP 5.5 servers.

To confuse matters, APC and Zend provide user caches which can be used as alternate cache backends to replace and/or supplement the database cache mechanism. I would not recommend APC for this. Memcache and Redis are the go-to solutions for these. MongoDB can also be used, too.

My PHP 5.5 servers also have APCu installed just in case there is anything that may be using it. Last time I checked, the Performance module would use APC user cache for stats.
> 3 votes

---
Tags: 7, caching
---


title: Time limit items in your cart

text:
# Question
Title: Time limit items in your cart
Product in your cart active only 20 minutes, then is removed

how to do?

# Answer
I think Commerce Cart Expiration (https://www.drupal.org/project/commerce\_cart\_expiration) will do what you want. But I've only used to expire carts that are older...48 hours, for example. That works fine with cron, but for shorter periods, you'll need something else.

From the readme:

*The module also provides a block which displays the time remaining. Its content gets refreshed by javascript just like a countdown. To show up the block, add the 'Cart expiration' block to your preferred region under admin/structure/block. You can configure this blocks content on the block configuration page. Use the token \[commerce-order:expiration-formatted\] to get a format that can be manipulated by javascript.*
> 1 votes

---
Tags: rules, commerce
---


# Question
Title: Button to selectively include content in an RSS feed
When creating or editing some content types I want to be able to have the option to add the content to an RSS feed thats generated by Views.

Is this achievable?

# Answer
Well, you can just add a field to the content type(s) you are collecting with your view and use that to filter the rss feed. You could easily add a "include in rss" checkbox for example with whatever default value you like.
> 1 votes

---
Tags: views, feeds
---


title: unique user name but duplicate password

text:
# Question
Title: unique user name but duplicate password
I'm having a developer work on a site for me. I'm being told that each user must have a unique username. That makes sense. I'm also told that they all need to have a unique password. This doesn't make sense and is causing problems for me client. Shouldn't a unique combination of username and password be what's required? Can anyone help direct me to a solution?

# Answer
> 2 votes
Users can have the same password, but they cannot have the same username by default. Theoretically, users could have the same username with some customization, but they would need to log in with something else that makes them unique such as an e-mail address.

---
Tags: users
---


title: Ajax error every time open view

text:
# Question
Title: Ajax error every time open view
i want to create new view but every time i make selection like user, content etc. i got this error

> An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows. Path: /dru/system/ajax StatusText: Internal Server Error ResponseText: registrar\_frameset({ a\_id: 48873, // edit this to pass your portfolio ID, drid: 'as-drid-2416478692338427'}); // edit this to pass your Domain Registrant ID

# Answer
I would comment this, but I do not have the reputation. If you are using jQuery Update module, make sure it is set to 1.5 for the admin pages.
> 0 votes

---
Tags: ajax
---