# Question
Title: Expose a custom view filter based on custom field in another node
I want an user configurable boolean view filter, displaying child nodes in an hierarchy based on a value, *canDisplayOthers*, in the master node. The master/children are joined by a field *setID*.

I tried to do a self-join, adding a view relationship based on *setID*, but *setID* is not in the list of relationship fields.

Using Php, the recipe in:

https://ohthehugemanatee.org/blog/2013/12/26/44497-people-are-wrong-how-to-never-use-views-php/

says to use a handler. My handler would return a boolean, something like:

```
class mymodule_handler_field_isDisplayable extends views_handler_field {
  /**
  * Render the name field.
  */
  public function render($values) {
    $value = $this->get_value($values);
    /*
       How can I get current node ID (nid) here?

    */
  }
}

```

and a hook\_views\_data something like:

```
function mymodule_views_data() {
  // Basic table information.
  $data['mymodule_ToDisplay'] = array(
    'table' => array(
      'group' => t('Global'),
      'base' => array(
        'title' => t('ToDisplay')
        ),
      ),
    'name' => array(
      'title' => t('ToDisplay'),
      'field' => array(
        'handler' => 'mymodule_handler_field_isDisplayable',
      )
    ),
    'filter' => array(
    'handler' => 'views_handler_filter_boolean',
    )
  );
  return $data;
}

```

I can't figure out:

1. in mymodule\_views\_data, what is this thing called 'table'?
2. how do I get the setID or current nodeID into the mymodule\_handler\_field\_isDisplayable function?

In curiosity; \- what is the minimal hook\_views\_data? \- Where is a good place to find where hook\_views\* parameters are explained?

I am using drupal7 and views 3

ADDITION 15 July 2014

Geoff, below, kindly mentioned that the problem would be easier if I created a master node content type. I created a masterNodeType content type, containing the fields:

* setID
* canDisplay

Now, masterNodeType and childNodeType have the common field, setID, but I can't see setID when I configure the view relationship. How do I get setID, and/or masterNodeType into the view relationship? What is the criteria for those view relationship components?

# Answer
Thanks to the clues provided by Geoff in a comment, I found the answer.

My mistake, (doing too much work), was to create my own foreign key, *test\_set\_id*. Drupal uses node\_reference fields for such joins. Using node reference, associated content can be directly accessed after adding the relationship in the set-up view screen, without any code.

I also ended up creating an additional *master* parent content type, to hold some generic test\_set information, and to give the child nodes something to point to.
> 1 votes

---
Tags: views
---


# Question
Title: How to send a message to users who flagged a taxonomy term?
I want to send a message to users who have flagged, for example, the *Toys* taxonomy term. But only when a new node is created and contains the taxonomy term of Toys.

Any suggestions?

# Answer
I would create this using a Custom PHP code in Rules and execute the following conditional code on 'After saving new content of type...' event trigger :

```
if( count(taxonomy_get_term_by_name('[node:field-tags]')) ) return TRUE;
else return FALSE;

```

Then create an 'action to send an email'.

Requires
-PHP Filter,
-Rules.
-Here the content type assumes the default 'Article' with default Tags field 'field\_tags'

```
{ "rules_tst" : {
"LABEL" : "Test Rule",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "php" ],
"ON" : { "node_insert--article" : { "bundle" : "article" } },
"IF" : [
  { "php_eval" : { "code" : "if( count(taxonomy_get_term_by_name(\u0027[node:field-tags]\u0027)) ) return TRUE; \r\nelse return FALSE;  " } }
],
"DO" : [
  { "mail" : {
      "to" : "me@mine.com",
      "subject" : "test subject Toys confirmed!",
      "message" : "There are toys to play with!",
      "language" : [ "" ]
    }
  }
]

```

} }

I ahve included an importable for you to test.
> 1 votes

---
Tags: rules, flags, privatemsg
---


# Question
Title: How can I find what nodes are causing 404 errors?
I'm watching entries in my *Top 'page not found'* report page steadily rise.

I am unable to fix the 404 errors because I have several hundreds of nodes, and there is no indication of which node is causing the problem.

Is there a way I can see which nodes are causing the 404 errors?

# Answer
Try a the "Recent log messages" report and apply a filter to show you only the "page not found" logs. You will then see a list of pages not found and you can click on the message to find out more details about it.

If the problem is that a lot of pages change their path then you might want to use the "Path Redirect" module (http://drupal.org/project/path\_redirect) if you are using Drupal 6 or the "Redirect" module (http://drupal.org/project/redirect) if you are using Drupal 7 to let search engines know about the new path of the content.

**Note:** if you have clean URL setup make sure it is working and you are not missing the .htaccess file. It happen to me once when I move a site from dev to production and I didn't copy the .htaccess file.
> 4 votes

# Answer
Install the Redirect module and visit `admin/config/search/redirect/404` on your site. You will see a report like this, which makes it very easy to identify the most "popular" missing pages, and create matching redirects to the correct location(s).
> 2 votes

---
Tags: nodes
---


# Question
Title: delete users and all its related records
Is there a way I could run mysql query from the backend to delete all the users and its related records except master-login.

There are some modules that help to do it or a via drush command but I am trying to do this from the backend database.

I am not sure about the how all the tables are maps. instead of figure it out I am trying to get a quick help here.

# Answer
> 1 votes
No.

You can install the Delete All module which provides some command line Drush commands to remove all content and users *safely*.

> This module is used to delete all content and/or users from a site. This is mainly a developer tool, which can come in handy in several cases, listed below.
>
> The usual way to do this is to go to Administer -\> Content then select all the nodes and delete them. This works if you have a handful of nodes only. If you have hundreds or thousands of nodes, then it is not a practical solution.
>
> Another option is to directly delete the nodes from the node table in the database. This does not work properly, since there are also comments, and many tables for add on modules that needs to be cleaned.
>
> * This is a test site that the client was using for a period of time, and they must clean it up before starting with real data.
> * You are testing something that creates a lot of nodes (e.g. aggregator), and want to do it over and over again.
> * You created a site in the past and want to replicate it again, but with new content.
>
> Note that for nodes, comments and all additions to nodes that contributed modules may have added. For users, any additional module data will also be deleted.

# Answer
> 0 votes
Use the following script to delete all users.

```
$table_select = db_select('users', 'u')
              ->fields('u',array('uid'))
              ->condition('name','master_login_name','!=') // Put admin name here in place of 'master_login_name'
              ->execute()
              ->fetchAll();

foreach($table_select as $users)
{
user_delete($users->uid);
}

```

user\_delete function will delete users from drupal tables.user\_delete

---
Tags: database
---


title: How do I use CkEditor with email?

text:
# Question
Title: How do I use CkEditor with email?
I'm trying to do the following to allow the CkEditor to be used with a rule-based email.

```
function mymodule_form_rules_ui_edit_element_alter(&$form, $form_state, $form_id) {
  $form['parameter']['message']['settings']['message']['#type'] = 'text_format';
  $form['parameter']['message']['settings']['message']['#format'] = 'full_html';
}

```

I receive the following warning.

> Warning: htmlspecialchars() expects parameter 1 to be string, array given in check\_plain()

The email I receive contains *Array* as body. It seems like I am hitting the issue described on Add a method for easily enabling CKEditor on a specific textarea.

Is there a way to convert the output of CkEditor into a string?

# Answer
I had the same problem and I figured it out myself how to resolve it.

You should use a *text\_formatted* field, not *text\_format*, otherwise the Rules module cannot correctly render the field. You need to use a different `hook_rules_action_info_alter()` to change the field type, as in the following code.

```
function mymodule_rules_action_info_alter(&$actions) {
  $actions['mimemail']['parameter']['body']['type'] = 'text_formatted';
  $actions['mimemail_to_users_of_role']['parameter']['body']['type'] = 'text_formatted';
}

```
> 2 votes

---
Tags: 7, rules, wysiwyg
---


title: Custom field Rules implementaion

text:
# Question
Title: Custom field Rules implementaion
I added new "Markup" field into commerce\_product table using custom module. Now I need to create a rule to calculate (sell\_price=prod\_price\*markup), but I can't acccess Markup field throught Rules selectors. Is there a UI , or what hooks should I implement to solve that problem? Here is complete comm\_markup module code:

```
function comm_markup_schema_alter(&$schema) {
  $schema['commerce_product']['fields']['markup'] = array(
    'type' => 'float',
    'not null' => TRUE,
    'default' => 1,
    'description' => 'Price markup field',
  );
}

function comm_markup_install() {
  $schema = drupal_get_schema('commerce_product');
  db_add_field('commerce_product', 'markup', $schema['fields']['markup']);
}

function comm_markup_entity_property_info_alter(&$info) {
  $properties = &$info['commerce_product']['properties'];
  $properties['markup'] = array(
    'label' => t('Price markup'),
    'type' => 'decimal',
    'description' => 'Gross price multiplier (defines profit amount).',
    'schema field' => 'markup',
    'getter callback' => 'entity_property_verbatim_get',
    'setter callback' => 'entity_property_verbatim_set',
  );
}

function comm_markup_views_data_alter(&$data) {
  $data['commerce_product']['markup'] = array(
    'title' => t('Price markup field'),
    'help' => t('Multiplier. Adds profit to the gross price.'),
    'field' => array(
      'handler' => 'views_handler_field_numeric',
      'click sortable' => TRUE,
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_numeric',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
  );
}

```

# Answer
Simple UI solution:

Add a condition of "Data Comparison"
Data selector - commerce-line-item:type
Value equals - "Modification" (or whatever your custom line item type is called)

Now when you add a condition that checks for a field, all the fields on that custom line item type should appear. Example, "Data value is empty - commerce-line-item:custom-field". Thanks to trevorkjorlien comment at Drupal.org
> 0 votes

---
Tags: 7, rules
---


# Question
Title: What is the best way to generate node(book) to ePub?
I want to create a Journal site that can generate book(node) to ePub, like Open Journal Systems(OJS). So what is the best way to generate node to ePub? I have tried Printer, but it only show the following error messages on iBook. File generated by PHPePub(Printer) can open by Calibre, but all images are missing.

> **This page contains the following errors:**
>
> error on line 47 at column 27: AttValue: " or ' expected
> **Below is a rendering of the page up to the first error.**

# Answer
> 3 votes
I know this answer is dead simple, but have you tried EPUB Export module?

> This project builds content objects from drupal and bundles them into an EPUB 3.0 document. Currently it will export a rendered entity seperate of all of the page markup and gather all the referenced resources within the content and bundle those into one EPUB document.

I tested it on a clean install and it appears to work as advertised.

---
Tags: files, nodes
---


# Question
Title: How to assign roles in my own registration form
I know about assigning roles and permission in `DRUPAL` admin login where admin can add user and even add new roles (check here) to the new users.

I have a basic registration form in my page and while user register I want to assign roles to them for example - employee, superuser and admin roles.

How do I do it, do I have create a new module and may be use the `ROLE` module functionality in Core `DRUPAL`.

I have also checked this Link which explains about basic Users, roles and permissions in DRUPAL but it does not answer my question.

So

1. I need to create new user in Drupal from my own Registration form.
2. I need to have my own custom roles (eg. employee, superuser and admin roles) - This Link might help me in this
3. This new user which are registering from my own custom registration form, should be assigned with this custom roles(eg. employee, superuser and admin roles).

Can some please tell me how do I do this in `Drupal 7` or Does anyone knows any `Drupal` modules which can help me do this efficiently or should I go with own PHP code.

which will be more efficient way for doing this.

Thanks in advance :)

