title: How to Disable some Page for View

text:
# Question
Title: How to Disable some Page for View
I have a website. In which I need to disable some pages for full view. Because I am using them in view. I don't need full view.

Is there is anything in D7 so we can stop full view of Page

# Answer
> 1 votes
Go to your nodes which you want to disable from viewing.

Go to node edit and find 'Published options' and uncheck *published* option.

So now you want to display them at view's page. So go to your *View* *Filter criteria* and select *Published* 'No'

That's it. Now you can see the unpublished nodes at *view*'s output but not at node output.

There is another way you can do it.

If those nodes (which you want to disable at node output) are all belongs to same content type, you can manage them under content type display settings. You can manage *view modes* there.

# Answer
> 0 votes
You could disable the Title-Link and any other Link (e.g. from images) in your field-settings, that lead to your nodes. This is a way to obscure the ways to nodes...

---
Tags: 7, views
---


# Question
Title: Automatically Fill a Second Term Reference Field in a Node Based On Filled Value from a First Term Reference Field
Given the following...

* A vocabulary (let's call Vocab1) with terms that each have an added term reference field referencing a single term from another vocabulary (let's call Vocab2).
* A node that has two term reference fields, the first for a single term from Vocab1 and the second for a single term from Vocab2

would it possible to automatically fill the second term reference field from Vocab2 based on what's is filled in the first term reference field containing a term from Vocab1?

# Answer
Have look at the following modules

Reference field option limit

> This module allows reference fields of several types to have their widgets' available options limited by the values of other fields in the current entity.

Hierarchical Select

> This module defines the "hierarchical\_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy.
> 0 votes

---
Tags: taxonomy-terms
---


title: How do I add a project?

text:
# Question
Title: How do I add a project?
How do I add a Drupal 8 project (e.g. the Panels module) to my site?

# Answer
Here are the steps to install from UI

Go to Manage \>\> Extend

Click on Install new module.

Install From URL or upload a module archive to install.

**Second Method:**

Just download module archive zip and extract to

yoursite \>\> modules

You can place downloaded and custom modules in modules directory.

Here in the given example installation directory is d8.

That's it. go to your module list. you can find your downloaded module there.
> 3 votes

# Answer
The third solution would be:

1- Install drush : https://www.drupal.org/node/1791676

2- Move to the local home directory of your drupal website inside the Command Prompt / Terminal (according to your OS type)

3- Type this command in the Command Prompt / Terminal (according to your OS type):

`drush en panels -y`
> 5 votes

---
Tags: 8
---


# Question
Title: Open Public Distribution on IIS 8.0 and SQL Server 2012 R2
I am having some issues on installing **Open Public** distribution **(openpublic 7.x-1.2)** on **IIS 8.0** and **SQL Server 2012 R2** **without** **Web PI**. Have any one tried it before in such way ? Is it possible ? I can install "**standard**" distribution on **IIS 8.0** and SQL Server 2012 R2 **without** Web PI, **without** any major issue.

This is the issue I am experiencing during installation of Open Public distribution:

```
An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging information follows.
Path: http://endri.net/install.php?profile=openpublic&locale=en&id=1&op=do
StatusText: OK
ResponseText: Home | Drupal @import url("http://endri.net/modules/system/system.theme.css?0"); .... Home Installation tasksChoose profile(done)Choose language(done)Verify requirements(done)Set up database(done)Install profile(active)Configure siteVerify Apps supportInstall AppsFinished Status message You can now configure the CAPTCHA module for your site. SQLSTATE[42000]: [Microsoft][SQL Server Native Client 11.0][SQL Server]Procedure or function dbo.CONCAT has too many arguments specified.

```

and

```
Warning: file_put_contents(temporary:///.htaccess): failed to open stream: "DrupalTemporaryStreamWrapper::stream_open" call failed in file_create_htaccess() (line 494 of C:\inetpub\wwwroot\includes\file.inc).

```

# Answer
I have **solved**, the issue is at this file on this location:

```
C:\inetpub\wwwroot\profiles\openpublic\modules\contrib\comment_notify\comment_notify.install

```

the statement on line 24

```
$comments_select->addExpression("MD5(CONCAT(:salt,c.mail,COALESCE(u.mail, u.init), c.uid,c.name,c.nid,c.hostname, c.cid))", 'notify_hash', array(':salt' => $salt));

```

should be replaced with

```
$comments_select->addExpression("MD5(CONCAT(CONCAT( CONCAT(:salt, c.mail) , CONCAT(COALESCE(u.mail, u.init), c.uid) ),CONCAT( CONCAT(c.name, c.nid) , CONCAT(c.hostname, c.cid) )))", 'notify_hash', array(':salt' => $salt));

```

because "**Drupal 7 driver for SQL Server and SQL Azure**" drops the **SQL Server** stored procedure `CONCAT` and creates a new one with only 2 parameters.
> 1 votes

# Answer
The specific error seems to be a permissions problem that prevents writing the .htaccess file, probably in your DOCROOT.

The more general problem is that anything is being done with an .htaccess file on an IIS server. See http://www.iis.net/learn/application-frameworks/install-and-configure-php-applications-on-iis/translate-htaccess-content-to-iis-webconfig for why that should not need to be attempted in your installation.

I expect either that Open Public does not support IIS (most likely) or you have failed to provide an installation parameter specifying IIS rather than Apache as the webserver.
> 0 votes

---
Tags: distributions
---


# Question
Title: Fatal error after subtheming Commerce Kickstart Admin Theme
I am trying to subtheme Commerce Kickstart Admin Theme. I have copied all the folders and files to sites/all/themes/my\__admin\_subtheme, and changed the appropriate lines in my\_admin\_subtheme.info.

When I go to /admin/appearance, and change the section Administration theme to My Admin Theme, I get an error in template.php telling that the function commerce\_kickstart\_admin\_preprocess\_maintenance\_page is declared twice.

How to solve this issue?

Edit:

When I change the name of preprocess function in template.php from commerce\_kickstart\_admin\_preprocess\_maintenance\_page to my\_admin\_subtheme\_preprocess\_maintenance\_page or delete template.php the fatal error disappear but I lose the formated html present in that function.

To make things more clear, the template.php is

```
<?php

/**
 * Override or insert variables into the maintenance page template.
 */
function livraria_acervo_admin_preprocess_maintenance_page(&$vars) {
  // While markup for normal pages is split into page.tpl.php and html.tpl.php,
  // the markup for the maintenance page is all in the single
  // maintenance-page.tpl.php template. So, to have what's done in
  // shiny_preprocess_html() also happen on the maintenance page, it has to be
  // called here.
  shiny_preprocess_html($vars);
  if (variable_get('install_task') != 'done') {
    $footer_markup =  '<div class="message">' . t('Proudly built by') . '</div>';
    $footer_markup .=  '<div class="logo">' . t('<a href="@url">Commerce Guys</a>', array('@url' => 'http://www.commerceguys.com')) . '</div>';
    $vars['footer'] = array(
      '#prefix' => '<div id="credit" class="clearfix">',
      '#markup' => $footer_markup,
      '#suffix' => '</div>',
    );
  }
}

```

I searched for that function in all file tree in root Drupal installation and didn't find any call for that function.

I see the function is related to the maintenance mode, the mode that I'm working now. Well, as I told above the fatal error disappeared but how to know where the function is called. I think the function is called somewhere and I would have to change the name in the file(s) that it's called, although I don't think this would the better way to solve the problem.

So some piece is missing in subtheming Commerce Kickstart 2 admin theme, and is related to the call of that function commerce\_kickstart\_admin\_preprocess\_maintenance\_page.

I'm new to Drupal and have not practiced php very much, so I hope I have been cleared. If more information is needed please tell me. And sorry about my English too.

Thanks in advance!

# Answer
PHP requires all function names to be unique\*, you'll need to rename the functions in your sub-theme to `my_admin_subtheme_FUNCTION_NAME`, e.g. `my_admin_subtheme__preprocess_page(&$vars)`.

You might want to consider clearing the `template.php` file completely and only copying the functions you need when you find you need them.
> 1 votes

---
Tags: commerce, theming
---


# Question
Title: AJAX calls in CTools Content Type Plugin?
I'm building a CTools Panels Content Type (i.e., that thing you insert into panels when adding content, not a type of node) and I am trying to use a form item's `#ajax` attribute to set some default values. See code below.

This is all inside of the content type's `my_module_content_type_edit_form($form, &$form_state)` call, by the way.

```
  $form['link_type'] = array(
    '#type' => 'radios',
    '#title' => t('Link Type'),
    '#ajax' => array(
      'callback' => 'my_module_set_target'
    ),
    '#default_value' => empty($conf['link_type']) ? '_blank' : $conf['link_type'],
    '#options' => array('none'=>t('No Link'), 'internal'=>t('Internal Link'), 'external'=>t('External Link'), 'document'=>t('Document Link')),
  );

```

My callback is the following.

```
function my_module_set_target($form, $form_state) {
  watchdog("Test", "Testing callback", array(), WATCHDOG_ALERT);
  $form['link_target']['#default_value'] = '_parent';

  return $form['link_target']['#default_value'];
}

```

Regardless of whether the return I'm suggesting would actually work, `watchdog()` doesn't even work.

I know CTools does some weird stuff with AJAX, but it can't be that weird. Do you have any idea on how I'd do what I'm wanting to do?

Thanks!

**Alternatively:** How do I set a default value based on the value of a previous form option?

I figured out how to do this, but it's a bit hacky -- you create new form fields for each dependency fork. You can then merge the values together in `hook_content_type_edit_form_submit()`, using whichever one corresponds to the value chosen for the component that initially forked everything.

I'm leaving the question open because I (and, frankly, every programmer I'm working with) is really wanting a good way to use AJAX inside these Panel content type edit forms.

**Update:** It appears you can't do stuff with #attached, either.

```
$form['link'][$i] = array(
  '#type' => 'fieldset',
  '#title' => t('Link #@num', array('@num' => $i)),
  '#collapsible' => TRUE,
  '#collapsed' => TRUE,
  '#attached' => array(
    'js' => array(
      'alert("Yay.");', 'inline'
    ),
  )
);

```

# Answer
> 8 votes
Short answer: you should use #ajax\['path'\].

Long answer:

Having a ajax callback does not help as ctools creates it's forms differently afaik. The callback done by system/ajax cannot find the complete form definition thus cannot find an element to process the ajax request for. Using #ajax\[path\] just triggers a menu item.

You can check for yourself by dumping the form when using #ajax\[callback\]

```
function ajax_form_callback() {
  list($form, $form_state) = ajax_get_form();
  drupal_process_form($form['#form_id'], $form, $form_state);

```

