title: Allow comments on profile pages

text:
# Question
Title: Allow comments on profile pages
What are the ways to allow comments on user profile pages in Drupal 7? There is a profile content module, which unfortunately is not available for Drupal 7.

# Answer
I think you can find an answer in this similar question here: How do I enable comments for user profiles?

Apparently, Profile2 module allows that functionnality.
> 0 votes

# Answer
Generally Drupal allows comments on nodes. There is a module in D7 module User Proifile Comments which does the job.

You can also check this https://www.drupal.org/node/68340 which was a more customized way.
> 0 votes

---
Tags: 7, users, comments
---


# Question
Title: how to pass multiple view fields to an action via vbo in D7?
I have a view relating different types of information together. I have a node type and 2 relation types. The base node is related to other nodes using the 2 relations.

Lets say there are 3 fields in the view listing: the base node and 2 other nodes related to the base node:

* nid of the "base node"
* nid of a related node (using relation1)
* nid of another related node (using relation2)

I like to do some action with the base node using views bulk operations. In this custom action I like to use the nids of the other 2 nodes.

My problem is, you can only use one of the three nodes in the action, depending on what you selected in the bulk operations field.

Is there a way to pass ALL three nids?

I know I can use views php to create a hidden field, containing the other two nids and then use the hook\_form\_submit to hook into the submitted form.

But is there a more elegant way, only to use the custom action, without hooking the submitted views form?

# Answer
> 0 votes
I just found an answer. Just put all the fields you like to use in your custom vbo action into the view. They might be hidden, if they are system fields you don't like to show to the user. Then write your action definition. It is important to set the 'pass rows'-parameter to true.

```
    /**
    * implements hook_action_info
    *
    * defines the custom actions
    **/
    function MY_MODULE_action_info() {
        $nid_page = menu_get_object();
        if (!isset($nid_page)) $nid_page = arg(1);

      /**
      * NOTE:
      * PLEASE NOTE THAT THE BEHAVIOUR PROPERTY IS NEEDED FOR THE SELECTED ITEM; ALTHOUGH YOU MIGHT NOT CHANGE THE SELECTED ITEM
      * CLEAR CACHES AFTER CHANGING THE action_info_array !!!
      **/

        return array(
            'MY_MODULE_custom_action1' => array(
                'type' => 'node',
                'label' => 'perform custom actions (WITH form)',
                'configurable' => FALSE,
                'behavior' => array('views_property'),
                'pass rows' => TRUE, /* this passes the entire views row to the $context array */
                'parameters' => array('page_nid'=>$nid_page), /* you can also define some other parameters that are passed via the $context array */
            ),
        );
    }
    /**
    * function to perform vbo actions
    *
    * @param $node
    * selected node entity from view to perform action with
    *
    * @param $context
    * array with context infos like view, options, row...
    *
    **/
    function MY_MODULE_custom_action1(&$node, $context) {
        global $user;
        dpm($node);dpm($context);
        /* row data can be accessed using the $context array */
        $var1 = $context['rows'][0]->field_name[0]['raw']['value'];
    }

```

# Answer
> 0 votes
You sort of can already. Create the component with three arguments. It will pass the selected node to the first argument. On the second page of VBO you'll have two more fields to fill in. You can enter tokens here e.g. `[yourrelationfield1]` for fields of your view.

---
Tags: views
---


# Question
Title: Custom module template override not loaded
Hi I am desperetly trying to override the template of my D7 custom module's block here is my code :

```
  function lnr_block_info() {
    $menus = menu_get_menus();
    $blocks['actualites_filter_article'] = array(
      'info' => t('Actualités: Filtres Articles'),
    );

    return $blocks;
  }

  function lnr_block_view($delta = '') {
    $block = array();
    $menus = menu_get_menus();

    if($delta == 'actualites_filter_article'){
      $block['content'] = theme('actualite_filter_article');
    }

    return $block;
  }

  function lnr_theme() {
    $module_path = drupal_get_path('module', 'lnr');

    return array(
      'actualite_filter_article' => array(
        'variables' => array('result' => NULL),
        'path' => $module_path. '/templates',
        'template' => 'actualite-filter-article',
        //leave off .tpl.php
      ),
    );
  }

```

The template of the module is loaded correctly, but once I copy paste it in the theme templates directory it is not overriden. (the name of the template file is : actualite-filter-article.tpl.php ). What aam i doing wrong ?

Thanks in advance

# Answer
> 0 votes
I think you are missing the argument for the hook\_theme so you can do it this way

```
/**
* Implements hook_theme().
*/
function lnr_theme($existing, $type, $theme, $path) {
 $items = array();
 $path = $path . '/templates';

 $items['actualite_filter_article'] = array(
  'path' => $path,
  'template' => 'actualite-filter-article',
 );

  return $items;
}

```

Give it a shot

# Answer
> 0 votes
All right I found where the problem came from, in this project I also used a custom theme named "lnr", the very same name as the one used by my custom module.

To solve it I renamed and reinstalled my module wich is the best course of action in my opinion (who knows what bugs this might induce ...).

If you don't want to rename your module you may also solve the problem by testing the type in your theme hook like so :

```
  function lnr_custom_theme($existing, $type, $theme, $path) {

    if($type == 'module')
    {
      return array(
        'actualite_filter_article' => array(
          'path' => $path. '/templates',
          'template' => 'actualite-filter-article'
        ),
      );
    }
    return array(); //will raise fatal error if void
  }

```

Credits goes to this guy : https://api.drupal.org/comment/19089#comment-19089

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


# Question
Title: Retain revision author when editing revision
I am using the Revisioning module and it has an option when saving nodes: 'Modify current revision, no moderation'.

When selecting that option I want to retain the node revision author.

So far I think I need to do this:

Create my own submit callback for node\_form and replace the submit button with my own so that the default submit handler is not called.

Copy the code out of the default submit handler into my new hander. Then before node\_save is called I must impersonate revision author if my condition is met.

Is this right, or is there a better way to achieve this?

# Answer
> 0 votes
The solution turned out to be quite simple:

```
function MYMODULE_revisionapi($op, $node_revision) {
  switch ($op) {
    case 'post update':
        if (isset($node_revision->revision_operation)){
          switch($node_revision->revision_operation) {
            case 0:
              db_update('node_revision')
                ->fields(array('uid' => $node_revision->revision_uid))
                ->condition('vid', $node_revision->vid)
                ->execute();
              break;
            case 1:
              break;
            case 2:
              break;
          }
        }
      }
      break;
  }
}

```

# Answer
> 0 votes
You definitely don't need to copy, replace, override, etc.

Node revision information is handled here. As you can see, the revision author is maintained, but most use-cases will call to show the original author.

Depending on your situation, there's many ways to show the revision author instead. For example, I see that the revisioning module you're using provides a `revision-author` token in `revisioning_tokens.inc`.

Other possibilities: hook\_node\_view in a module, template\_preprocess\_node in a theme's `template.php`, `node--NODE-TYPE.tpl.php`, etc.

Edit: BTW, if you went about updating the author ID like you mentioned, you would effectively change the ownership of the node to another user, which probably isn't a good idea!

---
Tags: nodes
---


# Question
Title: How to count webform radio button submissions
What would be the best way to count all submissions (True & False) of a radio button type in a web form?

There are about 100 radio buttons in each survey form so need to get a total number of True values

# Answer
> 0 votes
If you want do the number count after submit is done

1. Login as Admin
2. open your webfrom
3. Click Result
4. From webfrom menu click Analysis

It will give you the most complete Analysis of your form.

# Answer
> 0 votes
This pulls all submissions and results

SELECT `webform_submitted_data`.`sid`, `webform_submitted_data`.`data`, `webform_component`.`type`, `webform_component`.`form_key`, `webform_component`.`name` FROM `webform_submitted_data` INNER JOIN `webform_component` ON (`webform_submitted_data`.`cid` = `webform_component`.`cid`) WHERE `webform_submitted_data`.`sid` = :sid AND `webform_component`.`type` = 'select' GROUP BY webform\_component.form\_key

---
Tags: webforms
---


# Question
Title: How can I get the fivestar module to submit the page url to the database?
I know the module stores the entity\_id of the "page"/node and I can translate the enity\_id's (node id's) to url paths like so, so I can display them in a view:

```
function MYMODULE_views_pre_render(&$view) {
  // Translate the enity_id's to url paths.
  $results = $view->result;
  foreach ($results as $item =>  $data) {
    $view->result[$item]->votingapi_vote_entity_id = url('node/' . $data->votingapi_vote_entity_id);
  }
}

```

The problem I have is that when I add a filter to my view so that I can filter the content by url path it still requires to me add an actual entity\_id in the filter field (if this makes sense). I want to be able to extend the fivestar vote submission so that it also submits the node path. This will allow me to quickly add a filter to my view and filter the content by url path. I'm currently struggling with this and nothing seems to work. Any ideas?

# Answer
what about something like this:

* create a hidden field to include the path of the current node
* using Rules, set an event after node save to populate that field with the nodes path
* filter in views based on that field

I'm not certain if Rules will be able to pick up the new path, but I think it would trigger far enough into the process that the node path would be set.
> 1 votes

---
Tags: views, rating
---


# Question
Title: How to create multiple blocks for blog teasers from a single view automatically
I have created a site whose home page is built in a way that it will display 4 latest blog posts in separate blocks all the time.

I have created a view and successfully created a single block displaying one latest blog post, but I am not sure what to do to get the other 3 blocks generated automatically. Any idea?

# Answer
If I understand the question correctly - In views, create a new block for each instance of the block you want by clicking on +Add:

You could also create a completely new view, but this keeps things organized.

Where you put in the number of items to display, you can change the **offset** of the item:

In this way you can set the second block to have an offset of 1, the third 2, and so on. You can then create 4 blocks that each contain one of the most recent 4 items.
> 0 votes

# Answer
If you want to have 3 more blocks similar to that one, you could go to the view using the view UI, and clone the one you already have, setting the proper offset to the other three.

For cloning a display (in your case a block), you go to your view, click on the block link, once you are seeing your display you should see another link (select list) on the top-right of your screen. First item on this select list is "Clone \[your display name\]" (the others are "delete" and "disable").

But I'm not sure if you want that. "Automatically" is a little ambigous term.
> 0 votes

---
Tags: views, blocks
---


# Question
Title: Can't Rewrite the output of this field in views 7.x-3.3
I don't know if I am missing something, but when I check the box for Rewrite the output of this field or anything under the style options to customize the HTML nothing happens. I check it, save it, open it again and the boxes are unchecked. Anyone know what’s going on?

