title: List all blogs from users in same group

text:
# Question
Title: List all blogs from users in same group
I'm new to Drupal, and I'm using Organic Groups to make groups. The site is supposed to be a multi-blog platform where groups can have their own group and the group admin(only) should be able to get a list of all group members (linked to their blogs) in the side menu. How am I able to achieve this? Any help would be appreciated!

I found the following code from here:

```
<?php
    $query = db_select('node', 'n');
    $query->join('users', 'u', 'n.uid = u.uid');
    $query->join('file_managed', 'f', 'f.fid = u.picture');
    $query->fields('u',array('name'));
    $query->fields('n',array('type'));
    $query->fields('f',array('filename'));
    $query->fields('u',array('uid'));
    $query->condition('u.status', 1);
    $query->condition('n.status', 1);
    $query->condition('n.type', 'blog', '=');
    $query->addExpression('COUNT(n.uid)');
    $query->groupBy('u.uid');
    $query->groupBy('n.type');
    $query->orderBy('COUNT(n.uid)', 'DESC');
    $result = $query->execute();
    $output = array();
    while($record = $result->fetchAssoc()) {
    // print $record ;
     $output = '<div class="bloglist_row">';
     $output .= '<div class="bloglist_userimage"><img style="width:100%;" src="./sites/default/files/styles/thumbnail/public/pictures/'.$record['filename'].'"></div>';
     $output .= '<div class="bloglist_row_body"><a href="blog/'.$record['uid']. '">'.$record['name']. 's Blog</a><br />Posts: ('.$record['expression'].')</div>';
     $output .= '</div>';
     $output .= '<img src="blog_spacer.jpg" width="220" height="25" />';
   //  $output .= '<li />'.l($record['name']. ' ('.$record['expression'].')', 'blog/'.$record['uid']);
    }
    echo $output;
?>

```

Unfortunately this gives me the following error: `Notice: Array to string conversion in include()` on the last line (`echo $output`).

Any ideas on how I can achieve this with using Views?

# Answer
Try setting $output = array(); to $output = ''; and see if that fixes the issue. Also, I would recommend using views instead of custom SQL query while dealing with Drupal.
> 0 votes

---
Tags: organic-groups
---


# Question
Title: How to add button to user profile page in drupal
I start using drupal(7) 3 days ago and I have small task :

I'm using Profile2 Module to create 2 type of users (candite/employer) and I Want to create a button in the wiew page of the profile of employer.

I create new module for that to test if is an employer profil :

```
function ab_candidate_app_profile2_view_alter($build) {

  $test = $build['field_company_name']['#object'];
  if(isset($build))
    if($test->type == 'employer_'){

    // add the button here
    }

}

```

Thank you for your help

EDIT : and whene i do var\_dump($build) i get next result :

```
 array (size=12)
  '#view_mode' => string 'account' (length=7)
  'field_company_name' =>
    array (size=16)
      '#theme' => string 'field' (length=5)
      '#weight' => int 0
      '#title' => string 'Name' (length=4)
      '#access' => boolean true
      '#label_display' => string 'above' (length=5)
      '#view_mode' => string 'account' (length=7)
      '#language' => string 'und' (length=3)
      '#field_name' => string 'field_company_name' (length=18)
      '#field_type' => string 'text' (length=4)
      '#field_translatable' => string '0' (length=1)
      '#entity_type' => string 'profile2' (length=8)
      '#bundle' => string 'employer_' (length=9)
      '#object' =>
        object(Profile)[56]
          public 'pid' => string '6' (length=1)
          public 'type' => string 'employer_' (length=9)
          public 'label' => string 'Employer ' (length=9)
          public 'uid' => string '10' (length=2)
          public 'created' => string '1411278976' (length=10)
          public 'changed' => string '1411278976' (length=10)
          protected 'entityType' => string 'profile2' (length=8)
          protected 'entityInfo' =>
            array (size=22)
              ...
          protected 'idKey' => string 'pid' (length=3)
          protected 'nameKey' => string 'pid' (length=3)
          protected 'statusKey' => string 'status' (length=6)
          protected 'defaultLabel' => boolean false
          public 'field_company_name' =>
            array (size=1)
              ...
          public 'field_logo' =>
            array (size=1)
              ...
          public 'field_company_description' =>
            array (size=1)
              ...
          public 'field_country' =>
            array (size=1)
              ...
          public 'rdf_mapping' =>
            array (size=0)
              ...
          public 'entity_view_prepared' => boolean true
      '#items' =>
        array (size=1)
          0 =>
            array (size=3)
              ...
      '#formatter' => string 'text_default' (length=12)
      0 =>
        array (size=1)
          '#markup' => string 'adel' (length=4)
  'field_logo' =>
    array (size=16)
      '#theme' => string 'field' (length=5)
      '#weight' => int 2
      '#title' => string 'Logo' (length=4)
      '#access' => boolean true
      '#label_display' => string 'above' (length=5)
      '#view_mode' => string 'account' (length=7)
      '#language' => string 'und' (length=3)
      '#field_name' => string 'field_logo' (length=10)
      '#field_type' => string 'image' (length=5)
      '#field_translatable' => string '0' (length=1)
      '#entity_type' => string 'profile2' (length=8)
      '#bundle' => string 'employer_' (length=9)
      '#object' =>
        object(Profile)[56]
          public 'pid' => string '6' (length=1)
          public 'type' => string 'employer_' (length=9)
          public 'label' => string 'Employer ' (length=9)
          public 'uid' => string '10' (length=2)
          public 'created' => string '1411278976' (length=10)
          public 'changed' => string '1411278976' (length=10)
          protected 'entityType' => string 'profile2' (length=8)
          protected 'entityInfo' =>
            array (size=22)
              ...
          protected 'idKey' => string 'pid' (length=3)
          protected 'nameKey' => string 'pid' (length=3)
          protected 'statusKey' => string 'status' (length=6)
          protected 'defaultLabel' => boolean false
          public 'field_company_name' =>
            array (size=1)
              ...
          public 'field_logo' =>
            array (size=1)
              ...
          public 'field_company_description' =>
            array (size=1)
              ...
          public 'field_country' =>
            array (size=1)
              ...
          public 'rdf_mapping' =>
            array (size=0)
              ...
          public 'entity_view_prepared' => boolean true
      '#items' =>
        array (size=1)
          0 =>
            array (size=13)
              ...
      '#formatter' => string 'image' (length=5)
      0 =>
        array (size=4)
          '#theme' => string 'image_formatter' (length=15)
          '#item' =>
            array (size=13)
              ...
          '#image_style' => string '' (length=0)
          '#path' => string '' (length=0)
  'field_company_description' =>
    array (size=16)
      '#theme' => string 'field' (length=5)
      '#weight' => int 3
      '#title' => string 'Description' (length=11)
      '#access' => boolean true
      '#label_display' => string 'above' (length=5)
      '#view_mode' => string 'account' (length=7)
      '#language' => string 'und' (length=3)
      '#field_name' => string 'field_company_description' (length=25)
      '#field_type' => string 'text_long' (length=9)
      '#field_translatable' => string '0' (length=1)
      '#entity_type' => string 'profile2' (length=8)
      '#bundle' => string 'employer_' (length=9)
      '#object' =>
        object(Profile)[56]
          public 'pid' => string '6' (length=1)
          public 'type' => string 'employer_' (length=9)
          public 'label' => string 'Employer ' (length=9)
          public 'uid' => string '10' (length=2)
          public 'created' => string '1411278976' (length=10)
          public 'changed' => string '1411278976' (length=10)
          protected 'entityType' => string 'profile2' (length=8)
          protected 'entityInfo' =>
            array (size=22)
              ...
          protected 'idKey' => string 'pid' (length=3)
          protected 'nameKey' => string 'pid' (length=3)
          protected 'statusKey' => string 'status' (length=6)
          protected 'defaultLabel' => boolean false
          public 'field_company_name' =>
            array (size=1)
              ...
          public 'field_logo' =>
            array (size=1)
              ...
          public 'field_company_description' =>
            array (size=1)
              ...
          public 'field_country' =>
            array (size=1)
              ...
          public 'rdf_mapping' =>
            array (size=0)
              ...
          public 'entity_view_prepared' => boolean true
      '#items' =>
        array (size=1)
          0 =>
            array (size=3)
              ...
      '#formatter' => string 'text_default' (length=12)
      0 =>
        array (size=1)
          '#markup' => string 'teeeeeeeeeeeeeeeeeeeest' (length=23)
  'field_country' =>
    array (size=16)
      '#theme' => string 'field' (length=5)
      '#weight' => int 4
      '#title' => string 'Country' (length=7)
      '#access' => boolean true
      '#label_display' => string 'above' (length=5)
      '#view_mode' => string 'account' (length=7)
      '#language' => string 'und' (length=3)
      '#field_name' => string 'field_country' (length=13)
      '#field_type' => string 'list_text' (length=9)
      '#field_translatable' => string '0' (length=1)
      '#entity_type' => string 'profile2' (length=8)
      '#bundle' => string 'employer_' (length=9)
      '#object' =>
        object(Profile)[56]
          public 'pid' => string '6' (length=1)
          public 'type' => string 'employer_' (length=9)
          public 'label' => string 'Employer ' (length=9)
          public 'uid' => string '10' (length=2)
          public 'created' => string '1411278976' (length=10)
          public 'changed' => string '1411278976' (length=10)
          protected 'entityType' => string 'profile2' (length=8)
          protected 'entityInfo' =>
            array (size=22)
              ...
          protected 'idKey' => string 'pid' (length=3)
          protected 'nameKey' => string 'pid' (length=3)
          protected 'statusKey' => string 'status' (length=6)
          protected 'defaultLabel' => boolean false
          public 'field_company_name' =>
            array (size=1)
              ...
          public 'field_logo' =>
            array (size=1)
              ...
          public 'field_company_description' =>
            array (size=1)
              ...
          public 'field_country' =>
            array (size=1)
              ...
          public 'rdf_mapping' =>
            array (size=0)
              ...
          public 'entity_view_prepared' => boolean true
      '#items' =>
        array (size=1)
          0 =>
            array (size=1)
              ...
      '#formatter' => string 'list_default' (length=12)
      0 =>
        array (size=1)
          '#markup' => string 'Malaysia (MY)' (length=13)
  '#pre_render' =>
    array (size=1)
      0 => string '_field_extra_fields_pre_render' (length=30)
  '#entity_type' => string 'profile2' (length=8)
  '#bundle' => string 'employer_' (length=9)
  '#theme' => string 'entity' (length=6)
  '#entity' =>
    object(Profile)[56]
      public 'pid' => string '6' (length=1)
      public 'type' => string 'employer_' (length=9)
      public 'label' => string 'Employer ' (length=9)
      public 'uid' => string '10' (length=2)
      public 'created' => string '1411278976' (length=10)
      public 'changed' => string '1411278976' (length=10)
      protected 'entityType' => string 'profile2' (length=8)
      protected 'entityInfo' =>
        array (size=22)
          'label' => string 'Profile' (length=7)
          'plural label' => string 'Profiles' (length=8)
          'description' => string 'Profile2 user profiles.' (length=23)
          'entity class' => string 'Profile' (length=7)
          'controller class' => string 'EntityAPIController' (length=19)
          'base table' => string 'profile' (length=7)
          'fieldable' => boolean true
          'view modes' =>
            array (size=1)
              ...
          'entity keys' =>
            array (size=4)
              ...
          'bundles' =>
            array (size=2)
              ...
          'bundle keys' =>
            array (size=1)
              ...
          'label callback' => string 'entity_class_label' (length=18)
          'uri callback' => string 'entity_class_uri' (length=16)
          'access callback' => string 'profile2_access' (length=15)
          'module' => string 'profile2' (length=8)
          'metadata controller class' => string 'Profile2MetadataController' (length=26)
          'static cache' => boolean true
          'field cache' => boolean true
          'load hook' => string 'profile2_load' (length=13)
          'translation' =>
            array (size=0)
              ...
          'schema_fields_sql' =>
            array (size=1)
              ...
          'configuration' => boolean false
      protected 'idKey' => string 'pid' (length=3)
      protected 'nameKey' => string 'pid' (length=3)
      protected 'statusKey' => string 'status' (length=6)
      protected 'defaultLabel' => boolean false
      public 'field_company_name' =>
        array (size=1)
          'und' =>
            array (size=1)
              ...
      public 'field_logo' =>
        array (size=1)
          'und' =>
            array (size=1)
              ...
      public 'field_company_description' =>
        array (size=1)
          'und' =>
            array (size=1)
              ...
      public 'field_country' =>
        array (size=1)
          'und' =>
            array (size=1)
              ...
      public 'rdf_mapping' =>
        array (size=0)
          empty
      public 'entity_view_prepared' => boolean true
  '#language' => string 'en' (length=2)
  '#page' => null

```

