# Question
Title: How can I make it so that users can add content to my site?
I have created a custom content type for my site that takes three fields. I then created a view that displays only that content type in a grid form. I need to know how to allow users to add content based in the form of my custom content type so that they can add things that will directly be added to the custom view I made. (Essentially the view makes a grid that displays rows of 3 images in each row. The images when clicked on will then take the user to a page that gives a description of what the image is along with a few other things.) Does anyone know what I can do with this, or if there is a much easier way to do this that I am totally missing?

Thanks for the help!

# Answer
> 1 votes
You only have to provide access to anonymous user to add content for the content type that you have created. For that go to permission page of Drupal:

> admin/people/permissions

Check the following check boxes for anonymous user.

> Basic (your content type) page: Create new content
>
> Basic(your content type) page: Edit own content

# Answer
> 0 votes
Content access is the module you need, this module helps handling content type permission, nice and clean.

> 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.

# Answer
> 0 votes
For the content type that has the fields on it, allow the `anonymous` user role the ability to create new nodes. This is located at `/admin/people/permissions`.

---
Tags: nodes
---


title: Views field rearrange

text:
# Question
Title: Views field rearrange
I am using Field group module for creating fieldset in content type.

Can I have similar features while **rearranging the fields** selected in **views**.

# Answer
> 0 votes
You can try using module Field group views

Project page says

> Provides a view format for Field group.
>
> In other words, a field group can be displayed using a view. One possible usecase would be to generate a table using fields as columns.

---
Tags: views, entities
---


title: How to get body value (drupal 7)

text:
# Question
Title: How to get body value (drupal 7)
I would access to the description of node in body value, so I try this :

```
// ----------------------------
// Acesseur de la descrition d'un noeud
// ---------------------------
function dfsi_GetBodyOf( $node )
{
    $wrapper = entity_metadata_wrapper('node', $node);
    return $wrapper->body->value();
}
// ----------------------------
// Acesseur de la criticite d'un noeud
// ---------------------------
function dfsi_GetCriticiteOf( $node )
{
    $wrapper = entity_metadata_wrapper('node', $node);
    $wrapper-> field_criticite->value();
return $wrapper;
}

```

I have no problems to access criticite value, but when I try to access body value, it return "array" and I don't know why, can you help me?

# Answer
> 4 votes
The value of a formated text field is a structure with a `value` and a `format` property. Because the `body` is a formatted text, you likely need to use its `value` property. Tho get the formatted body value, you will need to use

```
$wrapper->body->value->value(array('sanitize' => TRUE))

```

---
Tags: 7
---


# Question
Title: Link product variations to its own pages (e.g. blue hat to blue hat variation, etc.)
I have a product display of two t-shirts variations, one is blue color and one is black. I also use it in Views Slideshow, to show it in front page.

The problem is that both variations link to the default one only. If default product display t-shirt is black, but also has a variation of blue, when clicked on blue t-shirt in homepage, it redirects you to the black version. How do I make it link all variations to it's own versions/pages? Is this even possible? Because when filtering variations on product display node, the page path is same and doesn't change.

# Answer
> 0 votes
I solved it by using the following rewrite results: \[path\]?id=\[product\_id\].

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


# Question
Title: migrating from multiple csv files in one migration class
I have multiple CSV files in different folders. The folder names are the node ids. And each folder contains its own CSV file. Now I want to loop these directories and import from the CSV files in one migration class but it only migrate from the last CSV file.

Here is my code

```
class MigrateNodes extends Migration {
  public function __construct($arguments) {
    parent::__construct();
    $columns[0] = array('Number', 'Number');
    $columns[1] = array('Title', 'Title');
    $columns[2] = array('Description', 'Description');
    //The Description of the import. This desription is shown on the Migrate GUI
    $this->description = t('Import lots from excell file ');
    $nids = db_select('node', 'n')
        ->fields('n', array('nid'))
        ->condition('n.type', 'type')
        ->execute()
        ->fetchCol();
    foreach ($nids as $nid) {
   $path = $nid . "/nodes.csv";
      //The Source of the import
      $this->source = new MigrateSourceCSV($path', $columns, array('header_rows' => 1));
      if ($this->source) {
        $this->destination = new MigrateDestinationNode('lot');
        $this->map = new MigrateSQLMap(
            $this->machineName, array(
          "Number" => array(
            'type' => 'int',
            'unsigned' => TRUE,
            'not null' => TRUE,
            'alias' => 'import'
          )
            ), MigrateDestinationNode::getKeySchema()
        );
        //Field ampping
        $this->addFieldMapping('title', 'Title');
        $this->addFieldMapping('field_lot_description', 'Description');
      //}
      }
   }
  }
}

```

The Number field is unique. Any one knows what I am doing wrong?

# Answer
I have solved it. Just place the following line after the field mappings if it is the import process.

```
$this->processImport();

```
> 1 votes

---
Tags: 7, migrations
---


title: Change templates based on path alias

text:
# Question
Title: Change templates based on path alias
What is the easiest way to select a template based on path alias. For example, if I have the following URLs:

http://www.example.com/mydirectory/page1
http://www.example.com/mydirectory/page2
http://www.example.com/mydirectory/page3

How would I go about creating a template for all of the pages in *mydirectory*? I should also add that using content type to theme these pages is not an option.

# Answer
You can add some logic in a `hook_preprocess_page()` implementation that checks the alias, and adds theme hook suggestions if the path matches, e.g.

```
function MYTHEME_preprocess_page(&$vars) {
  $alias_parts = explode('/', drupal_get_path_alias());

  if (count($alias_parts) && $alias_parts[0] == 'mydirectory') {
    $vars['theme_hook_suggestions'][] = 'page__mycustomtemplate';
  }
}

```

Then if you create a `page--mycustomtemplate.tpl.php` file in your theme, and clear the cache, any pages with an alias beginning `mydirectory/` will use that new file instead of the standard `page.tpl.php`.
> 22 votes

# Answer
It's actually easier than that using drupal\_match\_path() which is how the blocks module works out whether a block should be displayed on a page or not:

```
function MYTHEME_preprocess_page(&$vars) {
  if (drupal_match_path(drupal_get_path_alias(), 'mydirectory/*')) {
    $vars['theme_hook_suggestions'][] = 'page__mycustomtemplate';
  }
}

```
> 4 votes

---
Tags: 7, theming, path-aliases
---


title: How to setup node references

text:
# Question
Title: How to setup node references
im creating website for racing events, basically website have added all races that are happening during one year, and it stores data for previous races. I was asked to move from website from .net N2CMS to Drupal.

Im having problems with setting up proper content types and their references.

In the old website they have added several races. Every race node contains basic details ( town, country, best time, website url... ) and besides that details every race have data about previous years winners ( Name, Timings, Car ).

On the main race node there is this basic data and bellow that there are results from latest 5 years with ability to expand and show all previous years.

So its clear to me how to make main race content type and add fields, but i was wondering how to make it easy for admin to add winners of previous years, and this has to be modular as much as possible, because some races have this data all the way down to 1972, but yet some of them have just few years back.

So i guess some kind of node reference should be used here but just dont have it clear in my head what i need to do.

Sorry if my questions is not clear, i tried to explain it so that everyone can understand it.

Thanks

# Answer
> 0 votes
You can create two content types

* Race Details
* Race Standings

+ Node reference to Race Details as a field
    + Year
    + A Field Collection with details (Fields) like

    - Race Winner Name
        - Timings
        - Car
        - Position etc

# Answer
> 0 votes
It appears that it was not so hard as i thought.

I created 2 content types Race and Race details.

I installed references module and added a filed (node reference) called "Race" in node Race details.

Than i created new region and printed it below main content.

In next step i created a view with block and page, added all fields needed. And than using contextual filters ( Node id from url ) i printed block below main content.

---
Tags: 7, nodes
---


# Question
Title: Display Suite: Panel layouts in doesn't appear in "Manage fields"
I can select panel layouts using display suite in the manage display tab, but only display suite layouts are available in the manage fields tab but none of the panels layouts are.

Can you please help me with this problem?

# Answer
The `Manage Fields` tab is used for arranging fields for the Node Add/Edit form, as well as to Add/Edit/Remove fields to the Node/Entity.

If you want to use Panels for the layout of your Node Add/Edit forms, then you would do this through the Panels Interface by enabling and editing the `Node add/edit form` Panel that comes included when you install Panels. You would create variants in this Panel to handle the layouts for each content type you have. Hope that can help.
> 1 votes

---
Tags: panels, display-suite
---


title: WSOD appears in Drupal

text:
# Question
Title: WSOD appears in Drupal
During making of new variants performing steps. node edit form-\>add new variant-\>variant type -\>panel-\>selection rules-\>node type-\>context continue-\>choose layout 2 column-\>continue-\>render-\>standard-\>continue after this white display occur,i am stuck here.what is the problem.

# Answer
> 1 votes
There are some PHP settings that can lead to WSOD. These are as follows:

1. **max\_execution\_time:** Apparently, on WAMP, the default is 30 seconds, but some administrative pages may take longer than that to process and load.

> Go to XAMPP/php/php.ini and change :

```
    max_execution_time = 360

```
1. **PHP Memory Limits:** Another common reason for the WSOD is issues with memory limit.

```
memory_limit = 128M

```

# Answer
> 0 votes
I guess you should be able to find the issue if you can come to know the error that is causing the problem, as the error reporting is by default turned "OFF" to avoid end user know the internal error for security and other purposes, so enabling the error on local or on dev server might help you out, try adding the following code in **settings.php**:

```
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

```

**Note**:- Remove the above code from settings.php file once you are done with the development work.

Also check the errors/exceptions logged in the **watchdog** table in drupal at "**/admin/reports/dblog**":

```
http://YOUR_WEBSITE_DOMAIN/admin/reports/dblog

```

Also please check this link: **Blank pages or "white screen of death" (WSOD)** for other possible solutions to WSOD.

---
Tags: 7, commerce
---


# Question
Title: How to change drupal commerce views like checkout,payment?
i configured drupal commerce module all working fine.question is how to format or design the checkout page,billing page,review page,payment page. i can add more data but how change existing data..i make tpl file for related name but by this we can add more data but how to change existing data plz tell me ASAP.

in detail:actually drupal commerce provides four page for checkout (1)checkout(2)billing address(3)order review(4)payment all are working fine problem is: can i change the all four page's design and add more data to it.how can i find out the html of these four page. i can't figure out by making template file of those four page.