**Edited for clarity**. I create a new view, with the following settings: Page, Format:Unformatted list, Show:Fields, Fields is Content: Title. In the settings for Content: Title I check to create a label. I click under “Style settings” Customize field HTML, Customize label HTML, Customize field and label wrapper HTML or even Rewrite the output of this field, but nothing happens. If I save the checkbox goes back to unchecked

**SOLUTION** Got it. Views 7-3.3 does not work with jQuqery 1.7+. It prevents the box from expanding after clicking the checkbox

Source: http://drupal.org/node/1494860

# Answer
SOLUTION Got it. Views 7-3.3 does not work with jQuqery 1.7+. It prevents the box from expanding after clicking the checkbox

Source: http://drupal.org/node/1494860
> 9 votes

# Answer
The same problem happens when you use jQuery 1.10 or 1.9 with Drupal 7.31. Trying to edit a field in a View and checking boxes does not expand the relevant form elements.

One solution is to use the jQuery Update module that upgrades the version of jQuery in Drupal core to a newer version of jQuery.

Download the module, enable it and go to the page **/admin/config/development/jquery\_update**. The "Default jQuery Version" dropdown menu allows you to select the version of jQuery that you want to use.

I selected the 1.8 jQuery version and now I have no problem editing the View fields.
> 1 votes

---
Tags: views, theming
---


title: Making nodes from XLS files

text:
# Question
Title: Making nodes from XLS files
I'm trying to add a +2000 video database (stored on youtube) to my website. I have an excel file with on every line the video title, the url and the keywords.

Is there an easy way to automate this process rather then copy pasting +2000 times in to new nodes?

Kind regards!

# Answer
You can achieve that using the Feeds module

> Import or aggregate data as nodes, users, taxonomy terms or simple database records.
>
> * One-off imports and periodic aggregation of content
> * Import or aggregate RSS/Atom feeds
> * Import or aggregate CSV files
> * Import or aggregate OPML files
> * PubSubHubbub support
> * Create nodes, users, taxonomy terms or simple database records from import
> * Extensible to import any other kind of content
> * Granular mapping of input elements to Drupal content elements
> * Exportable configurations
> * Batched import for large files

This article might help you to achieve this.
> 2 votes

# Answer
You can use view inside node and Feed Import
> 2 votes

# Answer
Piece of cake!

First of all here is a question I have recently answered on how to import content from .CSV file and create nodes using the feeds module. You can develop a solution with this answer as a helper.

Alternatively you can instruct your FEED module to get the videos from youtube directly rather than having the EXCEL middleman. You need to make use of the Youtube Feeds Parser Module and the modules it REQUIRES.

Once you have enabled the youtube feeds module, you should have access to an extra parser which would allow you to map fields of the content type to specific metadata of youtube videos. You can then hook this Feed Importer into a content types and instruct the CRON to run it automatically in the background - magic.

See the review of Youtube Feeds Parser here
> 0 votes

# Answer
Another approach (with custom module): 1. install YouTube Field, add new field(YouTube video) to your content type. 2. install PHPExcel module. 3. create simple custom module (.module file with single hook\_enable function):

```
function MYMODULE_enable()
{
  module_load_include('inc', 'phpexcel');
  $path = 'sites/default/files/MYFILE.xls';
  $result = phpexcel_import($path);
  if (is_array($result)) {

    foreach ($result as $key => $value) {
      // here you need to know what's being returned by $value (you can use dpm() function from Devel module to debug the $result array).. I assume it's an object
      $node = new stdClass();
      $node->type = 'MY_TYPE';

      node_object_prepare($node);

      $node->title = $value->title;
      $node->MY_YOUTUBE_VIDEO_FIELD_NAME['und'][0]['value'] = $value->url;

      node_save($node);
    }

  }
  else {
    drupal_set_message(t('Oops ! An error occured !'), 'error');
  }
}

```

hook\_enable is launched only once when you enable your module (I am using it here to prevent launching tnat piece of code unnecessarily).. If you want you can run that snippet at any request (without hook\_enable), or from separate file (outside or inside of drupal by `drush scr`).
> 0 votes

---
Tags: nodes, files
---


title: Problems with notice

text:
# Question
Title: Problems with notice
I'm new in Drupal. I had to migrate a page from a client to another server. The page work well on a development test but not anymore.

I have these errors:

```
Notice: Undefined index: highlighted en include() (línea 126 de /home/portal/public_html/modules/system/page.tpl.php).
Notice: Undefined index: sidebar_first en include() (línea 138 de /home/portal/public_html/modules/system/page.tpl.php).
Notice: Undefined index: sidebar_second en include() (línea 144 de /home/portal/public_html/modules/system/page.tpl.php).
Notice: Undefined index: hotel en drupal_theme_initialize() (línea 100 de /home/portal/public_html/includes/theme.inc).
Notice: Trying to get property of non-object en _drupal_theme_initialize() (línea 146 de /home/portal/public_html/includes/theme.inc).
Notice: Trying to get property of non-object en _theme_load_registry() (línea 335 de /home/portal/public_html/includes/theme.inc).
Notice: Undefined index: hotel en theme_get_setting() (línea 1431 de /home/portal/public_html/includes/theme.inc).
Notice: Trying to get property of non-object en theme_get_setting() (línea 1478 de /home/portal/public_html/includes/theme.inc).

```

The link to the page is: http://www.portaldelcuadrado.com.ar/ What can i do?

Thanks

# Answer
Is the `theme` on the test site and the live site the same `theme` with the same `regions` defined. The drupal theme() function is complaining that `regions` are not defined which the body (node) content is trying to be placed in.
> 1 votes

---
Tags: 7
---


# Question
Title: Get current URL arguments inside ajax callback?
I have created custom module called 'mymodule'.

In this URL **localhost/es/mymodule/name/1/2/3**, I have this field:

```
$form['name'] = array(
  '#title' => t('Enter name'),
  ...
  '#ajax' => array(
    'event' => 'blur',
    'callback' => 'mymodule_ajax_callback',
    'wrapper' => 'my-wrapper',
    'method' => 'replace',
  ),
  ...
);

```

My ajax callback is successfully called:

```
function mymodule_ajax_callback($form, &$form_state) {
  ...
  return ...
}

```

However, inside 'mymodule\_ajax\_callback', I need to get the current URL arguments of the page such that `arg(1) = 'name'`, `arg(2) = 1`, `arg(3) = 2`, and so on.

By nature, Drupal uses the URL **system/ajax** so calling `arg(N)` does not work as I need it to be.

How to get the current URL arguments using `arg()` inside the ajax callback?

---

EDIT 1:

I thought of using `$_SESSION[...] = arg(1); $_SESSION[...] = arg(2); ...` on my form and calling the session variables on my ajax callback. But I am looking for a better way without using session but only using drupal methods if available.

# Answer
The arguments passed to the page callback are saved in `$form_state['build_info']['args']`, with the exception of the form ID.

