# Question
Title: How to remove the webform title field on add/edit form?
I am using bartik responsive theme. I made a sub theme of the theme. I enabled the sub theme as the default theme. I have given access to anonymous users to add webform content at xxx.com/node/add/webform. Users see the title field as required. I like to remove the title field of web form so users dont need to enter the title.

I found this link but I could not follow it all the way:

link.

* "You need to have both node.tpl.php and node-webform.tpl.php in your theme directory for this to work. Also make sure you clear your Drupal caches after copying the files in."

I went to theme directory(theme/xx/templates) and I see bartik, engines, garland, stark, seven. I dont see my sub theme and bartik responsive there. What would be my theme directory in my case?

I simply went to theme/bartik/template\> copied node.tpl.php to node-webform.tpl.php and then added

```
<?php if ($page == 0): ?>
  <h2><a href="<?php print $node_url ?>" title="<?php print $title ?>"><?php print $title ?></a></h2>
<?php endif; ?>

```

I still see the web form title field for public users at xxx.com/node/add/webform.

Do you know how I can remove the title field for web form module?

# Answer
> 2 votes
If you don't mind installing another module:

1. Install Automatic Nodetitles
2. Go to admin/structure/types/manage/webform/auto\_label
3. Select a default title and check "Automatically generate the label and hide the label field"
4. Profit!

# Answer
> 2 votes
I know this has been answered but I wanted to also offer a "DIY" alternative (as opposed to installing a module):

Implement `hook_form_alter` in your theme's *template.php* file:

```
function mytheme_form_alter( &$form, &$form_state,$form_id ){
  if ($form_id == 'webform_form_id') {
    // Prevent access to this field.
    $form['submitted']['form_component']['#access'] = FALSE;
  }
}

```

You will likely also need to set a default value on the field since it is required.

Source: Programmatically modifying a webform with hook\_form\_alter()

---
Tags: webforms
---


# Question
Title: How can I change tag separator from "," to "+"?
I want to change tag separator in a Term reference field of my content type (using Autocomplete term widget (tagging)) from "," to "+" or maybe something else (in Drupal 7) because this field needs to be filled in Persian.
What shoud I do ?
thanks.

# Answer
> 1 votes
Ideal answer of my question according to this issue is: In drupal/include/common.inc file, change the line `$regexp = '%(?:^|,\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",]*))%x';` to `$regexp = '%(?:^|,|،|\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",|،|]*))%xu';`.

Now both English and Persian comma is available for separator, and I will not worry about changing keyboard language or not!

# Answer
> 1 votes
you can use a hook\_form\_FORM\_ID\_alter. I used this validation to make sure users use commas instead of spaces:

```
function MYMODUDLE_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
 $form['#validate'][] = 'custom_form_validate';
}

function custom_form_validate($form, &$form_state) {
  $tags = $form_state['values']['field_MYNAME_tags']['und'];
  foreach ($tags as $tag) {
    if ((strlen($tag['name']) > 15) || (substr_count($tag['name'], ' ') > 1)) {
      form_set_error('field_MYNAME_tags', 'Please enter tags separated by commas');
    }
  }
}

```

# Answer
> 0 votes
Two notes for this regex fixed: At first you should change common.inc file unicode to utf-8; Then remember that when you upgrade your drupal core, you sholud redo this change in common.inc file again.

# Answer
> 0 votes
Your ultimate solution is `autocomplete deluxe` module. You can get from its project page

---
Tags: 7, meta-tags
---


# Question
Title: Creating custom button that gets a certain views block on the database
Is there a way to create a custom button that gets a certain views block on the database upon click?

I want to write a custom function button that upon click, connects to the database, retrieve a certain view block, and displays it in a .tpl page.

Thanks.

# Answer
> 0 votes
All you need to use modal form which uses ctool suites. Install exapmple and dependant module. Try create link or button just same as ajax form.

---
Tags: views, 7, database
---


# Question
Title: After logging off, user is able to see the workbench page by pressing back button of the browser
I am using workbench module to show the entry made by some particular user with some role when user is logged in he redirect to my workbench page and as the user log out it redirect to home page and after pressing back button it redirects to my workbench page

# Answer
Used this in custom module and it works

```
<?php
/**
 *Implements hook_init().
 */
function MY_MODULE_init() {
  drupal_add_http_header('Cache-Control', 'no-cache, no-store, max-age=0, must-revalidate, post-check=0, pre-check=0');
}

```
> 1 votes

---
Tags: users
---


# Question
Title: Views - Exposed Filter for 2 Field Collections with Same Fields
I have a content type with **2 Field Collections**(both set for unlimited values), they are Author and Editor. Both field collections are using the **same fields(first\_name and last\_name)**.

In a Views that I created has both field collections displayed. And I would like to exposed the First and Last Name, but they are not searchable without a relationship. Meaning I have to have 2 First Name and 2 Last Name filters exposed with different relationships.

***How to make 1 first name filter exposed and searchable for both Author and Editor?***

*PS: I have done many other searchable Views page, but this is different(2 field collections with same fields).*

# Answer
I agree with everything @Aaron said in his answer, however, if you don't want to restructure your view, you can search both fields with an exposed `Global:Combine Fields Filter`.

You'll need to have both fields listed in the `Fields` section (you can mark them as `Exclude from Display` if you want). Also, if you remove one of those fields while the filter is still in place, your view will throw an error.

Note: Remember, if you want to use `Global:Combine Fields Filter` for taxonomy terms, referenced nodes or field collections, you need to include a relationship to that entity and then add the search field to the field list.

Reference: How to filter by two fields using a single exposed filter in Views?
> 2 votes

# Answer
You need to make the base table for your View the Field Collection table rather than the Node (content) table. You'll need to add a filter to only show the type(s) of Field Collections you wish to query.

Now you'll be querying *all* Field Collections of the selected type(s), regardless of whether they're considered authors or editors. Simply add exposed filters to query on the first\_name and last\_name fields.

The real question is: what do you want actually displayed? If you only want data attached to the Field Collections displayed then that's easy enough. If you want to pull data from the host nodes beyond merely the NID then you're going to end up with 2 separate relationships to the nodes (one for each field) and you're probably not going to be able to get the UI you want out of that.

A much easier approach to all of this would be to put all of the "people" related to a node in a single Field Collection field and differentiate between Author and Editor by way of an additional "type" field in the Field Collection. You could then construct very straightforward views to query across all types of related people.
> 2 votes

# Answer
You could add a bit of javascript to maintain the 2nd set of filter fields in sync with the 1st. Then with some CSS you can hide the 2nd set of filter fields so the user doesn't see them.

The javascript would be something like the following:

```
var e = jQuery('#first-field-id');
e.on('keyup', function() { v = e.val(); jQuery('#second-field-id').val(v); }

```
> 0 votes

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


# Question
Title: How to set an alias to a fields on a db_select?
Like it said on the title, as we use alias to fields with a static query, i want to do same thing with a dynamic query

example :

with static select : `$sql = db_query ("SELECT my_super_long_field as mslf FROM {super_long_table} as slt")`

How to perform same with a db\_select query please ?

```
$sql = db_select ('super_long_table','slt')
->fields('slt',array('mys_super_long_field', 'here i want alias for long fields')

```

Thank you

# Answer
Use `addField()`. Here's an example:

```
$query = db_select('super_long_table', 'slt');
$query->addField('slt', 'mys_super_long_field', 'mslf');

```

Arguments passed to `addField()` are:

* Table alias
* Field - your long field name will be here
* Alias - your short field alias will be here

Read more about it here.
> 22 votes

---
Tags: entities, database
---


# Question
Title: How can I validate that a date is available before prompting the user to complete the rest of a webform?
I have a webform that contains a date field. I need to run some code that checks to make sure the date is not already in use (i.e. that no one else has submitted a webform with that particular date). I already have the webform validation module installed, and I know I could use that (create a custom module with custom validators), but the validations don't run until the form is submitted. Because there's a required file upload, I'd rather be able to allow the user to check if the date is available before doing the upload.

Is this possible? How would I go about it?

# Answer
> 1 votes
You have to use AJAX to check if the date is available.

In your form add a button to check for the date, for example:

```
  $form['submit-check'] = array(
    '#type' => 'submit',
    '#value' => '('Check date'),
    '#ajax' => array(
      'callback' => 'mymodule_check_date_callback',
      'wrapper' => 'datecheck-result-wrp',
    ),
  );

```

When user clicks on the button, an AJAX call is made. inside the AJAX callback you can check the date availability and return the result in the callback fucntion (mymodule\_check\_date\_callback() in the above example).

AJAX forms are beyond a simple answer, you'll have to check the documentation. I recoomend the Drupal 7 AJAX Forms documentation, the Example for Developers module that includes AJAX form examples and the Form API Internal Workflow Illustration

# Answer
> 0 votes
You could look at doing it through the Clientside Validation module, which also works with Webform/Webform validation. Since this module's validation is client-side, you can give feedback sooner rather than later. Please note that I don't know off the top of my head whether it supports out-of-the-box the specific date-checking functionality you are looking for.

# Answer
> 0 votes
A possible approach might be to use the Availability Calendars module, and then take advantage of the Webform integration of this module (from its project page):

> Kick off booking process for customers (booking formlet sub-module):
>
> * Select start and end date in the calendar itself and click "book now".
> * Prefilled start and end date based on e.g. an earlier availability search.
> * Integrates with webform for further booking details.

---
Tags: 7, webforms, forms, bookings
---


# Question
Title: Emails not being sent from Acquia dev desktop2, win7
I have a Acquia DevDesktop2 set up on my development machine (win7). I'm testing a webform submission and I'm running into an issue where I get messages that the emails are sent, but nothing reaches the inboxes. I have I'm trying to email them to regular Gmail accounts. The vanilla install on my live site sends the emails without a problem, but I don't want to code on the live codebase.

I've seen that a lot of people have this issue, but there's no good documentation that I've stumbled across on how to set up the xmail server, or how to configure it after the fact. The acquia docs all say it comes cooked in, but I'm not sure why this doesn't work for me. Any references to how to trouble shoot this would be appreciated.

So any advice would be appreciated

# Answer
Had the same problem and switched from XMail to Papercut recently:

> Papercut is a simplified SMTP server designed to only receive messages (not to send them on) with a GUI on top of it allowing you to see the messages it receives. It doesn't enforce any restrictions on addresses, it just takes the message and allows you see it.

So, turn off the XMail service and start Papercut. When a mail is sent in Drupal, Papercut acts as the (local) SMTP server and allows you to see the message.
> 3 votes

# Answer
Many (most?) ISPs will block email sent via port 25. See Comcast's info on the subject: http://customer.xfinity.com/help-and-support/internet/email-port-25-no-longer-supported/
> 0 votes

---
Tags: emails, acquia-dev-desktop
---


# Question
Title: Styling different fields before/while rendering it using drupal_render
I developed a custom module, in which I display tabs of different nodes. I render each nodes using the below piece of code,

```
$node = node_load($myNodeId);
$view = node_view($node, 'full');
$rendered = drupal_render($view);
print_r($rendered);

```

Is there a way in which I can access and style the individual elements in the `$node`, so that my `$rendered` contains the HTML that has the fields styled as per my wish.

Also a greedy thought, does drupal allow a call back function to be registered while rendering fields? so that my function takes care of rendering my `fields` of interest.

# Answer
Yes, assuming I understand correctly that you would like the nodes presented in these tabs to be styled differently to nodes presented normally on the site then I would recommend the first thing you do is set up a separate "view mode" (ie. like "Full content" or "teaser") for this purpose. You can set set up new view mode using hook\_entity\_info\_alter(), Entity view modes or Display Suite. For more information see this tutorial.

Once you have your new view mode in place, you should be able to replace the word "full" in your snippet with the machine name of the view mode. Then you will be able to do some themeing just by changing the formatter settings for your fields in your node type's display settings.

Their are many options for further overriding the themeing of the fields, you could for instance add the following code:

```
/**
 * Implements hook_preprocess_field().
 */
function MYTHEME_preprocess_field(&$vars) {
  $vars['theme_hook_suggestions'][] = 'field__' . $vars['element']['#field_name'] . '__' . $vars['element']['#bundle'] . '__' . $vars['element']['#view_mode'];
}

```

...to your theme. This will allow you to create a theme function called something like MYTHEME\_field\__FIELDNAME\__NODETYPE\__VIEWMODE() (replace the uppercase words with whatever's relevant in your case). This will override the funcion theme\_field() and you will be able to customise as much as you like.
> 0 votes

---
Tags: nodes, theming
---


# Question
Title: How to display multiple fields from a taxonomy term on a node (and control the html)
I have a content type (product) with a term reference field (colour).

When I create a new product and select a colour I would like the display of that node to render the taxonomy items term name and an image that I've attached to each term + control the html markup.

Via the Display Suite module I've managed to render the term's title and colour on the node using "Rendered taxonomy term" format on the field (screenshot below), however I want more control in how the title and image are outputted in the html markup. This is halfway there.

\[!\[enter image description here\]\[2\]\]\[2\]

The title and image appear right after each other in the markup (as it is correctly rendering the taxononmy term) but to achieve the layout the designer wants I need to be able to render the title and image individually (essentially separate fields "taxonomy title" and "taxonomy image" on my "Product" node's display, instead of just the single "Rendered taxonomy term" that I currently have configured.

Any help would be greatly appreciated.

**Edit**:

"Product" and "Colour" were just an example. In reality my site has a content type called a "lift" and it has a term reference field linking to a "location" vocab.

So if I add a "lift" and say the location is "Sydney" then when viewing that node I want to be able to pull the "Sydney" term's title and image..but as explained I need greater control over the positioning of the markup (specifically in relation to the "lift" nodes other fields)

Example of what I want the node to look like:

# Answer
Sounds like this this could be achieved with Inline Entity Display.

> **Overview**
> Make available the fields and text properties from referenced entities into the parent entity template and the manage fields display overview.

This should allow you to move individual fields from your referenced taxonomy terms aroung independently on you node's manage display setting page.
> 1 votes

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


title: Retain CKEditor styling

text:
# Question
Title: Retain CKEditor styling
I am using CKEditor for client side text editing. All works fine. I see the content styled correctly when node is saved.

The problem begins when the node content is added to a view. The text styling font boldness is retained but the spacing options like indents are overridden by the view settings.

What I wish to do is to retain the CKEditor styling for the entire view display. Is there are option in Views to achieve this?

# Answer
By default the text format filter "Limit HTML tags" will strip out "style" attributes in your HTML. You can't configure this via the admin but you can replace the filter with WYSIWYG Filter and configure that to allow specific styles whilst still filtering out dangerous HTML. The settings are found at /admin/config/content/formats/filtered\_html (or replace "filtered\_html" with the name of any other text format you need to alter). See this issue for pointer as to how best to set this up.

Please note though that if you're not sure what you are doing here then you may compromise the security of your site by setting up WYSIWYG Filter in a less than ideal way.
> 3 votes

---
Tags: views, wysiwyg
---


# Question
Title: Configuring views to display book pages as teasers, in the correct order
I am trying to display book pages as teasers, on the book cover node.

I created a Views block and display it under the parent node.

Book relationship is added, and a contextual filter as well.
Correct book pages are displayed in the block, but the problem is in the ORDER (weight).

None of the following criteria options work:

* `(Book parent) Book: Weight (asc)`
* `(Book parent) Book: Hierarchy (asc)`
* The two above combined

Book pages are always displayed in the same order, which is not the same as order of pages in that book.

What am I missing? Any ideas?

Thanks!

# Answer
> 2 votes
In the sort criteria use:

```
Book: Weight (asc)

```

If you take the weight of the parent then all childs will return the same value.

To avoid confusion a Views example to import is added at the bottom. It presumes that:

* the top parent node is NOT of the type '*book*'
* all child pages are of the type '*book*', also sub-childs.

Do not forget to:

* '*create a new book*' in *Book outline* for the top page (even if it is not of the type '*book*')
* enable the block '*View: Child page teasers*', probably in the '*content*' area.

You can try at *admin/structure/views/import* the example below on your site or with https://simplytest.me/project/views (after deploy enable the *Views UI* and *Book* module):

```
$view = new view();
$view->name = 'child_page_teasers';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Child page teasers';
$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'] = 'Child page teasers';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'node';
/* Relationship: Book: Parent */
$handler->display->display_options['relationships']['nid']['id'] = 'nid';
$handler->display->display_options['relationships']['nid']['table'] = 'book_parent';
$handler->display->display_options['relationships']['nid']['field'] = 'nid';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Book: Weight */
$handler->display->display_options['sorts']['weight']['id'] = 'weight';
$handler->display->display_options['sorts']['weight']['table'] = 'book_menu_links';
$handler->display->display_options['sorts']['weight']['field'] = 'weight';
/* Sort criterion: Content: Title */
$handler->display->display_options['sorts']['title']['id'] = 'title';
$handler->display->display_options['sorts']['title']['table'] = 'node';
$handler->display->display_options['sorts']['title']['field'] = 'title';
/* Contextual filter: Content: Nid */
$handler->display->display_options['arguments']['nid']['id'] = 'nid';
$handler->display->display_options['arguments']['nid']['table'] = 'node';
$handler->display->display_options['arguments']['nid']['field'] = 'nid';
$handler->display->display_options['arguments']['nid']['relationship'] = 'nid';
$handler->display->display_options['arguments']['nid']['default_action'] = 'default';
$handler->display->display_options['arguments']['nid']['default_argument_type'] = 'node';
$handler->display->display_options['arguments']['nid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['nid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['nid']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['nid']['specify_validation'] = TRUE;
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'book' => 'book',
);

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');

```

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


# Question
Title: How can i send a mail to specific user when workflow state is changed or changed to particular state?
I want to send a mail when workflow state will change from creation to pending,from pending to approval and from approval to published. How can i achieve this. I have tried with rules but it can't be done using same. I am using drupal 7.34 .

# Answer
This can be achieved with the help of Rules module.

> The Rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules). It's a replacement with more features for the trigger module in core and the successor of the Drupal 5 workflow-ng module. *Example use cases*
>
> Build flexible content publishing workflows changes
> Send customized mails to notify your users about important
> Create custom redirections, system messages, breadcrumbs, ...
> Build an eCommerce store using Drupal Commerce
>
> And many more...

Check Tutorial: editorial workflow with rules, which has good documentation on the how to's.
> 3 votes

---
Tags: rules, workflows
---


title: Hook menu - title arguments

text:
# Question
Title: Hook menu - title arguments
I have those menu elements declared in hook\_menu function:

```
$items['submission/%/id/%'] = array(
    'title' => 'View submission',
    'title callback' => 'fr_form_view_submission_page_title',
    'title arguments' => array(3),
    'page arguments' => array(1, 3),
    'page callback' => 'fr_form_node_object_id',
    'access arguments' => array('content access'),
    'type' => MENU_NORMAL_ITEM,
    'weight' => 100,
  );

  $items['submission/%/id/%/view'] = array(
    'title' => 'View submission',
    'title callback' => 'fr_form_view_submission_page_title',
    'title arguments' => array(3),
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );

  $items['submission/%/id/%/edit'] = array(
    'title' => 'Edit submission',
    'page arguments' => array(1, 3, 4),
    'page callback' => 'fr_form_node_object_id',
    'title callback' => 'fr_form_edit_submission_page_title',
    'title arguments' => array(3),
    'access arguments' => array('content access'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 100,
  );

```

As you can see the first menu item has a fr\_form\_view\_submission\_page\_title() function to set the title. And the function looks like this:

```
function fr_form_view_submission_page_title($id) {
  return t('View submission ID: @id', array('@id' => $id));
}

```

Second item makes the first one default.

Third menu item has a title callback function which looks like this:

```
function fr_form_edit_submission_page_title($id) {
  return t('Edit submission ID: @id', array('@id' => $id));
}

```

**When I go to page /submission/10/id/1** I get the result. Two tabs next to each other with text on it:

first tab: View submission ID: 1
second tab: Edit submission ID: 1

And the page title is: View submission ID: 1

**And if I go to the edit tab (/submission/10/id/1/edit)** I get exacly the same, so:

first tab: View submission ID: 1
second tab: Edit submission ID: 1

And the page title is: View submission ID: 1

**What I want to achive is to have tabs always signed:**

first tab: View submission

second tab: Edit submission

And the page title depending on path, so for /submission/10/id/1 I should get: View submission ID: 1

And for /submission/10/id/1/edit I should get: Edit submission ID: 1

# Answer
You can use single title callback by passing two arguments :

```
'title arguments' => array(3, 4),

```

and use same callback for both function :

```
function fr_form_view_submission_page_title($id, $type = 'view') {
  $type = ucfirst($type);
  return t('@type submission ID: @id', array('@type' => $type, '@id' => $id));
}

```
> 0 votes

---
Tags: routes, hooks
---


title: Views promoted/sticky items

text:
# Question
Title: Views promoted/sticky items
I have a view of all content, of all types, listed by date order. Paginated of course (with load more).

I want to find the latest piece of content of type X, and promote it/make it stick to the first result.

I was initially just going to use an attachment, but this comes with 2 problems.

* The item ideally won't repeat
* If it is already the first item, or in the first few results, there will be 2 right next to each other.

The item should not persist as the first item on each page, it should just be moved/re-ordered.

I feel like this should be very straight forward, but I am drawing a blank.

Any help most appreciated!

# Answer
So some credit to @paul-querol for pointing to `hook_views_post_execute()`, however the idea of using 2 views and custom code seems a bit odd to me… Views don't write the most efficient of queries, so for finding the promoted item I am using a custom function (although I have a bunch of extra things happening in there that views can't do).

