# Question
Title: Drupal 7 custom block not showing in block list
A Drupal 7 newbie here, with the following problem.

***I have enabled my block with it's dependencies, but doesn't show in the block list***

Can anyone spot anything I might've missed in my code?

Any help to point me in the right direction will be deeply appreciated!

Thanks in advance!

The code is the following.

*.info file*

```
name = Bloque para el buscador - INMO
description = Bloque para mostrar el buscador geográfico de InmoAnuncios.
package = Modulos de Inmo Anuncios
core = 7.x

scripts[] = bloque_buscador.js // exist in folder

dependencies[] = inmo_node_form // enabled

```

*.module file*

```
<?php

/**
 * @file
 * Modulo para el buscador de inmuebles
 *
 * Este modulo provee de un bloque donde se despliega un buscador de inmuebles en el sitio
 */

/**
 * Implementa el hook_block_info()
 * Este hook le dice a DRUPAL que este bloque se puede desplegar tanto en el home page como en el sidebar
 */
function bloque_buscador_block_info() {

    $blocks = array();

    $blocks['bloque_home'] = array(
        'info' => t('Inmo Buscador (home)'),
        'cache' => DRUPAL_NO_CACHE,
    );

    $blocks['bloque_sidebar'] = array(
        'info' => t('Inmo Buscador (sidebar)'),
        'cache' => DRUPAL_NO_CACHE,
    );

    return $blocks;
}

/**
 *
 * @param type $delta
 * @return type
 * Implementa el hook_block_view()
 *
 *
 */
function bloque_buscador_block_view($delta = '') {

    $estados = db_query("SELECT * FROM estados WHERE enabled = 1;");
    $inmuebles = db_query("SELECT * FROM tipo_inmueble WHERE enabled = 1;");

    $optEstados = '';

    foreach ($estados as $estado) {
        $optEstados .= "<option value=\"{$estado->id}\">{$estado->nombre}</option>\n";
    }

    $optInmuebles = '<option value=\"0\">--Todos--</option>';

    foreach ($inmuebles as $inmueble) {
        $optInmuebles.= "<option value=\"{$inmueble->tipo_inmueble}\">{$inmueble->tipo_inmueble}</option>\n";
    }

    $contenido = <<<EOSTR
      <div class="jsrequired {$delta}" id="bloque_buscador">
        <header class="title">
          <h2>Encuentra tu inmueble ideal!</h2>
        </header>
        <div class="filtros">

          <form action="/filtro" method="GET">
            <table  border="0" cellpadding="0" cellspacing="0">
                <tr>
                    <td><label for="operacion">Busco inmuebles en:</label></td>
                    <td>
                        <label class="vc">Venta <input type="radio" name="operacion" id="operacion" value="venta"/></label>
                        <label class="vc">Renta <input type="radio" name="operacion" id="operacion" value="renta" /></label>
                    </td>
                </tr>
                <tr>
                    <td><label for="tipo_inmueble">Tipo de inmueble?</label></td>
                    <td><select name="inmueble" id="inmueble" style="width:150px;"> $optInmuebles </select></td>
                </tr>
                <tr>
                    <td><label for="estado">En donde?</label></td>
                    <td><select name="estado" id="estado" style="width:150px;"> $optEstados </select></td>
                </tr>
                <tr>
                    <td colspan="2"><input type="submit" value="Buscar"></td>
                </tr>
          </table>
            </form>
        </div>
        <div class="mapa"><a href="#" class="mapa_buscador"></a></div>

      </div>
EOSTR;

  $bloque = array(
    "subject" => NULL,
    "content" => $contenido
  );
  return $bloque;
}

?>

```

# Answer
That is because your module\_block\_view() function is not written properly. the content is not passed into any of the blocks you defined in your module\_block\_info()

```
function bloque_buscador_block_view($delta = '')
{
        $block = array();
        switch ($delta)
       {
        case 'bloque_home':
            $block['subject'] = t('Syndicate');
            $block['content'] = YOUR CONTENT IN HERE,

        );
        break;
        case 'bloque_sidebar':
            $block['subject'] = t('Syndicate');
            $block['content'] = YOUR CONTENT IN HERE,

        );
        break;
      }
    return block;
 }

```
> 1 votes

# Answer
I don't see anything strange in your code in itself, especially the *hook\_block\_view()*!

Omission of the usual check on delta param in *hook\_block\_view()* is justified in your case as to my understanding that both blocks display the **same** content.

Beyond Clive's check points you may also try to *first delete your module's block entries* in Drupal's **block** DB table.

You can read full explanation of this suggestion in my answer to similar question:

Custom made blocks not getting displayed in Blocks page
> 0 votes

---
Tags: blocks
---


title: Custom template file field output

