title: How to remove taxes if outside EU

text:
# Question
Title: How to remove taxes if outside EU
I have a custom checkout page. I have already included the Swedish taxes of different amounts in my product price. Now the customer wants me to remove the taxes if the buyer is outside the EU. I tried commerce tax remove but couldn't make it happen. I was thinking if I use the base price instead of the commerce\_order\_total\['und'\]\[0\]\['amount'\] for order order total and to use base price for products on line items?

Will this be correct?

Thank you.

# Answer
You have three options:

1) Apply the patch from https://drupal.org/node/1240216. It will give you a rules action that will remove the tax.

2) Always enter product prices without tax, then the VAT rules can just be made conditional based on the customer address.

3) Use commerce\_vat (and commerce\_eu\_vat).

The first one is probably your easiest way out at this point.
> 3 votes

# Answer
Commerce remove tax seems to work for me when applied to "Calculating the sell price of a product" event. Im using conditions that order has shipping address and the country is not in one EU countries.
> 1 votes

---
Tags: commerce
---


# Question
Title: How to pre populate the commerce shopping cart with products
Is there a way to pre populate the Shopping cart with all products similar to this example? http://www.taytocrisps.ie/park/book\_tickets

I only have 5 products on the site and I want to skip one step and add to all products to the cart. The user then selects the number of the products in the cart and goes straight to billing information and payment.

# Answer
> 1 votes
I implemented a hook\_menu with callback that adds specific product variation from the arguments to the cart and then redirects the user to cart. With same logic you could toss in all the products you wish. Mayby just additionally check that that cart is initially empty.

```
function x_menu(){
    $items['tickets'] = array(
      'page callback' => 'x_tickets_callback',
      'access arguments' => array('access content'),
    );
    return $items;
}

function x_tickets_callback(){
    global $user;

    // mayby check that cart is empty here

    // you should get these really from some variable
    for($i = 1, $i<7,$i++){
      $commerce_product = commerce_product_load($i);
      // create line item from product
      $line_item = commerce_product_line_item_new($commerce_product);
      commerce_cart_product_add($user->uid, $line_item);
    }
    // prevent notification
    $messages = drupal_get_messages();
    drupal_goto('cart');
}

```

---
Tags: views, ajax, commerce
---


# Question
Title: How to create a filter in views which only shows contents that current user can edit?
I set content access permission using nodeaccess\_userreference module, I need a view to shows contents that user can change.

# Answer
> 0 votes
It's probably not a very well-elaborated patch/module but it might solve your problem: https://www.drupal.org/node/620392 I've just found it...

---
Tags: views, users
---


# Question
Title: export search_api settings with features
I used features to export search\_api settings and in the feature\_module.features.inc file was code that started like below:

I am trying to do the same thing again and I can't find the option to export these settings in features any more. Any idea how to do it?

```
>   /**  * Implements hook_default_search_api_index().  */ function
> vimn_search_default_search_api_index() {   $items = array();
> $items['node_search'] = entity_import('search_api_index', '{
>     "name" : "Node search",
>     "machine_name" : "node_search",
>     "description" : null,
>     "server" : "solr",
>     "item_type" : "node",
>     "options" : {
>       "index_directly" : 0,
>       "cron_limit" : "50",
>       "fields" : {
>         "nid" : { "type" : "integer" },
>         "title" : { "type" : "text" },
>         "created" : { "type" : "date" },
>         "changed" : { "type" : "date" },

```

# Answer
> 2 votes
I was having this problem today too. Features would not display my search\_api index for export. It also wasn't displaying my Page Manager pages, Page Manager handlers, or Views.

I realized the problem was that I had moved all of those configurations into a custom module. Features wouldn't try to export anything that is module-provided, even if those items had been created through that site's UI in the first place.

I disabled the module (without un-installing) and Features was happy to let me export my index configuration after that.

# Answer
> 1 votes
I have the same problem. I found that you can not export index setting, if your solr server does not turn on.

---
Tags: features, search
---


title: How to find url of content-type?

text:
# Question
Title: How to find url of content-type?
I am new in Drupal

I have an article website, and it has some category like History, Sport, Graphic, Music and etc.

But when I add some content-type for each of these and when I visit that post, I can't find the URL path of them. for example when I post a new Sport article that it's title is **"Ronaldo's regimen"** and when I click on save button on drupal, drupal show me an article that its URL is this :

> www.example.com/content/ronaldos-regimen

I need to add a link to my menu for each catagory, something like this:

> Sport | History | Graphic | Music

(*I use **pathauto** module*)

# Answer
You need to do two things if I understand you correctly.

You need to set up Pathauto patterns for your content, and you need to set up a few views.

**Pathauto:**

You can get really complicated with this, but as you are just starting do it the easy way.

Go to: admin/config/search/path/patterns

This will show you the pathauto pattens page. In the section content paths, for each of your content types add something like the following:

```
CONTENT_TYPE_OR_CATEGORY/[node:title]

```

So, for sports content or category type you will add:

```
sports/[node:title]

```

This means that when you create a new sports node it will get a URL alias that is a combination of the category and the title of the node.

Make sure to go to the Pathauto tab: Delete aliases, and delete all content aliases. Then go to Bulk Generate tab and generate content aliases before you continue.

**Views:**

When you navigate to 'sports/ronaldos-regimen' it will take you to that article, but what if you just type in 'sports' as the URL. You probably want to have a list of articles of type sports.

For each of your content types you create a view. (if you have a lot of different content types this will not work and you will have to use contextual filters, but for now lets assume you only have 5 or 6 different content types).

For sports you set:

1. the view's Title to 'Sports'
2. the path to 'sports'
3. the Menu to 'Sports', and set the menu it must appear in to main menu.
4. add a Filter Criteria of Content:type, and set it to sports type

Do the same for all the views (you can make sure your sports view is to your liking then clone the view for the other categories and make changes)
> 1 votes

# Answer
While creating node, Check on Provide a menu link. Add *Menu link title* and select *Parent item* where you want to add the current node.

That's it
> 2 votes

# Answer
There is no such thing as *url of content-type* in Drupal. However, you may be looking for:

# And if you want a listing

of nodes from a content type, taxonomy term, or anything like that, use Views. Views allows you to create listing pages, with (almost) any URL you want for them.
> 2 votes

---
Tags: uri
---


# Question
Title: How to extract query placeholders for debug purposes?
When I cast query to string, I can see `WHERE` that will be passed to the database, like this:

```
WHERE  (idProperty = :db_condition_placeholder_0)
  AND  (idCategory = :db_condition_placeholder_1)

```

But how can I extract these placeholders?

# Answer
This can be done using `arguments`:

```
echo (string)$query;
var_dump($query->arguments());

```

This simple code will give you both query and arguments, for simple debugging.
> 1 votes

---
Tags: database, debugging
---


# Question
Title: How to create a child page that has the same content type as parent page?
I enabled the Book module on drupal 7 and created 2 new content types. Let said I created a new "content type A" and "content type B", and keep the book module content type as "Book page". The issue I have is that whenever I adding a child page on a "Content type A" or the "Content type B" page, these child pages are "Book page" content type. **How to keep these child page the same content type as parent page?**

**PS: I see there is a "Books" setting under "content \> books" tab. But it only allow me to select one content type as child page.**

# Answer
I found a module that does the job, which is Book made simple. This module add the setting on content type and have the option for "**SELECT CONTENT-TYPES ALLOWED AS CHILD**.", "**SELECT CONTENT-TYPES ALLOWED AS PARENT**" and "**Other Settings**". Then a dropdown listbox will be added in the books link like the one on screenshot. I hope Drupal 8 has a similar feature like this.

PS: One of the issue is "Printer" module also print "Add child page" on each page.
> 1 votes

---
Tags: nodes
---


# Question
Title: Display children of taxonomy term in parent taxonomy page
i would like to print the children of taxonomy term in its parent taxonomy page.

For example there is a news portal and under Sports taxonomy term page i would like to print the children of Sports term:

SPORTS

# football #basketball #tennis ...

and then the latest nodes...

How can i achieve this?

# Answer
> 1 votes
1. Create a view of taxonomy terms
2. Create a block display for the view
3. Add a contextual filter for vocabulary ID
4. Make the block show up on all vocabulary pages in the block settings.

# Answer
> 0 votes
It's really easy to achieve this using the Views module.

Just install the views module and add a new view page fetching the taxonomy terms. The procedure is pretty straightforward if you know how to use Views.

# Answer
> 0 votes
Use Panels for this, and the `Views content panes` sub module that comes with it. Download and enable the module (and the sub module) as usual, then...

1. Create a view of taxonomy terms
2. Add a contextual filter for a term id
3. Go to `admin/structure/panels`
4. Enable the `Taxonomy term template`
5. `Edit` the `Taxonomy term template`
6. Add a new variant
7. Add the `Taxonomy term view` you created earlier to the content, and pass the current page's taxonomy term id context as an argument to the View
8. Add the Taxonomy term `Description` content to the Panel
9. Add the `List of related items` content to the Panel

---
Tags: taxonomy-terms
---


# Question
Title: Programmatically alter custom checkout panes depending on cart quantity
In a checkout process, I need to collect additional data *depending on the quantity in the cart*.

What is it about ?

* Customers book travels
* For the sake of argument, let’s say 2 couples of lovers book a week in Venice : they will add 4 "Venice trip" to the cart
* During checkout, I collect usual customer data, plus additional information (name, passport, birthday…) *for each other participant* in a dynamic custom pane.

My current work :

1. Set up a custom pane with Commerce Fieldgroup Panes, disabled by default
2. Add a rule with Commerce Rules Extra, which enables the pane if qty \> 1 for specific product type
3. Then with `MYMODULE_form_FORM_ID_alter`, I tried 2 different ways to add the relevant fields :

---

First one: **duplicate the whole custom pane into the checkout page** :

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

  $order = $form_state['build_info']['args'][0];
  //load line item
  $line_item = commerce_line_item_load($order->commerce_line_items['und'][0]['line_item_id']);
  //get quantity
  $qty = round($line_item->quantity);

  //duplicate the pane for each participant (minus the customer user)
  for($n=1; $n<$qty; $n++) {
    $form['commerce_fieldgroup_pane__group_pax_sup_'.$n] = array_merge(array(), $form['commerce_fieldgroup_pane__group_pax_sup']);
  }
}