Additionally, I want the "promoted" item to be treated the same as the other results, so don't want to be injecting info just befor render.

In the end it was very straight forward to push an item in, however you are getting that item.

My code:

```
/**
 * Implements hook_views_post_execute().
 */
function my_module_views_post_execute(&$view) {
  if ($view->name == 'view_name') {
    $results = $view->result;
    $promoted = '';
    $key = NULL;

    // Get promoted item.
    $target = _my_promoted_item _finding_function();

    if (!empty($target)) {
      // Loop through results.
      foreach ($results as $key => $item) {
        // Find our item of interest.
        if ($item->nid == $target['nid']) {
          $promoted = $results[$key];
          break;
        }
      }
    }

    // If we found the promoted item, and it isn't already first in the list.
    if (!empty($promoted) && ($key != 0)) {
      // Unset from current position and prepend to beginning.
      unset($results[$key]);
      array_unshift($results, $promoted);
    }

    $view->result = $results;

  }
}

```
> 0 votes

# Answer
One thing you can do is set up a "sticky" view which pulls out the node you're looking for and then store the nid of the node. You could do this using hook\_views\_post\_execute() in a custom module like so:

```
function MYMODULE_views_post_execute(&$view) {
  $nid = &drupal_static('MYMODULE_sticky_node_id');
  if(!empty($view->result)) {
    $nid = $view->result[0]->nid; // (or similar)
  }
}

```

(Replace all instances of "MYMODULE" with your module name)

Now if there is a result then it's nid should be stored in a static variable called 'MYMODULE\_sticky\_node\_id'.

Next add a contextual filter of NID to the main view, leave "When the filter value is NOT in the URL" as "Display all results for the specified field", and under the "More" fieldset, tick "Exclude".

Next implement something like hook\_views\_pre\_view():

```
function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'your_main_view_name') { // If need be add "&& $display_id == 'your_main_view_display_name'
    if ($nid = drupal_static('MYMODULE_sticky_node_id')) {
      $view->set_arguments(array($nid));
    }
  }
}

```

This will pull out the nid you saved while processing the sticky view and set it as the argument of the main view, therefore excluding it from that view.

You'll need to make sure that the sticky view is rendered before the main view for this to work.

Bear in mind that I haven't tested this exact code so it might need some tweaking to get it to work in context.
> 2 votes

# Answer
There are 3 option where you can those options can be seen:

* admin/structure/types/manage/article

* on node/123/edit

* on admin/content

in Views - add sort type: "Node: Sticky" - descending order.
> 0 votes

# Answer
If you use an attachment with the newest item, then you can skip the first item in the view by setting "Offset" to 1 in the Pager settings.

And your view should be sorted to show the newest item as first item, so this will be skipped from the views results.
> 0 votes

---
Tags: 7, views
---


# Question
Title: How do you setup shipping services that relate to a specific taxonomy term?
I have taxonomy reference field for each product. I have DVD,CD and e-Download. If user purchase the e-download related products shipping charge should be free. How to add the conditions using rules module.

# Answer
> 0 votes
Need to use Data Comparison in conditions section of rule. Where in data comparison you need set commerce-product:creator:fieldname **OPERATOR** equals and in DATA VALUE you need to select 'e-Download'. done

---
Tags: taxonomy-terms, commerce
---


# Question
Title: How to upload videos and play in Drupal 7?
I am trying to upload custom *video* files to *Drupal site* and play the video. I have custom videos which are to be uploaded to posts.

Here I am not using any *YouTube* embedded links, instead I want to upload my own videos into my posts.

I also have installed the media module and the *JWplayer* but I don't know how to configure the module to upload *videos* in my posts and play those videos.

I am a newbie to *Drupal*. Can anyone help me to configure this?

# Answer
Here is complete Community Documentation about the Media module.

There is another Drupal Video Setup Using Media and Media Youtube tutorial about using the \[Media\] and Media Youtube modules in a Drupal site.

If still you can't get it to work, then you can also check the tutorial Post YouTube Videos with Media + Media: YouTube (from Drupal's Post Installation forum).

Now choice is up to you in which you feel easy.
> 2 votes

# Answer
You need a module like Video. You can upload and also transcode videos with it. The module adds a new field type, Video, which can be used to upload and view videos. Here you can see how to install and test it out.
> 1 votes

# Answer
Finally got it working, The tutorial about "Uploading Video Files in Drupal" worked for me. Here is part of what it is about (quote from that link):

> If we want a simple approach to uploading and playing our videos inside an HTML5 player, we can use the built-in File field provided in the Drupal core to hold our uploaded video and an added module to provide a player.

Basically what this tutorial explains is this:

* Add a field of the 'File' field type to a content type.
* Use the Media Element module.

Head over to the tutorial for more details if needed.
> 0 votes

# Answer
Apart from the various modules already suggested in the other answers, I think you might also want to look at the Scald: Media Management made easy module, which is more and more considered as an alternative to the Media module.

Here is a quote about the Scald module (from its project page):

> ... a popular and flexible way to handle media in Drupal.
>
> Scald can handle images, video, audio, tweets and even Flash files. Scald works with YouTube, Vimeo, Soundcloud and other many other providers. You can see a full list on the scald provider's page, you can also read our FAQ.
>
> For end-users Scald is a great option because you can use Scald with popular editing tools such as CKEditor, and with Plupload for multiple file uploads. Scald also has a very user-friendly media library, based on Views.
>
> For developers, one of the best things about Scald is that it treats all files as full-blown fieldable entities.

And yes, it also has quite some Community Documentation.
> 0 votes

---
Tags: media, files
---


# Question
Title: Redirect beating out URL path and creating redirect loop
Currently ran a bunch of updates on our site, and we're experiencing this issue:

* Create nodea at /nodea
* Change nodea's path to /nodeb
    + a redirect will be written added to nodeb: /nodea -\> /nodeb
* Create a new new node, and call it nodea, so the URL path then becomes /nodea for it
* If you try to go to the new /nodea page, the redirect rule catches it first and sends you to /nodeb

I'm not sure what caused this, and it's a huge issue. (That example is, of course, just to show what's occurring; it's not the exact use case, but pretty close.)

Can anyone give me an idea on how to fix this? Or at least where to start looking?

# Answer
This has since been corrected with an update to the redirect module.

There's now an "enabled" field on redirects, and when a conflict occurs (e.g. a new active alias is entered when that path is already a redirect), the redirect becomes disabled.
> 0 votes

---
Tags: redirection, path-aliases
---


# Question
Title: How to make custom template for search results
I have developed a custom search module that is working perfectly. Currently I am using the existing "`search-results-tpl.php`" and "`search-result-tpl.php`" for showing search results.

But I want to make my own **custom template file** for showing results and that template file should be inside my custom module directory. In this template I will be able to style my search results however I like.

Any suggestions on this?

**Note**: I have tried many contributed modules also, but they don't satisfy my requirements, so therefor I have started a custom module. But if you have any better solution, then feel free to point me to any of them.

# Answer
By using the *theme* function I have got it working. Here is how it looks like:

```
/**
 * Implements hook_theme().
 *
 * Create custom theme and template files.
 */
function mymodule_theme() {
  $themes = array(
    'my_search_result' => array(
      'variables' => array('result' => NULL, 'module' => NULL),
      'file' => 'mymodule.pages.inc',
      'template' => 'my-search-result',
    ),
    'my_search_results' => array(
      'variables' => array('results' => NULL, 'module' => NULL),
      'file' => 'mymodule.pages.inc',
      'template' => 'my-search-results',
    ),
  );
  return $themes;
}

```
> 1 votes

# Answer
Below are some suggestions for some contributed modules (as per your **Note**), for implementing some "custom search" features, and as an alternative for the "custom template" in your question.

# Forena module

The Forena module can be used as a custom report writer, to be considered as an alternative to "custom searches".

You could take advantage of all sorts of features related to "Report Parameters". Refer to the Users in cities assigned to a state demo report for a very basic demo of such parameters.

Demo report Master Summary with drill down illustrates how you can "link" multiple reports together (also called "drill dow reports"). To experiment with it, click on any of the (green or yellow) bars in the barchart. You'll then be forwarded to another report corresponding to the bar you selected. If you'd rather want to use the links on the tabular report below it, that's an other option you could use. By the way: Forena is not just for (tabular) reports, but also for creating charts ... (using the open source library SVG Graph, which includes support for exporting charts to PDF ...).

After you'd become familiar with its FRX-language (to develop/design reports), you have the full xHTML spectrum available. To get an idea how its **Custom Queries** (SQLs) and/or **Report Specifications** look like, refer to my answer to the question "https://drupal.stackexchange.com/questions/152166/fetching-drupal-articles-tags-image-directly-from-database/154746#154746".

