# Question
Title: Completing commerce order triggering other modules rules checkout complete
i've coded a checkout complete but aint triggering other modules checkout complete rules, i'm assuming commerce\_checkout\_complete($order-\>order\_id); will do this.

The most important thing for me is that, the items on the cart are files, hence i have commerce licence that grant license to each files which is not triggered by the code below. Any tips on how to do this please?

Thank you very much.

```
<?php
    function custom_module_complete_order($order_id) {

     $order = commerce_order_load($order_id);

     commerce_order_status_update($order, 'checkout_checkout');

      $payment_method = commerce_payment_method_instance_load('commerce_payment_example|commerce_payment_commerce_payment_example');

      $transaction = commerce_payment_transaction_new('commerce_payment_example', $order->order_id);
      $transaction->instance_id = $payment_method['instance_id'];
      $transaction->amount = $order->commerce_order_total['und'][0]['amount'];
      $transaction->currency_code = $order->commerce_order_total['und'][0]['currency_code'];
      $transaction->status = COMMERCE_PAYMENT_STATUS_SUCCESS;
      $transaction->message = 'Name: @name';
      $transaction->message_variables = array('@name' => 'Commerce Cartmaker Payment');

      commerce_payment_transaction_save($transaction);
      commerce_payment_commerce_payment_transaction_insert($transaction);

     commerce_order_save($order);
     commerce_checkout_complete($order->order_id);
}
?>

```

# Answer
Updating to checkout\_complete status, make the code works. Thanks.

```
+     $order = commerce_order_status_update($order, 'checkout_complete');
      commerce_order_save($order);
      commerce_checkout_complete($order->order_id);

```
> 1 votes

# Answer
Axscode's answer will probably work (untested but I believe in you axscode ;) ) But to eleborate. Like alter hooks, rules events are called via code. Possibly after all hooks have finished running (this is how it works for the product add form for example). Snippet:

```
  // Allow modules to prepare this as necessary. This hook is defined by the
  // Product Pricing module.
  drupal_alter('commerce_product_calculate_sell_price_line_item', $line_item);

  // Process the unit price through Rules so it reflects the user's actual
  // purchase price.
  rules_invoke_event('commerce_product_calculate_sell_price', $line_item);

```

So to make it work you'll have to call the rules even manually via something like `rules_invoke_event('commerce_product_calculate_sell_price', $line_item);` you'll have to dig trough commerce code for the right rules event.
> 0 votes

---
Tags: commerce
---


# Question
Title: Trigger a JS function only if the view has no more results. or is empty?
Hi this might be a stupid question but i can't seem to work it out.

I'm using 'views ajax get', 'views load more (with waypoints)' and what i'm trying to achieve is to only display the footer when the last page of the view has been loaded and appended to the page. and if the view returns no results (using exposed filters)

I've attempted to use jquery's .ajaxSuccess() but i cant work out how to count the results or even to locate the variable with results. Do i have to search the responseJSON for results

What is the best way to do this? is there some Drupal specific structure i need to know about?

Thank in advance :D

# Answer
All you have to do is check if the "load more" div does not exist. (check if the load more button is no longer there).

```
(function ($) {
    $(document).ajaxComplete(function() {
               if ($(".loadmore").length = 0){
                   // do something here
               }
    });

})(jQuery);

```

**Check the actual name of the load more div, I just made it up for this example**
> 0 votes

---
Tags: views, javascript, ajax
---


# Question
Title: Adding text before and after cart contents block in Drupal 7 commerce
I need to add some text above and below the Cart Contents block at the top of the checkout form. I tried just editing the view and adding a header and footer to that view but no dice, it doesn't work (it shows in the View preview but not in the view results when saved).

So I'm looking for the page--checkout.tpl.php form and I can't find it anywhere. Does anyone know where I can find this template?

# Answer
The easiest way to do this, for me, is by code, as checkout pages are normal Drupal forms and as such, we can use hook\_form\_alter() to do whatever we need. In this case, you can use

```
(yourmoduleorthemename)_form_commerce_checkout_form_checkout_alter (&$form, &$form_state)

```