I've modified the simplecontext\_content\_type\_edit\_form by adding the user autocomplete widget and your field which both work :)

```
function simplecontext_content_type_edit_form($form, &$form_state) {
  $conf = $form_state['conf'];

  $form['owner_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Username'),
    '#default_value' => 'admin',
    '#autocomplete_path' => 'user/autocomplete',
    '#size' => '6',
    '#maxlength' => '60',
    '#description' => '$description',
  );

  $form['link_type'] = array(
    '#type' => 'radios',
    '#title' => t('Link Type'),
    '#ajax' => array(
      'path' => 'my_module_set_target'
    ),
    '#default_value' => empty($conf['link_type']) ? '_blank' : $conf['link_type'],
    '#options' => array('none' => t('No Link'), 'internal' => t('Internal Link'), 'external' => t('External Link'), 'document' => t('Document Link')),
  );
...

```

As you now use #ajax path you need to add a menu item as I did like

```
<?php

function my_module_menu() {
  $items = array(
    'my_module_set_target' => array(
      'title' => 'AJAX Example',
      'page callback' => 'my_module_set_target',
      'access callback' => TRUE,
      'expanded' => TRUE,
    )
  );
  return $items;
}

function my_module_set_target() {
  drupal_json_output( array('data' => "ABC"));
}

```

A nittpick about #attached\[js\]: the inline js should be key =\> value like:

```
'#attached' => array(
  'js' => array(
    'alert("Yay.");' => 'inline',
  ),
),

```

I've used Firebug to check for the resulting value not the resulted effect. So I hope this helps to fix your problem.

# Answer
> 2 votes
I've had a similar problem, where I wanted to include a Media element type into a CTools content type plugin, that also uses ajax for selecting an image.

It uses it's own ajax 'path' setting, instead of the 'callback' setting, but when selecting an image, the form was rebuilt without the media element entirely.

I traced this to the fact that drupal\_rebuild\_form couldn't find neither the CTools form wrapper function, nor the actual settings form function. So I fixed it by adding these lines of code to the ctools settings form:

```
function custom_module_my_content_plugin_content_type_edit_form($form, &$form_state) {

$background_image = isset($conf['background_image']) ? $conf['background_image'] : array();
  $form['background_image'] = array(
    '#title' => t('Background image'),
    '#default_value' => $background_image,
    '#type' => 'media',
    '#input' => TRUE,
    '#extended' => TRUE,
    '#tree' => TRUE,
    '#media_options' => array(),
  );

  // The two function calls below are necessary if we want to use a media
  // element type, because it causes ajax requests, which in turn call
  // drupal_form_rebuild(), and without the below includes, Drupal will
  // not be able to rebuild the form.

  // Include the CTools content type plugin file, because it provides
  // the ctools_content_configure_form_defaults() function, which is needed
  // when rebuilding the form, because of an ajax action, like selecting
  // a media element.
  ctools_form_include($form_state, 'content');

  // Include this plugin file as well, so that when the form is rebuilt, it
  // can successfully retrieve the settings form.
  ctools_form_include($form_state, 'my_content_plugin', 'custom_module', 'plugins/content_types/my_content_plugin');

}

```

Maybe I'm missing something obvious why the include files are not loaded, but including them manually fixed the issue for me.

# Answer
> 0 votes
on my side, I had to write a form wrapper function in .module file and to include the pane manually (where original form content is defined) like that:

```
function mymodule_form($form, &$form_state) {
  // include mymodule/panes/mypane.inc
  ctools_include('mypane', 'mymodule', 'panes');
  return mymodule_form_content($form, $form_state);
}

```

Now, during ajax call, Drupal is able to retrieve my form so I can use the standard AJAX form API.

---
Tags: 7, forms, panels, chaos-tool-suite
---


# Question
Title: How do I set a value based upon other values?
I have a content type of product, and want to set the postage cost for the item which is dependent upon length,width,height, weight but also product kind - e.g. hazardous items needing special courier etc. I have a series of prices for the various weights and size limits, so I'm wondering how can I utilise these prices for the postage field automatically.

At the moment, the prices aren't inserted in Drupal, would these prices be better as a separate content-type or as fields inside a courier content-type? If the latter would they be as easy to reference?

This is not for a commerce site, merely somewhere to manage all my stock from all the various suppliers - a product information manager.

# Answer
If you have a small number of settings to store, you might consider using system\_settings\_form() to store them in Drupal's variables table. Take a look at the core modules that implement this function for more examples.

If the rates group logically, and/or need to be edited by users, you might make a postage\_rates content type with fields on that for the information that changes in addition to any constants set by an admin using the first method. You can then add a entityreference field from you product to the postage\_rate.
> 2 votes

---
Tags: entities
---


title: Responsive images with multiple fields

text:
# Question
Title: Responsive images with multiple fields
I'm working on a site that has (and must have) three image fields for out three breakpoints. We could call them field\_img\_mobile, field\_img\_tablet and field\_img\_desktop

Is there a way (a module?) that could load the image field corresponding to the breakpoint?

# Answer
I think Picture module help you to solve your query.

Please check Responsive Images in Drupal with the Picture Module.

OR you can try these also :

1. Flickr
2. Responsive images and styles
> 0 votes

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


# Question
Title: Why source is empty object for hook_feeds_after_parse in dpm()?
Working on a module that modifies some CSV files before it's processed by `feeds_import`. I use the `hook_feeds_after_parse($source, $result)`. The processing and `$result` is ok.

But the object `$source` of type `FeedSource` is empty! So how can we know which source is being handled?

Why is it empty?

```
if $source == x: // do that.

```

is not possible.

Any solution?

# Answer
> 2 votes
Ooops ok, `dpm($source)` does not show protected class properties if you don't specify which protected variable you want to display. You have to point the property you want to display.

After some research in FeedsConfigurable.inc and DB `dpm($source->id)` is the unique id (string!) I search for.

/n

---
Tags: feeds, importing-exporting
---


# Question
Title: How to get e-mail from Drupal.org about new Drupal releases?
I have creates a account in drupal.org website. I saw this https://www.drupal.org/news link to know news about drupal.

Is there a way by which I can get latest updates in my mail without visiting the drupal site

# Answer
Go to https://www.drupal.org/user , click on the "Edit" tab and from there, the "My newsletters" tab. This will allow you to subscribe to "Drupal newsletter" and "Security announcements".

Also to get notifications of Drupal core or module updates for a particular Drupal site that you run, go to Reports -\> Available updates -\> settings (/admin/reports/updates/settings) and enter your email address and the desired frequency (daily / weekly) and type (security / all) of updates.
> 3 votes

---
Tags: 7, updating
---


# Question
Title: What content type select in View related to email?
I want to create a View. In my site there are lots of users are there, there is an email system i.e. send mail in these events : `At the time of registration, At the time of password reset, etc.`.

I want to create a View of type Email or related to Email so I want to show the following things inside View related email :

> Mail ID
>
> Subject
>
> Body

May anybody please help me to find out that what content type am I select for email while creating View. Please help. Thanks

# Answer
I think you want to use the content of users table so create a view as below

* Add the field `user:E-mail` field to list users E-mail ID's
* You could make use of Views Send Module
* Check this Link this might help you understand Views Send Module
> 1 votes

# Answer
It looks like you're trying to get a view of mails sent from your site.

There's a module which does this for you. Much easier than setting up a view.

https://www.drupal.org/project/mail\_logger
> 0 votes

---
Tags: views, emails
---


# Question
Title: Change the text on the message which is displayed after the user registration
I am looking for a way to replace the text in this message which appears on the website after a new account if created.

> Thank you for applying for an account. Your account is currently pending approval by the site administrator. In the meantime, a welcome message with further instructions has been sent to your e-mail address.

Has anyone managed to change this successfully?

Thanks! Anton.

# Answer
> 1 votes
Goto Admin -\> Configuration -\> Account Setting -\> Change the messages.

OR

You can implement through Rules module.

> Send mail after creating new user a/c

Usage :

1. Goto Admin -\> Configuration -\> Rule
2. Click on 'Add new rule'
3. Enter Name & Select **React on event** : After Saving a new user a/c & SAVE
4. Click on **Add Condition** & select **Send Mail**.
5. Click on **Data Selector button** & Enter **Data Selector** : `account:mail`
6. Enter Subject & Message & Save

# Answer
> 0 votes
I would add another way...

You could achieve this easily via String Overrides Module

> It includes a UI for quickly adding string replacements for anything that is passed through the t() function, which includes the message that you're trying to replace.

---
Tags: users
---


# Question
Title: How can I get path aliases arguments from a URL in a template?
I have a content type which has an automatic path alias to `latest-news/[title]` (e.g. latest-news/example-news-title).

I need to get the first part of the path alias in my `page.tpl.php` file, but when I use `arg(0)` I am given `node` and not `latest-news`.

How can I get the first part of an aliases URL in a page template?

# Answer
You can use function drupal\_get\_path\_alias() to get the path alias, then strstr() to get the first component of the path, like so.

```
echo strstr(drupal_get_path_alias(), '/', TRUE);

```
> 2 votes

---
Tags: 7, theming
---


title: Create a landing page as the front

text:
# Question
Title: Create a landing page as the front
I have created a content type called 'landing', however when I try and setup this as my homepage

**config/system/site-information** to the alias 'landing'

It takes on the node--front.tpl.php as the template rather than my node--landing.tpl.php.

If I look at it in /landing the page looks fine.

I also try and hijack the main landing page by setting this in the .htaccess

**DirectoryIndex landing**

but no luck - any idea how I can set this custom landing pages as my homepage and retain the template style?

# Answer
node--front.tpl.php is for the front page specifically.

If you don't want a specific template file to apply to the front page only, simply delete node--front.tpl.php and flush the caches. node--landing.tpl.php will then be used instead.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Remove empty url argument from view with exposed filter
I have a view with exposed filter "Has taxonomy term" (filter identifier: "topic") and exposed sort: Created (default one) and Rating. On a view page, when I change sort option to Rating, url of a view page is becoming *?**topic=**&sort\_by=rating*

How to remove this empty argument from page url?

I tried

```
  $('#views-exposed-form-taxonomy-term-page').find(':input[value=""]').attr('disabled', true);

```

and

```
  $('#views-exposed-form-taxonomy-term-page').submit(function() {
    $(':input', this).each(function() {
        this.disabled = !($(this).val());
    });
  });

```

but it didn't work.

# Answer
solved the problem:

```
(function ($) {
  Drupal.behaviors.citatyTaxonomy = {
    attach: function(context) {

      // disable blank input fields
      function disableEmptyInput() {
        $('#views-exposed-form-taxonomy-term-page').find(':input[value=""]').attr('disabled', true);
      }

      // on form submit
      $('#views-exposed-form-taxonomy-term-page').find('.views-submit-button input[type=submit]').click(function(){
        disableEmptyInput();
      });

      // view with auto-submit
      $('#views-exposed-form-taxonomy-term-page').find('.ctools-auto-submit-click').click(function(){
        disableEmptyInput();
      });

    }
  };
})(jQuery);

```
> 0 votes

---
Tags: 7, views
---


title: Database query in template.php

text:
# Question
Title: Database query in template.php
Is it ok to query the database in a template.php file of a sub-theme. If not where do I put it? Below I have function that is querying the database and it works fine but I want to make sure I doing it the right way =).

```
function inTheTemplateFile() {
   $query = db_query("SELECT tid FROM taxonomy_menu");
   return  $query->fetchAll();
}

```

# Answer
> 1 votes
The template should idealy not be used to do database queries or other code that belongs in the Model or Controller of the MVC pattern. The problem is that it is impossible to have a perfect implementation of the MVC pattern in Drupal.

What I mostly use as a rule of thumb is this:

* Is this functionality that belongs to a module? Then put it in a module.
* Would I have to copy this to a new theme if I made a second one? Then put it in a module (or parent theme if it should be in a subset of themes).
* Does this function get/compute data or results which should be provided by a module? (like fetching user-data or a list of items) Then put it in a module.

In general the theme should only contain HTML, JS, CSS and a minimum of PHP used for simple loops, printing and simple conditional statements.

So the answer to your question would be; Probably not, it should probably be in a preprocess function or a getter function (like book\_get\_books()) in the module.

Edit: As Clive points out in the comments, Drupal does not strive to be fully MVC. The MVC pattern is only used to make it clear what belongs in the template, the controller and view don't really exist in drupal. Even the view is not as clear cut as it is in something like Symfony or Zend framework.

# Answer
> -1 votes
You should never use query database on your templates.

Instead, data should come from views, and after, from a controller o event that render this view

---
Tags: theming, database
---


title: How to Use Contextual Filters

text:
# Question
Title: How to Use Contextual Filters
I have a view where I'm showing all postings by post author. Right now, I show (and filter) the posts by author name using contextual filters.

I want to change it so that I still use the username in the contextual filter, but when I override the the title, I want to show the human readable name.

So, for example,

```
www.example.com/postings/kyle.keiper

```

Currently shows

```
Postings by kyle.keiper

```

in the title.

How can I change the view so that the URL stays the same, but it shows "Postings by Kyle Keiper"?

# Answer
You need to rewrite the output of the field and use PHP for the text string manipulations.

Two modules can help you do that. Note that you'll likely choose one of these two modules. they aren't dependent on each other. They can both help you get what you want in different ways.

1. Views PHP
2. Computed Field