And don't forget you can write your custom (native) SQL queries ... with support for SQL parameters also.

Disclosure: I'm a co-maintainer of Forena,
I hope this does not violate the site's policy on self-promotion.

# DataTables module

By using the DataTables module for displaying Views results, and especially the "Search box" widget of it, you basically don't have to worry anymore about what exactly the users want to search for. Refer to my answer to the question "What are my options to visualise a views table with many fields grouped in columns?" for AbitMORE details about this (amazing I think) module.

# Forena's integration with the DataTables jQuery plugin

Forena also has a (straight forward) integration with the DataTables plugin (no need for the DataTables module). For an illustration of it, refer to these 2 demo samples:
> 1 votes

# Answer
You may copy these templates from search module folder into your custom theme folder
> 0 votes

---
Tags: theming, search
---


title: Views exposed filter for several fields

text:
# Question
Title: Views exposed filter for several fields
Have 3 content types. Apartment, hotel, motel.

Each has integer field "number of beds".

Lets say user wants to see apartments that have between 10 and 15 beds. In views for apartment i made exposed search filter adding number of beds 2 times, 1st is "greater or equal to" and 2nd is "less or equal to".

This all works fine.

Now i want to apply this filter to all content types in one view so that user after entering from 10 to 15 beds applies this search request to all content types at same time.

Solution that should work is to create 1 bed field on apartment and use that existing field on hotel and motel, but i want to have it separated so that i have control of each field in each content type separately.

I have tried Global: Combine fields filter, but it does not support "greater or equal to", "less or equal to" etc.

# Answer
Create your first view block for Apartment with the exposed filter. Create attachments for each of the other two that inherit the exposed filter. As the comments stated, as long as they used the same field this will work perfectly.
> 0 votes

---
Tags: views
---


# Question
Title: Would Drupal send to an alternative email address for reset password?
I am very new in Drupal. I have an installation of Drupal 7 with LDAP authentication and LDAP user provision, this LDAP is linked to corporate mail system too. Users have 2 mail accounts (a corporate account and an alternative account), if a user forgot his password, I need the password reset send mail to both email addresses not only to the corporate account.

# Answer
> 4 votes
You'll want to create a custom module, please see https://www.drupal.org/node/1074360

You can then implement hook\_mail\_alter().

```
/**
 * Implements hook_mail_alter().
 */
function my_module_mail_alter(&$message) {
  // Alter password reset
  if ($message['id'] == 'user_password_reset') {
    // Load the user by email address
    if ($user = user_load_by_mail($message['to'])) {
      // If you have another user field with their alternative email address, add to the $message array
      if (!empty($user->field_user_alt_mail)) {
        $message['to'] = $message['to'] . ', ' . $user->field_user_alt_mail[LANGUAGE_NONE][0]['value'];
      }
    }
  }
}

```

edit: changed 'password\_reset' to 'user\_password\_reset' as per Paul's comment.

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


# Question
Title: How to make vertical tabs display on a custom entity?
I have a custom entity in Drupal7 created using the Entity API. I am attempting to make it work with the meta tag module. I have added

```
'metatags' => TRUE

```

to hook\_entity\_info, and metatags display as a field under "manage fields" for the entity. The trouble is that the vertical tabs that usually display on every node do not show up on the entity. Thus, I have no way of changing any of the information in the meta tag field on the custom entity. How do you make the vertical tabs appear when using entity api?

# Answer
This seems to be the reverse of the question remove vertical tabs, and should have a very similar answer. In the documentation for the vertical tabs module, the first code snippet is how to enable vertical tabs on any form. The second snippet looks more appropriate, as it is how to enable tabs from your custom module that creates your custom entity.

```
<?php
$vtabs = variable_get('vertical_tabs_forms', array());

// Enable vertical tabs on a form.
$vtabs['my_form_id'] = TRUE;

// Disable vertical tabs on a form.
$vtabs['page_node_form'] = FALSE;

// Enable vertical tabs but be selective of which fieldsets are included.
$vtabs['page_node_form'] = array('menu' => FALSE);

variable_set('vertical_tabs_forms', $vtabs);
?>

```

**Edit:**

The site variables here is a huge array that is always accessible to drupal. Some of these settings can be stored in your site's settings.php file, as this variables array is present even there. However, because of the nature of the change that you desire, I think the best choice for you is to have a hook\_install in the module that defines your custom entity.

Assuming module name "your\_entity", add a file "your\_entity.install" to the module.

```
function your_entity_install() {
  // Enable vertical tabs on entity form.
  // this is supposed to be true as long as this module is enabled
  $vtabs = variable_get('vertical_tabs_forms', array());
  $vtabs['your_entity_form'] = TRUE;
  variable_set('vertical_tabs_forms', $vtabs);
}

```

Then disable and re-enable your module. These variables can be set in the form\_alter, but that would only be recommended if you needed the value to change based on other information that is not present at an earlier time.
> 2 votes

---
Tags: entities, forms
---


# Question
Title: Can i attach a views grid of images in a carousel
Hi i'm new to Drupal and this maybe kinda of advance, but how can i achieve a Drupal views of images grid format displayed in a carousel as shown in the image above

# Answer
> 1 votes
# Views Slideshow

You could use the Views Slideshow module for this. Here is a quote from its project page:

> ... can be used to create a slideshow of any content (not just images) that can appear in a View. Powered by jQuery, it is heavily customizable: you may choose slideshow settings for each View you create.
>
> **Potential uses**:
>
> * News item slideshow (such as the title, image and teaser of the last 5 news articles submitted).
> * The Last X number of X submitted (images, videos, blog entries, forum posts, comments, testimonials, etc.).
> * Rotate any image, based on any filters you can apply in views.
> * Hottest new products for any ecommerce drupal site.
> * Rotate contact links, share links, etc.
> * You could rotate entire nodes, categories, image galleries, etc. I wouldn't suggest it, but you have that power.
> * It's also a great space saver. Places where you had multiple images or multiple items such as RSS feeds or category listings can now be presented in a slideshow.
>
> The possibilities are really endless, as the more ways you can think of to categorize and add to views, the more you can rotate.

### Further enhancements

Possibly you may want to further extended this with related modules (there are dozens of modules to further enhance views) such as Views Slideshow: Galleria. Here is a quote from that module's project page:

> Integrating Galleria with Views Slideshow.
>
> Galleria is a JavaScript image gallery framework built on top of the jQuery library. The aim is to simplify the process of creating professional image galleries for the web and mobile devices.

# jCarousel

Another option is to consider the jCarousel module. Here is a quote from its project page:

> ... This module allows developers and themers to make use of the jCarousel jQuery plugin. It includes a developer API that other modules can use, as well as Views integration in the 2.0 version so that you can turn any list of content or images into a carousel.
>
> **Features**:
>
> * Built-in Views support.
> * AJAX-loading of additional items as needed.
> * Carousel pager/navigation to jump between multiple pages.
> * Circular wrapping of items.
> * API for direct usage of jCarousel without Views.

---
Tags: views, javascript
---


# Question
Title: How to blocks visible only in specific pages?
I am setting the links as a block in the left panel with the following code.

```
function notification_block($op = 'list', $delta = 0, $edit = array()) {
  if ($op == 'list') {
    $blocks[0] = array(
      'info' => t('Notification Management'),
      'weight' => 0,
      'status' => 1,
      'region' => 'left',
      'visibility' => 1,
      'pages' => 'notification'
    );

    return $blocks;
  }

  else if ($op == 'save' && $delta == 0) {
    variable_set('notification_block_items', $edit['items']);
  }
  else if ($op == 'view') {
    switch ($delta) {
      case 0:
        // Your module will need to define this function to render the block.
        $block = array(
          'subject' => t('Notification Management'),
          'content' => notification_block_conent(),
        );
        break;
    }
    return $block;
  }
}

function notification_block_content() {
     $ret = '<a href="'.$base_url.'/notification/addTemplate">Add new email template</a>';
     $ret .= '<br/><a href="'.$base_url.'/notification">Manage Email Notfication</a>';
     return $ret;
}
``

Unfortunately, this block is appearing in all the pages. I need to display this block on the notification module only. How can I achieve this?

```

# Answer
Go to the block configuration page and scroll down to **Page specific visibility settings**.

There are the following options.

> Show block on specific pages:
>
> * Show on every page except the listed pages.
> * Show on only the listed pages.
> * Show if the following PHP code returns TRUE (PHP-mode, experts only).

If you are using last option from the above options, see Display block on certain page.
> 2 votes

---
Tags: 6, blocks
---


# Question
Title: Module for floating vertical and customizable image menu
I'm looking alternative module to ShareBar (but not for social network buttons).

The features should include:

* floating image menu items/buttons (like: Menu Icons) on the side linking to pre-defined paths/URLs
* ability to add new menu elements
* visible to standard user (including anonymous), not like Quickbar which is for used for admin

Something like having Back To Top or SnapEngage floating button, but with multiple menu items grouped together which are customizable.

Which modules can provide such features? Or how this can be achieved?

---

In summary, like this:

Image source: Floating Social Share for Drupal

but beyond social buttons (so any button/menu item with any image/link can be added).

# Answer
> 2 votes
You can use **Floating block** module

**Floating Block** Module page says

> The Floating block module allows you to keep html blocks, selected using jquery selectors in a fixed position on the page as you scroll. It works in a similar way the table header fixer in Drupal Core. This means that when the user scrolls their browser selected parts of the page can stay in the users view.

# Answer
> 0 votes
Few alternative options:

See also:

---
Tags: 7, routes, media
---


title: Devel module and the WSOD on login

text:
# Question
Title: Devel module and the WSOD on login
I have a lot of trouble with the WSOD and have looked around quite few posts; like WSOD with Devel module and How to see the error messages when I get the white screen of death? as well as https://www.drupal.org/node/1692262

After reading the posts the best thing to do was to uninstall the the devel module, once i did that the WSOD is gone, but what if you need the devel module?

I'm struggling to get the errors up and work out where i have gone wrong. Doesn't Krumo need devel?

# Answer
This is not a complete solution, but can help.