# Answer
> 2 votes
```
    function company_form()
    {
         $form['company_username'] =  array(
          '#type' => 'textfield',
          '#title' => 'company-username',
          '#default_value' => '',
              '#required'=>'true'
      );
          $form['company_email'] =  array(
          '#type' => 'textfield',
          '#title' => 'company-email',
              '#required'=>'true',
          '#default_value' => '',
          '#element_validate' => array('generate_special_form_validate'),
      );
           $form['company_password'] =  array(
          '#type' => 'textfield',
          '#title' => 'company-password',
               '#required'=>'true',
          '#default_value' => ''
      );

      $form['submit'] =  array(
          '#type' => 'submit',
          '#title' => '',
          '#value' => 'Submit',
          '#default_value' => ''
      );
      return $form;
    }
    function company_form__validate(&$form_state,$form) {

         if (!valid_email_address($form['input']['email'])) {
         form_set_error($form['input']['email'],'Please enter a valid email address.');
       }
    }
    function company_form_submit($form, &$form_state)
    {

     global $user;
        $company_username = $form_state['input']['company_username'];
        $company_email = $form_state['input']['company_email'];
        $company_password = $form_state['input']['company_password'];
         $fields = array(
              'name' => $company_username,
              'pass' =>$company_password,
              'mail' => $company_email,
              'init' => $company_email,
              'status' => 1,
              'access' => REQUEST_TIME,
              'roles' => array(
               4 => 'company',
                ),

        );
        $account=user_save('', $fields);

    if($account->uid)
    {
     drupal_set_message('User Created SuccessFully');
    }

}

```

Firstly you have to create roles from backend. and then You can Assign as many roles by passing `role id` and `role name` in array.

```
'roles' => array(
               4 => 'company',
                ),

```

Hope this code helps you.

# Answer
> 1 votes
Drupal 7 administrator can assign roles to existing users through standard interface. If you looking for additional functionality (i.e. users can choose their roles) take a look at Auto Assign Role module.

If you need to implement your own specific logic use Form API to build and validate your form through custom module.

# Answer
> 1 votes
To do this you might have to use some alter functions.

1. First, have to alter the user registration form to add a new role option list.
2. Second, in the user save, add the role id to the user\_roles table.

```
/**
 * Implements hook_form_BASE_ID_alter()
 */
function CUSTOM_MODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  // Get the system roles.
  $roles = array_map('check_plain', user_roles(TRUE));

  $form['roles'] = array(
    '#type' => 'select',
    '#title' => t('Roles'),
    '#default_value' => array(),
    '#options' => $roles,
  );
}

/**
 * Implements hook_user_insert()
 */
function CUSTOM_MODULE_user_insert(&$edit, $account, $category) {
  // Save the role if it's set.
  if (isset($edit['roles'])) {
    // Push the roles to $account object so that user_save can get the role property.
    $account->roles[] = $edit['roles'];
  }
}

```

---
Tags: 7, users
---


# Question
Title: How to give a content editor access to the theme settings?
I'm using the Marinelli theme and want to give my main content editor access to the theme settings. Ideally just the ability to upload/change/add/subtract/enable the backgrounds of the rotating banner.

I don't see any way for them to do this without full access to the Theme settings. I was able to just give "administer themes" settings to this user and give them a shortcut to that theme. But that's still a lot of liability.

Has anyone been able to do this: limit theme configuration to just certain tasks?

# Answer
You could use a hook\_form\_alter in your custom module.

The following assumes you already have a role called **editor** existing in your website.

1. Create a **mymodule** folder (e.g. in http://www.example.com/sites/all/modules/custom/**mymodule**)
2. Create two files in that folder. **mymodule.module** and **mymodule.info**
3. Past the following code in **mymodule.module**

```
 <?php

  function mymodule_form_alter(&$form, &$form_state, $form_id) {
  global $user;

  if ($form_id == 'system_theme_settings' && in_array('editor', array_values($user->roles))) {
    // unset the elements you don't want your content editor to have access to
    // unset($form['css3']);
    // Here we want to hide some form elements.
    // To hide/show an element we must use $element['#access'] key in the render array.
    // Using unset($element) might cause issues in form_validate and form_submit processes.
    // So instead of unset($form['css3'], $form['layout']) we set their access to FALSE
    $form['css3']['#access'] = false;
    $form['layout']['#access'] = false;
  }
}

```
4. Past the following in **mymodule.info**

name = Mymodule
core = 7.x
5. Enable your module at http://www.example.com/admin/modules
6. Clear your cache

*Please note that these are the minimum requirements for creating a custom module and you should definitely read up on best practices for creating custom module at https://www.drupal.org/node/1074360*
> 0 votes

---
Tags: 7
---


title: Clean URLs aren't being displayed

text:
# Question
Title: Clean URLs aren't being displayed
I want clean URLs like webpage.com/page instead of webpage.com/?q=page, specifically in my menus.

I have gone here http://v6.dev/admin/config/search/clean-urls (which is a clean URL and works) and ticked the 'enable clean URLs' option and saved. But nothing happens, the page reloads without the tickbox checked.

Clean URLs are working, I can navigate to webpage.com/page fine, but the menus aren't being generated as clean URLs.

I have gone through this page: https://www.drupal.org/getting-started/clean-urls but can't solve the problem. I think the servers set up okay, because I can succesfully navigate to clean URLs, it's just that links aren't rendered as clean URLs. I've also tried cleaning the cache, and restarting server.

If it helps, I'm generating menus with this code:

```
<?php
    $menu = menu_navigation_links('menu-top-menu');
    print theme('links__menu_main_page', array('links' => $menu));
?>

```

# Answer
First thing I would check is the .htaccess is indeed working...maybe your getting a cached version of:

http://v6.dev/admin/config/search/clean-urls

What happens when you enter a URI which you know has never existed (and been cached) such as:

http://v6.dev/xxx-237347-3iu33

Does it 404? Does drupal handle it and say "page cannot be found"?

I had a similar issue a few days back...I had to manually disable "clean uri's" in the database...flush all cache tables...re-enable mod\_rewrite...log in and enable clean URI's

Let me know how you turn out. :)
> 0 votes

# Answer
I added

```
$conf = array(
  'clean_url' => 0,
);

```