# Answer
> 0 votes
I solve by overrieding the user-profile.tpl.php with this code :

```
<?php print render($user_profile);

  if(isset($user_profile['profile_employer_'])){
  $account_info=menu_get_object('user');
  $acount_id = $account_info->uid;

 // var_dump($account_info);die();

  echo '<a href="/jobPortal/Apply/'.$acount_id.'">Apply Now</a>';
  }
  ?>

```

I overied this file in the next path :

C:\wamp\www\jobPortal\themes\bartik\templates\

# Answer
> 0 votes
Your `$build` is an array, so it should be enough to add "fake" field to it:

```
$build['field_mymodule_button'] = array(
  '#theme' => 'link',
  '#text' => 'Click Here',
  '#path' => $path,
  '#weight' => 10,
  '#options' => array(
    'attributes' => array('class' => array('pretend-im-button-class'), 'id' => 'cool-id'),
      //REQUIRED?:
      'html' => FALSE,
   ),
);

```

Code sample from here. Note that `'html' => FALSE` is reported as needed by some, and as not needed by others. Just see if you need it.

To control order of your rendered elements, use `'#weight'`. It's an int, so you may need to alter other elements to make a place for yours.

---
Tags: hooks, views, users
---


title: Group Filter for taxonomy term in view

text:
# Question
Title: Group Filter for taxonomy term in view
Right now I have it so that I grouped a list of taxonomy terms with Group Filters like this:

House Pet:

* Dog
* Cat

Sea Creatures:

* Whale
* Shark

All:

* Dog
* Cat
* Whale
* Shark

My current problem is that when using group filters I keep getting No Results, however if I use a single filter and choose one of the options I get results.

I have seen a lot of videos of people using groups with taxonomy, but I have not been able to replicate what each of them have done. I have tried using the Filter Criteria with the field as well as the content taxonomy has terms with depth option as well. The content is tagged and has departments (you can see it from the the field I am showing with the view) so I know that the tags exist, but they always return with no results.

Ideas, options, patches, questions, help? I have run out of ideas.

# Answer
If I remember correctly, try this.

1. Create a relationship to the taxonomy parent term.
2. Add a taxonomy term name field, add relationship to Parent.
3. Add another taxonomy term field.
4. Group by Parent term.

Hopefully that works out. You can also look into Views Tree, I've used it before and works pretty well for specific use cases.
> 1 votes

# Answer
It was actually a bug in the Drupal View module. I posted a bug in the Views Module and a co-worker of mine submitted a patch for it.
> 0 votes

# Answer
No it is not bug, you can achieve it with below simple method

**Explain it with sample :**

I wanted to display a block using views where the taxonomy parent and child needed to displayed in separate fields.

Eg Books Parent term: Adult and Child Term: Fiction

So block view should be such that

Book Title – Parent Term – Child Term ie Eclipse – Adult – Fiction

To achieve this Go to Views

Add “Relationships” Select “Taxonomy: Parent Term” (use the default settings) Add Fields Select “Taxonomy: Term” Relationship: Parent Add Fields Again Select “Taxonomy Terms” Relationship: Do not use a relationship

Now we have reached our goal … simple but takes some digging …

enjoy ;)
> 0 votes

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


# Question
Title: Send Email using rules or other module depending on a field value?
What I'm trying to do is when a user creates a node on content type "Sample" with the field "Priority" set to "High" that said user will receive an email notification containing the field values of the node and a link.

I tried using rules but I can't seem to find a condition that supports a field containing value. I'm thinking into creating a hook function when the user creates a node. But the problem is I'm very new to drupal and I still don't know where to start. Can anyone enlighten me on what to do?

# Answer
> 1 votes
You would need to expose the node's field using the condition "entity has field" as the very first condition. Then Rules will allow you to select the field in the condition "data comparison".

---
Tags: 7, hooks, rules
---


title: Split blog posts over multiple pages

text:
# Question
Title: Split blog posts over multiple pages
Apologies in advance for the long message but I am very new to Drupal and really have no idea what I'm doing sowill try to explain. My company has there website built in Drupal 7, we have a module installed which allows us to create single page blogs. What we'd like to be able to do is also create blog posts that can be split over multiple pages (if we choose).

As an example, if the user clicked on a particular blog post from our blog page they would be taken to the first page (as they currently do), then, at some point on the page we would like to have a next button which takes them to the second part of the blog post. Then on page 2 they would have the 'previous'/'next' buttons and so on.

I have tried installing a module called Smart Paging which looked like it would do the job, however I cannot for the life of me get it to work. Here is a breakdown of what I have done:

* I've installed the module
* Enabled it
* Selected the 'Default page break method' as 'manual'
* Amended the 'text formats' so 'Convert line breaks into HTML (i.e. \< br \> and \< p \>) for Smart Paging compatibility' is ticked
* Unticked 'Convert line breaks into HTML (i.e. \< br \> and \< p \>)'
* Added '' to the 'Limit allowed HTML tags' list
* Move 'Smart Paging' up underneath 'Body' on Administration » Structure » Content types » Blog entry
* Changed the format setting to 'Show Smart Paging settings during content editing of this content type'
* Added '\< !--pagebreak-- \>' to a blog post

I have done all of the above but the blog post still just shows the text that I have written all on one page with no 'next'/'previous' buttons. I'm hoping I've just missed something simple which someone could kindly point out to me.

Thanks in advance.

# Answer
The core 'book' module will do what you're after.

First, configure the module so that the content type you are using for blog posts is allowed to be in books at `admin/content/book/settings`.

Second, understand that a book is a bit like a menu, each page is a single node and the book simply provides the links between those nodes in order. When you create or edit the node intended as the first page of your book go to the 'book outline' settings at the bottom of the node creation form and select `create new book`.

To add pages, create or edit the nodes that are to be the next page(s) and select the book you just created.

Finally there is a block that the module creates called 'book navigation', move that block to where you wish the 'next' and 'previous' links to go.

Some styling will probably be required if you want it to look like the example you gave.
> 0 votes

---
Tags: paging, nodes
---


# Question
Title: Search in comments of specific content type
I'm looking for a module that provides the possibility to filter/search in comments.

When there is content of the content type = `Proposal` you can comment on it. There's a good change that there will be **50 comments or more**. Now I would like to have a search box *beneath my content*, *above my comments* that filter the comments when you **search** for a string.

I would also need to **filter the comments** for ex. between dates, by username, by number of votes, ... .

I've searched the internet but couldn't find anything that provides this functionality.

Has anybody ever needed this and which module you used or how did you approach this?

It's something like this I need:

# Answer
For this you need to enable vote up/down and voting api module enabled Then enable voting for 'Proposal' content type mentioned in the image