```

The pane is duplicated fine, but the fields of duplicated panes are not saved, nor displayed at next step. Maybe because I have to tell the system these *ARE* checkout panes, + subsequent callbacks (as incheckout\_pane\_example module) ?

If so, I don't find **how to declare the added panes are checkout ones inside that loop**.

---

Second one : **duplicate each field of the custom pane inside the checkout pane itself** :

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

  $order = $form_state['build_info']['args'][0];
  //load line item
  $line_item = commerce_line_item_load($order->commerce_line_items['und'][0]['line_item_id']);
  //get quantity
  $qty = round($line_item->quantity);

  //duplicate the pane for each participant (minus the customer user)
  for($n = 1; $n<$qty; $n++) {

    foreach ($form['commerce_fieldgroup_pane__group_pax_sup'] as $key => $value) {

      //searching fields into the fieldgroup array
      if(substr($key, 0, 5) == 'field') {

        //we duplicate the field
        $form['commerce_fieldgroup_pane__group_pax_sup'][$key.'_'.$n] = array_merge(array(), $form['commerce_fieldgroup_pane__group_pax_sup'][$key]);
        //rename field to have it unique
        $form['commerce_fieldgroup_pane__group_pax_sup'][$key.'_'.$n]['und'][0]['#field_name'] = $form['commerce_fieldgroup_pane__group_pax_sup'][$key.'_'.$n]['und'][0]['#field_name'].'_'.$n;
        //add it to the fieldgroup : NOT SURE WHICH IS THE RIGHT ONE OR IF I MUST LEAVE ALL
        $group_pax_sup = $form['commerce_fieldgroup_pane__group_pax_sup']['#groups']['group_pax_sup'];
        $group_pax_sup->children[] = $key.'_'.$n;
        $form['commerce_fieldgroup_pane__group_pax_sup']['#group_children'][$key.'_'.$n] = 'group_pax_sup' ;
      }
    }
  }

```

This is adding the fields correctly, but again nothing is saved or displayed in next steps. Here it seems that I don't manage to **add the fields to the fieldgroup correctly?**

How could I achieve this ? Thank you so much!

# Answer
> 1 votes
It occurred to me there may be a nice way to do this with contrib so I'll put it down, but it does require different pieces playing together nicely, which doesn't always happen (:

I see ~~two~~three clean approaches.

**Using the Field API and contrib**

If you want to use the Field API to create/update/delete fields, then I still think you should use custom line item products. I'm a little surprised it doesn't have the option of displaying the form at checkout built-in. Maybe a module will be built to add that, it should be relatively simple. But in the meantime this might get you there with existing contrib:

1. Install editablefields and Commerce Views Pane.
2. Create a custom line item type for the customisable product. Add the necessary fields but don't configure them to show up on the add-to-cart form. Also ensure the line items can't be combined.
3. Create a line item view that accepts an order ID as an argument, and add the fields you'd like to edit (and give them the editable formatter). Add a filter to ensure it only displays line items of the correct bundle. You can test the view in preview by creating a new order with a few customisable products, find the order ID (eg. from the checkout page), and pass that order ID to the Views preview. It should show you a row for each customisable line item. I wouldn't try to get the Views pane working until it works in preview.
4. Add that view as a checkout pane.
5. Make a circle of salt around the server and whisper a prayer.

**Using the Field API and combined line items** (involves code)

If you'd like to have a single line item have multiple customisations, then you need to set up the fields to allow that.

1. Create a field collection with the fields you'd like.
2. Add a multi-value field collection of that type to the appropriate line item type (ensure it won't show up on the add-to-cart form).
3. Create your own checkout pane that displays the field edit form. You'd read the quantity from the line item and display just that many fields (as it's a multi-value field it'll save ok however many there are).

**Creating a custom pane and storing data serialised with the order** (involves code)

This has the disadvantages that you can't use the Field API to set up, modify, or read the fields (so no Views). checkout\_pane\_example.module shows how to do this, adding a nickname and second email field and storing the data with the order.

**Ugly method**

I think you could probably do it with Commerce Fieldgroup Panes if you create a field collection with the fields you want, and then add it as a multi-value field to the order entity. You'd need some code to ensure only the correct number of field collections are shown (to match the number of line items that need customising). This method feels dirty and has two concrete drawbacks I can think of:

1. As you add more customisable products the order entity will get more and more fields.
2. You can't associate the customisations with a particular line item (what if I want a want one message on my red sweater, and a different one on my blue sweater - which message goes with which line item?).

# Answer
> 0 votes
I ended using Andy's 2nd solution, using the Field API and combined line items.

> Create a field collection with the fields you'd like. Add a multi-value field collection of that type to the appropriate line item type (ensure it won't show up on the add-to-cart form). Create your own checkout pane that displays the field edit form.

As I fighted a while with some aspects of the API, especially with **Field collection**, here's my full checkout pane `.module`, maybe it will help somebody.

```
/**
 * Implements hook_commerce_checkout_pane_info().
 */
function vts_commerce_checkout_pane_info() {

  $panes['paxsup_pane'] = array(
    'title' => t('Other Participants'),
    'base' => 'vts_pane',
    'name' => t('Other Participants'),
    'page' => 'checkout',
    'weight' => -5,
  );

  return $panes;
}

/**
 * Implements hook_pane_checkout_form().
 */
function vts_pane_checkout_form($form, &$form_state, $checkout_pane, $order) {

  //load the current line item.
  $line_item = commerce_line_item_load($order->commerce_line_items['und'][0]['line_item_id']);

  $pane_form = array();

  if ($checkout_pane['pane_id'] == 'paxsup_pane') {
    field_attach_form('commerce_line_item', $line_item, $pane_form, $form_state, NULL, array('field_name' => 'field_paxsup'));
  }
  return $pane_form;
}

/*
 * Change general GUI edit field cardinality range from 1->1 to 1->20
 */
function vts_form_field_ui_field_edit_form_alter(&$form, &$form_state, $form_id) {
  // Increase the max cardinality to 20
  $range = drupal_map_assoc(range(1, 20));
  $new_options =  array(FIELD_CARDINALITY_UNLIMITED => t('Unlimited')) + $range;

  // Change the options
  $form['field']['cardinality']['#options'] = $new_options;
}

/*
 * Implements hook_form_FORM_ID_alter().
 */
function vts_form_commerce_checkout_form_checkout_alter(&$form, &$form_state, $form_id) {

  //Load line item to get pax number
  $line_item = commerce_line_item_load($form_state['build_info']['args'][0]->commerce_line_items['und'][0]['line_item_id']);
  $paxsup_nb = $line_item->quantity -1;
  if($paxsup_nb > 0){

    //Unset unnecessary items of paxsup field
    for($n=19; $n > $paxsup_nb-1; $n--){
      unset($form['paxsup_pane']['field_paxsup']['und'][$n]);
    }

    //Fill in paxsup with session values
    for($n=0; $n<$paxsup_nb; $n++){

      $form['paxsup_pane']['field_paxsup']['und'][$n]['field_paxsup_foo']['und']['#default_value'][0]            = isset($_SESSION['paxsup_foo_'.$n])? $_SESSION['paxsup_foo_'.$n]:'';
      $form['paxsup_pane']['field_paxsup']['und'][$n]['field_paxsup_bar']['und'][0]['value']['#default_value']        = isset($_SESSION['paxsup_bar_'.$n])? $_SESSION['paxsup_bar_'.$n]:'';
      $form['paxsup_pane']['field_paxsup']['und'][$n]['field_paxsup_date_of_birth']['und'][0]['#default_value']['value']  = isset($_SESSION['paxsup_date_of_birth_'.$n])? $_SESSION['paxsup_date_of_birth_'.$n]:'';

    }

  }
  else {
    unset($form['paxsup_pane']);
  }
}

/**
 * Implements hook_pane_checkout_form_validate().
 */
function vts_pane_checkout_form_validate($form, &$form_state, $checkout_pane, $order) {

  $line_item = commerce_line_item_load($order->commerce_line_items['und'][0]['line_item_id']);
  $paxsup_nb = $line_item->quantity -1;
  if($paxsup_nb > 0){

    for($n=0; $n<$paxsup_nb;$n++) {
      if(empty($form_state['values']['field_paxsup']['und'][$n]['field_paxsup_foo']['und'][0]['value'])
        || empty($form_state['values']['field_paxsup']['und'][$n]['field_paxsup_bar']['und'][0]['value'])
        || empty($form_state['values']['field_paxsup']['und'][$n]['field_paxsup_date_of_birth']['und'][0]['value']) ) {

        return FALSE;
      }
    }
  }

  return TRUE;
}

/**
 * Implements hook_pane_checkout_form_submit().
 */
function vts_pane_checkout_form_submit($form, &$form_state, $checkout_pane, $order) {

  $line_item = commerce_line_item_load($order->commerce_line_items['und'][0]['line_item_id']);
  $paxsup_nb = $line_item->quantity -1;
  if($paxsup_nb > 0){

    //Set paxsup SESSION values
    for($n=0; $n<$paxsup_nb;$n++) { //
      $_SESSION['paxsup_foo_'.$n] = $form_state['values']['field_paxsup']['und'][$n]['field_paxsup_foo']['und'][0]['value'];
      $_SESSION['paxsup_bar_'.$n] = $form_state['values']['field_paxsup']['und'][$n]['field_paxsup_bar']['und'][0]['value'];
      $_SESSION['paxsup_date_of_birth_'.$n] = $form_state['values']['field_paxsup']['und'][$n]['field_paxsup_date_of_birth']['und'][0]['value'];
    }

    // Add the paxsup values to the line_item fields
    if (!empty($form_state['values']['field_paxsup'])) {

      if(0 == count($line_item->field_paxsup)){
        //CREATE A NEW PAXSUP SET
        $entity = entity_load_single('commerce_line_item', $line_item->line_item_id);
        $wrapper = entity_metadata_wrapper('commerce_line_item', $entity);
        $collections = array();

        for($n=0; $n<$paxsup_nb;$n++) { //
          $fc = entity_create('field_collection_item',  array('field_name' => 'field_paxsup'));
          $fc->setHostEntity('commerce_line_item', $line_item, LANGUAGE_NONE, FALSE);

          $fc->field_paxsup_foo['und'][0] = array('value'=> $form_state['values']['field_paxsup']['und'][$n]['field_paxsup_foo']['und'][0]['value']);
          $fc->field_paxsup_bar['und'][0] = array('value'=> $form_state['values']['field_paxsup']['und'][$n]['field_paxsup_bar']['und'][0]['value']);
          $fc->field_paxsup_date_of_birth['und'][0] = array('value'=> $form_state['values']['field_paxsup']['und'][$n]['field_paxsup_date_of_birth']['und'][0]['value']);

          $fc->save(TRUE);
          $collections[] = $fc;
        }
        //Set the field collection items via the wrapper.
        $wrapper->field_paxsup->set($collections);
        $wrapper->save();

      }
      else {
        //UPDATE FIELD COLLECTION
        for($n=0; $n<$paxsup_nb;$n++) { //

          $fc = entity_load_single('field_collection_item', $line_item->field_paxsup['und'][$n]['value'] );
          $fc->field_paxsup_foo['und'][0] = array('value'=> $form_state['values']['field_paxsup']['und'][$n]['field_paxsup_foo']['und'][0]['value']);
          $fc->field_paxsup_bar['und'][0] = array('value'=> $form_state['values']['field_paxsup']['und'][$n]['field_paxsup_bar']['und'][0]['value']);
          $fc->field_paxsup_date_of_birth['und'][0] = array('value'=> $form_state['values']['field_paxsup']['und'][$n]['field_paxsup_date_of_birth']['und'][0]['value']);
          $fc->save(TRUE);

        }
      }
    }
  }
}

/**
 * Implements hook_pane_review().
 *
 */
function vts_pane_review($form, $form_state, $checkout_pane, $order) {

  $line_item = commerce_line_item_load($order->commerce_line_items['und'][0]['line_item_id']);
  $paxsup_nb = $line_item->quantity -1;
  if (!empty($line_item->field_paxsup['und'][0])) {

    $view = '';
    for($n=0; $n<$paxsup_nb;$n++) {

      $paxsup = entity_load_single('field_collection_item', $line_item->field_paxsup['und'][$n]['value'] );

      $display = array('label' => 'hidden');
      $foo = field_view_field('field_collection_item', $paxsup, 'field_paxsup_foo', $display);
      $bar = field_view_field('field_collection_item', $paxsup, 'field_paxsup_bar', $display);
      $date = field_view_field('field_collection_item', $paxsup, 'field_paxsup_date_of_birth', $display);

      $view .= '<p>'.$foo[0]['#markup'] .' '. $bar[0]['#markup'] .' '. $prenom[0]['#markup'] .t(', né(e) le '). $date[0]['#markup'] .'</p>';
    }

    return $view;
  }
}

```

---
Tags: commerce
---


title: Hide fields on content creation

text:
# Question
Title: Hide fields on content creation
I have added my own content type with many fields to enter, I want to hide some fields when adding a content according to radio button selection. I explain, in the add content page, i have two radio buttons (inside/outside) and inside is selected by default and some fields are hidden, when user select outside, some fields will be hidden and the fields accorded to outside will be shown to user to fill them. How to do this ?

# Answer
> 1 votes
You are looking for Conditional Field Module...

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

---
Tags: entities, nodes
---


# Question
Title: Add Help Text for User Roles Field on User Edit Page
I would like to add some help text for one of the fields displayed on the admin user edit page (the page seen when an admin edits a user account).

The help text would provide a brief description of each role that could be selected.

Is there some hook I can use to update the admin form?

# Answer
> 3 votes
You can able to do it using hook\_form\_FORM\_ID\_alter or using hook\_form\_alter in a custom module..

You can add help text either using #suffix form attribute or #description attribute..

# Answer
> 1 votes
Using a custom module, implement `hook_form_alter` to add the `#description` form key and text value to the form in question.

I recommend the Devel module to find the name of the form and it's structure by using `dpm($form)` and `dpm($form_id)` within your `hook_form_alter`.

---
Tags: hooks, users
---


# Question
Title: Drupal Search API facet block not listing all indexed fields
I have a content type that has a term reference field to a vocabulary called 'Categories'.

Categories

```
- Cat 1
- - Cat 1.1*
- - Cat 1.2
- - - Cat 1.2.1
- - - Cat 1.2.2*
- - Cat 1.3
- Cat 2
- Cat 3
- - Cat 3.1
- - - Cat 3.1.1
- - Cat 3.2

```

As you can see, the Category vocabulary has a terms in a Hierarchy.

Using Search API and Solr, im indexing the term reference field using 'Parents All'. I have set the index up to index the hierarchy.

Its all working perfectly, however, not all terms are listed in the facet box, despite the products being indexed correctly. There are a few terms that do not appear. (marked with a * above).

However, I know that the nodes are indexing correctly. I know this as I can filter by a facet that **is** working, then swap the argument in the URL arguments for the TID of a term that **isnt** working. When this happens, the products are displayed correctly in the view.

So my question is...what could cause Drupal/Search API to not display all items in a facet.

How can I start to debug this?

I have tried rewriting the facet using this function:

```
function HOOK_facet_items_alter(&$build, &$settings) {
                        if ($settings->facet == "YOUR_FACET_NAME") {
                          foreach($build as $key => $item) {
                            $build[$key]["#markup"] = drupal_strtoupper($item["#markup"]);
                          }
                        }
                      }

```

However, when I print out the list of terms inside $build the ones that arn't displaying are not listed in the array.

ANy help or any other hook suggestions are greatly appreciated.

# Answer
Turns out that I had a limit on the number of items to display.

To fix it, I had to change the limit under Facet \> Display.
> 1 votes

---
Tags: search
---


title: Formatting numbers in D7

text:
# Question
Title: Formatting numbers in D7
I have a serialized object in a field. I now need to output a float-value. Since the site has 2 languages (german/english) I now need to format the float-number based on the current language.

```
$value = 123456789.01;
// Language = english
print the_format_function($value); # => 123456789.01

// Lanuage = german
print the_format_function($value); # => 123.345.789,01

```

I'm lookin for `the_format_funtion();`.

# Answer
> 6 votes
There is a format\_number API module, which may eventually handle this for you. And possibly will make it into D8.

For the moment I think the function you are looking for is number\_format()

# Answer
> -1 votes
There is a number\_format function in native php, so you can do in your drupal template:

```
print number_format($value, 2, ',', '.'); # => 123.345.789,01

```

see http://php.net/manual/es/function.number-format.php

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


# Question
Title: Changing Global: Text Area based on an exposed filter in views?
A client wants to display different text in a page depending on the value of the View's Exposed Filter.

I could throw this logic into the template.php or use javascript (showing and hiding a span depending on the value), but this feels like a very poor way to do this when considering maintainability?

Does there exist a Views plugin to perhaps show different text blocks in the header based on the value of an exposed filter?

Currently on Drupal 7.31 using Better Exposed Filters. I'm open to using something other than Global: Text area if there is a better mechanism.

# Answer
You could use

```
hook_views_pre_render(&$view){
    $view->attachment_before = $view['exposed_input']['your_desired_field'];
}

```

Hope it works
> -1 votes

---
Tags: views
---


title: Ways to speed up a simpletest?

text:
# Question
Title: Ways to speed up a simpletest?
I'm trying to speed up my test. I have to use simpletest\_clone. I've read something like "copy the database to memory" but i did some research and didn't found how. Aaand if i want to do more than one test with the same database there is somehow a thing that let you use the same database cloned for the first case i tested to be still loaded to run the next test case? because if i want to run 4 or 5 test case using simpletest\_clone it may take years if i let it clone and drop the database for every case

# Answer
> 3 votes
There are few ways of speeding up the Simpletests:

Other option to consider:

Use alternatives:

---
Tags: 7, testing
---


# Question
Title: How to get a list of all displays of every view?
I'm doing some test and I'm trying to get a list of all the displays of every view to do the test things in every display of every view, but I don't have any idea how to do it. When using `views_get_all_views()` I only get the first display of every view, but what I want is every view and everything inside that view.

# Answer
Please find the following drush one-liner to list all the views including all display names:

```
drush eval 'foreach (views_get_all_views() as $view) { foreach ($view->display as $display => $data) { print "$view->name: $display\n"; }; }'

```

Modify the code as required.
> 6 votes

---
Tags: 7, views
---


# Question
Title: does node_save wait until end of php session to create db record?
Is it possible/expected that node\_save() does not create a new record until the current php session is complete?

In other words, if i have a set of nodes to create and i need to check something that is based on the entire list of nodes prior to creating each one; the ones i am creating in my script will not yet be included in the full list?

# Answer
> 0 votes
> Is it possible/expected that node\_save() does not create a new record until the current php session is complete?

I'm not sure 'session' is the right word there, I'm assuming you mean 'current request' (queuing actions to be run when the session has expired would be an odd thing, and not something PHP/Drupal would do without you telling it to).

Either way, before `node_save()` completes it commits the database transaction and flushes relevant caches. So no, it doesn't wait for the current request to complete.

So to address

> the ones i am creating in my script will not yet be included in the full list?

No, once you've saved the node, and assuming it completed without error, it will be in the database and available immediately via `node_load()`.

Of course you don't actually *need* to load it, as your `$node` object will be in an identical state to the loaded node when `node_save()` has completed anyway.

Ignoring all that, if you actually mean *"does running `node_save()` automatically update an array of nodes I've previously loaded into a variable earlier in the script"*, then also no. That would be magic :)