to the top of the settings.php file ('/sites/default/settings.php) which solved the problem, now clean urls were generated, as well as working to handle requests.

I first added it to the bottom, but this affected the admin theme of the site, adding it to the top instead of the bottom solved that.
> 0 votes

---
Tags: 7, routes, uri
---


title: Comments don't want turn off

text:
# Question
Title: Comments don't want turn off
I forgot to turn off the comments while creating a content type. Now when i set the Comments to Closed, the form for adding a comment is still being displayed in full node view.

Any suggestions?

Thanks!

# Answer
This setting only sets the default for nodes, so already created nodes will still have their comments turned on. Easiest way to update all the nodes is with a couple of SQL statements, back up your database first.

```
UPDATE node SET comment = 0 WHERE type = 'your_content_type';

UPDATE node_revision nrev
  INNER JOIN node nd ON nrev.nid = nd.nid AND nd.type = 'your_content_type'
  SET nrev.comment = 0;

```

then clear cache.

Note that comment can equal the following:

0 = disabled 1 = readonly 2 = read/write.

More details at How to finally disable comments on content type?
> 3 votes

---
Tags: comments
---


# Question
Title: How to display list of files under a particular directory in Drupal?
I've created a custom module to export node data of different content types into Excel (using PHPExcel hooks).

That will be stored into particular directory called "***Reports***" under ***site/all/files*** directory.

Now I would like to display the list of files exists under "***Reports***" directory, in a page/view in a table format.

How can I achieve that?

# Answer
I found a module called Filebrowser for this.

> Allows site administrators to expose a particular file system folder and all of its subfolders with a fancy FTP-like interface to site visitors. File metainformation (via descript.ion and files.bss) is supported. The module also allows these metafiles to store special content, which can be parsed with a callback. If no callback is specified in the file, only the description will be fetched.

This is the exact module what I was looking for. Using this module I could display all my exported files. Here is the screen-shot.

Additionally we can ***Delete*** the files and also download the selected items as an ***ZIP archive*** from here itself.

Hope this post helps someone.
> 7 votes

---
Tags: 7, files
---


title: Translating the homepage

text:
# Question
Title: Translating the homepage
I am quite new to translation of Drupal and cant figure to translate a the page content on the homepage.

The entire site is translate with the normal translation methods offered by Drupal.

I have translated the blocks on the homepage but the home page content always shows in English. I have already changed the homepage alias to 'home' and both translations aswel.

# Answer
> 1 votes
This should get you on the road: https://www.drupal.org/node/1216132

---
Tags: i18n-l10n
---


# Question
Title: Panels "Page not found" when using required wildcard argument
I have a Panel Page, which displays several View Panes. I have specified a term name as an argument in the path settings. This is used to filter the View Panes.

When I use an optional argument everything works fine - `clinical-role/!role_name`. But when I change to a required argument `clinical-role/%role_name` then I get page not found when visiting `/clinical-role` and when visiting `/clinical-role/early-skills-for-non-training-grade-doctors`

I need the argument to be required because I don't want the panel to display when people visit `/clinical-role`.

Here is an export of the Panel Page: http://pastebin.com/ASmFnVU5

Here are my argument settings:

And also my context settings:

# Answer
The problem was that my taxonomy terms had dashes, e.g. `"Early skills for non-training grade doctors"`. When used in conjunction with views contextual filters and the option to `"Transform spaces to dashes in URL"`, it doesn't match properly, so no value for the context is provided. This is related to the following views bug - https://www.drupal.org/node/672606 (no solution as yet for panels but there is a solution if you're just using a view page in comment #16). My solution was to remove all dashes from my term names. Not ideal but fixes the problem.

**Here is how I set things up to pull a taxonomy term name contextual filter into a View Pane**, in case it helps someone. If anyone knows a better way to go about this then please let me know and I will update this answer:

## View Setup - Contextual Filter

## View Setup - Argument Input

This part is counter intuitive, you have to choose "No argument input". Providing a context from panels will prevent the default filter value from being used. Thanks to the following comment for helping me figure this out: Views contextual filters taxonomy name

## Panel Setup

N.b you have to use a panel page here (structure \> pages), so that you can make use of the wildcard feature. I tried this by panelizing a node initially but couldn't get it to work.

Basic settings:

Argument settings:
> 1 votes

---
Tags: 7, panels, views
---


title: entity reference view in a view

text:
# Question
Title: entity reference view in a view
I have 2 content types: location and maintenance.

I would like a view that shows all the locations with a search box at the top so the user can search the right location; when users click on a location, they are redirected to the location details and the maintenance nodes listed under the location details.

So the workflow is like this:

* Search the location
* Click on the location
* See a view with location and maintenance nodes

I have already installed entity reference and made references from maintenance to locations, but I just can't get the view settings right; a list of all the locations is what I am getting, so far.

# Answer
Your existing view listing all locations is fine for now (assuming a path like "/locations"). Create another display in that view (or a complete different view if you want). This second display/view should first get a relationship to the (location) entity referenced by the field "location". Then the view should have a contextual filter on a node id using that relationship; argument should be in the URL, e.g. by using something like "/locations/%/maintenance" as path.

So if you have two locations (nids: 1 + 2) and 4 maintenance nodes (nids: 3-6), you should see all locations at "/locations" and all maintenance for the first location at "/locations/1/maintenance". Now you just need to link from the first view to the second one by using the correct path "/locations/\[nid\]/maintenance" and it should be the way you want it. You can take it a step further by displaying all locations along with the maintenance on a single page. You'll need an additional module (if not yet installed): views\_field\_view.

If that is installed, you can proceed to the next step and include the maintenance view in the location view. Add two new fields, first of type "Content: Nid" and second of type "Global: View". For the latter field choose the maintenance view in the dropdown and enter "!nid" in the argument textbox. By doing this, the current nid of the location is send as an argument to the maintenance view and thus only displaying maintenance nodes that are connected to that current location.
> 0 votes

---
Tags: views, entities
---


title: Image preview using views

text:
# Question
Title: Image preview using views
I want to Create like this type of Image preview on particular related images. I have image fields with multiple images for a content type, and I would like to obtain this effect.

Is there any possibility by creating views? Is there any way to obtain this effect with other ways?

# Answer
> 1 votes
Using Views Gallerific You can solve easily.Please follow the steps from here

# Answer
> 1 votes
# Modules You Need:

1. Views
2. Libraries
3. Views Slideshow
4. Cycle JS : Save this js file to `/sites/all/libraries/jquery.cycle/` where you have to create 2 directories i.e. libraries and under that jquery.cycle

Now assuming your content type name is **IMAGE** with two fields

* Title
* Image

# Add 3 dummy images to your newly created content type IMAGE

Now go to `admin/structure/views/import`

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

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Slideshow';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'slideshow';
$handler->display->display_options['style_options']['slideshow_type'] = 'views_slideshow_cycle';
$handler->display->display_options['style_options']['slideshow_skin'] = 'default';
$handler->display->display_options['style_options']['skin_info'] = array(
  'class' => 'default',
  'name' => 'Default',
  'module' => 'views_slideshow',
  'path' => '',
  'stylesheets' => array(),
);
$handler->display->display_options['style_options']['widgets']['top']['views_slideshow_pager']['enable'] = 1;
$handler->display->display_options['style_options']['widgets']['top']['views_slideshow_pager']['weight'] = '1';
$handler->display->display_options['style_options']['widgets']['top']['views_slideshow_pager']['type'] = 'views_slideshow_pager_fields';
$handler->display->display_options['style_options']['widgets']['top']['views_slideshow_pager']['views_slideshow_pager_fields_fields'] = array(
  'field_image' => 'field_image',
  'field_image_1' => 0,
);
$handler->display->display_options['style_options']['widgets']['top']['views_slideshow_controls']['weight'] = '1';
$handler->display->display_options['style_options']['widgets']['top']['views_slideshow_controls']['type'] = 'views_slideshow_controls_text';
$handler->display->display_options['style_options']['widgets']['top']['views_slideshow_slide_counter']['weight'] = '1';
$handler->display->display_options['style_options']['widgets']['bottom']['views_slideshow_pager']['weight'] = '1';
$handler->display->display_options['style_options']['widgets']['bottom']['views_slideshow_pager']['type'] = 'views_slideshow_pager_fields';
$handler->display->display_options['style_options']['widgets']['bottom']['views_slideshow_pager']['views_slideshow_pager_fields_fields'] = array(
  'field_image' => 0,
  'field_image_1' => 0,
);
$handler->display->display_options['style_options']['widgets']['bottom']['views_slideshow_controls']['weight'] = '1';
$handler->display->display_options['style_options']['widgets']['bottom']['views_slideshow_controls']['type'] = 'views_slideshow_controls_text';
$handler->display->display_options['style_options']['widgets']['bottom']['views_slideshow_slide_counter']['weight'] = '1';
$handler->display->display_options['style_options']['views_slideshow_cycle']['timeout'] = '5000';
$handler->display->display_options['style_options']['views_slideshow_cycle']['speed'] = '700';
$handler->display->display_options['style_options']['views_slideshow_cycle']['delay'] = '0';
$handler->display->display_options['style_options']['views_slideshow_cycle']['start_paused'] = 0;
$handler->display->display_options['style_options']['views_slideshow_cycle']['remember_slide_days'] = '1';
$handler->display->display_options['style_options']['views_slideshow_cycle']['items_per_slide'] = '1';
$handler->display->display_options['style_options']['views_slideshow_cycle']['wait_for_image_load_timeout'] = '3000';
$handler->display->display_options['style_options']['views_slideshow_cycle']['cleartype'] = 0;
$handler->display->display_options['style_options']['views_slideshow_cycle']['cleartypenobg'] = 0;
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Image */
$handler->display->display_options['fields']['field_image']['id'] = 'field_image';
$handler->display->display_options['fields']['field_image']['table'] = 'field_data_field_image';
$handler->display->display_options['fields']['field_image']['field'] = 'field_image';
$handler->display->display_options['fields']['field_image']['label'] = '';
$handler->display->display_options['fields']['field_image']['exclude'] = TRUE;
$handler->display->display_options['fields']['field_image']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_image']['click_sort_column'] = 'fid';
$handler->display->display_options['fields']['field_image']['settings'] = array(
  'image_style' => 'thumbnail',
  'image_link' => '',
);
$handler->display->display_options['fields']['field_image']['group_rows'] = FALSE;
$handler->display->display_options['fields']['field_image']['delta_offset'] = '0';
/* Field: Content: Image */
$handler->display->display_options['fields']['field_image_1']['id'] = 'field_image_1';
$handler->display->display_options['fields']['field_image_1']['table'] = 'field_data_field_image';
$handler->display->display_options['fields']['field_image_1']['field'] = 'field_image';
$handler->display->display_options['fields']['field_image_1']['label'] = '';
$handler->display->display_options['fields']['field_image_1']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_image_1']['click_sort_column'] = 'fid';
$handler->display->display_options['fields']['field_image_1']['settings'] = array(
  'image_style' => '',
  'image_link' => '',
);
$handler->display->display_options['fields']['field_image_1']['group_rows'] = FALSE;
$handler->display->display_options['fields']['field_image_1']['delta_offset'] = '0';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'image' => 'image',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'slideshow';

```

Simply go to your-site/slideshow and Voilà! Feel free to comment if you got stuck or need my help.

---
Tags: 7, views, javascript
---


# Question
Title: How obtain the Distance/Proximity between 2 fields?
I am working on a project (Omega subtheme) with Panels and Views. I'm trying to create a list of local secondary schools and their distance from a few locations.

Installed Location Module, enabled it, together with Location Search, Location Taxonomy, Node Locations and Location CCK. Also, imported list of zipcodes for my location (gb) into database.

Next I created Content Type ‘secodnary school’ with School Location field, containing Address ,Postal Code, City, Country, and Latitude and Longitude fields.

Then I created 3 pieces of content – namely 3 local schools (to start with) with their addresses and lat/long info.

Finally, I tried to create a view that will contain the above list of secondary schools, sorted by their proximity to the given location and to connect it to a different piece of content (page) that holds the location info (address, postcode, latitude/longitude) of different (X,Y,Z) locations. X, Y, Z (…) are pieces of content (pages) of XYZ content type that among other things contain their individual location info.

So I need my new view (lets call it distance\_sec\_schools) to pick up location info from it’s host (XYZ) content (hint: I tried to configure CONTEXTUAL FILTER – content NID to provide content ID from URL – but it didn’t do the trick) and then provide me with the distances to 3 local schools, which I will then sort by proximity criteria.

Take a look at the screenshots of my view and Location: Distance / Proximity - Field Settings (framed red) and Filter (framed blude), which I suspect might be where my problem lies.

At the moment, my view produces a table with the school names but without the distances.

# Answer
> 1 votes
As far as I know it is not built into the location module but can easily be done in php with Haversine Formula, have a look here.

To add it to your view you can use Views PHP or theme a field with views-view-field--your-field.tpl.php passing in the two coordinates.

---
Tags: 7, views, location
---


# Question
Title: Is it possible to extend Drupal's user_access() function to provide a more complex logic for permissions
This question is specific to Drupal 7, and I'm pretty sure that I already know the answer to this, namely that I won't be able to do what I want, but I thought I'd pose it to you Drupal experts.

Is it possible to extend Drupal's user\_access() function to provide a more complex logic for permissions? I know it is possible to create an access callback function that provides more complex logic, but I want it so that every function that calls the user\_access() function will implement this new logic for determining permissions.

So, how do you extend Drupal's user\_access() function to run your own functions too to check access?

# Answer
Looking at the code there's simply no way to do this without directly hacking the `user_access()` function.

There are no hooks invoked and the logic is completely self-contained, aside from one call `user_role_permissions()`. That function just runs a database query though so there's no scope to intercept the process there.

Obviously you could write your own access function and call it from your own code, but there are 152 calls to `user_access()` in core files (and countless others in contributed modules) which won't be able to take advantage of it unfortunately.
> 0 votes

# Answer
Despite its very generic name, `user_access()` is actually a simple function to *determine whether the user has a given privilege*. And by *privilege*, the documentation actually means *has a role whose has been granted a single permission*.
> 0 votes

---
Tags: 7, users
---


title: Commerce product variations switching

text:
# Question
Title: Commerce product variations switching
I have setup a product which has multiple variations as the image shows:

My variations have a colour taxonomy which I'm trying to use for when a user wishes to switch between variations on the same product.

**My problem is the product node is not presenting any option for selecting the list of available colour nor is there an add to cart form.**

I'm sure I'm missing one or two things ... I could use a second opinion, please.

**UPDATE:**

I already had the "**Enable this field to function as an attribute field on Add to Cart forms**" selected but didn't work.

I noticed in step#2 of the answer you directed me to, the taxonomy field is created in a Variation entity type. However, I don't see a Variation entity listed on my site.
**I'm adding my colour taxonomy field into the product type entity as shown in the image below**:

# Answer
You need to enable the taxonomy field to be used as attributes so it is exposed to the cart form.

Here you've got the step by step guide here: https://drupalcommerce.org/commerce-kickstart-2/adding-taxonomy-field-product-attributes
> 0 votes

---
Tags: 7, commerce
---


title: drupal_get_form renders blank page

text:
# Question
Title: drupal_get_form renders blank page
I'm building a module for basic e-mail sharing that will present a form on every node. So I hook into nodes and add a new variable called `share_form` which is supposed to contain the from from `email_share_node_form` after it has been fetched with `drupal_get_form`.

I have been checking out loads of examples and as far as I can see I'm doing everything right. But the page turns completely blank, with no errors either in the reports or on the page. The same occurs when I use other form\_ids such as `user_register_form` that is supposed to work.

If I add any normal string to `share_form` the page renders with no issues at all. So the error is definitely occuring inside `drupal_get_form`.

Is there obvious error in my code? How can I debug this?

**UPDATE:** If I put the `render(drupal_get_form('email_share_node_form'))` in my `node.tpl.php` it renders just fine. Why not in the module?

```
/**
 * Hook into node_load to insert an e-mail share form.
 */
function email_share_node_load($nodes, $types) {
  foreach ( $nodes as $nid => $node ) {
    $nodes[$nid]->share_form = drupal_get_form('email_share_node_form');
  }
}

// --------------------------------------------------

/**
 * Create a share-form to display on a node.
 */
function email_share_node_form($form, &$form_state) {
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit')
  );

  return $form;
}