Now import the below code mentioned in views.

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

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'test comments';
$handler->display->display_options['use_ajax'] = TRUE;
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['link_display'] = 'custom_url';
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['distinct'] = TRUE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'comment';
/* Relationship: Comment: Content */
$handler->display->display_options['relationships']['nid']['id'] = 'nid';
$handler->display->display_options['relationships']['nid']['table'] = 'comment';
$handler->display->display_options['relationships']['nid']['field'] = 'nid';
$handler->display->display_options['relationships']['nid']['required'] = TRUE;
/* Relationship: Comment: Votes */
$handler->display->display_options['relationships']['votingapi_vote']['id'] = 'votingapi_vote';
$handler->display->display_options['relationships']['votingapi_vote']['table'] = 'comment';
$handler->display->display_options['relationships']['votingapi_vote']['field'] = 'votingapi_vote';
$handler->display->display_options['relationships']['votingapi_vote']['votingapi'] = array(
  'value_type' => 'points',
  'tag' => '',
);
$handler->display->display_options['relationships']['votingapi_vote']['current_user'] = 0;
/* Relationship: Comment: Vote results */
$handler->display->display_options['relationships']['votingapi_cache']['id'] = 'votingapi_cache';
$handler->display->display_options['relationships']['votingapi_cache']['table'] = 'comment';
$handler->display->display_options['relationships']['votingapi_cache']['field'] = 'votingapi_cache';
$handler->display->display_options['relationships']['votingapi_cache']['votingapi'] = array(
  'value_type' => 'points',
  'tag' => '',
  'function' => '',
);
/* Field: Comment: Title */
$handler->display->display_options['fields']['subject']['id'] = 'subject';
$handler->display->display_options['fields']['subject']['table'] = 'comment';
$handler->display->display_options['fields']['subject']['field'] = 'subject';
$handler->display->display_options['fields']['subject']['label'] = '';
$handler->display->display_options['fields']['subject']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['subject']['alter']['ellipsis'] = FALSE;
/* Field: Comment: Comment */
$handler->display->display_options['fields']['comment_body']['id'] = 'comment_body';
$handler->display->display_options['fields']['comment_body']['table'] = 'field_data_comment_body';
$handler->display->display_options['fields']['comment_body']['field'] = 'comment_body';
/* Sort criterion: Comment: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'comment';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Comment: Author */
$handler->display->display_options['filters']['name']['id'] = 'name';
$handler->display->display_options['filters']['name']['table'] = 'comment';
$handler->display->display_options['filters']['name']['field'] = 'name';
$handler->display->display_options['filters']['name']['exposed'] = TRUE;
$handler->display->display_options['filters']['name']['expose']['operator_id'] = 'name_op';
$handler->display->display_options['filters']['name']['expose']['label'] = 'Author';
$handler->display->display_options['filters']['name']['expose']['operator'] = 'name_op';
$handler->display->display_options['filters']['name']['expose']['identifier'] = 'name';
$handler->display->display_options['filters']['name']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
);
/* Filter criterion: Comment: Comment (comment_body) */
$handler->display->display_options['filters']['comment_body_value']['id'] = 'comment_body_value';
$handler->display->display_options['filters']['comment_body_value']['table'] = 'field_data_comment_body';
$handler->display->display_options['filters']['comment_body_value']['field'] = 'comment_body_value';
$handler->display->display_options['filters']['comment_body_value']['operator'] = 'contains';
$handler->display->display_options['filters']['comment_body_value']['exposed'] = TRUE;
$handler->display->display_options['filters']['comment_body_value']['expose']['operator_id'] = 'comment_body_value_op';
$handler->display->display_options['filters']['comment_body_value']['expose']['label'] = 'Comment (comment_body)';
$handler->display->display_options['filters']['comment_body_value']['expose']['operator'] = 'comment_body_value_op';
$handler->display->display_options['filters']['comment_body_value']['expose']['identifier'] = 'comment_body_value';
$handler->display->display_options['filters']['comment_body_value']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
);
/* Filter criterion: Comment: Post date */
$handler->display->display_options['filters']['created']['id'] = 'created';
$handler->display->display_options['filters']['created']['table'] = 'comment';
$handler->display->display_options['filters']['created']['field'] = 'created';
$handler->display->display_options['filters']['created']['exposed'] = TRUE;
$handler->display->display_options['filters']['created']['expose']['operator_id'] = 'created_op';
$handler->display->display_options['filters']['created']['expose']['label'] = 'Post date';
$handler->display->display_options['filters']['created']['expose']['operator'] = 'created_op';
$handler->display->display_options['filters']['created']['expose']['identifier'] = 'created';
$handler->display->display_options['filters']['created']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
);
/* Filter criterion: Votes: Value */
$handler->display->display_options['filters']['value']['id'] = 'value';
$handler->display->display_options['filters']['value']['table'] = 'votingapi_vote';
$handler->display->display_options['filters']['value']['field'] = 'value';
$handler->display->display_options['filters']['value']['relationship'] = 'votingapi_vote';
$handler->display->display_options['filters']['value']['exposed'] = TRUE;
$handler->display->display_options['filters']['value']['expose']['operator_id'] = 'value_op';
$handler->display->display_options['filters']['value']['expose']['label'] = 'Value';
$handler->display->display_options['filters']['value']['expose']['operator'] = 'value_op';
$handler->display->display_options['filters']['value']['expose']['identifier'] = 'vote';
$handler->display->display_options['filters']['value']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
);

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

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block_1');
$handler->display->display_options['link_url'] = 'demo';

```

It will create a block in the admin/structure/block mentioned in the below image. Assign it to 'Proposal' content type.

It will be displayed under proposal node view page this way

Hope it will help you.
> 1 votes

# Answer
I would look to put the comments in a view that you can add exposed filters to for dates, username, etc. See How to display comments of current node in a view
> 1 votes

# Answer
1) Edit your content type.

2) Under comments setting section, search for "Default comment setting for new content" drop down.

3) Select "Hidden" from drop down.

4) Click on save.
> 1 votes

---
Tags: 7, comments
---


# Question
Title: How can I create a programmatic Search API query which uses a date field
I'm trying to create a programmatic Search API query. I've successfully created one which looks for all nodes which are published:

```
  $index = search_api_index_load("node_index");
  $myQuery=new SearchApiQuery($index);
  $myQuery->condition('status', '1', '=');
  $data=$myQuery->execute();
  $results=$data['results'];

```

However the condition that I want to search for is to find all nodes with a certain date on a date field.

The problem is I can't work out how the Search API stores dates. I've tried UNIX time stamps:

```
  $myQuery->condition('field_application_end_date', '1411084800', '=');

```

And the PHP date format that is stored on the nodes however neither returns any results.

```
  $myQuery->condition('field_application_end_date', '2014-10-01T00:00:00', '=');

```

Can someone explain how the Search API stores dates?

I've been digging through the module to try and work out how it's done, but it's a little out of my league.

# Answer
> 2 votes
Try

```
$myQuery->condition('field_application_end_date:value', '1411084800', '=');

```

Search API stores the dates as timestamps, so you're right there, but you forgot the 'value' after the field. If you want to use the 'to' date, use 'value2'.

---
Tags: 7, datetime, search
---


# Question
Title: Sorry, unrecognized username or password error after successful login
In user\_login block form alter I'm attaching a validator : **ws\_res\_auth\_authenticate** ( the last one in the dsm output below) and logging in a user using this code:

```
 user_login_submit(array(), $form_state);

```

Now this function is correctly logging in the user, opening a session since on refreshing the page it shows me logged in.

But the problem is that it is showing error "Sorry, unrecognized username or password.". In reality it appears to have logged in since on refresh it shows logged-in area and other My Account stuff. So it isn't redirecting. Just redirect it I'm calling PHP header function, then a "die".

In other words after pressing submit with login/passwd it shows error : "Sorry, unrecognized username or password." but if I refresh this page it shows logged-in area.

I've tried changing the order of validators in the form\_alter so that my validator 'res\_auth\_authenticate' is called first. But still the same problem.

What am I missing?

### What I'm trying to do

I've three types of accounts: Local account, on LDAP and CSV source. What I want is that if the logged in user is found in the CSV source, I want to log the user in.

## dsm($form\['#validate'\]) output

```
... (Array, 7 elements)
0 (String, 32 characters ) ldap_user_grab_password_validate | (Callback) ldap_user_grab_password_validate();
1 (String, 24 characters ) user_login_name_validate | (Callback) user_login_name_validate();
2 (String, 66 characters ) ldap_authentication_core_override_user_login_au... | (Callback) ldap_authentication_core_override_user_login_au...();
3 (String, 52 characters ) ldap_authentication_user_login_authenticate_val... | (Callback) ldap_authentication_user_login_authenticate_val...();
4 (String, 38 characters ) noreqnewpass_user_login_final_validate | (Callback) noreqnewpass_user_login_final_validate();
5 (String, 32 characters ) readonlymode_check_form_validate | (Callback) readonlymode_check_form_validate();
6 (String, 22 characters ) ws_rest_auth_authenticate | (Callback) rest_auth_authenticate();

```

## Here is the full code

```
    <?php

/**
 * @file
 * Allow users to login using an external web service.
 *
 * Users can login to the site using a RESTful web service. If the user is
 * associated with a Drupal user, that user is logged in. If not, a new user is
 * created.
 */
/**
 * Implements hook_menu().
 */
function ws_rest_auth_menu()
{
    $items['admin/config/people/rest_auth'] = array(
        'title' => 'REST Auth',
        'description' => 'Administer REST Auth settings.',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('ws_rest_auth_settings_form'),
        'access arguments' => array('administer users'),
    );
    return $items;
}

/**
 * Form to administer REST Auth settings.
 */
function ws_rest_auth_settings_form($form, &$form_state)
{
    $form = array();
    $form['rest_auth_general'] = array(
        '#type' => 'fieldset',
        '#title' => t('General settings'),
        '#collapsible' => TRUE,
        '#collapsed' => FALSE,
    );
    $form['rest_auth_general']['rest_auth_url'] = array(
        '#type' => 'textfield',
        '#title' => t('Host'),
        '#description' => t('Enter the fully-formed URL of the authentication service.'),
        '#default_value' => variable_get('rest_auth_url'),
        '#required' => TRUE,
    );
    $form['rest_auth_general']['rest_auth_param_name'] = array(
        '#type' => 'textfield',
        '#title' => t('Username parameter'),
        '#description' => t('Enter the username parameter name that will get passed to the web service. If the username is buried inside the JSON response object, enter the hierarchy using <strong>\\</strong> as level delimiter. For example, if the username is inside <code>{"User": {"name": "Druplicon"}}</code>, enter <code>User\\name</code> in this box.'),
        '#default_value' => variable_get('rest_auth_param_name'),
        '#required' => TRUE,
    );
    $form['rest_auth_general']['rest_auth_param_pass'] = array(
        '#type' => 'textfield',
        '#title' => t('Password parameter'),
        '#description' => t('Enter the password parameter name that will get passed to the web service. If the password is buried inside the JSON response object, enter the hierarchy using <strong>\\</strong> as level delimiter. For example, if the password is inside <code>{"User": {"password": "letmein"}}</code>, enter <code>User\\password</code> in this box.'),
        '#default_value' => variable_get('rest_auth_param_pass'),
        '#required' => TRUE,
    );
    $form['rest_auth_advanced'] = array(
        '#type' => 'fieldset',
        '#title' => t('Advanced settings'),
        '#collapsible' => TRUE,
        '#collapsed' => TRUE,
    );
    $form['rest_auth_advanced']['rest_auth_auth_side'] = array(
        '#type' => 'radios',
        '#title' => t('Authentication side'),
        '#description' => t('This options allows you to determine where authentication happens.<br /><em>Note: It is more secure to authenticate provider-side, but it may require additional code from the web service provider.</em>'),
        '#options' => array(
            'provider' => t('Provider (Web service)'),
            'consumer' => t('Consumer (Drupal)'),
        ),
        '#default_value' => variable_get('rest_auth_auth_side', 'provider'),
    );
    $form['rest_auth_advanced']['rest_auth_response_name'] = array(
        '#type' => 'textfield',
        '#title' => t('Response username'),
        '#description' => t('If your authentication is consumer-side, and the username is located in a different part of the JSON response object, enter that location here. If the username is burried inside the JSON response object, enter the hierarchy using <strong>\\</strong> as level delimiter. For example, if the username is inside <code>{"User": {"username": "Druplicon"}}</code>, enter <code>User\\username</code> in this box.'),
        '#default_value' => variable_get('rest_auth_response_name'),
    );
    $form['rest_auth_advanced']['rest_auth_param_email'] = array(
        '#type' => 'textfield',
        '#title' => t('Email parameter'),
        '#description' => t('If the response contains an email address, enter the email parameter name that will be returned from the web service. If this is left empty or if the parameter is not found, the module will try to use the username as the account email. If the email is buried inside the JSON response object, enter the hierarchy using <strong>\\</strong> as level delimiter. For example, if the email is inside <code>{"User": {"email": "mail@example.com"}}</code>, enter <code>User\\email</code> in this box.'),
        '#default_value' => variable_get('rest_auth_param_email'),
    );
    $roles = user_roles(TRUE);
    unset($roles[DRUPAL_AUTHENTICATED_RID]);
    $form['rest_auth_advanced']['rest_auth_roles'] = array(
        '#type' => 'checkboxes',
        '#title' => t('Roles'),
        '#description' => t('Select the role(s) you would like to assign to new users created by REST Auth.'),
        '#options' => $roles,
        '#default_value' => variable_get('rest_auth_roles', array()),
    );
    if (module_exists('devel'))
        {
        $form['rest_auth_advanced']['rest_auth_debug'] = array(
            '#type' => 'radios',
            '#title' => t('Debug'),
            '#description' => t('This option allows you to view the response object. Turn off for production websites.'),
            '#options' => array(
                0 => t('Disabled'),
                1 => t('Enabled'),
            ),
            '#default_value' => variable_get('rest_auth_debug', 0),
        );
        }
    return system_settings_form($form);
}