---
Tags: nodes
---


# Question
Title: Calendar View of Events shows 1st of month in header
I would like my Calendar Page View of Events to show "August 2014" (or whatever the current month is) as the heading instead of showing "Friday, August 1, 2014" (see attached pic). Is there a configuration setting for this please? I have looked at various YouTube vids and it shows the date how I want, but I cant seem to figure out how they are doing it? .

# Answer
> 0 votes
Here's the fix, the reference to it is here : click on this link and scroll down to item #20 : drupal.org/node/2294973 , however its pasted below just in case that link becomes broken...

Quick workaround for people unable to apply the patch:

STEP 1: Edit date\_views/theme/theme.inc and go find line 165.

Change these two lines:

```
$format_with_year = variable_get('date_views_' . $granularity . 'format_with_year', 'l, F j, Y');
$format_without_year = variable_get('date_views_' . $granularity . 'format_without_year', 'l, F j');

```

To these two lines:

```
$format_with_year = variable_get('date_views_' . $granularity . '_format_with_year', 'l, F j, Y');
$format_without_year = variable_get('date_views_' . $granularity . '_format_without_year', 'l, F j');

```

Note: the only difference is one underscore character added to each line.

Upload the changed file back to your web server.

STEP 2: Go to (YOUR\_WEBSITE)/admin/config/regional/date-time/date-views and click Save. If you get permissions errors, try clearing caches.

---
Tags: views, datetime
---


title: How to do it with views?

text:
# Question
Title: How to do it with views?
I have two content types BLOG and PROPERTIES

In BLOG, I have an entity reference field called "Related properties" that will point to the PROPERTIES content type.

Every BLOG node is gonna have a unique set of entity reference values i.e Content/Contents of PROPERTIES content type.

Now what I want is to list the entity referenced contents of content type PROPERTIES in a view with respect to the nid of the content of type BLOG.

How can I do this using Views?

# Answer
> 0 votes
Create a new view of type content

Then add contextual filter "Content: Nid". Here you can add different settings depending on your needs.

Under "Relationships" you should be able to select the entity reference field. This brings in all information about the referenced properties.

As fields you can now add any field from the references properties - just add this relationship

---
Tags: 7, views
---


# Question
Title: How to NOT "Print" a section by using Print module?
I installed "Print" and "Book Made Simple" modules on Drupal 7. The Print module also print the button "**add this child**" from "Book Made Simple". How can I not print "Add this child" on PDF?

***below screenshot is showing where the button from "Book Made Simple"***

***And here is the screenshot of a PDF contained "Add child page" and icon.***