You might need to turn the title off and create it instead in the View header using "Global: text" and turning tokens on their. The token for username (which is "\[name\]" will use the value from the written output you've used when defining the field.
> 0 votes

---
Tags: views
---


# Question
Title: Drupal 404 redirect to a custom PHP file
Is there any possibility to redirect Drupal 404 to a custom php file without sending actual 404 headers.

# Answer
Ofcourse there is a module for this too.. !!!

Search 404 Module would help you achieve this

> Instead of showing a standard "404 Page not found", this module performs a search on the keywords in the URL
>
> It also has Support for Custom Text and Title to be displayed in search404 pages
> 1 votes

---
Tags: redirection, .htaccess
---


# Question
Title: How to display comments and comments form on custom node pages
I am new developing my first ever site in drupal. Along the line, due to the requirements of the project I had to create custom node pages (template files) instead of the default ones in drupal. For example my site has content type 'Article' and the template file for that is page--node--article.tpl.php. In page preprocess, I switch to the right page template with this code

```
if (isset($variables['node']->type) && !empty($variables['node']->type)) {
  $variables['theme_hook_suggestions'][] = 'page__node__' . $variables['node']->type;
}

```

Now, my problem is how to display comments and comments form. The drupal print render($content\['comments'\]); is not working. I have installed Devel and I can see the comments and comments\_form variables in the back end under the Render tab but I do not know how to access and display comments on the front end either by using these variables or another means.

Please help.

EDIT After digging into variables available on the page I was able to get the form to show using

```
print render($page['content']['system_main']['nodes'][$node->nid]['comments'])

```

but when I try to submit a comment an alert comes up saying OK and the comments cannot be found when i check in the back end to approve. Any thoughts pls

# Answer
> 0 votes
Add your theme hook suggestion in **Node preprocess** hook instead of Page Preprocess

```
if (isset($variables['node']->type) && !empty($variables['node']->type)) {   $variables['theme_hook_suggestions'][] = 'page__node__' . $variables['node']->type; }

```

Now **$content** variable should be available for you.. Please remember **Clear Cache**

# Answer
> 0 votes
If you are new in Drupal, one of the best tool for building site in Drupal is Panels.

With this module you can create custom pages and override existing pages, like node view, user view pages etc. Best thing with this module is that you don't need to touch code, you can easily build layouts just via UI.

For your problem, for example, with Panels (you need also to enable Page manager module), you can override Node view page, create layout that you need, add variant just for Article content type and in Panel block/region you can add Node content in view mode that you want (you can choose) and below you can add Recent comments and Comment form.

If you need more information, just ask, I will attach screenshots without problem.

Hope this will be helpful.

---
Tags: nodes, comments
---


title: How do I execute this SQL query

text:
# Question
Title: How do I execute this SQL query
I'm trying to execute the following :

```
db_query('SELECT FROM_UNIXTIME(`created`, "%Y") as year, FROM_UNIXTIME(`created`, "%m") as month, FROM_UNIXTIME(`created`, "%d") as day FROM users ORDER BY `created`');

```

And because of the % sign the result is : PDOException : SQLSTATE\[42S22\]: Column not found: 1054 Unknown column '%Y' in 'field list'

I tried escaping the % with a double %% resulting in : PDOException : SQLSTATE\[42S22\]: Column not found: 1054 Unknown column '%%Y' in 'field list'

Of course this query works in phpmyadmin

Help ?

# Answer
> 0 votes
PDO requires that you use single quotes, e.g.

```
db_query("SELECT FROM_UNIXTIME(`created`, '%Y') as year, FROM_UNIXTIME(`created`, '%m') as month, FROM_UNIXTIME(`created`, '%d') as day FROM users ORDER BY `created`");

```

---
Tags: database
---


# Question
Title: Module that allows to compare, edit and/or merge revisions
At the moment I have installed on my site the Diff module, which allows me to compare the content of 2 revisions but I need a module that allows me to not only see the differences between revisions, but also to edit both revisions at the same time while comparing them and to copy the content of a field to either revision (like WinMerge or many other diff/compare applications)

I am well aware that revisions shouldn't be used this way, but i'm using the revisions system to allow unregistered users to post edit suggestions about my site's content so being able to copy only certain fields (since a suggestion might include both correct and incorrect data for different fields) in the current revision would save me a lot of time

# Answer
I doubt there is an out of the box solution. But maybe you can Views of Pending revision items per content item using Views and if needed the Revisioning module and maybe Rules. Eg, somehow you want to list stuff with pending changes and Revisioning+Rules seems to be able to do that:

> Rules: when Triggers won't do, use the event-condition-action paradigm of Rules. More complicated to set up than Trigger, but very powerful. Revisioning adds its own events and conditions to Rules, for example "content is about to be published" and "content has pending revisions".

Then for the view itself you could try to link to a 2nd page that uses the Diff Different module to make the UI per field item you are talking about to move field data around.

I don't see any out of the box solution and you need to build a Workflow of pages/forms/views etc. I'm just trying to help by listing some tools to help achieve that.
> 2 votes

---
Tags: 7, nodes
---


# Question
Title: How to remove title field from content edit page?
i want remove field title in any content type on drupal 7. i use module display suite and hidden title but when i add new content that "title is required .......................................... ". thank you for help.

i want remove title field in any content type.

# Answer
> 5 votes
You want to either:

In general most content types *need* a `title`. Titles are the **Names** we give content to find them using Search forms and pages.

---
Tags: 7, entities, nodes
---


title: Conditional display of a Views field

text:
# Question
Title: Conditional display of a Views field
The issue at hand is to change the display of one of a View's fields, based on a condition in another field of the same View. The field to be affected is the display of checkboxes associated with Flag Lists/List Operations. The conditional field would have a value "yes" or "no" and would be excluded from display. Ideally, the checkbox would simply be absent if the value is "no." Alternatively or additionally, it would be helpful to display a message explaining why the item can't be selected to include in a list. Can anyone provide suggestions for a general approach? Thank you for any help and suggestions.

# Answer
> 5 votes
By conditional field do you mean a simple Boolean? If so, you should be able to pull this off with some tactical field rewriting.

When creating the Boolean in your content or entity type, have 'Yes' as the only value, leaving the unchecked state assumed as no. Then in views add the flag list field first and exclude. Next the Boolean but don't exclude. Use its default formatting not its key. In its settings rewrite using the flag list field replacement pattern, and in the empty behaviour (eg the result of the empty checkbox when no value has been specified for it), choose to hide rewriting.

You may need to fine tune this or perhaps add additional fields, chasing the replacements until it works. You'll be amazed at the sophisticated conditions you can set up in this fashion.

# Answer
> 4 votes
maybe Views Conditional could be useful for small conditionals:

> Views Conditional is a simple module that allows you to define conditionals (if xxx then yyy). with fields in views. Conditions include:
>
> * Equal To
> * Not Equal To
> * Greater Than
> * Less Than
> * Empty
> * Not Empty

---
Tags: views
---


# Question
Title: Matching user accounts in views with taxonomy
In user accounts we have two Term fields that use the same taxonomy vocabulary. For example, the user profile has *I need* and a *I have* fields.

For example User A has a blue crayon but wants a red one.

```
- I have
-- X Blue Crayon
-- - Red Crayon
-- - Green Crayon
- I want
-- - Blue Crayon
-- X Red Crayon
-- - Green Crayon

```

I would like to craft a view that, based on User A's desire marked want, finds all users that have Red Crayon they want to lend.

Ideally, I'd like to auto populate this contextual filter with what the logged in user has specified. For example in this situation, I want to populate *When the filter value is not in the URL*'s *Provide Default Value* field with the term\_id of Red Crayon. Thus, listing everyone with ready to lend a red crayon.

# Answer
> 0 votes
From the create view wizard, you need to choose, show "Users."

In the filters section you'll create a filter for "I want" whose value is set via PHP to grab the current users choice for "I have." You'll need the Views PHP module for this.

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


# Question
Title: Migrating Drupal 6 - 7 Content Type with optional file field, throws error
I am currently working on migrating content from a Drupal 6 site to Drupal 7 and have started with a single content type for testing. The source content type has an optional image field, however if I try to import only those nodes with a file attached, I'm still running into issues.

Here is the source sql:

```
// Get source data:
//   1. node data
$query = Database::getConnection('default', 'extra')
  ->select('node', 'n')
  ->fields('n', array('nid', 'title', 'created', 'changed', 'status', 'promote', 'sticky', 'language', 'tnid', 'comment'))
  ->condition('type', 'guest_lecturer');
//   2. node revision data (body, etc)
$query->join('node_revisions', 'nr', 'nr.vid = n.vid');
$query->fields('nr', array('body', 'format', 'log'));
//   3. extra fields
$query->join('content_type_guest_lecturer', 'nt', 'n.nid = nt.nid');
$query->fields('nt', array('field_lecturer_title_value', 'field_lecturer_teaser_value', 'field_lecturer_featured_value'));
//   4. files (only nodes with this file field set)
$query->join('files', 'f', 'f.fid = nt.field_lecturer_photo_fid');
$query->fields('f', array('filename'));
//   4. files (all nodes)
//$query->leftJoin('files', 'f', 'f.fid = nt.field_lecturer_photo_fid');
//$query->fields('f', array('filename'));
//   5. url alias
$query->join('url_alias', 'a', "a.src = CONCAT('node/', n.nid)");
$query->addField('a', 'dst');

```

And the field mapping:

```
// add field mappings
$this->addFieldMapping('title', 'title');
$this->addFieldMapping('created', 'created');
$this->addFieldMapping('changed', 'changed');
$this->addFieldMapping('status', 'status');
$this->addFieldMapping('promote', 'promote');
$this->addFieldMapping('sticky', 'sticky');
$this->addFieldMapping('language', 'language');
$this->addFieldMapping('tnid', 'tnid');
$this->addFieldMapping('comment', 'comment');
$this->addFieldMapping('uid')->defaultValue(1);
$this->addFieldMapping('revision')->defaultValue(FALSE);
$this->addFieldMapping('log', 'log');
$this->addFieldMapping('translate')->defaultValue(FALSE);
$this->addFieldMapping('revision_uid')->defaultValue(1);
$this->addFieldMapping('is_new')->defaultValue(FALSE);
$this->addFieldMapping('path', 'dst');

// add photo field mappings
$this->addFieldMapping('field_lecturer_photo', 'filename');
$this->addFieldMapping('field_lecturer_photo:file_class')->defaultValue('MigrateFileUri');
$this->addFieldMapping('field_lecturer_photo:language')->defaultValue('und');
$this->addFieldMapping('field_lecturer_photo:destination_dir')->defaultValue('sites/default/files');
$this->addFieldMapping('field_lecturer_photo:source_dir')->defaultValue('sites/all/modules/custom/azamara_migrate/files/lecturer_photo');
$this->addFieldMapping('field_lecturer_photo:destination_file', 'filename');
$this->addFieldMapping('field_lecturer_photo:file_replace')->defaultValue('FILE_EXISTS_REPLACE');
$this->addFieldMapping('field_lecturer_photo:preserve_files')->defaultValue(FALSE);
$this->addFieldMapping('field_lecturer_photo:alt')->defaultValue('');
$this->addFieldMapping('field_lecturer_photo:title')->defaultValue('');

```

And the error when I try to run the import:

```
22911   Error   PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'id' cannot be null: INSERT INTO {file_usage} (fid, module, type, id, count) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4); Array ( [:db_insert_placeholder_0] => 92 [:db_insert_placeholder_1] => file [:db_insert_placeholder_2] => node [:db_insert_placeholder_3] => [:db_insert_placeholder_4] => 1 ) in file_usage_add() (line 696 of /htdocs_svn/includes/file.inc).
22911   Error   SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'id' cannot be null: INSERT INTO {file_usage} (fid, module, type, id, count) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4); Array ( [:db_insert_placeholder_0] => 92 [:db_insert_placeholder_1] => file [:db_insert_placeholder_2] => node [:db_insert_placeholder_3] => [:db_insert_placeholder_4] => 1 ) (/htdocs_svn/includes/file.inc:696)

```

I can see that the \[:db\_insert\_placeholder\_3\] is empty and is causing the problem, but how do I correct this?

# Answer
> 1 votes
Changing this line from:

```
$this->addFieldMapping('is_new')->defaultValue(FALSE);

```

to:

```
$this->addFieldMapping('is_new')->defaultValue(TRUE);

```

fixes this specific issue.

---
Tags: 7, migrations
---


# Question
Title: Is there a way to force some block caching despite system block caching option is disabled?
In `/admin/config/development/performance` settings page, my "cache blocks" options is disabled due to "Block caching is inactive because you have enabled modules defining content access restrictions."

But I absolutely need to globally cache some blocks (in particular some superfish blocks because they recreates menu items on every page load if not cached).

I've already tried Block Cache Alter module, but without success, probably because this module can works only if system "cache block" option is enabled (see: https://drupal.org/node/1954224 )

Thank you for help

# Answer
With latest Drupal 7.33 release there is a new setting variable now:

```
/**
 * Block caching:
 *
 * Block caching may not be compatible with node access modules depending on
 * how the original block cache policy is defined by the module that provides
 * the block. By default, Drupal therefore disables block caching when one or
 * more modules implement hook_node_grants(). If you consider block caching to
 * be safe on your site and want to bypass this restriction, uncomment the line
 * below.
 */

$conf['block_cache_bypass_node_grants'] = TRUE;

```

Setting the above to TRUE the "cache blocks" option becomes checkable.
> 7 votes

# Answer
block\_form\_system\_performance\_settings\_alter() is where that code lives. Looking into it you can force this by running `variable_set('block_cache', TRUE);` once or by adding `$conf['block_cache'] = TRUE;` to your settings.php file (near the bottom). I would opt for the settings.php method.

Core Issue for this as well: https://drupal.org/node/1930960 (Now in 7.33). See MXT's answer on how to use it.

Note that by doing this bad things might happen. You have been warned.
> 3 votes

---
Tags: 7, caching, performance
---


# Question
Title: WSOD after PHP 5.3: Issue with call_user_func_array() in menu.inc
EDIT Nov 10: This has been solved by Letharion's suggestion to do a md5 file compare of my file with an original package file containing the function that was throwing the error.

--

I was referred here by https://www.drupal.org/node/2336585#comment-9311707

I've spent the better part of two days on this. I have searched and tried suggestions and so far no dice. Summarizing as much as possible:

Recently my WHM/cPanel auto-updated itself and locked us out of phpMyAdmin short of upgrading to MySQL 5.5 or higher -- when I tried accessing phpMyAdmin one day I was confronted with a red box with red text stating to upgrade. We've been ignoring it but two days ago we needed to get into our database so we had cPanel perform an unassisted upgrade to SQL 5.5.

Process went perfectly smooth and things seemed normal until we went to edit a node on our Drupal 6.33 and received a WSOD. Reloading a different page gets this error:

`warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'node_page_edit' not found or invalid function name in /home/SITENAME/public_html/includes/menu.inc on line 350.`

Line 350 of my unmodified menu.inc is within the function menu\_execute\_active\_handler() as follows: `345 if ($router_item = menu_get_item($path)) {
346 if ($router_item['access']) {
347 if ($router_item['file']) {
348 require_once($router_item['file']);
349 }
350 return call_user_func_array($router_item['page_callback'], $router_item['page_arguments']);
351 }
352 else {
353 return MENU_ACCESS_DENIED;
354 }
355 }
356 return MENU_NOT_FOUND;`

After pulling out some hair I discovered that during the SQL upgrade the server automagically updated it's PHP from our longstanding 5.2-branch to now 5.3.29. I have since learned that D6 does not 'officially' support PHP 5.3.

Looking up call-user-func-array(), indeed it has changed in PHP 5.3+

Can anyone shed some light on how to patch this for now? We are still using D6 because a few modules we need are not ready for D7 yet.

Thank you very much in advance, BigMike

-- Additional Info:

So far everything else including a good number of contrib modules are working as expected. The only error we have seen is *call\_user\_func\_array() expects parameter 1 to be a valid callback* and only when trying to create (node\_add) or edit (node\_page\_edit) nodes.

I did a dump on $router\_item and call-user-func-array() is working for *node\_page\_view*, *drupal\_get\_form*, and *statistics\_node\_tracker* page\_callback's but not working for *node\_page\_edit* or *node\_add*.

Anything that uses *drupal\_get\_form* is fine, which so far I've tested creating and editing both blocks and taxonomy and both function as expected. So for kicks I intercepted 'node\_page\_edit' and changed it to 'drupal\_get\_form' and now my node edit pages load -- no longer white screen of death -- but have a ton of other errors and nothing useful is outputted to the screen.

We also get an error on our Clone page (Clone module v6.x-1.3),

`warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'node_form' not found or invalid function name in /home/SITENAME/public_html/includes/form.inc on line 421.`

which in form.inc is...

`419 // If $callback was returned by a hook_forms() implementation, call it.
420 // Otherwise, call the function named after the form id.
421 $form = call_user_func_array(isset($callback) ? $callback : $form_id, $args);`

Dumping $callback here and it's an ordinary string of value "node\_form".

**So I need to figure out how to manipulate call\_user\_func\_array() for use under PHP 5.3.x.** There are a few tips on the php.net site but so far I can't figure it out.

So far I've tried...  `return call_user_func_array($router_item['page_callback'], array(&$router_item['page_arguments']));` and `return call_user_func_array(array($router_item['page_arguments'], $router_item['page_callback']), $router_item['page_arguments']);`

...and I've tried adding ampersands and changing array orders... I'm really just spit balling as this is my first time ever working with call\_user\_func\_array().

Any help is GREATLY appreciated! Our website is http://www.marlincrawler.com and most things are working as they should. Not being able to edit content isn't the end of the world as we can do that in the DB, but we need to be able to create content and not having this feature is a critical issue for us.

# Answer
Letharion's suggestion above has solved my issue. For some reason the MD5 checksum of my `d6_root/modules/node/node.pages.inc` file changed during the cPanel auto-update of our PHP/SQL rendering 'node\_page\_edit' not found or as an invalid function name. Even despite a word-for-word text compare match of my unmodified node.pages.inc file with an original/stock Drupal 6.33 file, I was getting this WSOD. My node.pages.inc file was not a binary match of the stock D6 file, and directly after overwriting my unmodified node.pages.inc file with an original file from the D6 package, my website instantly began functioning normally.

To me it seems highly unlikely that this change occurred during the PHP & SQL upgrade. I wonder if rather the file had some issue with it before and perhaps the older version of PHP simply didn't mind it....?

So if anyone else out there has a particularly pesky white screen of death, in my example here, knowing which function was causing the issue and which file contains said function, perform a MD5 file match and see if for any reason your file differs from the original Drupal install file.

Many thanks to Ashish Bairagi, calebtr, and Letharion for their help is getting this resolved.
> 1 votes

# Answer
First of all I would like to mention that the error you are referring is indeed just a warning which does not cause WSOD. So you need to dig out what exactly the fetal error there which is causing WSOD.

To do this you need to change level of error reporting in you settings.php file. Add this code :

```
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
//Note:  Do not include the opening and closing PHP tags when you copy this code
?>

```

then you would be able to see exact error, if you are able to solve that then the issue might get resolved or you can simply post that here as well so any one of us can help you.

more details here: https://www.drupal.org/node/1056468
> 0 votes

# Answer
I don't have enough reputation to comment. I don't see you saying anywhere that you've tried this, but here it is:

Clear all of your caches.

(at admin/settings/performance)

call\_user\_func\_array() is working fine, but it can't find the function 'node\_page\_edit', so it PHP is complaining.

But of *course* you have a function called node\_page\_edit, it is part of the node module in Drupal core, and there is no way you can disable that module. So something is wrong with the way Drupal is loading modules and most of the time clearing caches helps.
> 0 votes

---
Tags: 6, wsod
---


# Question
Title: Omega theme on Ipad slides across and disappears
I'm using the latest Omega 3 theme on my drupal 7.32 site caerleonlodgehillprimary.org. I notice on the ipad2 (also Ipad Mini), if you swipe across to the left, the entire page disappears and you are left with a blank page. Has anyone got any ideas why that is? I was wondering whether its some kind of corruption in the footer, the last thing I added was to add a Contact Us block showing the address and email in the footer (which is a View based on the Contact Us node), I noticed in portrait mode, the email spills over into the next block. any idea?

# Answer
> 0 votes
This is caused by my social icons in the footer, the same problem is referred to in this posting, it occurs when a DIV gets too big for the page, the Ipad cant cope with this and creates a load of space on the right of your page. In my case, I have an text indent -999 in the class of my social button, defined as :-

```
.social-button{

    width: 30px;
    height: 30px;
    text-indent: -999em;
    display: inline-block;
    background-repeat: no-repeat;
    background-position: center center;
    margin-right: 2px;
    text-decoration: none;
    border: 1px solid #FFFFFF;

```

}