If you want to look at something but dont want to spend the time investigating your site's aversion to the devel module, then drupal core's watchdog call can be helpful. Also, I am assuming you have dblog or weblog module enabled to catch the error messages. To make it more readable, like a krumo output, I often add my Explain function to a custom module somewhere. Then in the place where I would have used `krumo($target);` I use `watchdog('bug_hunt', explain($target, 5, 'target') );` and go to /admin/reports/dblog and filter for bug\_hunt. That 5 is arbitrary in this case; 4 steps into something can get you `target->field_one[und][0][value] = Content`.Since I have that function terminating the recursion with html line breaks, it reads well in the log pages.

I started doing this when I was trying to expound on processes that did not have a page for krumo to inject into (maestro module workflows, etc). Since then, it has been a reliable fall-back method for me.

The better solution would be to spend the time finding why devel crashes your site, as it might be an issue that will appear again later on.
> 2 votes

---
Tags: debugging, wsod
---


# Question
Title: How to check if a url exists on my own website
I need to check if a url exists in a **module** that I am creating. How should I go about doing this? I tried to use a **@get\_headers()** function with php, but sadly that doesn't work. I am wondering if there is a built in drupal function that I can use?

# Answer
This is what fixed it:

```
if (!drupal_valid_path($path)) {
  // Not a system URL.
  if (!drupal_lookup_path('source', $path))  {
    // Not a path alias.
    // $path does not exist.
  }
}

```

Where `$path` is a relative url.

Source
> 4 votes

---
Tags: 7, uri
---


title: Custom Editor for a node based on type

text:
# Question
Title: Custom Editor for a node based on type
Using Drupal 7, I'm working on a module and want to have it so when the module is installed it will set a new node type called "project" When a user is adding/editing a $note-\>type="project" I want to bring up a custom editor for my module that is for that node type. I have been looking for tutorials for nodes and editors for nodes but I wasn't able to find any good examples of making a custom node type and making and assigning a custom editor for a node type.

I also don't know what hooks I need to use to target the node editor. As of right now I'm following the steps from the following tutorial. http://www.sitepoint.com/creating-a-new-drupal-node-type/

# Answer
> 0 votes
The WYSIWYG module allows embedding any supported WYSIWYG editor to a field via a `hook_form_alter()`/`hook_form_FORM_ID_alter()` invocation. Here's a link to its documentation page. You can alter your custom node type form by altering the its body field `#type` & `#format` elements.

Note: To do this it also requires:

1. The WYSIWYG libraries pre-installed to the **sites/all/libraries** directory.
2. A pre-existing WYSIWYG profile created.

As such, you'll need to have add a `wysiwyg` dependency in your module's .info file and some how do the above work in #1/#2 inside your `hook_install` invocation.

---
Tags: nodes
---


title: Block View for specific form

text:
# Question
Title: Block View for specific form
I have two forms on my site. I want to create a Block View for only one of them but as I choose "Webform: Webform form body (Form)" for the Fields in the View, I get both forms showing. I'm trying to only show one of the forms.

I tried adding a css class to a field and then using that as a means of filtering out the fields of just the one form but either I did it wrong or that isn't the way to complete the task.

How can I limit a Block View to show a specific Webform?

# Answer
> 2 votes
In your view, add a filter criteria of 'Content: Nid', then specify the node id of the webform in question. To locate the node id you can edit the webform and look at the url. The url will be /node/xxx/edit where xxx is the nid.

---
Tags: views
---


title: Views display 0 items

text:
# Question
Title: Views display 0 items
I got to be missing something obvious. I want to display in my view 0 items until they use the Filter Criteria exposed filter with a search parameter.

Under Pager Use Pager I can't see how to display 0 items?

Is it possible?

# Answer
There is a setting for this.

Advanced \> Exposed form \> "Basic"

If the view is still on default, it will be set to Basic, click basic and change it to "Input Required"
> 5 votes

---
Tags: 7, views
---


# Question
Title: drupal site crash and went to maintenance mode
While creating a huge volume of pages in drupal website, our live site went down after 5 hours. We investigated logs on Apache, PHP and MySQL thoroughly but couldn't identify any specific cause or error for the site crash.

# Answer
> 0 votes
It's quite possible that your server crashed (ran out of memory). You can start by restarting MySQL, otherwise just restart the entire server to get things going again.

---
Tags: database, maintenance-mode
---


# Question
Title: Custom tpl.php for custom content types rendered through another tpl.php
I have a custom module which displays multiple content types in tabs. My module uses a custom `tpl.php` which renders the tabs and the contents(of multiple types).

The challenge is to have custom *tpl.php* for each content types I render. The theme file *node--TYPE.tpl.php* works when I directly hit a node of a *TYPE*. But it is not used when I rendered the node content using the below code,

```
    $node = node_load($aTab['nid']);
    $view = node_view($node, 'full');
    $rendered = drupal_render($view);
    print_r($rendered);

```

What is the suggestion to have my module to render each content types using their custom theme file.

# Answer
You shouldn't be printing it with print\_r(), just try print.

```
$node = node_load($aTab['nid']);
$view = node_view($node, 'full');
print drupal_render($view);

```
> 1 votes

---
Tags: theming, nodes
---


# Question
Title: Update Drupal Core from 6.26 to 6.36 using update.php gave no errors, but Drupal still reports that it is on version 6.26
I've followed all of the steps on https://www.drupal.org/upgrade/running-update-php to upgrade my Drupal Core.

I put the site into maintenance mode. I disabled all modules except the core required modules. I used FTP to delete all of the folders associated with the upgrade. I copied the entire directory of contents except .htaccess and robots.txt and part of my sites directory I navigated to subsite.site.com/update.php I ran the update The update indicated that it performed 0 / 0 tasks and said it completed I navigated to the administration page I cleared cache I reenabled modules I checked the current upgrade status

Result: It still read that I was on 6.26 Expected result: It reads that I'm on 6.36

Quite confused about this. I have successfully upgraded my modules using the update.php script with no problems. Any thoughts?

Thanks!

# Answer
> -1 votes
Have you manually brought your codebase up to version 6.36 by overlaying 6.24 with 6.36?

The update.php will only update the database to the latest version of Drupal installed. So if it's still 6.24, it makes sense to me that it is applying 0 of 0.

https://www.drupal.org/node/1223018

---
Tags: 6, updating
---


# Question
Title: Which hook to use on initial creation of a node?
I would like to execute a script once a new piece of content of a specific type has been created, but not updated. Which hook would I use for this?

I basically want to execute a script that will node\_load the entity reference field and then email a bunch of users from that referenced node.

# Answer
> 5 votes
You're probably looking for `hook_node_insert` where `$node` should contain your node reference field.

---
Tags: 7, hooks
---


# Question
Title: How to prevent anonymous users not viewing any webform content
I have created a web form contact us page. Anonymous users can see the contact us page at xxx.com/node/add/webform. After they submit the webform, they can see the content of the form at xxx.com/node/x.

In People \> Permission page, I have given two permissions to anonymous users:

1. webform: create new content
2. View published content

If I uncheck number 2, anonymous users can not view anything. I also went to structure \> content types \> webform and I did not see anything there to set the permission.I also searched google and I could not find the specific answer.

Do you know how I can prevent anonymous users not viewing the web form published content except adding the webform content?

# Answer
You'll have to look at the content\_access module which will allow you to configure default access control on a per node type or per node basis.

**Content Access:**

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

---
Tags: webforms
---


# Question
Title: Get a single date value from a date field on a node with entity_metadata_wrapper()
I want to retrieve a date value from a date field attached to a node with entity\_metadata\_wrapper.

So far:

```
$node_wrapper->field_tournament_date->value();

```

Provides an array. Not many other methods work. So, I have to do:

```
$date = $node_wrapper->field_tournament_date->value();
$start_date = format_date($date['value'], 'short');

```

Is there a cleaner way of getting the value of a date field without breaking it up like that?

# Answer
In these situations with meta\_data\_wrapper you could put the array-value before the value function, like this:

```
$date = $node_wrapper->field_tournament_date->value->value();

```
> 5 votes

# Answer
If your server's running PHP 5.4 you could use:

```
$start_date = format_date($node_wrapper->field_tournament_date->value()['value'], 'short');

```

since function array dereferencing has been added.

Other than that I don't think there's a way of reducing your code to be honest. If you're manipulating date fields a lot you might consider creating a small helper function, something like

```
function MYMODULE_format_date_field($value, $column = 'value', $format = 'short') {
  return format_date($value[$column], $format);
}
$start_date = MYMODULE_format_date_field($node_wrapper->field_tournament_date->value());

```

or similar. It's not the best but it might save a bit of time.
> 2 votes

# Answer
I use the following approach:

```
foreach ($node_wrapper->field_tournament_date->getIterator() as $date_wrapper) {
  // dpm($date_wrapper->getPropertyInfo() // to see what properties you have
  $start_date = $date_wrapper->value->value();
  $end_date = $date_wrapper->value2->value();
  $duration = $date_wrapper->duration->value();
}

```
> 0 votes

# Answer
I used the following:

```
$entity->field_date->get( 0 )->value->value( );

```

The call to get is needed because date fields are lists.
> 0 votes

---
Tags: 7, datetime, entities
---


# Question
Title: Drilling down into an Entity Reference Field in Rules Actions
I have the following setup where I have 2 content types called BRIEFS and IDEAS. On BRIEFS, I have a list of users selected in a field called **brief\_recipients** which is a user reference field.

**IDEAS** has a entity reference field (associated\_brief) that references a **BRIEF**.

Currently when I create an IDEA, it will email the **author** of the referenced BRIEF. This works using the following rules setup:

Now I'm trying to add in a **LOOP** to access the entityfield associated\_brief's \> brief\_recipients field and email them too.

But the problem seems to be that Rules cannot drill down into an entityfield's fields as I can only get to body and author only as seen here:

Now the question is how do you drill down into an entity field's fields? Or is there another suggested way of doing this?

Which hook would I need to tap into if I had to write this custom?

# Answer
> 4 votes
In my scattered experience with rules, a limitation on what data you can access is usually a safeguard because the data has not been confirmed to exist yet. In the Rules conditions, create "entity has field" condition twice.

1) Rule Conditions \> Entity has field Data selector: node Field: field-associated-brief

This is your entity reference field, and gives Rules the comfort of knowing the reference field is usable. Once you have the above conditions, rules will load up the referenced fields from your node