# Answer
In those cases I added a custom print--pdf.tpl.php file to my theme and defined my custom css in the head of the HTML page which is rendered in this file (you find the original template file named "print.tpl.php" in the print modules folder - just copy it to your theme and rename it).

Here you can define any element by CSS and give it a "display: none;" - so it will not be seen in your final PDF.
> 3 votes

---
Tags: nodes
---


title: How to theme a blocktitle of a view?

text:
# Question
Title: How to theme a blocktitle of a view?
As i am still developing some basic php skills:

I want to theme the title of my views-block slightly (just color and fontweight)

I have created a views-view--my-view--block-1.tpl.php and pasted the code of the 'display output' under the theme information of my view.

However i am stuck here as i cant seem to find anything that looks like a block title variable.

I have looked in my block.tpl.php but dont know what code to use here.

Help appreciated,

# Answer
You can achieve what you have stated in several different ways. The easiest and straight-froward would be:

Right click on the title, select **Inspect element** and then find the default CSS classes that represent the generated view and the css class for the element (usually h2 tag) and apply your custom CSS to it.

You can also install/enable the Devel Themer module that would provide you more information about every section of your page. Let's say you want to know which template file exactly renders a particular, click on that section and the devel themer would display the template file that is being used. Don't forget to disable the module, once you are done.

Make sure that you clean the cache whenever you make changes to the template files, either the theme registry cache or the 'all'.

You can also add CSS directly to the tag inside the template file that would look something similar:

```
 <?php if ($title): ?>
    <h2<?php print $title_attributes; ?>><?php print $title; ?></h2>
  <?php endif;?>

```

Or you can style the above in your template file.
> 0 votes

# Answer
Have a look on the original template on modules/block:

```
<div id="<?php print $block_html_id; ?>" class="<?php print $classes; ?>"<?php print $attributes; ?>>

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

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

```

As you might see in line 4 there is a

```
<?php if ($block->subject): ?>
<h2<?php print $title_attributes; ?>><?php print $block->subject ?></h2>
<?php if ($block->subject): ?>

```

Use this... but do not forget to use

```
<?php print render($title_prefix); ?>

```

before the title and

```
<?php if ($block->subject): ?>

```

after the title - these variables enable contextual links.

Additionally assure that you follow the template naming conventions. I think it should be views--view--my-view--block-1.tpl.php (but I am not sure - did you alreay find out if your template file is used? To do this just add any text into the file to see changes in the browser).

When you just added a new template file remember to rebuild theme registry. Either by deleting all Drupal caches or by visiting admin/appearance. If you use Devel module in conjunction with Admin menu you find a possibility to rebuild the theme registry under the projects favicon on the left of the Admin menu.
> 0 votes

---
Tags: theming, blocks
---


title: hook_onload() replacement

text:
# Question
Title: hook_onload() replacement
I want to add JS functions to the body tag's onload and onunload attributes with a custom module. The only hook I found was hook\_onload() from Drupal 4.7, but this method has been deprecated. What is the Drupal 7 way of achieving this?

# Answer
You don't use PHP hooks to execute Javascript. You would put the Javascript you want to execute into a .js file, and then use PHP to just attach that file to any page where it is needed, for example, using `drupal_add_js()`.

For example if you wanted to attach it to every page with a certain type of form you would put `drupal_add_js()` inside of a `hook_form_FORM_ID_alter)`.

If you want it on every page all the time, you can add it to your module's .info file like so:

`scripts[] 'path/to/js/foo.js`
> 2 votes

---
Tags: 7, hooks
---


# Question
Title: How to manually make sure the database schema is right?
I updated my drupal installation to 7.7 and now it keeps giving me an alert that the database schema needs to be updated for views and google analytics. I click on it and follow the onscreen instructions and there are NO errors, and the message is still there. Can I manually make sure the schema is up to date and deactivate the warning message?

# Answer
The Schema module gives you a lot of different tools to handle your schema; for example, it checks whether your schema is in sync with your database.
> 3 votes

# Answer
Usually, what you have to do to update the database schema after core, module or theme upgrades is to call `/update.php` in your browser, as documented here:

Updating modules: Run update.php

If you use drush, you can do the same with the following command as per the drush documentation:

```
  drush updatedb

```
> 1 votes

---
Tags: 7, updating
---


# Question
Title: Is there a way to add a wrapper class to my blocks?
While views does a great job of placing blocks and content on a page, I am trying to make my website responsive. It is true that the blocks are responsive. I am just trying to make it so that the blocks take up a percentage of the screen rather than go below another block when the screen shrinks. I found a way to do this using CSS, but I would rather use standard Drupal methods so that my users can edit content. There is a nice module that lets you define a class on each block, and I am using it. I am just wondering if there is something similar so I can define a wrapper of several blocks. I am using Drupal 7.

# Answer
> 0 votes
If I understand you correctly, you can use the Theme Developer module to inspect the block itself. You will be able to take the default block template out of the main theme directory, rename it accordingly, and then edit it to have your class. This is not the best way to achieve this result, but it will work. Make sure to disable the module when you are done using it.

In addition to that, the block themselves will have their own independent ids "#block-block-17". A little more painful to work with, but if you don't have that many it could be another solution for you.

---
Tags: 7, blocks, theming
---


# Question
Title: How to attach Dropzone.js uploads to a form element
I'm integrating dropzone.js into my form, but I have an issue regarding my file uploads. I have my dropzone set up, and file uploads are in the $\_FILES array. I want to call file\_save\_upload to handle the file management, but per the code:

```
// Make sure there's an upload to process.
if (empty($_FILES['files']['name'][$form_field_name])) {
    return NULL;
}

```

it looks for the files under $\_FILES\['files'\]\['name'\]. The dropzone.js uploads my files to $\_FILES\['file'\]\['file'\].

I haven't seen an easy way to specify an input element for dropzone.js to upload to. On the Form API side, I could just mimic the functionality of file\_save\_upload(), but all the code already exists and it does a lot, and I'd hate to duplicate it.

Maybe I can copy the $\_FILES\['file'\]\['file'\] array over to $\_FILES\['files'\], then call file\_save\_upload()? I'm trying to make sure there is a better way to do it before I start hacking.

# Answer
> 1 votes
I now have the files under $\_FILES\['files'\].

My JS code:

```
(function ($) {

    Drupal.behaviors.dz = {
        attach: function (context, settings) {
            Dropzone.options.picsForm = {
                paramName: "files",
                autoProcessQueue: false,
                uploadMultiple: true,
                parallelUploads: 100,
                maxFiles: 100,

                init: function() {
                    var dz = this;
                    // #edit-next is the id of my submit button
                    this.element.querySelector("#edit-next").addEventListener("click", function(e) {
                        e.preventDefault();
                        e.stopPropagation();
                        dz.processQueue();
                    });

                }
            };

        }
      }

})(jQuery);

```

The '$form\_field\_name' parameter is a numeric index now, so I just get the count of the $\_FILES\['names'\] array and call file\_save\_upload() for each one.

---
Tags: 7, forms, javascript, files
---


# Question
Title: Template suggestion for 'content' in custom page
I need the equivalent for hook\_preprocess\_node for custom pages, which aren't nodes.

The particular page I need to theme is provided by the entity registration module 'node/10/register'. I can add theme suggestions for the page using hook\_preprocess\_page - but how to I add a theme suggestion for the actual content, so I don't have to rewrite the page.tpl.php?

Alternatively if there is an existing pattern to name the file then that would be even better.

# Answer
You need to copy the file

```
entity.tpl.php

```

from the theme directory of the module : entity.

Paste it into your theme's template directory, and rename it to

```
registration.tpl.php

```

Other theme suggestions are:

```
registration__TYPE
registration__TYPE__VIEWMODE
registration__ID

```

If you want to have access to the preprocess function then add this function to your theme's template.php file :

```
function MYTHEME_preprocess_entity(&$vars) {
  //dpm($vars);
}

```
> 0 votes

---
Tags: hooks, theming
---


# Question
Title: Can you set the directory from which the Media module populates its Library tab?
I would like to know if it is possible to set the directory from which the Media module populates its Library tab in the Media Browser.

For instance, when the newest version of the Media module is installed, the directory its Library tab is populated from seems to be `/sites/default/files/field/image/`. If another directory is already created on a server which contains a set of images I would like to choose from, is it possible to modify the Media module to look in that directory?

I've spent a fair amount of time digging through the module code and haven't found where the directory default is being set. Has anyone ever attempted this?

# Answer
> 1 votes
The Media Browser does not work with a physical path, but with the file managed table, and Drupal file system uses the uri of the file to get to the actual file.

Go to the views settings page admin/structure/views/settings and turn on 'Show the SQL query'.

Then open up the media browser and look at the SQL query. It starts of with

```
SELECT file_managed.timestamp AS file_managed_timestamp, file_managed.fid AS fid, SUM(file_usage.count) AS file_usage_count
FROM
{file_managed} file_managed

```

which means it is using the file\_managed table as its base. That comes from the file module in Core. Looking at that table definition in PHPMyAdmin for instance will reveal a fid as the primary identifier, a filename, a uri, filemime and some other fields. The uri is the important part as it tells Drupal how to get to files. The uri is prefixed by the stream wrapper (PHP classes that provide a common interface for getting to resources) and the two common Drupal ones are public:// and private://.

The media module already provides a remote internet sources wrapper, and Remote stream wrapper module provides a Remote Url plugin for the media module.

You can also write your own. Writing stream wrappers

---
Tags: media
---


title: Accessing field variables in Views 3.0