/**
 * Implements hook_form_alter().
 */
function ws_rest_auth_form_alter(&$form, &$form_state, $form_id)
{
    if ($form_id == 'user_login' || $form_id == 'user_login_block')
        {
        if (isset($form_state['input']['name']))
            {
            array_unshift($form['#validate'], 'ws_rest_auth_authenticate');

            dsm($form['#validate']);
            }
        }
}

/**
 * Authenticates the user.
 */
function ws_rest_auth_authenticate($form, &$form_state)
{
    $url = variable_get('rest_auth_url');
    $name = $form_state['values']['name'];
    $pass = $form_state['values']['pass'];
    $data = array(
        variable_get('rest_auth_param_name', 'name') => $name,
        variable_get('rest_auth_param_pass', 'pass') => md5($pass),
    );
    $options = array(
        'headers' => array(
            'Accept' => 'application/json',
            'Content-Type' => 'application/x-www-form-urlencoded',
        ),
        'method' => 'POST',
        'data' => drupal_http_build_query($data),
    );
    $response = drupal_http_request($url, $options);
    if (module_exists('devel') && variable_get('rest_auth_debug', 0))
        {
        dpm($response, t('Response'));
        }
    // Verify for response error
    if (isset($response->error))
        {
        drupal_set_message($response->error, 'error');
        }
    else
        {
        // Parse response data
        $data = json_decode($response->data, TRUE);
        if (module_exists('devel') && variable_get('rest_auth_debug', 0))
            {
            dpm($data, t('Data'));
            }
        if ($error = json_last_error())
            {
            // Error
            switch ($error)
                {
                case JSON_ERROR_DEPTH:
                    drupal_set_message(t('The maximum stack depth has been exceeded'), 'error');
                    break;
                case JSON_ERROR_STATE_MISMATCH:
                    drupal_set_message(t('Underflow or mode mismatch'), 'error');
                    break;
                case JSON_ERROR_CTRL_CHAR:
                    drupal_set_message(t('Unexpected control character found'), 'error');
                    break;
                case JSON_ERROR_SYNTAX:
                    drupal_set_message(t('Syntax error. Invalid or malformed JSON'), 'error');
                    break;
                case JSON_ERROR_UTF8:
                    drupal_set_message(t('Malformed UTF-8 characters, possibly incorrectly encoded'), 'error');
                    break;
                default:
                    drupal_set_message(t('Unknown error parsing data'), 'error');
                    break;
                }
            }
        else
            {
            // Success
            if ($uid = _rest_auth_login_register($data, $name, $pass, $form_state))
                {
                $form_state['uid'] = $uid;
                return true;
                dd(__LINE__);
                }
            }
        }
}

/**
 * Log in the user, registering if the user doesn't exist yet.
 */
function _rest_auth_login_register($data, $name, $pass, &$form_state)
{
    $account = null;

    //this user should not be existing in ldap_user

    $count = db_query("SELECT module FROM {authmap} WHERE authname = :authname and module <> :module ", array(':authname' => $name, ':module' => 'ws_rest_auth'))->rowCount();

    if ($count > 0)
        {
        //ignore it  as this user has already entry thru another extrnal authentication
        return FALSE;
        }

    // Authenticate if necessary
    // Create account if it does not exist
    if (!$account)
        {

        // Determine what the email for the user should be
        $mail_candidate = _rest_auth_parse_data($data, variable_get('rest_auth_param_email'));
        if (valid_email_address($mail_candidate))
            {

            // Use if it is a valid email
            $mail = $mail_candidate;
            }
        elseif (valid_email_address($name))
            {
            // Default to username as email
            $mail = $name;
            }
        else
            {
            drupal_set_message(t('A valid email was not found for this user'), 'error');
            return FALSE;
            }

        //A valid email has been found

        if (_rest_auth_user_exists($name))
            {
            //just verify the password and log him in
            $account = user_external_load($name);  //he must be existing in this
            }
        else
            {
            // Create and save new user
            $userinfo = array(
                'name' => $name,
                'pass' => $pass,
                'mail' => $mail,
                'init' => $mail,
                'status' => 1,
                'roles' => variable_get('rest_auth_roles', array()),
                'access' => REQUEST_TIME,
                'data' => $data,
            );
            // Provide hook to alter user information
            drupal_alter('rest_auth_user', $userinfo, $data);
            $account = user_save(drupal_anonymous_user(), $userinfo);
            // Set an error if the account creation failed

            if (!$account)
                {

                drupal_set_message(t('Error saving user account.'), 'error');
                return FALSE;
                }

            user_set_authmaps($account, array('authname_rest_auth' => $name));
            }
        }
    else
        {

        // Update $user->data with information from the server
        $userinfo = array('data' => $data);
        // Provide hook to alter user information
        $context = array('user' => clone $account);
        drupal_alter('rest_auth_user', $userinfo, $data, $context);
        user_save($account, $userinfo);

        }
    // Log the user in
    dd($account->uid, 'uid');
    $form_state['uid'] = $account->uid;

    user_login_submit(array(), $form_state);

    header('Location: http://localhost/my/user/1');
    die();
    return $account->uid;
}

/**
 * Checks if a username already exists.
 */
function _rest_auth_user_exists($name)
{
    if (db_query_range('SELECT 1 FROM {users} WHERE name = :name', 0, 1, array(':name' => $name))->fetchField())
        {
        return TRUE;
        }
    else
        {
        return FALSE;
        }
}

/**
 * Get the email based on the configured response path.
 */
function _rest_auth_parse_data($data, $xpath)
{
    if ($xpath)
        {
        $xpath = explode('\\', $xpath);
        $value = $data;
        foreach ($xpath as $key)
            {
            if (isset($value[$key]))
                {
                $value = $value[$key];
                }
            }
        return $value;
        }
}

```

# Answer
You shouldn't submit the form manually during the validation. The submit function will be automatically called if the validation passes. That means you should check for errors and use `form_set_error` if your check fails.

The error message you are getting is because you try to send the login form manually with empty information. And the reason for the user is still logged in, despite of the error, is that the original form submit method will also be called since there are no validation errors.
> 1 votes

# Answer
Not sure if this is it or not, but I was poking around in the user.module and I came across the function user\_login\_final\_validate (line 2184 from user.module).

The comments for that function state:

```
   /**
     * The final validation handler on the login form.
     *
     * Sets a form error if user has not been authenticated, or if too many
     * logins have been attempted. This validation function should always
     * be the last one.
     */

```

I noticed that final validate isn't in your list of validations, wondering if that could be causing it.
> 0 votes

---
Tags: 7, users, forms
---


# Question
Title: Entity creation-form: Prepopulate all existing entity-references of a field collection
I have a content-type `seasonal_prices` with field-collection containing an entity reference field (referencing content-type `room`) and a number field; the field-collection is multi-value with unlimited cardinality.

When adding new content of type `seasonal_prices`, I want the form to be pre-populated with an instance of the field-collection for every existing content of type `room`.

An example: If there are 5 nodes of type `room`, the create-form of `seasonal_prices` should show me 5 instances of the field-collection, where each reference-field is pre-populated with its reference to `room`, so all I have to do is fill out the number-field.

UPDATE: Here is the code i finally used in a custom module, hope this is helpful:

```
<?php

function seasonal_prices_form_field_ui_field_edit_form_alter(&$form, &$form_state, $form_id) {
  // Increase the max cardinality to 20
  $range = drupal_map_assoc(range(1, count(get_roomtype_ids())));
  $new_options =  array(FIELD_CARDINALITY_UNLIMITED => t('Unlimited')) + $range;
  $form['field']['cardinality']['#options'] = $new_options;
}

function seasonal_prices_form_alter(&$form, $form_state, $form_id) {
  // update cardinality in field settings
  $field_name = 'field_prices_and_roomtype';
  $field = field_info_field($field_name);
  $field['cardinality'] = count(get_roomtype_ids());
  // field_update_field() throws an exception on failure
  try {
    field_update_field($field);
  }
  catch (Exception $e) {
    drupal_set_message(t('Could not update cardinality of field.'), 'error');
  }
  // generate fieldcollection instances
  if($form_id == 'seasonal_prices_node_form') {
    $items_count = count(get_roomtype_ids());
    $form_theme = $form[$field_name][LANGUAGE_NONE]['#theme'];
    // remove delete and add more buttons
    $form[$field_name][LANGUAGE_NONE][0]['remove_button']['#access'] = FALSE;
    $form[$field_name][LANGUAGE_NONE]['add_more']['#access'] = FALSE;
    $items = &$form_state['field'][$field_name][LANGUAGE_NONE];
    // generate required number of fields collection
    if ($items_count > 1 and $items['items_count'] != $items_count) {
      $items['items_count'] = $items_count;
      $items['field']['cardinality'] = $items_count;
      $form[$field_name][LANGUAGE_NONE] = field_multiple_value_form($items['field'], $items['instance'], LANGUAGE_NONE, array(), $form, $form_state);
      // reset theme function, as field_multiple_value_form hijacks it
      $form[$field_name][LANGUAGE_NONE]['#theme'] = $form_theme;
    }
    // fill generated instances with default values and disable access
    for ($delta = 0; $delta < ($items_count); $delta++) {
      $form['field_prices_and_roomtype'][LANGUAGE_NONE][$delta]['field_ref_roomtype'][LANGUAGE_NONE]['#default_value'] = get_roomtype_ids()[$delta];
      $form['field_prices_and_roomtype'][LANGUAGE_NONE][$delta]['field_ref_roomtype']['#access'] = FALSE;
      // designate Fieldcollection Items correctly
      $form['field_prices_and_roomtype'][LANGUAGE_NONE][$delta]['#prefix'] = '<div class="roomtype-form-label"><b>' . get_node_title(get_roomtype_ids()[$delta]) . '</b>';
      $form['field_prices_and_roomtype'][LANGUAGE_NONE][$delta]['#suffix'] = '</div>';
    }

  }
}