And inside it, you can use Form API(https://api.drupal.org/api/drupal/developer%21topics%21forms\_api\_reference.html/7#markup-attribute) to change the way you want.

You can also create a block and put on the "checkout/%/\*", but it generates a lot of extra markup for almost nothing.

I believe you can solve your problem with one of these, but let me know if you need more details.
> 2 votes

---
Tags: commerce
---


# Question
Title: How can a text field be re-sized by touch and drag with finger in Smartphone devices
Hello Drupal Masters,

I have used Bootstrap template for my Drupal 7 website. When in Smartphone devices such as iPhone or Samsung phones, i tried to touch the screen using my finger to drag to resize the text field vertically (see screenshot) larger, so the text field could display all text simultaneously.

Whatever i do, I can't re-size the text field when using my finger. It works only with a mouse.

Does anyone know to make the field realizable in touch mode using fingers?

Thank you very much in advance for you tips & Tricks.

Regards Kim

# Answer
> 1 votes
You might need to implement a custom module that just loads a library similar to this one:

http://interactjs.io/

Scroll down to the resizing section and then check out the demo. You could presumably do this for your input fields.

---
Tags: theming
---


# Question
Title: Drupal 7 Ajax GET - Error 400 (Hook_menu)
I am trying to send an array back to Drupal to save in a database table. I'm getting an error 400 though when inspecting in the console and the url seems correct:

> GET http://localhost/audiophreak/callback/%?\[1,2,3,4,5,6,45,46,47\] 400 (Bad Request)

Here is my hook\_menu:

```
/**
* Implementation of hook_menu().
*/
function my_db_module_menu() {
  $items['callback/%?'] = array(
    'title' => 'My callback',
    'description' => 'Desc',
    'page callback' => 'mymodule_getinfo',
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content'),
    'page arguments' => array(1),
  );
  return $items;
}

```

Here is my callback:

```
/**
 * My callback
 */
function mymodule_getinfo($data) {

echo drupal_json_decode($data);

  // //Parse the data and input it into the database
  // $result = db_insert('my_db')
  // ->fields(array(
    // 'nid' => $data->node,
    // 'uid' => $data->user,
    // 'progress' => $data->progress,
  // ))
  // ->execute();
}

```

And here is my AJAX

```
//Data
    var post = plnzVideoTracker.progress

    //Begin Ajax
    $.ajax({
          url: '/audiophreak/callback/%',
          contentType: "application/json; charset=utf-8",
          type: 'GET',
          dataType: 'json',
          data: JSON.stringify(post),
          success: function(data) {
            if(data == "success")
            {
            $('.status').attr("innerHTML","<font color='green'>Name submitted successfully!</font>");
            }
            else
            {
              $('.status').attr("innerHTML","<font color='red'>Name submit failed!</font>");
            }
            },
            beforeSend: function() {
              $(document).ready(function () {
              $('.status').attr("innerHTML","Loading....");
            });
            },
            'error': function(data) {
              $(document).ready(function () {
              $('.status').attr("innerHTML","ERROR OCCURRED!");
            });
          }
     });

```

plnzVideoTracker.progress is an array inside of an object literal if that has anything to do with it?

# Answer
The `%` symbol is type of placeholder in hook\_menu item. You can read more about it here: https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook\_menu/7#sec\_path\_wildcards.

For you example I suggest to use the following:

```
function my_db_module_menu() {
  $items['callback'] = array(
    'title' => 'My callback',
    'description' => 'Desc',
    'page callback' => 'mymodule_getinfo',
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content'),
  );

  return $items;
}

```

Simple path - `callback`.

And use the following AJAX:

```
$.ajax({
  url: '/callback',
  type: 'POST',
  dataType: 'json',
  data: {data: post},
  ...

```

By this way, you can access the data in your webhook more simply:

```
/**
 * My callback
 */
function mymodule_getinfo() {
  $data = !empty($_POST['data']) ? $_POST['data'] : array();

  // do what you want...
}

```
> 1 votes

---
Tags: javascript, ajax, routes
---


title: Drupal admin menu on/off issue

text:
# Question
Title: Drupal admin menu on/off issue
I am using drupal 7 . I am having issue with drupal admin menu. When I open new menu this time admin menu disappear and after refresh this page 2-3 times then menu display.

# Answer
It's cache issue of admin menu, you should disable the caching on client side.

You can do it here: `/admin/config/administration/admin_menu`, under `Performance tab`.
> 1 votes

---
Tags: 7
---


# Question
Title: How to show a view inside another view on only first row?
I need to display a view inside another view and I'm using Views field views module, It works well, but I need the field (view) only appears in the first row result of the view page, like the following.

* View page - results
    + Title node 1
    + Image node 1
    + View field 1 (this should appear only here)
    + Title node 2
    + Image-node 2

# Answer
> 2 votes
I'm not sure if Views nodes split module will be useful for your situation as @DnBase mentioned.

However, because you're using Views Field View; you can follow the following steps to achieve what you're looking for:

* Edit field view actual view (referenced view)
* Add `Global: Null` from **CONTEXTUAL FILTERS** menu

* From the next dialog box that appear, select `Hide view` from *WHEN THE FILTER VALUE IS NOT AVAILABLE* fieldset.
* Then from *WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED* fieldset, check `Specify validation criteria` and select `PHP Code` from validator dropdown menu
* Then add the following code in `PHP Validate code` field
* From `Action to take if filter value does not validate` dropdown menu select `Hide view`

**Code:**

```
if($argument == 1) {
  return TRUE;
} else {
  return FALSE;
}

```
* Now edit the main view
* Add `Global: View result counter` from **FIELDS** menu, then from field configuration dialog box, check `Exclude from display`
* Then edit `Global: View` field, from field configuration dialog box, add this replacement pattern `[%counter]` into `Contextual filters` field

By applying these steps, you'll notice that view field will only appear on first item.

# Answer
> 0 votes
I can see 2 ways to 'split' the displays in your view so far:

1. Use an 'Attachement' display and attach it to your view.
2. Use Views nodes split module. See lullabot's review to have an idea.

BTW you can still use a display mode to display your content type fields in your view if you want. See my post here.

edit: The second solution will work only if your display mode contains the view by using EVA or Viewfield module. So never mind but I leave it just for the Views nodes split module if you're interested. In your case the first solution will be just fine.

# Answer
> 0 votes
I would rather use views template file, and put some PHP scripts using flags to ensure that the view field renders only first time.

---
Tags: entities, views
---


# Question
Title: Can I use plupload to load multiple image files into a single image field
I have an image file field on my Drupal 7 site that allows users to add 4 images. I would like to give my users the ability to load all 4 images at once. I have discovered the plupload module and plup library which should be able to let me do this. However, I have yet to discover an configuration (including the media module) which allows me to do this. How can I make this functionality work?

# Answer
After installing plupload module and placing plupload libraries, create an image file upload field and select **Plupload** widget. Itz done.
> 1 votes

# Answer
Add this js in your custom js file.

```
(function ($) {
  Drupal.behaviors.autoUpload = {
    attach: function (context, settings) {
      $('form', context).delegate('input.form-file', 'change', function() {
        $(this).next('input[type="submit"]').mousedown();
      });
    }
  };
})(jQuery);

```

It will automatically upload all the images on click of upload button using above Jquery.

for more information,look at this link. at http://drupal.org/sandbox/clivelinsell/1587560 .
> 0 votes

---
Tags: media, files
---


# Question
Title: Unique Identifier of Every Drupal User Instance
I've been developing a custom module in my drupal system. One user account can be simultaneously access in different computer/browser. For example:

```
Username: ghlatorre
Computers accessing my system/module using the username ghlatorre: Computers 1, 2, 3, 4, 5

```

Is there a unique identifier I could use to differentiate these different system user instances?

# Answer
> 2 votes
If you want to *uniquely identify browsers*, Drupal tracks browser sessions via the `sid` & `ssid` column in its `sessions` table.

If you're looking to *uniquely identify computers*, you could try the IP address manager module.

> IP address manager records user IP addresses, and allows admins to view which IP addresses have been tracked against a user, and which users have been known to use a certain IP address. This can be currently used to identify duplicate accounts.
>
> The aim of this module is to provide a way to identify a user when they are not logged in to provide some action or context to their presence by maintaining lists of users for some purpose - such as, but not limited to, banning them.

The caveats with this approach is, depending on the network setup between the client & host, you might get false duplicate IP addresses for users (e.g. a home network router using NAT).

# Answer
> 1 votes
You may use Manifest user lists module.

**MANIFEST USER LISTS:**

* Creates lists of users for some arbitrary purpose (usually administrative).
* Modules can add options to a manifest list, in order to act on users in that manifest.
* Users can be added to a list via their user role, through the profile page, actions, Views Bulk Operations, or through user update operations.

> This module was originally created to provide the common functionality between Cave your trolls and Misery, as well as eventually identifying anonymous users as known users through IP address manager and possibly other methods.

---
Tags: 7, forms
---


# Question
Title: Show a Particular Page in Drupal 7 Table Pager
I have a table and a table pager in my form.

```
// $table_rows is an array containing data.
$page = 2;
//$page indicates that I want to display the second page in the table pager
//$page is dynamic. It depends on the user.
$per_page = 5; //No. of items per page
$chunks = array_chunk($table_rows, $per_page, TRUE); // Split an array into chunks of $per_page

$html =  theme('table', array('header' => $header, 'rows' => $chunks[$page], 'sticky' => TRUE)) . theme("pager", array('quantity',count($table_rows)));

```

The result of my code is below:

It works fine as expected , but my pager number is not. It must show `2` as the current page. Where am I missing?

# Answer
> 1 votes
I think theme\_pager in your case never know about current page, by which it can decide where to add 'page-current' class.

Try passing 'element' parameter the way you are doing for quantity.

```
$html =  theme('table', array('header' => $header, 'rows' => $chunks[$page], 'sticky' => TRUE)) . theme("pager", array('element'=> $page, 'quantity',count($table_rows)));

```

While $page will be less than a value of actual current page value. Please see theme\_pager to see how it works.

# Answer
> 0 votes
check out this

```
<?php
$per_page = 10;
// Initialize the pager
$current_page = pager_default_initialize(count($rows), $per_page);
// Split your list into page sized chunks
$chunks = array_chunk($rows, $per_page, TRUE);
// Show the appropriate items from the list
$output = theme('table', array('header' => $header, 'rows' => $chunks[$current_page]));
// Show the pager
$output .= theme('pager', array('quantity',count($rows)));
?>

```

---
Tags: 7, forms, theming, paging
---


# Question
Title: Inserting NULL value with db_query OR db_write_record
I have a table called foo\_bar whose fields are as follows

```
id int(10) unsigned NOT NULL AUTO_INCREMENT
name varchar(255) DEFAULT NULL
amount float DEFAULT NULL

```

I want to enter the value to this table like this

```
$name_value = 'Dollar';
$amount = NULL;

db_query("INSERT INTO {foo_bar} (name, amount) VALUES ('%s', %d)", $name_value, $amount_value);

```

But now when I see the values into the table it showed me

```
id | name   | amount |
1  | Dollar |      0 |

```

I tried db\_write\_record as well like this...

```
$obj_foo_bar = new stdClass();
$obj_foo_bar->name = 'Dollar'
$obj_foo_bar->amount = ''

```

But I am getting the same result.

**EDIT: 17 Sep 2012**

Don't use **drupal\_write\_record** for insert/update queries where you want to place the default value to **NULL**

INSTEAD: Use content\_write\_record which is used by CCK module to update the database tables were you want to place default value as NULL.

This function says **Directly copied from core's drupal\_write\_record, which can't update a column to NULL. See http://drupal.org/node/227677 and http://drupal.org/node/226264 for more details about that problem.**

# Answer
> 5 votes
The `NULL` that you're passing is possibly/probably being interpreted as a string, ie. "NULL". When MySQL casts that to a float the result is `0`.

If you have a default value for the column you can just leave it out of the query altogether, and you'll get the results you expect:

```
db_query("INSERT INTO {foo_bar} (name) VALUES ('%s')", $name_value);

```

or

```
$obj_foo_bar = new stdClass();
$obj_foo_bar->name = 'Dollar'
// Leave out $obj_foo_bar->amount

drupal_write_record($table, $obj_foo_bar);

```

# Answer
> 3 votes
DISCLAIMER : Not a Drupal Expert, Just a MySQL DBA

In your code, you tried to enter NULL into a numeric field

**Clive already gave you this**

```
db_query("INSERT INTO {foo_bar} (name) VALUES ('%s')", $name_value);

```

However, to forcibly enter a NULL you must enter it like this

```
db_query("INSERT INTO {foo_bar} (name,amount) VALUES ('%s',%s)", $name_value);

```

NOT

```
db_query("INSERT INTO {foo_bar} (name,amount) VALUES ('%s',%d)", $name_value);

```

In other words, do not use `%d` in `db_query`.

The proper setup for using NULL would be

```
$name_value = "Dollar";
$amount_value = "NULL";
db_query("INSERT INTO {foo_bar} (name,amount) VALUES ('%s',%s)",$name_value,$amount_value);

```

# Answer
> 0 votes
A lot of the answers here are recommending you use `db_query` for your INSERT queries.

Note that the docs state;

> Do not use this function for INSERT, UPDATE, or DELETE queries. Those should be handled via db\_insert(), db\_update() and db\_delete() respectively.

The code is far more elegant also;

```
$name_value = 'Dollar';
$amount = NULL;
$fields = array(
  'name' => $name_value,
  'amount' => $amount,
);

$record = db_insert('foo_bar')
          ->fields($fields)
          ->execute();

// $record now contains the new row from the db.

```

I know this is an old question but it was worth posting in case somebody else stumbles upon it.

---
Tags: database
---


title: Drupal reference performance

text:
# Question
Title: Drupal reference performance
I have a project have a lot of field need to be reference by each other.

Does anyone could give me some suggestion about this situation?

How was the performance of field reference? Should I just saving field by text rather than reference type? (And then render by my custom module code)

# Answer
> 1 votes
There is no performance issue I see with reference field. Reference field holds lot of other things

1. A table which keeps relationship between two entities which is exposed to other modules where references are saved as entity ids with no control of user input, whereas for text field you do not have much control unless you put validations and turn into almost what reference field is already doing.
2. Different contributed module are built around reference fields.
3. As an example you can expose reference fields as relationship to views module.
4. Text Field is definitely not a replacement for Reference field.
5. You would not like to get the performance boost for a reference field on the cost of its functionality.
6. If you have long list of entities to reference, keep the widget as autocomplete that can help in performance boost a bit.

---
Tags: entities, nodes, performance
---


title: Organic groups api?

text:
# Question
Title: Organic groups api?
I have the Organic Groups module working in my site, but when I try to use a simple function like og\_load() in my module, I get the following error:

> Call to undefined function `og_load()`.

What should I do to use these functions?

# Answer
> 1 votes
og\_load() is defined on the module file, which means it should be available once the module is enabled. Be sure to call the function when Drupal completed its bootstrap, and loaded all the enabled modules. If you call it inside hook\_boot(), or hook\_exit(), the function could not be available, if Drupal didn't complete its bootstrap.

Sometimes it's enough to increase the weight of the module calling `og_load()` to avoid the error (if the function is not called in the hooks I previously described). Execute the following code in `hook_install()`. (Replace mymodule with the short name of your module.)

```
$weight = db_query("SELECT weight from {system} WHERE name = 'og' AND type = 'module'")->fetchField();
db_update('system')
  ->fields(array('weight' => $weight + 1))
  ->condition('type', 'module')
  ->condition('name', 'mymodule')
  ->execute();

```

# Answer
> 0 votes
The function is undefined within the scope of your module because your module doesn't know about the Organic Groups module. You have to invoke the Organic Groups module before you can call its functions. (This is the case when using any module's functions.)

Using module\_exists() should do the trick. As a bonus, it'll also protect you from unforeseen errors if the Organic Groups module is ever missing or turned off on your site:

```
if (module_exists('og')) {
  // your og_load() code goes here
}

```

# Answer
> 0 votes
If you are looking for drupal 7, the api function no more exist, instead node\_load($group\_id) can be used.

Check this issue link.

---
Tags: organic-groups
---


title: Class Autoloading include file

text:
# Question
Title: Class Autoloading include file
Class autoloading isn't working in custom module to extend webforms. Trying to call a function like this:

```
$utility = new webform_kk_utility();
$utility->getComponents('aaa')

```

getting this error:

```
[Mon Sep 21 20:29:28.287580 2015] [:error] [pid 15908] [client ******:39831] PHP Fatal error:  Class 'webform_kk_utility' not found in /var/www/html/sites/all/modules/webform_kk/webform_kk.module on line 12

```

Here's my code:

webform\_kk.info:

```
name = Webform kk
description = custom webform code
core = 7.x
package = Webform
dependencies[] = webform
files[] = includes/utility.inc

```

webform\_kk.module:

```
<?php

function webform_kk_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'webform_client_form_1') {
        $first = array_shift($form['#submit']);
        array_unshift($form['#submit'], $first, 'webform_kk_submit_1');
    }
}

function webform_kk_submit_1(&$form, &$form_state) {
    $utility = new webform_kk_utility();
    echo $utility->getComponents('aaa');
    die();
}

```