2) Rule Conditions \> Entity has field Data selector: node:field-associated-brief Field: field-breif-recipients

3) Now the action is able to use the field confirmed in the conditions

Even if you do not think the conditions should be required, it is good practice to confirm you have the data before you try to use it. Here is another person who had a very similar issue

---
Tags: rules, entities, emails, database
---


title: [function.unserialize]: Error at offset

text:
# Question
Title: [function.unserialize]: Error at offset
I initially came across this error while I migrated my site from local server to live server.

```
Notice: unserialize() [function.unserialize]: Error at offset 83 of 108 bytes in variable_initialize() (line 935 of /home/ebemorgi/kog.church/includes/bootstrap.inc).

```

I followed #9 from this drupal post , then I found out that the variable causing the issue was authorize\_filetransfer\_connection\_settings\_ftp.

I deleted the above variable but that hung up my whole website.

Then I deleted the content in the variable table and re-populated it. Initially the error didn't popup but when I tried installing a new module at the live server the error popped up with an new offset value. Again the villain is authorize\_filetransfer\_connection\_settings\_ftp. The error which I am now receiving is :

```
Notice: unserialize() [function.unserialize]: Error at offset 32 of 121 bytes in variable_initialize() (line 935 of /home/ebemorgi/kog.church/includes/bootstrap.inc).

```

I have made sure that I have updated the ftp details in my mysql dump file before importing it to live DB.

I'm not sure if this issue is related to Core, but I don't honestly know under which product to list it.

Any help is appreciated.

# Answer
> 3 votes
It looks as though you have invalid serialized data for that `authorize_filetransfer_connection_settings_ftp` variable.

If saving to the db manually, make sure you have serialized the data prior to db storage.

Some ways to set the variable include

`variable_set('authorize_filetransfer_connection_settings_ftp', $value);`

and

`drush vset authorize_filetransfer_connection_settings_ftp 'value'`

The former is a bit easier if setting an array value, otherwise you can do something like this with Drush:

`drush php-eval 'variable_set("authorize_filetransfer_connection_settings_ftp",array("key1" => "value1", "key2" => "value2"));'`

---
Tags: debugging
---


# Question
Title: How to implement bulk pricing/discounts with Drupal Commerce?
I've been trying to find a way using Drupal Commerce to be able to give discounts on individual item prices based on quantity. For instance:

1-9 units of product A: $1.99 per unit

10-19 units of product A: $1.75 per unit

1-19 units of product B: $2.99 per unit

20-39 units of product B: $2.60 per unit

and so on and so forth. However, I haven't been able to find any documentation or modules to do this. Is there any way to do this with Rules, or any modules?

# Answer
I figured it out. The Price Table module should be used in this case. I also used the tutorial that can be found here.
> 1 votes

# Answer
Maybe you should use the Commerce Discount module. Quote from its community documentation:

> The Discount UI (available under Admin → Commerce → Store → Discounts) allows creating and editing discounts. Each discount consists of two related entities: Commerce Discount and Commerce Discount Offer. The Discount allows you to choose what type of entity this discount this will apply to i.e. "Order Discount" or "Product Discount" (line item). The Commerce Discount Offer denotes the result the discount produces. The module provides 4 discount offers out of the box.
> 1 votes

---
Tags: 7, commerce, rules
---


# Question
Title: How can I flag (follow) user by REST API using service resources?
I am using flag module to have the following user function. So that the followers will be able to read the blog of the users that they followed. Now I want to provide api for mobile application, when a userA go to profile of userB, they can follow userB by follow button. Is there any way to return an api by POST method in RESTfull to do like that?

# Answer
> 3 votes
Try the following

**Flag**

```
URL: http://example.com/apiauthd/flag/flag

Method: POST

Parameters:-
    flag_name: like
    action: flag
    uid: { uid of the logged in user}
    entity_id: { uid of the other user to be flagged}

```

**Unflag**

```
URL: http://example.com/apiauthd/flag/flag

Method: POST

Parameters:-
    flag_name: like
    action: unflag
    uid: { uid of the logged in user}
    entity_id: { uid of the other user to be unflagged}

```

---
Tags: services, flags, 8
---


# Question
Title: Statistics module doesn't update when getting a node
I've created a custom module, which should regarding some other posts help updating the daycount. But it just doesn't get updated.

```
function services_statistics_improved_services_request_postprocess_alter($controller, $args, &$result) {
      // Increment hit count for node view api requests.
      if($controller['callback'] == '_node_resource_retrieve') {
        $nid = $result->nid; // May need to confirm this is the node id.
        dpm($controller);
        // See statistics_exit()
        if (variable_get('statistics_count_content_views', 0)) {
          // A node has been requested, so update the node's counters.
          db_merge('node_counter')->key(array('nid' => $nid))->fields(array(
            'daycount' => 1,
            'totalcount' => 1,
            'weekcount' => 1,
            'monthcount' => 1,
            'yearcount' => 1,
            'timestamp' => REQUEST_TIME,
          ))
          ->expression('daycount', 'daycount + 1')
          ->expression('totalcount', 'totalcount + 1')
          ->expression('weekcount', 'weekcount + 1')
          ->expression('monthcount', 'monthcount + 1')
          ->expression('yearcount', 'yearcount + 1')
          ->execute();
        }
      }
    }

```

Anyone able to help me out here?

# Answer
The query to update the node\_counter table may need tuning.

e.g:

```
if (variable_get('statistics_count_content_views', 0)) {
  // A node has been served, so update the node counters.
  db_merge('node_counter')
    ->key(array('nid' => $nid))
    ->fields(array(
      'daycount' => 1,
      'totalcount' => 1,
      'timestamp' => REQUEST_TIME,
    ))
    ->expression('daycount', 'daycount + 1')
    ->expression('totalcount', 'totalcount + 1')
    ->execute();
}

```

The other fields, such as 'yearcount' etc.. aren't in the node\_counter, at least not by default which may be causing a PDOException there.
> 0 votes

---
Tags: nodes
---


title: How to call view block on click?

text:
# Question
Title: How to call view block on click?
I have a page/node that contains 15 view blocks, each view block has many fields and all of this causes the page to load really slow.

How do I load the view block only when I need it? for example I would click a button/div (venue) then the view block venue will load instead of invoking all of the view blocks on the template and letting it load all at once.

UPDATE: I tried using ajax but it's not working even though I turned the ajax on the view block.

This the code I used:

JS:

```
$(document).ready(function(){
$("#getvenue").click(function(){
    $.ajax(
    Drupal.settings.basePath + 'views/ajax',
    {

    view_name: 'custom_package_form',view_display_id: 'block_56'
    },

    function(response)
    {
        if (response[1] !== undefined)
        {
            var viewHtml = response[1].data;
            $("#output-venue").html(viewHtml);

            Drupal.attachBehaviors();
        }
        else {
            $("#output-venue").html("NONE");
        }

    });
    });
 });

```

Node Venue TPL:

```
<button id="getvenue"> GET VENUE </button>
<div id="output-venue"></div>

```

Nothing happens, I tried alerting the var viewHtml to see if it has something, the alert only shows null.

What's wrong with the JS? Can someone point me to the right direction?

Thank you in advance!

# Answer
> 1 votes
Try this code

```
$.ajax({
    url: Drupal.settings.basePath + 'views/ajax',
    type: 'POST',
    dataType: 'json',
    data: 'view_name=custom_package_form&view_display_id=block_56',
    success: function(response) {
      var output = response[1].data;
      $("#output-venue").html(output);
    },
    error: function(data) {
        alert('An error occured!');
    }
});

```

# Answer
> 0 votes
You need to try this module ajaxblock, I have used it with ubercart for building e-commerce site.

> Permits to load some blocks by additional AJAX request after loading the whole cached page when the page is viewed by anonymous user. It is suitable for sites which are mostly static, and the page caching for anonymous users is a great benefit, but there are some pieces of information that have to be dynamic.

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


# Question
Title: How do I increase the number of shortcuts allowed in admin menu?
The number of shorctuts is limited to 7 (second row)

When I add an 8th shortcut it is in the disabled section

How do I change that?

# Answer
The maximum number of shortcuts is defined in `shortcut_max_slots()`, which just returns a variable:

```
return variable_get('shortcut_max_slots', 7);

```

So all you need to do is change that variable to something larger than 7. You can use the devel variable editor to do it, or just run the following code from somewhere:

```
variable_set('shortcut_max_slots', 10);

```
> 7 votes

# Answer
You can also refer to this Drupal core issue thread: Remove the default limit of 7 shortcuts per shortcut set. There's a patch there to completely remove the limit.
> 1 votes

# Answer
The easiest way to update the shortcut\_max\_slots variable is actually through drush (assuming that you are using it). The command is:

```
drush vset shortcut_max_slots number

```

For example, I did:

```
drush vset shortcut_max_slots 15

```
> 1 votes

# Answer
You can also do this by adding the following code to your settings.php in sites/default/files/ to increase max number of shortcuts to a preferred value.

/\* Configuration option to set max number of shortcuts on the shortcut bar \*/ $conf\['shortcut\_max\_slots'\] = 20;

source - https://api.drupal.org/comment/34883#comment-34883
> 1 votes

---
Tags: routes, users
---


# Question
Title: Is there a way to import a view grid into a Carousel
Hi i have created grid view of a content type coupon which has a logo,description and download button and i'm wondering is there a way to import that view into a Carousel so it can display a grid of 9 coupons and when i hit next it displays another set of 9.

# Answer
Try using the jCarousel module which has great integration with views module.

This tutorial might help you as well - https://www.youtube.com/watch?v=jEMBVGBFskE
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to get field values in rules condition from fetched entity
I have a content type "Event" that's linked to a registration type.