To resolve I put :-

```
width:auto;
overflow-x:hidden;

```

on the css for the social icons Block in the footer and it worked perfectly as suggested in the link above. Sorry this is slightly off topic with a CSS resolution, but I though it would save someone (like me) hours of messing around with their theme to find a problem thats not there . Thanks

---
Tags: theming
---


title: server migration issue

text:
# Question
Title: server migration issue
I've developed a website and deployed it in a server, I consider this server as a test server. Now, I'm in the final stage of development and I'm looking to move the website content to new server. In that process, I've moved my website contents from test server to the new server, updated the `database` details in `settings.php file`, created a database in the new server and imported the `.sql file` (from the test server). I anticipate all the cloning work is done.

Now, when I look into the new site, the home page appears in the old format - I mean most of the edits that I made have gone. When I click on the menu tabs, the corresponding pages are broken - there is no proper redirection to the pages.

What I've observed was, in the homepage the url was good but when I click on one of the links the url is pointing to something odd like - `localhost/new_mywebsite/search`. I feel that this is odd. I couldn't trace why it was showing in that way.

Moreover, when i compared the new database with old database(test server) the old one has around 130 tables and the new one has only 90 tables. Even it seems odd for me.

What might the real reason for this odd behaviour? Is it with database or links?

# Answer
> 2 votes
I had this same problem recently, and it took me forever to figure out. What you have to do is make sure the database at your new location is *empty*. You have to have a database, and it has to be an empty database. Of course, do still make sure your settings.php info is correct, as you did the first time around. Then run install.php and go through the normal steps. Once that is complete, then import all of the tables from the old database into the new database.

The reason for this is that Drupal caches the database connection information, so if you change that in settings.php, it will continue using the old information until you run install.php. And you can only run install.php if you’re pointing the site at a fresh database.

EDIT: Sorry, I missed part of your post. You need to also make sure that your base\_url settings in settings.php are set up for the live domain.

---
Tags: database
---


title: Page render array for front page

text:
# Question
Title: Page render array for front page
I need to paste full front page of Drupal site to other page. Can I get page render array for front page for example in html.tpl of not-front page? Thanks!

# Answer
> 0 votes
You can install Devel module and enable "Display $page array" on Devel settings page (/devel/settings).

Or you can implement hook\_page\_build() to get $page array:

```
YOURMODULE_page_build(&$page) {
  print_r($page);
}

```

---
Tags: theming
---


# Question
Title: How to update only one field using Views?
Is it possible to update only one field using Views? Say, you use Views to list all property items. Property content type has one field called 'Position' with option values as 'Featured', 'Hot', 'Sold', 'Vacant', etc.. For each item in a row listed you have what looks like the following:

Views Display:

```
ID   Title     Type       Address       Total Size (sq Ft)     Position        Action
123  Bay View  Apartment  Moroco        1245                   (combobox)      Update

```

There are other fields for this content type that will not be included, hence, only those relevant fields are shown in this particular Views. So when you click 'Update' button the item will be updated accordingly, that is, only the 'Position' will be updated.

And maybe for other instances, a few fields - instead of one as above - can also be updated. The above is only an example with one field.

Any ideas?

# Answer
You might try the module Editable fields It is an old module that hasn't been updated in a long time, but I did get it working recently on a new project.

Another option is to build your own with rules, and rules links

With rules links you can set a path that sets a rule to activate. You can have that rule update the content with whatever setting you wish.
> 2 votes

---
Tags: views
---


# Question
Title: Custom PHP vs Drupal Workflow for a Web Application not Websites
This question can be too ambiguous but i think many new drupal users face this difficulty like me.

There are many blogs which says that Drupal is a CMF and we can use it for making Web Application rather then using it like Wordpress for articles and pages.

For the sake of example lets say i have to make a task management system with a specific Application style UI and features. If i would have to make it by custom programming i would be making tables for tasks, users, task\_attachments, clients and so on and will make relations accordingy.

My question is how we can do all this stuff in Drupal? Nodes are for content and i would not go for nodes to achieve this. The other thing is Entity but How one can properly utilize Entities. If i have to list all tasks for a specific user, If a user want to update a status of his task or attach some file, If its a team and other team members should also be allowd to post updates on tasks. These are the common application scenarios that we usually make in this kind of application.

If someone provide a brief workflow then it would be a great effort for helping beginners like me to use Drupal as a developer rather than doing a data entry job by installing modules and copying content , images.

There is a good example erpal.info but its too advanced for me at this level to jump into it. but a mini erpal would be great.

Thanks Alot.

# Answer
> 1 votes
Your questions are somewhat vague but I'll provide some examples:

1. For instance I have a site that from a CSV file allows certain visitors emailed access keys to access a Webform and its tracked via a custom Node that has an embedded field collection and this relationship + status is tracked via a Relation. I use the Migrate module to add or update allowed visitor information from the CSV.

I use the Webform API, EntityFieldQuery's and drupal hooks to do my webapp business logic. Drupal core and contrib modules provide additional APIs. I use Views Send for bulk emailing.

2. I have another form site for class reviews for a campus. I use Migrate to pull `$form` structure info from a 3rd party survey database and then use a custom drupal `entity` and the drupal Form API to build a custom form from remote data. The remote database has a custom schema for say: Question, Options, Question position in Form, Form ID, etc ... it gets converted into a drupal `$form` array with some simple PHP in a Migration class. Again I use Relation to track what the student has completed between a `uid` and a `nid`. I use the drupal authorization mechanisms such as `authmaps` to integrate our local LDAP server.
3. On another site students should fill out like 10 content types after login. I use `hook_menu_alter` and a cookie to assure a student has `Opted-In` daily to EULA's for uploaded content. Then I use the core Form API to link 10 node edit forms on submission from 1 to another. Creating a kind of workflow for the student.

There are numerous times where knowing the Drupal contributed modules that help you create business logic, such as: Rules, Triggers, Rules Link, Maestro and WorkBench all help you create types of business logic.

Modules like References, Relation, Field Collection, Paragraphs let you create "embedded relationships". Mix and match as you need.

... I got tired of linking contrib modules :P

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


title: page--front.tpl.php not working

text:
# Question
Title: page--front.tpl.php not working
I have omega 4 installed as my sub-theme, in which i have a custom layout. Now i am trying to make my home page custom, for which i have defined page--front.tpl.php in my templates/system folder, but its not working. I did explored the drupal questions/answers but nothing worked for me. I also tried to add

```
$variables['theme_hook_suggestions'] = array('page__front');

```

But it doesn't seems to be working either. How do i make it work, please help??

# Answer
You don't have to specify a suggestion for the front page, it is already one.

The only thing you have to do is create page--front.tpl.php and clear your cache.

See the list of template suggestions.

Then if it doesn't work then something else in your setup is interfering somehow but we don't know much about your site so it's hard to debug from there.
> 3 votes

---
Tags: theming
---


# Question
Title: Set entity reference field in form to readonly
I am building a custom module to set default values for entity reference fields. To avoid overwriting these defaults, i would like to set the field readonly. While I got the defaults to work, setting it readonly does not work, the field is still editable. Here is my code :

```
function prepopulate_references_form_alter(&$form, $form_state, $form_id) {
  $query = new EntityFieldQuery();
  $query
    ->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'producttype')
  $result = $query->execute();
  $refobject_ids = array_keys($result['node']);
  // the next line works great:
  $form['field_testreference'][LANGUAGE_NONE]['#default_value'] = $refobject_ids;
  // this line doesn't have any effect:
  $form['field_testreference'][LANGUAGE_NONE]['#attributes']['readonly'] = TRUE;
  // ... and this one neither:
  $form['field_testreference'][LANGUAGE_NONE]['#attributes']['disabled'] = TRUE;

```

What is the problem here?

Edited: As Darvanen suggested, `dpm()` shows that `$form['field_testreference']['#access'] = FALSE;` works great.

# Answer
> 1 votes
Perhaps it's because you're referencing a language where it isn't necessary, try one of these:

```
$form['field_testreference']['#access'] = FALSE;

```

or

```
$form['field_testreference']['#attributes']['readonly'] = TRUE;

```

---
Tags: entities
---