# Answer
> 0 votes
Have you learned Views? you can try change default views shoppingcart,checkout page,billing page,review page etc. Eg: to modify shopping cart block you can go to http://your.site/admin/structure/views/view/commerce\_cart\_block/edit

---
Tags: commerce
---


# Question
Title: Stop Youtube when changing between tabs (Quicktabs)
I am trying to stop a Youtube video when I change between tabs using QuickTabs but the video is still running, even in the iPad, I can even play the both videos, in this case Trailer and Full Movie at same time.

By the way, I am using the vanilla Youtube iFrame.

# Answer
I think this post should help you: https://stackoverflow.com/questions/1094397/how-can-i-stop-a-video-with-javascript-in-youtube.

As @Pan Chrono said, it's not a drupal related question, more a youtube one.

What you basically need is:

* change the way the youtube video is embed. It's actually using an iframe, you need a "embed" tag.
* add "enable\_js=1" to your URL so you can use Youtube Api
* add a custom JS file to your page, and do some little jQuery code so that the video is stopped (with `var myPlayer = document.getElementById('playerid'); myPlayer.stopVideo();`) when you click on one of your tab
> 0 votes

---
Tags: javascript, theming, blocks
---


# Question
Title: Create users on the frontend, without 'administer users' permission
As you may know, there's one single permission that controls user's access to other user's creation - permission is called 'administer users'. It either gives access to full user's administration or to nothing.