```

Thanks

# Answer
If you have a white page then there is very likely an error somewhere. Check your apache or php error logs. Which could really be any where depend on what platform you are developing on.

Fatal errors won't make it into the database log file within Drupal since fatal errors tend to stop everything dead.
> 2 votes

# Answer
This is so late... Hope it helps someone... I had the same problem with a white page and no errors reported.

In the form function you need need to `return drupal_get_form(`

I was simply calling `drupal_get_form(` and not returning it and had the exact same problem.
> 0 votes

---
Tags: 7
---


# Question
Title: White screen of Death after clearing cache, can't find a way to get the site back up
My problem is that I keep getting the white screen of Death ever since I cleared the cache of my Drupal website.

The error is the following :

```
PHP Fatal error:  Call to undefined function uc_address_property_info() in
sites/all/modules/ubercart/shipping/uc_shipping/uc_shipping.rules.inc on line 12

```

It happened after I cleared all the cache using the button from the Drupal configuration page. I'm pretty sure the Ubercart Store module is enabled, and I tried clearing the cache from the database already. Before clearing the cache, the site was working fine. The only thing I did is trying to hide some profile2 fields that I created and since they were still there, I thought that clearing the cache would do the trick.

# Answer
If you have Drush, I would try doing another cache-clear. If that doesn't work, I would also try a registry rebuild.

Other than that, just make sure that file exists and that function exists.
> 1 votes

---
Tags: database, caching
---


# Question
Title: How to alter textfield auto-submit delay?
I have a view with exposed filters using AJAX and auto-submit feature.

The problem is it reacts too fast, **submitting the request after every key up very fast**, so that the view is reloaded before users could finish to type search text...

I would like instead to **choose how many millisec it waits before sending request**...

# Answer
> 3 votes
I tried different ways to do that, this working one was suggested by Andy in comments to a close but different issue, thanks to him !

In fact CTools autosubmit has a hardcoded delay on submitting fixed to 500ms.

A possible way is to switch auto-submit.js to your own modified copy. *However if you do this, you'll need to check if auto-submit.js has changed every time you do an upgrade to CTools.* :

```
function neptune_js_alter(&$javascript) {
  if ($some_condition) {
    $new_autosubmit = drupal_get_path('theme', 'YOUR_THEME') . '/js/auto-submit.js';
    $javascript['profiles/commons/modules/contrib/ctools/js/auto-submit.js'] = drupal_js_defaults($new_autosubmit);
  }
}

```

And set your value into auto-submit.js :

```
//Lines 87 and following
    var timer = 3000;
          .keyup(function(e) {
            if ($.inArray(e.keyCode, discardKeyCode) === -1) {
              timeoutID = setTimeout($.proxy(triggerSubmit, this.form), timer);
            }
          })
          .bind('change', function (e) {
            if ($.inArray(e.keyCode, discardKeyCode) === -1) {
              timeoutID = setTimeout($.proxy(triggerSubmit, this.form), timer);
            }
          });

```

To be more flexible you may want to add an attribute to the input you need to change :

```
function MODULE_form_MYFORM_alter(&$form, &$form_state, $form_id) {
  $form['MY_INPUT']['#attributes'] = array('class' => array('ctools-auto-submit-delayed'));
}

```

And then change value for this class only

```
    var timeoutID = 0;
    var timer = 500;
    if ($(this).hasClass('ctools-auto-submit-delayed')) {
      timer = 3000;
    }
    $(this)
      .bind('keydown keyup', function (e) {
        if ($.inArray(e.keyCode, discardKeyCode) === -1) {
          timeoutID && clearTimeout(timeoutID);
        }
      })
      .keyup(function(e) {
        if ($.inArray(e.keyCode, discardKeyCode) === -1) {
          timeoutID = setTimeout($.proxy(triggerSubmit, this.form), timer);
        }
      })
      .bind('change', function (e) {
        if ($.inArray(e.keyCode, discardKeyCode) === -1) {
          timeoutID = setTimeout($.proxy(triggerSubmit, this.form), timer);
        }
      });

```

This would be more elegant & flexible to pass directly the timer value to js, but I have no time to think more about it.

PS : there is an existing patch about that issue but it returns errors in my config.

---
Tags: ajax, views
---


title: CDN Module and Image Styles

text:
# Question
Title: CDN Module and Image Styles
Yesterday I installed the CDN Module using Amazon Cloudfront and magically everything worked as expected. I was quite happy.

This morning I was showing off my new improved CDN enabled website to a colleague and most (not all) of the image style generated images were broken! And to confuse things even further, when I opened a broken image in a browser window the file was actually Drupal's Access Denied Page.

Digging into this further, I found that the /sites/default/files/styles/STYLE folder was empty. This seems strange to me since it was not empty yesterday when all of these files were uploaded to Amazon. What could be deleting the styles/STYLE folder?

So, I installed the Image Style Flush Module and flushed the style in question. Still nothing, but it makes sense since the CDN module is re-writting all of the links to static content and Drupal doesn't actually get hit to re-create the missing image. How the Access Denied page was uploaded is a mystery as well.

Next, I disabled the CDN module and cleared the cache. Reloading the page recreated all of the images and everything works as expected. But, I need to use the CDN as it's a requirement of the project.

Drupal 7.27, CDN module latest version.

I could blacklist the /sites/default/files/styles/STYLE folder, but that represents almost 30 images that are loaded on every page.

Any advice would be greatly appreciated.

# Answer
AD MPD noted in the comments, the issue is how Amazon Cloudfront handles the image style URL, specifically the ?itok query string.

So, when creating your distribution in Cloudfront, make sure you set "Forward Query Strings" to "Yes". See screenshot:
> 7 votes

---
Tags: 7, media, cdn
---


# Question
Title: Alter views fields using preprocess function before render?
How do I edit a views field using preprocess before it is rendered to the screen? Let's say the field originally outputs something like this:

```
Note title

```

now I want to change that adding the number of comments in that node

```
Node title (4 comments, 1 new)

```

I know I can achieve this with joining two fields together or altering the template (tpl) files for that particular field but I'd like to learn how to use **preprocess** function in order to achieve this.

# Answer
> 0 votes
**Drupal 7**

Either you have to use hook\_views\_pre\_render() or create appropriate TPL file (e.g. views-view-fields--MYVIEW.tpl.php) in your template dir (check Theme:Information in view edit page for more details).

You may also use preprocess theme function to print a single record from a row, with fields which is template\_preprocess\_views\_view\_fields().

Related:

# Answer
> -1 votes
There is help on Using default views in your module.

I also found this how-to helpful: Theming a view from within your module.

---
Tags: views, theming
---


title: Contextual filters and node types

text:
# Question
Title: Contextual filters and node types
I have a block that is displaying related content to the node being viewed. Currently it's displaying node titles for three content types : hotel, tour operator and transport. I would like it to display only content type that is similar to the content of the node currently viewed and filter out the two other content types.

I have been trying to set this up using contextual filers in views but I can't get it to work.

Is it something that can be done using contextual filters without writing any code ? Or do I need to write some php (I can't) to get this to do what I need.

Thanks

# Answer
It might be possible to add a conditional filter on the node type and then add custom PHP code to get the default value based on the currently viewed node. The code to do this should look like this: (should work both in D6 and D7):

```
if ($node = menu_get_object()) {
  return $node->type;
}

```

It would be cleaner to do that in a views handler, that is however quite a bit more complicated to set up than pasting the above code in the textfield in the views UI.
> 6 votes

# Answer
Here comes the views handler for D7.

Create a folder for custom modules `sites/all/modules/custom` and therein create a folder for our module. Let's call it `nodetype_filter`. Now you save the following four lines as `nodetype_filter.info` file inside this folder to tell Drupal about our new module (`sites/all/modules/custom/nodetype_filter/nodetype_filter.info`):

```
name = Nodetype Filter
description = Adds a Views contextual filter to display only nodes of current node's type
core = 7.x
dependencies[] = views

```

Create a `.module` file in our module's folder (`sites/all/modules/custom/nodetype_filter.module`) and implement `hook_views_api()` by pasting in the following code:

```
<?php
/**
 * Implementation of hook_views_api().
 */
function nodetype_filter_views_api() {
  return array(
    'api' => 3 // this number depends on what version of Views you are using
  );
}

```

Once `hook_views_api()` is implemented, Views will automatically look for a file named `[module].views.inc` in our module's home directory. So let's create it by saving the following code inside `sites/all/modules/custom/nodetype_filter.views.inc`:

```
<?php
/**
 * Implements hook_views_plugins().
 */
function nodetype_filter_views_plugins() {
  return array(
    'argument default' => array(
      'param' => array(
        'title' => t("custom: current node's type"),
        'handler' => 'nodetype_filter_plugin_argument_default_param',
      ),
    ),
  );
}
/**
 * Default argument plugin to use the current node's type.
 *
 * @ingroup views_argument_default_plugins
 */
class nodetype_filter_plugin_argument_default_param extends views_plugin_argument_default {

  function get_argument() {
    if (arg(0) == 'node' && is_numeric(arg(1))) {
      $node = node_load(arg(1));
      return $value = $node->type;
    } else {
      return $value = FALSE;
    }
  }
}

```

Finally, activate your module and edit your view. Add a contextual filter `Content: type`. Select `Provide a default value` and select the filter `custom: current node's type` we created before.

Please feel free to help correcting my code if anything is wrong since I didn't test it altogether, but wrote a similar module earlier.
> 2 votes

# Answer
Instead of using contextual filter, you can just simply just add three blocks, each for one content type (hotel, tour operator and transport).

Something like this: display hotel content listing block only for hotel node, transport listing block only for transport node.

Don't forget to exclude the current node from the block view, so it won't show duplicated content.
> -2 votes

---
Tags: views, blocks
---


# Question
Title: find nodes by attribute and modify at once
If I want to filter content by attributes (besides content type name), is there is some module around? if I am able to find these nodes, some way to update this attribute for all nodes at once?

# Answer
Some options:

1. You can use Views in combination with Views Bulk Operations and Rules.
2. You can also have a look at Editable Fields in combination with Views
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: How do I add a simple form to the node edit page?
I've spent a grand total of 8 hours trying to solve this problem. The form needs to be separate from the node edit form so I can't use the form\_alter hook. It needs a separate submit button. It only needs to appear on admin screens ... I've tried overriding page.tpl.php (the one used by me admin theme, seven) with no luck. See the code below ... absolutely nothing happens. When I add html into the page.tpl.php file (located in my modules folder), the html does not appear.

```
/**
 * Implements hook_theme_registry_alter()
**/
function my_module_theme_registry_alter(&$theme_registry) {
  $mod_path = drupal_get_path('module', 'my_module');
  $theme_registry_copy = $theme_registry;       // munge on a copy
  _theme_process_registry($theme_registry_copy, 'phptemplate', 'theme_engine', 'seven', $mod_path);
  $theme_registry += array_diff_key($theme_registry_copy, $theme_registry);
  $hooks = array('node');
  foreach ($hooks as $h) {
    _my_module_insert_after_first_element($theme_registry[$h]['theme paths'], $mod_path);
  }
}
/**
 * Helper function for re-ordering arrays (needed by theme_registry_alter)
*/
function _my_module_insert_after_first_element(&$a, $element) {
  if(is_array($a)) {
    $first_element = array_shift($a);
    array_unshift($a, $first_element, $element);
  }
}

```

Also, I realize I can create forms the drupal way with the form hook (and page call backs). I've had success creating forms and showing them on custom urls, but I can't seem to programatically add the forms on pages I want, such as the node edit pages. If I could figure out how to do that, it would be preferable to just adding an html form into the template folder.

# Answer
It sounds like you want to let the author notify your module of significant changes to a node. Another approach you could take is to add a field to your node type, such as "field\_change\_notification" (boolean/checkbox) ... then look to check if the author selected the checkbox in hook\_node\_presave. You can even set it back to unchecked so they can again notify your module on the next update.

```
function HOOK_node_presave($node){
  if ($node->type == 'article'){
    if ($node->field_change_notification['und'][0]['value']){
      drupal_set_message('A change has been made...');
      $node->field_change_notification['und'][0]['value'] = 0;
    }
  }
}

```
> 0 votes

---
Tags: theming
---


# Question
Title: Moving from custom CMS to Drupal and need to keep a myriad of old mod_rewrites
I am moving content from an existing custom built CMS into Drupal 7. There is a host of mod\_rewrite rules in place. These rules expand path names in the URL. For example, the rule below effectively expands

`RewriteRule ^abc/?(.*)$ /alpha/beta/confusion/$1 [L,R`\]

Ideally we'd like put these rules inside of `/etc/httpd/conf.d/old_redirects.conf`. However, the clean URL rules are in .htaccess and are processed first.

Can I remove dependence on .htaccess and move these rules to `/etc/httpd/conf/httpd.conf` thereby allowing me to import the old\_redirects.conf into the httpd.conf file *before* the Clean URL set of rewrites executes?

(I've referenced the following question How do I use .htaccess to trigger mod\_rewrites before D7's Clean URLs take over? and Drupal 7 .htaccess redirects; and while good, they don't quite cover this from the perspective the a need.)

# Answer
Moving effort to this question and answer Drupal 7 rewrite not using .htaccess. THis is what I'm trying to do anyhow is eliminate the .htaccess.

However, I discovered a module called htaccess

> Htaccess is a module which autogenerates a Drupal root htaccess file based on your settings.
>
> Drupal tries to provide a one size fits all htaccess for Apache webservers, but this goal is increasingly difficult. This module allows the webmaster to set specific options.

Added benefits is that for every drupal core update (in which drupal overwrites htaccess), I just re-deploy my set of rules which this module appends to the active .htaccess file. Additionally, my customization to htaccess are in the database and safe in scheduled backups in from Backup Migrate.
> 1 votes

---
Tags: .htaccess
---


# Question
Title: How can I change a URL based on region and language selection?
I have five different regions and languages. When loading a page, the URL ends with \[domain name\]/\[region name\]/\[language name\]. When users change the language or the region, the URL should reflect that.

How can this be achieved?

# Answer
I've used a couple hooks in the past to rewrite all inbound/outbound URLs for Drupal 6. The Drupal 7 equivalent hooks are:

```
function mymodule_url_inbound_alter(&$path, $original_path, $path_language) {
  // Remove "region/language/" from beginning of $path
}

```

Official documentation: hook\_url\_inbound\_alter

```
function mymodule_url_outbound_alter(&$path, &$options, $original_path) {
  // Prepend $path with "region/language/"
}

```

Official documentation: hook\_url\_outbound\_alter

I don't recall the details of my implementation (it was several years ago), but this was the core of it.
> 0 votes

---
Tags: 7, uri
---


# Question
Title: Add User Edit and Profile pages to Quicktabs
I'm using the module Quicktabs on my user pages.

As you can see here I now have 2 rows of tabs and would like to move the User Edit and Profile to the Quicktabs tabs. However the options of block, view, node, qtabs and callback don't seem to cover these pages.

Has anyone else got around this problem.

thanks in advance

# Answer
I create my quicktabs programmatically most of the tines exactly to avoid this kind of problems and expedients.

You need to choose 'callback' for both tabs, and use 'user/x' for profile and 'user/x/edit' for the form.

What x is?

the user uid, but since you need it to change based on the current user, you need to take it from the path the tabs will be displayed on.

assuming the path is

```
"mysite/candidate/{user uid}/dashboard"

```

replace x with %2 (or %3).

you don't have the uid in your path?

then create the quicktab programmatically :)
> 1 votes

---
Tags: blocks
---


title: Organize shows and episodes

text:
# Question
Title: Organize shows and episodes
I'm moving from years after using joomla to drupal and i've hit the learning curve.

My question is below.

I want to create content like this:

```
Many shows
Each show has many episodes
Each show has many tags (genres)

Shows should be listable
Episodes should be listable per show
Shows should be listable per genre

```

It's basically a database for tv shows. But I want to hit the ground running.

I'm currently stuck with taxonomy and content types. Would a show and episode each be a content type? How can I relate them to each other?

I'm running drupal 7.x

# Answer
It looks like two content types: `Show` and `Episode`. You'll want to look into the Entity reference module to relate episodes to shows. This adds an `Entity reference` field type. And you'll be using `Term reference` fields for tagging.
> 1 votes

---
Tags: taxonomy-terms, nodes
---


title: Views images as label on a table

text:
# Question
Title: Views images as label on a table
I am trying to create a table in views. My main problem is that I want to have a image in the label

"CONTENT"

so far I've managed to add a space to the field and a custom class to it, and I've added background image to that field. It works but is not the best implementation. Can you point me in the right direction or it can not be done?

Thank you and keep up the good work. (i'm new to drupal but I know php css html javascript, mainly I've made small sites with custom cms and I'm moving go drupal)

# Answer
> 0 votes
CSS is the right solution if you have a fixed set of icons you want to use. If you need full control over the images for each node, you can add an image field and use the rewrite results settings to insert the image before your field. In this case, you would hide the label altogether.

---
Tags: views, media, theming
---


# Question
Title: Saving form data of forms modified with form_alter hook
I understand how to add stuff like checkboxes and fieldsets to existing forms (e.g. the form displayed on the node edit page) using \_form\_alter. But what I don't understand is how to collect the input and store it in a database table of my choosing (ideally with db\_insert). Let's say I've added a checkbox to the fieldsets at the bottom of article\_node\_form (the form which appears when editing content type article):

```
$form["Email Notifications"] = array(
    '#type' => 'fieldset',
    '#title' => 'Email Notifications',
    '#collapsible' => 'true',
    '#group' => 'additional_settings',
    '#required' => FALSE,
    'email_notify' => array (
        '#type' => 'checkbox',
        '#title' => 'Notify users of changes to this page',
        '#default_value' => 0,
        '#required' => FALSE,
)

```

How do I collect this data an store it in a database?

# Answer
Exactly like you alter a form to add custom fields, you alter it to add custom validation and submit handlers.

It should be:

```
$form['#validate][] = 'custom_validate';
$form['#submit'][] = 'custom_submit';

```

use those function to control the additional user input and store them later.
> 0 votes

---
Tags: forms
---


# Question
Title: Remove CDATA script from the page source
On my site i am getting some unnecessary CDATA script on the page source.

```
    <script type="text/javascript">
<!--//--><![CDATA[//><!--
jQuery.extend(Drupal.settings, {"basePath":"\/","pathPrefix":"","ajaxPageState":{"theme":"visapro","theme_token":"IoYFb0sv8oueNJZfQl2VKQDzEs_MwLTh97vN5AXTVQU","js":{"misc\/jquery.js":1,"misc\/jquery.once.js":1,"misc\/drupal.js":1,"misc\/ui\/jquery.ui.core.min.js":1,"misc\/jquery.ba-bbq.js":1,"modules\/overlay\/overlay-parent.js":1,"sites\/all\/libraries\/shadowbox\/shadowbox.js":1,"sites\/all\/modules\/shadowbox\/shadowbox_auto.js":1,"modules\/contextual\/contextual.js":1,"misc\/jquery.cookie.js":1,"sites\/all\/modules\/panels\/js\/panels.js":1,"modules\/toolbar\/toolbar.js":1,"sites\/all\/themes\/visapro\/js\/homeslider.js":1,"sites\/all\/themes\/visapro\/js\/jquery.bxslider.min.js":1,"sites\/all\/themes\/visapro\/js\/jquery.anythingslider.js":1,"sites\/all\/themes\/visapro\/js\/qswfobject.js":1,"sites\/all\/themes\/visapro\/js\/jquery.colorbox.js":1,"sites\/all\/themes\/visapro\/js\/prettify.js":1,"sites\/all\/themes\/visapro\/js\/sliders.js":1,"0":1},"css":{"modules\/system\/system.base.css":1,"modules\/system\/system.menus.css":1,"modules\/system\/system.messages.css":1,"modules\/system\/system.theme.css":1,"misc\/ui\/jquery.ui.core.css":1,"misc\/ui\/jquery.ui.theme.css":1,"modules\/overlay\/overlay-parent.css":1,"sites\/all\/libraries\/shadowbox\/shadowbox.css":1,"0":1,"modules\/contextual\/contextual.css":1,"sites\/all\/modules\/simplenews\/simplenews.css":1,"modules\/comment\/comment.css":1,"modules\/field\/theme\/field.css":1,"modules\/node\/node.css":1,"modules\/search\/search.css":1,"modules\/user\/user.css":1,"sites\/all\/modules\/views\/css\/views.css":1,"sites\/all\/modules\/better_messages\/better_messages_admin.css":1,"sites\/all\/modules\/ctools\/css\/ctools.css":1,"sites\/all\/modules\/panels\/css\/panels.css":1,"modules\/shortcut\/shortcut.css":1,"modules\/toolbar\/toolbar.css":1,"sites\/all\/themes\/visapro\/css\/layout.css":1,"sites\/all\/themes\/visapro\/css\/style.css":1,"sites\/all\/themes\/visapro\/css\/colors.css":1,"sites\/all\/themes\/visapro\/css\/view-home.css":1,"sites\/all\/themes\/visapro\/css\/theme-metallic.css":1,"sites\/all\/themes\/visapro\/css\/jquery.bxslider.css":1,"sites\/all\/themes\/visapro\/css\/anythingslider.css":1,"sites\/all\/themes\/visapro\/css\/colorbox.css":1,"sites\/all\/themes\/visapro\/css\/print.css":1}},"overlay":{"paths":{"admin":"media\/*\/edit\nmedia\/*\/multiedit\nmedia\/*\/delete\nmedia\/browser\nmedia\/browser\/*\nnode\/*\/edit\nnode\/*\/delete\nnode\/*\/revisions\nnode\/*\/revisions\/*\/revert\nnode\/*\/revisions\/*\/delete\nnode\/add\nnode\/add\/*\noverlay\/dismiss-message\nuser\/*\/shortcuts\nnode\/*\/simplenews\nadmin\nadmin\/*\nbatch\ntaxonomy\/term\/*\/edit\nuser\/*\/cancel\nuser\/*\/edit\nuser\/*\/edit\/*","non_admin":"admin\/structure\/block\/demo\/*\nadmin\/reports\/status\/php"},"pathPrefixes":[],"ajaxCallback":"overlay-ajax"},"shadowbox":{"animate":true,"animateFade":true,"animSequence":"wh","auto_enable_all_images":0,"auto_gallery":0,"autoplayMovies":true,"continuous":false,"counterLimit":10,"counterType":"default","displayCounter":true,"displayNav":true,"enableKeys":true,"fadeDuration":0.35,"handleOversize":"resize","handleUnsupported":"link","initialHeight":160,"initialWidth":320,"language":"en","modal":false,"overlayColor":"#000","overlayOpacity":0.8,"resizeDuration":0.55,"showMovieControls":true,"slideshowDelay":0,"viewportPadding":20,"useSizzle":false},"tableHeaderOffset":"Drupal.toolbar.height"});
//--><!]]>
</script>

```

I want to remove it. I am unable to find the exact source form where it is come. Please suggest me with a solution.

# Answer
> 4 votes
I'm assuming you're using an HTML5 `DOCTYPE`, The `CDATA` tags are required for XML-based documents (including XHTML).

The characters look to be hard-coded into common.inc, line 4287:

```
$embed_prefix = "\n<!--//--><![CDATA[//><!--\n";
$embed_suffix = "\n//--><!]]>\n";

```

Examining that code I think the only way to intercept it would be to override `theme_html_tag()` in your theme, e.g.

```
function MYTHEME_html_tag($vars) {
  if ($vars['element']['#tag'] == 'script') {
    unset($vars['element']['#value_prefix'];
    unset($vars['element']['#value_suffix'];
  }

  return theme_html_tag($vars);
}

```

# Answer
> 1 votes
For Drupal 7, where every theme function has preprocess functions, you could use the following code.

```
function mytheme_preprocess_html_tag(&$variables) {
  if ($variables['element']['#tag'] == 'script') {
    if (strpos($variables['element']['#value'], "\n<!--//--><![CDATA[//><!--\n") !== FALSE) {
      $variables['element']['#value_prefix'] = str_replace("\n<!--//--><![CDATA[//><!--\n", "", $variables['element']['#value_prefix']);
    }
    if (strpos($variables['element']['#value'], "\n//--><!]]>\n") !== FALSE) {
      $variables['element']['#value_suffix'] = str_replace("\n//--><!]]>\n", "", $variables['element']['#value_suffix']);
    }
  }
}

```

I remove the prefix and suffix only when they are present; I also remove only the part we don't want, not the full prefix/suffix.

# Answer
> 0 votes
Not sure this is what you were asking (remove the CDATA tags), but I came across this post in my search of wanting to remove the CDATA tags for one inline JS script, and Clive's answer got me headed in the right direction. But I ultimately used...

```
function MYTHEME_preprocess_html_tag(&$vars) {
  if (strpos($vars['element']['#value'], $needle) !== FALSE) {
    unset($vars['element']['#value_prefix']);
    unset($vars['element']['#value_suffix']);
  }
}

```

Just to give another example if anyone comes across the same scenario.

# Answer
> -1 votes
Set the field as: Text format "PHP" then put your css clases inside the tag style

---
Tags: javascript
---


# Question
Title: Anonymous view while developing without quit maintenance mode
I have a live website with 200 active users per hour, I put the site in maintenance mode for make some changes. You know the admin view is pretty different than the anonymous view of my website or other user roles views.

I need to know how to see how the anonymous and other roles will see my website after the changes I did "for see if everything is ok". I know you are going to answer "use local enviroment and then use backup and migrate" well I already use it but if preffer to ensure that everything is ok in the live site before take off the maintenance mode.

Thanks for your advice.

# Answer
This is exactly what the Maintenance Exempt module was built for. From the project description:

> This D7+ module allows specific people to perform the necessary testing on the site with all role combinations without opening the site up to all of your visitors.
>
> Exemptions can be added by:
>
> * Specifying a list of IP addresses (individually or by CIDR notation)
> * Specifying a query string variable
> 4 votes

---
Tags: 7, maintenance-mode
---


# Question
Title: Replace default words in exposed filters
I created an exposed view that allows users to sort content based on content type or date. In my content type drop down menu, the default choice is - Any -, I tried to replace it in the settings file's string override section, but while this works for numerous other defaults, it doesn't seem to be taking for exposed views. Any help would be much appreciated!

# Answer
I have tried to resolve from backend/server side, but without success, so I have reviewed a way using Jquery (client side), while an backend alternative is achieved:

```
<script>
$("#here-field-name option[value='All']").html("Anytext");
</script>

```

Also, here is alternatives from backend perspective, maybe are useful for you how to default value to select list CCK with form\_alter

I hope information be useful.
> 1 votes

# Answer
go to the folder : sites\all\modules\views\handlers and open the views\_handler\_filter.inc file...

and search for :"- Any-" in the file... one of them is located in the "exposed\_translate" function. change it to whatever you what. it is a little bit hacky but it works ;)
> 0 votes

---
Tags: views, 6
---


title: How to change module default path

text:
# Question
Title: How to change module default path
I recently organized my modules in /sites/all/modules in 4 differents subfolders: contrib, custom, patches, migration. It works very well, but after using the update manager, the new updated modules appears in /sites/all/modules instead of /sites/all/modules/contrib, so I have to move it manually to contrib. How can I set the default module location to /sites/all/modules/contrib ?

Thanks.

# Answer
> 0 votes
Sorry, I didn't find this issue before, it has been already reported here Set Update Manager to install to sites/all/modules/contrib?

I knew about drush, but I was wondering if it could be done with the update-manager.

# Answer
> 0 votes
You can try some steps:

1. Firstly, backup your database
2. Check-in your code into version control
3. Run following queries:

UPDATE system SET filename = REPLACE(filename, 'sites/all/modules', 'sites/all/modules/contrib');

UPDATE registry SET filename = REPLACE(filename, 'sites/all/modules', 'sites/all/modules/contrib');

UPDATE registry\_file SET filename = REPLACE(filename, 'sites/all/modules', 'sites/all/modules/contrib')

1. Move folders
    2. Run: drush cc all

---
Tags: 7, updating
---


# Question
Title: Is it possible to migrate taxonomy terms when having only the term name?
I'm starting to learn the migration module because i have to do quite a complicate migration from a Drupal 6 site to a Drupal 7 Importing nodes with different field names from Drupal 6 to 7

And i'm wondering if it's possible to migrate taxonomy terms if you have only their name but not the tid (or better, the tid is different between the sites), and if it's possible how? (that is, other than making a query to load the tid from the db, i'd like to know if there's a more "automated" way)

# Answer
I probably will use feeds module and hook\_feeds\_presave to manually re-import taxonomy name and reset the node associate your that taxonomy.
> 1 votes

---
Tags: taxonomy-terms, migrations
---


title: How do I theme the user/uid/edit page?

text:
# Question
Title: How do I theme the user/uid/edit page?
I am using two themes for my web and mobile site. And I'm using the ThemeKey module.

No matter what I try, the user edit page is always shown as in the theme of my web site and not my mobile site.

The following code doesn't work.

```
function mytheme_theme() {
  $items = array();
   $items['edit_profile_user_profile_form'] = array(
     'render element' => 'form',
     'template' => 'templates/user-profile'
   );

   return $items;
}

```

This only lets me theme the user profile page in user-profile.tpl.php. Also page--user--edit.tpl.php does not work.

How should I achieve this?

# Answer
I found the solution for this.

The reason for error was that the ThemeKey module was not overriding and admin pages, by default. Hence pages like user/uid/edit which are admin by nature are not overriden in their theme and pick the admin appearance theme always.

To bypass this I enabled the THEMEKEY COMPATABILITY Module (Part of Themekey module for D7). Open the following settings page:

```
http://localhost/admin/config/user-interface/themekey/settings/compat

```

Section `Modules>> Integrate Modules in Theme Switching Rule Chain>>`

Then check the option "System (Administration theme)".

Now all admin pages like user/uid/edit also come under theme switching rule and pick the theme as defined.
> 1 votes

---
Tags: 7, theming, users
---


title: How to create custom View template?

text:
# Question
Title: How to create custom View template?
I want to create a simple php template for Views in Drupal 7, but I think I'm missing a crucial element to this puzzle, as every time I try to get to the content of Views' output in the template's php code, even if I use the default *views-view.tpl.php* file as a template for that particular view, I get

> Undefined variable: fields in include() ...

How do I get around this?

# Answer
How is your override requirement? Is it for all the views or for a certain views?

**For certain views:** In that views admin page : go to `Advanced -> Theme:` Click on `Information`

you will see the active templates for 'Display output' in bold (**views-view.tpl.php**) and rest available theme suggestions for overridden (comma separated).

Now copy views-view.tpl.php from views contrib module theme folder and put it in your site theme folder, rename it to one of the name suggestion available in views. Make changes to your template.

Clear cache and check.
> 5 votes

# Answer
Have you tried with this format `views-view--content type--page.tpl.php` ?

or

create the view page in block type

put code like this in template file

```
if(arg(0) == 'user-favorites'){
  $variables['theme_hook_suggestions'][] = 'page__favorites';
 }

```

create tpl page name like this `page--favorites.tpl`

and render the block content like this

```
<?php
   $deal_block = module_invoke('views','block_view','user_favourites-block_5');
   print '<h2 class="block-title">title</h2>';
   print render($deal_block['content']);
   ?>

```
> 2 votes

# Answer
Simple answer is there is no variable `$fields` in the views-view.tpl.php.

You'll need to work with the `$rows` or the `$view` variables.
> 1 votes

# Answer
In addition to what @Jeet said:

It's important to understand how Views theming works. There is not simply one views template; views are themed with a chain of nested templates.

The first template is like a wrapper around the view, displaying title, header, footer, etc.

The second template depends on the view style you choose (list, table, grid, etc.).

Most views styles then use a third template for the row style. This contains the html that is repeated for each result.

Some views even have more templates, for instance for the separate fields within a row.

On every level you can override every template in multiple ways, by adding a template file with the correct name in your theme folder. All possible template file names are listed under `advanced -> theme -> information`. These templates range from generic (applies to all views) to specific (applies to a specific display of a specific view).
> 1 votes

---
Tags: views, theming
---


# Question
Title: List content referenced to another content type
I'm creating a simple site which has shows and episodes. I have created both content types and I added the entity reference field to the episode type. The episode would reference a show which it belongs to. I have a view which lists all the shows. However, when I click a show I want a list of all the episodes belonging to that show.

How would I achieve this?

# Answer
You can create a view that lists episodes that references the show. This is done using the module Views.

Go to admin/structure/views/add and add a view, call it episodes and create a block display.

Create a new view and a relationship, the label will be "Entity Reference: Referencing entity" and as description you will see "A bridge to the Content entity that is referencing Content via field\_YOURFIELD".

Then add a contextual filter called "Content: Nid". In the settings for the filter look for "When the filter value is NOT available" and choose "Provide default value" and choose "Content ID from URL".

Your settings will look something like this (I removed the second column to make the image smaller).

Now go to admin/structure/block and place the block you created (if named the same as my example it will be called "View: episodes") and place it in the region you want it to show.
> 1 votes

# Answer
What you are after is basically covered by the Corresponding Entity References module. From the module description:

> CER keeps reference fields in sync. If you have two entities that refer to each other using Entity Reference (or some other kind of reference field), it saves you the trouble of double-editing your entities in order to have them point at each other. If entity Alice references entity Bob, CER will make Bob reference Alice, and keep the references up-to-date when either entity is updated or deleted.

This practically means that, in your case, the show will also be referencing to the episodes and you can easily list the episodes through the content type's display options.

Notice that if you do not create a reference from the show to the episodes and you try to use views (or raw drupal database queries) in order to find the show backreferences from episodes, the generated SQL queries will probably be horrible, performance-wise.
> 0 votes

---
Tags: entities, views
---


# Question
Title: Files inside the CSS folder gets automatically deleted when I clear the cache
When i set my uploads path to ../ on file system, my files inside the css folder get deleted when i clear the cache. My aim is to be able to upload my files on the root outside drupal installation which is possible so far except the deletion of my files. I tried deleting the content of the .htaccess file that gets created in the root folder but there's no luck.

My directory structure is:

root/

----css

-------menu.css(file that get erased)

----drupal

-------drupal installation

----js

-------javascript

----other HTML files

Thank you

# Answer
What you are doing is dangerous. It opens a security hole in your installation. But that's your problem.

Drupal caches pre-combined css and js files in, respectively:

* `public://css`
* `public://js`

It's hardcoded, and you can do nothing about it. This means that if you will set `public` to mean your `../`, Drupal will use `../css` and `../js` for CSS and JS caching purposes - all purposes even cache clear. For performance reasons Drupal does not care if it was this installation that created cache item when you tell it to clear it all. Why should it? Clear is clear after all.

Long story short: **Don't** set drupal's `public://` to anything you don't want Drupal to manage. If you really have to, symlink specific directories, or write custom module to manage such uploads.
> 1 votes

# Answer
Yes as @Molot suggested you can create symlinks. If you want to upload files outside the drupal directory you can create symlink to that outside directory in /sites/default/files, and in apache configuration you can enable `FollowSymLinks` to allow the follow symlinks outside the drupal directory. To enable `FollowSymLinks` you can do change something like this in your apache config file.

```
<Directory /path/to/your/drupal/root>
  Options +FollowSymlinks
  AllowOverride All
</Directory>

```
> 0 votes

---
Tags: files
---


# Question
Title: Attaching existing server files to filefield
How do you set an existing file path for a file field, in Drupal 7? The only option I see is to upload the file again.

In Drupal 6, FileField Sources seems to do this.

Does FileField Paths or IMCE along with file field allow assignment of server files?
Is there an API to programmatically manage file fields?

**Edit**
I just discovered that this *can* all be done with the media module. I also have mediaelement installed. However it is not completely intuitive, so here are the steps I took:

Import to media library: `/admin/content/media/import`

Create a `mediafile asset` field. This allows you to attach from the library.

Display formats (example for audio) are at `/admin/config/media/types/manage/audio/display/`, instead of content type "manage display" which only provides "large", "small", "preview", etc.

# Answer
I would try Media and its associated modules. It's an evolution of FileField Sources, and provides most of the same kind of functionality although with Drupal 7 fields.
> 3 votes

# Answer
I can help you with the attaching a file to a filefiled. However, I have not attempted to achieve an autocomplete widget to get the file that you want to attach to the filefield.

you can use `file_get_contents()` to grab the file that you want to attach and then use file\_save\_data to get it into Drupal. The catch is that you'll need to change the status of the file you just added so that you can attach it to a node later. Other wise you'll get a validation error.

```
$file = file_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAME);

db_update('file_managed')
  ->fields(array('status' => 0))
  ->condition('fid', $file->fid, '=')
  ->execute();

```

Once the form is submitted with the fid as the value for the filefield that you want file attached to the managed files status will be updated automatically.

Check out http://api.drupal.org/api/drupal/includes--file.inc/group/file/7 for further reference.
> 3 votes

# Answer
I chose IMCE in combination with IMCE for FileField (D7) because the client needed a quick and unbloating selection of files uploaded with ftp - and this without duplicating them for each node.

As far as i see the Filefield Sources always duplicates attached files at the moment. The importer provided by Media does that too.
> 3 votes

# Answer
FileField Sources has been ported for D7 and it is great. Too there is module called Visual select file what adds abbiliti for nice Views-based select of existing files (good for images).
> 3 votes

# Answer
You could always go for the File as Node approach and use a Node Reference field + Custom Formatters (to render the Node as a File) to do this, which would allow you to update the File node and have all references of that File node updated across the board.

In D6 you can also use Node Relationships to provide a File Library and Formatters 4 Node Reference field to format the node as any available FileField formatter.
> 1 votes

# Answer
FileField Sources has not yet been ported to Drupal 7, but it's planned. See the corresponding issue on drupal.org.
> 1 votes

---
Tags: 7, files
---


# Question
Title: how to change output html of variable $output on file views-view-field--field-image.tpl.php
dpm($output) -\> `<a href="/content/photo-08"><img typeof="foaf:Image" src="http://www.flipbook.dev/sites/default/files/styles/337x220/public/document_images/9.jpg" width="337" height="220" alt="" /></a>` on file views-view-field--field-image.tpl.php so how to I can add `<div class="amezing"></div> => <a href=""><img /><div class="amezing"></div></a>`

# Answer
> 0 votes
You kind of answered yourself already.

open the views-view-field--field-image.tpl.php file, look for that and add what you need.

however, use the file you can find inside your theme folder ( usually named templates or tpl), not inside the view module.

if you can't find it in there, copy it from the view module. In this case clear the cache for drupal to register the new file.

Always and only edit the .tpl of your themes.

# Answer
> 0 votes
Instated of `<?php print $output;?>` in `views-view-field--field-image.tpl.php` file.

just print

```
<?php print_r($view->result);?>

```

You can able to edit the fields as you want.

---
Tags: views
---


# Question
Title: How to create Nested Accordion in Drupal 7?
2015

-- Jan

-- Feb

```
  -- Link 1

  -- Link 2

```

2014

-- Jan

-- Feb

```
  -- Link 1

  -- Link 2

```

I want same views accordion feature on this listing with expand or collapse feature .

First user select year then month then we show the node title according to month & year .

# Answer
> 2 votes
Drupal View Accordion triggers the accordion for the innermost Group Header. Though Nested Grouping can be done but the accordion effect will only applied to inner group.

For this we have to apply our own JS. I have created a module in which current accordion plugin has been extended, which itself was extending view plugin style. And additional setting has been added to it for nested accordion.

I have committed a \[D7\] Views Nested Accordion module on sandbox for this.

# Answer
> 0 votes
Use module Views Accordion.

Project page says:

> Views Accordion provides a display style plugin for the Views module. It will take the results and display them as a JQuery accordion, using the first field as the header for the accordion rows.

# Answer
> 0 votes
I don't think the nested feature is available as a module yet.

There is this module though: https://drupal.org/project/views\_accordion

I've used it in single level accordions.

Then to nest it you could try this JQuery UI widget: http://jqueryui.com/accordion/

Just edit your view so it will display the clickable items inside each row of your view as headers.

---

Though if you want to go expert mode, you can just use http://api.jquery.com/slidetoggle/

slidetoggle is pretty easy, just include a javascript file then use the jquery commands:

`$('#header1').click( function(){
 $(this).sibling('.content').slideToggle();
});`

Or something like that.

---
Tags: navigation
---


title: My "install module" link

text:
# Question
Title: My "install module" link
"install module" link disappears from module section in "Drupal 7" for some reason.How can this link enable to install my new modules.

# Answer
> 0 votes
Go to `admin/modules` and Enable **Update Manager** under **CORE** modules list

> **Update Manager:** Checks for available updates, and can securely install or update modules and themes via a web interface.

---
Tags: 7
---


# Question
Title: Node titles disappear sometimes when using tokens with Autonodetitles
There are instances where the node titles disappear for updated nodes. The site uses organic groups with APC for caching data. The drupal version installed is 7.18 however most modules including entity, token, entity token etc are up to date. The site has few custom modules and rules enabled but they do not affect the node title. I suspect there may be issue with cache which results in instances when node titles are not populated. Please do suggest ways in which I would be able to figure out the exact issue.

# Answer
Upraded the site to latest version of Drupal. The problem got resolved automatically.
> 1 votes

---
Tags: entities, tokens, nodes
---


# Question
Title: Handling circular entity references with Migrate
I am using Migrate D2D on a Drupal 6 to Drupal 7 migration right now.

I have three types: type1, type2, type3. Each of the three types has a entityreference field on it, which is configured to be able to point to all three types. This means that there can be circular references, and when a particular node is being migrated, the destination node may not exist yet and could potentially be any of the three types.

My migration class looks like this:

```
class MyNodeMigration extends DrupalNode6Migration {
  public function __construct(array $arguments) {
    parent::__construct($arguments);

    $this->addFieldMapping('field_legacy_nid', 'nid');

    $this->addFieldMapping('field_the_reference', 'field_the_reference')
      ->sourceMigration(array('type1', 'type2', 'type3');
  }
}

$node_arguments = array(
  array(
    'class_name' => 'MyNodeMigration',
    'description' => 'type1',
    'machine_name' => 'type1',
    'source_type' => 'type1',
    'destination_type' => 'type1',
    'dependencies' => array('roles', 'users'),
  ),

  array(
    'class_name' => 'MyNodeMigration',
    'description' => 'type2',
    'machine_name' => 'type2',
    'source_type' => 'type2',
    'destination_type' => 'type2',
    'dependencies' => array('roles', 'users'),
  ),

  array(
    'class_name' => 'MyNodeMigration',
    'description' => 'type3',
    'machine_name' => 'type3',
    'source_type' => 'type3',
    'destination_type' => 'type3',
    'dependencies' => array('roles', 'users'),
  ),
);

$common_node_arguments = $common_arguments + array(
  'user_migration' => 'users',
);

foreach ($node_arguments as $arguments) {
  $arguments = array_merge_recursive($arguments, $common_node_arguments);

  Migration::registerMigration($arguments['class_name'], $arguments['machine_name'], $arguments);
}

```

When I run the migrations, most nodes are fine, but I get a decent amount of Stubs **(\*)** created. Some of the destination nodes have the entityreference pointing to these Stub nodes. The source nodes are fine.

What I have uncovered is that the bundle on the destination nodes that are being made as stubs are incorrect, and look like they are all type1. A node of the proper type does end up being created, but it never gets set as the entityreference target.

Another way to explain this is that I end up with

* node: nid=123, type=type1
* node: nid=234, type=type1, field\_the\_reference=123
* node: nid=345, type=type2

where it should be

* node: nid=234, type=type1, field\_the\_reference=345
* node: nid=345, type=type2

How do I handle this situation?

**(\*)**: a "Stub" in the context of this question here refers to a node which is created for the purpose of being a reference target, but does not get its data initially. The term is used throughout the Migrate documentation and source code.

# Answer
> 1 votes
The main problem has to do with how stubs are handled in Migrate, and is related to a known issue.

In short, when the destination can be one of several content types, the migration doesn't know what content type to create the stub as in a generic way.

My current workaround for this is to prevent stubs from being created:

```
abstract class MyNodeMigration extends DrupalNode6Migration {
  ...

  protected function createStub(Migration $migration, array $source_id) {
    return FALSE;
  }
}

```

When the migration runs, stubs don't get created, but the entity reference fields in my destinations also don't get populated.

I then manually reset the highwater mark

```
db_update('migrate_status')
  ->fields(array('highwater' => 0))
  ->condition(...)
  ->execute();

```

and then rerun the migrations. Since the destination nodes exists, the entity reference fields can be populated properly.

---
Tags: entities, migrations
---


# Question
Title: How to use downloaded images, for specific field?
I have dropdown list with 2 options. First one is to upload image, where I use image upload field and imagecashe for re-sizing uploaded image. And Second option is to get picture from other site.

If user choose to get picture from other site, i don't know how to use downloaded image.

I downloaded image using following code

$managed = TRUE; $path = system\_retrieve\_file($image, 'public://down\_images/', $managed);

When this image is downloaded I want to use it as logo. Logo is image field which is added to user account.

How can I do that?

# Answer
> 1 votes
1. You need to get the file fid; you can use `EntityFieldQuery`.
2. Then insert/update the "file\_managed" table, using code similar to the following one:

```
db_update('file_usage')
  ->fields(array('id' => $user->uid,))
  ->condition('fid', $file->fid)
  ->execute();

```

# Answer
> 1 votes
One way to achieve this is to :

1. Have custom hook\_form\_alter implemented which will take the external image URL in custom field.
2. Create additional cck field in your content type and hide it while displaying in form
3. After submission you will download and save the file using file\_copy functions
4. Once the image is downloaded you will attach it (programmatically) to the cck field created @step2 in the form\_submit.

Hope this helps.

# Answer
> 1 votes
If you have the image downloaded then try with the following code

set image for current logged in user

```
global $user;
$user->picture = $file->fid;
 user_save($user);

```

else if for other user than

```
$user = user_load($uid);
$user->picture = $file->fid;
user_save($user);

```

# Answer
> 1 votes
I think you are getting the user's avatar once the user provides a link. So for that get the image URL and in your function you can do the following.

```
function custom_user_avatar_save() {
  global $user;
  $uid = $user->uid;
  // Copy the image in tmp directory.
  $user_avatar_path = 'http://upload.wikimedia.org/wikipedia/commons/thumb/4/41/Billy_c.jpg/800px-Billy_c.jpg'; // Change this as variable.
  $filepath = drupal_realpath(file_directory_temp() .  '/' . $uid . '.jpg');

  copy($user_avatar_path, $filepath);

  $account = user_load($uid);

  $file = (object) array(
      'uid' => 1,
      'uri' => $filepath,
      'filemime' => file_get_mimetype($filepath),
      'status' => 1,
    );

  $file = file_copy($file, 'public://');

  $edit['picture'] = $file;
  user_save($account, $edit);
}

```

---
Tags: 7, media
---


# Question
Title: Using Feeds importer to import separate urls to same content-type
I'll try to parse out my problem laconicly:

I've two separate urls formatted as csv files that I want to import to the SAME content-type.

I'm using the same Feeds importer to accomplish this task, using the same unique identifier to import each url and update/overwrite all existing nodes.

Yet, for some reason I'm still getting new nodes when I should be getting updated nodes.

I have no clue where the process could be going wrong hence my post herein. Any help would be most emphatically appreciated.

David

# Answer
If you don't find a direct solution to this issue, try set an unique field on the content type instead and use that instead of an UUID. Have a look at Support unique targets in mappers
> 0 votes

---
Tags: nodes, feeds
---


# Question
Title: Accessing variable_get when loading bootstrap from an external file
I am loading the core drupal 7 components through an external file by loading bootstrap. While the core drupal functions work properly, when I try to access variable\_get I keep getting the default value. The variable\_get works properly when accessed from within a module. Any ideas?

```
require_once dirname(__FILE__).'/scripts/encrypt.php';

//Include drupal
$currdir=getcwd();
define('DRUPAL_ROOT',$_SERVER['DOCUMENT_ROOT']);
chdir(DRUPAL_ROOT);
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
global $base_url;
$base_url = (array_key_exists('HTTPS', $_SERVER) ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'];
drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);

print_r(variable_get('var_name',DEFAULT_VAR_NAME));

```

This always returns

```
DEFAULT_VAR_NAME

```

# Answer
> 2 votes
Why not write a proper Drupal module and include your intended code in there? You miss out on so many of Drupal's nice features if you use it your way, including the issue you are asking about here, but also lots of security and sanity checks. Just sayin'

---
Tags: configuration, external-scripts
---


title: View sorting programmatically

text:
# Question
Title: View sorting programmatically
I have a view with grouping (by one field) and sorting by nodequeue weight. I want to sort the groups as well so I've used hook\_views\_pre\_render and sorted the results array programmatically, but as far as I can see the results aren't rendered as the results array on $view-\>result order.

What am I missing? Workaround will also be great! Thanks!

# Answer
The problem was hook\_views\_pre\_render, for some reason the markup is already render at this stage (weird..), when I used the same code in hook\_views\_post\_execute it worked perfectly.
> 0 votes

---
Tags: 7, views
---