If you use the following definition for the menu item, you would get them there. (Replace `'form ID`' with the form builder ID.)

```
$item['name/%/%/%'] = array(
  // …

  'page callback' => 'drupal_get_form',
  'page arguments' => array('form ID', 1, 2, 3),

  // …
);

```

### References
> 6 votes

# Answer
Create the hidden field in the form & store the current url as below:

```
$current_url = arg(1);
$form['current_url'] = array('#type' => 'hidden', '#value' => $current_url);

```

And that than you can access the above hidden field in the ajax callback as `$form_state['values']['current_url']`

The above method worked for me.
> 1 votes

# Answer
This is the trick I use for the OpenLayers module:

`function openlayers_ui_admin_settings($form, &$form_state) {
 $form['openlayers_default_map'] = array(
 '#type' => 'select',
 '#title' => t('OpenLayers Default Map'),
 '#description' => t('This is the default map that will be used
 in cases where one is not defined. It will also be used as
 the default when creating new maps.'),
 '#options' => $options,
 '#default_value' => variable_get('openlayers_default_map', 'map1'),
 '#ajax' => array(
 'callback' => '_ajax_reload_default_map',
 'method' => 'replace',
 'wrapper' => 'default_map_ajax',
 'effect' => 'fade'
 );
 $form['current_path'] = array('#type' => 'value', '#value' => current_path());
 return system_settings_form($form);
}
function _ajax_reload_default_map($form, &$form_state) {
 $_SESSION['current_path'] = $form_state['input']['current_path'];
 $map = openlayers_object_load('map', $form_state['values']['openlayers_default_map']);
 $form['default_map']['map'] = array(
 '#markup' => openlayers_render_map($map)
 );;
 return $form['default_map'];
}`

Instead of using `$form_state['values']`, I use `$form_state['input']`, it doesn't get updated through the AJAX calls and the current path remains correct.
> 0 votes

---
Tags: 7, forms, ajax
---


title: Views Slideshow Continuous Pager

text:
# Question
Title: Views Slideshow Continuous Pager
I'm in need of a little help here. I've recently begun my first website (ncpbc.us) and I began with building a Slideshow on my front page. However, the content that feeds into the slideshow uses nodequeue and will hold potentially hundreds of articles. Right now the queue holds 10 articles. The problem I'm having is that the slideshow pager only shows 5 thumbnails at a time and any new content simply makes the oldest content drop off. I'm trying to find a way that allows the user to advance the pager to the next set of 5 thumbnails.

Examples of this are at yahoo.com and http://joomlakave.com/joomla-modules/responsive-news- slider-like-yahoo. How would you suggest I go about this?

# Answer
> 0 votes
The link in the question is not working but after searching in google about the link I come across this page

If your looking for something like this then the best way will be to install view module and views Slideshow module

View Slideshow can be used to create a slideshow of any content that can appear in a view. to create a slideshow with thumbnails please check the video

---
Tags: views, paging, javascript
---


title: jQuery doesn't work on new hosting

text:
# Question
Title: jQuery doesn't work on new hosting
I'm using small jQuery script to change src argument on img tag. It works without any problems on my hosting but after migrating website on client's hosting this script doesn't work at all.

I have checked with Firebug and the script is there. I also tried to access to `[website]/misc/ui/jquery.ui.core.min.js` in browser and jQuery is shown. I tried to install jquery\_update module and change versions of jQuery (with and without CDN). None of this helped.

I noticed on 'Status report' page warning because of PHP mbstring extension.

Is this could be the possible reason for not working?

In Firebug my script shows like:

```
<script><![CDATA[
]]><!--//--><![CDATA[// ><!--

jQuery(document).ready(function() {
    var img;
        img = '/sites/all/themes/ave/img/logo2.png';
        jQuery('.logo-img a img').attr("src", img);
    });

//--><!]]><![CDATA[
]]></script>

```

Do you have some ideas or maybe similar experience?

# Answer
> 1 votes
Your issue is in this line

```
img = '/sites/all/themes/ave/img/logo2.png';

```

It should be something like this:

```
img = location.protocol + "//" + location.host + '/sites/all/themes/ave/img/logo2.png';

```

and if that does not work just inspect the src param of the image and adjust accordingly.

And perhaps replace the whole script with this:

```
(function ($, Drupal, window, document, undefined) {
    Drupal.behaviors.MYMODULE = {
        attach: function(context, settings) {
            var img = location.protocol + "//" + location.host + '/sites/all/themes/ave/img/logo2.png';
            $('.logo-img a img').attr("src", img);

        }
    };

})(jQuery, Drupal, this, this.document);

```

---
Tags: 7, javascript
---


# Question
Title: Cascade entity reference in a content type
I have two content types parts and maintenance. Parts has 3 fields.

* Oven type
* Oven Part
* Parts price

In maintenance i have a entity reference field with autocomplete that points to parts. So now when a user types in a part the autocomplete show a list of possible matches.

The problem is that 2 different ovens can have the same parts but the price is different. So I would like it to be a cascade so that a user can first select the oven and then select the part for this oven.

* select the oventype
    + show the parts that fit this oven

# Answer
It sounds like you want to try to use Reference Field Option Limit:

> Example 1:
>
> countries and cities Suppose you want to label articles (or products, or businesses, etc) by both city and country so both can be used for filtering and searching. You could use a hierarchical taxonomy with city terms as children of country terms, but that doesn't make sense when you come to set up Views filters.
>
> With this module, create two separate taxonomies for country and city (or content types, or whatever entity you want to use). Then add a reference field so that each city points to its country: eg, the term 'Paris' has a reference to 'France'.
>
> Then when editing an article, selecting 'France' in the country field will cause the city field to update to show only cities in France.

How you denote the different parts based on their price. I dunno. But you can look at this module and if need use it as a starting point to extend or create javascript behaviors or alter sql queries it's using.
> 0 votes

---
Tags: nodes, entities
---


# Question
Title: How to split Commerce Order: Shipping Address and/or Billing Address into different lines in Views
In a Views view that pulls out order information, I'm trying to put the Shipping and Billing addresses, but the addresses seem to be all joined up, and there's no way to split them into different lines. I'm grabbing a field called `Commerce Order: Shipping information` and `Commerce Order: Billing Information`

At the moment it looks like:

```
Name123 StreetSome RoadSome CitySome CountryPOSTCODE

```

I want it to look like:

```
Name
123 Street
Some Road
Some City
Some Country
POSTCODE

```

I'm outputting the result to a CSV export using the Views Data Export module. So I only need it to look readable when I open it with MS Excel.

# Answer
> 1 votes
The addresses from the commerce customer panes come from the module addressfield, you need to check which version of it you're using because since this issue, there's independent component support for views, you'll probably need to either apply the patch or use the -dev version for now.

# Answer
> 3 votes
Thanks to this question, and Stan Ascher's answer, I was able to find the correct tokens to use with Rules. I thought I would share it here:

```
[commerce-order:commerce-customer-billing:commerce-customer-address:name_line]
[commerce-order:commerce-customer-billing:commerce-customer-address:thoroughfare]
[commerce-order:commerce-customer-billing:commerce-customer-address:locality], [commerce-order:commerce-customer-billing:commerce-customer-address:administrative_area] [commerce-order:commerce-customer-billing:commerce-customer-address:postal_code]

```

# Answer
> 2 votes
I was looking at this website here - http://www.poi-factory.com/node/7347 which talk about using excel with line breaks.

Perhaps you can try rewriting the output or your display - You'll need the token module installed on your site

Click on the settings field in views to open it's settings

Under rewrite results group, Check the box for "Rewrite the output of this field"

Use these tokens (You can find them and more under "replacement patterns"

```
[commerce_customer_address-name_line <br>
[commerce_customer_address-thoroughfare] <br>
[commerce_customer_address-locality]<br>
[commerce_customer_address-administrative_area]<br>
[commerce_customer_address-postal_code]<br>
[commerce_customer_address-country]

```

You may have to experiment around to get exactly what you want, but we have used this method in the past. For US addresses we use:

```
[commerce_customer_address-name_line] <br>
[commerce_customer_address-thoroughfare] <br>
[commerce_customer_address-locality], [commerce_customer_address-administrative_area],
[commerce_customer_address-postal_code]<br>

```

---
Tags: 7, views, commerce
---


title: Conditional mapping with Feeds

text:
# Question
Title: Conditional mapping with Feeds
Using Feeds, I am trying to import products from a source CSV. One of the CSV columns contains the quantity of items in stock. The goal is to map it to a product 'Stock Status' field. If the quantity field is greater than zero, 'Stock Status' is 'In Stock'; if zero, 'Stock Status' is 'Out of Stock'.

I didn't see a Feeds Tamper plugin or combination of plugins that would work and my attempts to use Rules so far have failed.

Thank you in advance for any help.

# Answer
> 1 votes
The easiest is to just put a formula into a spreadsheet and alter your source csv.

Else you could write your own feeds tamper plugin.

Create an empty file called 'stock.inc' and place it into the feeds\_tamper/plugins directory. Add this to it:

```
<?php
$plugin = array(
  'form' => 'feeds_tamper_stock_form',
  'callback' => 'feeds_tamper_stock_callback',
  'name' => 'Calculate stock',
  'multi' => 'direct',
  'category' => 'Other',
);

function feeds_tamper_stock_form($importer, $element_key, $settings) {
  return array(
    'help' => array(
      '#markup' => t('Sets the stock status'),
    ),
  );
}

function feeds_tamper_stock_callback($result, $item_key, $element_key, &$field, $settings, $source) {
  $field = $result->items[$item_key] > 0 ? 'In Stock' : 'Out of Stock' ;
}

```

Clear your cache.

I have not tested this but I believe it will get you close.

# Answer
> 0 votes
Using J. Reynolds' answer as a guide, I downloaded Feeds Tamper PHP and added the following code to a feeds tamper PHP plugin.

```
if ($item['quantity'] > 0) {
  return 1;
} else {
  return 2;
}

```

The destination field is of 'List (text)' type with 1 representing 'in stock' and 2 representing 'out of stock'.

---
Tags: rules, feeds
---


# Question
Title: How do I create a list with the previous and next referenced entities of the one being viewed?
I have 2 content types: Books and Chapters.

Books have an entity reference field that can accept unlimited values. Chapters have an entity reference field (single value) that corresponds to a book.

These entity reference fields are "linked" with the Corresponding Entity References module.

My goal is to create a block that will be displayed at the top of the Chapter nodes that will act like a pager of some sort and will display the previous and next chapters from the one that is being viewed.

For example, when someone views Chapter 1 of a book, the block will show:

* Chapter 1 (no link)
* Chapter 2 (link to Chapter 2)
* Chapter 3 (link to Chapter 3)
* Chapter 4 (link to Chapter 4)
* Chapter 5 (link to Chapter 5)

When someone is viewing Chapter 10, the block will show:

* Chapter 8 (link to Chapter 8)
* Chapter 9 (link to Chapter 9)
* Chapter 10 (no link)
* Chapter 11 (link to Chapter 11)
* Chapter 12 (link to Chapter 12)

and when someone is viewing the last chapter (say chapter 25):

* Chapter 21 (link to Chapter 21)
* Chapter 22 (link to Chapter 22)
* Chapter 23 (link to Chapter 23)
* Chapter 24 (link to Chapter 24)
* Chapter 25 (no link)

My immediate thought was to create a view, but after I have created the view with the proper contextual filter and relationship, there was no option to sort the results based on the weight of the Chapter in the Book's entity reference listing.

I then tried to use Views PHP and sort the results via PHP with code like that:

```
$node = node_load($row1->nid);
$weights = $node->field_book_contained_chapter['und'];
array_walk($weights, function (&$v, $k) { $v = array_shift($v); });
return array_search($row1->nid_1, $weights) - array_search($row2->nid_1, $weights);

```

which works fine only if you select to display all items (doesn't work with pagers) but is also very inefficient: it runs through the whole array of referenced entities for every comparison between two rows (and some of my books have more than 1300 chapters). I haven't tested how it performs but my gut tells me that it's not a very elegant solution (I will also have to do additional filtering after I sort them).

Now I'm thinking about creating a custom block with php code that will traverse the $node-\>filed\_book\_contained\_chapter\['und'\] array and find the neighboring articles of the current article. This seems like a more efficient solution than the views' one, but still feels kind of an awkward approach.

Is there an obvious way that I'm missing to achieve the functionality that I'm after?

# Answer
> 3 votes
A solution that comes to mind could include creating a block in a custom module and manually generate your pager-like unordered list. I wrote some quick code to show you how it can be done. I also added some comments in there to help you understand what I'm doing.

Notice, that this code is assembled in a hurry so you may find additional optimizations that you can perform in there.

```
/**
 * Implements hook_block_info().
 *
 * Declares your custom pager block.
 *
 */
function YOUR_MODULE_block_info() {
  $blocks = array();
  $blocks['parent_book'] = array(
    'info' => t('Parent Law'),
  );

  return $blocks;
}

/**
 * Implements hook_block_view().
 *
 * Renders the block. Calls the main rendering function.
 *
 */
function YOUR_MODULE_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'parent_book':
      $block['subject'] = '';
      $block['content'] = _YOUR_MODULE_parent_book_content_generator();
      break;
  }

  return $block;
}

/**
 * Helper function: renders the block's content.
 */
function _YOUR_MODULE_parent_book_content_generator() {
  // We'll need this to create the links to the articles.
  global $base_url;
  // Initialize the $output variable
  $output = '';
  // Checks if this is a node page.
  // No content type checking, you'll either have to add extra code
  // to narrow it down or use something like panels.
  if (arg(0) == 'node') {
    $book_chapter_nid = arg(1);
    if ($book_chapter_nid) {
      // Load the current chapter node object
      $book_chapter = node_load($book_chapter_nid);
      // Get the container book's nid and load its object.
      // If you have a multilingual site you'll have to pass the node's language in there
      $book_nid = $book_chapter->field_container_book[LANGUAGE_NONE][0]['target_id'];
      $book = node_load($book_nid);
      // Create a references array and walk through it to remove the intermediate arrays
      $references = $book->field_book_contained_chapter[LANGUAGE_NONE];
      array_walk($references, function(&$value, $key) {
        $value = array_shift($value);
      });
      // Setup the items that you want to display here
      $items_to_display = 5;
      // Find the current chapter's position in the array
      $current_chapter_position = array_search($book_chapter_nid, $references);
      // Crude method to get a maximum number of loops that will be needed
      $no_of_loops = (2*($items_to_display - 1)) + 1;
      // Initialize our final array
      $chapters_to_show = array();
      // Push the current chapter in the array
      array_push($chapters_to_show, $book_chapter_nid);
      // Index to stop adding items when we've reached our goal of items to display
      // Initialized to 1 since we've already added the current chapter
      $items_added = 1;
      // Loop a specific amount of times
      // Notice that we'll always break out of the loop before it ends
      // i.e. when the number of items added becomes equal to the number of items that we wanted to display
      for ($index = 1; $index <= $no_of_loops; $index++) {
        // The condition to add an item before our current chapter is the not-negative index
        if (($current_chapter_position - $index) >= 0) {
          // Previous chapters are added at the top of the array
          array_unshift($chapters_to_show, $references[$current_chapter_position - $index]);
          // Update index
          $items_added++;
        }
        // Check if we need to exit the loop right now.
        // This is needed for even amount of items to display
        if ($items_added >= $items_to_display) {
          break;
        }
        // The condition to add an item after our current chapter is if the array key exists in the $references array
        if (array_key_exists(($current_chapter_position + $index), $references)) {
          // Next chapters are added at the bottom of the array
          array_push($chapters_to_show, $references[$current_chapter_position + $index]);
          // Update index
          $items_added++;
        }
        // Check if need to exit the loop again.
        if ($items_added >= $items_to_display) {
          break;
        }
      }
      // Time to print our unordered list
      $output .= '<ul class="book-chapter-pager">';
      // Loop through the array that we created and store the nid in $current_chapter variable
      foreach ($chapters_to_show as $current_chapter) {
        // Load the node since we need it to display the title
        // This: check_plain(db_result(db_query('SELECT title FROM {node} WHERE nid = %d',$nid)));
        // is also possible and more efficient than loading the entire node but revisions need to be taken
        // into account if it is used.
        $node = node_load($current_chapter);
        // Wrapper for the current list item
        $output .= '<li class="book-chapter-pager-item">';
        // If we are printing the current chapter, we don't want to print the link markup
        if ($current_chapter <> $book_chapter_nid) {
          $output .= '<a href="' . $base_url . '/node/' . $current_chapter . '" class="book-chapter-pager-link">';
        }
        // The title needs to be printed in any case though
        $output .= $node->title;
        // Close the link markup if applicable
        if ($current_chapter <> $book_chapter_nid) {
          $output .= '</a>';
        }
        // Close the list item markup
        $output .= '</li>';
      }
      // Close the unordered list markup
      $output .= '</ul>';
    }
  }
  // Return our final input which will be stored in $block['content']
  return $output;
}

```

---
Tags: 7, views, entities
---


# Question
Title: Views exposed filter using Solr only returning results for exact phrase
We're using a Views exposed filter (using the Search API Solr) that searches a Solr index to search for node titles, but only seeing exact phrases matched.

For example, if we have a node titled 'Trees of the Eastern Seaboard,' and do a search for 'Trees,' the node is returned. If we search for 'Trees of' the node is also returned. However if we search for 'Trees Seaboard,' no results are returned.

The Solr search index is using the 'Fulltext' setting. I've tried switching it to 'String' but that setting returns no results at all for the view.

The default search is also configured to use Solr, and returns results correctly for 'Trees Seaboard.'

Is there a way to allow the Views exposed filter to return the correct results for not exact phrases? (keywords?)

Is there a way to allow the filter to accept a 'contains any' setting for the search?

# Answer
This is a screenshot of the basic search view that we setup for our Search API + Apache SOLR configuration:

The settings for the filter can be shown here:
> 3 votes

---
Tags: search, views
---


# Question
Title: Active user account after administration's confirmation
How to, by using module Profile2 Registration Path, the user's account becomes active after it is activated by the administrator. The administrator should get email when user creates new account.

# Answer
I don't think you need a contrib module for that. You can set " Visitors, but administrator approval is required" under "Who can create accounts" on `admin/config/people/accounts`.

As for sending e-mail, create an advanced action at `admin/config/system/actions` and then set it on `admin/structure/trigger/user` to be triggered by account creation.

The core Action and Trigger modules are all that are required for that.
> 2 votes

---
Tags: users
---


title: Using Grunt.js with Drupal

text:
# Question
Title: Using Grunt.js with Drupal
I'm in need of an organization system for my JavaScript code Drupal. Currently, I've got it inside a folder in my theme's directory: "`sites/all/themes/mytheme/js`". I've looked at using Grunt.js, and wondering how I might implement it into my website. How would it help me?

Can it help organize large JavaScript files?

Could it help improve the speed of my website?

# Answer
I started using Grunt.js by reading their easy to follow tutorial. Then, I created a Gruntfile.js inside of my theme’s js directory “`sites/all/themes/mytheme/js/Gruntfile.js`”:

```
  module.exports = function(grunt) {
    grunt.initConfig({
       pkg: grunt.file.readJSON('package.json'),
       concat: {
          main: {
             src: [
                'src/*.js',
             ],
             dest: 'production.js'
          }
       },
       uglify: {
          build: {
             files: {
                'production.min.js': 'production.js',
             }
          }
       },
       jshint: {
          files: ['Gruntfile.js', 'src/*.js'],
          options: {
             globals: {
                jQuery: true,
                console: true,
                module: true,
                document: true
             }
          }
       },
       watch: {
          files: ['src/*.js'],
          tasks: ['concat', 'jshint', 'uglify']
       }
    });

    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-qunit');

    grunt.registerTask('test', ['concat', 'jshint']);
    grunt.registerTask('default', ['concat', 'jshint', 'uglify']);
  };

```

My Gruntfile does 3 things for me (right now):

1. Combines smaller, more manageable files inside `src/` into one file.
2. Checks for errors in my compiled file.
3. Compresses my file when I’m ready for production.

All I have to do is run `grunt watch` from the terminal and whenever one of the files inside `src/` is changed my `production.js` file is updated and compressed. When I’m all done debugging I just change the following in my .info file:

```
scripts[] = js/production[.min].js

```

This results in faster page loads because only one (smaller) request is being performed as opposed to many uncompressed file requests.
> 2 votes

---
Tags: theming, javascript
---


title: Jquery update "intterupts" Admin Menu

text:
# Question
Title: Jquery update "intterupts" Admin Menu
Drupal 7 system. minimalistic, almost no modules installed and the site works fine. The problem:

From the moment I've installed the module Jquery Update, There is no more Dropdown by the Admin Menu module... Please help.

# Answer
> 2 votes
Navigate to

```
admin/config/development/jquery_update

```

and set the Default jQuery Version to 1.8 or higher

and the Alternate jQuery version for administrative pages to 1.7 (1.5 and lower has issues with views and other modules)

Then clear your Drupal and browser cache if need be.

If you don't see these settings in jquery update ui then install the latest dev version of jquery update.

# Answer
> 0 votes
When you first install and enable this module, it will be set to 1.10. In my experience, almost everything will be buggy if set at 1.8 or higher. I always have my sites set at 1.7, and that's what I would recommend to use site wide.

---
Tags: javascript
---


title: LDAP password sync, happens every login

text:
# Question
Title: LDAP password sync, happens every login
I've successfully setup the LDAP configuration so that users can login to Drupal using their LDAP account. I've mapped the Drupal password to the LDAP password so that when users change their Drupal password it updates their LDAP password.

I mapped `Pwd: User only` to `[unicodePwd]` and it synchronizes `On LDAP Entry Creation` and `On Synch to LDAP Entry`.

Those are the only two Synch options, and I need them in order to set the LDAP password.

**The Question** How can I synchronize the password only when the user sets their Drupal password? The LDAP password expiration date keeps changing every time a user logs into Drupal because it synchronizes the password with LDAP.

Edit: I actually thought I answered this question by only checking `On LDAP Entry Creation` and not `On Synch to LDAP Entry`. That did prevent the password from being set every login, but it also prevented it from being changed at all! Problem remains...

# Answer
The password field is special in that it should only be synchronized when the password changes. The most current version of the LDAP module can trigger field synch's either on account creation or during any account synch. It doesn't allow the password field to be triggered only during password changes.

The password field can be unicodePwd for AD, or userPassword for other LDAP databases.

I had to modify the 7.x-2.x April 8, 2014 version of LDAP to get this to work. Within the modifyLdapEntry function we need to know if the password field is being modified. Don't synchronize the password field if we know the password is not changed (which is true during login synchronization). Also, do not synchronize the password if it's not set (such as during the edit account page).

Modify LdapServer.class.php, function modifyLdapEntry(), adding global variables for the current password, and for whether or not the password is being changed. If there is no current password but we are changing the password (such as password reset form or admin edit user form), set the password. Also, if the current password is given and it does not match the new password (such as user edit form), set the password. Otherwise, unset that property from being synchronized.

```
..

  global $current_password;
  global $changing_password;
  if ((empty($current_password) && $changing_password) || (!empty($current_password) && $current_password != $attributes['unicodePwd']))
  {
    $attributes['unicodePwd'] = ldap_servers_convert_password_for_active_directory_unicodePwd($attributes['unicodePwd']);
  }
  else
  {
    unset($attributes['unicodePwd']);
  }

..

```

Modify the ldap\_user.module, function ldap\_user\_grab\_password\_validate(), and set the current password if it is given, and set the changing password variable if we know it's changing.

```
/**
 * store password from logon forms in ldap_user_ldap_provision_pwd static variable
 * for use in provisioning to ldap
 */
function ldap_user_grab_password_validate($form, &$form_state) {

   // This is not a login form but profile form and user is inserting password to update email
  if (!empty($form_state['values']['current_pass_required_values'])) {
    if (!empty($form_state['values']['current_pass']) && empty($form_state['values']['pass'])) {
      ldap_user_ldap_provision_pwd('set', $form_state['values']['current_pass']);
    }
    // Or this is a profile form where the user is updating their own password
    elseif (!empty($form_state['values']['pass'])) {
      global $current_password;
      $current_password = $form_state['values']['current_pass'];
      ldap_user_ldap_provision_pwd('set', $form_state['values']['pass']);
    }
  }
  // otherwise a logon form
  elseif (!empty($form_state['values']['pass'])) {
    if ($form['account']['pass']['#type'] == "password_confirm") {
      global $changing_password;
      $changing_password = TRUE;
    }

    ldap_user_ldap_provision_pwd('set', $form_state['values']['pass']);
  }
}

```
> 0 votes

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


title: Flexslider change caption style

text:
# Question
Title: Flexslider change caption style
How do I change the caption style in Flexslider? I know how to change what the caption text, but I don't know how to change the size, font style, color, etc. I've been pulling my hair out trying to get this to work today. I've changed everything around it, through the flexslider.css file, but not the actual text.

# Answer
> 1 votes
That is going to be dependent on the name of the field you used for that field. If you inspect, using your browser's inspection tool (right click on the element and choose "inspect element") you can search the DOM for the appropriate div to use to style the field as a whole.

Most likely the field name you are looking for will be similar to:

```
.field-name-field-description

```

It should use that naming convention with the machine name of the field at the end, with the spaces as underscores.

This will not exist in the flexslider.css file by default. You will have to add this. I would recommend that you add this to your theme css rather than the flexslider's css.

Try adding these attributes to your field's selector initially to get a good idea of where it sits on your page relative to the flexslider itself:

```
float: left;
width: 100%;
background: red;

```

---
Tags: theming
---


# Question
Title: how to exclude current node from a view inside a node commerce kickstart
I know variations of this have been asked left and right but I can't get this to work.

I have a Commerce Kickstart Product Display (shopping cart form, basically a node).

Inside this content type is a display field which uses ViewField to insert a View inside the form. This View is a list of related products (nodes in the same category). I pass the category of the current node as a token %1 to the View and it works great.

However, I'd like to further exclude the current node (ie. the product being displayed) from this Related Products view.

I tried adding a second Contextual Filter:

Indexed Content: Node ID Provide Default Argument: Content ID From URL

and then checking the 'Exclude' box in the More section.

And this does nothing. The current node still displays in the Related Products View.

NOTES: 1. FWIW: This View is of Type: 'Product Display' (from Commerce) as opposed to 'Content' or 'Message')

2. There is no default argument for 'Node ID'. Only 'Indexed Content: Node ID'. Probably because of the type of View (I cloned an existing view in Commerce Kickstart as a template.)

Any ideas?

# Answer
Why don't you rather just pass the product display node id as a second parameter in your view field (you are allowed to use a comma separated list of arguments), and then don't bother with providing a default argument at all. The second argument to pass is \[node:nid\]
> 0 votes

---
Tags: views, commerce
---


# Question
Title: Attach a form input to a node that will be submitted by multiple users
I'm trying to create a content type that serves as a "Contest". Each contest needs the ability to upload an image by the user. Basically, I'm looking for the best way to attach a form field (file upload) to each Contest and be able to monitor all submissions, and by a user basis, for each individual contest, separately.

I've looked into Webform and Entityforms, but kind of running into road blocks. Does anyone have any suggestions?

# Answer
You can achieve that by the Webform module. or

Try the Simple Contest module

> Simple Contest module provides contest system for Drupal websites.
>
> Features:
>
> * contests are nodes. multiple contests of multiple contest type can be run same time
> * Two winner types : Users & Node, that means winners can be "user" or node"
> * multiple winners can be chosen by ranking/weight
> * Supports both automatic and manual winners selection
> * Winner chosen rule will be based on View. so it is up to you to decide how the winner will be selected
> * Modules integration with Views, Token, Rules, Userpoints, Date Repeat, Commerce Coupon, UC Gift Certificate & UC Coupon
> * Token integration and customized E-mail notifications

Please note the this module is in dev version. So try that in local (test) environment.
> 0 votes

---
Tags: forms, webforms
---


# Question
Title: Migrating multi-value FileField with description and display
I need to migrate nodes with attached files from Drupal 5 to Drupal 7. Basically I did it with media widget for file field what was easy but client wanted to have the functionality which allows him select which files should be displayed (this comes with file widget - so I had to change the widget).

Below is screenshot from drupal 5 node

And from new site in drupal 7

As you can see I've already did migration of those files using a callback function for specific field. Problem is I don't know how to migrate description and display options. Any idea how to migrate those two option to new site? If you want I can attached my code.

```
<?php
/**
 * @file
 * NodePageMigration class.
 */

class NodePageMigration extends TestBaseMigration {

  /**
   * Constructor.
   */
  public function __construct($arguments) {

    parent::__construct();
    $this->dependencies = array('NodeMicrositeHomepage');

    $fields = array(
      'node'                            => array(
        'nid'                           => 'nid',
        'vid'                           => 'vid',
        'type'                          => 'type',
        'title'                         => 'title',
        'uid'                           => 'uid',
        'status'                        => 'status',
        'created'                       => 'created',
        'changed'                       => 'changed',
        'promote'                       => 'promote',
        'sticky'                        => 'sticky',
      ),
      'node_revisions' => array(
        'nid'                           => 'nid',
        'body'                          => 'body',
        'teaser'                        => 'teaser',
        'timestamp'                     => 'timestamp',
      ),
    );

    $query = $this->get_db_conn()->select('node', 'n');
    $query->fields('n', array_keys($fields['node']));
    $query->join('users', 'u', 'u.uid = n.uid');
    $query->condition('n.type', 'page', '=');

    $query->join('node_revisions', 'nr', 'nr.vid = n.vid');
    $query->fields('nr', array_keys($fields['node_revisions']));

    $source_pk = array(
      'nid' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'alias' => 'n',
      )
    );

    $source_fields = array();

    foreach ($fields as $key => $values) {
      $source_fields += $values;
    }

    $this->source = new MigrateSourceSQL($query, $source_fields);
    $this->destination = new MigrateDestinationNode('page');

    $this->map = new MigrateSQLMap(
      $this->machineName,
      $source_pk,
      MigrateDestinationNode::getKeySchema()
    );

    $this->addFieldMapping('type', 'type');
    $this->addFieldMapping('title', 'title');
    $this->addFieldMapping('uid', 'uid');
    $this->addFieldMapping('status', 'status');
    $this->addFieldMapping('created', 'created');
    $this->addFieldMapping('changed', 'changed');
    $this->addFieldMapping('promote', 'promote');
    $this->addFieldMapping('sticky', 'sticky');
    $this->addFieldMapping('is_new')->defaultValue(TRUE);
    $this->addFieldMapping('body:summary', 'teaser');
    $this->addFieldMapping('body:format')
      ->defaultValue('client_input_format');

    $this->addFieldMapping('field_document_attach', 'vid')
         ->callbacks(array($this, 'getNodeUploadedDocuments'));

    $this->addFieldMapping('field_document_attach:file_class')
      ->defaultValue('MigrateFileFid');

    // $this->addFieldMapping('field_document_attach:display');
  }

 /**
  * Getting fid and list (display option in drupal 7)
  * for specific vid (node version id)
  */
 protected function getNodeUploadedDocuments($vid) {

    // Drupal 5 source
    $query = $this->get_db_conn()->select('files', 'f');
    $query->fields('f', array('fid'));
    $query->join('file_revisions', 'fr', 'f.fid = fr.fid');
    $query->fields('fr', array('list'));
    $query->condition('fr.vid', $vid, '=');

    $result = $query->execute();

    $files = array();

    foreach ($result as $row) {

      $fid = $this->importManagedFileFromRemoteFileproxy($row->fid);

      $files[] = $fid;
    }

    $fids = count($files) ? $files : NULL;

    return $fids;
  }

  /**
   * Helper function to get the image from the old site.
   */
  public function importManagedFileFromRemoteFileproxy($fid) {

    // If on file set return NULL.
    if (!$fid) {
      return $fid;
    }

    $old = $this->getFileFromFid($fid);
    // If no record in the db for the file returns NULL.
    if ($old) {

      $old_url = $this->remoteBaseUrl . 'fileproxy/' . $fid;
      $destination = 'public://' . str_replace('files/', '', $old->filepath);

      $dirname = drupal_dirname($destination);
      file_prepare_directory($dirname, FILE_CREATE_DIRECTORY);

      $file = $this->test_migrate_system_retrieve_file($old_url, $destination);

      $fid = !empty($file->fid) ? $file->fid : NULL;

    }
    return $fid;
  }

  /**
   * Helper function.
   *
   * @see system_retrieve_file()
   */
  function test_migrate_system_retrieve_file($url, $destination = NULL, $replace = FILE_EXISTS_REPLACE) {
    $parsed_url = parse_url($url);
    if (!isset($destination)) {
      $path = file_build_uri(drupal_basename($parsed_url['path']));
    }
    else {
      if (is_dir(drupal_realpath($destination))) {
        // Prevent URIs with triple slashes when glueing parts together.
        $path = str_replace('///', '//', "$destination/") . drupal_basename($parsed_url['path']);
      }
      else {
        $path = $destination;
      }
    }

    $files = &drupal_static(__FUNCTION__, array());

    if ($fid = array_search($path, $files)) {
      return file_load($fid);
    }

    // If exists in our installation, but not in the database, fake a download.
    if (file_exists($path)) {
      $result = new StdClass();
      $result->code = 200;
      $result->data = file_get_contents($path);
    }
    else {

      // Try normal download process.
      $result = drupal_http_request($url);

      // If protected use the HttpClient.
      if ($result->code == 403) {
        $client = migrate_get_http_client();
        $result = $client->download($url);
      }

    }

    if ($result->code != 200) {
      drupal_set_message(t('HTTP error @errorcode occurred when trying to fetch @remote.', array('@errorcode' => $result->code, '@remote' => $url)), 'error');
      return FALSE;
    }

    $local = file_save_data($result->data, $path, $replace);

    if ($local->fid) {
      $files[$path] = $local->fid;
    }

    if (!$local) {/**
   * Helper function.
   *
   * @see system_retrieve_file()
   */
  function test_migrate_system_retrieve_file($url, $destination = NULL, $replace = FILE_EXISTS_REPLACE) {
    $parsed_url = parse_url($url);
    if (!isset($destination)) {
      $path = file_build_uri(drupal_basename($parsed_url['path']));
    }
    else {
      if (is_dir(drupal_realpath($destination))) {
        // Prevent URIs with triple slashes when glueing parts together.
        $path = str_replace('///', '//', "$destination/") . drupal_basename($parsed_url['path']);
      }
      else {
        $path = $destination;
      }
    }

    $files = &drupal_static(__FUNCTION__, array());

    if ($fid = array_search($path, $files)) {
      return file_load($fid);
    }

    // If exists in our installation, but not in the database, fake a download.
    if (file_exists($path)) {
      $result = new StdClass();
      $result->code = 200;
      $result->data = file_get_contents($path);
    }
    else {

      // Try normal download process.
      $result = drupal_http_request($url);

      // If protected use the HttpClient.
      if ($result->code == 403) {
        $client = migrate_get_http_client();
        $result = $client->download($url);
      }

    }

    if ($result->code != 200) {
      drupal_set_message(t('HTTP error @errorcode occurred when trying to fetch @remote.', array('@errorcode' => $result->code, '@remote' => $url)), 'error');
      return FALSE;
    }

    $local = file_save_data($result->data, $path, $replace);

    if ($local->fid) {
      $files[$path] = $local->fid;
    }

    if (!$local) {
      drupal_set_message(t('@remote could not be saved to @path.', array('@remote' => $url, '@path' => $path)), 'error');
    }

    if (!file_exists($local->uri)) {
      drupal_set_message(t('@path downloaded from @remote was not found in the local system.', array('@remote' => $url, '@path' => $path)), 'error');
    }

    return $local;
  }
      drupal_set_message(t('@remote could not be saved to @path.', array('@remote' => $url, '@path' => $path)), 'error');
    }

    if (!file_exists($local->uri)) {
      drupal_set_message(t('@path downloaded from @remote was not found in the local system.', array('@remote' => $url, '@path' => $path)), 'error');
    }

    return $local;
  }
}

```

# Answer
> 0 votes
try

```
$this->addFieldMapping('field_document_attach:language', 'LANGUAGE_DATA' );

```

'LANGUAGE\_DATA' needs to come from your source.

If this doesn't work I have used the prepare function also to access destination fields I have struggled with; however those where not showing up in the Admin UI whereas yours are. Let me know if you still have issues and I will post up that code .

http://drupalcontrib.org/api/drupal/contributions!migrate!plugins!destinations!entity.inc/function/MigrateDestinationEntity%3A%3Aprepare/7

---
Tags: files, migrations
---


# Question
Title: login programmatically with remember me feature
I'm trying to create a custom login form, since I need it to be ajax based. And I can't use the existing modules that do this. So far I have achieved this by setting the `global $user` object to the loaded user and calling `user_login_finalize()`. But now I need to make the login persist and I have no idea how the default drupal login does it. Any tips are appreciated. Thanks

## UPDATE:

The duplicate question indicated by Pontus Nilsson does not mention in any way how to make the login persist nor how to use the default drupal remember me or the RememberMe module functionality.

## UPDATE 2:

I must elaborate that I have installed Remember Me module to make the persistent login optional for the user. Is that a reason why I needed to go through all this hassle explained in my answer to make the programmatical login persist?

# Answer
> 1 votes
This is how I accomplished the remember me feature. Since I didn't find any specific resources on this matter, the proposed solution may or may not be optimal and correct, although it works fine.

You use the following code to login a user programmatically:

```
$user = user_load($uid);
$login_array = array ('name' => $user_first_query->name);
user_login_finalize($login_array);

```

After that you have to decide whether to persist the login or not using the provided check box in the login form:

```
//at this point we need to persist the login by saving the user again
//with the remember_me data. But doing so, resets the user picture.
//So we need to preserve it somehow.
$user_picture_id = $user->picture;
if($_POST['remember_me']) {
    user_save($user, array('data' => array('remember_me' => (int)$_POST['remember_me'])));
}
else {
    unset($user->data['remember_me']);
    user_save($user, array());
}

//restore the user picture id
db_update('users')
    ->fields(array(
         'picture' => $user_picture_id,
    ))
    ->condition('uid', $uid)
    ->execute();

```

For the part where I have done `unset($user->data['remember_me']);` I have made sure that the rememeber\_me data does not exist from a previous login. I think this should be done in the `modulename_user_presave()` hook but I couldn't implement it there.

Remember that since the main question is how to persist a user login, I have not provided a full login procedure, for example you should authenticate the user's credentials using the `user_authenticate()` function.

---
Tags: 7, users
---


# Question
Title: How to add link to my module in the Structure admin page
I would like to add a link to my module in the Structure admin page.

I already use a hook\_menu for turn in my module accessible but how can I add a link in the "structure" admin section ?

`function tamtamimporter_modules_menu() {
$items['admin/config/tamtamimporter'] = array(
 'title' => 'Gestion du Tamtam importer',
 'description' => 'Gestion de l\'importation des flux par le biais du module Tamtam importer',
 'page callback' => 'tamtamimporter_modules_page',
 'page arguments' => array('tamtamimporter_modules_page'),
 'access arguments' => array('administer site configuration'),
 'file' => 'tamtamimporter_modules.admin_list.inc',
 'type' => MENU_NORMAL_ITEM,
);
}`

Thank you very much for you help.

# Answer
Is it currently appearing under config? I think all you need to do is change the path to being 'admin/structure/mylinkgoeshere' and a link will appear under structure
> 1 votes

# Answer
You would need to specify a url that beggins with `/admin/structure` for that matter (Drupal 7).
> 1 votes

# Answer
Here is the code snippet from simplenews module which shows implementation of hook\_menu using multiple links

```
 /**
 * Implements hook_menu().
 */
function simplenews_menu() {
  $items['admin/content/simplenews'] = array(
    'title' => 'Newsletters',
    'description' => 'List newsletters and newsletter sent status.',
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'drupal_get_form',
    'page arguments' => array('simplenews_admin_newsletter_issues'),
    'access arguments' => array('administer newsletters'),
    'file' => 'includes/simplenews.admin.inc',
  );
  $items['admin/config/services/simplenews'] = array(
    'title' => 'Newsletters',
    'description' => 'Configure your sites newsletters.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('simplenews_admin_categories'),
    'access arguments' => array('administer newsletters'),
    'file' => 'includes/simplenews.admin.inc',
  );

  $items['admin/config/services/simplenews/categories'] = array(
    'title' => 'Newsletters',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );

  .......

  return $items;
}

```

It clearly shows that you can do your work with

```
$items['admin/structure']=....

```
> 0 votes

---
Tags: 7, users, files
---


# Question
Title: Update entity on cart page programmatically Drupal Commerce
I need to rewrite default view - commerce\_cart\_form, because of my design of /cart page. So, I've created file views-view--commerce-cart-form.tpl.php and try to repeat something like on original /cart page were. I can print all needed information about line items in cart, but I don't know how to create "Update" button, to change quantity which I typed in textfield with quantity of line item. That's why I want to get help with this.

I use Drupal Commerce 7.x-1.9

Many thanks in advance!

# Answer
> 0 votes
Assuming that you want to display the full view result and add some extra content to your cart, put the following lines in a file named `views-view--commerce-cart-form.tpl.php` :

```
if($view->current_display == 'default'){//OR your display
  //dsm($view);
  print $rows;
  print '<div>MY CUSTOM CONTENT</div>';
}

```

Check views-view.tpl.php doc to see available variables.

Otherwise, have a look at Commerce Cart View Override :

> This module provides the ability to override the default cart page view for Drupal Commerce.

---
Tags: commerce, updating
---


# Question
Title: Can't get data from drupal_http_request result
I'm requesting a zip file from a remote location, and I'm getting some strange affects here. Here is a snippet:

```
$result = drupal_http_request($serviceUrl, $options);
    $file = $result->data;

    dpm($result, 'file result'); //returns the object, and I can see $result->data is a string of characters
    dpm($result->data, 'data'); //But, this is empty
    dpm($file, 'file'); //This is also empty
    dpm($result, 'file result'); // Still shows me the object with $result->data

```

The http request works fine as it returns with a code 200

I want to use it as follows (example):

```
temp_filename = "my_zip.zip";
$zip_file = fopen($temp_filename, "w+");
fwrite($zip_file, $file); //$file is $result->data, but is empty.
fclose($zip_file);

```

Anybody got an idea why I can't get $result-\>data?

The code is inside an object method, not a standard PHP function. Not sure if that has anything to do with it.

Also worth mentioning that I can read $result-\>code and $result-\>status\_message with no problems.

# Answer
I got it working myself. Kudos to Clive who mentioned that the data is binary which probably means why I can't view it with dpm().

In closure, here is a code example to fetch a zip file with drupal\_http\_request where you can set header information.

```
function MY_MODULE_download_zip($service_url, $token, $request_body) {
    $request_headers = array(
        'Content-Type' => 'text/xml', //sending additional data as XML
        'Content-Length' => strlen($request_body), //See options['data']
        'charset' => 'utf-8',
        'loginToken' => $token, //I needed to pass a login token
        'Cache-Control' => 'no-cache',
        'Pragma' => 'no-cache',
        'Connection' => 'keep-alive'
    );

    $options = array(
        'method' => 'POST',
        'headers' => $request_headers,
        'data' => $request_body, //I needed to pass more info here as a XML
        'timeout' => 60.0, //it's a big file
    );
    $result = drupal_http_request($service_url, $options);

    if ($result->code != 200) {
      watchdog('ERROR', 'ERROR: :error', array(':error' => $result->error);
      return FALSE;
    }

    $temp_filename = "my_zip_file.zip";
    $zip_file = fopen($temp_filename, "w+");
    fwrite($zip_file, $result->data);
    fclose($zip_file);

    return TRUE;
}

```
> 3 votes

---
Tags: files
---


# Question
Title: How do I safely get the internal path to the current site in a multisite setup?
I'm working with a multisite Drupal 7 install with many sites. The site accepts both "www." and without via Apache. I'm developing a themes in /sites/all/themes which is used by many of these sites and I want something like this:

```
$apple_icon =  array(
    '#tag' => 'link',
    '#attributes' => array(
      'href' => '/' . path_to_site() . '/apple-touch-icon.png',
      'rel' => 'apple-touch-icon',
    ),
  );
  drupal_add_html_head($apple_icon, 'apple-touch-icon');

```

where `path_to_site` gives like `/www/drupal7/sites/blah.com` etc. depending on the site being used. I need this since each site will need a different icon.

I guess something like `'/sites/' . $_SERVER['HTTP_HOST']` and then I can use symlink aliases for the "www." variant.

How can I do this properly?

# Answer
You can use `conf_path` to get the path root to the current site - then append the rest of your path to that.

> Returns the configuration path based on the site's hostname, port, and pathname.

e.g:

```
$apple_icon =  array(
  '#tag' => 'link',
  '#attributes' => array(
    'href' => base_path() . conf_path() . '/apple-touch-icon.png',
    'rel' => 'apple-touch-icon',
  ),
);
drupal_add_html_head($apple_icon, 'apple-touch-icon');

```
> 1 votes

---
Tags: theming, multi-sites
---


title: log publish/unpublish actions

text:
# Question
Title: log publish/unpublish actions
For certain node types I want to log/track each time the publish status changes from published to unpublised and from unpublished to published. I am aware I could do this with rules and write log entries into the standard log, but I don't think this is a good solution. I prefer to have a specific logtable for that, so that I can export it and that I can also show the history in a special tab of the node.

I was doing now some research, but could not find anything in this direction.

Is there a module I have not seen and which would be the solution?

If not, what would be the best approach? Thanks

# Answer
> 0 votes
The only module I can think of is Workbench Moderation. It may be much too large and complex for your needs, but within the node's "Moderate" tab, it provides a list of all editing actions including the change of the node's status.

Screenshot

# Answer
> 0 votes
Try the Event Log module. Install the event\_log\_node sub module and then you create a view of type 'Logged Events' and add relationships to the author and node, or visit admin/reports/events

It does not provide a publish/unpublish logging action because there is no such hook, so you should just replace the whole of the function event\_log\_node\_update($node) function in the event\_log\_node.module with this one here which adds that functionality:

```
function event_log_node_update($node) {
  $log = array(
    'type' => 'node',
    'operation' => 'update',
    'description' => t('%type: %title', array(
      '%type' => $node->type,
      '%title' => $node->title
    )),
    'ref_numeric' => $node->nid,
    'info' => $node->original,
  );
  event_log_insert($log);

  if ($node->original->status == 0 && $node->status == 1) {
    //publish event
    $log = array(
      'type' => 'node',
      'operation' => 'publish',
      'description' => t('%type: %title', array(
        '%type' => $node->type,
        '%title' => $node->title
      )),
      'ref_numeric' => $node->nid,
      'info' => $node->original,
    );
    event_log_insert($log);
  }
  elseif ($node->original->status == 1 && $node->status == 0){
    // unpublish event
    $log = array(
      'type' => 'node',
      'operation' => 'unpublish',
      'description' => t('%type: %title', array(
        '%type' => $node->type,
        '%title' => $node->title
      )),
      'ref_numeric' => $node->nid,
      'info' => $node->original,
    );
    event_log_insert($log);
  }
}

```

You also might want to delete the function in that same file

```
function event_log_node_init()

```

as it adds a log entry for every view and that will clutter up the log. If you do clear the cache.

---
Tags: nodes
---


# Question
Title: How to bulk delete Orders in Drupal Commerce module
I need to delete 200 Drupal commerce orders. Is there any way to do this in a bulk action?

Orders are at: **/admin/commerce/orders**

Same with Customer profiles. I need to delete them with a bulk action. Can I accomplish with this?

Customer profiles are at: **/admin/commerce/customer-profiles/list**

# Answer
There is a module for that™

With Commerce VBO views you can create a view where you can mass delete orders and products. I don't know about customer profiles, but that could be a feature request if it's not added yet.
> 4 votes

# Answer
If you've got 65,000 orders that you need to wipe, VBO isn't an option. You can try this:

```
TRUNCATE commerce_customer_profile;
TRUNCATE commerce_customer_profile_revision;
TRUNCATE commerce_funds_transactions;
TRUNCATE commerce_funds_user_funds;
TRUNCATE commerce_line_item;
TRUNCATE commerce_order;
TRUNCATE commerce_order_revision;
TRUNCATE commerce_payment_transaction;
TRUNCATE commerce_payment_transaction_revision;
TRUNCATE commerce_paypal_ipn;

TRUNCATE field_data_commerce_customer_address;
TRUNCATE field_data_commerce_customer_billing;
TRUNCATE field_data_commerce_customer_shipping;
TRUNCATE field_data_commerce_line_items;
TRUNCATE field_data_commerce_order_total;
TRUNCATE field_data_commerce_price;
TRUNCATE field_data_commerce_product;
TRUNCATE field_data_commerce_shipping_service;
TRUNCATE field_data_commerce_total;
TRUNCATE field_data_commerce_unit_price;

TRUNCATE field_data_commerce_coupon_order_reference;
TRUNCATE field_data_commerce_display_path;
TRUNCATE field_data_field_order_deliveryinstructions;
TRUNCATE field_data_field_order_flags;
TRUNCATE field_data_field_order_id;
TRUNCATE field_data_field_order_notes;
TRUNCATE field_data_field_supplier;

TRUNCATE field_revision_commerce_customer_address;
TRUNCATE field_revision_commerce_customer_billing;
TRUNCATE field_revision_commerce_customer_shipping;
TRUNCATE field_revision_commerce_line_items;
TRUNCATE field_revision_commerce_order_total;
TRUNCATE field_revision_commerce_price;
TRUNCATE field_revision_commerce_product;
TRUNCATE field_revision_commerce_shipping_service;
TRUNCATE field_revision_commerce_total;
TRUNCATE field_revision_commerce_unit_price;

TRUNCATE field_revision_commerce_coupon_order_reference;
TRUNCATE field_revision_commerce_display_path;
TRUNCATE field_revision_field_order_deliveryinstructions;
TRUNCATE field_revision_field_order_flags;
TRUNCATE field_revision_field_order_id;
TRUNCATE field_revision_field_order_notes;
TRUNCATE field_revision_field_supplier;

```
> 6 votes

# Answer
Commerce Order Cleanup is another attempt on this front:

> Allows to cleanup the orders by various order properties like last changed, status.
> 2 votes

---
Tags: commerce
---


title: Images not shown in View Mode Teaser

text:
# Question
Title: Images not shown in View Mode Teaser
I have a content type teaser with an image field and display these teaser in a panel layout. This works perfect if I choose the Build Mode "Full Content" in the Panel Settings for the content.

I themed the content type with a node template (node--xyz.tpl.php) and have no checks about the view\_mode in it. I print out the image with the function `render()`:

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

```

I'm very confused, as I wrote above, with the Build Mode "Full Content" it works fine. I've checked the Manage Displays Settings and they are the same for both View Modes. The Variable in the render() function is filled in both cases, but in View Mode "Teaser", the output is empty.

# Answer
> 0 votes
Check http://YOUR\_SITE.NAME/admin/structure/types/manage/YOUR\_CONTENT\_TYPE/display/teaser

You have to add field\_teaser\_image to visible fields list.

Field UI module must be active.

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


title: How to create Block configuration form

text:
# Question
Title: How to create Block configuration form
I am new to drupal. I have created a block from module using `hook_block_info()` and `hook_block_view()`. This block will be used as front page image slideshow. So I want to provide text fields in the configuration page of that block where user can add Image files for slideshow.

What is the process of creating configuration form for the block. I searched online but couldn't understandable solution. Thanks!

I am using Drupal 7

# Answer
> 0 votes
You need to create a custom module for this. The module will create a database table that will store the image file path. The module will also provide an admin interface (drupal form) with a file field. When the admin uploads image and submits form, you need to store the file path in the database table you created. Now in `hook_block_view()` you need to iterate through every file path and render it as slideshow.

There is an alternate solution to your problem which will be more usable.

> Create a content type with an image field. Now create nodes of that content type and upload images. Use views\_slideshow module to display the nodes of the content type. Since it is a view, therefore you will be able to display it as a block and place it anywhere.

Hope the above solution will be more useful.

# Answer
> 3 votes
You can create block configuration page using hook\_block\_configure(). where you can create form with your required field like textfield, file etc.

```
function demo_block_configure($delta = '') {
    $form = array();
    if ($delta == 'demo') {
        $form['demo_number'] = array(
            '#type' => 'textfield',
            '#title' => t('Number of nodes you want the block to show'),
            '#default_value' => variable_get('demo_number', 10),
            '#size' => 60,
        );
    }
    return $form;
}

function demo_block_save($delta = '', $edit = array()) {
    if ($delta == 'demo') {
        variable_set('demo_number', $edit['demo_number']);
    }
}

```

now you can get this variable using variable\_get function

```
$no_of_block = variable_get('demo_number');

```

you can see this page in configuration of your block

# Answer
> 0 votes
You could take a look at the Examples module this provides code examples of various different api implementations, including block forms. The code your looking for is in the block module. All the examples are working so you can play around with them on a test Drupal 7 site if you want.

---
Tags: 7, blocks
---


# Question
Title: Redirecting %20 Based URL to Non %20 based URL
I have a URL suppose http:www.domain.com/somepath%20%20

When i open the above URL, it exist with both URLs http:www.domain.com/somepath and http:www.domain.com/somepath%20%20

I would like to know how can I redirect %20 based URL to Non %20 based URL

P.S I have made this page using Panels.

# Answer
> 1 votes
I would check the alias on the page to see if two trailing spaces exist. That's where the %20 typically comes from. %20 is an HTML encoded space character.

In the meantime, you can handle multiple links to one page using Global Redirect.

Best to get that in so your site is not penalized by search engines.

---
Tags: uri, redirection
---


title: Rendering a form to a block

text:
# Question
Title: Rendering a form to a block
I have created a block named 'xyz'. I also created a form whose id is 'form-type-node-form' and i want this form to display in that block. How can i do this? please help me to get solution.

# Answer
You can achieve that in couple of ways. You can create custom module or simply by using on the modules mentioned below.

Advanced Form Block

> With this module you can do the following:
>
> 1) Create any number of blocks with a particular node edit form.
>
> 2) create any number of blocks with a particular node add form of a content type.
>
> 3) Create as many blocks as you like of each kind.
>
> 4) From the content type choose which fields to display on a per block basis.However required fields will be automatically displayed.
>
> 5) All forms will be saved through ajax. So multiple node forms can be independently placed on a single page and worked with simultaneously.

OR

Form Block

> Enables the presentation of user registration, site wide contact, or node creation forms in blocks. This is particularly useful for including forms on panels.

OR

You can also achieve that by creating custom module. Follow this link
> 0 votes

# Answer
You can use drupal\_get\_form function to get form, example:

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

  $block = array();

  switch ($delta) {
    case 'xyz':
      $block['subject'] = t('XYZ');
      $block['content'] = drupal_get_form('FORM_ID');
      break;
  }
  return $block;
}

```
> 0 votes

---
Tags: forms
---


title: Confusing Widget of inline entity form

text:
# Question
Title: Confusing Widget of inline entity form
Inline Entity Form ships with two widgets as `Inline entity form - Single value` and `Inline entity form - Multiple values` when I use `Inline entity form - Single value`, I only get add entity form and when I use `Inline entity form - Multiple values` I get option to add/edit both.

what I was expecting to see to have both add/edit with `Inline entity form - single values` with only difference of not allowing to have multivalued field in this case.

Am I missing something?

# Answer
> 0 votes
If you modify your inline entity form by writing a small module, (for this look at README and the ..api.php) you can set your default values by loading them from the entity. So your former entries are available.

---
Tags: entities
---


title: Entity Malformation Exception Error

text:
# Question
Title: Entity Malformation Exception Error
When I try to access some specific pages, I get the following errors in my log, one after the other:

> Notice: Trying to get property of non-object in ds\_field\_formatter\_view() (line 1233 of /var/www/sites/all/modules/ds/ds.module).

Followed by

> EntityMalformedException: Missing bundle property on entity of type taxonomy\_term. in entity\_extract\_ids() (line 7729 of /var/www/includes/common.inc).

And the page serves the following error:

> Error The website encountered an unexpected error. Please try again later.

I had the modules taxonomy and taxonomy manager enabled. I disabled taxonomy manager, but no effect. I wanted to disable taxonomy too, but could not because there was a field with data in it. This has made almost 44 pages of the site with good content in accessible, so any help will be greatly appreciated.

# Answer
The error was happening due to the fact that database records where not removed when a taxonomy term reference field was deleted. The solution was to install taxonomy orphanage module which removes such references.
> 2 votes

---
Tags: 7, taxonomy-terms, display-suite
---


# Question
Title: Easy way to create author account on node creation?
Is there an easy way to add a field that will automatically create an account for the author with the specified email address if that address doesn't exist? I have to enter information for new and old users on occasion and it would help if I could just type the e-mail address each time, instead of creating an account manually first.

# Answer
You can do this easily using Rules Module. Just trigger a rule that whenever you create a node of the particular type, the Rule checks the entered email-id in the field and creates a new account using that email-id if it doesn't already exist.
> 1 votes

---
Tags: nodes
---


# Question
Title: How to have View output is same as node output
I have a content type called poem and a View page that has path like poem/% too. There is a View page for listing the poems called /poems. The poems page will list all the poem titles linked the actual poem (eg: "a href="poem/1"\>What a world ).

I have a block in the poem view to show all the poems written by the poet. My problem here is when I go to the node by /node/1, I can see the block that list all the poems written by the poet who wrote the node/1 but when I go like /poem/1 I am not seeing the block that list the poems. The node/1 view has bold header of the title but that's missing in my /poem/1 too.

Please help me how to make poem/1 to have the same view as the /node/1.

/poems -\> this will list all the poem titles in site, title link would be /poem/1 instead of node/1

/poem/1 -\> display poem content + it should display all the titles of the poem written by the author (/poem/1)

poem list view

poem view

node view of the same poem

poem view setup

# Answer
> 0 votes
> but when I go like /poem/1 I am not seeing the block that list the poems. The node/1 view has bold header of the title but that's missing in my /poem/1 too.

In the Blocks Admin UI at `admin/structure/blocks` be sure the Block for your `block view` for a *poem listing* is enabled for the `url path = poem/*`.

You can also assign blocks to regions easily with the Context module.

---
Tags: views
---


title: Beginner - How to make CSS changes?

text:
# Question
Title: Beginner - How to make CSS changes?
I have very little Drupal experience and recently inherited a Drupal 6 site. I want to make some CSS changes, but from what I can tell all the CSS is in /home/saybrook/drupal/sites/default/files/css, where there are a bunch of CSS files that seemed to be cached. If I make changes to those files, they'll probably be lost eventually.

Can someone point me in the right direction?

# Answer
1. Find out what theme you're using (visit /admin/build/themes)
2. Find the files in your Drupal installation for that theme (if it's a core theme it'll be under /themes, if contrib it'll likely be in /sites/all/themes)
3. Change what you need to.

If it's a core theme, don't edit it (you'll lose the changes when you next update Drupal core) - create a subtheme instead.

The files in /sites/default/files/css are the optimised files produced when CSS aggregation is turned on; for development you'll want to disable that (/admin/settings/performance), or you'll need to clear the css cache every time you make a change.
> 3 votes

# Answer
If the site is still in development I would recommend you turn off performance caching at /sites/all/themes completely until your CSS changes are made.

You will then want to locate the .css files of the custom theme you uploaded, which would either be in the /themes folder or the /sites/all/themes folder.
> 0 votes

---
Tags: theming
---


# Question
Title: Is there a module that allows users to post content in steps?
sometimes posting a blog post can seem daunting to some of my users. They see a large page with so many entry points that I think I'm missing out on some good content. So what I would like to do is give users the ability to add entries in steps. without seeing the entire form.

1. Title
2. body
3. tags
4. video

# Answer
> 0 votes
Try Multistep Nodeform

> Multistep Nodeform" is a module to split the node creation and node editing form into several steps. This may be usefull for you if you have lots of fields in your content type and would like to provide a wizard-like UI for content creation/editing.

---
Tags: nodes
---


# Question
Title: Taxonomy term view with number of items for parent and child terms
For my shop, I need a taxonomy tree view with 2 levels, the number of items should be shown in brackets for every parent and child term. My problem: it works for the child terms, but not for their parents.

*This should my view look like:*

parent-term-1 (15)
\- term-1.1 (7)
\- term-1.2 (8)

parent-term-2 (15)
\- term-2.1 (6)
\- term-2.2 (9)

*But it looks like this:*

parent-term-1 (0)
\- term-1.1 (7)
\- term-1.2 (8)

parent-term-2 (0)
\- term-2.1 (6)
\- term-2.2 (9)

***My view***
Vocabulary Name = Category

**Relationships**
Taxonomy Term: Parent term (Identifier = Parent)
Taxonomy Term: Content with term (Identifier = node)

Use aggregation: Yes

**Fields**
Taxonomy Term: Term ID (Exclude from display)
(Parent) Taxonomy Term: Term ID (Exclude from display)
Taxonomy Term: Name
(node) COUNT (Content: Nid)

**Filter criteria**
Taxonomy vocabulary: Machine Name=(Category)

**Format**
Format: Tree (Main field: 1st Term ID, Parent Field: 2nd Term ID)
Field Settings: 3rd + 4th field inline

Any ideas?

# Answer
I now have worked out a solution. You need to implement the taxonomy edge module. With that you can define a new relationship: Taxonomy term: child term. After that it's possible not only to count the number of nodes tagged with one term, but also the number of nodes tagged with the child terms of this term.

My nodes are always tagged with terms from the deepest level. So I have to consider the number of nodes tagged with the considered term OR the number of nodes tagged with the childs terms of the considered term (if available).

Completing my initial post, I **add two relationships**:

```
Taxonomy term: Child terms (Identifier = Childs)
(Childs)Taxonomy Term: Content with term (Identifier = node_childs)

```

I further **add one field**:

```
(node_childs) COUNT (Content: Nid)

```

In the field settings, i set these **fields inline**:

* Taxonomy Term: Name
* (node) COUNT (Content: Nid)
* (node\_childs) COUNT (Content: Nid)

The field `(node) COUNT (Content: Nid)` is excluded from display.
In the field `(node_childs) COUNT (Content: Nid)` I set the No-results-behavior to the token `[nid]`.

The effect is that either the considered term has child-terms, then the number of nodes tagged with the child terms is counted. Or the considered term has no childs, than the number of nodes tagged with the considered term is counted.
> 1 votes

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


# Question
Title: Why can't I modify my comment form using hook_form_alter
I have enabled comments for a custom node type.

I am trying to theme that comment form using `hook_form_alter(&$form, &$form_state)` (For example, I'd like to remove the label of the `comment_body` form field)

To do that, I use the following function:

```
function MYTHEME_form_comment_form_alter(&$form, &$form_state) {
    $form['comment_body']['und']['#title'][0] = '';
}

```

However in the output the title of the form field is still there:

Here's the markup:

The value of `$form` does not correspond to what I am used to see. Here's a screenshot from my debugger:

# Answer
> 0 votes
It looks like the label "Comment\*" is not from comment\_body container wrapper, then again comment\_body shouldnt be of type container.

Most likely the actual comment field is somewhere not visible of your debug screenshot. This is because drupal core comment module form doesnt use normal form api structure where containers only reference children and reverse. Instead the actual field is placed directly to container. Luckily drupal\_render has no problem with neither structure.

Removing the label should not require specifying language on the actual field. It should be as easy as

`$form['comment_body']['#title']='';`

Instead with funky comment form render array you need to specify language of the containers sub items, hence the path transforms to

`$form['comment_body'][LANGUAGE_NONE][0]['#title']=''`

# Answer
> 0 votes
I Was attempting to add a placeholder for the comment\_body field and after struggling through this a bit, was able to figure out that the changes will take in affect if you utilize the "value" array key like so:

```
$form['comment_body'][LANGUAGE_NONE][0]['value']['#title']='foo bar';

```

---
Tags: theming, forms, comments
---


title: Create node via REST from Android app

text:
# Question
Title: Create node via REST from Android app
I use restful between Drupal 7 and Android app. I logged in successful and got 3 variable session\_id, session\_name and token When I use POST method to create node. I getting error : "node type is required" This is my code :

```
private class addArticleTask extends AsyncTask<String, Integer, Integer> {

    protected Integer doInBackground(String... params) {

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://mysite/endpoint/node");

        try {

            //get title and body UI elements
            TextView txtTitle = (TextView) findViewById(R.id.editTitle);
            TextView txtBody = (TextView) findViewById(R.id.editBody);

            //extract text from UI elements and remove extra spaces
            JSONObject json = new JSONObject();
            String title=txtTitle.getText().toString().trim();
            String body=txtBody.getText().toString().trim();

            //add raw json to be sent along with the HTTP POST request
            StringEntity se = new StringEntity("{ \"title\" : \"Sample post\" , \"type\" : \"article\" , \"body\" : { \"und\" :[{ \"value\" : \"comments about something\" }]} }");
            se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            se.setContentType(new BasicHeader("Cookie",session_name+"="+session_id));
            se.setContentType(new BasicHeader("X-CSRF-Token",token));
            httppost.setEntity(se);

            HttpResponse response = httpclient.execute(httppost);
            Log.v("Return add article", EntityUtils.toString(response.getEntity()));

            return 0;

        }catch (Exception e) {
            Log.v("Error adding article",e.getMessage());
        }

        return 0;
    }

```

In Logcat : Return add article : \["node type is required"\] any one help me.

# Answer
> 1 votes
You must mention the node type while doing the POST.

**node\_type will the machine name of your content type**

for example try creating page with this,

```
StringEntity se = new StringEntity("{ \"title\" : \"Sample post\" , \"page\" :

```

---
Tags: 8
---


# Question
Title: Show a block only on the frontpage of the sub-domains
I am using Drupal 7 for a site and I installed the *Domain access* module for maintaining the sub-domains. The slideshow block (created using the Views module) should be displayed on the sub-domains front page, but not on the main domain.

I tried the *Domain block* module, but it would require to manually set the block for each domain.

How can I make the block appear only on the front page of the sub-domains?

# Answer
> 1 votes
I recommend you to use context module for block displays with the domaincontext module extension.

> **Domain Context** module is an integration module for the Domain Access module and the Context module.
>
> The Domain Access module allows administrators to set specific settings for each of their domains that are using the same code base. The Context module allows you to assign blocks to regions (and more) given certain conditions that can be set in the Context admin. Currently when both modules are installed you have no interface that will allow you to trigger a context on a specific domain. This module adds a domain condition to the context administration so that you can trigger a context on a specific domain.

# Answer
> 1 votes
I added a view filter based on the domain ID (unique key ID).

These key IDs are nothing but the domain IDs you get while creating new domains. By default,the main domain ID is 1.
In the view, I added the *Domain: Key ID* filter and made a filter for *Domain Key ID ~ 1*.

It worked.

---
Tags: 7, domain-access, blocks
---