text:
# Question
Title: Accessing field variables in Views 3.0
Since the Documentation for Views 3.0 isn't out yet, does that mean that the way you access field variables is different from Views 2.0? That's because whenever I try the following code (from Views 2.0 docs: http://drupal.org/node/352970), all I get are errors:

```
<?php
    dsm(array_keys($fields));

    //ERROR message after placing it in views-view.tpl.php:
    Notice: Undefined variable: fields in include() (line 33 of D:\xampp\htdocs\foo\sites\all\themes\foofoo\views\views-view.tpl.php).
    Warning: array_keys() expects parameter 1 to be array, null given in include() (line 33 of D:\xampp\htdocs\foo\sites\all\themes\foofoo\views\views-view.tpl.php).
?>

```

In my modules I have Devel and Theme Developer enabled so why isnt it working? I also rescan my template files like a boss and clear my cache like a disease but still nothing.

# Answer
> 2 votes
Have you tried:

```
<?php
 dsm (array_keys(get_defined_vars()));
?>

```

# Answer
> 0 votes
I Drupal 7 `$fields` variable is undefined in the view template. Use $row:

```
//for id
$row->_field_data['id']['entity']->id
//for field_second_side
$row->_field_data['id']['entity']->field_second_side[LANGUAGE_NONE][0]['value']

```

Current field value is stored in `$output`.

---
Tags: 7, views
---


title: Troubleshooting a slow query

text:
# Question
Title: Troubleshooting a slow query
I've taken over a Drupal 7 website, and i'm having trouble with a slow query that is run when an editor visits the /admin/content page. The query in question is the following:

```
SELECT COUNT(*) AS expression
FROM
(SELECT DISTINCT node.nid AS nid, node.title AS node_title, history.timestamp AS history_timestamp, node.created AS node_created, node.changed AS node_changed, node.type AS node_type, users_node.name AS users_node_name, users_node.uid AS users_node_uid, node.status AS node_status, 1 AS expression
FROM
node node
LEFT JOIN users users_node ON node.uid = users_node.uid
LEFT JOIN taxonomy_index taxonomy_index ON node.nid = taxonomy_index.nid
LEFT JOIN taxonomy_term_data taxonomy_term_data_node ON taxonomy_index.tid = taxonomy_term_data_node.tid
LEFT JOIN history history ON node.nid = history.nid AND history.uid = '1') subquery;

```

Edit: I've just managed to solve this issue, but there is a more general question:

***How can a drupal 7 administrator identify the cause of errant queries to stop them from occurring?***

# Answer
To identify:

1. Install the Devel module
2. Visit admin/config/development/devel, enable the "Display query log" option.
3. At the bottom of every page you'll see a log of the queries run for the page, and what module and function has been responsible for invoking them. Run time of each query is also listed so you can see where the problems are.

As for stopping them, that will depend entirely on the individual query; whether you need it, whether the bottleneck is simply a matter of weight of data, poorly designed tables (contrib or custom, core tables are fine), not enough system resources, bad caching strategy, and so on. You'll need to profile that in the context of your web server for it to make any sense, there's no recipe for it.
> 3 votes

---
Tags: 7, database
---


# Question
Title: Rule with if statement prevents users from saving their user account
I have set up a rule that is causing some odd behaviour.

The event of the rule is: "After updating an existing account"

However the rule is preventing the user to save the data of his particular useraccount.

Allthough drupal says "The changes have been saved." non of the filled in data of the useraccount is saved.eg password etc

It looks like the second condition (If: NOT Data value is empty) is causing the bug. However i dont know what the alternative should be.

Thanks

Here my rule:

```
{
  "rules_if_oginvite_redirect_to_oghome_after_userpagesave_and_remo" : {
    "LABEL" : "If registered by mail redirect to oghome or mypage",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Redirect" ],
    "REQUIRES" : [ "rules", "rules_conditional", "php" ],
    "ON" : { "user_update" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "2" : "2", "4" : "4" } },
          "operation" : "OR"
        }
      },
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      }
    ],
    "DO" : [
      { "user_remove_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "4" : "4" } }
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is_empty" : { "data" : [ "site:current-user:og-membership--1" ] } },
            "DO" : [
              { "php_eval" : { "code" : "global $user;\r\n$uid = $user-\u003Euid;\r\n$result = db_query ( \u0022SELECT * FROM {og_membership}\r\nWHERE etid = :uid\r\nand entity_type = \u0027user\u0027\r\norder by gid DESC\u0022, array (\u0027:uid\u0027 =\u003E $uid ) );\r\n\r\n\/\/ get the results\r\nforeach ( $result as $row ) {\r\n\/\/ Do stuff with $record, which is an object\r\n$gid = $row-\u003Egid;\r\nbreak; \/\/get the latest one by breaking here\r\n}\r\n$_SESSION[\u0027ses_user_group_gid\u0027] = $gid;" } },
              { "redirect" : { "url" : "\u003C?php print \u0022node\/\u0022.$_SESSION[\u0027ses_user_group_gid\u0027];  ?\u003E" } }
            ]
          },
          { "ELSE" : [ { "redirect" : { "url" : "mypage" } } ] }
        ]
      }
    ]
  }
}

```

# Answer
As an observation I would advise against using PHP directly in a rule if it can be avoided. Much better to put your logic into a custom action and call it.

But looking at the code you supply, you should note that the user account referred to in the rule and the global current one need not be the same (an administrator may edit someone's profile, for example). You should be using the account passed in to the rule throughout, not site:current-user. Also the user update condition, IIRC, may be called when a user object is saved in other circumstances than a profile edit, so the redirect won't be appropriate.

So in order to be sure the user is editing their own profile, you should add a condition to the rule which compares the account's uid to that of the current user to make sure they are the same.
> 1 votes

---
Tags: rules
---


# Question
Title: Creating and Linking anchors using CKEditor
I am using CKEditor in my drupal 7 website. I am designed a new content type, in which I am writing about project activities in the following manner.

```
(1) Project A [anchor]
     This project describes about the design and analysis of Binary Search Tree
(2) Project B [anchor]
     This project describes about the design and analysis of Red Back Tree

```

Now, from a different page, I want to provide a link to anchors in following way-

```
The Binary Search Tree [as described here] also called an ordered or sorted binary tree.

```

I wanted to know using CKEditor-

1. How to create links (anchors) inside a page?
2. How to add these links to text on a new page?

# Answer
> 5 votes
> How to create links (anchors) inside a page?

There is an icon with a flag. You click on it and you create the anchor.

If the icon is missing, go to /admin/config/content/ckeditor , edit the respecive profile and customize the icons under section 'Editor appearance'.

> How to add these links to text on a new page?

You add a link as you would:

---
Tags: 7, wysiwyg
---


title: Commerce Donation page

text:
# Question
Title: Commerce Donation page
I want to create a button on each node to a donation page. The button needs to send the title of the node to that page, I have managed to do this.

I have a product type ***donation***. I modify the form price with line item and setup a form where you can select different donations values.

The problem is that I need to find a way to include that title in the donation form so It can be passed to cart.

I have tried commerce add to cart function to alter that, but it doesn't work.

# Answer
> 1 votes
1. Made a Product Type: Donation
2. After that I created Products of: 2 USD, 10 USD etc.
3. Created a donation page of form: `/donation/*`
4. When I reference the donation page from the node page the links look like this: `/donation/%nid`
5. On the donation page I create a custom form and there I modify the submit function.

---
Tags: commerce
---


# Question
Title: Unwanted data show after add password-comfirm
In my form I would like to add comfirm password field, the pic below show is before adding comfirm field, there is no data in waiter name field, after adding comfirm-password field there are data in waiter name field and password field, where do they come from. Anyone could please to help me to solve this problem.

```
function waiter_form($form, &$form_state= NULL) {

$form['waiter_name'] = array(
'#type' => 'textfield',
'#title' => t('Waiter Name'),
'#maxlength' => 70,
'#description' => t("You Need To Add Waiter Name. "),
'#required' => 'true'
);

$form['pass_fields'] = array(
  '#type' => 'password_confirm',
  '#description' => t('Enter the same password in both fields'),
);

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

return $form;
}

```

Screen shot of before adding confirm password field

Screen shot of after adding comfirm password field

# Answer
> 1 votes
Your browser autocomplete functionality is responsible for this.

If it's undesirable something like this should fix it:

```
$form['waiter_name'] = array(
  '#type' => 'textfield',
  '#title' => t('Waiter Name'),
  '#maxlength' => 70,
  '#description' => t("You Need To Add Waiter Name. "),
  '#required' => 'true',
  '#attributes' => array('autocomplete' => 'off'),
);

```

I would expect just adding it to the name field is enough, the browser shouldn't try to fill the password if it doesn't perceive a username.

---
Tags: forms
---


title: Render an array in Block_view

text:
# Question
Title: Render an array in Block_view
I want to render an array and print the output as Block\[content\]. There is either my Foreach or the way I use $item array or $row that is wrong. I will appreciate your help.

The result i get is the HTML I define in Block\[content\] without the values of $row-\>uri, $row-\>title, $row-\>body\_value. They are empty. And it means I have done something wrong.

```
function produkt_block_view($delta = '')
{

  $block = array();

  $list = produkt_produkliste(1);
  $items = array();
  foreach ($list as $row) {
    $items[1] = $row->uri;
    $items[2] = $row->title;
    $items[3] = $row->body_value;
  }

 switch($delta) {
  case 'produkt' :
    $block['content'] = '<a href="/19">';
    $block['content'] .= '<img class="pimg" src="'.$row->uri.'" alt="Se alle vores filter elementer her">';
    $block['content'] .= '<p class="pname">"'.$row->title.'"</p>';
    $block['content'] .= '<p>"'.$row->body_value.'"</p>';
    $block['content'] .= theme ('item_list',array('items' => $items, 'type' => 'ol',   'attribute' => 'produkt'));
    break;
  }

  return $block;
}

```

And I ended with this solution that get some results.

```
function produkt_block_view($delta = '')
{

   $query  = db_query("SELECT node.title,    field_data_field_kortbeskrivelse.field_kortbeskrivelse_value, file_managed.uri
    FROM node
    JOIN field_data_field_tilh_rsforhold ON
    node.nid = field_data_field_tilh_rsforhold.entity_id

    JOIN field_data_field_kortbeskrivelse ON
    node.nid = field_data_field_kortbeskrivelse.entity_id

    JOIN field_data_field_billede ON
    node.nid = field_data_field_billede.entity_id

    JOIN file_managed
    ON field_data_field_billede.field_billede_fid = file_managed.fid

    WHERE field_data_field_tilh_rsforhold.field_tilh_rsforhold_target_id = 30
    AND  field_data_field_billede.bundle = 'produkt_kategori'
    "

      );

    $rows   = array();
    foreach ($query as $row)
    {
        $rows[] = array(
        $row->title,
        $row->field_kortbeskrivelse_value,
        $row->uri
      );
            print_r($row->uri);

            $block['content'] = '<a href="' . url(19) . '"><img class="pimg" src=/"'.   $row->uri . '" alt="Se alle vores filter elementer her" /></a>'; // assuming that anchor tag will wrap img
            $block['content'] .= '<p class="pname">' . $row->title . '</p>';
            $block['content'] .= '<p>' . $row->field_kortbeskrivelse_value . '</p>';
            $block['content'] .= theme ('item_list',array('type' => 'ol',     'attribute' => 'produkt'));

    }

  return $block;
 }

```

# Answer
I don't think `$block['content'] = '<a href="/19">'; $block['content'] .= '<img class="pimg" src="'.$row->uri.'" alt="Se alle vores filter elementer her">';...` will work, `.` is a string(concatination) operator. You should create render array and assign it to `$block['content']`, example:

```
$array = array('#markup' => 'SOME HTML');
$block['content'] = render($array);

```

**EDIT:**

After below comments, I played a little with `hook_block_view` hook, and I found out some information about it:

* `$block[subject]` doesn't affect to its `content` even if you don't set it; `content` will be displayed without any `subject` (so, your missing `subject` doesn't cause any error here, as j.Reynolds mentioned);
* `$block['content']` can be string value and you don't need to render it, as Molot andj.Reynolds mentioned below, and you can concatinate it as many times as you want:)

So, if we return back to your snippet, you can try something like this:

```
$block['content'] = '<a href="' . url(19) . '"><img class="pimg" src="'. image_style_url('STYLE_NAME:E.G:LARGE', $row->uri) . '" alt="Se alle vores filter elementer her" /></a>'; // assuming that anchor tag will wrap img
$block['content'] .= '<p class="pname">' . $row->title . '</p>';
$block['content'] .= '<p>' . $row->body_value . '</p>';
$block['content'] .= theme ('item_list',array('items' => $items, 'type' => 'ol',   'attribute' => 'produkt'));

```

I don't know what `$row->uri` looks like in your code, but I assumed that it is something like `public://FILE_NAME.EXT`, if so you can use image\_style\_url function to generate image src..
> 0 votes

---
Tags: theming
---


# Question
Title: Want to modify drupal default pager functionality
I am creating a page with teaser of articles using views... In the Full pager, the default functionality is....

**1** 2 3 4 ... next \>

when i click next now the next number gets highlightd like...

\< prev ... 1 **2** 3 4 ... next \>

and now when i again click next...

\< prev ... 2 **3** 4 5 ... next \>

the number set gets altered...

But what i actually need is...

**1** 2 3 4 next \>

\< prev 1 **2** 3 4 next \>

\< prev 1 2 **3** 4 next \>

\< prev 1 2 3 **4** next \>

and now when i click next...

\< prev **5** 6 7 8 next \>

There are some modules like PAGERER to change the appearance of the core pager... But is there any to make this functionality or should I do some custom work...

# Answer
> 1 votes
You should be able to do this by implementing `function [THEMENAME]_pager($variables)` inside your theme. Default implementation is shown and described in `function theme_pager()` documentation.

# Answer
> 2 votes
I worked on it and found a result... actually Drupal core pager is user friendly enough but in case you need to alter it's functionality you need to edit variables in `theme_pager()` in your theme's template file.

To obtain the above functionality I altered some variables which are as follows...

```
$pager_first = (floor($pager_current / $quantity) * $quantity) + 1;

$pager_last = $pager_first + $quantity - 1;

if( $pager_current % $quantity == 0){
  $pager_first = $pager_current - $quantity +1;
  $pager_last = $pager_first + $quantity - 1;
}

```

I neglected `$page_middle` variable since I did not needed it...

Warning: Do this when its absolutely necessary...

---
Tags: views, 7, paging
---


# Question
Title: How to add new blocks when "The block X was assigned to the invalid region Y and has been disabled"
I have inherited a site (in Drupal 6) and the original developers are completely out of the picture. I need to add a block but it looks like they've customized things and blocks are being rendered in a way other than assigning them to block regions as per the default.

I get a lot of warnings to the effect of `The block X was assigned to the invalid region Y and has been disabled` but those blocks still appear on the site. So they must be being brought in another way. I am not too terribly worried about the warnings (so seeing this discussion is not really what I need: https://drupal.org/node/1172560). I am more concerned that it is taking me hours to add a link and image to the homepage.

I see that the previous developers installed the `Nodeblock` and `Nodeblock Auto` modules and the nodes that come in have html ids like: `block-nodeblockauto-node_<NID>` so I imagine this is how they are being brought in.

But I don't see any options in the admin panel for configuring nodes any further than what I am used to from the default. In looking through the template files for the custom theme, I also do not see where these are being brought in.

Note: I am not in a position to migrate to Drupal 7 so I have to keep things in Drupal 6 for now.

# Answer
In D7 I finally got rid of that message by placing an `if ($theme == variable_get('theme_default', '0'))` around the region assignment. So the block *only* gets assigned to my (default) frontend theme which actually contains the region the block is assigned to.

```
function MYMODULE_block_info_alter(&$blocks, $theme, $code_blocks) {
  if ($theme == variable_get('theme_default', '0')) {
        if (isset($blocks['MYMODULE']['MYMODULE_block'])) {
            $blocks['MYMODULE']['MYMODULE_block']['status'] = 1;
            $blocks['MYMODULE']['MYMODULE_block']['region'] = 'header';
            $blocks['MYMODULE']['MYMODULE_block']['weight'] = 2;
            $blocks['MYMODULE']['MYMODULE_block']['visibility'] = BLOCK_VISIBILITY_NOTLISTED;
        }
    }
}

```
> 3 votes

---
Tags: 6, theming, blocks, nodes
---


# Question
Title: template.php function for adding field CSS classes
I'm using Drupal 7 with Bootstrap. I copied the sub-theme and renamed all the files accordingly and everything works fine, however I'm having problems with my sub-theme's `template.php` not doing what it should.

I am trying to add specific CSS classes to my form field while editing the form or adding new content. I tried following http://atendesigngroup.com/blog/adding-css-classes-fields-drupal, but I can't change the field's classses.

This is the code I have in template.php.

```
/**
 * Overrides theme_field()
 * Remove the hard coded classes so we can add them in preprocess functions.
 */

function MojCrm_field($variables) {
  $output = '';

  // Render the label, if it's not hidden.
  if (!$variables['label_hidden']) {
    $output .= '<div ' . $variables['title_attributes'] . '>' . $variables['label'] . ': </div>';
  }

  // Render the items.
  $output .= '<div ' . $variables['content_attributes'] . '>';
  foreach ($variables['items'] as $delta => $item) {
    $output .= '<div ' . $variables['item_attributes'][$delta] . '>' . drupal_render($item) . '</div>';
  }
  $output .= '</div>';

  // Render the top-level DIV.
  $output = '<div class="' . $variables['classes'] . '"' . $variables['attributes'] . '>' . $output . '</div>';

  return $output;
}

/**
 * Implements hook_preprocess_field()
 */

function MojCrm_preprocess_field(&$vars) {
  /* Set shortcut variables. Hooray for less typing! */
  $name = $vars['element']['#field_name'];
  $bundle = $vars['element']['#bundle'];
  $mode = $vars['element']['#view_mode'];
  $classes = &$vars['classes_array'];
  $title_classes = &$vars['title_attributes_array']['class'];
  $content_classes = &$vars['content_attributes_array']['class'];
  $item_classes = array();

  /* Global field classes */
  $classes[] = 'field-wrapper';
  $title_classes[] = 'field-label';
  $content_classes[] = 'field-items';
  $item_classes[] = 'field-item';

  /* Add specific classes to targeted fields */

  switch ($name) {
    case 'field_baza_direktor':
      $title_classes[] = 'inline';
      $content_classes[] = 'col-sm-6';
      break;
  }

}

```

# Answer
> 1 votes
Using `yourtheme_preprocess_field()` won't work for forms because `theme_field()` isn't called. Instead, `theme_form_element()` is executed, which builds the form element wrapper. If you want to use/override the input itself override the corresponding theme function, e.g. `theme_textfield()` and so on.

Another way could be using `hook_form_alter()`/`hook_FORMID_form_alter()` if you want to override the attributes for a specific form only.

---
Tags: theming, forms
---


# Question
Title: Static page on main domain and Drupal on subdomain
In my installation, I'm utilizing Drupal's awesome capability to run on multiple subdomains using one code base. Each subdomain has its own database. So, I only need to have a static page on the main domain (root) but Drupal running on subdomains.

How do I do that? I know that I could modify the .htaccess file to make it look up for index.html first, but that would affect the subdomains.

Thanks.

# Answer
You can solve this one using a RewriteRule in your .htaccess file. What you basically will do is check if the request is destined for your main domain (both with and without the www), and if so, tell Apache to go fetch the files from somewhere else. All this is done on the server-side, so the browser doesn't see a thing about this.

For the example below, I assume that Drupal is installed in /var/www. If it's installed somewhere else, update all occurrences of /var/www below.

1. Create a new directory /var/www/static\_main\_domain. This directory will contain the static content of your main domain.
2. Add the following lines of code to your .htaccess file (preferably immediately behind the RewriteEngine On):

`# Check if the request is destined for www.yourdomain.com OR
 RewriteCond %{HTTP_HOST} ^www\.yourdomain\.com [NC,OR]
 # Check if the request is destined for yourdomain.com
 RewriteCond %{HTTP_HOST} ^yourdomain\.com [NC]
 # If so, go get the requested files from the static_main_domain subdirectory.
 RewriteRule ^(.*)$ static_main_domain/$1 [L,QSA]`

For more info, check this: http://httpd.apache.org/docs/current/mod/mod\_rewrite.html
> 1 votes

# Answer
Most solid way is to change configuration of your web server. Something like:

```
<VirtualHost *:80>
  DocumentRoot /var/www/static_page
  ServerName example.com
</VirtualHost>

<VirtualHost *:80>
  DocumentRoot /var/www/drupal_multisite
  ServerName other.example.com
  ServerAlias *.example.com
</VirtualHost>

```

See Virtualhost For Wildcard Subdomain and Static Subdomain for more server-oriented answers.
> 0 votes

---
Tags: subsites
---


title: Get orders with free items

text:
# Question
Title: Get orders with free items
I have a pricing rule to do some items free. User can purchase only 3 items per month.

Question is how to programmatically get count of free items purchased by user?

# Answer
I needed to do something vaguely similar the other day and the only way I could find was to go into the db tables directly to grab the data. The problem is you need to join the line item and orders tables (for the order status), which you can't do with (for example) an `EntityFieldQuery`.

I think you'd be looking for a query simliar to:

```
SELECT SUM(li.quantity)
FROM {commerce_order} o
INNER JOIN commerce_line_item li ON li.order_id = o.order_id
WHERE o.status = :status
AND li.line_item_label = :sku
AND order.uid = :uid

```

But it'll probably need some tweaking for your needs (to get results for orders created between certain dates for example).
> 1 votes

# Answer
I got it working by making the rule for payment to be above $0. It was difficult getting to the answer because they don't explain the steps, but here's my steps if you want to accomplish this:

> Go to Store\>Configuration\>Payment Methods and "edit" your Payment method, in my store I had to edit Paypal WPS. Add a condition for the payment under "Conditions" and select "Price Comparison" . The "Operator" I selected was '\>=' and I had to select $1 under "Second Price" because it didn't want to take $0 . And save your rule...then it should work although this rule is in effect catered for any products that are cheaper than $1
> 0 votes

# Answer
You may check the following function:

```
/**
 * Count number of user purchased free products.
 */
function foo_count_free_products($uid = NULL, $type = 'trial') {
  // Initialize the variables.
  empty($uid) && $uid = $GLOBALS['user']->uid; // If empty, set to currently logged user id.

  $orders = commerce_order_load_multiple(array(), array('status' => 'completed', 'uid' => $uid)) + commerce_order_load_multiple(array(), array('status' => 'invoiced', 'uid' => $uid));
  $product_ids = array();
  foreach ($orders as $order) {
    foreach (entity_metadata_wrapper('commerce_order', $order)->commerce_line_items as $delta => $line_item_wrapper) {
      if (in_array($line_item_wrapper->type->value(), commerce_product_line_item_types())) {
        $line_item_wrapper->commerce_product->type->value() == $trial &&
          $product_ids[] = $line_item_wrapper->commerce_product->raw();
      }
    }

  }
  return count($product_ids);
}

```

Where 'trial' is the type of your free product, if you're using special product type for it. Otherwise, you can count all the products with zero price. You can modify this function to use with the rules.

---

Or you can use the direct SQL query, some suggestion:

```
  $result = db_query("
    SELECT
      O.order_id,
      O.created AS order_created,
      O.status AS order_status,
      (O.status NOT IN ('checkout_complete', 'pending', 'completed', 'invoiced')) AS order_in_cart,
      CP.commerce_product_product_id AS product_id,
      P.sku,
      P.`type`,
      P.title,
      SEP.commerce_subscription_end_period_interval AS length_interval,
      SEP.commerce_subscription_end_period_period AS length_period,
      CAST(O.data AS char(4096)) AS data
    FROM {commerce_order} O
    LEFT JOIN {commerce_line_item} LI ON LI.order_id = O.order_id
    LEFT JOIN {field_data_commerce_product} CP ON CP.entity_type = 'commerce_line_item' AND CP.entity_id = LI.line_item_id
    LEFT JOIN {commerce_product} P ON P.product_id = CP.commerce_product_product_id
    LEFT JOIN {field_data_commerce_subscription_end_period} SEP ON SEP.entity_type = 'commerce_product' AND SEP.entity_id = P.product_id
    WHERE O.uid = :uid AND (P.`type` IN (:subscription_types))
      AND (:search_in_cart OR O.status IN ('checkout_complete', 'pending', 'completed', 'invoiced'))
      AND product_id IS NOT NULL
    ORDER BY order_created ASC, O.order_id ASC
  ", array(
    ':uid' => $uid,
    ':subscription_types' => array('foo'),
    ':search_in_cart' => ($flags & FOO_WEBSTORE_GET_USER_PRODUCTS_CART) ? TRUE : FALSE,
  ))
  ->fetchAll();

```
> 0 votes

---
Tags: commerce
---


title: Drupal page other than main

text:
# Question
Title: Drupal page other than main
It mightbe a lame question but I want to be able to display a custom page let say: "/news".

So, I created a template named: page--news.tpl.php with my content, some rendered views etc. Now when I got to this address, I can see my requested content however there are two problems: \- title of the page is "Page not found" \- the search form does not work.

Could anyone explain what is going on? I am on Drupal 7.

BTW. My template contain some html and this section to embed another view:

```
        <div class="col-md-8">
            <div class="panel panel-primary">
                <div class="panel-heading">
                    <h1 class="panel-title">News</h1>
                </div>
                <div class="panel-body">
                        <?php echo views_embed_view('news_view_block_more', $display_id = 'block'); ?>
                </div>
            </div>
       </div>

```

Thank you

# Answer
> 0 votes
If you have created a node, for instance a "Page" node, by going to "Content" =\> "Add Content", AND have the Path or Pathauto module enabled, you can give that node the path "news" when you are editing it. Alternately, you can create a view that is a page, and has that path.

Specifically, the Drupal menu router has to have an entry for the path "news", and know what to serve up. Blocks and templates don't create that path entry.

More information on creating content can be found at: https://www.drupal.org/node/120635

# Answer
> 0 votes
Have you tried taking a look at page-manager with a view for example? Or is the content you are trying to display so specific that this is not possible?

---
Tags: 7
---


# Question
Title: How do I find what content is supplying my current page?
I have a webpage on my site that doesn't have edit tabs, so I am not sure where this website is retrieving content. How can I find out what content represents this webpage? I am using Drupal 7.

# Answer
Take a look if you can see the contextual "settings wheel" in the top right corner. This can provide you with a direct link to edit the "page"/"view" or Panel that you are on
> 0 votes

---
Tags: nodes
---


# Question
Title: Is it possible to divide a field into fields?
I think this is impossible. However, is it possible to change a field into fields on Drupal 7? I have a content type of author. We used the "Title" field for user full name with their title. Is it possible to change it to "First Name", "Middle Name", "Last Name", and "Title" fields?

# Answer
It's definitely possible, but will require some coding. I can't work out the whole thing for you but I can point you in a direction.

You would have to create three new fields for 'first name', 'last name' and 'title' in the content type.

Then create a script that loads all of the nodes of that type with node\_load\_multiple then iterates through them, taking the old value of 'title' and splitting it using regex or the php 'explode' string function. Then using entity\_metadata\_wrapper, stick the individual values into the new fields and save the node.

Using drush, you can run the script like this: drush php-script scriptname.php
> 2 votes

# Answer
You might use Field Collection. It provides fieldable entities that, themselves, can be added to other fieldable entities.
> 0 votes

# Answer
There's no way to do this without some coding, as far as I can see. Work with the following assumptions:You know that there is always 3 or 4 elements, and in the case where there is 3 elements, the missing element is always the middle name. So load the node, get the value of the old field, explode it into an array, count the number of elements and if it's 3, then insert an empty element at array\[1\]. Then you have an array with 0 =\> First, 1 =\> Middle, 2 =\> Last, 3 =\> Title. Now use entity\_metadata\_wrapper to insert the individual array elements into the new fields. 0 into First Name, 1 into Middle Name (regardless of if it's empty or not), 2 into Last Name, and 3 into Title. Once you have the new fields populated, delete the old field from the content type, and use display rules or theming to decide when to display the Middle Name field, based on whether or not it has content. Something like that should work.
> 0 votes

---
Tags: entities
---


# Question
Title: Is there a robust, free module for SE-style social signup?
I want to enable users to create accounts using existing Google, Facebook etc accounts, without needing to come up with and remember yet another password. Similar to how the StackExchange network does.

There's a proliferation of modules that have related features to these. I'd like to know if there's any one of them which has proven to be stable, robust, simple (requiring few dependencies or possible points of failure) and working without requiring paid subscriptions.

---

**Some modules I've looked at:**

* I've seen many recommendations for Janrain Social Login, but I read that it's a paid-for service. This site is a very small project and that's beyond its scope. The demos I've seen also suggest that it removes the ability to create a Drupal-only account should the user want to.
* I tried the built-in OpenID module plus OpenID Connect, but discovered that it only supports log in, not sign up.
* There's a stack of modules built around OAuth (e.g. OAuth Connector). I gather that OAuth is a different protocol to OpenID, and requires dependencies to be installed on the server. In terms of functionality I haven't yet figured out what the fundamental difference is between the OAuth stack and Drupal's built-in OpenId stack, and I can't find any confirmation in the various docs available that it does indeed support signups. It has all the hallmarks of a serious project, though.
* There's the connector module \- I think this an API module used by the OAuth stack?
* Hybrid Auth looks really promising and is **my current front-runner**: it explicitly supports signup and login, and has minimal dependencies (one open-source library, `php-curl`, and ctools), and is under active development with a stable D7 release. Sounds great, but I've not seen many recommendations for it, so I'm wondering if there's something I've overlooked.
* There's Gigya, which looks like a 3rd-party service with fancy social features that aren't relevant in my case.
* There's OneAll social login, which has a promising-sounding description but doesn't appear to be widely used.
* There's Social Connect, but it seems to be Facebook only.
* ...and loads more, including many more 3rd party services and modules for specific providers.

I'd appreciate any expert advice from experience on the simplest stable way to get a sign up screen similar to this:

# Answer
I used Hybrid Auth . It works well. I tried anothers. They were not so good. Yes, Hybrid Auth does not have another functionality to share content. But It should not have it. It uses the separated library. It does not use third party services. It's free and independent.

If you tell me your successful experience with another libraries I will be pleased.
> 2 votes

---
Tags: 7, authentication-authorization
---


# Question
Title: Image-clicking Q&A captcha alternative that is customisable?
I'm looking for a simple way to spam-proof new user registration that works along the lines of Confident Captcha (demo, module page).

These work by asking a simple question, then the user clicks on the appropriate image. Very easy for humans, very difficult for bots.

My problem with the Confident Captcha system, however, is that it relies on a 3rd party plugin which isn't customisable. I want to be able to set the questions, images and widget display to match the content and theme of my site.

---

Note: I'm aware that this approach has accessibility issues for blind or partially sited users. For my project, this can be dealt with manually and isn't an issue, but bonus points for options that have a built-in accessible alternative.

Also, bonus points for options that don't depend on a 3rd-party service.

---

One related module worth mentioning:

* Captcha Questions \- totally customisable, but appears to be text only requiring users to do more typing.

# Answer
Here's one option I've found - Fancy captcha \- based on a library which uses icons. Looks like a simpler stack than Confident Captcha, but no stable release on D7.

Pros:

* Based on a re-purposed library installed locally, so you can modify the files
* Doesn't require a third-party service

Cons:

* No stable non-dev release yet (at time of posting)
* I can't see any evidence of an accessible fallback for screen readers etc
> 0 votes

---
Tags: captcha
---


# Question
Title: problems with CKEditor install in drupal 7
I have installed CKEditor correctly and still get the error:

> The CKEditor component is not installed correctly. Please go to the CKEditor homepage in order to download the latest version. After that you must extract the files to the sites/all/modules/ckeditor/ckeditor or sites/all/libraries/ckeditor directory and make sure that the sites/all/modules/ckeditor/ckeditor/ckeditor.js or sites/all/libraries/ckeditor/ckeditor.js file exists. Refer to the README.txt file for more information.

I have downloaded and re-downloaded CKEditor several times. Everything is there but still getting error.

I am also confused about exactly what to put in the CKEditor global profile.

# Answer
It's an issue that happens from time to time.

The instructions that you see are fine:

> Extract the archive and copy its contents into a new folder in the following location: sites/all/libraries/ckeditor
>
> So the actual library can be found at: sites/all/libraries/ckeditor/ckeditor.js

If the issue is caused by the message "The version of CKEditor could not be detected." at admin/config/content/wysiwyg.

This solution helped me yesterday:

1. Open "\sites\all\libraries\ckeditor\ckeditor.js" file in a text editor.
2. Add in the first line of the ckeditor.js file:

// version:'4.4.4',revision:'4391'

and save it.

You can get more help about this module on the documentation page.
> 4 votes

# Answer
I had the same problem and found a solution at https://drupal.org/node/1161738#comment-7857451.

> In the file: .../modules/wysiwyg/editors/ckeditor.inc at about line 81
>
> replace

```
if (preg_match('@version:\'(?:CKEditor
> )?([\d\.]+)(?:.+revision:\'([\d]+))?@', $line, $version)) {

```

> with

```
if (preg_match('@version:[\'"](?:CKEditor
> )?([\d\.]+)(?:.+revision:[\'"]([\w]+))?@', $line, $version)) {

```
> 2 votes

# Answer
Have you moved the files to sites/all/libraries/ckeditor or sites/all/modules/ckeditor/ckeditor and tried clearing your cache by going to /admin/config/development/performance and selecting clear caches? I know that is redudant with the error message. The global profile doesn't normally need changes, it's really the 'advanced' and 'full' profiles that do, these are where you select what kind of buttons you want etc etc.
> 0 votes

---
Tags: 7, wysiwyg
---


title: Get the nid of a node

text:
# Question
Title: Get the nid of a node
As you know drupal has a function " node\_type\_get\_types " that we can use to get the type of the node, so is there also a function that we can use to get the nid of the current node that we are viewing?

# Answer
it's just a property of the `Node` itself, the `nid` of the node. It is the value `$node->nid`.

EDIT

There is also entity\_extract\_ids() which is 1 level up from a `Node` in the object hierarchy and this function interacts with `Entities` -- if you're trying to do something more generic than merely interact with solely `Nodes` ... such as a process a `Queue` of `Entity` objects all of different types but sharing a `field` you want set with a certain value.

> Helper function to extract id, vid, and bundle name from an entity.
>
> **Parameters**
>
> $entity\_type: The entity type; e.g. 'node' or 'user'.
>
> $entity: The entity from which to extract values.
>
> **Return value**
>
> A numerically indexed array (not a hash table) containing these elements:
>
> 0: Primary ID of the entity.
>
> 1: Revision ID of the entity, or NULL if $entity\_type is not versioned.
>
> 2: Bundle name of the entity, or NULL if $entity\_type has no bundles.
> 1 votes

# Answer
A little NID trick... (if this is what your talking about)

Go to your Content Manager page and hover over the Edit link on the node. Look down at the bottom of your browser (bottom-left for chrome) and you'll see the NID listed within the url that appears there.
> 0 votes

---
Tags: views
---


# Question
Title: views_query_alter change to operator OR for contextual filters and normal filters
My question is rather simple and I have searched quite a bit for the answer with no result. My view produces below SQL (simplified):

```
SELECT stuff
FROM
tableA
LEFT JOIN tableB
LEFT JOIN tableC ON stuff
WHERE (( (MY_CONTEXTUAL_FILTER = '5' ) )AND(( (MY_NORMAL_FILTER IS NULL ) )))

```

All I want to do is to change that AND between the contextual filter and normal filter. I have tried to change all ANDs (including `set_group_operator()`) to OR and it does not change my AND.

Also need to mention it is an 'Entity Reference' display which I am trying to achieve the above on. Views version 7.x-3.7.

**UPDATE**

In order to achieve the above, I also tried `hook_views_pre_execute()` as below:

```
 $old_query = (string)$view->query->query();
 $new_query = str_replace('AND', 'OR', $old_query);
 $view->build_info['query']=$new_query;

```

But that doesn't work and throws and error. I know they are different approaches with different issues but both are trying to solve one problem.

# Answer
> 2 votes
As a simple try to help, did you implement `hook_views_query_alter(&$view, &$query)` as following ?

First, call *Views API* in `YOUR_MODULE.module` :

```
/**
 * Implementation of hook_views_api().
 */
function YOUR_MODULE_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'YOUR_MODULE_NAME'),
  );
}

```

Create a file `YOUR_MODULE.views.inc`. It seems that with Views, you don't need to put `files[] = YOUR_MODULE.views.inc` in your module's .info file, as you usually would.

Then implement hook\_views\_query\_alter() in `views.inc`.

```
function YOUR_MODULE_views_query_alter(&$view, &$query) {

  if($view->name == 'VIEW_NAME') {

    dpm($query);
    //at this point find the right part to alter and adapt following line
    $query->where[0]['type'] = 'OR';

  }
}

```

**EDIT:** If for any reason, you can't override the View with `hook_views_query_alter()`, Views Filter Harmonizer might fit your need.

> Views Filter Harmonizer solves an operational foible with the Views module regarding filtering. This small module allows you to have a contextual filter argument apply only when there is no corresponding regular (exposed) filter value present.

Last, **check also Views arguments in filters sandbox**, or test this patch. Both rely on the same logic, setting a "*Global: Null*" contextual filters and using it in regular filters. Many people report using it to solve the same *And/Or* contextual filters issue. Good luck !

# Answer
> 1 votes
Download and install the module Views arguments in filters. It is a sandbox module so you will have to use git.

In your view, remove your contextual filter and replace it with a global null contextual filter.

Then add the filter that you want as the contextual filter to the normal filter area in views, and in its value argument set the value as %1 (ie you are ferencing the global null contextual filter).

Now rearrange the filter and-or groups to your liking.

---
Tags: views, database
---


# Question
Title: What is the value of $page['content'] in custom front page?
I'm a Drupal noob and inherited a Drupal website to maintain. The site has a custom theme, which includes a "page--front.tpl.php" that Drupal loads as the front page. Within this script, there is the following call:

```
<?php print render($page['content']); ?>

```

This call used to display homepage-view.tpl.php (found under themes//), but I upgraded some modules and changed some settings in an attempt to fix some problems and now it appears to be showing all nodes, (there is a pager for /node?page=X in the section rendered by that print statement).

My guess is that $page\['content'\] is returning /node. Either /node pointed to homepage--view.tpl.php before or $page\['content'\] returned the value of homepage--view.tpl.php. Either way, how can I get the old behavior back?

Thanks in advance.

# Answer
$page\[content\] returns the content for the current page, whatever that may be. If a view is set at the content, it would return the view, or a node, or a block in the content region or anything else set to show in that region, either through the UI or programmatically. It returns rendered html for all elements in that region.

Chances are under blocks, that view? is no longer listed to render in the main content region as a result of whatever setting changes you made.

If it's a view and set as a block you can modify it under the blocks page, block configuration to show in the region.
> 0 votes

---
Tags: theming
---


# Question
Title: Content Type: Is it possible to have Term reference on Parent Term instead of Vocabulary?
I have many Parent Terms with child terms on a Vocabulary. I wanna use one of the parent terms on a content type as option. Is it possible to have a Term Reference field on a Parent Term instead of a Vocabulary?

# Answer
> 1 votes
Create a view that show the taxonomy terms that you want to have as options for selection (you will have to manipulate depth).

Then you create an Entity reference field on your content type that references a taxonomy term. When you add the field it will ask for Entity Selection mode. You select Views (the alternative is Simple), and then you select the view that you created above.

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


# Question
Title: drush omega-guard and missing or unreadable gemfiles
My machine is running Archlinux and and I am new in drush and omega theme. I have installed drush and then run bundle install to install the dependencies of my subtheme. When I run drush omega-guard, I get some errors which says the file to import not found or unreadable, while I have installed those gems too.

```
[timmy@MyPC drupal-7.31]$ drush omega-guard
Which theme do you want to run Guard for?
 [0]  :  Cancel
 [1]  :  First (Subtheme of Omega) - My first theme.
 [2]  :  Ohm (Subtheme of Omega) - Omega based demonstration theme. Serves as a best-practice reference for the Omega documentation. Ohm
         will be constantly updated as best practice evolves so shouldnt be used in production.
 [3]  :  Omega - A powerful HTML5 base theme framework utilizing tools like Sass, Compass, Grunt, Bower, Ruby Version Manager, Bundler and
         more.
1
/home/timmy/.gem/ruby/2.1.0/gems/bundler-1.7.2/lib/bundler/runtime.rb:222: warning: Insecure world writable dir /home/timmy in PATH, mode 040777
/home/timmy/.gem/ruby/2.1.0/gems/bundler-1.7.2/lib/bundler/runtime.rb:222: warning: Insecure world writable dir /home/timmy in PATH, mode 040777
/home/timmy/.gem/ruby/2.1.0/gems/bundler-1.7.2/lib/bundler/runtime.rb:222: warning: Insecure world writable dir /home/timmy in PATH, mode 040777
    error sass/first.no-query.scss (Line 3 of sass/first.styles.scss: File to import not found or unreadable: breakpoint.
Load paths:
  /srv/http/drupal-7.31/sites/all/themes/first/sass
  Compass::SpriteImporter
  /srv/http/drupal-7.31/sites/all/themes/first/sass
  /usr/lib/ruby/gems/2.1.0/gems/compass-core-1.0.1/stylesheets
  /usr/lib/ruby/gems/2.1.0/gems/susy-2.1.3/sass
  /usr/lib/ruby/gems/2.1.0/gems/compass-normalize-1.5/stylesheets
  /usr/lib/ruby/gems/2.1.0/gems/compass-rgbapng-0.2.1/lib/stylesheets
  /usr/lib/ruby/gems/2.1.0/gems/toolkit-2.6.0/stylesheets
  Sass::Globbing::Importer)
    error sass/first.normalize.scss (Line 8: File to import not found or unreadable: toolkit/border-box.
Load paths:
  /srv/http/drupal-7.31/sites/all/themes/first/sass
  Compass::SpriteImporter
  /srv/http/drupal-7.31/sites/all/themes/first/sass
  /usr/lib/ruby/gems/2.1.0/gems/compass-core-1.0.1/stylesheets
  /usr/lib/ruby/gems/2.1.0/gems/susy-2.1.3/sass
  /usr/lib/ruby/gems/2.1.0/gems/compass-normalize-1.5/stylesheets
  /usr/lib/ruby/gems/2.1.0/gems/compass-rgbapng-0.2.1/lib/stylesheets
  /usr/lib/ruby/gems/2.1.0/gems/toolkit-2.6.0/stylesheets
  Sass::Globbing::Importer)
    error sass/first.styles.scss (Line 3: File to import not found or unreadable: breakpoint.
Load paths:
  /srv/http/drupal-7.31/sites/all/themes/first/sass
  Compass::SpriteImporter
  /srv/http/drupal-7.31/sites/all/themes/first/sass
  /usr/lib/ruby/gems/2.1.0/gems/compass-core-1.0.1/stylesheets
  /usr/lib/ruby/gems/2.1.0/gems/susy-2.1.3/sass
  /usr/lib/ruby/gems/2.1.0/gems/compass-normalize-1.5/stylesheets
  /usr/lib/ruby/gems/2.1.0/gems/compass-rgbapng-0.2.1/lib/stylesheets
  /usr/lib/ruby/gems/2.1.0/gems/toolkit-2.6.0/stylesheets
  Sass::Globbing::Importer)
Compilation failed in 3 files.

07:11:22 - INFO - Guard::Compass is waiting to compile your stylesheets.
07:11:22 - INFO - LiveReload is waiting for a browser to connect.
07:11:22 - INFO - Guard is now watching at '/srv/http/drupal-7.31/sites/all/themes/first'
[1] guard(main)> help

```

# Answer
> 1 votes
Found the answer. here is the solution: https://www.drupal.org/node/2323235#comment-9069731

---
Tags: drush, theming
---