// Helper function to get the node title without loading the whole node object.
function get_node_title($nid) {
return db_query('SELECT title FROM {node} WHERE nid = :nid', array(':nid' => $nid))->fetchField();
}

// Helper function
function get_roomtype_ids() {
    $query = new EntityFieldQuery();
    $query
    ->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'roomtype')
    ->propertyCondition('status', 1)
    ->propertyOrderBy('created', 'ASC');
    $result = $query->execute();
    return array_keys($result['node']);
}

```

# Answer
You will need to create a custom module that alters the node creation form before it rendered using hook\_form\_FORM\_ID\_alter().

You want to edit the form\_state which stores the information on how a form is filled out.

It should look something like this:

```
<?php

/**
 * Module to prepopulate season price list with rooms
 */

/**
 * Implements hook_form_FORM_ID_alter(&$form, &$form_state)
 */

function mymodule_form_seasonal_prices_node_form_alter(&$form, &$form_state){

    // Load all of the room node ids into an array
    $node_type = "room";
    $result = db_query("SELECT nid FROM node WHERE type = '%s' ", $node_type);
    $nids = array();
  while ($obj = db_fetch_object($result)) {
    $nids[] = $obj->nid;
  }

  // Set the form state to include each room
  foreach($nids as $nid){
    $form_state->field_collection_you_want_to_edit[] = $nid
  }
}

```

You will need to do a bit of sleuthing to figure out what to put in the last line as it is specific to your build, and I don't know whether you need to set it to the $nid or node\_load($nid) or something else. But this should give you a framework to go on with.

If you haven't come across the Devel module yet, install it, and use `dpm($form_State);` to look at the structure of the variable so that you know what to change.

Finally, make sure you change the name of the function from 'mymodule' to whatever name you have given your module, make sure the machine names for your content types and form ids are correct (I just guessed them), and clear the cache so that Drupal picks up the hook.
> 1 votes

# Answer
Darvanen suggest a very good solution.

You need a form\_alter to pre-populate your room collection field But while fetching all rooms from database, I will recommend if you will use db\_select instead of db\_query in form\_alter as it is better way to interact with drupal database.
> 1 votes

---
Tags: entities
---


# Question
Title: How to set default role as 'Member' in drupal 7?
If I have a role i.e. Member. How to set 'Member' as a default role for the users after they registered yourself ? Please help. Thanks

# Answer
> 3 votes
Can you not do this through Rules?

Event: After saving a new User account

Condition:

Action: Add User role \> \[account\] - Member

# Answer
> 3 votes
Use Auto Assign Role module to set a default role at the time of user registration.

You can also use registration\_role module to fulfill your requirement.

# Answer
> 1 votes
It is always recommended to use contributed module instead of writing a custom module if it is in stable release and fulfills your requirements. Auto Assign Role is exact solution of your problem.

1. Install the module.
2. Go to Configuration-\>People-\> Auto Assign roles.
3. Click on Automatic Assignment.
4. Select your default role. (Member in your case)
5. Click on save.

Bingo!

# Answer
> -2 votes
click edit column on **People** page on specific user who will have role **Member**, and tick **Memeber** checkbox on that edit page.

---
Tags: users
---


# Question
Title: Custom warning on when viewing cart (anonymous users)
I am wondering with what mechanisms it would be possible to add a warning message to anonymous users viewing their cart saying: "Please log in with any of the listed services in order to proceed to checkout".

If possible I'd like to avoid changing the module's code in order to avoid future update problems.

Thanks for any help, Best

# Answer
The easiest way is overriding a default cart page template (cart page has been created with Views module, name - 'commerce\_cart\_form', display - 'default');

1. Create a template for Style Output
2. Copy the content of it
3. Views module provides `logged_in` variable in `template_preprocess_views_view(&$vars)` function, so you can check with that variable and display a text;

example (`views-view-table--commerce-cart-form--default.tpl.php`):

```
<?php if (!$logged_in): ?>
  MY MESSAGE FOR THE ANONYMOUS
<?php endif; ?>

<table <?php if ($classes) { print 'class="'. $classes . '" '; } ?><?php print $attributes; ?>>
  // Rest of code from Style Output
</table>

```
> 1 votes

---
Tags: users, commerce
---


title: How do I add a field label?

text:
# Question
Title: How do I add a field label?
I am trying to override a VBO field in order to add a label.

In the following code, `preg_match()` returns an empty array and `var_dump($output)` returns a 41-character string, which is wrong.

```
print $output;
preg_match ("/id=\"(.*)\"/si", $output, $matches);
print_r ($matches);

```

The content of `$output` is the following.

```
<div class="form-item form-type-checkbox form-item-views-bulk-operations-11">
<input class="vbo-select form-checkbox" type="checkbox" id="edit-views-bulk-operations-11" name="views_bulk_operations[11]" value="12">
</div>

```

How do I add a label to the field?

# Answer
> 1 votes
If you just want to add a label, instead of going to the hook\_form\_FORM\_ID\_alter and figuring which fields need to change and how, you should first check the options that are already available in Views and allow you to change your field's styling. Specifically, you can edit the Bulk Operations field:

and search for the Style Settings:

A sample configuration may look like this:

---
Tags: views
---


# Question
Title: How to remove/hide 'to time' in time field
I need to show only one time, no need of start and end time. Or I need to show only start time. Please anyone help me on this.

# Answer
> 2 votes
You can change in the field setting

Go to your content type, Now when we add a field of **Date** type. Then it will show a section for start and end date mentioned in the image

For already added field, you can not edit it i think because there is already content with end date. You can hide it if neccessary

Hope it will help!

---
Tags: datetime
---


title: add value to shipping service

text:
# Question
Title: add value to shipping service
I am using flat rate shipping service and I want to add a value to shipping service price, I know drupal commerce has a rule for this job, `Add an amount to the unit price` , but when I want to complete it I don't know what is should enter in **Line item** section ?

I try below one by one

```
commerce-order:commerce-line-items:0
commerce-order:commerce-line-items:1
commerce-order:commerce-line-items:2
commerce-order:commerce-line-items:3
commerce-order:commerce-line-items:4

```

but no one work. exactly what this mean, I want add value to only line item that is shipping type, I search google but didn't get any example or something similar this.

appreciate any lead an suggestion about what I should enter in **line item** ?

# Answer
You are editing the component rule for the flat rate. Instead, you'll want to create a shipping pricing rule.

http://youtu.be/trLydGpimD4?t=10m7s

In that video, I show you how to set up a shipping pricing rule that only runs on a particular flat rate service ... I've linked for you to jump to the part of the video that walks you through that.

The two conditions you're looking to add:

Entity has field (it should have the shipping service field) Data Comparison (the shipping service field should equal whatever flat rate you want to tweak)

Josh
> 0 votes

---
Tags: commerce
---


title: Update Drupal core from a low version

text:
# Question
Title: Update Drupal core from a low version
I have to update a website from 7.14 to 7.31.

I feel like this contains a lot of risks. As anyone updated so many versions? What are your recommendations ?

I figured it would be better to update version per version instead of applying the 7.31 update right away. I made sure the core was not modified.

Thanks,

# Answer
As long as core is not modified in any way, there should be no risks of updating it straight from 7.14 to 7.31. It will apply all database updates from each version in between. There's literally no difference in doing it one version at a time compared to doing it straight to 7.31.

But as always, test it in a development environment before doing it in production and always make backups.
> 2 votes

# Answer
I have done it before without any problem using drush in my test environment for an old project. My core did not have any modification or hack. Check also that your modules are up to date.

**Please make sure before doing anything to do the proper backups to the database and code.**
> 0 votes

---
Tags: updating
---


title: Disable path user on Drupal 7

text:
# Question
Title: Disable path user on Drupal 7
Since most of my d7 users will authenticate somewhere outside Drupal itself, I need to disable "/user" path for most of them (not uid 0 of course). What is the best approach we have here?

# Answer
how about

```
function mymenu_menu_alter(&$items) {
$global $user;
 if ($user->uid != '0'){
  $items['user']['access callback'] = FALSE;
}
}

```
> 1 votes

# Answer
Other solutions is fine and work correctly,but if you want do it with modules feature you can try redirect it with Redirect module, install it, then redirect every `user` and `user/*` path to `/`(or any path you want).
> 1 votes

# Answer
You can disable the access to this path:

```
function mymenu_menu_alter(&$items) {
  $items['user']['access callback'] = FALSE;
}

```
> 0 votes

# Answer
My best bet so far is:

```
function MYMODULE_user_view($account, $view_mode, $langcode)  {
  global $user ;
  if ($user->uid > 1) {
    drupal_goto ("");
  }
}

```
> 0 votes

# Answer
May be like this (in template.php) :

```
function THEME_preprocess_page(&$variables)
{
  if ($variables['user']->uid > 1 && arg(0) == 'user') {
    drupal_goto('SOME_PATH'); // instead of restricting the access
  }
}

```
> 0 votes

---
Tags: users
---


title: how to remove wrapper for boxes?

text:
# Question
Title: how to remove wrapper for boxes?
I am trying Boxes for first time instead of block, however. It is adding some wrapper DIVs. I usually use hook\_preprocess\_block() to remove them but it is not the case with Boxes

```
 function HOOK_preprocess_block(&$variables)
{
    switch ($variables['block']->region) {
        default:
            $variables['theme_hook_suggestions'][] = 'block__no_wrap';
            break;
    }
}

```

How to remove DIVs wrapper for Boxes? Thank you for any help

# Answer
I have not tried Boxes myself, but looking at its code, it looks like they use a theme function to produce the markup for the boxes.

If you implement `theme_boxes_box` (found in `boxes.admin.inc`) in your own theme/module you can just copy the code from it and remove the markup you don't want.

```
/**
 * Overrides theme_boxes_box().
 */
function MYMODULE_boxes_box($variables) {
  $block = $variables['block'];

  $empty = '';

  // Box is empty
  if ((empty($block['title']) || ($block['title'] == '<none>') ) && empty($block['content'])) {

    // add a class to mark the box as empty
    $empty = ' box-empty';

    // show something if the block is empty but the user has the permission to edit it
    if (boxes_access_edit()) {
      $block['content'] = t('This box appears empty when displayed on this page. This is simply placeholder text.');
    }
    else {
      return;
    }
  }

  $output = "<div id='boxes-box-" . $block['delta'] . "' class='boxes-box" . (!empty($block['editing']) ? ' boxes-box-editing' : '') . $empty . "'>";
  $output .= '<div class="boxes-box-content">' . $block['content'] . '</div>';
  if (!empty($block['controls'])) {
    $output .= '<div class="boxes-box-controls">';
    $output .= $block['controls'];
    $output .= '</div>';
  }
  if (!empty($block['editing'])) {
    $output .= '<div class="box-editor">' . drupal_render($block['editing']) . '</div>';
  }
  $output .= '</div>';
  return $output;
}