Inside rules I want to trigger the action only if a field value from the host entity is "Open" (it's a checkbox field).

Under actions I'm able to fetch the host entity and access this field but i'm baffled how to access the same field under conditions. How can I go about this?

Thanks.

# Answer
> 1 votes
You have to first add conditions that allow the rule to know what fields are available.

To do this you can use combinations of the following conditions:

* Entity exists by property
* Entity has field
* Entity is new
* Entity is of bundle
* Entity is of type

Those conditions help rules identify the entity and bundle so it can show the relevant fields.

You can then access those field tokens in subsequent conditions and actions.

For example, you might use Entity is of bundle "Event" to then get access to fields used on the event content type.

In your case where you only have access to he user/profile entity you would have to add a condition like above to determine the entity/bundle of the user/profile so that you could get access to the field that references the event.

Then have an action to load the event entity (you could use the action "Fetch entity by id") using the entity id in that field.

Then you could add an if condition in the actions (using the conditional rules module) and say if the fetched entity is of type "Event" then if the value of your field is "Open" then do your final action.

It's a bit complex but you should be able to achieve what you want using the conditional rules module. I think though that this will only work if you have a field on the user that references the event.

If it is the other way around and you have a field on the event that references the user then it would work differently.

In that case I would use the "Fetch entity by property" action to fetch content where the checkbox field = "Open".

---
Tags: rules
---


# Question
Title: Added fields are not displaying while creating the user
I am new to drupal and I have added few more necessary fields to the user create page \[i,e in configuration-\>people-\>account setting-\>manage fields\],but the added fields are not displaying while creating the user\[i,e admin-\>people-\>add user\] but its **displaying while editing the created user**, I have searched to figure it out from last 1 week but no luck for me. if anyone know the reason for not displaying please help me. I have attached the screen shot too.Thanks in advance.

---

# Answer
this is a similar questions on Drupal answers. I would remove this one as i considered duplicated.

Adding fields to user registration form
> 0 votes

# Answer
The solution of your problem is that you are missing an option while saving new fields. Please must tick the check-box **"Display on user registration form"** placed below the **"label"** field as shown below in the image.
> 0 votes

---
Tags: users
---


# Question
Title: Access forbidden 403 to homepage but the rest of website working Drupal 7
I have Drupal 7 installed in localhost, with XAMPP, and it is a replica of a complete working site. I think I have configured everything ok as I can see all the site working nice, with its friendly urls, multilanguage, multidomain, dozens of modules. But still the home page is not rendered, with an Apache error of forbidden. When I try to put site\_name/index.php, it gives a 404 error, and the same trick in remote works rendering homepage!!

Any idea or suggestion on what could be happening? Thanks.

# Answer
For reasons of module SiteMap, I needed to have folders called en, es, fr, which coincides with the suffixes of the language switcher. This was causing some problem in XAMPP while not causing any problem in Linux version. I have renamed the folders and everything is ok now.

I suspect that having an URL as example.com/fr/ which renders the homepage in french is not a good idea if you have a directory, that, if Drupal were switched off, would point to a folder example.com/fr.
> 0 votes

---
Tags: 7, http-request
---


# Question
Title: How to delete cache after updating/deleting/adding new content using hooks?
We have a custom services module and a site in Drupal 7, and I got the task to delete the cache after the editor adds new content or update the existing ones.

I've read about a module called Cache Actions, but, as i said, i need to create the function on my custom module.

Also, I've started reading about Drupal hooks, but still don't have a clue of how to implement this task. Any suggestions? Thanks.

# Answer
> 12 votes
It sounds like you've already got a custom module, but just in case you haven't see the Module Developer's Guide.

The hooks you're looking for are `hook_node_insert()` and `hook_node_update()`, and the function to clear the cache will either be `cache_clear_all()` or `drupal_flush_all_caches`. The former will let you clear specific cache bins (and even specific cache items), and the latter will clear absolutely everything.

For example:

```
function MYMODULE_node_insert($node) {
  drupal_flush_all_caches();
}

```

or to clear only the static page cache after a node has been updated:

```
function MYMODULE_node_update($node) {
  $nodeurl = url('node/'. $node->nid, array('absolute' => TRUE));
  cache_clear_all($nodeurl, 'cache_page');
}

```

# Answer
> 1 votes
You can easily clear specific node cache after updating them. Ex. :

```
function MYMODULE_node_update($node) {
  $nodeurl = url('node/'. $node->nid, array('absolute' => TRUE));
  cache_clear_all($nodeurl, 'cache_page');
}

```

Please note that you must need to specify `array('absolute' => TRUE)`.

---
Tags: 7, hooks, caching
---


# Question
Title: How to remove the shipping flat rate for particular products in Drupal commerce kickstart?
I am using Commerce kickstart. I have to add the products for category wise. Categories are DVD,Audio CD and edownload.I have to use term reference field for field\_category in the products content types.

Now the user purchase the edownload products means shipping charge should be 0rs. How to set the edownload term reference field products for shipping charge is 0. Anyone guide to me?.

Thanks in advance.

# Answer
Try using these modules:

1. Commerce Discount Product Category
2. Commerce Discount
> 0 votes

---
Tags: taxonomy-terms, commerce
---


title: Create node display custom tab

text:
# Question
Title: Create node display custom tab
I'm trying to create tab in node display that links to node delete form. I used hook\_menu\_local\_tasks\_alter in template.php

```
function mytheme_menu_local_tasks_alter(&$data, $router_item, $root_path) {
// Add a tab linking to node/add to all pages.
$data ['tabs'][0]['output'][] = array(
'#theme' => 'menu_local_task',
'#link' => array(
    'title' => t('Delete'),
    'tab_parent' => 'node/%',
    'tab_root' => 'node/%',
    'tab_root_href' => 'node/'.arg(1),
    'tab_parent_href' => 'node/'.arg(1),
    'href' => 'node/'.arg(1).'/delete',
    'access callback' => 'node_access',
    'access arguments' => array('delete', 1),
    'localized_options' => array(
    'attributes' => array(
     'title' => t('Delete'),
    ),
  ),
),

);

}

```

Tab is created but it is displayed for every user and on every page where tabs are enabled. How can I configure `access arguments` to display tab only on node display page and only for user with permissions `[Content type]: delete own content`?

# Answer
This will be done by hook\_menu, See the example below for creating tabs (MENU\_LOCAL\_TASK). This is how tabs will be created.

```
    // For the default local task, we need very little configuration, as the
  // callback and other conditions are handled by the parent callback.
  $items['examples/menu_example/tabs/default'] = array(
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'title' => 'Default primary tab',
    'weight' => 1,
  );
  // Now add the rest of the tab entries.
  foreach (array(
    t('second') => 2,
    t('third') => 3,
    t('fourth') => 4,
  ) as $tabname => $weight) {
    $items["examples/menu_example/tabs/$tabname"] = array(
      'type' => MENU_LOCAL_TASK,
      'title' => $tabname,
      'page callback' => '_menu_example_menu_page',
      'page arguments' => array(t('This is the tab "@tabname" in the "basic tabs" example', array('@tabname' => $tabname))),
      'access callback' => TRUE,

      // The weight property overrides the default alphabetic ordering of menu
      // entries, allowing us to get our tabs in the order we want.
      'weight' => $weight,
    );

```
> 0 votes

---
Tags: users, routes
---


# Question
Title: How to display data export icon on top of an admin view without views-view.tpl.php in admin theme?
I want the XLS/CSV export link buttons of an admin view to be displayed on top of that view. If it weren't a admin view I'ld simply put a slightly changed `views-view--NAMEOFMYVIEW.tpl.php` into my default theme's template folder. But now I'ld have to put that template inside the core's themes folder to work on that certain view since this view has an admin path and is themed by a core theme.

I don't want to add anything custom to the core. Is there another way to bring that button to the top?

# Answer
You can create

```
function MODULE_preprocess_views_view_NAMEOFMYVIEW(&$variables) {
  $variables['title_suffix'] = array(
    /* Renderable data or just string instead of array */
  );
}

```

it will render you content between view title and view content.
> 2 votes

# Answer
Thanks @mr1rk! Was a little bit difficult to get the `MODULE_preprocess_views_view__NAMEOFMYVIEW` to work. Fore more informations about that read: Specific preprocess functions for theme hook suggestions are not invoked in D7. Finally did it like that:

```
function MODULE_preprocess_views_view(&$vars) {
  $function_name = 'MODULE_preprocess_views_view__' . $vars['view']->name;
  if (function_exists($function_name)) {
    $function_name($vars);
  }
}

function MODULE_preprocess_views_view__NAMEOFMYVIEW(&$vars) {
  $vars['title_suffix'] = '<div style="float: right;">' . $vars['feed_icon'] . '</div>';
}

```
> 1 votes

# Answer
you can also add the feed icon in the views header:

```
function MODULE_preprocess_views_view(&$vars) {
  if($vars['name'] == 'view_name') {
    $vars['header'] = $vars['feed_icon'];
  }
}

```
> 1 votes

# Answer
Right click your data export button. In my case **XLS** and select *Inspect Element*.

1. Collapse the `<div class="feed-icon"></div>`, right click and select Copy.
2. Paste the code inside your `page.tpl.php` file inside your theme.
> 0 votes

---
Tags: 7, views, theming
---


# Question
Title: How do I embed a node creation form inside a view
I have a View with some fields and a couple of link items.

What I want to do is when I click on the link items, a node creation form associated with link should appear inside the view (the AJAX way).

The solution that I can think of is to embed the forms inside the view, but have no idea how to do that?

What is the best way to implement this?

# Answer
> 5 votes
Hope this will help you,

In Drupal 7 you can achieve by the following steps

* You can embed a **node creation form** inside a VIEW

+ Either in **VIEW Header** or you can created a **new VIEW and attach it to your VIEW**
* For this example I am embedding inside **Views Header**. Embedding inside **Views Header** will be the better options. Click to **Add Views Header**
* Select Global: Text area
* Add the PHP code and don't forget to change the **Text Format to PHP**
* PHP code

```
<?php
    module_load_include('inc', 'node', 'node.pages');
    $node_form = node_add('node_type');
    print drupal_render($node_form);
?>

```

Note :

* Don't forget to replace **node\_type** in the PHP code.
* Use **hook\_form\_alter** for node form redirection, as after the node creation the form will redirect to node detail page. If you want to redirect to your page then use `$form_state['redirect'] = 'mycustompage';` reference
* Enable **PHP Filter** module using **admin/modules**

* Set the **Permissions** for this module by enabling "Administrator" for **Execute PHP Code** as follows:

If any one has better solution, please share it.

# Answer
> 1 votes
If you are happy to play with some custom code, a similar question was asked on StackOverflow, and there were some pretty extensive solutions to embed forms within a view. All you would have to do is use the form\_id of the node creation form specific to your type, and place it within one of the solutions posted here within your site.

# Answer
> 1 votes
Have a look at Inline Entity Form for this; the Commerce Kickstart employs this as part of the recipe for managing products and product variations. I'm sure there's more to it than I can recall right now, but if this looks promising I'll circle back and improve this answer (or, perhaps others will help improve this answer).

A potential alternative (or complimentary?) module might be Entity Views Attach, which, I believe is also employed in commerce kickstart.

# Answer
> 0 votes
I can't comment the Views Headers solution posted by inizio, I haven't enough reputation.

Well I want to post that you can solve the form redirection after submission with Rules, and you don't have to create a custom module the hook\_form\_alter.

* Create a Rule triggered on "After saving new content" for your node type
* Add condition, compare data and compare the selector \[site:current-page:path\] is equals with your view path
* Add action page redirect to the view path

Can be useful too Form Block and Advanced Form Block modules, but putting php code in view headers you prevent to install extra module

And is done !

---
Tags: 7, views, forms
---


# Question
Title: Order of search results for exact match content
I am using Search API module with Search API DB module to use drupal database for search indexing.

Issue is when I do a phrase search as following "test content" I get results having "test"(let's say nid:1) or "content"(nid:2) or "test content"(nid:3) in them but the content having exact match which is "test content" which is node 3 shows down in the search results.

I do not have any fields for sorting in my search view.

My question is why I am not getting search results on phrase match on top of those who have partial matches?

# Answer
Database search doesn't support phrases searches as stated here by the maintainer of the module (cf. https://www.drupal.org/node/2043339#comment-7654017) :

> Are you using the Database Search backend? In this case it's clear, because that backend currently doesn't support phrase searches due to technical restrictions. However, results should always contain both words, though not necessarily next to each other.

In order to sort your results, see this related question/answer I have no fields available for sorting with Search API sorts module
> 2 votes

---
Tags: search
---


title: Include Views output in href

text:
# Question
Title: Include Views output in href
I am trying to create a custom button in Drupal 7. The link which the href should be equal to is dependent on the context such as the current UID.

I have created a view which normally has a plain text output as \[title\].

I want to use that text output as part of a link field such as

```
http://my-site.com/page/title

```

so I had written the code for the above link as such:

```
<a href="http://my-site.com/page/<?php $block = module_invoke('views', 'block_view', 'profile3-block_4'); print render($block[content]); ?>">LINK TEXT</a>

```

however the output seems as if it is placing part of a views div tag in the link instead. I tried stripping all html from the views block but no success. Anyone got ideas? Could it be an improper use of quotes?

# Answer
You can try like this:

```
$block = module_invoke('views', 'block_view', 'profile3-block_4');
$url = render($block[content]);
Assume your Output will be <div>TITLE</div>
then use **$url =  strip_tags($url);**
<a href="http://my-site.com/page/".$url>LINK TEXT</a>
It will be better to use **l()**
l(t('Link text'), 'http://my-site.com/page/'.$url);

```

If you are still facing issue request you to provide block html output.
> 0 votes

# Answer
`print render($block[content]);` returns a lot of tags. It simply cannot be a valid part of URL string. Also, be sure to avoid `module_invoke` in tpl files if feasible.
> 0 votes

# Answer
If the url is one of the fields returned in the view query then you could access the raw data of the url by calling views\_get\_view\_result($name, $display\_id).

If it returns a uri then you may need to pass it though file\_create\_url() to get a url.

If the row returns a nid then the url might be generated via something like drupal\_get\_path\_alias('node/' . $nid) (adapt as required for taxonomy terms, users, etc).
> 0 votes

---
Tags: views, navigation
---


# Question
Title: custom user page image field crashes when uploading, removing image
I am loading user form with this code

```
   $account = user_load($user->uid);
  module_load_include('inc', 'user', 'user.pages');
  $userform = drupal_get_form('user_profile_form', $account);
  return drupal_render($userform);

```

I have a image field in the form and i'm altering form to append another template file

```
function customuserprofile_form_alter(&$form, &$form_state, $form_id, $account = 'account') {
  switch ($form_id) {
    case 'user_profile_form':

 $form['#theme'] = 'custom_profile_form';

```

and i am printing this field in custom-profile-form.tpl.php

```
<div class="field1"><?php print drupal_render($form['field_profile3'])    ?> </div>

```

it is ok that code is showing me image field but when i click upload or remove button in image field i get this error

```
Notice: Undefined index: user_profile_form in drupal_retrieve_form() (line 760 of Z:\home\drupaler.uz\www\includes\form.inc).
Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'user_profile_form' not found or invalid function name in drupal_retrieve_form() (line 795 of Z:\home\drupaler.uz\www\includes\form.inc).
Notice: Undefined index: #user_category in block_form_user_profile_form_alter() (line 563 of Z:\home\drupaler.uz\www\modules\block\block.module).
Notice: Undefined index: #user in ckeditor_user_customize() (line 41 of Z:\home\drupaler.uz\www\sites\all\modules\ckeditor\includes\ckeditor.user.inc).
Notice: Trying to get property of non-object in ckeditor_user_customize() (line 41 of Z:\home\drupaler.uz\www\sites\all\modules\ckeditor\includes\ckeditor.user.inc).
Notice: Undefined index: #user_category in system_form_user_profile_form_alter() (line 1954 of Z:\home\drupaler.uz\www\modules\system\system.module).
Notice: Undefined index: field_profile in file_ajax_upload() (line 271 of Z:\home\drupaler.uz\www\modules\file\file.module).
Notice: Undefined index: #suffix in file_ajax_upload() (line 280 of Z:\home\drupaler.uz\www\modules\file\file.module).

```

problem is that image field works uncorrectly with in my page. but it is ok in /user/1/edit page Maybe ajax in uploading, removing image needs some corrections or any hacks? Please help me I'm in trouble!

# Answer
> 7 votes
In the menu entry for your custom page, if you have not already done so, you need to add the file path and file to reference the user module files, like so...

```
$items['my/custom/page'] = array(
    'title' => 'My Title',
    'page callback' => 'my_page_function',
    'access callback' => TRUE,
    'file path' => drupal_get_path('module', 'user'),
    'file' => 'user.pages.inc',
  );

```

I find it's necessary to include the reference in the function, as you have already done, and also include it in the menu entry. Don't forget to clear the Drupal cache after updating the menu entry.

# Answer
> 1 votes
To create a custom page for user account form you should go this way:

```
$account = user_load($user->uid);
$form_state['build_info']['args'][] = $account;
form_load_include($form_state, 'inc', 'user', 'user.pages');
$userform = drupal_build_form('user_profile_form', $form_state);
return drupal_render($userform);

```

source: https://www.drupal.org/node/1336212#comment-6056524

---
Tags: 7, users, media
---


title: Views Data Export - Selectable fields

text:
# Question
Title: Views Data Export - Selectable fields
Is it possible to select fields for the export?

For example: When i click button it shows me a popup, where i can select content i want to attach to the exported file.

# Answer
Currently this is not possible. You can always build a view that contain only fields you need. Or select fields when configuring view's display.

Developers needed to choose between GUI on export and unattended processing. They choose automation capabilities, and for good reasons - large exports can take a long time, so it makes sense to trigger them at night using `drush`.

If you believe there should be such option, then you can fork project - it's opensource, GPL v2, so you have full right to do so. You can also file a feature request in module's issue queue, but personally I don't think it would be implemented by maintainers. If you will provide ready to use patches, then maybe.
> 0 votes

# Answer
May be Views Dynamic Fields will help you.

From the project page:

> The Views Dynamic Fields module provides a filter for use with Views module. This filter allows the user to pick and choose which fields to display for a rendered instance of a view for that user. This provides a customized view instance for each user.
>
> This module provides additional advantages when used with the Views Bonus Pack module or the Views Excel Export module to generate an xls file from a view. The xls file will only display the fields you have chosen on the rendered view instance in browser.
> 0 votes

---
Tags: views, importing-exporting
---


# Question
Title: Shipping rules for group of countries (ex. UK or ITALY)
I'm creating the shipping rates depending on country. I've got groups of countries with the same rate.

I've installed Shipping 2.0 and Flat Rate module.

I've limited the available countries through the customer profile and then I've created the flat rates for group of country (ITALY or BRAZIL) and some for a single country (UK).

In the components I did this

Condition: Order address component comparision

Address : Shipping address

Address component : Country

VALUE : GB

(REMEMBER, THE VALUE IS THE TWO LETTER ABBREVIATION, ITALY WILL BE IT AND UNITED KINGDOM IS GB. YOU CAN FIND IT LOOKING A THE HTML OF THE SHIPPING FORM)

I've added one condition per each country of that group. I've implemented with OR but for some reason it does not work.

This is the result: Condition 1 : IT

OR

Condition 2: FR

This does not work, so I tried:

Condition 1: IT

--OR

----Condition 2: FR

But nothing...

What Am I doing wrong? It's something related to the "OR"?

The flat rate with single country works, the one with complex rules doesn't.

---

I SOLVED IT: IT WAS THE CONDITIONS POSITIONS. THE RIGHT WAY TO USE "OR" IS THIS:

OR

--CONTITION 1

--CONTIDION 2

HERE YOU CAN FIN A REALLE NICE RULES TUTORIAL

# Answer
The OR and AND-groups takes all conditions inside of them with the chosen operator.

Your:

Condition 1: IT
--OR
----Condition 2: FR

Will be converted into (\[Condition 1\] AND (\[Condition 2\])).

Try putting both **Condition 1** and **Condition 2** in the OR-group:

--OR
----Condition 1: IT
----Condition 2: FR

This should be converted into (\[Condition 1\] OR \[Condition 2\]). If that's what you're after.

*Edit: Just a couple of minutes too late :)*
> 7 votes

# Answer
I am trying to **exclude** a shipping rate for certain countries and had no luck with the examples above.

But this one works:

--NOT Country A
--OR
----NOT Country B
--OR
----NOT Country C
> 0 votes

---
Tags: rules, commerce
---