# Question
Title: Simple row saving through link with Drupal 7
I have a simple requirement but I am not sure how to fulfill it. On my Drupal site, I need a link which when I click creates a row in a table in DB through AJAX.

That's about it.

The main goal of mine is to create a "My List" for any user. The user can go to any node and press "Save it" and it can then save it to the "List". User can later go to "My List" and see all the "saved" nodes which he saved.

Hence Basically, it's a Save for later for the nodes.

I hope there is some module for it. I couldn't find hence I thought I can create it myself, hence the question.

Many Thanks

# Answer
take a look at the Favourites module:

> Favorites provides a tiny block that allows users to easily bookmark any content of the site.

or the Flag module:

> Flag is a flexible flagging system that is completely customizable by the administrator. Using this module, the site administrator can provide any number of flags for nodes, comments, users, and any other type of entity. Some possibilities include bookmarks, marking important, friends, or flag as offensive. With extensive views integration, you can create custom lists of popular content or keep tabs on important content.
> 3 votes

---
Tags: views
---


# Question
Title: Problems trapping AJAX'ed form input click event
Using Drupal 7.x w/ jQuery 1.4x, I'm trying to trap the click event when I click on a submit input of an AJAX form generated from this Commerce AJAX Cart module.

In my custom.js behaviors file, I have the following code.

```
$(".form-submit").click(function(){
    alert('test');
});

```

The alert doesn't get displayed and I have no clue as to why. I load my custom.js file from template.php using the following code.

```
drupal_add_js(path_to_theme() . '/scripts/global.js', array('weight' => 200));

```

I tried lowering 200 down to insanely low levels just to test if weight had anything to do with any of this, but nothing I tried helped.

Any ideas as to why this click event isn't working would be helpful.

# Answer
> 0 votes
Because the form is being loaded via ajax, your click handler is not binding at the right time. You need to use Drupal.behaviors, the context argument, and possibly the one() method to attach this.

Or a less drupally (but better jQuery) solution would be to use delegated events like

```
$(document).click(function(event)) {
  if ($(event.target).is(".form-submit") {
    alert('test');
  }
});

```

Note: delegated events are *way* more elegant in modern jQuery, the on() method is great for this. But the above is probably the best you can do in jQuery 1.4.

---
Tags: 7, ajax
---


title: Unable to print form submission result

text:
# Question
Title: Unable to print form submission result
The structure of my form is as follows:

Form is built here

> function mymodule\_member\_search\_form

The form submission processing happens in the callback function

> \_mymodule\_search\_form\_submit(&$form, &$form\_state)

Here I am able to get the results and do the various processing I want and the final result I have stored in

```
if(isset($myvalues)){
        $form['results'] = array(
            '#type'     => 'item',
            '#markup'   => $myvalues,
        );
    }

```

But the values are not printed on the page after form submission, I have also set

```
$form_state['rebuild'] = TRUE;

```

in the above submission function

What am I missing here?

Additional Information is this form I have added as a block. So do I have to pass this ass the result of block? If yes, how do I do that?

Thanks.

# Answer
> 0 votes
I believe you start with a fresh form in `mymodule_member_search_form()`, i.e. with `$form = array();`. Is it correct? If so, your `$form['results']` are not in the form returned by `mymodule_member_search_form()`. You should either do the processing in form callback itself or fetch results from the form prior to redefining it.

---
Tags: 7, forms, blocks
---


# Question
Title: How to shift/change timestamp in a scheduled rule?
A scheduled rule was triggered. Is it possible to change a date of the scheduled action? (programmatically or not) For example, the scheduled action will be triggered in 3 days but then you would like to change it for 1 day.

# Answer
Yes, the timestamp of when the task is to be scheduled is stored in `rules_scheduler` db table, in `date` field. You can run a query like:

```
db_update('rules_scheduler')
  ->expression('date', 'date + 86400') // 86400 = 24 * 60 * 60
  ->condition('tid', $your_task_id)
  ->execute();

```
> 1 votes

---
Tags: rules
---


# Question
Title: drupal loses track of a library (leaflet), randomly
I have an strange problem with a library (leaflet).

I have some maps, and it works fine, but randomly (as far as I have been able to detect) drupal is unable to find leaflet.js and leaflet.css (it is allways located in sites/all/libraries/leaflet , as indicated in leaflet drupal module website).In fact I can see in Firebug that Drupal is not even trying to get the library (I get no server error message saying it cannot find the files or similar)

When this 'error' happens, I have to do strange things like moving the leaflet.js file to another folder or change the name and then, after drupal fails and I rename the file again, MAYBE drupal is able to find it again. Sometimes it seems like flushing cashes helps but not allways...I know it sound dummy but it only happens with this libarry and it seems completely random. Hours wasted trying to set up again...

The folder is 755 in permissions. Have tested in a different PC and the same problem! changing browser or clearing its cache doesn't help neither.

thanks in advance

# Answer
How do you see that drupal does not find that files? Is it correct that you just get 404 for that files in browser? Try to load these files in browser window like http://yourdomain.com/sites/all/libraries/leaflet/leaflet.js. If it's not loaded, it's your server issue, rather than drupal one.
> 0 votes

---
Tags: javascript, caching
---


# Question
Title: Remove or hide the submit button on search block in Drupal 7
I need to do some custom theming on the search block in Drupal 7.

Specifically, **I need to add a class to the submit button that makes it invisible and removes it from the content flow.** So:

```
<div class="form-actions form-wrapper" id="edit-actions">
  <input type="submit" id="edit-submit" name="op" value="Search" class="form-submit">
</div>

```

Becomes...

```
<div class="form-actions form-wrapper element-invisible" id="edit-actions">
  <input type="submit" id="edit-submit" name="op" value="Search" class="form-submit">
</div>

```

I added `element-invisible` to the edit-actions div element. However, I can't figure out how to do this. What's the best practice for doing this sort of thing?

# Answer
One of the standard ways to do this would be to use `hook_form_alter()` and add the attributes to the actions element directly:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form['actions']['#attributes']['class'][] = 'element-invisible';
  }
}

```
> 13 votes

# Answer
You can also hide it using a php condition like this:

```
<?php
function your_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'your_form_id') {
      unset($form['actions']['submit']);
  }
}
?>

```
> -1 votes

---
Tags: 7, search, theming
---


# Question
Title: Add custom CSS code for a textbox in form
The following are the code in my module function for textfield in my form:

```
 $form['price'] = array(
   '#type' => 'textfield',
   '#title' => 'What is Your Price?',
   '#size' => 100,
   '#maxlength' => 10,
   '#required' => TRUE,
  );