text:
# Question
Title: Custom template file field output
I have a *Netrunner Card* content type. (It's a card game I play.) I have a "field\_card" field that holds the card image. In the node--netrunner-card--Runner\_Identity\_Card--full.tpl.php file, I am trying to control the output of each field. Instead, I seem to just be dumping the same fields on the screen.

I tried using the following code.

```
<img src="<?php print render($content['field_card'])?>" />

```

It scattered the HTML, because the output of `render()` **is** the HTML. What is the standard practice for doing what I am trying to do?

I'm trying to theme the output of each card to make it look like I want it to be, and to learn the theming engine for Drupal.

# Answer
Typically, to control the output of your field you'd just print out all your fields in your template files by doing precisely what you have up there:

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

```

You can have as much html in your template file in addition to these rendered fields and then style them with css! So you can have

```
<div id="some_field_grouping">
  <?php print render($content['field_1']); ?>
  <?php print render($content['field_2']); ?>
</div>

```

And then theme this with css using any of the ids and classes you get and whatever the fields themselves render.

If you *really* need to modify the field's output more precisely and the standard output from print render doesn't work for you, you could certainly look into the field structure itself and grab the individual field parts you need. I'd only do this if you absolutely need to...

To start peering into the exact structure of the fields, I'd

* Install and enable the devel module... You can just enable the 'Devel' module that comes with it for this purpose
* In your template file, put a

```
<?php dsm($content['your_field']); ?>

```

statement somewhere. That function is only available if you have the devel module enabled, and it will print out the field array for you to inspect in detail. Here is an example of the dsm output:
* Once you can look into the structure of that array, you can take any pieces of the field you need, if you don't want to render it in the default way.

So, you can do something like getting *only* the uri of your image...

```
<img src="<?php print $content['field_image'][0]['#item']['uri']; ?>" >

```

Anyway, hope this helps!
> 3 votes

---
Tags: theming
---


# Question
Title: how to generate view data from sql query?
i need to create a view that display last post for each user to make them into carousel, i do many search but no pure response. than i will try to generate my view from this sql query:

```
SELECT *
FROM `node`
WHERE `type` = 'post'
AND `nid`
IN (
SELECT MAX( `nid` )
FROM `node`
WHERE `type` = 'post'
GROUP BY `uid`
)
LIMIT 0 , 30

```

Any Idea?

# Answer
It looks like you're selecting 30 nodes of type 'post' and grouping them by user. This view would be pretty easily built using the views UI. Once you've created the view, you should be able to add an author uid as a grouping field. This will group the post fields by author.

Let me know if you have questions.
> 1 votes

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


# Question
Title: Can you change the view item output amount depending on user role?
Is there a way to do this within one view/display or do I have to make two seperate displays, one showing field\_images with unlimited item output and one display showing field\_images but only showing max 2 images - depending on user role?!

# Answer
I'd clone the view, the public one I'll name (temporarily) Public and change the access permission so anonymous users can view it. The original one I'll name (again temporarily) Private and change the access to the authenticated user role.

Now you have two view displays, Public & Private. Public display setting can be 2 and Private can be set to unlimited.
> 0 votes

---
Tags: views, users
---


title: theme_hook_suggestions and tpl.php

text:
# Question
Title: theme_hook_suggestions and tpl.php
```
if ($variables['node']->type == 'netrunner_card' && $variables['view_mode'] == 'full')
{
    $blinksFileName = $variables['node']->field_card_type['und'][0]['taxonomy_term']->name;
    $blinksFileName = str_replace( " ", "_", $blinksFileName);
    $blinksTemplateName = 'node__netrunner_card__' . $blinksFileName . '__full';
    $variables['theme_hook_suggestions'][] = $blinksTemplateName;
}

```

I can't get the tpl to load! Ive got two tpl files currently for two types of cards.

'node--netrunner-card--Runner-Identity-Card--full.php' 'node--netrunner-card--Operation--full.php'

and I even tried: 'node--netrunner-card--Runner\_Identity\_Card--full.php'

Nothing. I'm so confused at this point I don't know where else to go... Any help would be appreciated.

# Answer
The solution was to rename my template files so that the extension was tpl.php instead of just .php. Once I renamed the files to add the tpl the files started working instantly.
> 0 votes

---
Tags: theming
---


# Question
Title: Limit taxonomy terms display on hierarchical select
I need to limit the taxonomy terms visible in a field type 'taxonomy term' using the module 'hierarchical\_select' when creating a post.

There is a way to do this?

1. I have a vocabulary called 'cities' in this format:

* state
    -- City 1
    -- City 2
2. I have a content type called 'condominiums' and this type of content I have a field called 'city' of type 'taxonomy term' (vocabulary cities) using the HS module.
3. I have a user with role 'city' and in this paper there is also a field called 'city' of type 'taxonomy term' (vocabulary cities) using the HS module.
4. I need the user with role 'city' look in the 'city' (when you create a new content) only city that is attributed to him.

Something like:

1. superadmin user (city 1) can see:

* state
    -- City 1
    -- City 2
2. user city (city 2) can see:
state-
-- City 2

Tanks :)

# Answer
Workbench Access module might be a great solution for your issue.

> Workbench Access creates editorial access controls based on hierarchies. It is an extensible system that supports structures created by other Drupal modules.
>
> The module supports Taxonomy and Menu modules for the management of access hierarchies.

Also, take a look at the current issue for Hierarchical Select module integration with Workbench Access module
> 0 votes

---
Tags: rules, taxonomy-terms
---


# Question
Title: Why would a new user role have default permissions that are greyed out and cannot be changed?
I recently installed a new role for the LoginToBoggan module for pre-authentication, aptly named 'pre-authenticated.'

However, this user has has all the default permissions of an authenticated user, and even one that is not (Edit own comments).

If I hit 'edit permissions' to the right of the user role name on the roles page, I get the single column and can set them as desired.

However, when I look at the permissions column when all roles are listed, none of my configuration settings I had saved are honored. Also, they are greyed out and cannot be changed, giving this user permission to add and edit content. Even more of a problem, this role can indeed add and edit at will before being authenticated.

Thoughts on why this is happening and how to fix it?

# Answer
> 2 votes
Under Drupal 7, assigning a permission to the authenticated user defaults that permission to all roles except the anonymous user. If you wish to have a lesser role (non-authenticated) you are going to have to remove the permissions from the authenticated user first. Then set up a post authentication role with the permissions you wish to add on authentication and set up a rule to assign that role when the user authenticates.

(I know! Not straight forward at all!) Remember that the permissions are additive. You do not have to repeat their assignment. Just specify the permissions that each role will add to the default. Then assign the roles to the users as required.

---
Tags: 7, users
---


title: Nodes that point to panel pages

text:
# Question
Title: Nodes that point to panel pages
I'm having an issue with deciding how to display nodes that in turn point to panel pages.

My site currently has a lot of panel pages that have static content. I have a view on my front page that displays nodes which in turn point to these panel pages. However, when a user clicks on a node link, they'll of course see the node in isolation.

In order for me to point users to the correct page, I've been using redirects. So if a user clicks on featured article on the home page, a redirect pushes them to the panel page I've set up instead of just the node view.

Have I made this overly complicated? Is there a way to making this workflow a lot simpler?

# Answer
> 0 votes
@MPD was correct. I had neglected to use the node override panel page correctly. Thank you!

---
Tags: panels
---


# Question
Title: Drupal 6: using template based on browser version
Is it possible to serve up a specific page template based on browser version? If I can satisfy my IE 7 requirements with a special template, I'd prefer that rather than loading a bunch of extra css only used when IE7 is being used.

I have a special drop-down menu and though on its own will work in IE7, once it's a block and assigned to a region, issues start with height. I can put it in another region within a page template but then I'm changing all the css for all other browsers so I'd just as soon as have a template for the specific pages.

thanks

# Answer
> 2 votes
Normally that would be done with conditional css e.g. conditional\_styles and that approach is recommended first.

Mainly because why change the entire template when only the CSS needs changing?

However, if you really need separate tpls ( e.g for new HTML markup ), you could probably use template suggestions in hook\_preprocess\_page after checking the browser user agent.

Something like this in template.php

```
/**
 * Implements hook_preprocess_page
 */
THEMENAME_preprocess_page(&$variables){
  // Requires browscap.ini, check PHP docs for details, else use $_SERVER['HTTP_USER_AGENT']
  $browser = get_browser();
  if($browser->browser == 'IE' && $browser->majorver == 7) {
    $variables['template_files'][] = 'page-ie7';
  }
}

```

After clearing all caches, you could then use page-ie7.tpl.php for IE7.

See the note on http://php.net/manual/en/function.get-browser.php for info else use `$_SERVER['HTTP_USER_AGENT']` to check browser from request. You'll also need to make sure your cache varies on user agent as well.

---
Tags: 6, theming
---


title: Sort view before print

text:
# Question
Title: Sort view before print
I have some node IDs I'm passing to a view; however the sort order is wrong.

Here's my pseudo code:

```
//query to grab the nids

if (!empty($nodeids)) {
  $view = 'taxo_listing';
  foreach ($nodeids as $nid) {
    print views_embed_view($view, block_1, $nid);
  }
}

```

What I need to do is pre-build the view then run implement `hook_views_query_alter` to sort the view before printing out the view.

Been looking at http://views.doc.logrus.com/ for a while now, but it's all a bit confusing, can anyone offer any clues as how to go about this? I know what I want to do but unsure how to go about it, sound familiar guys?

Thanks in advance.

# Answer
I don't know where `$nodeids` comes from, but I expect it's an array of nids from a database query? If so, you're effectively running a view with a view and can probably get away without writing any code for hooks.

Therefore, you can either:

* Sort the `$nodeids` yourself with uasort() which will mean probably returning more fields to sort with and maybe writing your own comparison function.
* Let Views handle all of this, thus gaining access to the UI and all it's powers.

The latter 'view within a view' approach is better for sustainability and sanity because it uses the Views UI and theme layers more consistently. A good approach that's worked for me is:

1. Make a view that can either:
    * return the properly sorted `$nodeids`, or;
    * get it to take an argument of a comma-separated list of nids you can pass `implode(',', $nodeids)` to.
2. use Views PHP to add a field that can contain your `views_embed_view($view, block_1, $nid)`, probably with `$nid` replaced by `$row->nid` but will depend on your setup.
3. Add any sorting or sorting code to the view you want.
> 0 votes

# Answer
You can try hook\_views\_pre\_render as well

> This hook is called right before the render process. The query has been executed, and the pre\_render() phase has already happened for handlers, so all data should be available.

Example

```
function hook_views_pre_render(&$view) {
  // Scramble the order of the rows shown on this result page.
  // Note that this could be done earlier, but not later in the view execution
  // process.
  shuffle($view->result);
}

```

Read Views hooks
> 0 votes

---
Tags: views, entities
---


# Question
Title: Custom module's output is not wrapped in the site theme
I've put together my first Drupal 7 custom module. I've implemented hook\_menu() to get it to path correctly, but I cannot seem to get the output wrapped in the page tpl.

I can visit domain.com/mycustommodule to see the output, but it's just the photos and links that the custom module built, not the site wrapper. How do I get this output into the node area of the page?

Here's my hook\_menu if that helps.

```
function mymodule_menu() {

$items = array();
$items['mymodule/view'] = array(
'title' => 'Mymodule',
'page callback' => 'mymodule_display',
'access callback' => 'user_access',
'access arguments' => array('Access administration menu'),
'weight' => 1,
'type' => MENU_CALLBACK,
);
return $items;
}

```

# Answer
> 3 votes
What would help is the code for the `mymodule_display()` function. However, it sounds like you are printing the output in the function instead of returning it.

Blank page:

```
/**
 * Creates a blank page with only the module output.
 */
function mymodule_display() {
  print 'Module content';
}

```

Themed page:

```
/**
 * Output the content in the main content area of active theme.
 */
function mymodule_display() {
  return 'Module content';
}

```

# Answer
> 0 votes
You should go to domain.com/mymodule/view to see the output of your `mymodule_display` function.

The complete code will be

```
function mymodule_menu() {
 $items = array();
 $items['mymodule/view'] = array(
 'title' => 'Mymodule',
 'page callback' => 'mymodule_display',
 'access callback' => 'user_access',
 'access arguments' => array('access content'),
 'weight' => 1,
 'type' => MENU_CALLBACK,
 );
 return $items;
}

function mymodule_display() {
 return '<h2>Heres is your module's output</h2>';
}

```

Make sure you clear cache after writing this code.

---
Tags: 7, theming
---


# Question
Title: User login through token in URL in drupal 6
I have a drupal 6 website and I would like to implement the functionality to allow user of a particular user role to login into site using the token value in the url.

I have user role "SAP" in the website and will send a link to user in mail "www.example.com/user/token". When user click on this link, I want allow user to login into site automatically.

I have searched through into google and drupal site but I did not find any solution.

Thanks in advance.

# Answer
> 1 votes
urllogin module provides a way to transparently log users into the web site when they follow a link.

Give the “login via URL” permission to users who are allowed to log in with this module.

Alternatively you can try this module also

Easy Login allows the admin to give a permission to users so they are able to log in via an url.

Hope it will match your requirement !!

---
Tags: 6, users
---


# Question
Title: Prevent Drupal from timing out during a large node export?
Is there a setting to prevent drupal from timing out during long operations?

# Answer
> 2 votes
There is (obviously ;)) no setting to make Drupal faster, so you're only chance is to allow it to run longer.

You will only be able to change these settings if you are running your own server. If so, then see http://drupal.org/node/207036 and http://www.php.net/manual/en/info.configuration.php#ini.max-execution-time.

You could also ask your hoster nicely to increase these settings for you, but that might not happen as these settings are usually setfor good reasons (On shared hosting servers are usually tons of users, so hosters want to prevent that one of those users is taking up too many ressources from others..)

# Answer
> 0 votes
Views data export uses batch api to build your export in chunks short enough to be processed properly. And you can safely leave it in cron to generate your data at night, if you need daily updates.

---
Tags: 6
---


title: Drupal Content Types

text:
# Question
Title: Drupal Content Types
Content types that are created recently are not showing up. They are displayed in content type list but not in "Add content" list and navigation menu. I tried few solutions like:

1. I checked in the database node\_type table if the fields type and orig\_type are same; they are same.
2. I configured the navigation block to access all content types, though it is not necessary.
3. I tried to do add the link directly in navigation menu, but the link is not getting added to the menu.
4. I cleared the cache several times and run the cron tasks too.
5. Its is not even permissions, I have given them already. Can anyone help? I am stuck and I cannot start everything from scratch.

# Answer
> 2 votes
When you create a new content type, it should be visible in the "Content Type" page.

If they are not visible, then it could be a permission issue: You have to give permission for creating/modifying nodes using content types you added. The only exceptions are the first user created for a Drupal site (who always has all the permissions) and the users with the "administer content types" permission.

# Answer
> 0 votes
If you are logged in through admin and you are not getting the list of content type in "Add content" list and navigation menu, but displayed in "Content type" list page, then it mean that links are deleted from "Navigation" menu.

I know that this is not best solution for the problem, but you can add menu item in the "Navigation" menus for the content type. You can add link url for menu item as "node/add/\[machine\_name\_of\_content\_type\]" and title same as name of content type.

---
Tags: nodes
---


# Question
Title: Redisplay Captcha on form error in Ajax form submit
I have a Fancybox form and the form is sent via Ajax. I know that there is the error about "reuse attack" for Captcha, but this is not my case.

When I wrong the form (some required fields missing) I see the fieldset of Captcha, but no Captcha inside. It's empty.

How can I fix this ?

# Answer
> 0 votes
If user can submit the form when there is no captcha after errors, it's by design. In captcha settings you checked an option to only verify humanity of an user once. User gets validated as a human on first, failed submit, and is not bothered any more on that form. Go to captcha settings and make him validate each and every time and it will not disappear, but your users will not love you.

---
Tags: 7, ajax, captcha
---


# Question
Title: Can you temporary grant a user permission to avoid captchas in drupal 7?
I have a module which alters a webform's form. Depending on the user agent, I want to grant the ***current*** user the permission to skip captchas, so that the captcha block wont appear at the end of my webform. The problem is, within the init function of my module, if I enable the following line:

```
if (functionWhichChecksStuff()) {
        user_role_grant_permissions(DRUPAL_ANONYMOUS_RID, array('skip CAPTCHA'));
    }

```

the permission is being granted for ALL anons, every time since it actually grants the permission to that user role *permanently*.

Is there a way or function which does that *dynamically and temporary*?

# Answer
> 1 votes
There are basic problems with your approach:

* All anon users are one user for Drupal. They share common UID 0, so they are one user. And HTTP is a stateless protocol, so you can't decide "it's the same user" basing on connection. In Drupal 7 sessions are not guaranteed for anonymous users, so you can't use them reliably for that purpose either.
* If you will try to modify $user-\>roles, it will add a role for current http **call** all right, but it will not regenerate caches, like admin/reports/status/rebuild or views caches based on roles.
* hook\_init docs says: This hook is not run on cached pages.

So, this is no-go by design, and if you need to give some privileges or options by browser session, you need to implement your own solutions, like cookies. There is a list of modules that works that way, you can use their code for reference.

---
Tags: forms, captcha, users
---


# Question
Title: Filter data from two content types with different criteria in view
I've got these two content types, A and B. It's pretty straightforward to set up and display them in the same view. However, I can't get them filtered. I've added two filters rules, one for each content types, a1 and b1 respectively, in the hope that I can extract the right parts of the data from A and B and show them in my view. But that doesn't work out.

// a1=published *and* content type A *and* category=aa b1=published *and* content type B *and* tag=bb //

Here is what I got while trying to do so:

1. no rules at all, view displays all the stuff from A and B
2. rule a1, view displays A only
3. rule b1, view displays B only
4. rule a1 or b1, shows nothing

filter groups i used

Is there anything wrong or filter criteria can only be applied? Any help is appreciated.

--update 1-- I did some more experiments about grouping filter criteria:

```
 - case 1
Content: Published (Yes)  AND
Content: Type (= Portfolio)
OR
Content: Published (Yes)  AND
Content: Type (= Blog entry)  AND
Content: Tags (= frontpage) | Settings
 - case 2
Content: Published (Yes)  AND
Content: Type (= Portfolio)
Content: Tags (= frontpage) | Settings
OR
Content: Published (Yes)  AND
Content: Type (= Blog entry)  AND

```

"Content: Tags" is a unique field which only appears in content type "Blog entry" . To my surprise, case 1 and 2 will yield the same result, blog entries, even though "Content: Tags" has nothing to do with the content type "portfolio".

--update 2-- a bug?
Incorrect filter group OR behavior

# Answer
a1 and b1 will show nothing, because `content type == A AND content type == B` is always false for 'A != B'

On filter block, you have a drop down with options. You need to group them into groups connected with OR, so you will have:

```
published and ( (content type == A and category == aa) or (content type == B and tag == bb ) )

```
> 2 votes

# Answer
If you want to show parts (you must mean fields) of your two content types just do the following:

1. Add a filter of Content type checking the two content types A & B
2. At the Format/Show section click on content and on that window choose fields.
3. Then go the Fields section and start adding fields that belong to those types.
> 0 votes

---
Tags: nodes, views
---


# Question
Title: How do you change the location of `form_set_error` output?
Is there a way in Drupal 7 to change the location of the output of `form_set_error`?

At the moment, it calls `drupal_set_message` which queues all the form's errors to the top of the screen.

What I would like instead is for each message to appear below the appropriate field.

If this is not possible, can I manually flag the form as "invalid" within the `MODULE_form_name_validate()` function **without** using `form_set_error`?

# Answer
> 7 votes
The Inline Form Errors module has that functionality:

> IFE or Inline Form Errors allows you to place form submission error inline with the form elements. Three options are provided for setting your inline error behaviour. You can configure the default behaviour or override the behaviour on a per form basis. You can add as many forms as you like.

The Drupal 7 release is only in alpha but I'd say it's worth a try. Even if there are issues, it should give you a good place to start to implement your own version. This is the module screenshot:

# Answer
> 8 votes
Extending the (correct) answer from Clive, I worked through the IFE code. I didn't really need an entire module dedicated to this, so I adopted a few snippets here and there to get the result I needed. I've marked his answer as correct because it is ultimately the right answer.

The code is below, all credit goes to Clive and the IFE team - I just wanted to present the simplified version for anyone looking for a similar answer.

```
// Standard gear - do some custom validation and set the errors
// as you go..
//
// Once all the validation has been done, call MODULE_errors_reset
// which will return an array of all errors against their ID.
// Expose this array however you like to your template, or loop
// over your form adding a #suffix to each element with an error
//
function MODULE_form_name_validate($form, &$form_state) {
    drupal_set_message("validating...");

    form_set_error("description", "There is an error here!!!!");
    form_set_error("tags", "Yep, and here too!!!");

    $reset_errors = MODULE_errors_reset( $form );

    drupal_set_message( "<pre>" . print_r( $reset_errors, true ) . "</pre>" );
}

// This part is adopted from IFE. It's changed in two ways, it returns
// an array (which also merges with its recursive self).
// And it also skips all the 'display' stuff present in the original
// Essentially it extracts out the error messages from the session and unsets
// them. I am assuming that Drupal 7 marks the success of a validation based not
// whether the SESSION variable contains anything, the SESSION seems to be only
// for the message at the top of the screen.
//
function MODULE_errors_reset( $element ) {
    if( ! isset( $_SESSION[ 'messages' ] ) ) {
        return;
    }

    $reset_errors = array();

    // Recurse through all children.
    foreach( element_children( $element ) as $key ) {
        if( isset( $element[ $key ] ) && $element[ $key ] ) {
            $reset_errors += MODULE_errors_reset( $element[ $key ] );
        }
    }

    // Check for errors and settings
    $errors = form_get_errors();
    $element_id = implode( '][', $element[ '#parents' ] );

    if ( !empty( $errors[ $element_id ] )) {
        $error_message = $errors[ $element_id ];

        // Get error id
        $error_id = array_search( $error_message, $_SESSION[ 'messages' ][ 'error' ] );

        if( $error_id !== FALSE ) {
            unset( $_SESSION[ 'messages' ][ 'error' ][ $error_id ] );
            $_SESSION[ 'messages' ][ 'error' ] = array_values( $_SESSION[ 'messages' ][ 'error' ]  );

            if( count( $_SESSION[ 'messages' ][ 'error' ] ) <= 0 ) {
                unset( $_SESSION[ 'messages' ][ 'error' ] );
            }

            $reset_errors[ $element[ '#id' ] ] = $error_message;
        }
    }

    return $reset_errors;
}

// If there are no form errors, we still hit here, even after the 'reset', this is
// a good thing.
function MODULE_form_name_submit( $form, &$form_submit ) {
    drupal_set_message("submited!");
}

```

---
Tags: 7, forms
---


# Question
Title: How do I delete nodes older than X days?
Does anyone have a snippet for deleting nodes that are older than 1 day? I would like to run this on cron tasks.

# Answer
You could use the Auto Expire module.

> This module allows site administrators to set expiration times for content types.
>
> End users creating content that has auto expiry set cannot control the expiry time. They could be allowed to renew the content for one or more cycles.
>
> Before a node is expired a warning message is sent to the user that created that node. If the user has the proper rights he can then extend the node.
> 2 votes

# Answer
I had problems with D7 using Auto Expire, and ended up using HOOK\_cron() in a custom module:

```
function mymodule_cron() {

// we only want to deal with messages (a content type)
$message_type = "message";

// grab all messages
$message_nodes = node_load_multiple(array(), array('type' => $message_type));
// set up the timestamp for the expiry
$message_search_date = strtotime("- 30 days"); // UNIX timestamp for 30 days ago

// now loop through messages, & if they are old, expire them
  foreach($message_nodes as $m) {

    $obj = entity_metadata_wrapper('node', $m);

    // when was it last updated, & is it still published?
    $last_update = $obj->changed->value();
    $published = $obj->status->value();

    // if it's still published & it's not recent, then unpublish it
    if(($message_search_date > $last_update) && $published<>0) {
        $obj->status = 0;
        $obj->save();
    }
  }
}

```
> 4 votes

---
Tags: 7, nodes
---


# Question
Title: How to make filter that can find users by location of each other in miles or kilometers?
On a lot of dating sites like this one:

http://www.pof.com/basicsearch.aspx

users can search each other by proximity, can this be done with Drupal? Like searching for users within X kilometers of my IP?

# Answer
> 0 votes
IP Geolocation Views and Maps looks like what you are looking for. It can obtain user's location, and it integrates with Views using Views PHP as it's connector.

---
Tags: location
---


# Question
Title: Add counter to view with rendered entity output
On my site I've a search based on Views, with an exposed filter. The style output is "rendered entity", and I've to add the "result counter" beside the title.

Is there a way to do this or I've to use "fields" output?

I should have something like:

> 1. Title1
> 2. Title2

# Answer
Result number is a views field node has no clue about. You need to use "fields" output to add fields that are not in the node itself - that's the very reason of this output's existence.
> 1 votes

---
Tags: 7, views
---


title: custom table view: delete/edit row D7

text:
# Question
Title: custom table view: delete/edit row D7
I've spent hours trying to find good examples or working scripts, but couldn't find anything yet. What I *desire* to achieve: I have a sortable table with database entries in it, each row has a edit and delete link with each its own ID. So far so good. Now I have to add the functionality to actually delete/edit DB rows. Im totally lost..

Its a custom module and don't want to use other modules to achieve this, so these answers are useless : Help needed for adding and edit & delete link in a column in a view table

I also found this website

but the description is way too complicated and I think the whole script is incomplete.

I've also tried the http://drupal.org/project/examples but that didn't get me any further

does anyone have really good examples or a complete working module?

thanks for your input

# Answer
> 2 votes
So first of all you want a page callback to handle the deleting. You either want to use `confirm_form()` or add a token to the link to avoid CSRF. node.module does the former, so I'd go with core. You can also use that as a reference: `node_menu()` (look for `$items['node/%node/delete']`), `node_delete_confirm()`, `node_delete_confirm_submit()`.

Regarding the actual deleting, this page has some instructions. Please update the Q if you have specific issues.

Here's an example, not tested:

```
/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {
  $items['MYMODULE/%/delete'] = array(
    'title' => 'Delete',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('MYMODULE_delete_confirm', 1),
    'access arguments' => array('PERMISSION_TO_CHECK'),
  );

  return $items;
}

/**
 * Form function returning a delete thingy confirmation form.
 */
function MYMODULE_delete_confirm($form, &$form_state, $id) {
  $form['#MYMODULE']['id'] = $id;

  $name = MYMODULE_get_name_from_id($id);

  return confirm_form($form,
    t("Are you sure you want to delete %name?", array('%name' => $name)),
    '<front>',
    t("This action cannot be undone."),
    t("Delete"),
    t("Cancel")
  );
}

/**
 * Submit handler for MYMODULE_delete_confirm.
 */
function MYMODULE_delete_confirm_submit($form, &$form_state) {
  if (isset($form['#MYMODULE']['id'])) {
    $id = $form['#MYMODULE']['id'];
    db_delete('MYMODULE_thingy')
      ->condition('id', $id)
      ->execute();
  }
}

/**
 * Loads the name of the thingy from its id.
 */
function MYMODULE_get_name_from_id($id) {
  return 'thingy ' . $id;
}

```

# Answer
> 0 votes
```
    <?php
// $Id$
/**
* @file
* First menu module file
* Learning Menu
*/
/**
* Implement hook_help().
*/
function learning_help($path, $arg) {
  if ($path == 'admin/help#learning') {
    return t('learning menu.');
  }
}

/**
 * Implementation of hook_menu().
 */
function learning_menu() {
  $menuitems['hello'] = array(
    'title' => 'Hello world',
    'page callback' => 'sam_mymenu',
    'access arguments' => array('administer users'),
    'type' => MENU_CALLBACK,
  );
  $menuitems['survey'] = array(
    'title' => t('Survey form'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('survey_form'),
    'access arguments' => array('administer users'),
    'type' => MENU_CALLBACK,
  );
  $menuitems['admin/people/survey'] = array(
    'title' => t('Survey List'),
    'page callback' => 'survey_list',
    'access arguments' => array('administer users'),
    'type' => MENU_NORMAL_ITEM,
  );
  $menuitems['admin/people/survey/%/delete'] = array(
    'title' => 'Delete Survey item',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('delete_survey_record_comfirm',3),
    'access arguments' => array('administer users'),
    'type' => MENU_LOCAL_TASK,
  );
  $menuitems['admin/people/survey/%/edit'] = array(
    'title' => 'Edit Survey item',
    'page callback' => 'form_values_edit',
    'page arguments' => array(3),
    'access arguments' => array('administer users'),
    'type' => MENU_LOCAL_TASK,
  );
  return $menuitems;
}

/**
 * Display Hello World.
 */
function sam_mymenu() {
  return t('Hello world');
}

/**
 * Implements hook_block_info().
 */
function learning_block_info() {
  $blocks = array();
  $blocks['show_ip'] = array(
    'info' => t('Show IP Address.'),
    'cache' => DRUPAL_NO_CACHE,
    );
  $blocks['recent_survey'] = array(
    'info' => t('Recent Survey'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function learning_block_view($block_name = '') {
  if ($block_name == 'show_ip') {
    $list = ip_address();
    $content = $list;
    $block = array(
      'subject' => t('Current IP Address'),
      'content' => $content,
    );
  }
  if ($block_name == 'recent_survey') {
    $query = db_select('learning', 'n')
      ->fields('n')
      ->orderBy('sid', 'DESC')
      ->range(0,3)
      ->execute();
    $list = array();
    while($data = $query->fetchAssoc()){
      $list[] = $data;
    }
    $count = count($list);
    $content = "<table border='0'>
      <tr>
        <th>" . t('Name') ."</th>
        <th>" . t('Email') ."</th>
      </tr>";
    for($i=0; $i < $count; $i++)
    {
      $content .= "<tr><td>". $list[$i]['name'] . "</td>";
      $content .= "<td>". $list[$i]['email'] . "</td></tr>";
    }

    $content .= "</table>";
    $block = array(
      'subject' => t('Recent Survey'),
      'content' => $content,
    );
  }
    return $block;
}

/**
 * Implements survey_form().
 */
function survey_form($form, &$form_state, $my_object) {

  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#required' => TRUE,
    '#default_value' => isset($my_object['name']) ? $my_object['name'] : '',
  );
  $form['sid'] = array(
    '#type' => 'value',
    '#value' => $my_object['sid'],
  );

  $form['email'] = array(
    '#type' => 'textfield',
    '#title' => t('Email'),
    '#required' => TRUE,
    '#default_value' => isset($my_object['email']) ? $my_object['email'] : '',
  );
  $form['age'] = array(
    '#type' => 'select',
    '#title' => t('Age'),
    '#options' => drupal_map_assoc(range(18, 100)),
    '#default_value' => isset($my_object['age']) ? $my_object['age'] : '',
  );
  $form['gender'] = array(
    '#type' => 'radios',
    '#title' => t('Gender'),
    '#options' => array(
      'male' => t('male'),
      'female' => t('female')
    ),
    '#default_value' => isset($my_object['gender']) ? $my_object['gender'] : '',
  );
  $form['about'] = array(
    '#title' => t('About'),
    '#type' => 'textarea',
    '#cols' => 60,
    '#rows' => 5,
    '#default_value' => isset($my_object['about']) ? $my_object['about'] : '',
  );
  $form['disclaimer'] = array(
    '#type' => 'checkbox',
    '#default_value' => variable_get('disclaimer', FALSE),
    '#title' => t('I agree that the information provided above are true to my knowledge'),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Send Surveys'),
  );
  return $form;
}

/**
 * Implements From Validation.
 */
function survey_form_validate($form, &$form_state) {

  if (!valid_email_address($form_state['values']['email'])) {
    form_set_error('email', t('That e-mail address is not valid.'));
  }
  if (!($form_state['values']['disclaimer'])) {
    form_set_error('disclaimer', t('Please accept our legal to proceed.'));
  }
  $words = explode(' ',$form_state['values']['about']);
  $count_words = count($words);
  if ($count_words < 50) {
    form_set_error('about', t('About should have at least 50 words.'));
  }
}

/**
 * Implements survey_form_submit().
 */
function survey_form_submit($form, &$form_state) {
  if(isset($form_state['values']['sid'])) {
    db_update('learning')
      ->fields(array(
        'name' => $form_state['values']['name'],
        'email' => $form_state['values']['email'],
        'age' => $form_state['values']['age'],
        'gender' => $form_state['values']['gender'],
        'about' => $form_state['values']['about'],
      ))
      ->condition('sid', $form_state['values']['sid'] )
      ->execute();
    drupal_set_message(t('Record has been updated.'));
  }
  else {
  // Here u can insert Your custom form values into your custom table.
    db_insert('learning')
      ->fields(array(
        'name' => $form_state['values']['name'],
        'email' => $form_state['values']['email'],
        'age' => $form_state['values']['age'],
        'gender' => $form_state['values']['gender'],
        'about' => $form_state['values']['about'],
      ))->execute();
    drupal_set_message("successfully saved survey details.");
  }
  $form_state['redirect'] = 'admin/people/survey';
}

/**
 * Display Suryvey form list.
 */
function survey_list(){
  //return t('Survey List');
  $query = db_select('learning', 'n')
    ->fields('n')
    ->execute();
  $rows = array();
  while($data = $query->fetchAssoc()){
      // Fill the table rows
    $data['operation'] = l(t('Delete'), 'admin/people/survey/' . $data['sid'] . '/delete');
    $data['operation'] .= "|";
    $data['operation'] .= l(t('Edit'), 'admin/people/survey/' . $data['sid'] . '/edit');
    $rows[] = array('data' => $data, 'style' => 'word-break:break-all;',);
  }

  // Prepare table header
  $header = array( t('S.No'),t('Name'), t('Email'), t('Age'), t('Gender'), t('About'),t('operation'));
  // Output of table with the paging
  $output = theme_table(
    array(
      "header" => $header,
      "rows" => $rows,
      "attributes" => array(),
      "sticky" => true, // Table header will be sticky
      "caption" => "",
      "colgroups" => array(),
      "empty" => t("Table has no row!") // The message to be displayed if table is empty
    )
  );
  return $output;
}

/**
 * Delete Survey Record Confirmation
 */
function delete_survey_record_comfirm($form, &$form_state, $id){
  //die($id);
  $form['delete'] = array(
    '#type' => 'value',
    '#value' => $id,
  );
  return confirm_form(
    $form,
    t('Are you sure you want to delete this?'),
    'admin/people/survey',
    t('This action cannot be undone.'),
    t('Delete'),
    t('Cancel')
  );
}

/**
 * Delete Survey Record Function
 */
function delete_survey_record_comfirm_submit($form, &$form_state) {
  $record = $form_state['values']['delete'];
  if ($record ) {
    $num_deleted = db_delete('learning')
      ->condition('sid', $record )
      ->execute();
    drupal_set_message('The record has been deleted!');
  }
  $form_state['redirect'] = "admin/people/survey";
}

/**
 * form_values_edit
 */
function form_values_edit($id){
  $id_val = $id;
  $my_object = db_select('learning', 'n')
    ->fields('n')
    ->condition('sid', $id_val )
    ->execute()
    ->fetchAssoc();
  return drupal_get_form('survey_form', $my_object);
}

```

# Answer
> 0 votes
```
    // Create menu for Delete

    $menuitems['admin/people/survey/%/edit'] = array(
        'title' => 'Edit Survey item',
        'page callback' => 'form_values_edit',
        'page arguments' => array(3),
        'access arguments' => array('administer users'),
        'type' => MENU_LOCAL_TASK,
      );

    /**
    * Delete Survey Record Confirmation
    */
    function delete_survey_record_comfirm($form, &$form_state, $id){
      //die($id);
      $form['delete'] = array(
        '#type' => 'value',
        '#value' => $id,
      );
      return confirm_form(
        $form,
        t('Are you sure you want to delete this?'),
        'admin/people/survey',
        t('This action cannot be undone.'),
        t('Delete'),
        t('Cancel')
      );
    }

    /**
    * Delete Survey Record Function
    */
    function delete_survey_record_comfirm_submit($form, &$form_state) {
      $record = $form_state['values']['delete'];
      if ($record ) {
        $num_deleted = db_delete('learning')
          ->condition('sid', $record )
          ->execute();
        drupal_set_message('The record has been deleted!');
      }
      $form_state['redirect'] = "admin/people/survey";
    }

```

---
Tags: 7
---


# Question
Title: Use Context to load JavaScript on certain pages
Is it possible to load a JavaScript file on certain pages with the Context module?

# Answer
> 3 votes
The Context Add Assets module does *exactly* that :)

*Taken from the README*

> Supports adding active theme files to page via context

I've used 7.x-1.0-beta1 with no major problems, so don't be afraid that there's no full release :)

---
Tags: 7
---


# Question
Title: How to apply theme to Drupal view or block
I have created 1 view for displaying Category on home page using Ubercart module.

but i want to apply custom css changes to my Category view fields like image and title

can any knows how to apply css change to DRUPAL views.

Thanks in advance.

# Answer
> 2 votes
Go to your view display and look at the bottom of the "advanced" column. You'll see something like "Theme : Information". Try to locate your template name and click on it to get it's base code.

# Answer
> 0 votes
Block Class module allows you to assign arbitrary classes to your blocks. You can use it in CSS selectors without manually rewriting tpl.php files.

---
Tags: views
---


title: Visit counter for anonymous visits?

text:
# Question
Title: Visit counter for anonymous visits?
I would like to keep track of the number of visits for each anonymous user. I want to be able to show special messages, for example when they visit the site the 10th time.

Incrementing a cookie variable will just be fine in this case. How do I find out when a new session has started?

# Answer
> 1 votes
This would be difficult I believe, because every anonymous visitor is essentially treated as the same, as one account.

# Answer
> 0 votes
You are most likely best to make use of session\_api module and some custom moduling.

# Answer
> 0 votes
Needed functions are readily described in manual: http://api.drupal.org/api/drupal/modules!user!user.module/function/user\_cookie\_save/7

Don't forget to respect Do Not Track or you risk a lawsuit in some jurisdictions.

---
Tags: 7, sessions
---


# Question
Title: Can't choose checkboxes as field widget in d7
I recall in previous versions (Or maybe even this version and mine is just bugging) you could take text or int fields and supply a list of key|values and make checkboxes or a selectbox from it.

The core module "Options" seems to offer this functionality from the module description but whenever I select field type Integer, Decimal, Float, or text the only widget option I have is a standard textbox.

Term and node references do allow checkbox widgets.

Am I seeing a bug? Is there a different way of doing this in D7? I've tried adding these field types to both node types and vocabs but neither acknowledges the existence of the checkboxes widget.

# Answer
Set "Type of data to store" to *List (text)*, *List (integer)* or *List (float)* and Check boxes will be default widget. If you can't see them, make sure List module is enabled.
> 2 votes

# Answer
No this isn't a bug. The options module doesn't itself define any field types for which it can be used. This is left to modules wishing to implement `hook_field_widget_info_alter()` and add to the `field types` property.

For example, the taxonomy module provides that functionality through `taxonomy_field_widget_form_alter()`:

```
function taxonomy_field_widget_info_alter(&$info) {
  $info['options_select']['field types'][] = 'taxonomy_term_reference';
  $info['options_buttons']['field types'][] = 'taxonomy_term_reference';
}

```

The number module doesn't implement that hook, so you can be pretty sure the behaviour you see is by design.

The list types are instead provided by the List module (List(Text), List(integer), etc.)
> 2 votes

---
Tags: 7, entities
---


# Question
Title: Is it a good idea to load the css files from page.tpl file instead of .info file
I am just curious, because i am trying to get my site working for both IE and chrome, and I want it to load only a specific css file. Conditional stylesheets arent working for me, as I cannot see the change in the browser when I check it's html file.

# Answer
It is bad idea, on so many levels I'm sure I can't list all.

* Conditionally included stylesheets will get cached by various proxies and served with no respect for original conditions.
* Modules like CDN will not be able to work on your CSS files to speed things up.
* Aggregation and cache modules will stop working as well.
* Search engine bots will get confused and may think you are trying to trick them by serving different version of a page to bot, and other one to bot disguised for an user - risk of google ban.
* If, in future, someone will redefine page.tpl.php for certain content types, you will have the same file described in many places - easy way for inconsistency and styling bugs.
* CSS provided by modules might end up in other position to your own than they are now, this can cause hard to diagnose display bugs.
> 2 votes

---
Tags: theming, .info
---


# Question
Title: How to include node of a certain content type as links in a menu?
I have create a menu called: **Products**. Then I have a content type called: **Product**. Now when I create a **Product** node I need it automatically include in the **Products** menu.

Then if I have 10 nodes I should have a menu with 10 links.

Should I use a Rule to accomplish this? Thanks.

# Answer
> -1 votes
You can do it with Rules. This module: http://drupal.org/project/menu\_rules adds some actions to rules. One of them is to create a menu item for a node. You select: Event: Create a node | Update a node Condition: Content type is "your content type" Action: Update a menu item for node (there is a checkbox to create the menu item if it doesnt exist)

---
Tags: routes
---


title: Overwrite the default taxonomy view

text:
# Question
Title: Overwrite the default taxonomy view
I want to overwrite the default taxonomy view. I am cloning the original one, but the view I get does not provide any item.

How can I achieve this? Also could I have two views, default and cloned enabled and visible through a panel?

It seems to be \[a critical issue on an upgrade of the Views module.

# Answer
Can't really comment on the no results problem.

However, the Taxonomy View renders as a page, so no you can't have both the original view and the cloned view enabled at the same time and expect them both to override taxonomy pages.

The only way to have both enabled is to set a different path for each view, which means one or both views would not override taxonomy pages at all.

If what you want to achieve is overriding taxonomy pages for terms of specific vocabularies, what I did was use the Disable Taxonomy Term Listing module to completely hide results of the normal taxonomy page, then replaced that content with taxonomy block views. If this isn't what you are looking for then feel free to disregard this all ;-)
> 1 votes

# Answer
Marking the answer here in case it save other people's time :) Upgrade your views version to 3.7 and it should work!
> 0 votes

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


# Question
Title: How to create submenu based on content type and taxonomy?
I would like to create a submenu that lists items based on content type and taxonomy. Here's the setup.

```
Shop for a Car [Basic Page]
    Financing Options for cars [Basic Page]
       loan 1 [Content Type: Loan / Taxonomy: Car, Home]
       loan 2 [Content Type: Loan / Taxonomy: Car]
       loan 3 [Content Type: Loan / Taxonomy: Car, Home]
Shop for a Home [Basic Page]
    Financing Options for homes [Basic Page]
       loan 1 [Content Type: Loan / Taxonomy Car, Home]
       loan 3 [Content Type: Loan / Taxonomy Car, Home]

```

Notice that loan 1 and loan 3 appear under two different parents. I know I can create this menu structure manually using NodeSymlinks. In that case the Taxonomy terms are not needed. However, I would like to generate the menu automatically using the terms for a particular content type. I looked into the taxonomy menu module but it only allows one parent and it lists the taxonomy tag rather than the items tagged. Any suggestions?

Thanks!

# Answer
You could use views to create your links for the content types and then use the views field view module http://drupal.org/project/views\_field\_view as a field on that to show the child taxonomy terms associated to the content type.
> 2 votes

# Answer
You can do it with Rules. This module: http://drupal.org/project/menu\_rules adds some actions to rules. One of them is to create a menu item for a node. You can create two rules:

1.Rule:

Event: Create a node | Update a node

Condition: Content type is "Loan" | Taxonomy term is "Home"

Action: Update a menu item for node (there is a checkbox to create the menu item if it doesnt exist) -\> Select "Financing Options for homes" for parent menu item

2.Rule:

Event: Create a node | Update a node

Condition: Content type is "Loan" | Taxonomy term is "Car"

Action: Update a menu item for node (there is a checkbox to create the menu item if it doesnt exist) -\> Select "Financing Options for cars" for parent menu item
> 1 votes

---
Tags: taxonomy-terms, routes, nodes
---


# Question
Title: Multivalue entity reference synchronization
I have node type A with Entity Reference **multivalue field** that can reference other nodes of type A (existing). Is there a simple way/module/workflow/ruleset/other to do synchronization as follow: after saving new node of typa A (ie. nid=112) referring two nodes (ie. nid 66 and 77) I want node 66 and node 77 automatically have references to 112.

# Answer
Two way references are described in this drupal.org issue

Corresponding Entity References seems to be consensus solution there, but if it's no good for you, read whole thread, it provides interesting ideas and alternative approaches.
> 3 votes

---
Tags: 7, entities
---


# Question
Title: Additional fields for Ubercart uc_order_product
I need to add fields to the Ubercart entity uc\_order\_product. I was looking into the function field\_create\_instance, but don\`t know exactly where to use it. I believe I should attach the field I want to the uc\_order\_product entity using field\_create\_instance.

The 'uc\_order\_product' definition in uc\_order.module doesn't have a fieldable =\> TRUE definition. May I add that definition from my custom module and tell uc\_order\_product is fieldable? This is uc\_order\_product entity definition in the uc\_order.module.

```
'uc_order_product' => array(
  'label' => t('Order product'),
  'base table' => 'uc_order_products',
  'controller class' => 'UcOrderProductController',
  'metadata controller class' => 'UcOrderProductMetadataController',
  'entity keys' => array(
    'id' => 'order_product_id',
    'label' => t('Order product'),
  ),
  'bundles' => array(
    'uc_order_product' => array(
      'label' => t('Order product'),
    ),
  ),
  'view modes' => array(
    'full' => array(
      'label' => t('Normal view'),
    ),
    'cart' => array(
      'label' => t('Cart view'),
    ),
  ),
  // Entity API callbacks.
  'access callback'   => 'uc_order_order_product_access',
  'save callback'     => 'uc_order_product_entity_save',
  'deletion callback' => 'uc_order_product_delete',
)

```

Finally, I am trying to hook to this entity when it gets updated (hook\_entity\_update, hook\_entity\_presave) but they never get called on uc\_order\_product update. How can I hook to this entity when it is being saved, or when it has been saved? Thank you!

# Answer
> 1 votes
First of all, if you want alter the meta information of an entity, the `hook_entity_info_alter` in your custom module is the right way. More information in official page: hook\_entity\_info\_alter

In this particular case, attributte 'fieldable' is not defined, so the function responsable to call the `hook_entity_info` and `hook_entity_info_alter` is the `entity_get_info()` in common.inc file. This function provide default values and the default value to 'fieldable' is `FALSE`. You only need change this value implementing `hook_entity_info_alter`.

```
 function YOUR_MODULE_entity_info_alter(&$entity_info){
   if(isset($entity_info['uc_order_product'])){
     $entity_info['uc_order_product']['fieldable'] = TRUE;
   }
 }

```

Second issue, This is a link to a previous question about how create fields programatically. The best answer suggests `field_create_field`and 'field\_create\_instance', but if you have a defined field (for example, an image type field created through the UI), you could use `field_update_field` and 'field\_update\_instance'. You can find more information about these functions in field.crud.inc in the field module folder.

---
Tags: entities, hooks, ubercart
---


# Question
Title: How should I implement an alternative file upload?
I want to write a module for Drupal 7 to integrate http://filepicker.io's awesome functionality. It's a simple JS widget that returns a URL of where the file is hosted.

I've never written a D7 module before, though I've written several for D6.

Should I create this as a fields widget (and if so, for which fields- file/image/link?), or should I create a whole new field type for this?

In production, my intent is to mix up the types a bit with this; that is, we have lots of images uploaded already, I'd just like to upgrade the 'upload' button (in lay terms) without breaking everything.

# Answer
If you want it to use http://filepicker.io's storage, it will definitely be link field. It's your own design decision if you will just add a widget (that's what I would do) or clone it and add that widget to a clone. However, don't expect seamless work from images on your own domain and images stored away of it - you can't really resize, rotate, crop, generate thumbnails, and service may become paid one with only short notice (and unavailable without any notice at all).
> 0 votes

---
Tags: entities
---


# Question
Title: Cron is 403: forbidden with cron_key and through 'run cron' link
I'm getting a `403: You don't have permission to access /cron.php on this server.`

This is whether or not I am logged in. Stranger thing is that it is happening on our development server, but not the live server (drupal 7)

# Answer
If token is valid (and it should be when you use Drupal-generated link), there is one other mechanism that can generate 403: `.htaccess` \- check it for rewrites that might block it. If this will not help, try running cron from Drush. Drush bypasses Apache altogether, so you can know if the problem was Apache related (conf files, .htaccess), or purely Drupal related.
> 1 votes

---
Tags: cron
---


# Question
Title: Commerce Customizable product (Example: add/remove topics for pizza)
I'm trying to find a way to give the chance to the customers to "customize " their products.

Straight example: Luigi has got a Pizzeria and he would like to sell his pizze online where customers can add or remove topics.

Is there a way to get this option with the basic function of Drupal commerce? Maybe playing around with products and rules?

This could be very useful for a lot of website type.

I found this module Commerce Customizable Products , it seems to do half of the job. I can add my topics and then with rules I can update the price. It looks like i cannot show the basic topics. Every pizza has to start empty.

Is there anyone who was had experience with it? Any suggestion?

If someone wanted to build a module, I would like to help with it.

Thanks in advance.

12/09/2012 UPGRADE ---------------------

Using Customizable Products I've created a new line item with a term reference field. It will be visible in the product page and will show all the term from that taxonomy. In the product I've got the term field(manage display: hidden) where the editor can select the pizza toppings.

Now, because the line item will print all the terms I would like to create a function that checks the term in the product and puts a flag on the right line item term.

Then, because customers can add and remove toppings from the pizza, in the view I would like to create another function that check if the user has unflagged the basic toppings and print the sign " - " before the toppings.

So the pizzeria will receive: Pizza:

-ham

+salami

Ham was in the basic toppings.

What API can I use to get this work?

# Answer
> 0 votes
I think this Josh Millar video will help.

Customizable Product with Drupal Commerce: Pizza Store

---
Tags: commerce
---


# Question
Title: Warning: explode() expects parameter 2 to be string, array given in menu_node_submit()
I get the above error after a creating a new content type.

> Warning: explode() expects parameter 2 to be string, array given in menu\_node\_submit()

The function which gives error is shown below :

```
function menu_node_submit($node, $form, $form_state) {
  // Decompose the selected menu parent option into 'menu_name' and 'plid', if
  // the form used the default parent selection widget.
  if (!empty($form_state['values']['menu']['parent'])) {
    list($node->menu['menu_name'], $node->menu['plid']) = explode(':', $form_state['values']['menu']['parent']);
  }
}

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Adds menu options to the node type form.
 */

```

# Answer
The line that is throwing the error is in the core `menu.module`. The arguments that are getting passed to it are not valid. To troubleshoot it you would have to backtrace what is getting passed to it to see what is malforming the data or not creating proper data in the first place. If you use `debug_backtrace` you should be able to find where the bad data is originating from.

Specifically `$form_state['values']['menu']['parent']` should be a string (to have explode work on it) but at that time, it is an array.
> 1 votes

# Answer
This is because you tired to explode array. See `explode()`.

```
 $arrayString =   explode(",",$string);

```

You can't explode array. It is already a collection of elements.
> 0 votes

---
Tags: 7
---


# Question
Title: How to display both the taxonomy parent and child in a node?
I have a simple two-level taxonomy in my site: parent level is responsible for the "kind of place" (wine bar, restaurant...), and the children terms make more precise disintctions (french, italian etc. for restaurants).

Now, if i display a taxononomy term, only the child appears (only "french", not "Restaurant French").

Is there any way to display both of them? I've found this http://drupal.org/node/1532198 but I am not sure how to use it.

Maybe there's a module that is more universal way, or a module that manages the display of the terms?

# Answer
> 2 votes
The answer you linked is correct. You need to write .tpl.php file and use provided code in place of default taxonomy renderer. In Drupal nodes belongs only to explicitly selected taxonomy element, not to it's parents. It was the design decision.

---
Tags: taxonomy-terms
---


title: layout content in columns

text:
# Question
Title: layout content in columns
I'm trying to figure out someway to allow end-users to format page content into columns. Right now if they edit a page they get a title field and a body field which is fine a lot of the time but what if they want to do something like this...

```
-------------------------------------------------------------------------
| TITLE                                                                 |
|                                                                       |
| Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam      |
| pharetra lorem mollis dui egestas convallis. Nam vitae sapien urna.   |
| Nam quis tellus ligula, non gravida metus.                            |
|                                                                       |
|              HEADER                             HEADER                |
|                                                                       |
|      ----------------------             ----------------------        |
|      |                    |             |                    |        |
|      |                    |             |                    |        |
|      |       image        |             |       image        |        |
|      |                    |             |                    |        |
|      |                    |             |                    |        |
|      ----------------------             ----------------------        |
|                                                                       |
|    Lorem ipsum dolor sit amet,       Aliquam pharetra lorem mollis    |
|    consectetur adipiscing elit.      dui egestas convallis.           |
|                                                                       |
|                                                                       |
| Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam      |
| pharetra lorem mollis dui egestas convallis. Nam vitae sapien urna.   |
| Nam quis tellus ligula, non gravida metus.                            |
|                                                                       |
-------------------------------------------------------------------------

A title followed by a full width paragraph
then two 50% width columns with headers, images, and text
and a full width footer paragraph

```

This is just an example of what they might want to do. I'm using the WYSIWYG module's ckeditor to edit the page contents. The only way I can think of doing this is either allowing them to inline css in style attributes or using something like panels.

using inline styles and predefined classes might work but it would require the end user to know css. Panels looked good as I could create the layout the way I liked and add custom content (or otherwise customize the page) but I couldn't figure out how to translate the panels page into another language like I can with nodes.

This must be a common situation but I haven't found the solution yet. Anyone have any suggestions?

# Answer
In a recent project I needed content editors to insert a special div wherever they needed that would float right and have custom styling.

The best solution I came up with was a custom ckeditor plugin. Basically editors just click on the appropriate icon and the necessary html is inserted into the editor. All they have to do is add the content.

Example:

* Create a folder inside ckeditors plugin dir and name it "doublecolumn".
* Create a plugin.js file inside that dir.
* Add an icon to use for the button inside that dir i.e. "myimage.png.

Then, add the following code in plugin.js:

```
(function ($) {
CKEDITOR.plugins.add( 'doublecolumn',
{
    init: function( editor )
    {
        editor.addCommand( 'insertDoubleColumn',
            {
                exec : function( editor )
                {
                    editor.insertHtml('<div style="half-width"></div><div style="half-width"></div><div class="clearfix"></div>');
                }
            });
        editor.ui.addButton( 'doublecolumn',
        {
            label: 'Double Columns',
            command: 'insertDoubleColumn',
            icon: this.path + 'myimage.png'
        } );
    }
} );
})(jQuery);

```

I haven't actually tested this but it's similar to what I had used and it should work.

You could also expand the html for each column to something like:

```
<div class="half-width">
  <h3>Add Title</h3>
  <p class="image">add image</p>
  <p class="text">add text</p>
</div>

```

In your case it might be better to put the two columns inside a wrapper div - just to be safe.

Don't forget to enable the plugin and add it to your toolbar from `admin/config/content/ckeditor`.

Hope this helps.
> 5 votes

---
Tags: panels, nodes, theming
---


# Question
Title: How do I remove taxonomy links from nodes?
Lately, I've noticed an interesting situation related to my Drupal site. When I enter the name of my site in Google's search engine, a list is retrieved with my site maintaining the first position in search results. When I click the link that says "See more results from .com," it lists my Home page first followed by links to three Taxonomy pages.

```
/taxonomy/term/1
/taxonomy/term/2
/taxonomy/term/3

```

When I click the pagination links at the bottom of those taxonomy pages, I am taken to the following link locations :

```
/category/categories/<category_name>?page=<page_num>

```

I have nodewords installed to control metatags. I have set the NOINDEX and NOFOLLOW metatags for all taxonomy terms (and for taxonomy itself).

I don't mind using CSS to hide taxonomy terms. I use the taxonomy terms to determine which category to highlight via CSS by using jQuery's addClass/removeClass functions. I need to remove the link surrounding the taxonomy term so that it's not indexed in search engine results. Using jQuery to remove this link is ineffective and the results remain in search engine results. It's my understanding that there is a way to remove the link using the **template.php** file and the **template\_preprocess\_node(&$vars, $hook)** function.

I don't know how to go about doing this. All help is very much appreciated.

# Answer
> 1 votes
In the Manage Display page of your content-type i.e.: `admin/structure/types/manage/product/display` you should be able to set the output format for your terms to 'plain text'.

# Answer
> 0 votes
You can wild-card the taxonomy pages in robots.txt to prevent google from crawling those pages.

More info

# Answer
> 0 votes
I would suggest Display Suite module or some jQuery

```
jQuery(".taxonomy-term h2 a").each(function(){
var $t = jQuery(this);
$t.after($t.text());
$t.remove();

```

Thanks @Will and @Matt for this elegant solution.

# Answer
> 0 votes
In your template.php file try to do a print\_r($vars). It is an array containing all the theme variables. The terms could be in $vars\['terms'\]. Simple set $vars\['terms'\] = NULL or unset that array element. You could remove the variable in the page template files too.

---
Tags: 6, theming, taxonomy-terms
---


# Question
Title: Sorting Content easily - wish to avoid a "weight" integer
As the title describes, I want to create a mechanism with which a bunch of Content Types can be sorted 'easily' so they can be presented with a View according to that sorting.

Adding an Integer that would act as 'weight' should work but can end up being confusing if the number of nodes get's too high.

Ideally some sort of 'tablesorting' would be sweet.

Is there a way to accomplish such a thing?

Thanks in advance.

# Answer
Here is a "Comparison of Node Ordering Modules".

I have tested most of these modules and decided to go with the Weight module because it was easier to implement and slightly faster then all the other module because it does not add any table joins to your queries since it is re-using the node's sticky field. It includes a very easy to setup Views plugin for drag-n-drop sorting. The Weight module is designed to 'sort nodes', while DraggableViews is designed to 'sort anything'.
> 3 votes

# Answer
DraggableViews allows you to create any list based on a View, and then renders Drupals regular drag-handles system over that. My experience with D6 is good, when I last tried it in D7 it was a bit buggy, though that should work out soon enough if not already.
> 1 votes

# Answer
My old-web-style solution is to add the weight handly by editing the machine name of the content type (1\_nodetypetosortfirst, 2\_nodetypetosortsecond, etc.) and then sorting by content types (asc).

That's the easiest solution I found.

But better think twice the order (and validate it) because if you need to change later the machine name, it might be painful.

Oh yep, and I forget : group the result by the field content type if you want to have something like : content type 1 \- result \- result \- result / content type 2 \- result \- result ...
> 0 votes

---
Tags: views, nodes
---


# Question
Title: How to implement apple-touch-icon to a site
I'm trying to place an apple-touch-icon on a site. I have attempted to implement this via the following code block placed in `example_preprocess_node()`..

```
function example_preprocess_node(&$variables) {

  ...

  $apple_touch = array(
    'rel' => 'apple-touch-icon',
    'href' => path_to_theme() . '/apple-touch-icon.png',
    'sizes' => '114x114'
  );

  drupal_add_html_head_link($apple_touch);

  ...

}

```

I cleared the caches and reloaded the page, but I'm not seeing the `<link.../>` line in my header at all.

Is this this right place to implement the apple-touch-icon?

# Answer
I enhanced @willtate code a little. **Note**: If you need to create the icons quickly use this online generator: http://iconifier.net/

## Add the default icon

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

drupal_add_html_head($apple_icon, 'apple-touch-icon');

```

## Loop through to add various sizes

```
$apple_icon_sizes = array(57,72,114,144);

foreach($apple_icon_sizes as $size){
  $apple = array(
    '#tag' => 'link',
    '#attributes' => array(
      'href' => path_to_theme().'/apple-touch-icon-'.$size.'x'.$size.'.png',
      'rel' => 'apple-touch-icon-precomposed',
      'sizes' => $size . 'x' . $size,
    ),
  );
  drupal_add_html_head($apple, 'apple-touch-icon-'.$size);
}

```

## HTML Output

```
<link sizes="57x57" rel="apple-touch-icon-precomposed" href="sites/all/themes/yourtheme/apple-touch-icon-57x57.png"></link>
<link sizes="72x72" rel="apple-touch-icon-precomposed" href="sites/all/themes/yourtheme/apple-touch-icon-72x72.png"></link>
<link sizes="114x114" rel="apple-touch-icon-precomposed" href="sites/all/themes/yourtheme/apple-touch-icon-114x114.png"></link>
<link sizes="144x144" rel="apple-touch-icon-precomposed" href="sites/all/themes/yourtheme/apple-touch-icon-144x144.png"></link>
<link rel="apple-touch-icon-precomposed" href="sites/all/themes/yourtheme/apple-touch-icon.png"></link>

```
> 8 votes

# Answer
After some tinkering I've finally got it working:

```
function example_preprocess_html(&$variables) {

  ...

  //regular apple-touch-icon
  $apple = array(
    '#tag' => 'link', // The #tag is the html tag - <link />
    '#attributes' => array( // Set up an array of attributes inside the tag
      'rel' => 'apple-touch-icon',
      'href' => path_to_theme() .'/apple-touch-icon.png',
    ),
  );
  drupal_add_html_head($apple, 'apple-touch');

  // 72x72 apple-touch-icon
  $apple = array(
    '#tag' => 'link',
    '#attributes' => array(
      'rel' => 'apple-touch-icon',
      'href' => path_to_theme() . '/apple-touch-icon-72x72.png',
      'sizes' => '72x72',
    ),
  );
  drupal_add_html_head($apple, 'apple-touch-72');

  // 114x114 apple-touch-icon
  $apple = array(
    '#tag' => 'link',
    '#attributes' => array(
      'rel' => 'apple-touch-icon',
      'href' => path_to_theme() . '/apple-touch-icon-114x114.png',
      'sizes' => '114x114',
    ),
  );
  drupal_add_html_head($apple, 'apple-touch-114');

  ...

}

```

Note: I was forced to use `drupal_add_html_head()` here as `drupal_add_html_head_link()` only allows for distinct `rel` values.
> 4 votes

---
Tags: theming
---


# Question
Title: Taxonomy Terms based on already created content
Ok I have a client that builds homes in subdivision. I have created a subdivision and homes content type. What I want to be able to do is attach homes to subdivisions.

What i want to be able to do is when a subdivision is created, it will automatically be available as either a taxonomy term, or as part of a drop down available when the client is creating a new home.

Is there a way that I can achieve this using the taxonomy module?

Thanks in advanced.

# Answer
> 0 votes
Instead of using taxonomy term use the following options:

**Option 1:** References module

> This project provides D7 versions of the **'node\_reference'** and **'user\_reference'** field types.

**Option 2:** Entity reference module

> Provides a field type that can reference arbitrary entities.

---
Tags: taxonomy-terms, nodes, navigation
---


# Question
Title: Show taxonomy term's image field on node page
Ive added an image field to my taxonomy terms. On a node I need to display the image of the terms it tagged with.

Ive created a view with the NID as an argument and attached it to the node content type with the EVA module.

Ive added a relationship of 'Taxonomy terms on node'. This allows me to add 'Content: All taxonomy terms' as a field which shows the term name, but I cant figure out how to load the term's image instead.

# Answer
You can achieve this in a different way, using Display Suite module you can simply render taxonomy terms in a desired view mode.
> 0 votes

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


# Question
Title: show results for a view with certain node reference
I have created two content types a home and a subdivision. I have added a subdivision reference field in the home content type.

What i want to have is in each subdivision page, show a teaser of the homes that reference that particular subdivision. I imagine that would be done using views, but I am not sure.

Any help on how to create this view block on the subdivision node would be appreciated.

# Answer
This is what views is particularly good at, in my opinion. You should be able to get started by creating a subdivision page view. Then you should be able to create a relationship based on the reference field. This would give you access to sort based upon whether the home appeared in that subdivision.
> 1 votes

---
Tags: views, nodes
---


# Question
Title: Why are comments enabled on my content types in Simpletests?
When I run Simpletest, it's showing comment forms at the bottom of all the nodes, even though I don't even have the comment module enabled, nor permissions assigned for it. These comment forms showing up in tests is interfering with my tests and I need to disable them, but I don't know how since I never enabled them in the first place.

# Answer
> 1 votes
`module_disable(array('comment'));` inside `setup()` does the trick.

---
Tags: comments, testing
---


# Question
Title: How can I replace the "Add to cart" button with an "Ask about product" button, based on product property?
Let's say client wants button "Ask about" for chosen product instead of "Add to cart" (he requires personal contact for some products). It should be based on data from a specific product field, so he could choose for what products he requires personal contact. It would be also nice if that optional button would redirect user to webform, that would automatically contain name and attributes of chosen product. How can I approach this?

**Added:** I can disable "add to cart" form, from hook\_preprocess\_node, or hook\_node\_view\_alter, but I wonder if it can be ajaxified, so only if user will choose specific product, from configuration of attributes, the "add to cart" button, would disappear and "Ask about product" would appear. I also need to turn off possibility of adding that product to cart by forged POST requests. Anyone know how to do it?

# Answer
I figured out answer, and it's not that bad as I though. I decided to write a tutorial for it as it looks like very useful feature. So here it is:

**Tutorial**

1. Install everything, I mean, Commerce and Webforms,
2. Create example webform - let's name it "Contact",
3. Create Product Display, create some product with few attributes, and one boolean field (not attribute) "Contact required",
4. Configure webform, specifically, create there a field that will have default value, fetched from GET query string (how to do this: http://drupal.org/node/296453#webform-url-default ), we will pass to our Contact form a SKU of our product by using GET method.

Now create your own module, I will not elaborate on that, as there is a lot of info out there. The hooks that we will need are:

> HOOK\_form\_commerce\_cart\_add\_to\_cart\_form\_alter(&$form, &$form\_state)
>
> HOOK\_commerce\_cart\_attributes\_refresh\_alter(&$commands, $form, $form\_state)

The first one will allow us to manipulate our form initially (if default product will have "Contact required = true"), the latter will allow us to adjust our form to AJAX calls.

Yes, that means that, our "Add to cart" button will be dynamically changing based on current product "Contact required" field. Looks promising doesn't it? :)

We will also use two helper functions that are not hooks:

> MODULE\_ask\_for\_product($product)
>
> MODULE\_contact\_required\_validate($form, &$form\_state)

The first one will return HTML of our new button "Ask for product" (I encapsulated it in function, because we will need that data in both above hooks), and the second one will validate our form, so if "Contact require" field on product, will be set to 1, the form will not validate, and product will not be added to cart. The submit button for regular user will be removed, but this is only against smart guys that would like to annoy you by sending this form even if you hide submit button.

Those are the functions:

```
    function HOOK_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {
    // Adding new class to our button, that will allow us, to target it by jQuery
    $form['submit']['#attributes']['class'][] = 'add-to-cart-button';
    // Adding new validator, that will make sure that our products with required contact, will not be added to cart
    $form['#validate'][] = 'MODULE_is_contact_required_validate';

    // Getting value of field_is_contact_required of default product
    $product = $form_state['default_product'];
    $field = field_get_items('commerce_product', $product, 'field_is_contact_required');

    // If value is 1, then replace our button with markup.
    if($field[0]['value'] == 1) {
        unset($form['submit']);
        $form['ask_for_product'] = array(
            '#markup' => MODULE_ask_for_product($product),
            '#weight' => 50,
        );
    }
    }

```

Now we need to do something with AJAX:

```
    function HOOK_commerce_cart_attributes_refresh_alter(&$commands, $form, $form_state) {

    if (!empty($form_state['context'])) {
        // Getting value of field_is_contact_required of new chosen product
        $product = $form_state['default_product'];
        $field = field_get_items('commerce_product', $product, 'field_is_contact_required');

        // If field_is_contact_required is set to 1, then replace a container that have class ".add-to-cart-button" (we just added that class), with our markup
        if($field[0]['value'] == 1) {
            $replacement = '.add-to-cart-button';
            $commands[] = ajax_command_replace($replacement, MODULE_ask_for_product($product));
        }

    }

    }

```

And our helpers:

```
// Return markup of our new button. 'node/7' is node of our contact form, 'subject' is a key of our query string
function MODULE_ask_for_product($product) {
    return '<div class="ask-for-product">' . l(t('Ask about product.'), drupal_get_path_alias('node/7'), array('query' => array('subject' => 'Ask about product with SKU: ' . $product->sku))) . '</div>';
}

// Prevent some products from be added to cart.
function MODULE_contact_required_validate($form, &$form_state) {

    $product = $form_state['default_product'];
    $field = field_get_items('commerce_product', $product, 'field_is_contact_required');

    if($field[0]['value'] == 1) {
        form_set_error('', t('Don\'t try to be annoying! :P'));
    }

}

```

That's all, you can customize it, or by extending the idea, do much more with it (maybe by using webform api).
> 10 votes

# Answer
One approach would be to add a payment plugin that would check for product property and then disallow payment until client asks for contact, and site operator marks all products as "contacted". That would allow client to keep products in a shopping cart and only ask when he feels pretty much decided. It would also allow to ask about all products that are supposed to go in one shipment, and that seems to be a good thing. Maybe there is an option to write commerce plugin that works at cart level, too, but I never tried it. Way faster, Q'n'D approach would be to test for a given property at tpl.php level and substitute buttons. Of course it has some drawbacks, smart people still could get around it and try to force-feed their choice to basket and checkout.
> 1 votes

---
Tags: 7, commerce, webforms
---


title: Upgrading from Pressflow

text:
# Question
Title: Upgrading from Pressflow
The ultimate goal here is to take a somewhat large (about 15,000 nodes) and complex (many contrib and custom modules) site from Pressflow 6 to Drupal 7, so I am assuming I should make the shift to Drupal 6, then upgrade to Drupal 7. Is that the safest path? Is there a better way? And if this is the best way, I was curious about the strategy or things to think about when making the move from Pressflow 6 to Drupal 6.

I have seen a lot of things about going from Drupal to Pressflow but not so many going in the opposite direction. I did find this question: is there a safe way to convert a pressflow website to drupal 6?

But like everything I found about moving from Drupal to Pressflow, people just say it is a drop-in solution, but what does that actually mean? I have done a diff between base Drupal 6 and Pressflow 6 and I can see the differences. But if I do a diff on base Drupal 6 and our Pressflow 6 site there are a lot more differences and it doesn't appear that just dropping in the Drupal 6 core and overwriting what is there will turn out well (though I will have to try this as an experiment to confirm).

In short, I am looking for a more in-depth answer to how to migrate from Pressflow 6 to Drupal 6, other than just saying it is a drop-in replacement. For example, what files/dirs definitely have to be replaced, which files/dirs should you definitely not replace, what if any changes are required to the DB (my impression is that there are none), etc?

Thanks!

# Answer
The only point is that you should disable and un-install the Pressflow modules, the rest is the same that drupal 6.

The big problem will be with the custom modules. The best always is try to make the migration.

If you don't want to migrate you can use feeds to move from drupal 6 to drupal 7. But in this way you must build the site in drupal 7.

Oskar
> 1 votes

# Answer
I'm the primary author of Pressflow 6. I can't think of any issues you'll experience moving to Drupal 7, even directly from Pressflow 6. Pressflow doesn't make any schema or SQL data changes.

Now, post-upgrade you may still want to consider Pressflow 7. Its changes are nowhere near the scope of Drupal 6, but it does include important optimizations for running sites on networked or distributed file systems, which are necessary for multi-server deployments.
> 0 votes

---
Tags: 7
---


# Question
Title: Relationship to content in term view causes duplicate and missing results
I have these terms, nodes and comments. So 'NodeA' and 'NodeB' are tagged with 'Term1'. Both 'NodeA' and 'NodeB' have new comments.

```
Term1
-NodeA (has new comments)
-NodeB (has new comments)
Term2
-NodeC (no new comments)
-NodeD (no new comments)
Term3
-NodeE (no new comments)
-NodeF (has new comments)
Term4

```

I need to make a view that looks like this:

```
Term1 – new comments!

Term2

Term3 – new comments!

Term4

```

If I make a term view is stars out ok:

```
Term1

Term2

Term3

Term4

```

However when I add a relationship 'Taxonomy term: Content with term' then add the field 'Content: New comments' using this relationship, then I get this:

```
Term1
New comments: 1

Term1
New comments: 1

Term2
New comments:

Term2
New comments:

Term3
New comments:

Term3
New comments: 1

```

I get a result for each node, not 1 result for each term. I also get no result at all for the term with no nodes. Is there a solution within views for this?

# Answer
> 1 votes
You can use aggregation ("Advanced" menu, "Other" section, "Aggregation" feature) to sum your results and have something like: Term 1 (5) - New comments Term 2 (3)

Or you can try having distinct enabled ("Advanced" menu, "Other" section, "Query settings" feature) to show just the distinct results.

Hope it helps

---
Tags: 7, views
---


# Question
Title: Views relationship outputting duplicate nodes?
I have a view of Planet content types. These Planets have a node reference field for Trade Routes to reference other Planets. I'm attempting to output both the current Planet's x/y coordinates, as well as the x/y coordinates of the Planets it references in it's Trade Routes field.

Setting up the fields with each Planet outputting its own x/y and the x/y fields again but using the Trade Route relationship this time results in each Planet being returned as a row once per Trade Route it is storing, instead of returning an array of x/y like I would expect.

What am I doing wrong here?

# Answer
> 3 votes
Maybe You can try to use the Query Parameter and check the "Distinct" option to have distinct result :

# Answer
> 3 votes
I've tried every recomendation I've found and nothing seems to do the trick perfecly. The most precise result I can get is filtering the views results before rendering the view, like this:

```
function YOURTHEMENAME_views_pre_render(&$view) {
  $used_nids = array();
  $new_view_result = array();

  if ($view->name == 'YOURVIEWNAME') {
    foreach ($view->result as $row) {
        if (!in_array($row->nid, $used_nids)) {
          $new_view_result[] = $row;
          $used_nids[] = $row->nid;
        }
    }

    $view->result = $new_view_result;
  }
}

```

Put that snippet in your template.php and replace YOURTHEMENAME and YOURVIEWNAME with your values, you should have no duplicates. **HOWEVER**, I'm finding that this creates pages with less rows than expected, for example, if you want 10 results per page and your view has 8 duplicates in the first page, the first page would have just 2 rows. So, take my code as a partial result and only if you don't care having less results per page or if you are displaying all results at once.

# Answer
> 2 votes
you can use an "attachment" to show the related content. This article describes it well.

Or you could use the table format and group by the first field. That will put the first field above the table and just show the values of the 2nd field in the table.

---
Tags: 7, views
---


# Question
Title: How to access $user_profile in page.tpl.php or $page in user-profile.tpl.php in Drupal 7?
I need to change layout of a profile depending on user's field. So, I need to either include regions in `user-profile.tpl.php` or access `$user_profile` to test that field in `page.tpl.php`.

I've seen this done, but can't find it now.

# Answer
> 1 votes
As for including regions in `user-profile.tpl.php` here how you do it.

In your custom theme add the following code to template.php file

```
function mytheme_preprocess_user_profile(&$variables) {
  // List of all regions for the current theme
  foreach (system_region_list($GLOBALS['theme']) as $region_key => $region_name) {
    // Add content to $region variable
    if ($blocks = block_get_blocks_by_region($region_key)) {
      $variables['region'][$region_key] = $blocks;
    }
    else {
      $variables['region'][$region_key] = array();
    }
  }
}

```

Then copy `user-profile.tpl.php` to your custom theme and then place the following code between any HTML tag.

```
print render($region['region_name']);

```

---
Tags: 7, theming, users
---


title: Aggregation in Drupal 7,many errors

text:
# Question
Title: Aggregation in Drupal 7,many errors
its always a problems with drupal aggregation,once scripts don't work, now i get this error

```
Warning: file_get_contents(/sites/all/themes/subtheme/js/script.js): failed to open stream: No such file or directory in drupal_build_js_cache() (line 4942 of /home/ideald2/domains/idealdesigns.tk/public_html/includes/common.inc).

```

i checked the path but its right,why it says no such file or directory,am tryin to get my portfolio online but been failing since a week, how to make aggragation without errors

# Answer
> -1 votes
Are you using drupal\_add\_js()? Make sure you use:

drupal\_add\_js(path\_to\_theme().'/js/script.js');

aggregation seems to fail otherwise

---
Tags: css-js-aggregation
---


title: Views & Filter criteria

text:
# Question
Title: Views & Filter criteria
I've got a filter criteria saying field xyz = NO. Old nodes meeting the criteria above do not get picked up by the filter. When I edit the node, and resave it, only then they appear in the view. Is there a reason for this?

# Answer
> 1 votes
Yes this is possible. You will have to create two or more filter groups which will be separated with an OR condition.

Click "And/Or, Rearrange Filter Criteria" from the drop down menu of the Filters section and then click "Create New Filter Group". After that drag the filters you want in the new filter group and change the condition separating the groups to OR from AND. I would do it as follows:

**1st group**

Content: Published Yes And

Content: Type = News And

Content: Xyz (xyz) = Yes

**OR**

**2nd Group**

Content: Published Yes And

Content: Type = News And

Content: abc (abc) = Yes

---
Tags: views
---


# Question
Title: Drupal 7 Form AJAX button to return javascript script
I am trying to create a form that allows a user to type in an address and click submit. In return the button makes an AJAX callback that builds the javascript link for a user to copy and paste into their site. Once a user inserts the javascript into their site it will display a map from my site. The problem I am having is when the user creates their custom map using my form I want to return a sample map of what it should look like. I need this javascript to be printed to the browser.

```
<script type="text/javascript" src="http://widget.pickerspal.com/search/get?lat=41.6005448&lng=-93.6091064&height=500"></script>

```

But when it is returned nothing is displayed. Here is my form & callback function.

```
function d3vo_widget_builder_form($form, &$form_state) {
    $form['city'] = array(
      '#title' =>   t('City'),
      '#type' =>    'textfield',
      '#required' => TRUE,
      '#description' => t('Find your city'),
    );

    $form['height'] = array(
      '#title' =>   t('Widget Height'),
      '#type' =>    'textfield',
      '#size' => 5,
      '#description' => t('Set the widget height'),
      '#element_validate' => array('_validate_field_is_numeric'),
    );

    $form['map-area'] = array(
      '#type' => 'markup',
      '#prefix' => '<div id="mapsample-div">',
      '#suffix' => '</div>',
      );

    $form['submit'] = array(
      '#type' =>    'button',
      '#value' =>   'Get Widget',
      '#ajax' => array(
        'callback' => 'd3vo_widget_map_ajax_callback',
        'wrapper' => 'mapsample-div',
        'method' => 'html',
        'effect' => 'fade',
        //'progress' => array('type' => 'none'),
    ),
    );

    return $form;

function d3vo_widget_map_ajax_callback($form, $form_state){
       $point = geocoder('google',$form_state['values']['city']);
       $lng = $point->coords[0];
       $lat = $point->coords[1];
       if($form_state['values']['height'] == NULL){
           $height = 500;
       } else {
       $height = $form_state['values']['height'];
       }
       $widgetScript = '<script type="text/javascript" src="http://widget.pickerspal.com/search/get?lat='. $lat .'&lng='. $lng . '&height='.$height.'"></script>';

        $form['script'] = array(
         '#value' => $widgetScript,
         '#type' => 'textfield',
         '#attributes' => array('readonly' => 'readonly'),
         );

        $form['map'] = array(
          '#type' => 'markup',
          '#markup' => $widgetScript,
        );

        return array($form['script'], $form['map']);
    }

```

Im not very familiar with using Javascript in Drupal. I have searched and tried many different ways but I can not get the map area to show. Any help would be greatly appreciated.

# Answer
> 1 votes
The AJAX callback is only used to tell Drupal's AJAX engine what part of form to update. All actual work of building the form elements is supposed to happen in form's hook, in code wrapped in a control statement like the following.

```
if (!empty($form_state['values'])) {
  // ...
}

```

---
Tags: javascript
---