On my system I have tiered users who are supposed to have some permissions in relation to user administration. But not all permissions. I basically need to be able to create user accounts (based on profile2) on the frontend url (not /admin/people/p2rp-create/user but eg. /add-user.

I know there's a way of rendering an existing Drupal registration form, not sure how to a) render profile2 form, or, to be precise, render profile2 form that includes forms for few created profile (I have 3 at the moment) b) make it create a user even tho user doesn't have 'administer user'

I played with the following for starters

```
function module_menu(){
  $items['add-user'] = array(
  'title' => 'Add user',
  'page callback' => 'module_reg_form',
  'access arguments' => array('access create customer'),
 );

function module_reg_form(){
  $user_register_form = drupal_get_form('user_register_form');
  $form_state = array('profiles' => array('contact_details'));
  $registration_with_profile_fields_form = profile2_attach_form($user_register_form, $form_state);
  print(drupal_render($user_register_form));
}

```

This throws an error

```
EntityMalformedException: Missing bundle property on entity of type profile2. in entity_extract_ids() (line 7721 of /home/dreamweddings/www/dreamweddings.eu/public/includes/common.inc).

```

# Answer
Can you not simply give user permissions to create users of specific roles (via the administerusersbyrole module) and then use the existing user creation form at `/admin/people/create`? If you do go with administerusersbyrole, make sure you follow the two steps on the project page for assigning the configuration.

If you must have a custom form via another page, you probably want to do it via a proper form definition function by setting the menu 'page callback' to 'drupal\_get\_form', and then passing the function that provides the form definition in 'page arguments'. See this particular comment for a code example. This way you'll be able to do proper form validation and a for submit handler too. Even if you get your current snippet working, the form still needs to submit somewhere to work.
> 1 votes

---
Tags: users
---


title: Validate URL with a specific pattern?

text:
# Question
Title: Validate URL with a specific pattern?
Anyone know of a module that can check the base path of the URL to ensure the user is entering the correct URL?

I.e. the field is asking for the Facebook URL but they put in a Twitter one.

So should the user enter a different URL they won’t be able to continue unless the link contains `www.facebook.com/`.

# Answer
> 0 votes
Solved it by using regular expressions.

Attaching sources:

https://drupal.org/project/field\_validation http://m.youtube.com/watch?v=hE87Z2sOtfs

# Answer
> 0 votes
Not a module, but you can add a custom validator that parses the string that the user put in for URL to see whether it contains the expected strings, e.g.

```
if (strpos($url, 'facebook.com') === 0) { ... }

```

Note the triple-equals is necessary with strpos because otherwise "found at position zero" (return value of 0) is falsey, and so is "not found" (no return value).

---
Tags: uri, forms
---


# Question
Title: Views exposed sort handler with asc + desc + inactive
I have a view with the following sort handlers:

* price (exposed, asc/desc, default=asc)
* stock (desc)

I would like to have a third option for price so that it can be inactive/asc/desc, with "inactive" being the default.

So by default it sorts by stock availability (or any other sort handlers I may configure in the future), and only if the user chooses "cheapest first" it will sort by price.

(I am going to use Better exposed filters to display the sort options as links, but this is secondary)

# Answer
> 3 votes
Things to learn:

* If more than one sort option is exposed, then only one of them will be active at a time.
* The first of all exposed sort option will be active by default, the others will be inactive by default.
* The non-exposed sort options will always be active. But if you put them below the exposed sort options, they will have a lower priority, obviously, so you might not see the effect.
* One field can be used multiple times. E.g. one time exposed, another time not exposed.
* BEF can be used to re-label the options.
* BEF can be used to hide some sort options, by leaving the label empty.

Example sort configuration:

1. stock, exposed, descending.
2. amount, exposed.
3. stock, descending. (not exposed)

Then in the BEF settings, "Advanced sort options", "Rewrite the text displayed":

```
Stock Desc|No sort
Stock Asc|
Price Asc|Cheapest first
Price Desc|Most expensive first

```

---
Tags: views
---


title: Limit access to subsite

text:
# Question
Title: Limit access to subsite
I googled for it but couldn't find anything about that. Is it possible to create drupal website (example.com) with subsites (example.com/subsite1 and example.com/subsite2) where access to them are limited to:

```
2 users on example.com/subsite1
users on example.com/subsite2
no limits on example.com/"

```

I want to share some digital content on those subsites to not more than X users at time.

# Answer
There's no built-in way to do this, afaik. Are the sites truly separate sites? Drupal multi-site?

You could build a custom module that uses one of the hook\_preprocess\_XXX functions. In that function you could do a mysql query with the "sessions" table. If there are 2 active sessions, block/redirect the user. Session management would be tricky though. You'd want to change the session timeout length for that site, and also encourage your users to logout when they're done browsing to make room for the next guy.

edit: process for the content type, or you could look in to hook\_menu functions which might be cleaner, though I am not sure it will work.
> 0 votes

---
Tags: 7, nodes, users
---


title: Custom content drupal6

text:
# Question
Title: Custom content drupal6
I'm new to drupal, so forgive me if my question will be silly :) I've a little problem with my first custom content on a drupal 6 installation. My content "biography" is listed in admin/content/types page, but when i click on my type, page reloaded instead of loading /admin/content/node-type/biography

If i force the url in the browser, i'll be redirect to /admin/content/types page again.

Do you know why? I've implemented both the node\_info and form hooks, but with no luck.

Thank you in advance and sorry for my english! Have a nice day!

**UPDATE**

I cant reply on my own post because i still have low reputation, but...

Bingo..Thank you ARUN! I had been deceived by the fact that it had appeared in content type's list without clearing cache!

have a nice day!

# Answer
> 0 votes
That might because of cache. Clear your site cache here **/admin/settings/performance**. Then try to load your content type edit page **/admin/content/node-type/biography**.

---
Tags: hooks, nodes
---


title: Show drupal message with ajax flags

text:
# Question
Title: Show drupal message with ajax flags
I bound an action to my flag to display a message on flagging. However because I am using AJAX flags the message is only displayed after I refresh the page.

Is there any way to make the message appear after the flag is flagged and not on page reload?

Thanks

# Answer
> 0 votes
This feature already there with flags module. Please check in your flags settings page.

---
Tags: 7, ajax, flags, status-messages
---


# Question
Title: Hook path in main menu not hold active trail
In custom module names supply\_area I've created custom path.

```
function supply_area_menu() {
    $items['supply-area'] = array(
        'title' => 'Supply area',
        'page callback' => 'supply_area_page',
        'type' => MENU_NORMAL_ITEM,
        'access callback' => true,
        'menu_name' => 'main-menu',
    );
    return $items;
}

```

Everything works perfectly except that even if I assign this path into main menu structure it does not hold menu structure so breadcrumbs looks like: Home \> Supply area and not Home \> About \> Supply area. Is there something wrong with my hook\_menu?

# Answer
I am not sure what you are doing in a lot more areas of your system than described above, but doing the following on a d7 testbed here:

```
function MYMODULE_menu() {

  array $items;

  $items['about'] = array(
    'title' => 'About',
    'page callback' => 'MYMODULE_about_page',
    'type' => MENU_NORMAL_ITEM,
    'access callback' => TRUE,
    'menu_name' => 'main-menu',
  );

  $items['supply-area'] = array(
    'title' => 'Supply area',
    'page callback' => 'MYMODULE_supply_area_page',
    'type' => MENU_NORMAL_ITEM,
    'access callback' => TRUE,
    'menu_name' => 'main-menu',
  );

  return $items;

}

function MYMODULE_about_page() {
  return 'What\'s it all about, Alfie?';
}

function MYMODULE_supply_area_page() {
  return 'Making Supplies';
}

```

...followed by clearing caches and then setting it up via the Menu UI:

...provides the following:

so I would check how you might be doing it slightly differently on your system.
> 0 votes

---
Tags: routes
---


# Question
Title: How to get a count of groups that user has joined?
I have used OG module to implement the Groups functionality. I want to get:

1. Count of all groups that are there on the website
2. Count of groups that a user has joined

How can I do this?

Note: My preference would be to use an existing function (if there is any).

# Answer
> 1 votes
To get Count of all groups....

```
$groups = og_get_all_group($group_type = 'node');
$count = count($groups);

```

To get User Groups Count

```
$user_groups = og_get_groups_by_user();
$user_count = count($user_groups);

```

---
Tags: 7, organic-groups
---


title: Theming output of node_view

text:
# Question
Title: Theming output of node_view
I'm printing the output as described in here: How to programmatically render a node's teaser using the theme layer? in block using PHP filter.

Also I've a theme implementation file named: `views-view-field--field-image.tpl.php` in the custom Mobile theme directory with this content:

```
<?php

?>
<?php /*print $output;*/ ?>

```

This is hiding all image field output but not the output of drupal\_render($view).

How to hide the images in this redered output as well?

# Answer
> 0 votes
Before calling `drupal_render($view)` inspect the $view array. (Use devel's dmp or print\_r to inspect the array.)

Find out what part of the array contains information about your images, and then unset this before calling drupal\_render.

E.g.

```
unset($views['my-image-field']);
print drupal_render($view);

```

---
Tags: 7, theming
---


title: How to create a drupal view using sql

text:
# Question
Title: How to create a drupal view using sql
Is there anyway for me to create a Drupal view from two sql queries and have two separate outputs. Here is the two SQL queries I want to create a view from:

SELECT f.delta AS field\_data\_field\_session\_start\_date\_delta , f.entity\_id AS date\_id\_date\_filter , f.delta AS date\_delta\_date\_filter , n.title AS node\_title , n.nid AS nid , n.language AS node\_language , f.field\_session\_start\_date\_value AS field\_data\_field\_session\_start\_date\_field\_session\_start\_date , f.field\_session\_start\_date\_value2 AS field\_data\_field\_session\_start\_date\_field\_session\_start\_date2 , 'node' AS field\_data\_field\_session\_start\_date\_node\_entity\_type FROM `node` n JOIN `field_data_field_session_start_date` f ON f.entity\_id = n.nid AND f.entity\_type = 'node' AND f.deleted = '0' AND f.field\_session\_start\_date\_value \>= NOW() WHERE n.status = '1' ORDER BY f.field\_session\_start\_date\_value ASC LIMIT 3 OFFSET 0

SELECT f.delta AS field\_data\_field\_session\_start\_date\_delta , f.entity\_id AS date\_id\_date\_filter , f.delta AS date\_delta\_date\_filter , n.title AS node\_title , n.nid AS nid , n.language AS node\_language , f.field\_session\_start\_date\_value AS field\_data\_field\_session\_start\_date\_field\_session\_start\_date , f.field\_session\_start\_date\_value2 AS field\_data\_field\_session\_start\_date\_field\_session\_start\_date2 , 'node' AS field\_data\_field\_session\_start\_date\_node\_entity\_type FROM `node` n JOIN `field_data_field_session_start_date` f ON f.entity\_id = n.nid AND f.entity\_type = 'node' AND f.deleted = '0' AND f.field\_session\_start\_date\_value \<= NOW() AND f.field\_session\_start\_date\_value2 \> NOW() WHERE n.status = '1' ORDER BY f.field\_session\_start\_date\_value ASC LIMIT 3 OFFSET 0

# Answer
> 0 votes
Make 2 Views with your `LIMIT 3` clauses from the SQL you've provided using the Views UI.

Then make a custom block in a module. Use views\_get\_view\_result (see additional documentation and usage of views\_get\_view\_result here) to call your 2 views programmatically from PHP code. Then in your block output content simply loop through upto 3 items in your *NOW* listing, then add any needed items from your *UPCOMING* listing if the max of 3 items hasn't been reached yet. An example of how to make a block in code by Four Kitchens can be seen here. Taking their example your `hook_block_view` may look like below.

```
function custom_block_block_view($delta='') {
  $block = array();
  switch($delta) {
  case 'my_block' :
    $block['content'] = my_three_upcoming_events();
    break;
  }
  return $block;
}

function my_three_upcoming_events() {
  $output = '';
  $now_events = views_get_view_result('VIEWNAME_FOR_NOW_EVENTS_VIEW');
  $upcoming_events = views_get_view_result('VIEWNAME_FOR_UPCOMING_EVENTS_VIEW');
  $max_events = 3;
  // Make a big list of events now; upcoming events will be on the end of this list.
  $all_events = $now_events + $upcoming_events;

  for ($i=0,$z=$max_events;$i<$z;$i++) {
    $node = node_load($all_events[$i]['nid']);
    $output .= '<div>' . l($node->title, '/node/'.$node->nid) . '</div>';
  }
  return $output;
}

```

# Answer
> 0 votes
I think the easiest way to create this in views will be to just manually read it and re-create using the views UI.

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


# Question
Title: Is there any way to delete ubercart role expiration through rules in Drupal 7
I am using Drupal 7 and ubercart roles where I have given the role expiration period of 1 day, and with that role the user can create one node. I want that as soon as the new node is created the role expiration should be deleted.

I am able to remove the role through rules but as the expiration period is still set, it cannot be re-assigned the role the same role if the user purchases the same role again,

Is there any way to remove the role expiration of ubercart?

thanks for any help.

# Answer
It seems that you are removing the role through the drupal standard rules. Try calling the own uc\_ubercart function to better compatibility.

```
/**
 * Deletes an expiration using user id or user id and rid.
 *
 * This function deletes expirations associated with users and roles. If
 * no role ID is passed, the function deletes all role expirations associated
 * with the given user. Otherwise, the function only deletes expirations whose
 * user and role IDs match. If any roles were actually deleted, the function
 * notifies the user. The menu cache is then flushed, as privileges to view
 * menu items may have been lost in the process.
 *
 * @param $account
 *   A Drupal user object.
 * @param $rid
 *   A Drupal role ID.
 * @param $silent
 *   When set to TRUE will suppress any Drupal messages from this function.
 */
uc_roles_delete($account, $rid = NULL, $silent = FALSE) {}

```

An example with custom module (without rules):

https://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook\_node\_insert/7

```
/**
 * Implements hook_node_insert().
 */
function mymodule_node_insert($node) {

  if ($node->type == 'customtype') {
    $rid = 3; //@TODO: set rol ID
    $account = user_load($node->uid);
    // Delete UC Role!
    uc_roles_delete($account, $rid, TRUE);
  }

}

```

You can also use this code on the rules action PHP but I prefer the hook.
> 1 votes

---
Tags: rules, ubercart, users
---


title: Url aliases for Drupal 7 Views page

text:
# Question
Title: Url aliases for Drupal 7 Views page
I have a view which has the path set to events/%, where the wildcard will the the nid of, for example, a department. The view will display all events for a particular department.

I want to be able to change the second nid argument to be an alias, such as events/programming. I don't see this option in the standard Pathauto settings. I found a module which almost does this (only for taxonomy terms), https://drupal.org/project/view\_alias, but its only for D6.

Is ther anything for d7, and if not, what would be the best hook to implement to make this change?

EDIT: There was a suggestion to use the Extended Path Aliases module, but I was not able to get that to work properly, and requires you to hack core (or install hte PECL library). I found a different module, subpathauto, which seems to do the same thing with out core hacking and it also says that it works with views. It still didn't work, this is what happened:

```
Node path: node/24
Node alias: department/[nid]
View path: department/[nid]/conditions

Example alias: department/physical-therapy-department

```

When I use the url of department/24/conditions, I reach the view page I want and the filtered content is displayed. When I use the url department/physical-therapy-department, I reach the correct node page. When I use department/physical-therapy-department/conditions, I DO reach the view page, but it has no content. Clearly the system did not translate physical-therapy-department back to 24 for processing, and the view didn't work.

Does anyone know how to use this module properly?

# Answer
You can try using Extended Path Aliases module..

Project page says

> Would you like your human-readable, SEO-friendly aliases to be carried through on all your tabs, links, **Views**, and blocks, on all your pages, not just on that single aliased base path? If so, then this little module is for you.
> 3 votes

---
Tags: views, path-aliases
---


title: how to display view block in node page

text:
# Question
Title: how to display view block in node page
I have a block in view that is displaying the user details, i want to display that block in a nodes created by the respective users.

i am successfully using this block in user page now i want it on node page.

please help me.

For another block which is also coming from view is worked fine with this code Show block on specific pages:

```
<?php

//Read URL
$path=$_GET['q'];

//If URL is node page

if ( strpos($path,'node')===0){
//Parse URL to get nid
$links=explode("/",$_GET['q']);
$nid=$links[1];

//Load node

$node=node_load($nid);

//Display block only if node is of certain content type
if($node->type=='user_art'){
return TRUE;
}
}

return FALSE;
?>

```

Thanks

# Answer
> 0 votes
It is better to check the arguments from arg() function, this way:

```
<?php
// PHP VISIBILITY CODE:
// If URL is node page

if (arg(0) == 'node' && is_numeric(arg(1))){
  $nid = arg(1);

  // Load node:
  $node=node_load($nid);

  // Display block only if node is of certain content type
  if ($node->type=='user_art') {
    return TRUE;
  }
}

return FALSE;
?>

```

Maybe the problem is with the views argument to get $node-\>uid. Try this:

More info: https://groups.drupal.org/node/129979#comment-751473

```
1 - Create a new Block View to view Users (not Content)

2 - Filter Criteria should say User: Active (Yes)

3 - There is a default sort Criteria item. Remove it since it doesn't matter.

4 - Add a Relationship: Choose "User: Content authored"

5 - Add a Contextual Filter: Chose "Content: Nid"

6 - In the configuration options for the newly added Content: Nid, choose these options:
WHEN THE FILTER VALUE IS NOT AVAILABLE:
Provide default value
In the Select box, choose Content ID From URL.

WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED
Specify validation criteria
Validator select box: Content
Content Types: choose the content types you want the view to work with.
Filter Value Format: Node ID
Action to take if the filter value does not validate: Hide View

7 - Save the View.

8 - Go to Structure -> Blocks and configure the block to show on the types of content you want it to show on and position it wherever you want it to appear.

9 - Done.

```

# Answer
> 0 votes
I *think* what you are trying to accomplish is something like this:

```
<?php

  global $user;

  $node=menu_get_object();

  if (isset($node->uid) && $node->uid==$user->uid) {
    return TRUE;
  }

  return FALSE;

?>

```

The above uses the menu\_get\_object() function to look at what, if any, node page you are currently on, and if the user who created that node is the same as the current user, it returns TRUE. Otherwise, if you aren't on such a node page, it returns FALSE.

I might add this *may* be a better way to accomplish your logic for displaying a block on only a certain type of node, eg something like this:

```
<?php

  $node=menu_get_object();

  if (isset($node->type) && $node->type=='WHATEVER') {
    return TRUE;
  }

  return FALSE;

?>

```

---
Tags: views, nodes, blocks
---


# Question
Title: Creating a website with search filters like amazon and Ebay. Is it possible?
I want to create a website which will be a search based. It will allow users to narrow down results based on categories and tags. The website is not a shopping website but will be a collection of articles. The user will narrow down the results using categories and sub categories and various types. I want to know that is this kind of functionality obtained from Drupal. I am using Joomla and its not allowing me to do what I want.

# Answer
You can use something like Solr as that supports faceted searching.

It is rather complicated to set up though if you are using your own search server.
> 1 votes

---
Tags: search, navigation
---


# Question
Title: Link checker modules fails to detect a test broken link
I downloaded, installed, enabled and configured the linkchecker module. When I run it from the Drupal interface, it seems to be checking but I don't see in the report a test link (within ) that I have purposefully misspelled. This test link is to an external site. Does it matter for the link checker module if my development site is not publicly accessible-- I think it is accessible only from campus.

Linkchecker version 6.x-2.7; drupal-6.26

# Answer
> 0 votes
## Found Link checker works after 'run cron'

-- Found in video: https://www.youtube.com/watch?v=Hcl9iwIFZ2k
That a cron job has to be run after the configuring.
-- I had already set for automatic running of cron job. For some reason it didn't work.
-- It worked after running cron job manually.
`site-url/cron.php` for D5 and D6

-- OR For Drupal 6.x, see in your site: Administer \> Reports \> Status report \> Cron maintenance tasks \> Run cron manually.

### Steps for checking links:

1. Make sure link checker configuration is what you want
2. `http://site-url/cron.php` in browser to run cron job (it yields blank page after the run)
3. See report for broken links and follow up specific links.

Here is another link for some relevant info on link checker module: http://www.lullabot.com/blog/article/module-monday-link-checker

---
Tags: 7
---


# Question
Title: Adding a CDN asset to drupal theme via info file
Just as the title suggests...I tried using an absolute path:

stylesheets\[all\]\[\] = 'http://fonts.googleapis.com/css?family=Lato:300,400,700,900'

This doesn't work...how do I add this to a theme?

# Answer
> 2 votes
You can add it in the theme template.php file.

```
function YOURTHEME_preprocess_html(&$vars) {

      // Load font
      drupal_add_css('//fonts.googleapis.com/css?family=Lato:300,400,700,900', array(
        'type' => 'external'
      ));

}

```

Tip: Dont set a protocol to load external resources from Google

---
Tags: theming
---


# Question
Title: Create a view block on a node reference field (using Node Reference)
Creating a related content block on a node reference field. I have two content types: **Article and Author**.

The content type Article has the field Label: Por 'field\_autor' which is a node reference to an author node.

I want to be able to take that ID and lis other articles with the same NID.

**The view is setup as such:**

* Format: HTML List
* Fields: Title
* Filter: Published;
* Type (Article)
* Order: Weight

Advanced Options

* Contextual Filters: (field\_autor) Content: Nid
* Relationships: Content: Por (field\_autor) - reverse

However, this isn't displaying articles with the same author. Looking for assistance!

# Answer
> 0 votes
**UPDATE**

There are some decent explanations on the internet

1. http://www.webomelette.com/related-content-block-views-drupal-7
2. http://www.webomelette.com/related-content-views-taxonomy-drupal

As well the eva module was suggested as being helpful in my situation, but I haven't tried it yet

Currently, this is still an issue for me.

---
Tags: nodes
---


# Question
Title: Test if Anonymous users can sign up for a new account
In a Drupal theme, how can you test if Anonymous users are able to sign up for a new account?

Background:

I am theming my user login form according to this tutorial.

On my themed user loser login form, there is an option for users to sign up if they do not have account.

On my site, I periodically disable anonymous sign ups, so when this happens, I want the sign up link in my theme to be not printed out.

# Answer
> 1 votes
If you look at the implementation of the login block in the core user module:

```
$items = array();
if (variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL)) {
  $items[] = l(t('Create new account'), 'user/register', array('attributes' =>
    array('title' => t('Create a new user account.'))));
}

```

you'll see that it queries a variable name `user_register`. If you disable anonymous registration, this becomes `0`, and the link to "Create a new account" doesn't show.

This logic should work, no matter how you theme your site.

If your theme breaks this logic in the core user module, then you need to rework your theme until it don't break the core user module.

(Btw - this also tells you how to "test if Anonymous users are able to sign up for a new account" - check the status of the `user_register` variable, and if it is non-zero they should be able to sign up. But this does *not* belong in your theme. It belongs where it already is: In the core user module. I will advice against putting it in the theme.)

---
Tags: theming, users
---


# Question
Title: hook_menu not producing expected tab structure, problem?
I'm trying to create a tabbed menu system with `hook_menu()` following the hook documentation and Clive's answer. I am using the following code.

```
/**
 * Implements hook_menu().
 */
function newforms_menu() {
  $items = array();
  $items['admin/config/content/newforms'] = array(
    'title' => 'NewForms',
    'description' => 'Configure web forms via drag and drop.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('newforms_administration_settings'),
    'access arguments' => array('administer newforms module'),
    'file' => 'newforms.admin.inc',
  );

  $items['admin/config/content/newforms/list'] = array(
    'title' => 'Forms',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );

  $items['admin/config/content/newforms/components'] = array(
    'title' => 'Components',
    'type' => MENU_LOCAL_TASK,
    'page arguments' => array('newforms_components_list'),
  );

  return $items;
}

```

I would expect this to produce two tabs, labeled 'Forms' and 'Components', but it does not. I see no tabs. On admin/config/content/newforms/list, I get the same page as admin/config/content/newforms; on admin/config/content/newforms/components, I get "You are not authorized to access this page."

I've cleared cache and ran cron, disabled the module, uninstalled it, reinstalled it, cleared cache, and ran cron; I get the same results.
Both callback argument form functions are defined in newforms.admin.inc.

Do you have any idea as to what is going on here?

# Answer
> 1 votes
What happens is documented in a comment for \_menu\_router\_build(), which the function that builds the menu routers from the `hook_menu()` implementations done from modules.

```
    // If an access callback is not found for a default local task we use
    // the callback from the parent, since we expect them to be identical.
    // In all other cases, the access parameters must be specified.

```

Your fist menu is a `MENU_DEFAULT_LOCAL_TASK`, so you can avoid specifying the access arguments. The other menu is a `MENU_LOCAL_TASK`, and you need to specify the access arguments; failing to do so will cause Drupal to consider the second tab not accessible. That is the reason you don't see any tab: Drupal sees one accessible (i.e. visible) tab, and it doesn't show any tab because Drupal shows tabs only when there are more than one visible tab.

# Answer
> 1 votes
So this works:

```
/**
 * Implements hook_menu().
 */
function newforms_menu() {
  $items = array();
  $items['admin/config/content/newforms'] = array(
    'title' => 'NewForms',
    'description' => 'Configure web forms via drag and drop.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('newforms_administration_settings'),
    'access arguments' => array('administer newforms module'),
    'file' => 'newforms.admin.inc',
  );

  $items['admin/config/content/newforms/list'] = array(
    'title' => 'Forms',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );

  $items['admin/config/content/newforms/components'] = array(
    'title' => 'Components',
    'type' => MENU_LOCAL_TASK,
    'page arguments' => array('newforms_components_list'),
    'access arguments' => array('administer newforms module'),
  );

  return $items;
}

```

I think there were two things happening. I have two theories. One was that Drupal essentially saw two identical tabs and said "this is dumb I'm not doing this" and didn't render the components tab. The other theory is that as soon as Drupal saw a different page argument for the second tab (components), it demanded an access arguments specification. I'm not sure which is true, if both are true, or if both are wrong, but this works.

The moral of the story is that things in hook\_menu don't inherit the way you expect them to sometimes.

EDIT:

This is straight from the hook\_menu documentation.

```
// Make "Foo settings" appear on the admin Config page
$items['admin/config/system/foo'] = array(
  'title' => 'Foo settings',
  'type' => MENU_NORMAL_ITEM,
  // Page callback, etc. need to be added here.
);
// Make "Tab 1" the main tab on the "Foo settings" page
$items['admin/config/system/foo/tab1'] = array(
  'title' => 'Tab 1',
  'type' => MENU_DEFAULT_LOCAL_TASK,
  // Access callback, page callback, and theme callback will be inherited
  // from 'admin/config/system/foo', if not specified here to override.
);
// Make an additional tab called "Tab 2" on "Foo settings"
$items['admin/config/system/foo/tab2'] = array(
  'title' => 'Tab 2',
  'type' => MENU_LOCAL_TASK,
  // Page callback and theme callback will be inherited from
  // 'admin/config/system/foo', if not specified here to override.
  // Need to add access callback or access arguments.
);

```

The second to last line is what tripped me up. For every MENU\_LOCAL\_TASK you must add an access callback/access argument. Mystery solved.

---
Tags: 7, routes
---


# Question
Title: how to make a field disabled, greyed out
I found the hide() function to make a form field hidden. Is there a similar function for making a field disabled or greyed out? I want it to display but not allow it to be edited.

# Answer
I am pretty sure you are looking for the `#disabled` property, eg the Form API Reference Disabled Property that...

> Disables (greys out) a form input element. Setting #disabled to TRUE results in user input being ignored, regardless of how the element is themed or whether JavaScript is used to change the control's attributes.
> 2 votes

---
Tags: forms
---


# Question
Title: Add .active class when certain view is executed using hook_menu
I have a view that is not related with a menu but I need to add .active class to an element of this menu when the view is shown. How can I alter the element adding a class active?

# Answer
> 2 votes
You can use the Context module for this. Context is capable of adding active classes to menu items based on conditions, e.g. path, content type, etc.

# Answer
> 0 votes
The function you want is `menu_tree_set_path()`, and you also need `menu_get_item()` to figure out if to use it, eg:

```
function mymodule_base_init() {
  $item = menu_get_item();

  if ($item['page_callback'] == 'views_page') {
    if ($item['page_arguments'][0] == 'myview' && $item['page_arguments'][1] =='mydisplay) {
      menu_tree_set_path('menu-mymenu', 'some/arbitrary/path/in/the/menu');
    }
  }
}

```

---
Tags: routes
---


# Question
Title: My custom module does not show persian or arabic texts!
I am developing a custom module. When I try to use Persian or Arabic text it does not show the text properly! The texts are shown in black square.
should I add anything?

As you see I installed Farsi language and menus are in Farsi but my custom text in module is not shown!

# Answer
You have to install Locale module. Then you have to configure Arabic language.

* To get our languages hooked in, let's enable the core module, Locale.
* Go to Languages section in admin - admin/config/regional/language:
* Click Add Language button
* Then select Arabic form the drop down and save.

That's all you have to do :)
> 0 votes

# Answer
Looks like fonts rendering issue. I want you to try this:

Insert some inline coding for you module and let me know if its working.

Example:`<p lang="ar" dir="rtl" style="font-family: Verdana, Arial, Tahoma;">your arabic text here</p>`
> 0 votes

---
Tags: 7
---


# Question
Title: Integrate external DB users via their API in Drupal 7
I want to integrate an external API (REST) to login users which are on that external database using the drupal 7 login form on my site.

I have the API specifications for Login, Registering, Getting member details and Check logged in. I also have a URL to test GET and POST requests on that external DB.

How do I integrate it with Drupal database so that users can log in using either Drupal's DB or external DB (integrated with the API)?

I have just discovered Services module but not sure if it is of any help.

I'm not an expert in creating custom modules either so any sample code or any pointers would really help here.

NOTE: External API requests return XML output

# Answer
In order to implement external authentication you need to alter the login forms (`user_login` and `user_login_block`) to alter their validation handlers.

The default validation handlers for the forms are `user_login_name_validate()`, `user_login_authenticate_validate()` and `user_login_final_validate()`. You will need to replace `user_login_authenticate_validate` which is used to check the supplied username/password against local users table. Your replacement should invoke your API to handle the authentication.

Depending on your need, you may want to provide automatic registration (on the Drupal site) of new user on authentication. In such as case, you can use the `user_external_login_register()` function to create the account from your `user_login_authenticate_validate` replacement.

To map the Drupal user to the user on the external system, Drupal provides the `user_get_authmaps()` and `user_set_authmaps()` functions. Note that that user mapping mapping is automatically handled when using the `user_external_login_register()` and `user_external_load()` functions.

The perform your HTTP requests, you can use the `drupal_http_request()` function which usually do the job and support HTTPS. Of course, you can also use another HTTP library.

All of this will have to be done in a custom module and you will need good understanding of Drupal's Form API.

A comment on the documentation page for `user_external_login_register()` provides detailed explanation of the complete process.

Note: The Services module is useful when you need a read/write HTTP-based API for your Drupal site's data. In your case, it would not be usefull since you need to consume an existing API to authenticate the users.
> 1 votes

---
Tags: 8
---


# Question
Title: How to create new type element to form API?
Drupal form API provides some built in type of element to build a form. But I want to create other type such as:

```
$form['mail']['#type'] = 'email';

```

And the output I want it to be:

```
<input class="input-1" type="email" id="edit-mail" name="mail" maxlength="128">

```

So, how can i do that?

# Answer
> 1 votes
You need to implement `hook_element_info()`. See the `form_example_elements.inc` file from the Example: Form API module, and the Creating Custom Elements documentation guide.

Note that the Elements module already provides a form element type for HTML5 mail inputs.

---
Tags: 7, forms
---


# Question
Title: How can I tell drush to use another php.ini file?
I've gone through the setup instructions on https://github.com/drush-ops/drush, but I can't seem to get drush to use a different configuration file, very frustrating.

I've already added the PHP\_INI environment variable to my .bashrc and sourced it, seems like there is something I'm missing.

# Answer
> 3 votes
I copied my php.ini file to my home directory, and then ran:

```
$ PHP_INI=~/php.ini drush status

```

The "PHP configuration" line accurately reflected the new location of my php.ini file, so I believe this is still working on Drush 6.x and master.

# Answer
> 3 votes
drush uses PHP CLI which has it's own `php.ini` file

e.g, in ubuntu:

```
/etc/php5/cli/php.ini

```

You can use that.

---
Tags: drush
---


# Question
Title: Editing a single field on a rendered node
On a given content type called Tracking (which is also a Group), I have a title, OG fields, and a repeating text field called Log. I'd like a member of the OG to be able to enter a value and submit without entering the edit field.

The use case is a mobile site with observers in the field. They won't be editing the entire node. They're just taking notes into a repeating text field?

Is this possible or should I seek a different solution? Or should I just rely on Comments for such a function?

# Answer
Use whatever works for you. I've used the below modules to achieve this type of functionality before.

Look at Field Permissions:

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

And look at Editable Fields to easily edit a field when not on the edit page:

> This module allows CCK fields to be edited on a node's display (e.g. at node/123), not just on the node edit pages (e.g. node/123/edit). It also works within views etc. Anywhere a 'formatter' can be selected, you can select editable (or click to edit).

Or maybe Editable Views, modules:

> Editable Views lets you create Views where the fields can be edited. Fields show both the current value and a form to edit it. A 'Save' button allows saving of all the entities shown in the View.
>
> Editable fields can be added on the base entity as well as on entities brought into the View by a relationship. Other, non-editable fields may be added to the View, in which case they function normally.
> 0 votes

# Answer
Consider the Edit module which is part of the Spark distribution.
> 0 votes

---
Tags: organic-groups, comments
---


title: How to properly call entity form?

text:
# Question
Title: How to properly call entity form?
I have created a wrapper in form of a "page" controller for my entity's form because I needed to do some tasks before it was rendered.

I ended up with this:

```
<?php
  class MyEntityController extends ControllerBase {
    public function mymethod(AnotherEntity $anotherEntity) {
      $myentity = $this->entityManager()->getStorageController('myentity')->create(array());
      $form = $this->entityManager()->getFormController('myentity', 'default');
      $form->setEntity($myentity);
      $form->setParentEntity($anotherEntity);
      $form->setRedirectRoute(array(
        'route_name' => 'some.route',
        'route_parameters' => array('somearugment' => $anotherEntity->id()
      ));
      return $this->formBuilder()->getForm($form);
    }
  }
?>

```

Is this the recommended way in regard of the entity form itself(ie. manually setting the form's entity object)?

# Answer
```
<?php
class MyEntityController extends ControllerBase {
  public function mymethod(AnotherEntity $anotherEntity) {
    // @todo The methods don't exist in core, so it's not clear what object they
    //   should be called on.
    //$form->setParentEntity($anotherEntity);
    //$form->setRedirectRoute(array(
    //  'route_name' => 'some.route',
    //  'route_parameters' => array('somearugment' => $anotherEntity->id()
    //));

    $myentity = $this->entityManager()->getStorageController('myentity')->create(array());
    return $this->entityFormBuilder()->getForm($myentity, 'default');
  }
}
?>

```
> 1 votes

---
Tags: forms, entities, 8
---


# Question
Title: Node template.tpl.php for custom view mode?
I tried this http://www.fredparke.com/blog/using-custom-template-files-different-display-modes-drupal-7, but doesn't work, gives errors and tried this How to provide template for particular view mode? kind of works, but gives errors.

My content type is product\_display and view mode is Product List, created with display suite. I need this, so I could delete h2 title from it, because views forces title output via rendered entity format no matter what.

Errors I get are either Notice: Undefined index: product\_display in mytheme\_preprocess\_node() (line 170 of /template.php).

or this https://i.stack.imgur.com/s6bEn.jpg

# Answer
> 2 votes
You need theme\_hook\_suggestions.

```
    /**
     * Implements hook_preprocess_node().
    */
    function MYMODULE_preprocess_node(&$vars) {

      if ($vars['type'] != 'product_display'){
         return;
      }

      if($vars['view_mode'] == 'product_list'){

        $vars['theme_hook_suggestions'][] =  'node__' . $vars['type'] . '__' . $vars['view_mode'];
      }

  }

```

Now you will be able to use: node--product\_display--product\_list.tpl.php

Make sure you have to change MYMODULE.

If you want to use it from template php then use following code. I also assume you use zen theme:

```
function template_preprocess_node(&$variables) {
 if ($variables['type'] == 'product_display' && $variables['view_mode'] == 'product_list'){
// looks for node--node_type--view_mode.tpl.php in your theme directory
   $variables['theme_hook_suggestions'][] =  'node__' . $variables['type'] . '__' . $variables['view_mode'];
 }
}

```

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


# Question
Title: Is it possible that a view list entities that are not related to other (like a not in (select ...) )?
I have been trying to build a view to list entities A that are **not related** with entities B.

Entities A are users. Entities B are submissions. I need to list users that don't have submissions for a certain year.

In SQL it would be: `select uid from users where uid not in (select uid from submissions where year = NNNN`).

Is there a way to do this using Drupal 7 and Views 3?

# Answer
Views is a simple query builder, it's UI doesn't really support this out of the box.

I recommend looking at Views Custom Conditions:

> This Views Custom Conditions module facilitates the site administrator to inject custom conditions into a views query. ‘Views’ is a powerful and highly flexible module that provides website builders with critical list making abilities. It generates a dynamic SQL query according to views construction for displaying data. So, adding a one more step to filter your data as per your requirement, this module will really be helpful.
>
> This module adds the condition specified by the site admin to any views where clause with the existing conditions implemented by views itself in conjunction with AND operator.

Also if you want to do custom calculations on Fields see Views Raw SQL or Views Calc.
> 0 votes

---
Tags: 7, views
---


# Question
Title: access node field variables in theming view-field
How can I access a filed value of the node that I don't want to display in the view, is there any way to pass the field variable in $fields using view but not include it in display, I'm just want to use this field for checking a condition.

# Answer
You can simply check "exclude from display" for this field.
> 2 votes

---
Tags: theming
---


title: Price Range in Drupal

text:
# Question
Title: Price Range in Drupal
I am using ubercart where I enter different price ranges.

In the left sidebar, I want to display different price ranges like:

```
less than 20$
21-40$
41-65$
more than 65$

```

So that whenever I click on one of these items all products in that price range will show up.

Does anyone have any ideas about how to do this?

Thanks.

# Answer
use facetapi or faceted\_search module i think it helpful..
> 1 votes

# Answer
You could go with the Search API Range module form where you can filter product by the price range ..
> 0 votes

---
Tags: 6, views
---


title: autocomplete tags in textarea?

text:
# Question
Title: autocomplete tags in textarea?
I need a tagging functionality for my content type. The normal term reference tag autocomplete widget has a problem, because I can't find a way to use textarea instead of textfield for it. I would need textarea to be able to see all tags while typing them. One node will have 10-20 tags, some of which are not just words, but expressions. So it all takes place and textfield is not acceptable.

How to enable entering tags into textarea with autocomplete?

# Answer
> 1 votes
You should use Autocomplete Delux module. After installing and enabling the module you can change your tag field widget in your form.

**Autocomplete Delux:**

> This is an enhanced autocomplete element, that uses the JQuery UI autocomplete. It will also implement a widget for taxonomy.

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


# Question
Title: Rules condition if user has certain roles not working at all?
I have 2 roles:

* Customer
* Moderator

I have created a Rule:

**Event.** On account creation

**Condition.** If user has role: Moderator (and checked reverse, so when user doesn't have a role Moderator it should return TRUE), also as data selector i chose "account"

**Action.** Assign role: Customer, selector "account"

However, when i logged in with a user with role Moderator and create a new user with role Moderator it automatically adds the role customer as well. So my condition isn't working?

**UPDATE** I have tried in conditions: \[site:current-user\], still it adds the "Customer" role to a newly created account with a role Moderator by Moderator

# Answer
Sorry, ignore my last comment.

You need a condition of "user as role" set to "site:current-user". Then select the role that is required which is "moderator". Leave everything else unchanged and save.

You need an action of "add role" This action defaults to "account" so leave it as is. Select the role you want to add, and save.
> 3 votes

---
Tags: 7, rules
---


# Question
Title: Retrieve file URL when upload form is submitted
I have the following code in my form.

```
function video_subtitles_menu() {
  $items = array();

  $items['video_subtitles_test/upload'] = array(
    'title' => 'Upload Subtitle', //page title
    'description' => 'Uploading subtitle for videos',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('video_upload_subtitles_form'),
    'access callback' => TRUE
  );

  return $items;
}

function video_upload_subtitles_form($form, &$form_state) {
  $form = array('#attributes' => array('enctype' => 'multipart/form-data'));
  $form['video_name'] = array(
    '#title' => t('Name Of the video'),
    '#type' => 'textfield',
  );

  $form['sub_file'] = array(
    '#type' => 'file',
    '#title' => t('Upload video'),
    '#size' => 48,
    '#description' => t('Pick a video file to upload.'),
  );

  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

  return $form;
}

function video_upload_subtitles_form_validate() {
  if (!file_check_upload('upload')) {
    form_set_error('upload', 'File missing for upload.');
  }
}

function video_upload_subtitles_form_submit($form, &$form_state) {
  $video_name = $form_state['values']['video_name'];
  $file = file_save_upload('sub_file', array());
  print "<pre>";print_r($file);// no response here
  drupal_set_message(t('The form has been submitted.'));
}

```

On the submission handler, it only returns the text field. I don't get anything from file upload field, when I use `file_save_upload()`.

This is the response which I get in Firebug. I tried uploading text and Excel files.

>

What I am trying to do is creating a block where users can upload a file; I then need to get to upload it to a CDN.

# Answer
found the solution here.I am not sure what is the core issue but below is the solution

This was the comment in the above link where I found solution.

> More than likely eveyone who is having a problem here has been developing on their local computer, then are tryng to migrate their system to a remote server. When you do this, you are probably moving your setting for directory paths along as well.
>
> For example the temp path for your images is probably different than the image temp path on your host system.
>
> I recommend this test in Drupal 6.14. goto /admin/settings/file-system
>
> and look at your temporary directory... if its glaring red, then try renaming it to something like: /tmp. if that does not work, try renaming to just tmp ( no forward slash)
>
> Next step to test this will be to upload an image or file. I tested it by uploading a new logo. But remember, that if you do a FULL DB dump from phpmyadmin from your local computer to the new host, you will probably see this problem again.

For Drupal 7 guys I just went to admin/config/media/file-system , so basically find out where the file system is in your config area and I change the '/tmp' to 'tmp'.

After changing it was able to print the file object :)

```
stdClass Object ( [uid] => 1 [status] => 0 [filename] => 3-26-2014 12-15-54 PM.png [uri] => temporary://3-26-2014 12-15-54 PM.png [filemime] => image/png [filesize] => 30536 [source] => private_file [destination] => temporary://3-26-2014 12-15-54 PM.png [timestamp] => 1395828492 [type] => image [field_replacement] => stdClass Object ( [uid] => 1 [status] => 0 [filename] => 3-26-2014 12-15-54 PM.png [uri] => temporary://3-26-2014 12-15-54 PM.png [filemime] => image/png [filesize] => 30536 [source] => private_file [destination] => temporary://3-26-2014 12-15-54 PM.png [timestamp] => 1395828492 [type] => image ) [fid] => 3102 )

```

Hope it help someone.
> 0 votes

---
Tags: 7, forms, files
---


# Question
Title: how to change address bar by its content-type/title of node
I have a content type where user allowed to add the content, which create a node of that particular content, when i click to that content for detail page it re-direct to the node page created by authenticated user, but the address bar is something like

> www.myexample.com/node/23 23

or some no. Now i want the address should be

> www.myexample.com/(content-type)/(node-title)

please help me.

Thanks

# Answer
> 3 votes
1. Install Pathauto
2. Visit the URL Alias Patterns page at /admin/config/search/path/patterns
3. Choose an appropriate token-based pattern for your content type in the relevant text field, before saving. (e.g. `[node:content-type]/[node:title]`)
4. Visit the "Bulk Update" tab and generate all Content aliases.

From now on any time you (or anyone else) creates a node of that type, the URL alias will be automatically set.

---
Tags: nodes, path-aliases
---


# Question
Title: How do I link fields of a 'user content type' to the actual logged in user?
I'm using the User Content Type module (Drupal 7) in order to store some fields for each user, such as "zip code."

Now, in this node\_edit page, I made a variant for a Catalog node, for a specific role. (Let's say "salesman".)

How do I link the actual logged in user with their respective *User* node, to show and store the "zip code" field in the Catalog node?

# Answer
> 0 votes
In Drupal 7, the simplest way to associate fields with a specific user is via Admin =\> Configuration =\> People =\> Account settings =\> Manage fields.

Because of its simplicity, I recommend this approach as a starting point. If it's not flexible enough, consider the contributed Profile 2 module.

---
Tags: 7, nodes, users
---


title: Error in executing drush command

text:
# Question
Title: Error in executing drush command
I am trying to execute drush command from my project root directory and i am getting following error

bootstrap a site that has not been installed or does not have a configured database. In this case you can select another site with a working database setup by specifying the URI to use with the --uri parameter on the command line. See `drush topic docs-aliases` for details. * connect the database through a socket. The socket file may be wrong or the php-cli may have no access to it in a jailed shell.

# Answer
This message occurs with a working site if the site settings.php file is not in the *sites/default* directory but a *sites/example.com* directory. In that case to specify the uri of the site you wish to address you use the syntax

`drush --uri=example.com [command`\]
> 0 votes

# Answer
Could you provide the output what you get when you run the following command from your drupal root directory

```
drush status --uri="application-uri" --debug

```

You should be seeing something like below in the output

```

 Drupal version                  :  7.22

 Site URI                        :  www.xyz.com
 Database driver                 :  mysql

 Database hostname               :  localhost
 Database username               :  DB-UserName

 Database name                   :  DB-Name

 Database                        :  Connected

 Drupal bootstrap                :  Successful

 Drupal user                     :  Anonymous

 Default theme                   :  seven
 Administration theme            :  seven

 PHP configuration               :  /etc/php5/cli/php.ini

 Drush version                   :  5.10.0

 Drush configuration             :  /etc/drush/drushrc.php

 Drupal root                     :  /var/www/

 Site path                       :  sites/default

 File directory path             :  sites/default/files/
 Private file directory path     :  /mnt/tmp/files-private/
 Temporary file directory path   :  /mnt/tmp/

```

Check whether you could see the below.

```
Database                        :  Connected
Drupal bootstrap                :  Successful

```

If you see them both then you Drupal is able to connect to the Database, If not then they are not able to connect

You need to check the **settings.php** in that case.

Also let me know whether you Drupal Front end loads with out any issue
> 0 votes

---
Tags: 7, drush
---


title: Trying to create a custom block

text:
# Question
Title: Trying to create a custom block
Hi I am trying to create a custom block but it is not appearing in the block listing is there something missing in my code.

```
   <?php

  $view = views_get_view('schedule_list2');
  $view->execute();
  print $view->render();

  $view = views_get_view('next');
  $view->execute();
  print $view->render();
/**
 * Implements hook_block_info().
 */
function custom_block_block_info() {
  $blocks = array();
  $blocks['my_block'] = array(
    'info' => t('My Custom Block'),
  );

  return $blocks;
}
/**
 * Implements hook_block_configure().
 */
function custom_block_block_configure($delta='') {
  $form = array();

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

      // File selection form element
      $form['file'] = array(
        '#name' => 'block_image',
        '#type' => 'managed_file',
        '#title' => t('Choose an Image File'),
        '#description' => t('Select an Image for the custom block.  Only *.gif, *.png, *.jpg, and *.jpeg images allowed.'),
        '#default_value' => variable_get('block_image_fid', ''),
        '#upload_location' => 'public://block_image/',
        '#upload_validators' => array(
          'file_validate_extensions' => array('gif png jpg jpeg'),
        ),
      );
      break;
  }
  return $form;
}

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

      // Saving the file, setting it to a permanent state, setting a FID variable
      $file = file_load($edit['file']);
      $file->status = FILE_STATUS_PERMANENT;
      file_save($file);
      $block = block_load('custom_block', $delta);
      file_usage_add($file, 'custom_block', 'block', $block->bid);
      variable_set('block_image_fid', $file->fid);
      break;
  }
}
?>
<?php
/**
 * Implements hook_block_view().
 */
function custom_block_block_view($delta='') {
  $block = array();
  switch($delta) {
  case 'my_block' :
    $block['content'] = my_three_upcoming_events();
    break;
  }
  return $block;
}
/**
 * Custom function to assemble renderable array for block content.
 * Returns a renderable array with the block content.
 * @return
 *   returns a renderable array of block content.
 */
function my_three_upcoming_events() {
  $output = '';
  $now_events = views_get_view_result('schedule_list2');
  $upcoming_events = views_get_view_result('next');
  $max_events = 3;
  // Make a big list of events now; upcoming events will be on the end of this list.
  $all_events = $now_events + $upcoming_events;

  for ($i=0,$z=$max_events;$i<$z;$i++) {
    $node = node_load($all_events[$i]['nid']);
    $output .= '<div>' . l($node->title, '/node/'.$node->nid) . '</div>';
  }
  return $output;
}
?>

```

# Answer
Make sure your module is named custom\_block to match the function names you have used for your hooks. If you have to change the name of your module you will need to re-enable it. Technically you should uninstall the module, then rename and re-enable - unless it isn't properly installed ans you can't uninstall it. This will keep unwanted data out of your database.

You also should not be printing things outside of functions in module files, like the views code at the top is doing.

Printing markup should be done at the theme level in templates, or in appropriate functions in your module (like you are going in your hook\_block\_view()).
> 0 votes

---
Tags: 7, blocks
---


# Question
Title: Preventing other sites from embedding Drupal page
How do I prevent other sites from embedding a page from my Drupal site using an iframe? Ideally, I'd like the parent window to redirect to my website if this happens, or alternatively redirect the iframe to an error page.

Any modules/hacks/code/tips?

Thanks

# Answer
The technique that you want to employ is called framebusting (or framekilling).

The Frameprevention does this. However, I typically do this manually, as I want it to happen as soon as possible, or I need to do it a certain way to pass an automated test.

Typically, I will edit html.tpl.php to add a `no-js` class onto the `<html>` tag, then then add this code bit directly after the opening `<head>`:

```
<head<?php print $rdf->profile; ?>>
  <script>
    // http://www.456bereastreet.com/archive/201209/tell_css_that_javascript_is_available_asap/
    document.documentElement.className = document.documentElement.className.replace(/(\s|^)no-js(\s|$)/, '$1js$2');
  </script>
  <?php // bypass render array so this is guaranteed to be very first thing ?>
  <style>html.js { display:none }</style>
  <script>
    if (self == top) {
      document.documentElement.style.display = 'block';
    } else {
      top.location = self.location;
    }
  </script>

```

This does force users to have Javascript enabled in their browsers, which is a common problem with framebusting. I cannot find the exact reference for the technique above, but I think it came from OWASP.

You can also implement X-Frame-Options:

```
function MYTHEME_html_head_alter(&$head_elements) {
  $head_elements['mytheme_x_frame_options'] = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => array(
      'name' => 'X-Frame-Options',
      'content' => 'DENY',
    ),
  );

  $head_elements['mytheme_x_frame_options']['#attached']['drupal_add_http_header'][] =
    array('X-Frame-Options', $head_elements['mytheme_x_frame_options']['#attributes']['content']);
}

```

Keep in mind that you may need additional logic to account for legitimate `<iframe>` elements in your site. Some ctools modals come to mind, as well as some WYSIWYG situations.
> 4 votes

---
Tags: 7, nodes
---


title: Ajax ignoring my default_value

text:
# Question
Title: Ajax ignoring my default_value
I have a drupal form that contains a select box. Next to the select box is a link that pops a ctools modal up with an inner form that adds a value to the database table that drives the original select box. When someone clicks submit on the modal form, I would like to rebuild the select box on the original form and set the new value to the default. I've had success with adding the new elements to the select box by doing some ajax in the form\_submit hook for the modal form, but it seems like Drupal ignores the value in #default\_value in my render array. I have the following in my form\_submit hook after the database update and after getting the render array from another function:

```
if(isset($id)) {
   $newdata['data_source']['#default_value'] = $id;
}
$commands = array();
$commands[] = ctools_modal_command_dismiss();
$commands[] = ajax_command_html('#measure-data-source', drupal_render($newdata));
print ajax_render($commands);
exit();

```

Again, the select box is getting the new value, and my render array seems fine. I just can't get it to select the new value by default.

# Answer
> 0 votes
Alright, so this is slightly hackey, but I got this to work. I totally gave up on trying to set a default value in the render array, and instead did the drupal\_render and set it to a variable. I then modified the html directly in the variable. The code I originally posted now looks like this:

```
if(isset($id) && is_numeric($id)) {
  $newrender = drupal_render($newdata);
  $newrender = str_replace('value="'.$id.'"', 'value="'.$id.'"  selected="selected"', $newrender);
}

$commands = array();
$commands[] = ctools_modal_command_dismiss();
$commands[] = ajax_command_html('#measure-data-source', $newrender);
print ajax_render($commands);
exit();

```

If anyone on here has a more elegant solution, I'd be happy to know the "correct way" of doing this, but this produces the desired result.

---
Tags: forms, ajax, chaos-tool-suite
---


# Question
Title: How to browse the server to upload files from there in Drupal 7
I need to upload the audios and videos on server in a specific folder via FTP and then let the content managers to select them when they want to upload any of them in `add/content` path (because it takes a long time to upload them via the Add Content user interface). Is there such a capability in Drupal 7?

# Answer
> 2 votes
\****UPDATE\****

Best option is to use https://drupal.org/project/imce\_filefield This is specially made to upload files to sites/default/files and add them.

Just configure imce and the field.

Uninstall file field sources, because it's not compatible to have them at the same time

---

*Old anwser*

You could use the FileField Sources module. To browse the server it looks like you need to use this with IMCE. From the FileField Sources project page:

```
The FileField Sources module expands on this ability by allowing you to
select new or existing files through additional means, including:

    Re-use files by an auto-complete textfield
    Attach server-side files uploaded via FTP
    Transfer files from a remote server (cURL required)
    Select existing files through the IMCE file browser

```

This question / answer was on another question: Image Field Browser Option

---
Tags: files
---


# Question
Title: creating messages that appear after content is created
I am trying to create an a message to appear with a link to the content when the new content is created

Thanks for any help on this

# Answer
> 0 votes
Using RULES you can achieve it, as suggested by ROOBY

* Create new RULE
* Add action
* Create Node view link

# Answer
> 0 votes
This could be done with some code in a custom module:

```
hook_node_insert($node) {
    if($node->type=='my_content_type') {
        drupal_set_message(t('New content created: :link', array(':link' => l($node->title, 'node/'.$node->nid))));
    }
}

```

---
Tags: 7, nodes
---


# Question
Title: How to programatically get the product id of newly added product using the commerce form
I allow users to create their own products using the default commerce product add form (/admin/commerce/products/add/product). Programatically, I need to get the product ID and do more processing.

I have a submit handler attached like this (I use it to redirect users to a custom page):

```
$form['actions']['submit']['#submit'][] = 'my_module_redirect_handler';

```

However, I don't seem to have any information about the newly added node. How can I obtain it?

# Answer
> 0 votes
Provided that your additional submit handler is invoked after default one (which by looking how you added it, is the case), you can access **nid** of the node created as follows:

```
function my_module_redirect_handler(&$form, &$form_state) {
    $node_id = $form_state['values']['nid'];
}

```

Now that you have **nid** you should be able to do required processing.

Hope that helps.

---
Tags: commerce
---


# Question
Title: Search API and Domain Access: Filter user per domain
I've got a site with multiple domains using Domain Access. I want to display a search form on each site that searches for users on that site.

I'm using a modified version of the code here (that code works fine when searching for nodes) but it doesn't work. When searching it always return an empty result.

Here's my code:

```
/**
* Implements hook_entity_property_info_alter().
*
* Adds an entity property for the domain access of the user.
*/
function custom_search_users_entity_property_info_alter(&$info) {
  $properties = &$info['user']['properties'];

  $properties['custom_search_users_domain_access'] = array(
    'label' => t('Domain Access Information'),
    'description' => t('The domains to which the user has access.'),
    'type' => 'list<integer>',
    'getter callback' => 'custom_search_users_get_domain_info',
  );
}

function custom_search_users_get_domain_info($data, array $options, $name, $type, $info) {
  return (!empty($data->domain_user) ? $data->domain_user : NULL);
}

/**
* Implements hook_search_api_query_alter().
*
* Adds a filter for the current domain.
*/
function custom_search_users_search_api_query_alter(SearchApiQueryInterface $query) {
  $domain = domain_get_domain();

  $query->condition('custom_search_users_domain_access', $domain['domain_id']);
}

```

So basically what I've changed in my code is the use of $data-\>domain\_user instead of $data-\>domain to comply with the user object.

Anyone got any idea of why this doesn't work?

# Answer
> 1 votes
I think your approach is just fine, but you forgot to index your field. You've to check the field you created on the field page (`admin/config/search/search_api/index/**your_index**/fields`)

Once checked, you'll be able to index your extra field and by so, filter on domain.

---
Tags: search, domain-access
---


title: How to transfer data between 2 fields

text:
# Question
Title: How to transfer data between 2 fields
I have profile 2 installed. I added a new field called "maiden name" to my profile form using the "add existing field" option. I had previously created this field in the default user registration form.

Now I want to delete the field (maiden name) from the user registration form. Please how can I transfer the data/values to the new field in my profile 2 form.

Thank you.

# Answer
This in untested code so you will need to adjust the paths to get the correct values however it shows the general approach to take:

```
$uids = db_query("SELECT uid FROM user WHERE status=1")->fetchCol();

foreach($uids as $uid) {
    $account = user_load($uid);
    $profile2 = profile2_load_by_user($account, 'profile_2_type_name_here');
    $profile2['maiden_name']->field_maiden_name[LANGUAGE_NONE][0]['value'] = $account->field_maiden_name[LANGUAGE_NONE][0]['value'];
    profile2_save($profile2);
}

```
> 0 votes

---
Tags: entities, users
---


# Question
Title: How to rename address labels on Address field module?
I wanted to know if it's possible to change the input labels on the address field module 'Address 1' and 'Address 2' without using the string overrides module?

I want to be able to change them to say 'Address line 1' and 'Address line 2'.

Can this be done in a template preprocess function?

# Answer
> 2 votes
This can be done with hook\_form\_alter:

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

    //drupal_set_message("Form ID is : " . $form_id);

    switch($form_id) {

        case 'MY_FORM_ID':

            // dpm($form);

            // $form['NAME_OF_YOUR_FIELD'] - this is the field you want to edit

            // check that the field is set before looping over values
            if(isset($form['NAME_OF_YOUR_FIELD'][LANGUAGE_NONE])) {
                // loop over each values passing $item by reference
                foreach($form['NAME_OF_YOUR_FIELD'][LANGUAGE_NONE] as &$item) {
                    if(is_array($item) && isset($item['street_block'])) {
                        $item['street_block']['thoroughfare']['#title'] = 'Address Line 1';
                        $item['street_block']['premise']['#title'] = 'Address Line 2';
                    }
                }
            }
            break;
    }

}

```

I found the path to the variable I wanted to change by outputting the $form array to the message area using devel's dpm function, and then searching though the array for the value "Address 1" using the search krumo module.

---
Tags: forms
---


# Question
Title: How to use $query->add_where_expression in hook_views_query_alter
I'm trying to use `hook_views_query_alter()` to select some nodes based on a calculation using two fields in that node. I can't find much documentation or many examples that help me understand how this works.

I could use Views PHP, but this module is very buggy in Drupal 7.

I think I need to use $query-\>add\_where\_expression() but I can't work out how to use it.

My view is called "latlong", and as a test to see if I have the right approach, I've tried to select nodes based on the value of field\_latitude. Copying other functions i've seen through googling, this is my best guess, but it's not working. I know one of my nodes has the value 53.9519 so if my syntax is right I should get a row back, but I don't:

```
function my_module_views_query_alter(&$view, &$query) {
  switch($view->name) {
    case 'latlong':
      $query->add_where_expression(0,'field_data_field_latitude.field_latitude_value = 53.9519');
      break;
  }
}

```

If I `print_r($query->where[0])` I get:

```
Array (
  [conditions] =>
    Array (
      [0] =>
        Array (
         [field] => field_data_field_latitude.field_latitude_value = 53.9519
         [value] => Array ( )
         [operator] => formula ) )
         [args] => Array ( )
         [type] => AND )

```

What am I doing wrong?

# Answer
If you look at the documentation for views\_plugin\_query\_default::add\_where\_expression(), you will notice the following note. (The emphasys is mine.)

> The caller is reponsible for ensuring that all fields are fully qualified (TABLE.FIELD) and that **the table already exists in the query**. Internally the dbtng method "where" is used.

Looking at this Stack Overflow question, I would get your code should be the following one.

```
function mymodule_views_query_alter(&$view, &$query) {
  switch($view->name) {
    case 'latlong':
      $alias = $query->add_table('field_data_field_latitude');
      $query->add_where_expression(0, "$alias.field_latitude_value = :latitude", array(':latitude' => 53.9519);
      break;
  }
}

```

Since the latitude is a floating point, I would use a comparison that is different from `$alias.field_latitude_value = :latitude`, for example checking the latitude is inside the range \[$latitude - $epsilon, $latitude + $epsilon\].
> 8 votes

# Answer
The query dump you provided definitely looks wrong.

If you read through `views_plugin_query_default::add_where_expression()`, you will see that the the `$snippet` is just the clause, and that you should really be adding the `{table.field}` blip with an placeholder.

I think that this is what you really want

```
$query->add_where_expression(0, 'field_data_field_latitude.field_latitude_value = :latitude', array(':latitude' => 53.9519));

```

However, doing exact comparisons with floating point values with decimal portions can be troublesome. You should test this with something simple (say, `node.uid`) to be double sure. If the simple test works, but yours doesn't then I suspect you are running into floating point problems.

You can also preview the SQL to see exactly what is being generated. Copy/paste this into your favorite SQL tool and see what is going on.

You mention that you are trying to find the twenty nodes closest to a point. Your approach is wrong for this. You need to add a correlation field that gets returns the distance between the node in that row and your point, sort ascending on it, and then limit to 20 results. This isn't a total pain, but not simple, either (I just did this on a project).

Thankfully, there are at least two modules that can do this for you. One is Geofield, the other is Location. Both integrate with Views, and I know Geofield support proximity sorting, and I am pretty sure Location does to. Using one of these may require converting your fields to use the ones defined by the module, but those two modules provide other benefits, too.
> 1 votes

---
Tags: views
---


title: counter on each images in view

text:
# Question
Title: counter on each images in view
I have a view that display 8 images(which links to their particular node) uploaded by the all users, now i want to display a counter which counts total number of times that image or that image link have been visited/viewed.

Please help me.

I think ..Its like if you on the left of this Question answer section on this site they have mentioned three things 1.Asked Today 2.Viewed 4 times(or total no. of times viewed ) 3.etc

my requirement is second. Thanks

# Answer
Sounds like Node view count module would be suitable, especially as it integrates with views.
> 0 votes

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


# Question
Title: Total number of likes on views images and social networking?
I have a view that displays 8 images (which links to their particular node) uploaded by the all users. Now I want to display a counter which counts total number of likes on that post either by facebook or on the site.

Can I link the image like with the facebook likes of that particular image post?

# Answer
> 0 votes
To count how many times users have liked a particular node maybe checkout the Like Button module.

---
Tags: views
---


title: Get node path via javascript

text:
# Question
Title: Get node path via javascript
I am attempting to add history states to view items that are loaded using the infitine scroll module. On my first attempt, I am adding the following code to the infinite scroll.js file in the load section. I have partial success in using Drupal.settings.basePath variable, however, I would like to get the node that gets loaded as opposed to the baseurl. Is there a call in javascript for this? Here is my sample so far:

```
var baseUrl = Drupal.settings.basePath;
history.pushState('', '', baseUrl);

```

# Answer
> 0 votes
You can add the node ID manually to Drupal settings with `drupal_add_js()`, for example from a preprocess function.

```
// PHP
$setting = array('setting_1' => 'value_1', 'setting_2' => 'value_2');
drupal_add_js($setting, 'setting');

```

```
// JavaScript
var nodeId = Drupal.settings.setting_1;

```

---
Tags: javascript, views
---


# Question
Title: How to grant "edit any file" permission only to files attached to a certain node type?
The same question in other words:

**How a file can inherit edit permission from node permission which is attached to?**

Hi all,

I have 2 node types: articles and cars.

A file entity field is attached to both so users, through media module, can attach images to articles and cars.

Now I want a moderator role that can edit files attached to cars ONLY.

How to accomplish this?

Granting "Edit any files" to Moderator allow him to edit every files, articles attached files also, but I don't want this.

Thank you for any help

# Answer
> 0 votes
Maybe I've found a workaround.

Files editing is accessible in a general direct way (bypassing their nodes) by the following url:

```
www.mysite.com/file/[fid]/edit

```

So only through this link a Moderator can have access and edit ANY file (please tell me if this is correct).

So, doing:

```
/**
 * Implementation of hook_menu_alter()
 */
function helper_menu_alter(&$items) {
  // Provide custom access callback for direct files edit url
  $items['file/%file/edit']['access callback'] = 'helper_direct_file_edit_url_access_callback';
}

/**
 * Custom access callback
 */
function helper_direct_file_edit_url_access_callback() {
  // Disallow direct files edit url to everyone but superadmin
  if (!_helper_is_user_superadmin()) {
    return FALSE;
  }
  return TRUE;
}

```

Moderators with "Edit any file" permission (and everyone in anycase) cannot directly access to edit files, but they can edit files with media module through nodes they have edit access to (e.g. cars)

Do you think guys this could be a good workaround?

There is a better way to accomplish this?

Thank you very much

---
Tags: 7, files
---


title: Display image field from nid

text:
# Question
Title: Display image field from nid
I'm trying to print the image field from a node using the nid in the url.

$nid = $\_GET\['field\_item\_request'\];

Is there a specific way to do this?

# Answer
```
$nid = arg(1);
$node = node_load($nid);
$image = field_get_items('node', $node, 'field_item_request');
$output = field_view_value('node', $node, 'field_item_request', $image[0]);
print render($output);

```
> 1 votes

# Answer
I needed to add a specific style to my image. So I modify the code above to fit my needs. Hopefully it will help somebody out.

```
  $nid = $_GET['field_item_request'];
  $node = node_load($nid);
  $image = field_get_items('node', $node, 'field_image');
  $image_output = render(field_view_value('node', $node, 'field_image', $image[0], array('settings' => array('image_style' => 'medium', 'label' => ''))));

  print render($image_output);

```
> 0 votes

---
Tags: entities, theming, media
---


title: Adding an email field to comment forms

text:
# Question
Title: Adding an email field to comment forms
I have given permission for anonymous users to comment on my site. But the default comment form being displayed does not have a field for email address in it. Also, I have comment notify installed. The email field to be displayed on the comment field should be recognized by comment notify as the email address of the commentor so that it can send notifications. Also, the email field should not be made visible for logged in users. I cannot solve all the three problems at once. Any help will be greatly appreciated.

# Answer
> 2 votes
I think you can make this work as follows:

1. In the Permissions settings via admin/people/permissions, ensure ANONYMOUS USER can *View comments*, *Post comments*, and *Subscribe to comment notifications*
2. In the Comment Notify settings via admin/config/people/comment\_notify, ensure comment notification is enabled for the content type(s) you care about
3. For each content type you care about, e.g. for Basic page via admin/structure/types/manage/page, expand the Comment settings tab in the vertical menu at the bottom of the page and ensure "Anonymous commenting" is set to *Anonymous posters must leave their contact information*

---
Tags: 7, comments
---


title: AJAX link error (form API)

text:
# Question
Title: AJAX link error (form API)
I have an AJAX link and a callback function. The problem is that when I click the link an error is thrown.

I have absolutely no idea where did I make an error, the debug information unfortunately doesn't help.

As I understand the AJAX and Form API, the TSTDiv should be replaced with the TST link therefore two links should be visible on the page, right? The problem is, it not only doesn't work, but even throws an (really unhelpful) error.

The callback function / menu hook work fine (correct output is rendered when you access the URL (of the AJAX request) directly).

Code:

```
function HOOK_menu() {
  $items = array();

  $items['groups_hierarchy_load_more'] = array(
    'page callback' => '_fmg_agh_hierarchy_load_more',
    'access callback' => 'user_access',
    'access arguments' => array('Can view all groups'),
    'type' => MENU_CALLBACK,
  );
...

  $page_array['l'] = array(
    '#type' => 'link',
    '#title' => 'TEST',
    // Note the /nojs portion of the href - if javascript is enabled,
    // this part will be stripped from the path before it is called.
    '#href' => 'groups_hierarchy_load_more/' . '5' . '/nojs',
    '#ajax' => array(
      'wrapper' => 'TSTDiv',
      'method' => 'replace',
    ),
  );

  $page_array['d'] = array(
    '#type' => 'markup',
    '#prefix' => '<div id="TSTDiv">',
    '#suffix' => '</div>',
  );
...

function _fmg_agh_hierarchy_load_more($group_id, $ajax) {
  $page_array = array();

  $page_array['tst']['data'] = array(
    '#type' => 'link',
    '#title' => 'TST',
    // Note the /nojs portion of the href - if javascript is enabled,
    // this part will be stripped from the path before it is called.
    '#href' => 'groups_hierarchy_load_more/' . 'TST' . '/nojs',
  );

  return $page_array;
}

```

Error:

```
An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /drupal7/?q=groups_hierarchy_load_more/5/ajax
StatusText: OK
ResponseText:
localhost
@import url("http://localhost/drupal7/modules/system/system.base.css?n3277e");
...

```

# Answer
While I still don't know where the problem is (it should work this way) I've found a solution.

Instead returning the whole $page\_array in callback function and hoping that Drupal will understand it and replace the div specified in `'#ajax' => array('wrapper' => 'TSTDiv',...` property of the link with it you can simply use ajax commands and 'return' something like this:

```
$commands[] = ajax_command_replace('#TSTDiv', render($page_array));
$page = array('#type' => 'ajax', '#commands' => $commands);
ajax_deliver($page);

```

And vuala it works just fine (and looks more professional at the same time!).

Would still appreciate and answer why the original approach didn't work, though.

BTW: I didn't know the AJAX commands before.
> 0 votes

---
Tags: forms, ajax, navigation
---