includes/utility.inc:

```
<?php

Class webform_kk_utility {
    function getComponents($components) {
        return $components;
    }
}

```

I tested the code without calling the external function, the code is running and the form submit dies where expected. I tried disabling, uninstalling the module and clearing the cache.

Thanks for the help.

# Answer
"Class" -\> "class".
It needs to be lowercase, or else Drupal does not discover it while scanning the file.
> 1 votes

---
Tags: 7
---


# Question
Title: Custom php to handle url based on taxanomy terms
Our site uses taxanomy to maintain a blog page. And for now we use views to render the contents. Now we are planning to get rid of views and use templates. What we need is to have custom tpl.php only for request containing vocabulary. So for any request to my site of a pattern ***path/\****,

1. I need my custom tpl.php to be used only when the **path** is valid vocabulary.
2. Let the default flow get executed when the **path** is not a valid vocabulary.

What would be right way to handle this?

# Answer
In views use TID converted to Name filter then use TID in url as a parameter and when the url is hit check the tid is valid or not and write behavior accordingly.
> 0 votes

# Answer
You can use **template\_preprocess\_page()** to check the specific path and add your custom template.

```
function template_preprocess_page(&$vars, $hook) {
  $path = current_path();
  if ($path == 'your_path') {
    $vars['theme_hook_suggestions'][] = 'page__custom';
  }
}

```

So your template file should have the name **page--custom.tpl.php**
> 0 votes

---
Tags: taxonomy-terms, theming
---


title: How to 'drush sql-dump' all databases

text:
# Question
Title: How to 'drush sql-dump' all databases
I have two databases I connect to with drupal. Does `drush sql-dump` back up all databases defined in settings.php?

If not how can I create dumps of both databases?

I've attempted using the `--database=db_to_backup` option but it throws an error:

```
sh: 1: Syntax error: "&&" unexpected
Database dump failed

```

Many thanks

# Answer
> 5 votes
If your database connection on settings.php looks like

```
$databases = array(
  'default' =>
  array(
    'default' =>
    array(
      'database' => 'mydatabase1',
      'username' => 'root',
      'password' => 'root',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  'test' =>
  array(
    'default' =>
    array(
      'database' => 'mydatabase2',
      'username' => 'root',
      'password' => 'root',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

```

The following command will back up both the data bases;

```
drush sql-dump --database=default --result-file=default.sql; drush sql-dump --database=test --result-file=test.sql

```

---
Tags: 7, database, drush
---


# Question
Title: How might I find a render array of a parent OG group?
If given the node id, how may I get that node's menu's render array?

I'm almost looking for an API function such as

```
function get_menu_for_node($nid) {}

```

Where this would return the render array to which node/$nid belongs.

# Answer
> 0 votes
I did the following to achieve this. I'm still not happy with the results but given time pressures, it'll have to do. I'm posting to see if anyone can suggests a better alternative.

I grab the nid of the parent group first and use it to do a query against `menu_links`. Once I have a result of a menu\_id(s), we loop through, get the links, use `theme()`, and then `drupal_add_region_content()`.

```
<?php
/**
 *
 *
 * This module creates a block that looks for any parent OG group and displays the menu of that
 * group.
 */

define('_OGPN_NODETYPE', 'user_posted_content');
define('_OGPARENTNAME_TITLE', 'OG Parent Menu');

/**
 * Implements hook_block_info().
 */
function ogparentmenu_block_info() {
    // This example comes from node.module.
    $blocks['_ogparentmenu'] = array(
        'info' => t(_OGPARENTNAME_TITLE),
        'cache' => DRUPAL_NO_CACHE,
    );

    return $blocks;
}

/**
 * Implements hook_block_view().
 */
function ogparentmenu_block_view($delta = '') {
        return [
            'subject' => t(_OGPARENTNAME_TITLE),
            'content' => __ogparentmenu(),
        ] ;
}

/**
 * @return string
 * @throws Exception
 */
function __ogparentmenu() {

    $node = menu_get_object();

    /* Set up menu on UserPosts  */
    if ($node->type == _OGPN_NODETYPE) {

        // get parent link of og
        $parent_og = filter_var($node->og_group_ref[LANGUAGE_NONE][0]['target_id'], FILTER_SANITIZE_NUMBER_INT);

        // Query menu_links based on node/$nid path
        $menu_query = db_select('menu_links', 'ml')
            ->fields('ml', ['menu_name', 'mlid'])
            ->condition('link_path', "node/$parent_og", '=')
            ->execute();

        // if single
        if ($menu_query->rowCount() == 1) {
            $menu_id = check_plain($menu_query->fetchAs()['menu_name']);
            $links = menu_navigation_links($menu_id);

            $themed_menu = theme('links__system_main_menu', [
                '#title' => t('title'),
                'links' => $links,
                'attributes' => [
                    'class' => ['user_post_menu_injected', 'section']
                ],

            ]);

            return $themed_menu;

        }
        // TO DO : handle multiple
        elseif ($menu_query->rowCount() > 1) {

            return 'null';
        }

    }
}

```

---
Tags: 7, routes, theming
---


title: Images are not showing in localhost

text:
# Question
Title: Images are not showing in localhost
I have taken a clone of my site, downloaded the files folder and the database to my local system.

I am using Xampp server in my local system and I have kept the site image ‘files’ folder in the sites/default/files directory.

The problem is that in my local system 30% of the images are not displaying in the local site. The images are available in the files/images folder, but in local site the images are not showing.

I tried all the process and i also updated the base url in my setting.php file but the issue is not yet fixed.

According to my understanding the issue is related to the image path. In site those images we are calling through css is not taking the site base url. For example:

Current path: http://www.localhost/sites/default/files/images/mobile-block-img-new.png

Correct path: http://www.localhost/repliconwebsite/sites/default/files/images/mobile-block-img-new.png

Please suggest if you get the solution.

# Answer
As you are using subdirectory structure at localhost and previous drupal installation was at root directory, the base url will not change for database entries.

Use Pathologic module to change base url of urls coming from database

or

search n replace them in .sql file, then import the database.

search: src="/sites/default/files/images

replace: src="/repliconwebsite/sites/default/files/images
> 1 votes

# Answer
First of all check, whether your files are in `sites/default/files/` folder or `/sites/all/themes/your_theme/images/` folder ? If your files are in `sites/default/files/` folder, You need to change permission and it is not right place to put your images. You should put images in your `/sites/all/themes/your_theme/images/` folder and in `Src` attribute of `image tag` give path from `sites/all/themes/your_theme/images/mobile-block-image.png` path.
> 0 votes

---
Tags: media
---


# Question
Title: My custom Save button does not save the new form values
I added a custom button to my form which I want to call a function which grabs some values from that form, email them out to whomever, and then save the form. I have successfully emailing the value, but I cannot get the form to save.

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

    $type = $form['type']['#value'];
    if($type !== 'support_ticket')
        return;

    $form['actions']['submit2'] = array(
        '#type' => 'submit',
        '#value' => t('Accept And Close'),
        '#submit'=>array('my_mod_email_and_close')
    );
    return $form;
}

```

`function my_mod_email_and_close(&$form, &$form_state)` does not contain any logic to actually save the form values. It only checks the form for some values and emails those values out.

I need to save the form however, how do I also get this custom button to submit and save the form. I tried adding these lines to the bottom of `my_mod_email_and_close()`

```
$form_id = $form['form_id']['#value'];
drupal_form_submit($form_id, $form_state);

```

but it doesn't actually save. I get 2 of the same errrors however: `Trying to get property of non-object in _support_assigned()` from a different module so I am not sure whats going on.

Perhaps I am using the wrong hook?

# Answer
Add the original form's submit function to your #submit array in addition to your custom function.

https://api.drupal.org/api/drupal/developer%21topics%21forms\_api\_reference.html/7#submit\_property
> 1 votes

---
Tags: 7, forms
---


# Question
Title: How to add item to $vars[breadcrumb] in Drupal
The current breadcrumb only shows 'home'. I would like to update it so it shows 'home\>shoes\>Tennis Shoe' where 'shoes' is referenced content type(product display) and 'Tennis shoes' the instance(node) title of that content type

Here is how i tried to accomplish this.

I would push additional items(shoes, tennis shoe) into vars\[breadcrumb\] at page level(theme\_preprocess\_page) as following:

```
function THEME_preprocess_page(&$vars, $hook) {
...
$vars['breadcrumb'][] = '<a href="/shoes">shoes<a>';
$vars['breadcrumb'][] = '<a href="/shoes/tennis-shoe">Tennis Shoe<a>';
...
}

```

And then let my theme\_breadcrumb() handle it as it walks through the array:

```
function THEME_breadcrumb($variables) {
    $breadcrumb = $variables['breadcrumb'];
    if (!empty($breadcrumb)) {
        $breadcrumbs = '<ul class="breadcrumb">';
        $count = count($breadcrumb) - 1;
        foreach ($breadcrumb as $key => $value) {
            if ($count != $key) {
                $breadcrumbs .= '<li>' . $value . '<span class="divider">/</span></li>';
            }
            else{
                $breadcrumbs .= '<li>' . $value . '</li>';
            }
        }
        $breadcrumbs .= '</ul>';
        return $breadcrumbs;
    }
}

```

This doesn't work. Whenever I add the items to the vars\['breadcrumb'\] in the preprocessor function as showed above, it never goes to 'THEME\_breadcrumb', instead displays 'array' text. (apparently, it expects non array at vars\['breadcrumb'\]) How do you manipulate breadcrumbs? Whats wrong with my reasoning? Thank You

Drupal 7, base of boostrap theme

# Answer
I hope that you have set $breadcrumb in page.tpl.php. Secondly, you do not need to do it by using theme\_preprocess\_page.

Just implement using THEME\_breadcrumb like this:

```
function theme_breadcrumb($variables) {
  $breadcrumb = $variables['breadcrumb'];
  $output = '';
  if ((arg(0) == 'node') && is_numeric(arg(1)) && ($node = node_load(arg(1)))) {
    if ($node->type == 'TYPE NAME') {
      $breadcrumb[] = $node->title;
    }
  }
  if (!empty($breadcrumb)) {
    $output.= '<div class="breadcrumb">' . implode(' › ', $breadcrumb) . '</div>';
  }
  return $output;
}

```
> 2 votes

# Answer
You can also use `drupal_set_breadcrumb()` in your `template_preprocess_page()` hook. Something like:

```
function THEMENAME_preprocess_page(&$variables) {
  // Wrap the code below with some logic here to target just content type you want, like
  // an if() block that looks for $variables['type'] == 'shoe' or whatever

  // Building breadcrumbs
  $breadcrumb = array();
  $breadcrumb[] = l('Home', '<front>');
  $breadcrumb[] = l('Shoes', 'shoes');
  // Setting breadcrumbs
  drupal_set_breadcrumb($breadcrumb);
}