```

Now I want to add css for the textbox like I want to add inline code `display:none;` only for the textbox. How can I do that? Please help.

# Answer
I do it like this:

```
function the_form($form, &$form_state){
     $form['price'] = array(
       '#type' => 'textfield',
       '#title' => 'What is Your Price?',
       '#size' => 100,
       '#maxlength' => 10,
       '#required' => TRUE,
       '#prefix' => '<div style="display:none;">',
       '#suffix' => '</div>',
     );

```
> 2 votes

---
Tags: theming
---


# Question
Title: How to get term name using PHP code in views? Drupal 6!
how can i get term name of current term using PHP code? I am using it in views. Thank you.

I dont know why, but the below code doesant work:

```
$term = taxonomy_get_term($tid);
$name = $term->name;

```

# Answer
> 0 votes
If you want to get the term name of current node in views you can make use of `Content: All taxonomy terms field`. There is no need for diving into PHP code.

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


# Question
Title: Image widget stopped working after core update
I recently did a long overdue update from 7.20 to 7.33.

However, after I've made the update, the "Image" widget has stopped working when trying to edit content through the admin screen. I cannot add or remove any images using this widget - it makes an AJAX call and the request comes back as 200, but the image upload/removal fails without an error.

I think it's a problem with the AJAX but I can't be sure.

# Answer
> 0 votes
Got it - the AJAX form was not being cached by memcache, and so it was failing out every single time. Restarting memcache did the trick.

---
Tags: ajax
---


title: "no line items found" in user order

text:
# Question
Title: "no line items found" in user order
I have installed Drupal Commerce (7.x.1.8 version) but in user orders section when I select an order only price and total is shown. In despite of order details the message "no line items found" appears. What can I do on here to show order datails?

# Answer
> 1 votes
I found a solution that worked for me via this article.

The author propose to change the Commerce view settings.

# Answer
> 0 votes
This is a common problem for anonymous users depending on the permission configuration you might have, the usual solution is to disable the SQL query rewriting for the affected view.

Check out these related issues in drupal.org

# Answer
> 0 votes
'Disable SQL rewriting' in the affected view:

1. Edit the view: in 'Advanced' select 'Query settings'
2. Select 'Disable SQL rewriting'

---
Tags: commerce
---


# Question
Title: How to add special character validation on specific field in form registration process
I want to add a special character validation on a specfic field. Here I have my code but it does not work and there is no error.

```
function mymodule_form_alter(&$form, &$form_state, &$form_id) {
   if ($form_id == 'registration_node_form') {
        $form['#validate'][] = 'mymodule_form_validate';
   }
}

function mymodule_form_validate($form, $form_state){
    if(isset ($form['field_employer_name']['und'][0]['value']['#default_value'])){
        $special_character_list = '[\'^£$%&*()}{@#~?><>,|=_+¬-]';
        if (preg_match($special_character_list, $form_state['field_employer_name']['und'][0]['value']['#default_value'])== 0) {
            form_set_error('field_employer_name', t('The specified form name contains one or more illegal characters. Spaces or any other special characters except dash (-) and underscore (_) are not allowed.'));
        }
    }
}

```

Please help. Thank You.

# Answer
Try using Field Validation Module it simplifies your work!!

If you want to code it then check this post It solves the same issue

Try changing your code:

```
 $special_character_list = '\'^£$%&*()}{@#~?><>,|=_+¬\-\[\]';
  if(preg_match('/[' . $special_character_list . ']/',$form_state['field_employer_name']['und'][0]['value']['#default_value']) !== 0)

```
> 2 votes

---
Tags: javascript, forms, 7
---


title: Language fallback stack

text:
# Question
Title: Language fallback stack
I have 4 language versions on my website. Is there a way to define a language fallback order?

For example, if I'm on a node page and the language is set to English and there's no English translation I'd like Drupal to look for French, then German, then Spanish translation.

# Answer
If you have language fallback enabled, then the fallback order is the order of the languages you have set at `admin/config/regional/language`
> 1 votes

# Answer
You can try Language Hierarchy module. It works with entity translation, i18n menu, i18n node translation and string translations.
> 0 votes

---
Tags: i18n-l10n
---


# Question
Title: Duplicate home / front page - available on two urls
I created a view and set it as the front page; its path is */front*.

The front page is accessible as https://example.com/ and https://example.com/front. Is there a way to prevent this?

# Answer
> 3 votes
It's normal Drupal behavior to have front page accessible by it's original path.

What I would recommend in the case is installing the Global Redirect module and configuring it to 301 redirect from `/front` to `/`.

---
Tags: 7, views
---


title: Date field Start and End limit

text:
# Question
Title: Date field Start and End limit
When we create a date field in node form, we can set START and END years to be shown in that date field. If we are creating a date field programatcaly, how do we do that?

I have a date field, `my_date`, I want to to show only next 5 years from now on. Any help?

```
$form['my_date'] = array(
  '#type' => 'date',
  '#date_format' => 'd-m-y',
  '#default_value' => format_date($primary_start1, 'custom', $format),
  '#date_type' => DATE_DATETIME,
  '#date_timezone' => date_default_timezone(),
  '#date_format' => 'm/d/Y',
  '#size' => 20,
  '#access' => TRUE,
);

```

I tried to see structure bu creating a date field and printing the form, but found nothing.

# Answer
> 0 votes
We can do it like this...

```
$form['my_date'] = array(
  '#type' => 'date',
  '#date_format' => 'd-m-y',
  '#default_value' => format_date($primary_start1, 'custom', $format),
  '#date_type' => DATE_DATETIME,
  '#date_timezone' => date_default_timezone(),
  '#date_format' => 'm/d/Y',
  '#size' => 20,
  '#access' => TRUE,
  '#after_build' => array("custom_range_date")
);

```

using `'#after_build' => array("custom_range_date")`

```
function custom_range_date($form_element, &$form_state){
    // We unset the current values
    unset($form_element['year']['#options']);

    // Now we set the range we want
    $max_age = date('Y') - 100; // 100 years ago
    $min_age = date('Y') - 7; // 7 years ago

    // Now we populate the array
    $form_element['year']['#options'] = array();
    foreach (range($max_age, $min_age) as $year){
        $form_element['year']['#options'][$year] = $year;
    }

    // We return our modified element
    return $form_element;
}

```

SEE: https://www.drupal.org/node/1165138

---
Tags: datetime
---


# Question
Title: Drupal 7 views - distinct not working with ordering by multiple (date) field
I have "Episode" content type and some "Showing from" date field in it which is repeating (more than one value can be added). Then I have a view that list episodes ordered by that field, which works, but I want to exclude same episodes. Now if episode has i.e. 3 times that fulfill filter criteria episode will be listed 3 times. I checked "Distinct" option but it doesn't help - still episode is listed 3x. Actually I'm not very sure how Distinct works - is it possible to select a filed that has to be distinct (if yes - how?) or it works for all fields? I would like to set distinct on episode nid of course.

# Answer
* Apply a filter on the date field
* Select the operator: 'Is equal to', and type '0'

> When you have a multiple value field, the field has a list or array of values. delta=0 is the first value

https://www.drupal.org/node/1872262#comment-6869736
> 1 votes

# Answer
for that you can use aggregation with views i.e in advanced option in views from their you can use aggregation yes, and in that field click agregation settings set your option as distinct
> 0 votes

---
Tags: views
---


# Question
Title: Check if the page is the front page in a template
How do I make a simple front page check wich only shows a in my template when the user is on the front page of the drupal website?

I tried this but it ended up crashing:

```
<?php function drupal_is_front_page() {?> <h1>TEST</h1> <?php } ?>

```

Is this possible with a if instead of this function wich i found on the drupal website?

Thanks!

# Answer
> 19 votes
You should not declare a function in a Drupal template. Instead, you should just refer to that function:

```
<?php
if (drupal_is_front_page()) {
    ?><h1>Test</h1><?php
}
?>

```

# Answer
> 6 votes
`drupal_is_front_page()` returns boolean value.

```
<?php if(drupal_is_front_page()): ?>
<h1>TEST</h1>
<?php endif; ?>

```

---
Tags: 7
---


# Question
Title: Run a view's bulk operation immediately but in background. Is that possible?
Is it possible to run a view's bulk operation immediately after pressing the button but in the background (in other words, without forcing the user to wait until the progress bar completes to 100%)?

I understand that this can be achieved by enqueuing the operation. But the problem of this solution is that execution is postponed until cron is run.

Thanks.

# Answer
PHP needs something to drive the process, it's not multi-threaded. Drupal's queue process runs by either the client's browser making a series of calls (kind of like it emulates the cron), or by the cron itself.

Why isn't the cron an acceptable method? You can use something like ultimate\_cron The control the schedule for each cron tasks.

## Update

As @Molot mentioned, the CLI is an option. I believe `shell_exec` is subject to PHP's timeout (I could be wrong). See this blog post on executing PHP in an asynchronous fashion.
> 0 votes

---
Tags: views, actions
---


# Question
Title: Where to export i18n mode for menus in features?
I'm using a combination of Entity Translation and Node Translation for a site and when I go and set up the menu, I need to edit each menu and select Translate and Localize.

Where is the feature to export this?

# Answer
> 2 votes
This is stored in the menu itself. Menu\_links aside, the menu features wil be stored in some custom.inc file.

---
Tags: 7, i18n-l10n
---


# Question
Title: Restrict language content for a given role
I have a multilingual site (spanish/english). I created 1 role: **translator**.

I need the **anonymous users** to ONLY see the contents in english language and the **translator users** to see both.

How can I accomplish this?

# Answer
> 0 votes
A way to achieve it can be this. Note I am assuming you are using the standard node-based translations, and *not* entity-based translations.

Suppose the content is a node-type one and the content-type is called `Page_en_es`. Give permissions at `/admin/people/permissions`:

1. `View own unpublished content`, `Page_en_es: Edit any content` etc to *translator users*
2. `View published content` to *anonymous users*.

Then, whenever a translator edits or creates the Spanish content, s/he will set it (=node) to be **not** published. And the Spanish version won't be seen by anonymous users.

---
Tags: users, i18n-l10n
---


title: How to create Content Types with Drush

text:
# Question
Title: How to create Content Types with Drush
Is it possible to create content types with Drush? Such as a new Galery content type?

I created a content type manually via web interface and checked the changes in database. However, there are quite a lot of changes - some changes are also in blob fields.

How do you do this?

# Answer
> 5 votes
If you want to re-create content-types you have created in other drupal-installations you can use the features module:

This module allows you to export content-types to code (called features). Those features can be copied to other sites like normal modules and then be activated via drush using

drush en -y feature\_name

# Answer
> 1 votes
In the drush docs I don't see anything like `drush entitytype-bundle-create node foo` but I do see `drush field-create` which is pretty cool.

http://www.drushcommands.com/drush-7x/field/field-create

---
Tags: nodes, drush
---


# Question
Title: Services custom resources issues - IIS, MSSQL
This really is two issues, but possibly both are related.

Main issue:

I have a custom resource setup in Services, the endpoint seems to be "mostly" working. The endpoint is api/ada/ and my resource is named "assessment", so when I go to mydomain/api/ada/assessment/retrieve, it works. I have an arg setup which is the assessmentID to retrieve and I'm returning a json array with just that ID for my test.

When I set the arg source to array('path'=\>'0') it works, but the ID value in the json aray is the word 'retrieve'. When I set the path to '1' and go to mydomain/api/ada/assessment/retrieve/1 I get a "Controller not found" error in my console (using Chrome).

Secondary, but possibly related:

I have my custom module info file setup with files\[\] = includes/my\_module.inc which doesn't seem to work, so my callback in the above has to be in the same file for it to work. When I try to require 'includes/my\_module.inc' or do module\_load\_include(...) it's outputting the file contents onto the screen rather than including them. I'm certain this is an IIS config issue, but you'd think other modules would be doing this, but it's not, I get no other errors (or this type of output) across the site, though I'm less certain of that.

Anyway, I've setup a work-around using the hook\_menu() functionality and setting up an "api" of sorts so I can build out the functionality while I recover from bashing my head on the desk trying to figure this endpoint issue out, but I get the module\_load\_include(...) error in this method as well, so I'm thinking maybe it's not entirely an issue with the Services Module.

Any help is greatly appreciated!

Link to code

# Answer
> 1 votes
In your case the path should be 'path' =\> 0, because it is the first argument after the endpoint url. Currently you have 1 and it will look for undefined argument which will end up with an exception.

For more information read services oop to get a better understanding in an OOP way. https://github.com/hugowetterberg/services\_oop

---
Tags: services, iis, database
---


# Question
Title: Location Proximity Search using db_select in Custom Module
I want to build a custom block which uses the nid of the node it's visible on to pull in nodes within a radius of 50 miles based on it's geolocation. I am using the location module and gmap where doing this query in views is easy but I have no idea where to even begin in building this query in db\_select.

this is what views is outputting for the same query:

```
SELECT node.title AS node_title, node.nid AS nid, (COALESCE(ACOS(0.61832265427253*COS(RADIANS(location.latitude))*(0.99735883206175*COS(RADIANS(location.longitude)) + -0.072631674277943*SIN(RADIANS(location.longitude))) + 0.78592435718291*SIN(RADIANS(location.latitude))), 0.00000)*6364902.7458257) AS location_distance_sort
FROM
{node} node
LEFT JOIN {location_instance} location_instance ON node.vid = location_instance.vid
LEFT JOIN {location} location ON location_instance.lid = location.lid
WHERE (( (node.nid != '3849' OR node.nid IS NULL) )AND(( (node.status = '1') AND (node.type IN  ('weather_reports')) AND (location.latitude > '51.081897505891' AND location.latitude < '52.530604494109' AND location.longitude > '-5.3366374087818' AND location.longitude < '-2.9936745912182') AND ((COALESCE(ACOS(0.61832265427253*COS(RADIANS(location.latitude))*(0.99735883206175*COS(RADIANS(location.longitude)) + -0.072631674277943*SIN(RADIANS(location.longitude))) + 0.78592435718291*SIN(RADIANS(location.latitude))), 0.00000)*6364902.7458257) < '80467.35') )))
ORDER BY location_distance_sort ASC
LIMIT 1 OFFSET 0

```

How do i run a db\_select query to select the nodes within 50 miles of 51.6599, -3.9215

# Answer
Thanks to @joemurray for pointing me in the right direction. This is my function to grab the closest nid to my target nodes lat, long.

```
/**
 *
 * Load the nid we are interested in for this report taken from the page we are on.
 * [http://funkjedi.com/technology/308-search-using-geolocation-data-in-mysql/][1]
 */
function _load_proximity_nids($lat, $lon) {
  $nids = array();

  // in Miles
  $radius = 25;

  // Constants related to the surface of the Earth
  $earths_radius = 3958.9394;
  $surface_distance_coeffient = 69.174;

  // Spherical Law of Cosines
  $distance_formula = "$earths_radius * ACOS( SIN(RADIANS(latitude)) * SIN(RADIANS($lat)) + COS(RADIANS(longitude - $lon)) * COS(RADIANS(latitude)) * COS(RADIANS($lat)) )";

  // Create a bounding box to reduce the scope of our search
  $lng_b1 = $lon - $radius / abs(cos(deg2rad($lat)) * $surface_distance_coeffient);
  $lng_b2 = $lon + $radius / abs(cos(deg2rad($lat)) * $surface_distance_coeffient);
  $lat_b1 = $lat - $radius / $surface_distance_coeffient;
  $lat_b2 = $lat + $radius / $surface_distance_coeffient;

  // Construct our sql statement
  $results = db_query('SELECT node.title AS node_title, node.nid AS nid, node.status AS status, node.type AS type, (' . $distance_formula . ') AS distance
FROM
{node} node
LEFT JOIN {location_instance} location_instance ON node.vid = location_instance.vid
LEFT JOIN {location} location ON location_instance.lid = location.lid
WHERE (location.latitude BETWEEN ' . $lat_b1 . ' AND ' . $lat_b2 . ') AND (location.longitude BETWEEN ' . $lng_b1 . ' AND ' . $lng_b2 . ') HAVING distance < :radius
AND (node.status = 1)
AND node.type = :type
ORDER BY distance ASC',
  array(
    ':type' => 'weather_reports',
    ':radius' => $radius)
  );

  foreach ($results as $result) {
    $nids[] = $result->nid;
  }

  return $nids;
}

```
> 2 votes

# Answer
Given your comment, I see the question is related not to the query itself but how to use db\_select. I don't think you should. Use db\_query() instead - https://api.drupal.org/api/drupal/includes%21database%21database.inc/function/db\_query/7

If you are comfortable hardcoding the lat/long and 50 miles, then you don't need to change the query in order to accept arguments for these values.

Assuming the query was produced for the latlong and 50 mile radius you provide, then it looks to me like you just need to remove the LIMIT 1 OFFSET 0 to get all of the relevant nodes, like this:

```
    SELECT node.title AS node_title, node.nid AS nid, (COALESCE(ACOS(0.61832265427253*COS(RADIANS(location.latitude))*(0.99735883206175*COS(RADIANS(location.longitude)) + -0.072631674277943*SIN(RADIANS(location.longitude))) + 0.78592435718291*SIN(RADIANS(location.latitude))), 0.00000)*6364902.7458257) AS location_distance_sort
FROM
{node} node
LEFT JOIN {location_instance} location_instance ON node.vid = location_instance.vid
LEFT JOIN {location} location ON location_instance.lid = location.lid
WHERE (( (node.nid != '3849' OR node.nid IS NULL) )AND(( (node.status = '1') AND (node.type IN  ('weather_reports')) AND (location.latitude > '51.081897505891' AND location.latitude < '52.530604494109' AND location.longitude > '-5.3366374087818' AND location.longitude < '-2.9936745912182') AND ((COALESCE(ACOS(0.61832265427253*COS(RADIANS(location.latitude))*(0.99735883206175*COS(RADIANS(location.longitude)) + -0.072631674277943*SIN(RADIANS(location.longitude))) + 0.78592435718291*SIN(RADIANS(location.latitude))), 0.00000)*6364902.7458257) < '80467.35') )))
ORDER BY location_distance_sort ASC;

```

My sense is that the code has calculated a bounding rectangle 50 miles in every direction for the where clause as a performance optimization. The trigonometry calulations define the distance between the nodes/latlongs, and is used to limit to a 50 mile radius in the where condition and just to provide the distance in the SELECT clause.

If you want to be able to produce queries like this for other latitudes and longitudes or radiuses, I would recommend looking at how the code converts miles to degrees, and calculates the values in the rest of the trig parts of the query.
> 1 votes

---
Tags: location, google-maps, database
---


# Question
Title: How to add role selection field to the registration form?
How can I add the role to registration form that users can choose their role?

I tested the Profile2 module and the Auto Assign Role module but they don't do what I want.

I want to add a CCK field in the admin/configure/account/fields.

**Is there any module to add a CCK field to registration form for choosing the role?**

# Answer
> 1 votes
If any module doesn't fit yoour requirement then you can use the below code You can create any custom module or put this code in template.php of your theme. function testing\_custom\_form\_alter(&$form, $form\_state, $form\_id){

```
if($form_id=="user_register_form"){
    $result = db_select('role', 'r')
                ->fields('r',array('rid','name'))
                ->condition('name',array('administrator','anonymous user'),'NOT IN')
                ->execute()
                ->fetchAll();
    $role   =   array();
    foreach($result as $userRole){

        $role[$userRole->rid] = $userRole->name;
    }

$form['role']['#type'] = "select";
$form['role']['#options'] =$role;
$form['role']['#required'] = 1;
$form['role']['#size']='auto';
    $form['#submit'][] = 'custom_assign_role';

}

}