```
> 1 votes

---
Tags: blocks
---


# Question
Title: Display Local tasks from one page to another
I have a menu structure like this:

* $items\["foo"\] -\> MENU\_NORMAL\_ITEM
* $items\["foo/bar"\] -\> MENU\_DEFAULT\_LOCAL\_TASK
* $items\["foo/something"\] -\> MENU\_LOCAL\_TASK
* $items\["foo/bar/bazz/%"\] -\> MENU\_CALLBACK

I want to have the tabs (local tasks) from page `foo/bar` displayed on `foo/bar/bazz/%` as well but I don't want to have another local task for this new page.

Any ideas on how can I achieve that? Thanks.

# Answer
> 0 votes
I kinda managed to to this by using the following piece of code:

```
$path = drupal_get_normal_path('path-where-local-tasks-are-displayed');
if($path) {
  menu_tree_set_path("navigation", $path);
  menu_set_active_item($path);
}

```

---
Tags: 7, routes
---


title: Webform Redirect Hook

text:
# Question
Title: Webform Redirect Hook
I built a module that submits the webform data to a soap api. The API an take a while to respond (out of my control), so what I'm looking for is a redirection hook, so I can go Submit-\>Force Redirection-\>submit to api.

Users are hitting submit more than once due to the api response time (understandably)

# Answer
> 0 votes
You can disable the double click on submit using the below jQuery code.

```
$('#formid').submit(function(){
    $(this).children('input[type=submit]').prop('disabled', true);
});

```

Now you can use the below code to alter submit of webform in your custom module

```
/**
 * Implementation of hook_form_alter().
 */
function mywebform_extra_form_alter(&$form, &$form_state, $form_id) {
  // Add extra submit for a particular Webform node:
  if ($form_id == 'webform_client_form_44') {

    // Add the submit handler after the existing Webform submit handler,
    // but before the second Webform handler. Pop off the first one and add
    // ours second.
   $form['#submit'][] = 'mywebform_extra_validate_44';
  }
}

/**
 * Submit handler for Webform ID #44.
 */
function mywebform_extra_submit_44(&$form, &$form_state) {
  global $user;

  // Now you can perform here api request and redirect
}

```

Hope it will help you.

---
Tags: webforms, redirection
---


title: Secondary Tabs and views

text:
# Question
Title: Secondary Tabs and views
I am trying to get Secondary Tabs to work. I want to create a local tab with sub tabs.

View | Edit | **Reg Report**

Reg Report
Reg Report | Pre-Registration | Post-Registartion (Secondary Tabs)

I tried this method (Menu secondary tabs) and have it showing the naviagation, however when I add the path for Photo to my second view the navigation goes away.

Here is the code:

```
/**
 * Implements hook_menu().
 */
function secondary_tabs_menu() {
  $items['node/%node/update'] = array(
   'title' => 'Update',
   'page callback' => 'price_callback_function',
   'access arguments' => array('access args'),
   'type' => MENU_LOCAL_TASK // This adds the 'Update' tab to the node path
 );

 $items['node/%node/update/price'] = array(
   'title' => 'Price',
   'type' => MENU_DEFAULT_LOCAL_TASK,
   'weight' => -10
 );

 $items['node/%node/update/photo'] = array(
   'title' => 'Photo',
   'page callback' => 'callback_function',
   'access arguments' => array('access args'),
   'access callback' => TRUE,
   'type' => MENU_LOCAL_TASK // This adds another tab under 'Update'
 );
  return $items;
}

/**
 * Implements hook_admin_paths().
 *
 * Show admin theme on the participants totals report.
 */
function secondary_tabs_admin_paths() {
  return array(
    'node/*/update' => TRUE,
  );
}

```

My goal is to create a sub-section where I can click through a few views within this secondary tab area.

Also, I was trying to add the Admin theme to the views as well.I have it in code but it doesn't seem to work.

Can someone guide me towards what I might be missing. Thanks!

# Answer
So, Basically I was trying to piece together a few views under one local task tab for a content admin. I finally figure out how to write a small module to create the structure and used views path and menu to point to the sub task items. See below.

```
/**
 * Implements hook_menu().
 */
function secondary_tabs_menu() {
  $items['node/%node/update'] = array(
   'title' => 'Update',
   'page callback' => 'price_callback_function',
   #'access arguments' => array(2),
   'type' => MENU_LOCAL_TASK // This adds the 'Update' tab to the node path
 );

 $items['node/%node/update/price'] = array(
   'title' => 'Price',
   'type' => MENU_DEFAULT_LOCAL_TASK,
   'weight' => -10
 );

 $items['node/%node/update/test'] = array(
   'title' => 'Test',
   'page callback' => 'callback_function',
   #'access arguments' => array(2),
   'access callback' => TRUE,
   'type' => MENU_LOCAL_TASK // This adds another tab under 'Update'
 );
 $items['node/%node/update/test/test1'] = array(
   'title' => 'Test1',
   'page callback' => 'callback_function',
   #'access arguments' => array(2),
   'access callback' => TRUE,
   'type' => MENU_LOCAL_TASK // This adds another tab under 'Update'
 );
 $items['node/%node/update/test/test2'] = array(
   'title' => 'Test2',
   'page callback' => 'callback_function',
   #'access arguments' => array(2),
   'access callback' => TRUE,
   'type' => MENU_LOCAL_TASK // This adds another tab under 'Update'
 );

  return $items;
}

/**
 * Implements hook_admin_paths().
 *
 * Show admin theme on the participants totals report.
 */
function secondary_tabs_admin_paths() {
  return array(
    'node/*/update' => TRUE,
    'node/*/update/test' => TRUE,
    'node/*/update/test/test1' => TRUE,
    'node/*/update/test/test2' => TRUE,
  );
}

```

I also found out the best way to make those views show up within the admin theme. See hook\_admin\_path().
> 0 votes

---
Tags: routes
---


# Question
Title: Hook to catch a variable in a POST request to a specific url?
I'm testing an external email collection service that appears periodically at certain time intervals on a site.

When a user completes the form, the application can pass the email address as a variable in a POST request to a specific url.

What hook should I use to catch and process the email address at this one specific url?

I thought of using hook\_init() something like the following, but I'm not sure if this is a good way to do something like this?

```
/**
 * Implements hook_init()
 * Check for variable sent via POST and process if found
 */
function mymodule_init() {
  if (drupal_get_path_alias() == "myurl") {
    if (isset($_POST['email_variable'])) {
      <custom processing>;
    }
  }
}

```

Notes:

1. The url is a normal node page that already exists on the site.
2. The form is externally hosted, so a form alter is not an option.

# Answer
You should use the services module to create an endpoint and use the url where is sent as the path to endpoint.

You don't state which type format the data is being posted to your site but the services module can handle many different types.

Also it's not stated exactly what you want to do with the received data but the services module can be set up to process it in a variety of ways.

You can capture it to a databse table etc or Here's an example of creating a node using services: http://www.drupalwoo.com/content/blog/drupal-services-creating-node-from-external-form
> 0 votes

# Answer
Use `mytheme_preprocess_node(&$vars, $hook)` in your active theme's `template.php` file.

```
function mytheme_preprocess_node(&$vars, $hook) {
  if($vars['nid'] =='node id of that node page'){

 //Add your code to get the data from post using post key
   $data = $_POST['datakey'];// datakey will contain data with which data is posted to this form
 }
}

```

Please, don't forget to clear drupal cache.

Hope it will help!
> 0 votes

---
Tags: hooks
---


# Question
Title: Drupal 6 will not use updated htaccess 301 information
I'm not 100% sure that this is a Drupal problem, but I think there is any issue with my site not flushing the cache. I am trying to change a redirect. I was having some trouble with URL Redirect in the CMS, so I am using the .htaccess file directly. Previously I had set up

redirect 301 /renew https://OLDREDIRECT.com

I just changed that to

redirect 301 /renew https://NEWREDIRECT.com

However, no matter what I do, the site keeps redirecting to the old link.

I have flushed the cache in Drupal, I've flushed my own browser cache, and I even tried running cron, but it will not use the new redirect info in .htaccess.

Does anyone have any idea what might be going on?

Thank you.

# Answer
> 0 votes
.htaccess shouldn't require any cache flushes, restarts of the server, etc. They should just take effect.

If you want to check to make sure that your editing the right file (and your not on a production server) you can always throw and invalid line in your .htaccess file. If it throws back a 500 error, your editing the right file and something is wrong somewhere in it, if it doesn't your're working on the wrong file.

# Answer
> 0 votes
Whoops, it turns out the problem was with my URL. I had retained a “++++++” instead of using “%2B%2B%2B%2B%2B%2B”

That fixed it.

---
Tags: 6, .htaccess
---


# Question
Title: How do I delete a vote (e.g.rate module)?
Is there a module with a functionality to delete votes using the voting api? If not, how do I implement a button that erases *all* votes? Or is it easier if I just empty the MYSQL table?

# Answer
The voting api defines some drush commands:

```
drush generate-votes <entity_type> <vote_type>
drush votingapi-recalculate <entity_type>
drush votingapi-flush <entity_type>

```

if you don't use drush, you can run the code from the function that the module uses on devel php or similar

```
<?php
$entity_type = "name_of_the_entity";
$cache = db_delete('votingapi_cache');
$votes = db_delete('votingapi_vote');

if (!empty($entity_type)) {
  $cache->condition('entity_type', $entity_type);
  $votes->condition('entity_type', $entity_type);
}
if (!empty($entity_id)) {
  $cache->condition('entity_id', $entity_id);
  $votes->condition('entity_id', $entity_id);
}

$cache->execute();
$votes->execute();