```

This only sets the **breadcrumb trail**, so the current page title will automatically be placed at the end of the breadcrumbs.
> 1 votes

---
Tags: theming
---


# Question
Title: How to properly delegate form error to parent?
I have a form with multiple radios. I need to display the radios in a certain way(separately with additional form elements) so I had to use **radio** form elements instead of one **radios** element.

The radios are required but I have an issue with delegating the error to the parent element. I switched off the error message for the radios themselves via the `#error_no_message` attribute. Now the form error is properly displayed for the parent element but the error message contains the label of the first radio element instead of the parent element. So for example if I have fieldset named "Manufacturer" and it contains radios with labels like "Audi", "Mercedes" or "BMW" and I won't select any radio the form error, after form submission, will say "Field **Audi** is required." instead of "Field **Manufacturer** is required".

So how can I delegate the form error to the parent(which is working) but with making the form error to be applied to the parent itself so the proper label is displayed?

# Answer
I did what I could but in the end I had to create new form element that provided me with the proper structure. The important thing about it though is mostly that it has input so the form element can be properly delegated whereas before I used fieldset which has no input therefore it would not display error properly.
> 0 votes

---
Tags: 8, forms
---


# Question
Title: How do I add an access condition to a menu item?
How can I add new conditions on top of existing conditions that determine whether a menu item is visible? These conditions should not be limited to permissions settings.

As an example use case (not necessarily the reason for this question): Suppose I have a content type of which users are only allowed to create one node. I have a menu item for adding that type of content. But if the user has already created a node of that content type, I want to hide the menu item. My first thought is to run a query to check for the existence of a node created by the current user that is of the specific content type. If one exists, hide the menu item.

I would think this type of functionality should go into `hook_menu_alter()` and add the required logic there. But I'm not sure how to do that without bypassing the existing checks, like checking if the user has permissions to create that type of content. Would I have to include that logic within my own condition? Or can I add to the existing access logic without overwriting it?

---

Edit: Some people seem focused on answering "how do I limit a user to creating one node of a content type". That is not the question here. The question is how to I add custom access conditions to a menu item.

# Answer
> 11 votes
What you need to do is to add your callback via hook\_menu\_alter(), and then inside your callback you simply do your logic then return the data via the original callback.

To be certain that you don't overwrite any other hook\_menu\_alter() changes, you should pass the previous callback to your callback via the access argument.

This is all theoretical, but the code should go something like this:

```
MYMODULE_menu_alter(&$items) {
  $items['menu']['access arguments'] = array_merge(array($items['menu']['access callback']), $item['menu']['access arguments']);
  $items['menu']['access callback'] = 'MYMODULE_access_callback';
}

MYMODULE_access_callback() {
  $args = func_get_args();

  // Do Stuff.
  if ($something == FALSE) {
    return FALSE;
  }

  $function = array_shift($args);
  return call_user_func_array($function, $args);
}

```

# Answer
> 1 votes
In response to the comments above, the solution in D7 would be to use:

```
/**
 * Implements hook_node_access().
 */
function mymodule_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;

  if ($op == 'create' && $type == 'mynodetype' && db_query("SELECT 1 FROM {node} WHERE type = :type AND uid = :uid", array(':type' => $type, ':uid' => $account->uid))->fetchField()) {
    // If the user has already created a node of a specific type, they cannot
    // create any more.
    return NODE_ACCESS_DENY;
  }

  // Otherwise do not affect any node access.
  return NODE_ACCESS_IGNORE;
}

```

# Answer
> 1 votes
You're looking for the Chain Menu Access API module.

> Chain Menu Access API allows your module to chain its own menu access callback functions into other modules' menu router entries.

There is at least one example on Drupal Stack Exchange of how to use it.

# Answer
> -1 votes
One option would be to create a new role that has create content permission for your content type. After a user creates a node of that type, take away that role and they wont be able to create any more.

# Answer
> -1 votes
Perhaps you should try the Node Limit module.

From the project page:

> The Node Limit module allows administrators to restrict the number of nodes of a specific type that roles or users may create. For example, if a site has an "Advertiser" role that can create "advertisement" nodes, then the node limit administrator can restrict all users in that role to a specific number of nodes. He may also restrict users on a per-user basis.

---
Tags: routes
---


# Question
Title: Error: Argument 2 passed to drupal_array_get_nested_value() must be of the type array, string given
I'm using Entityform with some custom module for multipage which is based on FGAM.

> Recoverable fatal error: Argument 2 passed to drupal\_array\_get\_nested\_value() must be of the type array, string given, called in includes/form.inc on line 1200 and defined in drupal\_array\_get\_nested\_value() (line 6771 of includes/common.inc).
>
> The website encountered an unexpected error. Please try again later.

Why this happens and how do I fix or debug this kind of error?

# Answer
> 3 votes
The error:

> Argument 2 passed to drupal\_array\_get\_nested\_value() must be an array, string or null given

means there is a problem with the structure of your form you're trying to submit. So string/NULL were given instead of array for the second parameter.

The function:

```
&drupal_array_get_nested_value(array &$array, array $parents, &$key_exists = NULL)

```

retrieves a value from a nested array with variable depth, for example:

```
$value = drupal_array_get_nested_value($form, $parents);

```

Here are the example calls from Drupal core (see the 2nd argument):

```
./common.inc:  drupal_array_get_nested_value($array, $parents, $key_exists);
./form.inc:      $input = drupal_array_get_nested_value($form_state['input'], $element['#parents'], $input_exists);
./form.inc:  $source = drupal_array_get_nested_value($form_state['complete form'], $element['#machine_name']['source'], $key_exists);

```

If you don't know which field is causing it, the easiest way to find out is by doing this simple hack (which should be reverted after that of course):

```
function &drupal_array_get_nested_value(array &$array, $parents, &$key_exists = NULL) {
  if (!is_array($parents)) { var_dump($parents, debug_backtrace()); exit; }

```

Which would display value of `$parents` which should be an array and the backtrace.

Usually this could happen during the validation and it can caused by invalid `#parents` or `#limit_validation_errors` structure of form array.

If there is no any custom coding involved, then it's a bug of the contrib module which cause that (e.g. Conditional Fields, Email Field, Entity Translation, etc.), so it should be reported against the right module.

---

In my specific case, I've to fix `#limit_validation_errors` by wrapping it into `array()` where it contained list of `$group['children']`:

```
  $form['actions']['continue'] = array(
    '#type' => 'submit',
    '#value' => t('Continue'),
    '#limit_validation_errors' => array($validate_fields),
    '#submit' => array('foo_form_submit'),
    '#validate' => array('foo_form_validate'),
  );

```

---
Tags: forms
---


title: Add a field between name and email

text:
# Question
Title: Add a field between name and email
I'm running Drupal 7.39 and I'm trying to add a textfield exactly between the "name" and "email" field. I also tried with the `#weight` property as noted by the Form API but it does not work.

# Answer
> 1 votes
If you are doing it by custom code, you have to move the field to 'account' container, example code looks like

```
function my_module_name_form_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register_form') {
    // Change weight in respect of user name field.
    $form['field_test']['#weight'] = $form['account']['name']['weight'] + 1;
    // Use machine name of field as form field, replace 'field_test' with your machine name.
    $form['account']['field_test'] = $form['field_test'];
    unset($form['field_test']);
  }
}

```

# Answer
> 0 votes
Have a look at Display Suite. You can create new fields with it and customize the output.

---
Tags: theming, users
---


# Question
Title: weird features behavior - constantly adding and removing entries from taxonomy.inc
I'm using `features` and I commit the features module to my repository to track changes.

Every now and then (after `drush fu foobar`) I see the following change to the `foobar.features.taxonomy.inc` file:

```
@@ -16,8 +16,6 @@
       'hierarchy' => '0',
       'module' => 'taxonomy',
       'weight' => '0',
-      'language' => 'und',
-      'i18n_mode' => '1',
       'metatags' => array(),
       'rdf_mapping' => array(
         'rdftype' => array(
@@ -42,8 +40,6 @@
       'hierarchy' => '0',
       'module' => 'taxonomy',
       'weight' => '0',
-      'language' => 'und',
-      'i18n_mode' => '1',
       'metatags' => array(),
       'rdf_mapping' => array(
         'rdftype' => array(
...

```

Note the removals in the above diff starting with `-`. That takes place at the same time for all of my 15 taxonomy vocabularies.

After some development and in the next `drush fu foobar` those exact lines are added back.

In the meantime of that cycle:

* I haven't touched anything on those taxonomies
* I haven't updated `features` (I use the latest)

Any idea why this is happening?

**Edit: More info** After the offending lines are added in the `foobar.features.taxonomy.inc` file if I do a `drush cc all` then I get the following output in the console:

```
Reset language for all terms.

Reset language for all terms.

[...]

Reset language for all terms.

```

That is 15 times if I have 15 taxonomy vocabularies.

# Answer
> 0 votes
Taxonomy Edge optimizes tree functions for taxonomies. It provides a transitive closure table data model for easily managing hierarchical terms. It was created to avoid recursive functions when fetching all children, and to avoid the not-quite-so-scalable memory footprint of taxonomy\_get\_tree().

The provided patch contains overrides for the core module Taxonomy in regards to taxonomy\_get\_tree() and taxonomy\_select\_nodes().

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


# Question
Title: How do you update a user role to be an admin role via Drush sql-query?
I know the following User ID 2524 and the Name is Tester. And the role to be an admin is 3. What command is needed to make a user an admin using only the the drush terminal?

# Answer
I do not see a reason to execute a sql query, when this can be as simple as

```
drush user-add-role "administrator" --uid=2524

```

To see more options with command type

```
drush help user-add-role

```
> 1 votes

# Answer
You can use the following sql statement:

**drush sql-query 'insert into users\_roles (uid, rid) values (2524, 3)'**

The **users\_roles** table is where user and role data is stored. Initially I thought the roles was stored in the users or roles table.
> 0 votes

---
Tags: drush, users
---


# Question
Title: How to pass cookie value into Drupal View
We want to create some logic using JS that creates a cookie and set the node's taxonomy term id (preferred) or taxonomy term name as the cookie value. Then we want to use the cookie value to filter a View so that when a user visits a page, the view that is shown is filter based on the cookie value.

How can I pass a cookie value into the View?

/\******************** Update - 9/23/2015 \**************************/

I ended up using a mixture of a list block, javascript, and a custom module that on full node view, the taxonomy term id is stored into the browser's locale storage. I am no longer using a filter view based on cookie. Also, the custom module stores the taxonomy term ids into the block.