function custom_assign_role(&$form, $form_state){
   $uid=  $form_state['values']['uid'];

    user_multiple_role_edit(array($uid), 'add_role', $form_state['values']['role']);

}

Hope it will help!

```

# Answer
> 1 votes
Role selection actually already exists on the user registration form, it's just not accessible for unauthenticated users.

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  // Display the roles selection.
  $form['account']['roles']['#access'] = TRUE;

  // Get available roles.
  $roles = array_map('check_plain', user_roles(TRUE));

  // Unset system roles.
  unset($roles[DRUPAL_AUTHENTICATED_RID]);
  unset($roles[DRUPAL_ANONYMOUS_RID]);

  // Add options without system roles.
  $form['account']['roles']['#options'] = $roles;
}

```

Where the user\_account\_form is built: https://api.drupal.org/api/drupal/modules%21user%21user.module/function/user\_account\_form/7

Where the user\_account\_form is included in the user\_register\_form: https://api.drupal.org/api/drupal/modules%21user%21user.module/function/user\_register\_form/7

# Answer
> 0 votes
You can add field called as field\_role over here `admin/config/people/accounts/fields` and assign various roles to it.You can use select list.

Based on role selected while registering you can assign that role to the user by using rules module.

* Rules module you can compare text comparison for the selected field\_role by user while registering.
* Based on that you can assign user the role what you want to assign for each text.

Example:

```
     Seller as Seller(Roles)

     Editor as Editor(Roles) etc

```

---
Tags: users, forms
---


# Question
Title: Load certain modules only if user is administrator
I have a number of custom admin modules that deal with site statistics, site management, etc. These are quite heavy and I would like to reduce the site footprint for non-admin users.

Is there anyway to selectively load modules based on a users role? For example, if the user is an admin the load everything otherwise exclude modules admin1, admin2 and admin3.

# Answer
> 1 votes
Modules are either enabled or disabled in Drupal. They then may use access control to determine whether the user has access to them.

If these are custom modules, you may wish to write them so that either the heavy processing is skipped for non-admins, or that the data is cached to avoid calculations on every page load.

---
Tags: hooks, users
---


title: Why would $user->sid be undefined?

text:
# Question
Title: Why would $user->sid be undefined?
I added some debugging statements (using dd()) which include a timestamp and $user-\>sid (after declaring $user as a global). I tested it, of course, and everything worked great for me. Then a user reported getting some notices which said "Undefined property: stdClass::$sid ..."

I added a conditional to test to see if $user-\>sid is set before writing out the value, but I didn't think that it was possible for it to not be set! I did some quick Google and drupal.stackexchange.com searches, but couldn't find any info on how this might be possible.

Anybody have any insight here?

TIA, Lee

# Answer
> 1 votes
If you are not logged in the property will be undefined. This is all I've got for the anonymous user

```
object(stdClass)#7 (4) {
  ["uid"]=>
  int(0)
  ["hostname"]=>
  string(9) "XXX.XXX.XXX.XXX"
  ["roles"]=>
  array(1) {
    [1]=>
    string(14) "anonymous user"
  }
  ["cache"]=>
  int(0)
}

```

---
Tags: 7
---


# Question
Title: How to add 'add to cart' button to view based on a search index?
Just got started with search\_db and the search\_api and facets. I have a view set on an index of my commerce products, but I don't have the option to add the 'add to cart' form as a field. There isn't an option to pull one in from a related field that I can see either. Any help would be appreciated.

thnx

# Answer
> 0 votes
I changed the index from the Commerce Products to the product displays, and this got me a different range of field choices. I could have probably achieved a similar result by adding a relationship, but I wanted this to be relatively clean and simple.

---
Tags: commerce, search
---


# Question
Title: How to redirect URL with language prefix to the same URL with no prefix (default language)
I have installed i18n module so two languages Japanese and English are available. I have set Japanese to the default language and also "language Language negotiation" to "path prefix only". So all the URL without language prefix show the Japanese pages and English pages with the prefix of "en".

What I want to do is to redirect some of URL with prefix to the same URL without prefix as I need to make some of the pages available only in Japanese. For example, when a user is trying to view `my-site.com/en/cart` the user is automatically redirected to `my-site.com/cart` as I want to make the `my-site.com/en/cart` unavailable.

I have tried path redirect but the redirect doesn't work though I set two cases as below

1. "Language" to "All languages " ,"From" to "my-site.com/en/cart" and "To" to "my-site.com/cart".
2. "Language" to "English" ,"From" to "my-site.com/en/cart" and "To" to "my-site.com/cart".

# Answer
> 1 votes
The below answer requires that at least part of your website is using Page Manager + Panels. In my opinion, they *should* anyway, but others will disagree. Both of these modules are **tools**, as opposed to solutions, so this answer will require that you research and understand these two modules. Link to excellent video tutorial. At the time of writing, this requires the -dev version of Ctools.

At the time of writing, this Ctools patch must be applied for the following instructions to work.

1. Ensure that the page you want to redirect *from*, is managed by Page Manager. This page will have 2 variants.
2. Add a "HTTP response" variant, with a 301 response to cart. More details on this step in another question. It's important that this variant is the *topmost* one. You can reorder them afterwards, if need be.
3. On the HTTP variant, go to the "Context" tab on the left side, add a "Language" context, selecting "Current language".
4. Go to the "Selection rule", and add a "User:Language" == "English".
5. Add a second variant, this time a Panels variant.
6. In the second variant, add all the content that you wish to be part of the Japanse page.

# Answer
> 0 votes
In .htaccess, add directive

```
RewriteRule ^en/(.*)$ http://my-site.com/$1 [L,R=301]
RewriteRule ^cn$ http://my-site.com [L,R=301]

```

---
Tags: redirection, i18n-l10n, multi-sites, uri
---