```
> 1 votes

---
Tags: rating
---


# Question
Title: Drush returns "sh: php: command not found, code: 127"
Drush returns "sh: php: command not found, code: 127"

I just managed to get Drush working finally on my MacBook-Pro (2008). For the longest time Drush would not interact with the Drupal installation. Turns out the reason for this was the fact that Drush expects to use the default MacBook-PHP which is different from the MAMP-Stack-PHP which is what Drupal will be using.

This was sorted out and now appears to mostly work. My environment is MacBook-Pro with Drupal-7.31 and Drush-5.9. I am using the MAMP-PHP-5.5.14.

The conflicting PHP issue was resolved by renaming the MacBook-Default PHP file by adding an extension to its name. Then the .bash\_profile file was modified to add a PATH to the MAMP-PHP and an alias was added for file-name of the PHP that Drush usually expects to substitute the newer MAMA-PHP. If you need the details, those are explained in my other recent question: "Drush on Macbook Pro cannot read Drupal Correctly".

Now there is another issue coming up. When I run a "drush upc" or a "drush owiz" command, I get an error: "sh: php: command not found, code: 127". This seems to be telling me that Drush runs an sh-shell command which cannot locate my new MAMP-PHP file.

Any guidelines in fixing this, if this is in fact what this error means?

# Answer
> 1 votes
Exit code 127 means "command not found", just as the error message says. https://www.gnu.org/software/bash/manual/html\_node/Exit-Status.html

If php is in your PATH, then this should not happen. If you want to explicitly tell Drush which php to run, then set the DRUSH\_PHP environment variable as explained in the Drush README. This should help out in the case of Drush commands such as the ones you mention before, that run a Drush subcommand in a new process.

**Update:**

To make things work correctly, you need to understand how bash initializes itself. For example, did you know that .bash\_profile *is* sourced if you run `ssh user@host`, but it is *not* sourced if you run `ssh user@host pwd`? Drush uses the later form to re-launch Drush subprocesses, so if you initialize your PATH in .bash\_profile, then it will be fine when you test it in the shell, but it will be broken for Drush subprocesses.

To get around this problem, you should also export your PATH in your .bashrc file, as bash will source this file for non-login shells. Be sure to set up your PATH at the TOP of the file, as there is a line near the top that reads: `[ -z "$PS1" ] && return`. This causes the script to exit if ssh did not create a tty (run `ssh -t` to create a tty; Drush adds this flag for interactive commands only.)

# Answer
> 0 votes
RESOLVED. 9/22/2014

I began to discover that the previous method of attempting to change the 'alias' or otherwise redirecting Drush to use MAMP's PHP was the wrong way to go. Especially 'name-distorting' the original MacBook-OS-PHP so that Drush would opt for the MAMP-PHP was causing all kinds of problems with other software, as might be expected. I don't know how this method came to be recommended, but it appears that it is actually a pit-fall.

The way better approach (watch me eat my words in a few weeks), is to rather just upgrade the MacBook-OS-PHP to the same or nearly same version as the MAMP-PHP. Then it does not matter which version of PHP Drush or anything else uses because they are both the same. This overcomes all the issues and is not that difficult to accomplish. At least on my platform which is a MacBook-Pro (2008-Mavericks).

The way that I upgraded my MacBook-OS-PHP was by the CLI-command "curl -s http://php-osx.liip.ch/install.sh | bash -s 5.5".

This is a download from a group of developers in Germany which upgrades your PHP. Check out "http://php-osx.liip.ch/".

Once my System-PHP and MAMP-PHP were almost the same, all my issues with Drush went away. I undid all my 'aliases', 'redirects' and 'name-distortions'. So far all is working well.

Note that on my machine MAMP is using PHP-5.5.14 and my CLI reports with a "php -v" command that MacBook-OS is using PHP-5.4.30 though I am not sure that the version is accurate. In the write up on the PHP-Upgrade it mentions that the version might not be accurate.

By the way this does not OVERWRITE your previous PHP installation but rather just adds a newer installation and directs your system to use it.

I will update if there later prove to be drawbacks in this approach.

---
Tags: installation, drush
---


# Question
Title: I cannot get Drush to work on Macbook Pro
I tried to get Sass and Compass working on Windows, but I ran into too many problems. Now I have purchased a vintage Macbook Pro (2008). I finally got Drush working on Windows, but I can't seem to get Drush to work on the Macbook.

On the Mac, I am using a MAMP Stack. I tried installing Drush 6.0, but it began to ask for Composer and other such further complications. I installed Pear, but could not figure out the instructions to use Pear to install Drush. So I tried a simple installation of Drush 6.0 from a tar file. I installed it in the '/Applications/MAMP/htdocs' directory. It could download modules and themes, but Drush couldn't do a simple status check or clearing cache. Somehow it could not interact with Drupal.

Next I tried a zip download of Drush 5.9. When I try to launch Drush, Drush can show a status report. It reports Drupal, but incorrectly reports the Garland theme as default theme. By the way this same output happens if I am in the Omega-Theme working directory or the Drupal-Root working directory.

Drush also fails to accomplish clear the cache; it can only clear its own cache. `drush pm-list` returns an error message about Drush not being able to bootstrap the Drupal database.

I read the *ReadME* file in the Drush installation directory; I tried to follow the instructions to set the PHP directory in .bash\_profile. Then trying to follow the instructions for configuring php.ini, I got lost in finding out the PHP versions used by the webserver. (I suppose this means MAMP.)

Now I am at a loss as what to do next to get Drush working.

Any help is greatly appreciated.

# Answer
> 2 votes
RESOLVED. 9/22/2014

I began to discover that the previous method of attempting to change the 'alias' or otherwise redirecting Drush to use MAMP's PHP was the wrong way to go. Especially 'name-distorting' the original MacBook-OS-PHP so that Drush would opt for the MAMP-PHP was causing all kinds of problems with other software, as might be expected. I don't know how this method came to be recommended, but it appears that it is actually a pit-fall.

The way better approach (watch me eat my words in a few weeks), is to rather just upgrade the MacBook-OS-PHP to the same or nearly same version as the MAMP-PHP. Then it does not matter which version of PHP Drush or anything else uses because they are both the same. This overcomes all the issues and is not that difficult to accomplish. At least on my platform which is a MacBook-Pro (2008-Mavericks).

The way that I upgraded my MacBook-OS-PHP was by the CLI-command "curl -s http://php-osx.liip.ch/install.sh | bash -s 5.5".

This is a download from a group of developers in Germany which upgrades your PHP. Check out "http://php-osx.liip.ch/".

Once my System-PHP and MAMP-PHP were almost the same, all my issues with Drush went away. I undid all my 'aliases', 'redirects' and 'name-distortions'. So far all is working well.

Note that on my machine MAMP is using PHP-5.5.14 and my CLI reports with a "php -v" command that MacBook-OS is using PHP-5.4.30 though I am not sure that the version is accurate. In the write up on the PHP-Upgrade it mentions that the version might not be accurate.

By the way this does not OVERWRITE your previous PHP installation but rather just adds a newer installation and directs your system to use it.

I will update if there later prove to be drawbacks in this approach.

---
Tags: drush, installation
---


# Question
Title: How can I achieve basic authentication in Drupal?
I am trying to get working webservices in drupal (Services, restws,...), but ,as a first step I am trying to get a cookie using 'Basic Authorization' using the following python script:

```
import urllib2
import base64