# Answer
> 2 votes
On May 26th 2011 a new EU originated law came into effect that requires website owners to make significant changes to their sites and may fundamentally change the whole web browsing and shopping experience for everybody.This Cookie Law is amended privacy legislation that requires websites to obtain informed consent from visitors before they can store or retrieve any information on a computer or any other web connected device.

Cookie Control does just that, presenting users with clear information on whether cookies are present, linking to your privacy policy (where you should have specific information about what cookies are in use), and advising users on how to adjust browser settings and what cookies mean for them.

---
Tags: views, nodes, javascript, cookies
---


# Question
Title: How can i override all node book/book_alias usng alias
How can i override all node "book/book\_alias" using View when i tried "contextual filter" not provided for alias i must use a node id rather then book\_alias.

Any Solution to override a multiple node using alias ?

# Answer
> 0 votes
Quick and fast method for D7 by using Pathauto 7.x-1.2, VBO 7.x-3.0 and Admin Views 7.x-1.0:

```
drush dl views_bulk_operations
drush en views_bulk_operations
drush dl admin_views
drush en admin_views

```

Go to /admin/content, edit the view with contextual menu on top right of view.

Then Click the "Bulk operations: Content" field. Then click the "Update node alias" checkbox and save.

Go back to /admin/content and select all nodes

Choose an operation, then select "Update node alias", then execute!

===================

Although pathauto in 6.x-1.x provides a utility to "bulk generate paths", this one-off action fails on thousands of nodes, and does no "batch" processing. This results in timeouts, memory overruns, and failure. (Pathauto token generation can be expensive, and becomes painful over thousands of nodes)

This "batch" issue is being addressed in 6.x-2.x & 7.x

Until then, you still have an alternative, and it's better! The pathauto 6.x-1.x module already exposes the pathauto path-rebuilding function as a node operation that can be applied through the content management screen, or if using "Views Bulk Operations" - as a bulk operation there.

This means you will be able to select only and all nodes of a desired content type, and do them all in a "batch" mode without processing overruns. Get Views Bulk Operations

See the project itself for install and configuration options.

Once enabled, a new action "Update URL alias" becomes available as an available action within VBO. (when editing the view, and the Style: Bulk Operations settings) You will want to turn that on.

At the same time, ensure that VBO will use "batch mode" ( To execute operations: "Use Batch API" )

Once that is on, the update task will show up on the VBO screen, and you can, for example, choose to regenerate updated alias paths for 3000 'Article' type nodes without doing the same for 15000 'Image' type nodes. Advanced usage

The global pathauto settings do not allow for any extra logic, though sometimes you want to to different things to different content (especially if working with bulk imported content, or re-architecting)

You can set the pathauto settings to agressively discard or overwrite any existing paths, then trigger the bulk update over a selection of pages you have defined through VBO. (ones you really need to rewrite) After that you can change the global pathauto settings to just 'update' or 'leave existing aliases' for other content from then on. Or vice versa or something else. Without VBO, you could do one or the other of these updates, but not both. It takes a few more steps, but it's possible.

---
Tags: nodes, views
---


# Question
Title: Translation table: How do I restore a deleted metatag string?
At the Translation table module (admin/config/regional/translate/translate), I was translating metatags. By accident I deleted one (metatag:global:og:street-address). I thought I just delete all the useless translations, but then it deleted the whole tag.

Is there a way to restore or (if easier) add it again to the table?

# Answer
> 0 votes
Here are the steps to reproduce:

1. Enable Metatags, Entity Translation and Inline Entity Forms.
2. Make a node type translateable (using Entity Translation) and add an entity reference field that uses the inline\_entity\_form widget (it doesn't matter what it points to).
3. Create a node of that type, with custom meta tags and add one referenced entity, save it.
4. Add a translation in another language, translate the meta tags and save the translation (you can also translate the referenced entity, this isn't relevant for this bug though). At this point we have all content as it should be.
5. Now edit the translation again, leave the meta tags as they are (everything still looks fine) and make a modification to the referenced entity using the inline entity form widget, then save the entire form. The translated meta tags are gone and have been reset to the default values.

The cause of this issue is the following code in metatag\_field\_attach\_form():

```
<?php
// Entity_Translation will trigger this hook again, skip it.
if (!empty($form_state['entity_translation']['is_translation'])) {
     return;
}
?>

```

This code works as intended when adding a translation, but not when editing a translation, because in that case $form\_state\['entity\_translation'\]\['is\_translation'\] is not defined (it gets defined later, only after the code above has already been executed). However, even though the logic is broken, the resulting behavior is correct, because when editing a translation metatag\_field\_attach\_form() doesn't actually get called twice as mentioned in the code comment, so we really don't want to return yet.

The problem arises when using the inline\_entity\_form widget, which reloads part of the form using Drupal's standard ajax mechanism. This causes the form to be rebuilt, and the code above from metatag\_field\_attach\_form() is run again, but this time after Entity Translation has set $form\_state\['entity\_translation'\]\['is\_translation'\]. The code is now running as intended, but the resulting functionality is broken. Now the function returns prematurely, $form\['#metatags'\] doesn't get set, metatags' hook\_form\_alter() gets skipped and the form submit handler doesn't get set in metatag\_metatags\_form(), so meta tag information gets lost and is replaced with the default value.

The solution is to fix the code above to only return when a new translation is being added, not anytime a translation is edited:

```
<?php
// Entity_Translation will trigger this hook again when adding a new     translation, skip it.
if (isset($form_state['entity_translation']['is_translation']) &&     !empty($form_state['entity_translation']['is_translation'])) {
  return;
}
?>

```

---
Tags: 7, i18n-l10n, meta-tags
---


# Question
Title: Default values for panelizer and fieldable panel panes
I have a template being applied to a node with a few different fieldable panel panes on it. I can create a new piece of content and it's page will load with the template applied and all of the FPP's right where they should be.

Say I make 10 pieces of content and they all have that same template. If I go to one of them and add something to an FPP on it and then save as custom that FPP will be modified the same way on all 10 pages. If I use the inline editor and remove the panel with content, save as custom, and then add that panel back it will be empty.

If I have a blank panels template and go to all 10 pages one at a time and add the FPPs to them and save them each as custom then the FPPs will stay unique.

I need to be able to load the complete template with the content panes already there but have them all be empty when the page is initially made.

Is there anyway to assign a panel a default value of nothing?

# Answer
The methods hook\_entity\_insert() / hook\_entity\_update() don't check whether an entity has dedicated panelizer settings or not and just always saves the panelizer object found for it. Which can be the defaults of course. The attached patch looks worse than it actually is. It basically introduces the property entity\_custom\_panelizer which indicates if a panelizer setting is dedicated to the entity or not. And the hooks hook\_entity\_insert() / hook\_entity\_update() only save the settings into the panelizer\_entity if the flag is set. I really hope I didn't miss something but first smoke-tests look promising.
> 1 votes

---
Tags: panels
---


title: how do i get openscholar to work again

text:
# Question
Title: how do i get openscholar to work again
Im trying out drupal openscholar, and every time i change some setting (enabling css agregation, enabling require.js) after installation, it stops serving js and css files till i reinstall even if i revert the setting. what could be going on? here are some errors:

```
Notice: Undefined index: os_default in drupal_theme_initialize() (line 100 of /var/www/html/dr20o32/includes/theme.inc).
Notice: Trying to get property of non-object in _drupal_theme_initialize() (line 145 of /var/www/html/dr20o32/includes/theme.inc).
Notice: Trying to get property of non-object in _theme_load_registry() (line 334 of /var/www/html/dr20o32/includes/theme.inc).
Notice: Undefined index: os_default in theme_get_setting() (line 1414 of /var/www/html/dr20o32/includes/theme.inc).
Notice: Trying to get property of non-object in theme_get_setting() (line 1451 of /var/www/html/dr20o32/includes/theme.inc).
Notice: Trying to get property of non-object in theme_get_setting() (line 1461 of /var/www/html/dr20o32/includes/theme.inc).

```

This is with drupal-7.20 , and openscholar 3.2.0, the same thing happens with drupal-7.22 and openscholar 3.4.1

this is what it looks like:

here are the permissions on sites/\*/files

```
[default]3 ll *
total 52
-rw-rw-r--. 1 apache apache 23197 May 14 11:50 default.settings.php
drwxrwxr-x. 5 apache apache  4096 May 14 12:27 files
-r--r--r--. 1 apache apache 23501 May 14 11:56 settings.php
[default]# ll files/
total 12
drwxrwxr-x. 2 apache apache 4096 May 14 12:31 css
drwxrwxr-x. 3 apache apache 4096 May 14 18:12 ctools
drwxrwxr-x. 2 apache apache 4096 May 14 12:02 styles

```

even the selinux contexts look ok.

# Answer
> 0 votes
Disable css and js aggregation. If it helps, you have problem with `sites/*/files` directories and your php can't write to them.

# Answer
> 0 votes
The easiest way to get started is with the latest release here: http://openscholar.harvard.edu/download We've already downloaded drupal, run the build script, and packaged everything up into a file for you to download.

Start with that, put it in a folder apache can see, and browse to install.php. If you get stuck, we're happy to help but you'll need to be specific.

---
Tags: distributions
---


# Question
Title: How do I get line breaks when using Plain Text format?
I feel like this should be reaaaaaally simple, but it's driving me crazy.

I have 'plain text' selected for all my Body elements. I don't want anyone to be able to put in any html at all when filling out forms.

However, I do want the line breaks preserved. On the configuration page for plain there there is indeed a 'check this box to to turn line breaks into br and p, but no matter what I check or how I rearrange the weight of the filters, I cannot get it to preserve the breaks.

What is the correct configuration to get this to work so that I can preserve returns in the texts?

# Answer
Looks like a bug in Drupal core http://drupal.org/node/1019042
> 8 votes

# Answer
This seems like a Drupal 7.x bug. Changing the order of filters doesn't work in my case.

My short term solution was to throw this inside my theme's template.php (ref):

```
<?php
/**
 * Implements template_preprocess_field().
 */
function THEMENAME_preprocess_field(&$vars, $hook) {
  // Add line breaks to plain text textareas.
  if (
    // Make sure this is a text_long field type.
    $vars['element']['#field_type'] == 'text_long'
    // Check that the field's format is set to null, which equates to plain_text.
    && $vars['element']['#items'][0]['format'] == null
  ) {
    $vars['items'][0]['#markup'] = nl2br($vars['items'][0]['#markup']);
  }
}
?>

```

For fields in views, it's needed to set this option separately in the "Rewrite Results" section of the field settings.
> 12 votes

# Answer
Actually, it should work with this filters order setting at "admin/config/content/formats/plain\_text"

1. Display any HTML as plain text
2. Convert URLs into links
3. Convert line breaks into HTML (i.e. \<br\> and \<p\>)

Try the filters below by removing "Display any HTML as plain text":

1. Limit allowed HTML tags ( set only \<a\> and \<br\> for allowed HTML tags list )
2. Convert URLs into links
3. Convert line breaks into HTML (i.e. \<br\> and \<p\>)
> 4 votes

# Answer
The solution is simple. Just display the plain-text content with following css.

```
white-space: pre-line;

```
> 3 votes

# Answer
I used the Advanced Text Formatter module to quickly solve this problem without code.

1. Install and enable the module.
2. Click 'Manage Display' of your content type.
3. Change the 'Plain Text' of your field's format to 'Advanced Text'
4. Click the gear on the right (or a link to format settings)

1. Set trim length to 0
    2. Set filter to 'Limit Allowed HTML tags'
    3. Remove all items from 'Allowed HTML tags'
    4. Check 'Converts line breaks into HTML'
    5. Click 'Update,' and Save your Field Display.
> 1 votes

# Answer
I don't think it's the input filtering: it's probably the display setting for the field. If it's set to "Plain text", change it to "Default". Otherwise the tags generated for the input line-breaks get stripped before the field is displayed.

For clarity, this is on the "Manage Display" panel for the content type in question. At Administration » Structure » Content type » MyContentType » Manage Display. Under the Format column for the field.
> 0 votes

# Answer
I don't think this a bug but the result of confusion (not helped by the way Drupal is set up) between a field with a "filtered text" input format set to "plain text" and a "plain text" field. If when you create your field you select "filtered text", the user will get the option to select from "plain text" and any other input formats available, and using the "plain text" option here when creating your content will render the line breaks and links out of the box. If however on field creation you select "plain text", no tags will be available/rendered at all, no matter how you configure the "plain text" input format. So before panicking that "plain text" doesn't work, first check in your content type setup that the field has "filtered text" selected. It's paradoxical and annoying, but, Drupal... ;)
> 0 votes

# Answer
"Plain Text format" as "Text processing"-method does NOT support any HTML-Tags, therefore line breaks don´t work normally.

Create a "text format" for "Filtered text (user selects text format)" and set the "Text format" to "Plain text".
> 0 votes

# Answer
This great module can help you https://drupal.org/project/wysiwyg\_linebreaks

> Wysiwyg Linebreaks allows users of wysiwyg editors to save and open markup from their website with linebreaks instead of `<p>` and `<br />` tags.
> -2 votes

---
Tags: 7, input-formats
---


# Question
Title: Taxonomy exposed filter with parent hierarchy only
I have a taxonomy vocabulary with terms in hierarchical order. If I use an exposed filter, with level depth, all terms are listed, which are \> 6,000. I want only the parent terms, which are only around 30.

I found here the following code (I adapted it to my case). It is an answered question, but obviously it does not apply efficiently to my case, because though it does what is suppose to do, it goes through every item and as a consequence is extremely slow (several seconds). Is there a better way that does not directly make a db\_query to the taxonomy database tables or use a hook (PHP) ?

```
function mymodule_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if($form['#id'] == 'views-exposed-form-search-page-page'{
    foreach ($form['term_node_tid_depth']['#options'] as $term_key => $term) {   // Check if this isn't the 'ANY' option
      if($term_key !== 'All') {
        // Check if this is a child by looking for '-' as first char in string
        $term_value = reset($term->option);
        if($term_value[0] == "-") {
          unset($form['term_node_tid_depth']['#options'][$term_key]);
        }
      }
    }
  } // if
} // function

```

# Answer
> 1 votes
I had a situation like this, i done it by giving a custom options array to the exposed filter in `hook_form_alter()`.

```
 function mymodule_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "views_exposed_form" && $form['#id']=='your-form-id' ){
 $tid_options = get_tid_options();

 $form['your-field-name']['#type'] ='select';
 $form['your-field-name']['#size'] = null;
 $form['your-field-name']['#default_value'] = '';
 $form['your-field-name']['#options'] = $tid_options;
   }
}

function get_tid_options() {
  $cc=array();
  $tax=taxonomy_vocabulary_machine_name_load('machine-name');
  $vid= $tax->vid;
  //Code to find parent terms here according to your vocabulary structure.
  $child_terms = taxonomy_get_tree($vid);
  foreach($child_terms as $values)
  $tid=$values->tid;
  $name=$values->name;
  $cc[$tid] = $name;
 }
return $cc;

```

}

Use taxonomy\_get\_parents or taxonomy\_get\_parents\_all to find parent terms.

May be this will help you..

# Answer
> 0 votes
For listing the zero-level (parent) (or others), it is best to use the Drupal function **taxonomy\_get\_tree**

```
function get_options_of_custom_form() {
    $terms = taxonomy_get_tree(2, 0, 1);
    $options = array();
foreach($terms as $key => $value){
    $options[$value->tid] = $value->name;
} // foreach
  return $options;
} // function

```

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


# Question
Title: Is a MySQL statement from an external script possible?
I'm working with a PM on a Drupal project, and we're having little success finding a developer to answer (what we believe to be) a simple question. I'm afraid I have no Drupal experience to speak of.

We've made well aware that Drupal itself doesn't use MySQL statements per se, but it is MySQL based, so - is it possible to write a SQL statement to find all users that have purchased a particular product/sku? The SQL is to be used in an external script, outside of the website itself.

The developer is vague, at best, so I can't be any more specific than the fact that it's Drupal 7 using a standard ecommerce package. I absolutely *hate* asking a broad question like this, but we're locked into this particular resource, and is insisting it will take 100+ hours to get this data to us, and I am unable to get to the DB to even try to construct the SQL.

Any advice is appreciated! (and if you want some contract work, I'd be MORE than happy to talk).

**Clarification**

Again, I know this is vague, and the SQL itself would be a bonus in the answer. The challenge is that the developer *insists* that Drupal doesn't use SQL statements, and therefore an external script isn't possible because it will take 100 hours to write a Drupal module to get that the result of the query. I'm imagining something like this to determine if/when a customer last ordered product #1234.:

```
SELECT MAX(o.orderdate)
FROM users AS u
JOIN orders AS o on o.userid = u.userid
JOIN orderitems AS i on i.orderid = o.orderid
JOIN products AS p on o.productid = i.productid
WHERE u.email = 'somecustomer@example.com' AND o.productid=1234

```

With my limited Drupal experience, I know that this example isn't close to correct, but in principal, this is what we need to execute on a different server, with different software to simply get a date or a null. If she'd give us credentials to *look* at the database, I could probably figure it out, but her "position" in the matter is that it can only be done with this exhaustive module development effort that she seems to want to do.

# Answer
Drupal does use SQL statements to communicate with the database, however it does so through a built in abstraction layer. That said, you can write regular old SQL from any PHP script to query the information you need, as long as you have the database connection info. Personally I would build whatever functionality you're after into a custom Drupal module, and then use that to interface with whichever external service you're working with. We would need a bit more information on exactly what you're trying to achieve to provide more specific feedback however.
> 3 votes

# Answer
Yes it's absolutely possible, but almost certainly not the best way to do things.

Drupal uses MySQL (or equivalent) to store data, so it has to use SQL statements to store data. This is done at the core level (meaning the vast majority of developers will never need to write SQL statements for their Drupal development). Instead, developers call various Drupal functions that will run the appropriate SQL statements. Basically you can think of it like this: as a developer, you tell Drupal you want to save a certain object type and it will translate your object into SQL statements that save it in the database the best way it knows how.

Drupal saves data in dozens of tables. A user might have their information saved in half a dozen tables, and your products could be saved in many more. To find the history purchases of users via SQL statements is probably more difficult than hiring a developer to write a custom module that would be able to calculate that for you and potentially even track and display purchase trends going forward in a much cleaner way. As far as the 100 hour estimate, I'm not sure.. I'm betting that some e-commerce modules already store this historical purchase information and they could probably be setup in an hour or so. Others might not have that functionality and will need some custom code that could take 100 hours, sure.

Instead of insisting on running SQL statements to run your reports, find out which modules your e-commerce store is using (perhaps ubercart?). Then do some research to find out of that module already offers the functionality you're looking for (or ask your developer to do that research). If not, a custom module might be required, otherwise other modules (like the rules module) could be sufficient.

I highly recommend you do not run external SQL scripts. If you do, I highly recommend you do not hire a Drupal developer to do it and instead hire a Database Administrator (which is probably much more expensive than a Drupal developer). Instead, you should hire a Drupal developer with the following experience:

1. Has developed a Drupal module (more than just hello world)
2. Has experience with the e-commerce module your Drupal site uses
3. Understands what MVC is and how Drupal implements MVC
4. Has at least 3 years of PHP experience

That developer will be able to tell you the best way forward for your case.
> 1 votes

---
Tags: external-scripts
---


title: Converting Drupal Content Types

text:
# Question
Title: Converting Drupal Content Types
What are the steps needed and modules required to convert a large number of nodes from one content type to another, both in Drupal 7. They are fairly simple. If you know of a good tutorial that would be great too.

All my searching seems to bring up migrate which I thought was from 6 to 7.

I've tried node convert but I'm not sure how to use actions or if it can do many nodes at once.

And would it be possible for the URL alias and the taxonomy selections to be transfered?

# Answer
Have a look at the Node Convert module.

> Node Convert adds a menu tab "Convert" on the node view page, i.e. node/1/convert, which gives the ability of converting the node from its current node type to another node type. Also it gives the ability of transfering all the custom CCK field values of the current node type to the destination CCK fields, or discard them. As of 5.x-1.4 you can bulk convert many nodes of the same type, to another one that can be accesed in Administer → Content → Convert Nodes.
>
> The module has been tested on converting node types with the following CCK fields:
>
> * Text
> * Number
> * Image
> * Node reference
> * User reference
> * Link
> * Date
> * Datestamp
> * Email
> * Audio
> * Video

Here is the documentation for the module: https://drupal.org/node/291564
> 1 votes

# Answer
Two different ways to use node convert for converting a lot of nodes:

1. Use the node convert API, this requires writing some PHP, just like with Migrate, but it's probably a lot simpler to wrap your head around.
2. Use node conversion templates with Views Bulk Operations, see also d.o: Create node conversion templates.
> 1 votes

---
Tags: 7, nodes, migrations, views
---


# Question
Title: show specific number of posts on front page for mobile d7
I would like to show only a few posts for mobile I have mobile\_detect as well as mobile\_detect\_ctools mobile\_detect\_variables, installed and working.

I am using an adaptive theme, `$is_mobile` successfully in theme/page.tpl but I am unable to use it in settings.php where I believe I need to set.

`$conf['default_nodes_main'] = $mobile-frontpage-post-number //(much lower than desktop);`

How can I put global `$conf` vars in page.tpl or get `$is_mobile` from mobile\_detect\_variables working in settings.php.

tyvm.

# Answer
> 1 votes
I ended up just redirecting the mobile devices to mobile front page(view), I was trying to avoid this, but it does not seem to be much trouble.

Add this code near the top of MYTHEME/page.tpl.php

```
<?php if ($is_mobile == TRUE && drupal_is_front_page()):
drupal_goto('/mobile');
endif;
?>

```

Then you can adjust the pager, number of posts etc. I suppose this is a workaround not an answer.

---
Tags: 7, theming
---


title: Omega 4: manually installing a subtheme

text:
# Question
Title: Omega 4: manually installing a subtheme
Just learning Omega 3 and 4 is out so I'm switching to try it out, but.. how does one install a subtheme manually? My drush is whacked and I already running multiple installs so I just want to do it manually.

However, copying the "default" folder to the sites/all/themes/ folder... there is no info file... so I duped the one in Omega, changed the name and it shows in the Appearance menu. However, the name isn't correct and I've gone through the few files to see what to change to my themes name but there was only one file.

So, I enabled one, it enables, but then when I click "Settings" next to that theme, I get the WSOD.

Seems not to be the same process as in D6 or even Omega 3. Anyone installed a subtheme of Omega 4 yet manually?

# Answer
> 2 votes
go the omega theme folder omega\starterkits select : default or extended folder and copy in site/all/themes . change folder name default or extended to your subtheme name for example "alex".

go to your theme folder finde the extended.starterkit.inc or default.starterkit.inc and change to your theme name in my case is: alex.info

open alex.info and change name and description of your subtheme.

# Answer
> 1 votes
Use drush it will solve your problem cd to *.../sites/all/themes*

run

```
drush omega-wizard

```

and follow the steps

# Answer
> 0 votes
run `drush omega osup [themename]`

# Answer
> 0 votes
1. This method used for Omega 3 and 4 which I advise.

> ```
> 1) Install Omega theme
> 2) Download drush7.x from [here][1]
>    http://docs.drush.org/en/master/install/#windows-zip-package
> 3) Unzip the file some where safe (I am using wampserver so I have placed in into C:\wamp\bin\windrush)
> 4) Add the drush to your windows command so you can call drush from commandline.
>    Go to => start windows/ system / Advanced system settings/ Environment Variables / Select Path from system variables / Edit / add the drush path to here e.g. ;C:\wamp\bin\windrush; don't forget to use ";" to separate the paths.
> 5) now open you command line and enter
>
>    drush omega-subtheme name-of-sub-theme
>
> ```

2. You should be having a new sub-theme in drupalsites/all/themes/name-of-sub-theme

But if you are using Omega 3 the other option would be simply install "Omega Tools" module to create subtheme (Bear in mind Omega 4.x should NOT be used with Omega Tools and Delta)

---
Tags: theming
---


title: Issue with Entity Reference and Views

text:
# Question
Title: Issue with Entity Reference and Views
I'm needing to change the 'Entity Selection' mode on an entity reference field for a content type from 'Simple' to 'Views: Filter by an entity reference view'.

However, the 'Views: Filter by an entity reference view' option does not appear. 'Simple' is the only option. I have tried creating new test fields to see if it's an issue with that particular field, however this issue persists across new fields as well.

Additionally, I've noticed that if I try to create a new view, the option to change the display type to 'Entity Reference' is also missing.

I've been unable to determine what is preventing these options from appearing, and I'm wondering if the issue might be with either the Entity Reference or Views modules themselves. I haven't been able to locate someone with a similar problem on Stack Overflow or the Drupal forums yet.

Any thoughts on what I might be overlooking that could be causing this?

# Answer
> 1 votes
Looks like it was an issue with the Entity Reference module after all.

This site is part of a multi-site setup that was using an older version of Entity Reference which I was hesitant to update due to potential repercussions. After updating the module, everything is working as intended.

---
Tags: views, entities
---


# Question
Title: Why does simpletest report a missing schema for my custom module?
My custom module is working as expected with the following settings, config and config export. But when I try to run tests, I get the following error. I'm not sure what is wrong.

> Drupal\Core\Config\Schema\SchemaIncompleteException: Schema errors for riddler.settings with the following errors: riddler.settings:riddles missing schema in Drupal\Core\Config\Testing\ConfigSchemaChecker-\>onConfigSave() (line 102 of /var/www/sb/sboss/docroot/core/lib/Drupal/Core/Config/Testing/ConfigSchemaChecker.php).

```
# settings.yml
riddles:
 -
    question: 'Do you really hate Spam?'
    response: 'Yes!'
langcode: en

--------------------------------

#schema
riddler.settings:
  type: config_object
  riddles:
      question:
        type: label
        label: 'Question'
      response:
        type: label
        label: 'Response'

#config export

riddles:
 -
    question: 'Do you really hate Spam?'
    response: Yes!
  -
    question: 'What''s your favorite primary color?'
    response: 'blue, yellow, red'

```

# Answer
Here's what worked.

```
riddler.settings:
  type: config_object
  mapping:
    riddles:
      type: sequence
      sequence:
        type: mapping
        mapping:
          question:
            type: label
            label: 'Question'
          response:
            type: label
            label: 'Response'

```

Thanks to chx for getting this most of the way there.
> 1 votes

# Answer
There are several errors. You missed a type for riddles and tried to define a mapping immediately under, but riddles is a sequence and each element in the sequence is that mapping. This is probably what you wanted.

```

riddler.settings:
  type: config_object
  mapping:
    riddles:
      type: sequence
      sequence:
        type: mapping
          question:
            type: label
            label: 'Question'
          response:
            type: label
            label: 'Response'

```
> 1 votes

---
Tags: 8, configuration
---


title: Merging multiple feature modules

text:
# Question
Title: Merging multiple feature modules
It looks like I went a bit too overboard with number of features modules on my website (~50), but it really made initial development easy (for multiple people). Now the question is - what would be a safe procedure that would allow to merge them into less number of beefier features?

Is creating those new ones with "Allow conflicts to be added" option, and then disabling and UNINSTALLING the smaller ones safe? Should I firstly enable conflicting new modules? What is the order and procedures?

# Answer
> 3 votes
Sometimes the best way to merge/split features is to edit the module code directly. It's pretty straightforward where everything is laid out in a module created by Features. And it's a great way to start learning module development (if you're new to it). Just start at the \*.info file - that's where Features describes all the various things it manages in the module. Then you can pretty easily find those things in the \*.module file and other \*.inc files. Just clone the whole module, rename it and all the files, search and replace all occurrences of the name in the code, then remove the stuff you don't want in each.

---
Tags: 7, features
---


# Question
Title: Global Filter as main menu drop down link
I'm looking for right steps to implement Global Filter module not as a block, but rather as an *main menu* links. The biggest problem is that each user can see only links they have access to (taxonomy access). So it's not possible to make these links static.

I've tried to include a block in the menu link, but that's not what I want.

Has anybody an idea where I could begin?

# Answer
> 1 votes
To rewrite your taxonomy URLs (you should probably rewrite your question to this end) you can use the following.

```
/*
 * Modify taxonomy uris to point back to facetted search
 */
function my_module_entity_info_alter(&$entity_info) {
  $entity_info['taxonomy_term']['uri callback'] = '_my_module_term_uri';
}

/**
 * Rewrite term URIs to point to our search query.
 */
function _my_module_term_uri($term) {
  $path = null;
  // Do your stuff to get your path correct.

  // Return your path if you've managed to rewrite it.
  if ( $path ) {
    return array(
      'path' => $path,
      'options' => array(), // url style options
    );
  }

  // Otherwise just return the default.
  return taxonomy_term_uri($term);
}

```

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


# Question
Title: Drupal Commerce have customer choose how many items to buy
I would like to give my customers an option of how many products to buy. So I would like to have a page (or view) that gives the user the option to but 1, 3, or 6 items of my product each with a little more discount. For example: 1 for $3.50 3 for $7.50 6 for $10.00

And have those three options displayed next to each other.

Also, I would like to give the customer no other quantities. It is either 1, 3 or 6 items that they can buy.

Anyone knows how to do this?

# Answer
You could just create 3 separate products in Commerce to represent each quantity. This makes sense especially if you only have a few like you describe. Each "bundle" product can have it's own SKU/model number, and it's own price. This also provides historical record, if you change your bundles in the future, you can keep the old SKU but archive it, and make a new one to represent your new pricing/quantities.
> 0 votes

# Answer
I think the easiest solution would be to edit the view commerce cart form and change the select box showing the quantity to contains just 1, 3 and 6.

```
function yourmodule_form_alter(&$form, &$form_state, $form_id) {
   if (strpos($form_id, 'views_form_commerce_cart_form_') === 0 ) {
      //change the select option here
   }
}

```

For the discount option, I think you should change the checkout page and deduct the amount that you want to give concession on and show the user that you're giving this concession based on buying 1 or 3 or 6 products.
> 0 votes

---
Tags: commerce
---


title: Field Class Dependencies

text:
# Question
Title: Field Class Dependencies
The question is pretty straightforward. How can I add a class on field A, if field B is empty? I can not find any module does this feature. The Conditional Fields does not have the class feature too. Can this done by programmatically? If so, how?

# Answer
> 2 votes
One solution here is is to use `template_preprocess_field` function. In your **template.php** add a `MYTHEME_preprocess_field` function and perform a check on the node's field value to determine a class that you set in the `classes_array` variable.

```
function MYTHEME_preprocess_field(&$variables) {
  $node = menu_get_object();

  //Add a new CSS class to field_MYHIDDEN_FIELD
  if($variables['element']['#field_name'] == 'field_MYHIDDEN_FIELD') {

    //Check field_MYCHECKED_FIELD for an empty value
    $new_class = (!isset($node->field_MYCHECKED_FIELD[LANGUAGE_NONE][0]['value'])) ? 'mytheme-field-novalue' : 'mytheme-field-value';
    $variables['classes_array'][] = $new_class;
  }
}

```

# Answer
> 1 votes
I would use states for something like this:

https://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7#states

# Answer
> 1 votes
Another more pure UI route is to use Views, Views "No Results" and View "Rewriting" and either the EVA or ctools Content Panels to construct the node view.

I haven't tested this, but it will look something like this:

1. Create a content view filtering by node and published value
2. Add fields B and A (in that order)
3. Set Field A to "Exclude from Display"
4. Configure field B's "No results behavior" to render something like `<span class="b_empty">[field_a]</span>` but set the "Rewrite Results" to `<span class="b_has_data">[field_a]</span><span>[field_b]</span>` Here, field B is doing all the heavy lifting, empty or not.
5. Using EVA, you can then attach that result to your node's field display as you need.

---
Tags: 7, entities, theming
---


title: Custom Image Background in Block

text:
# Question
Title: Custom Image Background in Block
I tried Dynamic background module but it seems it's not what I am looking for. Is there such a module that will allow me to change the background for a certain pages or group of pages that works the same like block?

Like in Block, I can select which pages this block will be shown.

Example:

```
    Show background on specific pages
         All pages except those listed
         Only the listed pages

```

I believe there's a module that can do this, I would be very glad if somebody can point me to the URL of the module.

Thanks in advance.

# Answer
> 1 votes
You can do it via a class that you selectively add to the pages, then using CSS add a background. Two modules stand out:

Node Class

> Node Class is a simple module that allows users to add custom CSS classes to any node through the node/add interface.

Context

> Context allows you to manage contextual conditions and reactions for different portions of your site. You can think of each context as representing a "section" of your site. For each context, you can choose the conditions that trigger this context to be active and choose different aspects of Drupal that should react to this active context.

See also:

Is it possible to add css class to the page's body tag with rules when certain conditions are met?

and

Context Block Classes

# Answer
> 0 votes
Check out these module :

Jq maphilight

> 1. provides simple interactive graphics via HTML image maps (no flash required).
> 2. easy to use: either select the 'highlight all image maps' default \> setting or simply add class="jq\_maphilight" to the tag of any specific image map you wish to highlight.
> 3. no jquery or javascript knowledge required: plugin configuration is handled via an admin/settings screen rather than having to enter jquery code.
> 4. fully configurable: options for fill, fill color, fill opacity, outline, outline color, outline opacity, outline thickness, as well as a fade effect.
> 5. per image map settings: add image map specific options with an additional class.

qTip

> qTips are stylish tooltips that can be configured and styled (more to come in later releases) to fit nearly any website's design.

Background Images Formatter

> 1. You want to display a image on the back of a div when viewing a particular node.
> 2. You want to display a random image on the back of a div on the frontpage only. This can be done using Views. Create a block, select the "Background Image" formatter for your image field, save, place the block, boom, you're done.

or you can do it by using node id or create hierarchy of css

---
Tags: 7
---


title: Include images in Aggregator feed

text:
# Question
Title: Include images in Aggregator feed
Drupal 7. I'm bringing in an RSS feed, and for the most part it's working. It's not, however, bringing in the images with each entry. I tried adding an to the list of allowed tags in the admin screen, to no avail. The lines come across as this:

```
<media:thumbnail url="http://www.bjtonline.com/uploads/tx_bjt/FINAL3_Flexjet_thumb_b.jpg"/>

```

Any ideas?

# Answer
> 0 votes
As I've not gotten anywhere with this, I'm working around it. I'm only interested in bringing in the most recent article from a site that's on our own servers - so I'm writing a script that will import it into the node table and I'll use Views for the block.

I'll set the script to run nightly. Thanks for the help guys.

# Answer
> 0 votes
You can use Feeds: MediaRSS module to fetch `media:thumbnail` type of data.

This is from the projects page, currently only supports following media types.

> media:content - WORKING
>
> media:title - WORKING
>
> media:description- WORKING
>
> media:keywords (csv)- WORKING
>
> media:thumbnail (url) - WORKING
>
> media:categories (csv)- WORKING
>
> media:player (url) - WORKING

For further reading on media rss: http://www.rssboard.org/media-rss

---
Tags: 7, feeds
---


# Question
Title: How to replace a taxonomy term by its description?
In drupal 7.39, I have created a taxonomy vocabulary called **TYPE**. Inside this vocabulary I have added list of terms called **CLOSE**, **END** and **INITIAL**.

By default, when I view the node page it will show the Taxonomy term as **CLOSE**, **END**. But I don't want this, instead of the **CLOSE** term it should be replaced with the description specified in the **CLOSE** term.

Any suggestions about how to do this?

# Answer
> 4 votes
You can achieve your requirement using view. In view configuration, add relationship to "Content: Taxonomy terms on node", then add "Taxonomy term: Term description (Term description)" field.

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


title: Drupal Commons Completely private posts

text:
# Question
Title: Drupal Commons Completely private posts
How can I give users the opportunity to make few posts completely private (i.e. visible only to themselves)? I'd like to do this with a *make this post private - only for me* checkbox.

# Answer
> 0 votes
Content Access

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

Or you can do by allow permission to allow specific viewer/role

---
Tags: 7
---


title: Render tabs as vertical tree

text:
# Question
Title: Render tabs as vertical tree
How do I render `$tabs` used in **page.tpl.php**, not horizontally, but as a vertical tree so the secondary tabs will be placed under/in the parent?

**This is what I got:**

```
<h2 class="element-invisible">Primary tabs</h2>
<ul class="tabs primary">
    <li><a href="#">Item 1</a></li>
    <li class="active"><a href="#">Item 2</a></li>
</ul>
<h2 class="element-invisible">Secondary tabs</h2>
<ul class="tabs secondary">
    <li class="active"><a href="#">Child item 1</a></li>
    <li><a href="#">Child item 2</a></li>
</ul>

```

**This is how I want it to be:**

```
<h2 class="element-invisible">Primary tabs</h2>
<ul class="tabs primary">
    <li><a href="#">Item 1</a></li>
    <li class="active">
        <a href="#">Item 2</a>
        <h2 class="element-invisible">Secondary tabs</h2>
        <ul class="tabs secondary">
            <li class="active"><a href="#">Child item 1</a></li>
            <li><a href="#">Child item 2</a></li>
        </ul>
    </li>
</ul>

```

How do I achieve this without using javascript? I'm currently using `render($tabs);` to get something similar to the output above.

# Answer
> 0 votes
Basically after examining the code example from the example module, I've found that the **vertical\_tabs** are the container of the different **fieldsets**, and the title of the **fieldset** is the vertical tab's title. All tabs are connected to the **vertical\_tabs** through the **#group** attribute. It's that simple...

```
$form['additional_settings'] = array(
         '#type' => 'vertical_tabs',
         '#weight' => 99,
      );

      $form['vertical_tabs_example2'] = array(
      '#type' => 'fieldset',
      '#title' => t('Example vertical tab2'),
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
      // The #group value must match the name of the vertical tabs element.
      // In most cases, this is 'additional_settings'.
      '#group' => 'additional_settings',
      // Attach the javascript for vertical tabs.
      '#attached' => array(
        'js' => array(
          'vertical-tabs' => drupal_get_path('module', 'vertical_tabs_example') . '/vertical_tabs_example.js',
        ),
      ),
      '#tree' => TRUE,
      '#weight' => -2,
    );

      $form['vertical_tabs_example'] = array(
      '#type' => 'fieldset',
      '#title' => t('Example vertical tab1'),
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
      // The #group value must match the name of the vertical tabs element.
      // In most cases, this is 'additional_settings'.
      '#group' => 'additional_settings',
      // Attach the javascript for vertical tabs.
      '#attached' => array(
        'js' => array(
          'vertical-tabs' => drupal_get_path('module', 'vertical_tabs_example') . '/vertical_tabs_example.js',
        ),
      ),
      '#tree' => TRUE,
      '#weight' => -2,
    );

```

---
Tags: 7, routes
---


# Question
Title: Default images also as user selected image functionality
I have a content type with a taxonomy and based on that taxonomy, I want to have a default image to show unless the user wants to upload a different image. I'm not sure how to go about this functionality. Is there a module that should one could recommend or any suggestions?

I have used this to display taxonomy images https://www.drupal.org/node/1224916 and it works great but it doesn't give the user the option to upload their own pic.

# Answer
Representative\_image

> Allows you to define representative image or media fields for entities like nodes, taxonomy terms and the like. These can then be used in Open Graph meta tags (via tokens); or as fields in views. The media module is also supported. A default image can be defined for those entities without images.
> 0 votes

---
Tags: taxonomy-terms, media
---


# Question
Title: Running cron without setting a cron job on web server
I know that in Drupal 7 *Poormanscron* is part of the core, but to have cron running I need the site must be visited regurarly and it's not my case. I can't set up a cron job on web server to periodically run cron.

Is there any way to run cron periodically without setting a cron job on web server?

# Answer
> 1 votes
Yes indeed, Drupal exposes a URL to invoke cron, e.g.

```
http://www.example./com/cron.php?cron_key=ka_88ikb7ZbkszCQo6_GtZclwUsUsskfH54oOJqqBcE

```

Which you can call from anywhere, using whatever method you like (pingdom jumps to mind, for example). Obviously if your site is an intranet or something you'll need to work out how to route that request either from the internal or external network, but Drupal has you covered however you decide/need to do it.

You can find your external cron URL by visiting the status report at /admin/reports/status.

Note that if you have an advanced cron module like Elysia cron, your external URL may be different. Check the documentation for the specific module to be sure.

---
Tags: cron
---


title: Different page appear when testing

text:
# Question
Title: Different page appear when testing
What I want to do is checking whether a link is exist on frontpage.

I've set up a content with with node id 5 as my frontpage.

But when testing it, and see the verbose message (http://screencast.com/t/ldWSBwJNcO) different page appear. The default drupal frontpage appear instead of the content that I've set up.

My test code:

```
class MyUserManagementTestCase extends DrupalWebTestCase {

  // Some says this improve tests performance
  protected $profile = 'test';

  public static function getInfo() {
    return array(
      'name' => 'My User Management Test Case',
      'description' => 'Ensure that the My functionality for user management works.',
      'group' => 'My',
    );
  }

  public function setUp() {
    parent::setUp();
  }

  public function testFrontpage() {
    $this->drupalGet('');
    $this->assertResponse(200, t('Frontpage page is accessible'));
    $this->assertLinkByHref('user/register');
    $this->assertLinkByHref('user/login');
  }
}

```

# Answer
In Simpletest each time the test is run. New Drupal install will occur. You are testing the Simpletest Database right now. There is a possibility to run simpletest on "live" db. To do so add `$this->originalPrefix = $GLOBALS['db_prefix']` to your `setUp()`
> 0 votes

---
Tags: testing
---


# Question
Title: What happens if a user uploads an image but doesn't save the node?
I would like to know what happens if a user uploads an image by `image` field but doesn't save that node?

It seems that image will be in the directory but no node refers to it. Is there anyway to remove such files?

# Answer
The image files will be removed during cron runs.

This happens because the `status` column in `file_managed` for those files will still be zero, indicating that they're temporary, and can be safely removed after a period of time.

The responsible code is in `system_cron()`, in case you need to reproduce/analyse further.
> 15 votes

---
Tags: 7, nodes, media, files
---