def login(u,p):
    url = 'http://127.0.0.1/drupal/node?destination=node'
    r = urllib2.Request(url,None,{'Authorization':'Basic '+base64.b64encode(u +':' + p),
                                  'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                              'Accept-Encoding': 'gzip, deflate'})
    f = urllib2.urlopen(r)
    cookie = f.headers.dict['set-cookie'] # <--- this fails, raises exception
    csrf = f.read()
    return csrf,cookie

csrf, cookie= login('username', 'password')
print base64.b64encode(csrf)
print "cookie:", cookie

```

The line 'cookie=f.headers.dict\['set-cookie'\]' fails, since there's no cookie returned in the response. What could I have missed ?

# Answer
> 1 votes
Drupal 7 will not set a session cookie unless it has to, for performance reasons. If there is no form under `http://127.0.0.1/drupal/node`, and no module requires sessions, you will not get any session, simple as that.

---
Tags: services, users
---


# Question
Title: How to remove submitted & author information on Entityform submission view?
I'm trying to remove the author/submitted information from an entityform submission view and I don't seem to find the right way to do so.

I'm using Display Suite to manage the view of the email that is being sent to the user with the values of the submission, also in the regular view submission page. The submission is for anonymous users, so it's useless to add the following prepended information:

> Submitted by Anonymous on thu, 06/12/2014 - 14:18

Which obviously doesn't make any sense in the way my form is working.

Does anyone knows how to achieve the removal of this information?

Thanks!

# Answer
> 1 votes
That value is a `t()` function call here http://cgit.drupalcode.org/entityform/tree/entityform.module#n1092

This is used by the custom EntityClass provided by the EntityForms module in the `buildContent` function: http://cgit.drupalcode.org/entityform/tree/entityform.module#n1226

This is PHP class. You have many options:

* See if there is a `TPL` file defined for this submission and alter the default output with your own.
* Try to use String Overrides to and set the `t()` string to `""` in the Admin interface for String Overrides. The string you'd look to replace is `"Submitted by !name on !date"`. This may have un-desired affects for other content types and non-Anonymous users ...
* Your other option is to replace the custom EntityForms class with 1 of your own using a database query to change the `system` table's entry for the EntityForms class to 1 you copy-paste of the same name and change the 1 line of code in it :/ (I don't really recommend this.
* Lastly you can use `hook_page_alter` to scan for the string in the `content` array of the Node on the page and remove the text out.
* Or really lastly, you can hide the text using CSS rules.

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


# Question
Title: "Shopping cart form" view breaks after adding a field
I'm creating a website using the Drupal Commerce module. The module implements a view for the customer's cart at "cart/my", listing all the items the customer added to her/his cart.

The view used to render the item list is "Shopping Cart Form".

I edited this view (well cloned it first) to add an image field owned by the product. In order to get this field in the fields' field list, I first had to create a relation called "(Line items referenced by commerce\_line\_items) Commerce Line item : Product" for that view. The issue I'm having is that, when the relationship is added (and only then) to get my image field, the view completely breaks when viewed by anonymous or regular authenticated users, and only for these roles. Everything is fine when the cart is viewed by a different role (either a custom role or the administrator role).

I know it sounds crazy, but that's it... Somehow, addind this relation makes the results found for this view to 0 (as shown in the kpr() function run from mytheme\_preprocess\_views) and only for anonymous and regular authenticated users. If I remove the relation from the view, all goes well again.

Could it be a permission rule somewhere that I skipped ?

# Answer
> 0 votes
what you're experiencing is actually the same as another user whose anonymous users were not able to view their carts. It's related to Views relationships and the automatic access checks they add to Views queries. For more information, please see my answer here:

Anonymous cannot see cart in cart page

---
Tags: views, commerce
---


# Question
Title: Rules: How to send an email when an OG membership field changes its value?
I have some OG groups in my site. Each group is an online classroom.

The membership has a few fields (I use the default membership), and one of those fields is a select field with "approved" or "not approved" information about each student's final exam.

**I would like to use rules to send an email to each student that change that OG membership field status to "approved".** I want this workflow only for users of "exchange-student" role.

But I cannot do that because it seems that I didn't fetched the OG membership. I don't know what I'm doing wrong here.

This is my Rule:

## Event:

After updating an existing og membership

## Conditions:

Entity exists by property (Parameter: Entity type: OG membership, Property: Exam, Value: Approved)

User has Role (Parameter: User: \[site:current-user\], Roles: exchange-student)

Action: Send a message (Parameter: Receptáculo: \[site:current-user\], Private message author: \[site:current-user\], Private message subject: Aprobaste, Private message body: Mensaje de Prueba)

What am I doing wrong? What am I missing?

Thanks for your help.

# Answer
I believe the answer lies in your Conditions.

You are checking whether the *current user* has the appropriate role.

See if you can find a token for the *user whose membership has been changed.*
> 0 votes

---
Tags: rules, organic-groups
---


title: Creating node when cron runs

text:
# Question
Title: Creating node when cron runs
I'm a bit new to drupal and I have a task, where I have to create a node when cron runs. I set up the node like this in my custom module's cron hook:

```
$node = new stdClass();
$node->type = 'reports';
$node->language = LANGUAGE_NONE;
$node->uid = 1;
$node->status = 1;
$node->promote = 0;
$node->comment = 0;
$node->sticky = 0;
$node->moderate = 0;
$node->title = 'Daily Report for ' . date('d.m.Y');
$node->field_reporting_cycle[LANGUAGE_NONE][0]['value'] = 1;
$fid = generate_periodic_report(1);
$node->field_period_of_reporting[LANGUAGE_NONE][0]['value'] = date('Y-m-d', strtotime('-1 days'));
$node->field_period_of_reporting[LANGUAGE_NONE][0]['value2'] = date('Y-m-d');
$node->field_reciver[LANGUAGE_NONE][0]['value'] = 2;
$file = file_load($fid);
$file = (array)$file;
$file['display'] = 1;
$node->field_report_file[LANGUAGE_NONE][] = $file;
node_object_prepare($node);
$node = node_submit($node);
node_save($node);

```

The node doesn't get created. I don't get any error messages in the log. I don't know what I'm doing wrong.

# Answer
So I got my answer by myself: I ran clear cache and it performs everything perfectly. @Andrew Morris: I haven't used Rules before but I think it can't be performed by that. The generate function creates 2 xls files via PHPExcel and gets all files uploaded by user in a period of time. Then it compresses all the files into a zip archive via ZipArchive and saves the data for the zip file. Then it returns the fid of the saved file.
> 2 votes

# Answer
This is an oddly similar answer to the last question I answered but... Can't you just do this with Rules?

Event: Cron maintenance tasks are performed

Condition:

Action: Create a new Entity \> Type - Node

Then you can use individual 'Set a data value' to set the parameters you need.
> 1 votes

# Answer
Either way, you can use your custom code with the drupal function `hook_cron()`.

```
MyModulename_cron(){

$node = new stdClass();
$node->type = 'reports';
$node->language = LANGUAGE_NONE;
$node->uid = 1;
$node->status = 1;
$node->promote = 0;
$node->comment = 0;
$node->sticky = 0;
$node->moderate = 0;
$node->title = 'Daily Report for ' . date('d.m.Y');
$node->field_reporting_cycle[LANGUAGE_NONE][0]['value'] = 1;
$fid = generate_periodic_report(1);
$node->field_period_of_reporting[LANGUAGE_NONE][0]['value'] = date('Y-m-d', strtotime('-1 days'));
$node->field_period_of_reporting[LANGUAGE_NONE][0]['value2'] = date('Y-m-d');
$node->field_reciver[LANGUAGE_NONE][0]['value'] = 2;
$file = file_load($fid);
$file = (array)$file;
$file['display'] = 1;
$node->field_report_file[LANGUAGE_NONE][] = $file;
node_object_prepare($node);
$node = node_submit($node);
node_save($node);

}

```

Everytime the cron runs, a new node is created.

I hope it works for you searching on!
> 0 votes

---
Tags: 7, cron
---


# Question
Title: Can I add a "edit node" link as field in a node?
I need to have the "edit node" link as a field so that I can manage its display.

Can I do this?

Update: I created the field but the token code is printed instead of its value. The code you see in the capture is printed: `http://misite.com/node/%5Bnode%3Anid%5D/edit`

Capture:

# Answer
> 2 votes
As variant, You can create custom code field via display suite module.

Example field code for node edit link:

```

print l(t('Edit this node'), 'node/' . arg(1) . '/edit');

```

# Answer
> 4 votes
You could also check to see if the user has access before printing the edit link. `<?php
 if (node_access('update', $entity)) {
 print l(t('Edit'), 'node/' . $entity->nid . '/edit');
 }
?>`

# Answer
> 1 votes
I think you better use $entity-\>nid when you want to print the nid in display suite format. With $entity-\>nid the correct nid of each item is printed when used in teaserlists.

```
<?php print l(t('Edit this node'), 'node/' . $entity->nid . '/edit'); ?>

```

---
Tags: entities
---


title: Save Link field in custom form

text:
# Question
Title: Save Link field in custom form
I'm brand new at making custom forms and I'm having trouble getting the link field to save to the database.

The text body field saves fine but the link field object defined below it does not. I'm sure that this is an easy fix but I haven't been able to find proper documentation on adding the link field to custom forms.

Thanks in advance.

```
    /**
* Implements hook_block_configure().
*/

function My_Module_block_configure($delta='') {
$form = array();

switch($delta) {
case 'my_module' :
    // Text field form element
    $form['text_body'] = array(
        '#type' => 'text_format',
        '#title' => t('Enter your text here in WYSIWYG format'),
        '#default_value' => variable_get('text_variable', ''),
     );

     //link field
    $form['link'] = array(
        '#type' => 'link_field',
        '#size' => 20,
        '#field_name' => 'link',
    );

    break;
}
return $form;
}

/**
* Implements hook_block_save().
*/
function My_Module_block_save($delta = '', $edit = array()) {
    switch($delta) {
    case 'my_module' :
        // Saving the WYSIWYG text
        variable_set('text_variable', $edit['text_body']['value']);
        variable_set('link_variable', $edit['link']['value']);

        break;
    }
}

```

# Answer
> 3 votes
I get success with this. It needs to be improved though, especially the '#language' bit. What I found to be important was to wrap the link field in a container and set '#tree' to true to group it under its key. And the link field is a multi-value field with a link title and url, so you have to take care of that.

```
function MYMODULE_block_configure($delta='') {
  $form = array();

  switch($delta) {
    case 'my_module' :
      // Text field form element
      $form['text_body'] = array(
        '#type' => 'text_format',
        '#title' => t('Enter your text here in WYSIWYG format'),
        '#default_value' => variable_get('text_variable', ''),
      );

      //link field
      $form['link_container'] = array(
        '#type' => 'container',
        '#attributes' => array('class' => array('some-class')),
        '#tree' => TRUE,
      );
      $form['link_container']['link'] = array(
        '#type' => 'link_field',
        '#field_name' => 'link_field',
        '#language' => 'und', // how to fix this??
        '#field_parents' => array(),
        '#delta' => 0,
        '#default_value' => array(
          'title' => variable_get('link_title', ''),
          'url' => variable_get('link_url', ''),
        ),
      );
      break;
  }
  return $form;
}

/**
 * Implements hook_block_save().
 */
function MYMODULE_block_save($delta = '', $edit = array()) {
  switch($delta) {
    case 'my_module' :
      // Saving the WYSIWYG text
      variable_set('text_variable', $edit['text_body']['value']);
      variable_set('link_title', $edit['link_container']['link']['title']);
      variable_set('link_url', $edit['link_container']['link']['url']);
      break;
  }
}

```

# Answer
> 0 votes
You need to add format in your custom form field as 'format' =\> 'filter\_html' or full\_html So form look like this way

```
$form['text_body'] = array(
        '#type' => 'text_format',
        '#title' => t('Enter your text here in WYSIWYG format'),
        '#default_value' => variable_get('text_variable', ''),
        'format' => 'filter_html'
     );

```

Also please check `<a>` tags are allowed in text format or not on path `'admin/config/content/wysiwyg/profile/filtered_html/edit'` and `'admin/config/content/formats/filtered_html'`

Hope it will help

---
Tags: forms, blocks
---


title: Using Drush to upgrade Drupal

text:
# Question
Title: Using Drush to upgrade Drupal
I'm trying to determine if I can migrate a site from 6 to 7 with Drush 7. I get this, "Error: Call to undefined function drush\_sql\_empty\_db()", and I did some searching and this function does not seem to exist in Drush 7. On the drush\_sup page it says to use Drush 6 or later, which would insinuate that Drush 7 is compatible. Any insight would be appreciated, I'm not in the mood to downgrade my Drush installation.

Thanks!

# Answer
> 2 votes
The function `drush_sql_empty_db()` has been removed in Drush 7. You have two choices:

1. Downgrade to Drush 6 (it is possible to install Drush 6 at a different location, and alias 'drush6' to point to the older version).
2. Fix the site upgrade command.

The equivalent function to `drush_sql_empty_db()` in Drush 7 is:

```
$sql = drush_sql_get_class();
$sql->drop_or_create();

```

There may be other issues with Drush site-upgrade and Drush 7; I have not tried it in a while.

---
Tags: 7, drush
---


# Question
Title: Is there any hook to multiple total price only in payment method
Let think you want show 10000 USD in your site with 10 K$, I did it with `hook_commerce_currency_info_alter` and work correctly, ( I enter price in scale Thoundans, this mean when my product price is 20000, I enter 20 in price field ),everything in view is fine but my problem is in payment gateways, I want when user go to payment gateways multiple total price to 1000.

Is there any hook or clean to I achieve it in my module?

Or another way is achieve this job only in display, in all displays division to 1000 ( price /1000) and when go to payment gateway use origin price.

# Answer
> 1 votes
Personally I would rather use `hook_commerce_price_field_formatter_prepare_view`.

> This hook is used by modules like the Product Pricing module that implement ways to alter prices prior to display.

That way you could keep your prices as regular dollars internally, and only display them as kilodollars for your customers. Regular storage will make it easier to interact with gateways.

Other way, although I'm not sure about it's specific implementation, would be to define second currency. You can have a shop that sells in Euro and USD, and internally re-calculates prices to meet client's payment method, right? Maybe you could define kilodollars just he same way, with exchange ratio 1000:1 to regular dollars?

---
Tags: commerce, payment-gateways
---


# Question
Title: How can I create newsletter template by Simplenews
I have Drupal v7 and installed the Simplenews module, but now when I send a newsletter, I need to edit the HTML format.

Where can I edit this template?

# Answer
> 1 votes
from this tutorial website I found after a quick google search: http://www.wdtutorials.com/2012/07/06/drupal-7-how-create-newsletters-simplenews#.VCEqY\_l\_uVM

4. Using templates First select the theme you like to use to render the emails in

/#overlay=admin/config/system/mailsystem

There are 4 template files you can override in sites/all/modules/simplenews/theme:

* simplenews-block.tpl.php
* simplenews-multi-block.tpl.php
* simplenews-newsletter-body.tpl.php
* simplenews-newsletter-footer.tpl.php

Just copy them to your theme templates folder (like themes/bartik/templates) and edit them.

# Answer
> 1 votes
Once you've downloaded and installed the Simplenews module, your best bet is to also download and install the Mimemail module, which will allow email configuration to be set to use HTML rather than plain text.

Once Mimemail is installed, in its directory you should find a \*.tpl.php file - this is the template you'll need to copy and drop into your theme among the other template files.

Edit that copy in order to change the HTML output of your newsletter email.

---
Tags: 7, emails
---