title: Accessing content type data using mysql

text:
# Question
Title: Accessing content type data using mysql
I'm trying to use data captured within my drupal database to drive some analytics in another tool. I am trying to develop a view which gets the field data for a content type i've created. The db model seems rather complicated, can anyone give me any tips on how to join the tables together to find fields for a given content type.

Cheers A

# Answer
> 0 votes
I'd definitely recommend using Views and one of the Views Data Export modules (I've used Views JSON with good results to get location data into an app powered by the google maps API)

EntityFieldQuery is THE way to query for Entity data in Drupal, however 1) in most cases, you'll be able to get the same data exported in a View much faster 2) once you have the data from an EntityFieldQuery, you still need to loop through the results and load the nodes, then format the data from the nodes into your output. Unless your output or your data needs are highly specialised this will deifnitely be more time and hassle than simply running it through Views

# Answer
> 2 votes
I would advise you to learn how to use the views module.

In order to achieve what you want. Make sure to install the views module first. To add a new view go to **admin/structure/views/add** and you should see the page below. Select the content type you want

On the same page change teasers to fields. And then click continue and edit. It should take you to a new page. To add more fields from the content type you want, click on the Add link under the fields category. To make it better formatted, you can change the format type under the format category. Once you have added all your fields, click on the save button at the top.

# Answer
> 2 votes
There's a an API specifically for avoiding the need to manually join the tables together.

Check out How to use EntityFieldQuery, which

> allows retrieval of a set of entities based on specified conditions.

A large advantage of using an EFQ instead of manually joining the tables is that it will keep working even if table structures change, such as for a D7 to D8 upgrade.

On a slightly related note, you may want to install the zero-conf Entity cache module, to improve the performance of the entity loading.

# Answer
> 1 votes
For the case of exporting data for use by a statistical package for analysis, I would recommend using the Views module in conjunction with Views Data Export.

Views will allow you to to create custom queries over your database, configured fully through the UI. Views Data Export can take a View, and present it as CSV, XLS, or XML for consumption by another tool.

Directly querying a Drupal database from the outside is not an easy task, and is not recommended; the schema can vary as configuration changes. In some cases, it is possible to get the raw SQL that a View is using, and copy that to another tool. However, certain types of Views will not get all of the data as a single query.

---
Tags: entities, nodes, database
---


# Question
Title: Drupal 7 use custom layouts created by Panels module
I have recently installed the Panels module. It allows me to create custom layouts for my contents. I now want to choose these template layouts while creating/editing a certain type of component so that when viewed that content appears in the selected layout.

I am a newbie in Drupal and more so in the Panels module. So not really sure if my requirement is feasible in the first place.

# Answer
> 0 votes
You are probably looking for Panelizer; use it along with the panels in-place editing tool

From the module's project page:

> The panelizer module allows you to attach panels to any node in the system. It is similar to the panels\_node module that ships with Panels, which provides a single node type that is a panel. Panelizer, however, allows this to work for many entity types. It works by using the Page Manager template to take over the page rendering of the node. In Panelizer 7.x-3.0, you can also panelize view modes. The old-style "Page Manager" implementation is treated as a specialized view mode.

---
Tags: panels, theming
---


# Question
Title: what is the use of form[#special] in a drupal form?
Now i'm working with forms and trying to add template in to it, I have form\['#special'\], but i don't know how to set it and what's the use of that and its usage.

# Answer
You can embed anything in your form. Just add `#` at the beginning of the array index to indicate it's not a child element, and Form API will accept that even if it does not define or use it. Form API reference does not mention `#special`, so it is not an standard parameter. Instead, it's a parameter created by module's author for his own need.

For example, I usually add `#machine_name` to anything that can trigger AJAX, for easier handling of `$form_state['triggering_element']`. There are many uses.
> 9 votes

---
Tags: forms
---


# Question
Title: How to display physical dimension fields on node--product.tpl.php?
I am using the Drupal Commerce module and I want to print the physical dimension fields(machine name: field\_width) value on product detail page.

How can I print physical dimension fields value in `node--product.tpl.php` file?

My file code is like so:

```
<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?>"
<?php print $attributes; ?> >

<?php print $user_picture; ?>

<?php print render($title_prefix); ?>
<?php if (!$page): ?>
<h2<?php print $title_attributes; ?>><a href="<?php print $node_url; ?>"><?php print $title; ?></a></h2>
<?php endif; ?>
<?php print render($title_suffix); ?>

<?php if ($display_submitted): ?>
<span class="submitted"><?php print $submitted ?></span>
<?php endif; ?>

<div class="content clearfix"<?php print $content_attributes; ?>>

<div class="c-i-rgt">

<div class="zomer_img">
<?php
if ($view_mode == 'teaser')
else
print render($content['field_image1']);
print render($content['field_width']);
print render($content['product:commerce_price']);
?>
</div><div class="clear"></div></div></div>

```

# Answer
Have you set the field to be displayed under display settings for the content type?

Above is how the Field UI looks, maybe your product dimension field is hidden?

There is a guide here, on how to customize the Drupal commerce product display.

If you want to print the field in node--product.tpl.php you should first drag it so it is visible in the field UI.

Then you need to add `render($content['product:field_width']);`
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: Drupal Ajax Form Add More error - Buttons duplicate and outside of fieldset
I have added an add field button to a module form. The fieldset displays properly and the callback works one time - I click the add more button, and my fields add properly.

The issue is when I click it a second time...the fields add to the form, but outside of the fieldset, and the add/remove buttons start to duplicate.

Here is my form and callback functions...basically copied directly from the example module. I'm leaving the entire form...the top part is a bunch of other fields, the AJAX fields and function are at the bottom. I've spent 2 days fiddling...so I'd very much appreciate some direction!

```
    function _nnreport_shipping_new($form, &$form_state) {
    $jobId = $_GET['id'];
    $job = new stdClass();
    $job = _nnjob_retrieve_jobid($jobId);

    $form['jobId'] = array(
           '#type'=>'hidden',
           '#value'=>$jobId, );
    $form['rigId'] = array(
        '#type'=>'hidden',
        '#value'=>$job->rigId,);
    $form['clientId'] = array(
        '#type'=>'hidden',
        '#value'=>$job->clientId, );
    $form['clientsName'] = array(
            '#type'=>'hidden',
            '#value'=>$job->clientName, );
    $form['wellsName'] = array(
            '#type'=>'hidden',
            '#value'=>$job->wellName, );
    $form['rigCo'] = array(
            '#type'=>'hidden',
            '#value'=>$job->rigCoId, );
    $form['fullRig'] = array(
            '#type'=>'hidden',
        '#value'=>$job->rigCompanyName.' '.$job->rigName, );
    $form['jobIdTitle'] = array(
            '#markup' => '<h2>For:  ' .$job->clientName. ' | '.$job->rigCompanyName.' '.$job->rigName. ' | '.$job->wellName. ' | ' ._nnjob_format_job_id($jobId).'</h2>', );
    $form['date'] = array(
            '#markup' => '<div style="float:right; padding-right: 350px;"><label for="date" class="ui-input-text">Date</label><input type="date" data-clear-btn="true" name="date" id="date" value=""></div>',

        );

     $form['carrier'] = array(
        '#type' => 'textfield',
        '#size' => 30,
        '#title' => t('Carrier:'),
        '#required' => FALSE,);
    $form['carrierPhone'] = array(
        '#type' => 'textfield',
        '#size' => 30,
        '#title' => t('Carrier Phone:'),
        '#required' => FALSE,
        //'#suffix' => '</div><div style="float:left; padding-right: 50px;">',
        );

    $form['origin'] = array(
        '#type' => 'textarea',
        '#cols' => 30,
        '#rows' => 5,
        '#title' => t('Origination:'),
        '#prefix' => '</div><div style="float:left; padding-right: 50px;">',
        );

    $form['fromContact'] = array(
        '#type' => 'textfield',
        '#size' => 30,
        '#title' => t('Contact:'),
        '#required' => FALSE,);

    $form['destination'] = array(
        '#type' => 'textarea',
        '#cols' => 30,
        '#rows' => 5,
        '#title' => t('Destination:'),
        '#required' => FALSE,
        '#prefix' => '</div><div style="float:right; padding-right: 350px;">',

        );

    $form['destContact'] = array(
        '#type' => 'textfield',
        '#size' => 30,
        '#title' => t('Contact:'),
        '#required' => TRUE,
        '#suffix' => '</div><div style="clear:both;"></div>',
        );

    $form['#tree'] = TRUE;

    $form['items_fieldset'] = array(
    '#type' => 'fieldset',
    '#title' => t('Shippment Inventory Items:'),
    '#prefix' => '<div id="items-fieldset-wrapper">',
    '#suffix' => '</div>',
    );

     if (empty($form_state['num_items'])) {
    $form_state['num_items'] = 1;
    }

     for ($i = 0; $i < $form_state['num_items']; $i++) {

    $form['items_fieldset'][$i] = array(
    '#prefix' => '<div class="two-col">',
    '#suffix' => '</div>'
    );

    $form['items_fieldset'][$i]['amount'] = array(
        '#type' => 'textfield',
        '#size' => 30,
        '#title' => t('Amount:'),
        '#required' => TRUE,
        '#prefix' => '</div><div style="float:left; padding-right: 50px;">',

    );

    $form['items_fieldset'][$i]['description'] = array(
        '#type' => 'textfield',
        '#size' => 50,
        '#title' => t('Description:'),
        '#required' => TRUE,
        '#prefix' => '</div><div style="float:left; padding-right: 50px;">',
        );

    $form['items_fieldset'][$i]['serial'] = array(
        '#type' => 'textfield',
        '#size' => 30,
        '#title' => t('Serial Number:'),
        '#required' => TRUE,
        '#prefix' => '</div><div style="float:left;">',
        '#suffix' => '</div><div style="clear:both;"></div>',

            );
    }

    $form['items_fieldset']['add_items'] = array(
    '#type' => 'submit',
    '#value' => t('Add more'),
    '#submit' => array('_nnreport_shipping_new_add_one'),
    '#ajax' => array(
        'callback' => '_nnreport_shipping_new_callback',
        'wrapper' => 'items-fieldset-wrapper',
        //'method' => 'after',
    ),
    );

    if ($form_state['num_items'] > 1) {
    $form['items_fieldset']['remove_items'] = array(
    '#type' => 'submit',
    '#value' => t('Remove one'),
    '#ajax' => array(
        'callback' => '_nnreport_shipping_new_callback',
        'wrapper' => 'items-fieldset-wrapper',

//added this prevent  and limit validation error as another attempt...didn't change anything

'prevent' => 'submit click mousedown',
        ),
    '#limit_validation_errors' => array(),
    '#submit' => array('_nnreport_shipping_new_remove_one'),
    );
    }

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

    return $form;

    }

    function _nnreport_shipping_new_add_one($form, &$form_state) {
      $form_state['num_items']++;
      $form_state['rebuild'] = TRUE;
    }

    function _nnreport_shipping_new_callback($form, $form_state) {
    return $form['items_fieldset'];
    }

    function _nnreport_shipping_new_remove_one($form, &$form_state) {
      if ($form_state['num_items'] > 1) {
        $form_state['num_items']--;
      }
      $form_state['rebuild'] = TRUE;
    }

```

# Answer
There are some errors with opening and closing divs that you declare in the `#prefix`.

See the code below where I simply removed your `#prefix` and `#suffix` definitions. If there are unclosed divs in the markup it will create problems such as the one you mention with the new markup ending up outside the fieldset.

So simply replace the definition of `$form['items_fieldset'][$i]`, `$form['items_fieldset'][$i]['amount']`, `$form['items_fieldset'][$i]['description']` and `$form['items_fieldset'][$i]['serial']` with the code below.

```
$form['items_fieldset'][$i] = array(
  '#prefix' => '<div class="two-col">',
  '#suffix' => '</div>'
);

$form['items_fieldset'][$i]['amount'] = array(
  '#type' => 'textfield',
  '#size' => 30,
  '#title' => t('Amount:'),
  '#required' => TRUE,
);

$form['items_fieldset'][$i]['description'] = array(
  '#type' => 'textfield',
  '#size' => 50,
  '#title' => t('Description:'),
  '#required' => TRUE,
);

$form['items_fieldset'][$i]['serial'] = array(
  '#type' => 'textfield',
  '#size' => 30,
  '#title' => t('Serial Number:'),
  '#required' => TRUE,
);

```
> 2 votes

---
Tags: 7, forms, ajax
---


# Question
Title: How to get the URL for an image thumbnail
I'm using a view template to override how a field is displayed.

The field happens to be an attached image to the node.

I notice in the view it's configured to display the thumbnail - when overriding, how do I get the thumbnail?

(I'm using entity\_metadata\_wrapper )

**EDIT**

So based on the suggetions below I need to use image\_style\_url - how do I get the path to pass to it?

ie, how do I complete this code

```
$node = node_load($row->{$field->field_alias});
$wrapper = entity_metadata_wrapper('node', $survey_node);

// Field is called field_image

$path = ???

$thumbnail_url = image_style_url('thumbnail', $path)

print "<img src='" & $thumbnail_url & "'>"

```

# Answer
You need to use function `image_style_url($style_name, $path)` to obtain proper path in Drupal 7.20 and later. `$path` is a path to an original file. Preferably output normal path, and make it a thumbnail in proper `.tpl.php` file.

If you need to do it in place that does not accept php functions and cannot alter it in template, you can consider disabling `itok` token. To do so, add following line to your settings.php

```
$conf['image_allow_insecure_derivatives'] = TRUE;

```

Then you can simply add `styles/thumbnail/public/` like Kevin says, and use path like `example.com/sites/default/files/styles/thumbnail/public/myimage.jpg` to get thumbnail of `example.com/sites/default/files/myimage.jpg`.
> 2 votes

# Answer
In your default/files you will see a styles folder containing the same structure and same name for the files. Those are all your image styles inclusive thumbs.

so *default/files/myimage.jpg* has thumbnail *default/files/styles/thumbnail/public/myimage.jpg*
> 0 votes

---
Tags: views, theming
---


# Question
Title: Inheritance value from the exposed filter
I've got content-type with two double-valued fields field\_price1 and field\_price2. There are interior names. I've also got page view (its machine name is search) displaying contents. I've got search with some filters. I decided to create one exposed filter connected with field\_price1 field with between operator. Second filter isn't exposed and it is connected with field\_price2 field.

I want to display content in the view only if its field\_price1 or field\_price2 is between values given by user in the search. So that, filter for field\_price2 field has to inherit the value from the first exposed filter. I created custom module named customSearch with code posted below in customSearch.module file.

```
function customSearch_views_pre_view(&$view) {
  if ($view->name == 'search') {
    $filters = $view->display_handler->get_option('filters');
    $filters['field_price2_value']['value']['min'] = $view->exposed_input['field_price1_value']['min'];
    $filters['field_price2_value']['value']['max'] = $view->exposed_input['field_price1_value']['max'];
    $view->display_handler->override_option('filters', $filters);
  }
}

```

Unforntunately, I've got errors.

> Notice: Undefined property: view::$exposed\_input in customSearch\_views\_pre\_view() in line `$filters['field_price2_value']['value']['min'] =
>  $view->exposed_input['field_price1_value']['min'];`
>
> Notice: Undefined property: view::$exposed\_input in customSearch\_views\_pre\_view() in line \`$filters\['field\_price2\_value'\]\['value'\]\['max'\] = $view-\>exposed\_input\['field\_price1\_value'\]\['max'\];

Could someone help me, please?

# Answer
Try replacing

```
function customSearch_views_pre_view(&$view) {
  if ($view->name == 'search') {
    $filters = $view->display_handler->get_option('filters');
    $filters['field_price2_value']['value']['min'] = $view->exposed_input['field_price1_value']['min'];
    $filters['field_price2_value']['value']['max'] = $view->exposed_input['field_price1_value']['max'];
    $view->display_handler->override_option('filters', $filters);
  }
}

```

with

```
function customSearch_views_pre_execute(&$view) {
  if ($view->name == 'search') {
    $filters = $view->display_handler->get_option('filters');
    $filters['field_price2_value']['value']['min'] = $view->exposed_input['field_price1_value']['min'];
    $filters['field_price2_value']['value']['max'] = $view->exposed_input['field_price1_value']['max'];
    $view->display_handler->override_option('filters', $filters);
  }
}

```

And then clear your cache.
> 0 votes

---
Tags: views, 7
---


title: Create a repeatable Drupal install?

text:
# Question
Title: Create a repeatable Drupal install?
When installing Drupal for different sites I find myself frequently installing the same modules over and over again. In the interest of DRY, how can I create a kind of custom site "template" which would allow me to install drupal and have the basic modules I install already installed, basic theme set, and possibly some other common configuration options set?

I've read a little about Drupal profiles and I've seen the Drush tool and perhaps there are other tools besides these. I'm wondering what's the best way to do this?

**UPDATE**

Ok so it seems Drush make and Drupal installation profiles are the correct tools for the job. I found these blog posts which talk about them:

Overview

Drush make

Installation profiles

I feel like I've got almost all the puzzle pieces. What I'm still not clear on is how to combine the drush make process with the profiles? How do you get your profile files into the profiles directory of the drupal install that drush make creates? Or should I just do this via a shell script?

**UPDATE 2**

I found this video:

http://chicago2011.drupal.org/sessions/zero-distribution-using-features-profiler-and-drush-make

which explains using drush make with profiler. Seems like the connection between drush make and profiles is you have one drush make file which downloads only drupal and your profile. Then inside your profile "module" you have another drush make file which will download all your module components.

The video also talks about features which is another level of drupal setup automation.

I'm not sold on this work flow. It all seems a little convoluted. However this was my first exposure so maybe I will appreciate it more later. I like drush make but I'm thinking I can use drush to enable modules instead of messing with profiles. I think I will make a bash shell script that runs drush make and then uses plain drush to enable modules.

Next step would be how to do some configuration of the modules in a repeatable way. I guess this might be features? Or maybe I should look further into profiles.

# Answer
> 13 votes
Have a look at the Drush make project:

http://drupal.org/project/drush\_make

There is also a companion website at:

http://drushmake.me/

This website allows you to select the modules you want to package with Drupal, and produces a Drush-ready makefile.

There are other varieties of this functionality out there, so I advise experimenting and testing with your specific configuration.

# Answer
> 5 votes
We have solved this problem with the use of:

* drupal 7
* custom installation profile (these are much better and easier to make in drupal 7 compared to 6)
* custom features
* aegir to manage the sites, and handle backups and code migrations

The end result is that aegir can provision a new site, with all modules/features installed, and also with a base IA with dummy content in around 6 minutes on our production servers.

# Answer
> 3 votes
**The easiest solution is to** : install this module Profiler Builder

> Profiler Builder is a module for automating the creation of installation profiles and distributions. It has support for the Profiler installation profile simplifier library but is able to run independent of it (1.0-RC4+). This module creates a downloadable tar package that gives you a well made installation profile and associated drush make file based on the site its installed on.
>
> This is a fast, simple way of creating a distributions from any produced drupal site and is an excellent form of documentation via blue-print creation.

Its so easy,

together with Bryan Ollendyke how to video, you can do this in under 15 minutes.

How to create a profile with Profiler Builder

# Answer
> 1 votes
You should make the module you need as a profile put all modules in the profiles folder before installation and choose your profile in installation

---
Tags: 7, installation, distributions, drush
---


# Question
Title: How can I display content of the same type in different ways
I have some content of the same type already on the site, but there are distinctions within the content, maybe categorized with taxonomy, that sub-type the items. What is a good approach to displaying these sub-types in different ways?

# Answer
> 1 votes
One approach would be to generate your theme's template recommendations based on the URL alias of the page you're viewing. For example consider the following example paths:

**car/ferrari/red**

**car/ferrari/black**

**car/bmw/blue**

**car/bmw/red**

The paths above are generated using the following URL path pattern:

**\[node:content-type\]/\[node:field-car-brand-category\]/\[node:field-car-color-category\]**

Now that you've defined the URL paths, you can add this PHP snippet to your template.php either in hook\_preprocess\_page or hook\_preprocess\_node, depending on the template type you'd like to add to the suggestions:

```
function mytheme_preprocess_page(&$variables, $hook) {

    //get path alias without querying DB manually
    $alias = explode('/',drupal_get_path_alias(request_uri()));

    //add template suggestions based on path
    $path = drupal_get_path_alias($_GET['q']);

    if ($path != $_GET['q']) {
      $template_filename = 'page';

      //Break it down for each piece of the alias path
      foreach (explode('/', $path) as $path_part) {
        $template_filename = $template_filename . '__' . str_replace('-', '_', $path_part);
        $variables['theme_hook_suggestions'][] = $template_filename;
      }
    }
}

```

Now if you examine the var dump for **$variables\['theme\_hook\_suggestions'\]**, you'll notice a template hierachy based on the current URL path tokens.

This might not be a fool proof way to achieve what you're after, but it is certainly works and is quick and easy.

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


# Question
Title: How do I put the user registration form on my front page?
I'm using Panels and have a panel page for my front page. I found a discussion for Drupal 6 but the code doesn't work for Drupal 7: http://drupal.org/node/257721

I would like to show the user registration form on the front page to make it extremely easy for new users to sign up.

# Answer
> 7 votes
You just need to add a "New custom content" to a panel pane and add the following code to the body (you need to have PHP format selected):

```
<?php

if(user_is_anonymous()) {
  $form = drupal_get_form('user_register_form');
  print drupal_render($form);
}

?>

```

It works :)

# Answer
> 2 votes
You may try Form Block module which will convert user registration form into block.

---
Tags: 7, panels, users
---


title: Drupal and Hiphop php VM

text:
# Question
Title: Drupal and Hiphop php VM
Faceboock has just released on GitHub their new Hiphop PHP VM, please follow this link:

Do you know if it is possible to enhance Drupal performance with HipHop PHP VM?

If yes, do you have a good howto, or the different steps to make it work, with a CDN?

# Answer
> 9 votes
At the time of writing Drupal does not work out-of-the-box with HipHop VM (1). Some people have managed to make it work with previous versions, but there isn't a simple easy option.

On php.webtutor.pl you can find a number of useful resources:

These are for an older version of Drupal 7 (7.2) and an older version of Hiphop. However the patches are still useful as a place to start. Some of the issues addressed in the patches (eg. the infinite loop caused by drupal autoload) are still current - others may or may not be, I have not investigated further myself though the article by @tvlooy suggests the PDO issues have been fixed.

The article at http://nickveenhof.be/blog/getting-drupal-7-almost-running-hhvm (on which the tests by @tvlooy was based) provides an example configuration - even though the author failed to get Drupal to run under HHVM, it gives a helpful starting point in addition to the webtutor patches.

(1) As tested with Drupal 7.22 and the latest development version of HipHop (HEAD on the master branch) as of 01/08/2013

**Edit:** A post made on the 12/09/13 (after this answer was written) on the HHVM blog suggests that HHVM now passes 98% of Drupal core unit tests. There has been more HHVM releases since then - a comment on the 2.2.0 release that came out a month later suggests that Drupal 7 can be installed using HHVM, though file uploading, clean URLs and php-gd do not work. I do not want to change my original answer as I have not tested this myself, however the comment (together with the 2.2.0 changelog) suggests that some of the issues, such as the autoload loop, have been fixed.

---
Tags: 7
---


# Question
Title: Slight design problem with Roles, Rules and Profile2 on my site
I'm a little stuck with the registration flow on my site. What I have is a multi-user environment, where each user can, but does not have to, create a secondary/Profile2 "shop" profile.

Now I don't want to just expose the Profile2 shop type to everyone. So I've set up a shopkeeper role, and would like to somehow allow users to request or opt into the role. This isn't for security or anything. It just doesn't look professional having the menu link available to users who don't want or need the profile. Also, some newbie is bound to get curious and enter random crap, which will later mess with the display of their content.

My solution was to use a flag on the user page, which triggers a rule to promote the user, but the problem is; there's no Flag option to prevent users from being able to flag other user's accounts. Unless I use a page template to hide the flag link, but that's a perhaps a little too hacky, and as far as I understand, doesn't actually disable the link.

All I really want is some sort of link or checkbox somewhere(preferably on the user-page) saying, "I have a shop, lemme create a profile". So if anyone has a suggestion for my issue, it would be greatly appreciated!

Cheers,

Matt

# Answer
> 0 votes
Here's a fairly straightforward way to do it.

1. Create a field (boolean) on the user account manage fields page. Assign it useful label such as "I want to run a store" etc.
2. Create a rule to add the role as follows:

**Event** After saving user account **AND** After updating an existing user account

**Conditions** Data comparison (user account field value) == yes **AND** User has role (*store*) NOT

**Actions** Add user role (*store*)

And create another rule to remove the role:

**Event** After updating an existing user account

**Conditions** Data comparison (user account field value) account-unchanged == yes **AND** data comparison (user account field value) account == yes

**Actions** Remove user role (*store*)

This should let the users check the box and then the role will automatically be toggled on or off.

---
Tags: rules, users, flags
---


# Question
Title: Panel content page not displaying correctly after restoring backup on different server
I recently had to restore a backup to a new server, and many things seem to be working fine, but others are not. For example The panes page which is suppose to show links neatly on the page in a dropdown menu is displaying them messily around the page. My pixture reloaded theme is also not working correctly.It doesn't seem to have the css styling.

Here is a picture of what it looks like:

# Answer
> 0 votes
First, before doing anything else, try clearing all the Drupal caches.

Then, if that doesn't do the trick, you need to make sure that you restore your files as well as your database. Adaptivetheme and Panels both save some of their settings in files (for example, Adaptivetheme saves the color information of the theme); if you restore the database without the files, your site will behave strangely until you restore the files as well.

Alternately, if for some reason you do not have a copy of the files, you can re-save the theme settings by going to Appearance -\> Theme name -\> and then scrolling down to the bottom of the page and clicking "Save," which will cause Drupal to regenerate the theme files.

---
Tags: theming, backups
---


# Question
Title: form textfield name -value changed and does not validate any more
i have a checkout-page (drupal commerce) form with an address section generated by the module addressfield. currently all text-inputfields have this markup-structure:

`<input class="last-name" id="edit-last-name" name="customer_profile_billing[commerce_customer_address][und][0][last_name]">`

class + id + name

in this config they validate.

if i change the value of the name attribute the form doesnt validate anymore, the form says:

> field XY is required

the form-validator obviously doesnt recognise my inputs.

question: how can i get the validation process to work with a modified `name` attribute?

# Answer
> 1 votes
It all happens in `drupal_validate_form()`.

> Validates user-submitted form data in the $form\_state array.

If I could offer some advice - have a re-think. Changing the name attribute of form elements, especially on those that are part of field widget forms, is a good way to get unexpected results. The `name` on an input is completely irrelevant to the page, so changing it doesn't actually get you anything. If you're trying to change it so you can target the elements using JS, for example, I'd advise changing your JS code rather than the form markup. Trust me when I say it will be easier.

The only valid situation I know of to override the name of an element is when you need to provide multiple submit buttons on a single form that carry out the same action, but in a different context.

---
Tags: forms
---


# Question
Title: How can we insert multiple values in field values?
```
$values = $form_state['values'];
    $images = array();
    foreach ($values as $k => $val)
    if (strpos($k, 'images') !== false && $val !== 0) {
        $images[$k] = $val;
        unset($values[$k]);
    } elseif (strpos($k, 'images') !== false)
        unset($values[$k]);
    $node = new stdClass();
$node->language = LANGUAGE_NONE;
$node->promote = 0;
$node->uid = 1;
$node->type = 'beaches';
    $node->title = $values['location_name'];
    $node->field_location[$node->language][0]['value']=$values['location'];
    $node->field_location_name[$node->language][0]['value']=$values['location_name'];
    $node->field_beaches_continent[$node->language][0]['value']=$values['continent'];
    $node->field_country[$node->language][0]['value']=$values['country'];
    $node->field_about_location[$node->language][0]['value']=$values['description_location'];
    $node->field_travelling_location[$node->language][0]['value']=$values['travelling_details'];
    $node->field_location_facilities[$node->language][0]['value']=$values['location_facilities'];
    $node->field_beach_tag[$node->language][0]['value']=$values['tags'];
    $node->field_longtitude[$node->language][0]['value']=$values['longtitude'];
    $node->field_latitude[$node->language][0]['value']=$values['latitude'];
    foreach ($images as $image) {
    $file = file_load($image);
    $file->status = FILE_STATUS_PERMANENT;
    $node->field_beaches_images[$node->language][0]['value']=$file->fid;
    file_save($file);
    }
    node_object_prepare($node);
node_save($node);
return $node;

```

edit submit action:-

```
global $user;
$values = $form_state['values'];
$updatenode=node_load($values['beach_id']);

unset($values['submit']);
unset($values['form_build_id']);
unset($values['form_token']);
unset($values['form_id']);
unset($values['op']);

$clid = $values['beach_id'];
unset($values['beach_id']);;
$images = array();
foreach ($values as $k => $val){
    if (strpos($k, 'images') !== false && $val !== 0) {
        $images[$k] = $val;
        unset($values[$k]);
    } elseif (strpos($k, 'images') !== false)
        unset($values[$k]);
}
   if($updatenode->nid==$clid  ){
    $updatenode->title = $values['location_name'];
    $updatenode->field_location[$updatenode->language][0]['value']=$values['location'];
    $updatenode->field_location_name[$updatenode->language][0]['value']=$values['location_name'];
    $updatenode->field_beaches_continent[$updatenode->language][0]['value']=$values['continent'];
    $updatenode->field_country[$updatenode->language][0]['value']=$values['country'];
    $updatenode->field_about_location[$updatenode->language][0]['value']=$values['description_location'];
    $updatenode->field_travelling_location[$updatenode->language][0]['value']=$values['travelling_details'];
    $updatenode->field_location_facilities[$updatenode->language][0]['value']=$values['location_facilities'];
    $updatenode->field_beach_tag[$updatenode->language][0]['value']=$values['tags'];
    $updatenode->field_longtitude[$updatenode->language][0]['value']=$values['longtitude'];
    $updatenode->field_latitude[$updatenode->language][0]['value']=$values['latitude'];
    foreach ($images as $image) {
    $file = file_load($image);
    $file->status = FILE_STATUS_PERMANENT;
    $updatenode->field_beaches_images[$updatenode->language][]['value'] = $file->fid;
    file_save($file);
    }
    node_object_prepare($updatenode);
node_save($updatenode);
   }
$form_state['redirect'] = 'beaches/' . $clid;

```

I want to store multiple images fid in the field "field\_beaches\_images\[$node-\>language\]\[0\]\['value'\]" I have ten images, one image is mandatory user can upload up to 9 images. The problem is if any of the image field is empty, it does not store the other values,the node itself not creating. How can we achieve this (ie) the user can insert 1,2,...9 images. Assume if the user enters only 4 images, then the node itself is not created and generating error.

I'm facing a issue on this. I can able to add the images, but it does not supports updation. I have added the code used for editing the form.

# Answer
For background read Why is hook\_form\_alter() so messy?, but essentially you want something like

```
foreach ($images as $image) {
  $file = file_load($image);
  $file->status = FILE_STATUS_PERMANENT;
  $node->field_beaches_images[$node->language][]['value'] = $file->fid;
  file_save($file);
}

```
> 1 votes

---
Tags: entities, media
---


title: Created Date Doesn't Import (D7 to D7)

text:
# Question
Title: Created Date Doesn't Import (D7 to D7)
I'm using the Node Export Features module to move over some blogs to another Drupal installation.

Everything seems to transfer but the created date. It resets all nodes to the present date. How do I preserve the original created date?

# Answer
> 1 votes
In the dashboard, Go to Configuration \> Node Export \> Reset Values on Import.

...

I love answering my own questions. In fact, every question I've asked here ..well, have been answered by me, and me only. Thanks for all the wonderful help from the (non-existent) Drupal community.

---
Tags: nodes, features, importing-exporting
---


# Question
Title: How to get taxonomy translated when creating a new node in a different language than the interfaces?
**Configuration:**
I set up a multilingual site with `Multilingual support: Enabled, with translation` so I'm creating a new node for each language.

The taxonomy term is set up with the `Translation mode: Translate`, so I have a new term for each language.

**Creating a node with default language first is working fine:**
If I create a new node in my default language using `node/add/page` I correctly see the taxonomy terms in the site language, then after the node is created, using the `Translate` tab and select the Spanish language will work correctly and display the terms in Spanish.

**Creating a node in a different language:**
Now if I want to create a Spanish node first and I go to `node/add/page` I will see the site default language for the terms, so my tid will be in English instead of Spanish even if the language switcher is correctly set to Spanish.
Then when I'll edit this node, my terms will switch back to Spanish and loose the default term I selected while creating the node.

**Partial solution:**
A way to avoid this problem is to go to `es/node/add/page` instead and now the terms are correctly in Spanish.

This solution isn't very convenient, so what is the correct way to handle this efficiently and avoid saving a Spanish node with English terms ?

# Answer
> 0 votes
**Language Selecting**

There are number of ways Drupal distinguishes which language the current user is in (yourself for example).

The admin page at '/admin/settings/language/configure' lists 4 methods.

1. None.
2. Path prefix only.
3. Path prefix with language fallback.
4. Domain name only.

As you can see, to determine the language, Drupal either uses a 'path prefix', 'language fallback' and 'domain'.

The path prefix is simply something like '/de/about-us-page'. Drupal sets the language to German. When I say set, I actually mean it sets it for that particular page request. Then visiting '/about-us-page' would NOT display the language in German but your default language (maybe English).

For Language Fallback, Drupal check if the currently logged in user has a language set in their $user account. If not, it will look for a language from the headers sent from the browser. If in any case the language cannot be determined, the default language is used; again may be English.

The Domain method is simply inspecting the domain and checking if it has been mapped to a language. e.g. German to domain.de.

**Conclusion**

From this, you can see that Drupal is simply reverting back to the default language. You setting the 'language' within the node edit form, is simply mapping this node to that language. Usually when adding content for other languages, I switch into the native language. This ensure my taxonomy terms are mapped correctly.

Essentially, this is not a problem but the way this system works.

**Possible Fix**

If all the terms you are using are common to all languages, you can modify the Taxonomy translation mode to 'Localize' instead of 'Translate'. This should allow all the terms to be saved correctly even if you use the edit page without prefix 'node/add/page'. Just ensure you translate the terms using the String translation module.

Hope this help. Amarjit

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


# Question
Title: Users can spam votes and users will get userpoints
I created the following rule:

* Event: User votes on a Материал
* Condition: Check the value of the vote, greater than 0
* Action: Load points of a user, node:author
* Action: Grant points to a user, node:author 1

When a user votes on a node, the node author will get 1 user point. The same user can vote more than once, and the node author would get 1 user point each time.

UPDATE. Solved my issue by myself. Will add link to solution soon.

# Answer
One simple way to avoid this is to add a rule that removes points whenever a downvote happens. Same rule, different condition (if the value is -1) and different action: Decrease points.
> 0 votes

# Answer
You can use google translate to understand it (russian text):

http://webcoder.kz/modul-rate-userpoints-voting-rules-flag-dobavlyaem-bally-yuzeram-pri-golosovanii-za-nody-kotorye-oni
> 0 votes

---
Tags: 7, rating
---


# Question
Title: 240sec Registering New Account with Services
I am working with a fresh copy of Services 7.x-3.4 / user resource enabled.

A POST to api/user/register is made with Content-Type header application/json and body:

```
{
   "name": "ffftest",
   "pass": "123",
   "mail": "afsdf@awdfasd.com"
}

```

The Drupal user is created immediately, but the HTTP request takes about 240sec to respond. When that finally happens, the response is good: status 200 with the uid/uri.

How do I find out what's going on with the HTTP response and get Services to respond immediately?

(Possibly related to the new CSRF token https://drupal.org/node/2013781#comment-7508325)

# Answer
> 0 votes
This was a server configuration issue as described here: http://www.promediapublishing.com/blog/2012/07/fixing-a-slow-registration-form-post-on-drupal-7

---
Tags: 7, services
---


# Question
Title: How to add link to create relationship in a view
In my project, I have user relationship module installed. I created a view of online users. I then tried to include a link to enable users "add friends or create relationship" in the view by adding the following code

```
 global $user;
  $opt = '';
  $requestee_id = $row->uid;
  $requester_id = $user->uid;
  if (user_is_logged_in()) {
    if ($requestee_id != $requester_id) {
      //for friend request button
      $relationships = user_relationships_load(array('between' => array($requester_id, $requestee_id)));
      if (empty($relationships)) {
        $opt = l(t('Add Friend') , "relationship/$requestee_id/request/1", array('html' => TRUE, 'absolute' => TRUE, 'query' => array('destination' => 'user/' . $requestee_id), 'attributes' => array('class' => array('ur-link add-friend-btn user_relationships_popup_link'))));
      }
      else {
        foreach ($relationships as $relationship) {
          if ($relationship->approved == 1 && user_relationships_ui_check_access('view', NULL, $relationship)) {
            $opt = t('<span class="already-frnd">Friends</span>');
          }
        }
      }
    }
  }
  print $opt;

```

When I try to create a relationship, i am informed that "this user does not exist". Please what could I be doing wrong.

P.S: I have 2 relationships on my site. Thanks in anticipation.

# Answer
I found out this could be done without writing custom code.

In the view:

1. I added a field, User:uid.
2. I unchecked "create a label" and "link this field to its user"
3. Using Rewrite results, i checked Rewrite the output of this field and input "Add as friend".
4. I checked the "Output this field as a link" and then added the path www.example.com/relationship/\[uid\]request/1?destination=user/\[uid\]

That solved the issue.
> 0 votes

---
Tags: views, users
---


# Question
Title: Profile Completeness reminder to the user
Hi i need to send an mail reminder to the user whoever not been completed the profile information. Is there any module available for this? or how do i do this?

Can we do this using rules?

# Answer
You could take a look at Profile Complete Percent (for core Profile module) Content Complete (if using Content Profile).

If you are using Content Profile, here is an article to assist setting up with Rules: Measure node completion in Drupal, part 3. I'm sure you could probably get a Rules workflow going with core Profile module as well.
> 4 votes

# Answer
If you are using Drupal 7 (for the benefit of those coming to this at a later date) you can use the Field Complete module. It has Views and Rules support as well as additional Field module integration. (For the sake of transparency, I wrote it.)
> 1 votes

# Answer
I would build a module that checks the db tables to see if they dont have the default values in them.

If the default value exists, then setup mailing on cron to send reminder mail. just be careful cause if you run cron 10 times in a day that could get very irritating for you users ;)
> 0 votes

---
Tags: 6, hooks
---


title: Error while migrate wordpress to drupal

text:
# Question
Title: Error while migrate wordpress to drupal
I want to migrate a wordpress blog to drupal. I create an "Article blog" content type with three fields: body, tags and categories (plus default title field). I am trying to import with Wordpress migrate (version 7.x-2.2) via url or file, both solution return same error while importing for each article:

> Illegal string offset 'translatable' File drupal\_root/modules/field/field.multilingual.inc, line 176

I am using drupal 7.22 with commons profile 7.x-3.2. All other imports (tag, categories and attachments) works fine.

Do you have an idea about how to solve my problem?

# Answer
> 0 votes
If you can export the content to a csv format. Then use Feeds to import the csv file to the mapped fields.

---
Tags: migrations
---


title: display a complete node

text:
# Question
Title: display a complete node
i want to display a node (from a menu callback), but when i do this:

```
echo node_view(node_load($_POST['classid']));

```

it displays the node without the page template. How do show the entire node, just like someone navigated to '/node/xxx'.

by the way, i can't just redirect to 'node/xxxx' because i need to leave the url without any parameter (stupid requirement by employers)

# Answer
> 0 votes
It's a bit strange that node\_view is not returning a fully formatted node. The node module calls `node_view` inside it's own `hook_menu` to handle `node/%nid` requests.

Is there any chance that your CSS is selecting on something specific to `node/%nid` pages or your templates are setup in a non-standard way.

Can you show us the exact HTML string that is being returned by that function and the HTML string you are expecting?

# Answer
> 0 votes
Only a year late.

```
$url = url('node/XXX', array('absolute' => TRUE));
$html = file_get_contents($url);

```

That will do the trick under most circumstances.

---
Tags: 6
---


# Question
Title: drupal 7 block to show if page has taxonomy term
I want to have a block to show only if the current page has a certain taxonomy term and was planning on using the block visiablity settings.

where Pages on which this PHP code returns TRUE (experts only). and need php code to find out how to tell check if taxonomy term is on the page and then the block will show up on nodes with that term.

# Answer
The code posted by Triskelion did not work for me. Here is the code that I used and worked:

```
<?php
$term_id_to_trigger_show_block = 14; // show this block on nodes with this term id.
$taxonomy_to_search = "field_machinenameofvocab"; // The 'field_' + machine name of the vocabulary to search for the terms
$make_block_visible = FALSE;

// Show this block on nodes with the right term id
if (arg(0) == 'node' && arg(1) && is_numeric(arg(1))) {
  $node_obj = node_load(arg(1));
  $taxonomy = $node_obj->$taxonomy_to_search;
  foreach ($taxonomy['und'] as $term) {
    if ($term['tid'] == $term_id_to_trigger_show_block) {
      $make_block_visible = TRUE;
    }
  }
}

return $make_block_visible;
?>

```

Note that `$taxonomy_to_search` should be set equal to the machine name of the vocabulary prefixed with `field_`. So if my vocabulary machine name is `animal_species` that line would be `$taxonomy_to_search = "field_animal_species";`

**UPDATE:** After using the above code on a site for quite some time I realized that it was giving me PHP errors in my logs. My solution was to give up on displaying a standard block and use views instead.

Create a new block view, set it to display fields. For your only field use "Global: Custom Text," entering your desired block content in the custom text field.

Under "Contextual Filters" add "Content: NID" and then "Provide default value" of "Content ID from URL."

Finally under "Filter Criteria" your only filter should be "Content: Has taxonomy term." Set it up to look for your term.
> 2 votes

# Answer
To do this, the code you need would be like the following:

```
<?php
// ID of desired term
$term_tid = 3;
// Check if you are on a node page, and get the nid
if (arg(0) == 'node' && is_numeric(arg(1)) && is_null(arg(2))) {
  $nid = (int)arg(1);
  // Load the node object
  $node = node_load($nid);
  // Check for the existence and then check the value of the term ID
  if (isset($node->field_term[$node->language][0]['tid']) && $node->field_term[$node->language][0]['tid'] == $term_tid) {
    return TRUE;
  } else {
    return FALSE; }
}
?>

```

Just substitute the name of your term reference field for field\_term, and set the tid of the term you wish to use. If your term reference field allows multiple values, you will have to get a little more rigorous and look for the value in the array.
> 0 votes

---
Tags: taxonomy-terms
---


title: How to define a function in drupal core

text:
# Question
Title: How to define a function in drupal core
How should I define a function in the core of drupal 7 that I can use the function in the blocks, pages and etc?

# Answer
> 7 votes
Simple answer - don't :)

You shouldn't change anything in the core files, it'll just make things difficult when you try to update.

Drupal's way of extending functionality is through Modules; it's easy to write your own.

When a module is enabled, all the functions defined in the 'MODULENAME.module' file are available during the page build. So if you define a function

```
function MYMODULE_say_hello() {
  return 'Hi!';
}

```

That will be available for use in code in the same module, other modules and themes.

As Drupal doesn't currently use namespaces, it's important to prefix your 'global' function names with the name of the module. This just helps to make sure you avoid collisions with other functions of the same name (imagine another module also wanted to say\_hello()), which would otherwise result in a fatal error.

There's also a convention in Drupal programming to prefix 'private' function names (those that should only be used internally by your module), with an underscore, e.g.

```
function _MYMODULE_say_hello_quietly() {
  return '<hush>Hi</hush>';
}

```

This doesn't technically stop them from being available to other modules (which is actually a good thing in a lot of cases), but it's a good pattern to fall into for Drupal 6/7 development.

For Drupal 8, thankfully, we'll have a much more OO focused core. But that's a topic for another day...

---
Tags: 7
---


title: From array to menu

text:
# Question
Title: From array to menu
How can I render an array as a menu? Is there some core function I can use?

# Answer
Yes, if your array has the structure of a menu array. See the output of

```
$tree = menu_tree_page_data('main-menu');

```

for a reference of a valid menu array structure.

Once you have your array, this is how you can render it.

```
$main_menu = menu_tree_output($tree);
print drupal_render($main_menu);

```
> 1 votes

# Answer
I think you are looking for theme\_links().

```
$links = array(
  'item1' => array('title' => '1st Item', 'href' => 'one' ),
  'item2' => array('title' => '2nd Item', 'href' => 'two' ),
);

print theme('links', array(
  'links' => $links,
  'attributes' => array('class' => array('links', 'inline')))
);

```
> 2 votes

---
Tags: routes
---


# Question
Title: External class (migration class) not found
I have a module for my migration. My .info is:

```
name = "Migrate from MHT"
description = "Module to migrate my old site content to Drupal 7"
package = "ZbLabs"
core = 7.x

dependencies[] = migrate

#  include the files that contain your Migrate classes
files[] = migrate_mht.migrate.inc
files[] = migrate_mht.module
files[] = migrate_mht_author.inc
files[] = migrate_mht_author_update.inc
files[] = migrate_mht_eventi.inc

```

In the migrate\_mht\_author\_update.inc I have a class with this code:

```
$this->map = new MigrateSQLMap($this->machineName,
  array(
    'id' => array(
      'type' => 'int',
      'not null' => TRUE,
      'description' => 'ID utente',
    )
  ),
  MhtAuthorDestination::getKeySchema()
);

```

The MhtAuthorDestination class is defined in "migrate\_mht\_author.inc" file.

```
class MhtAuthorDestinationMigration extends MigrateDestinationUser {

  public function __construct(array $arguments = array()) {
    dd("MhtAuthorDestinationFin __construct");
    dd($arguments);
    parent::__construct();
  }
  [....]
}

```

Now when I exec "drush ms" I receive this error:

```
Error: Class 'MhtAuthorDestination' not found in /MY/PATH/sites/all/modules/zblabs/migrate_mht/migrate_mht_author_update.inc, line 38

```

In "migrate\_mht.migrate.inc" file I have: function migrate\_mht\_migrate\_api() {

```
 $api = array(
    'api' => 2,
    //'migrations' => array(
      //'MhtAuthorDestination' => array('class_name' => 'MhtAuthorDestination'),
    //),

  );

  return $api;
}

```

I have tried without comment (//) but the error remain.

Where is my error ?

# Answer
> 0 votes
The class name in your include file is MhtAuthorDestinationMigration, but you list its class name in hook\_migrate\_api as MhtAuthorDestination. Uncomment the line and try:

```
$api = array(
  'api' => 2,
  'migrations' => array(
    'MhtAuthorDestination' => array('class_name' => 'MhtAuthorDestinationMigration'),
  ),
);

return $api;

```

---
Tags: 7, migrations
---


# Question
Title: How to change Drupal's default login error text
I have tried using this code -

```
     */
    function customform_demo_form_alter(&$form, &$form_state, $form_id) {
     global $user;

      if ($form_id == 'user_login'); {
        if (!$user->uid) {
            array_unshift($form['#validate'],'customform_demo_user_login_form_validate');
        }else{
        drupal_get_messages();
        }
      }

}

function customform_demo_user_login_form_validate(&$form, &$form_state) {
  drupal_set_message('Your username or password was not recognized. <a class="login_link" href="/user/password">Click here to reset your password.</a>', 'status');
}

```

but can't get the message in the default format.

# Answer
I'm pretty sure you shouldn't have a semi-colon after your if condition.

```
 if ($form_id == 'user_login'); {}

```

Does removing that have any effect?
> 0 votes

---
Tags: users
---


# Question
Title: Need help modifying the OG "add user" form to replace the user search box with first and last name searches
I could really use some guidance with an OG related task. I'm needing to modify a form used to add existing users to organic groups. The path is "/group/node/1/admin/people/add-user". I need to remove the user search box and instead implement a couple of name searches: "Firstname, Lastname", and "Lastname, Firstname". Not sure what I should be modifying via a hook\_form\_alter, or other hook. Any thoughts?

Attached is a before and after view of the form. I appreciate any guidance anyone can provide.

Thanks!

# Answer
I ended up using a custom callback to populate a new field called "full\_name", and then used JQuery to populate the username field on blur of my new field, and also hid the username field to make the interface a little more intuitive. It worked well enough, but it would be nice to completely override the submit function and use a custom one to ensure everything worked as expected. If a user enters in an invalid name and clicks enter, the default validation fires off, and nothing I've created works without a page reload. Kind of stinks, but at least it's working for the time being.
> 0 votes

---
Tags: users, search, organic-groups, forms
---


# Question
Title: Module-heavy site quits without error on W7 dev machine
I have taken over development of a major Drupal 6 site (I'm not a Drupal newbie by any means) - I did quite a lot of the original work and never had the following problem, however there have been changes since then:

Any admin function which involves building large data structures from all modules causes the dev site to silently quit. There are no Apache or PHP errors, just:

*Unable to load the webpage because the server sent no data. Error code: ERR\_EMPTY\_RESPONSE*

That's the result in Chrome, IE fails similarly. It's definitely happening in the code.

I can't rebuild menus, access the module page or enable the Update module. The rest of the site works fine.

I analysed the problem down to the point where I have established the crash definitely occurs when it's building big data structures. It has about 360 modules and when building the module page can get to 252 before it simply dies.

I running on WAMP over W7 with PHP 5.3.13 and Apache 2.2.22 Any ideas on what's causing it and if it's solvable?

(Any comment like "don't use windows" or "use fewer modules" are not very helpful at this point.)

EDIT: Additional data. I was wrong about the lack of Apache error messages, although it's not very helpful:

```
[Fri Aug 02 22:21:09 2013] [notice] Server built: May 13 2012 19:41:17
[Fri Aug 02 22:21:09 2013] [notice] Parent: Created child process 10076
[Fri Aug 02 22:21:09 2013] [notice] Child 10076: Child process is running
[Fri Aug 02 22:21:09 2013] [notice] Child 10076: Acquired the start mutex.
[Fri Aug 02 22:21:09 2013] [notice] Child 10076: Starting 64 worker threads.
[Fri Aug 02 22:21:09 2013] [notice] Child 10076: Starting thread to listen on port 80.
[Fri Aug 02 22:21:09 2013] [notice] Child 10076: Starting thread to listen on port 80.
>>>> ERROR MESSAGE NEXT
[Fri Aug 02 22:23:08 2013] [notice] Parent: child process exited with status 255 -- Restarting.
<<<<
[Fri Aug 02 22:23:08 2013] [notice] Apache/2.2.22 (Win64) PHP/5.3.13 configured -- resuming normal operations
[Fri Aug 02 22:23:08 2013] [notice] Server built: May 13 2012 19:41:17

```

Seems there are a multitude of possibilities for this and it may be related to this: What can cause Drupal to crash Apache?

# Answer
> 0 votes
Okay. I do not understand why but it seems the answer here actually is the answer in the other question. Here's what you do:

In Apache's httpd.conf find the line

```
# Server-pool management (MPM specific)
Include conf/extra/httpd-mpm.conf

```

And un-comment it so the httpd-mpm.conf file is run. Then load up that file and go to the bottom where you'll see this:

```
# WinNT MPM
# ThreadsPerChild: constant number of worker threads in the server process
# MaxRequestsPerChild: maximum  number of requests a server process serves
<IfModule mpm_winnt_module>
    ThreadStackSize      8388608
    ThreadsPerChild      150
    MaxRequestsPerChild    0
</IfModule>

```

Not including the ThreadStackSize - add that line with the nice big number. And the crash stops. Essentially I was right in my diagnosis - the data structure being built is too big but it's too big for the thread, not the overall memory allocation.

The reason I'm confused is that, as far as I can see, that module is not loaded and run in Apache, but maybe it's not configurable and always runs.

Anyway this works.

---
Tags: 6
---


# Question
Title: Product View does not show for Anonymous user
I would like to use a view to display products in front page. So, in the view 'Products (Commerce Product)' i created separate block view 'My Products Block'. This view is added to the region in Block section and then rendered in the front page:

```
print render($page['region_containing_product_view']);

```

This displays products fine if logged in as admin but not for anonymous users. For anonymous users it shows:

```
No products have been created yet. Add a product.

```

I have updated the permissions for my custom view to 'Access:Role | anonymous user' but it still doesn't show the products. How come? what am i doing wrong?

Thank You p.s. Drupal 7, Commerce module

# Answer
> 7 votes
It turns out for every product type created there is permissions that need to be enabled for every user roles including anonymous users

'people-permissions-roles'

---
Tags: commerce
---


title: problems usings new custom theme

text:
# Question
Title: problems usings new custom theme
I have created a custom theme for my website. Now, I've started getting some strange problems.

After installing Profile2 module, I am not getting view & edit option but it work fine if I use Bartik theme.

Another problem is that if an authenticated user logs in, his defalut home page changed to 'user/18' & couldn't able to access front page (as defined in page--front.tpl.php). But this works fine in case of Bartick.

I don't know what did I miss in my new custom theme. Any suggestions?

# Answer
> 0 votes
You must have forget to render `$tabs` variable in your custom theme. You have to render it before you render your `$content` in `page.tpl.php`

Example from my `page.tpl.php` --

```
<?php if ($page['content']): ?>
    <div class="content">
        <?php if ($tabs): ?>
            <div class="tabs">
                <?php print render($tabs); ?>
            </div><!--tab end-->
        <?php endif; ?>
        <?php if ($title) : ?>
            <h1 class="title">
                <?php print $title; ?>
            </h1>
        <?php endif; ?>
        <?php print render($page['content']); ?>
    </div><!--content end-->
<?php endif; ?>

```

Structure your `page.tpl.php` like this by rendering `$tabs` variable before title, clear the cache & you will have tabs..

---
Tags: theming, users, installation
---


title: Need to change the title of views

text:
# Question
Title: Need to change the title of views
I have created a view which displays all the posts of an author. I need to set the title as - "(Author Name)'s Posts" or "Posts by (Author Name)" where Author Name will change depending on the profile the reader is visiting. Can someone please help me with it...

# Answer
> 3 votes
If you are using **Contextual Filter** in the view then you can override the title by putting `%1` for first argument, `%2` for second argument etc..

Otherwise add a contextual filter for something like "`Content:Author`"(depend upon your need) in your created view & override the title in there by placing `%1`

---
Tags: views, 7
---


# Question
Title: new content type with fields for username and password
I have a requirement for creating a new content type and creating a new user through that.

The content type have fields like 'name', 'address' etc. but the client wants to have username and password field in that, so that the user could be created along with it.

I am a bit lost with this, any suggestions please?

# Answer
Under `Configuration->People->Account settings->Manage fields` in the menu (admin/config/people/accounts/fields) you can add fields to the User entity, such as name and address.

Fields added to the User entity has a settings whether they should be displayed on user registration form.
> 2 votes

---
Tags: 7, entities, users
---


# Question
Title: Mass Node Update (e.g., disable comments for all nodes of a given content type)
Is it possible to mass update nodes from, say, "Comments Read/Write" to "Comments Disabled" for all nodes of a certain content type?

I changed the Content Type setting and that worked for all the other nodes types, except for a certain Node type that has given us problems in the past.

Thx

# Answer
> 5 votes
There's a module called Views Bulk Operations.

I never tried to do it, but I think you can write your own operations for this module pretty easily.

# Answer
> 2 votes
Not for the weak of heart, and this bypasses the chance for hooks to fire on the node save / update as well as revisioning, but I usually do this with direct queries.

```
UPDATE node
SET comment = 0
WHERE type = 'some_type'

```

should do it. Make sure you take a backup to be safe. If you are on Drupal 7, the comment status is also in `node_revision`, so you need to do

```
UPDATE node_revision nr
INNER JOIN node n ON n.vid = nr.vid
SET nr.comment = 0
WHERE n.type = 'some_time'

```

as well.

# Answer
> 1 votes
Disable comments here first:

```
structure->content types->{node_type}->edit->comment settings

```

To update the nodes use hook\_update below:

```
/**
 * Disable comments on node_type
 */
function hook_update_N(&$sandbox) {
  $content_type = 'node_type';

  // Initialize batch.
  if (!isset($sandbox['total'])) {
    $query = db_select('node');
    $query->addExpression('COUNT(*)');
    $query->condition('type', $content_type);

    $sandbox['total'] = $query->execute()->fetchField();
    $sandbox['progress'] = 0;

    if (empty($sandbox['total'])) {
      $sandbox['#finished'] = 1;
      return t('No %type nodes exist in database.', array('%type' => $content_type));
    }
  }

  // Get and update nodes.
  $nids = db_select('node')
    ->fields('node', array('nid'))
    ->condition('type', $content_type)
    ->range(0, 10)
    ->execute()
    ->fetchCol();

  if (!empty($nids)) {
    $nodes = node_load_multiple($nids, NULL, TRUE);

    foreach ($nodes as $node) {
      $node->comment = 1; // I set comments as 1 where value of 2 enables the comments.
      node_save($node);   // Re-save the node.
    }
  }

  // Increment & check progress.
  $sandbox['progress'] += count($nids);
  if (empty($nids) || $sandbox['progress'] >= $sandbox['total']) {
    $sandbox['#finished'] = 1;
    return t('Updated @count nodes.', array('@count' => $sandbox['progress']));
  }
  else {
    $sandbox['#finished'] = $sandbox['progress'] / $sandbox['total'];
  }
}

```

Do not forget to replace **'node\_type'** to your node type.

# Answer
> 0 votes
If you're looking for a Drupal 6 solution that does not involve SQL queries or running your own PHP code via VBO or custom module, there is also Mass Change. It allows you to change statuses, including comment status, for all nodes of a particular content type.

---
Tags: nodes
---


title: Is there simple drupal 7 cart modules?

text:
# Question
Title: Is there simple drupal 7 cart modules?
I really need to create a cart system without payment methods , I only want to get an order email from the user. Is there any modules in drupal 7 to do this?

# Answer
Maybe the Webform module is sufficient in your case?

With Webform you can create forms and form components from an UI. When a submission has been made from a user you can setup mails that should be sent.
> 0 votes

---
Tags: 7
---


# Question
Title: XMLSitemap- Is it OK to add nodes both by content type and menu?
I'm making a sitemap using the XML Sitemap module. The module and its submodules allow nodes to be added to the sitemap from the content type configuration screen as well as the menu configuration screen.

So, for example, I can add all nodes of type *Basic page* to the sitemap, and then I can add all links in the *Primary links* menu (many of which are nodes of type *Basic page*) to the sitemap as well.

My question: Is doing this OK? Should I be worried about having duplication between adding the content types and adding the menus? Or is this nothing to worry about?

# Answer
> 2 votes
There is no harm in adding both by menu and by content type (I have tested this before). In my experience, paths will not be duplicated.

If you also add by content type, then that priority will be used, even if it is lower than the one you have set for the menu. Also, the last modification date will be used; it doesn't get used when you add by menu. The XML Sitemap module also checks node access rights, so only ones visible by anonymous will end up in the sitemap.

If you add by menu, the module will not output links that the anonymous user doesn't have access to.

I don't recall explicitly testing paths that exist in multiple menus, though.

# Answer
> 1 votes
There are 2 aspects:

1. SEO - if one node is always seen under one address, or you properly set canonical, it's no problem.
2. HTML structure - you need to make sure there are no duplicated IDs on links when you output them twice, as it can sometimes mess Drupal's (and contrib) javascript operating on links. And of course it prevents your site from validating with w3c tools.

---
Tags: xml-sitemap
---


title: Inheritance filters in view

text:
# Question
Title: Inheritance filters in view
I've got content-type with two fields with real values. Their interior name are field\_price1 and field\_price2. I created page view includes contents. I've got search. I want to allow user to give some value(s) in search (min and max) to seek contents. I want to display only these contents whose field\_price1 OR field\_price2 is between min and max filled in by user.

Has someone any ideas?

I tried and I decided to create two filters. First filter (for field\_price1) exposed, second (for field\_price2) not. So that, in my search I've got two inputs (I chose between operator). I wanted the second filter inherits values from first filter. I coded:

```

function customSearch_views_pre_execute(&$view) {
  if ($view->name == 'search') {
    $filters = $view->display_handler->get_option('filters');
    $filters['field_price2_value']['value']['min'] = $view->exposed_input['field_price1_value']['min'];
    $filters['field_price2_value']['value']['max'] = $view->exposed_input['field_price1_value']['max'];
    $view->display_handler->override_option('filters', $filters);
  }
}

```

I place that function in my custom module named customSearch. My view is named search. Unfornately it doesn't work. Second filter doesn't inherit values from first one. I don't know why. Could someone help me, please?

# Answer
You will need to implement hook\_views\_query\_alter to get this going.

Start with the filters in Views.

Make your filters look **exactly** like this. With that I mean that there should be two groups of filters with AND between the groups. And you need to set Or in the second group. This is important otherwise the code below will not work.

Then replace hook\_views\_pre\_execute with the code below for hook\_views\_query\_alter. I also recommend you rename your module to customsearch instead of customSearch, small letters is standard in function names for Drupal.

```
/**
* Implements hook_views_query_alter().
*/
function customsearch_views_query_alter(&$view, &$query) {
  if ($view->name == 'search') {
    if (isset($query->where[2]['conditions'][0]['field']) && $query->where[2]['conditions'][0]['field'] == 'field_data_field_price1.field_price1_value') {
      $query->where[2]['conditions'][1]['value'][0] = $query->where[2]['conditions'][0]['value'][0];
      $query->where[2]['conditions'][1]['value'][1] = $query->where[2]['conditions'][0]['value'][1];
    }
    else {
      unset($query->where[2]);
    }
  }
}

```

In the code I first check to see if something has been entered in the exposed filter. If it is present we populate the second filter's values.

If you enable the module devel and do dsm($query) just before the last `}` you can debug and look in the array yourself. For exammple number 2 in `$query->where[2]` means the second group of filters, which you will see easily if you debug.

Update: I've added an else statement so that the price fields are not in effect at all if nothings been entered in the in betweens.
> 0 votes

---
Tags: views, 7
---


# Question
Title: Download count module does not work for me
I installed the Download Count module for Drupal 6. The automatic views were normally generated by the module. One of these views is file\_download with a page format. The view should generate statistics, but I find no statistics generated by the view. I opened the view and I found everything is normal, unless there is something I am not aware of.

Did I miss anything?

# Answer
> 1 votes
Try setting your file field to use private file system instead of public.

---
Tags: views
---


# Question
Title: Checking if module has the right output on multilingual pages with simpletest_clone
I'm trying with simpletest\_clone to check if my modules have the right output depending on the language.

Now my problem is, that when I do the following Code:

```
$this->drupalGet('de');
// check the output

$this->drupalGet('fr');
// check the output again for the french version

```

Drupal then checks for `localhost/de/de` and `localhost/de/fr` (`de` is the default language) instead of `localhost/de` and `localhost/fr`

How can I change that behaviour?

# Answer
I would set the default langauge in code first instead.

```
// Get the list of languages
$languages = language_list();

// Set up the new language code
$new_lang_code = 'fr';

// Make sure the required language object is actually set
if (isset($languages[$new_lang_code])) {
  // Overwrite the global language object
  global $language;
  $language = $languages[$new_lang_code];
}

```

and then you just need to get the front page (and Drupal should add the prefix).

```
$this->drupalGet('<front>');

```

If `front` doesn't work you might need

```
$front_url = variable_get('site_frontpage', 'node');
$this->drupalGet($front_url);

```
> 0 votes

---
Tags: testing, i18n-l10n
---


title: Multiple Rules under Rule Set

text:
# Question
Title: Multiple Rules under Rule Set
I am trying to create a Rule set which has 4 Rules under it. Using this Rule set as an action in a Triggered Rule. I want that when any of the these 4 Rules is True, the action is triggered.

But looks like the Rules under Rule Set is assigning them AND condition. How can I set it to OR condition.

I have tried changing the logical operator to Or for each group. But that is not working.

Am I missing something, or this feature is not a part of Drupal 6?

# Answer
Ok. I got my problem. I was using checkbox cck field. So the Rules were checking all values to be matched. To overcome this issue, I used Rules Bonus Pack module and in that used "Field value is one of several" condition.

Finally got it working as desired!
> 0 votes

---
Tags: 6, rules
---


title: an error when changing the date form

text:
# Question
Title: an error when changing the date form
I need to change the date form of quiz module in quiz.module on line 1307 it was this:

```
  $form['quiz_availability']['quiz_open'] = array(
    '#type' => 'date',
    '#title' => t('Open Date'),
    '#default_value' => _quiz_form_prepare_date($node->quiz_open),
    '#description' => t('The date this @quiz will become available.', array('@quiz' => QUIZ_NAME)),
    '#after_build' => array('_quiz_limit_year_options'),
  );
  $form['quiz_availability']['quiz_close'] = array(
    '#type' => 'date',
    '#title' => t('Close Date'),
    '#default_value' => _quiz_form_prepare_date($node->quiz_close, variable_get('quiz_default_close', 30)),
    '#description' => t('The date this @quiz will cease to be available.', array('@quiz' => QUIZ_NAME)),
    '#after_build' => array('_quiz_limit_year_options'),
  );

```

and I changed it to this:

```
 $form['quiz_availability']['quiz_open'] = array(
    '#type' => 'date_select',
    '#date_format' => 'Y-m-d H:i',
    '#title' => t('Open Date'),
    '#default_value' => _quiz_form_prepare_date($node->quiz_open),
    '#description' => t('The date this @quiz will become available.', array('@quiz' => QUIZ_NAME)),
    '#after_build' => array('_quiz_limit_year_options'),
  );
  $form['quiz_availability']['quiz_close'] = array(
    '#type' => 'date_select',
    '#date_format' => 'Y-m-d H:i',
    '#title' => t('Close Date'),
    '#default_value' => _quiz_form_prepare_date($node->quiz_close, variable_get('quiz_default_close', 30)),
    '#description' => t('The date this @quiz will cease to be available.', array('@quiz' => QUIZ_NAME)),
    '#after_build' => array('_quiz_limit_year_options'),
  );

```

but now the webpage gives an error. How do I fix this error? The Error:

> Please supply a valid date. PDOException: SQLSTATE\[01000\]: Warning: 1265 Data truncated for column 'quiz\_open' at row 1: INSERT INTO {quiz\_node\_properties} (vid, nid, aid, number\_of\_random\_questions, randomization, backwards\_navigation, repeat\_until\_correct, quiz\_open, quiz\_close, takes, show\_attempt\_stats, keep\_results, time\_limit, pass\_rate, summary\_pass, summary\_pass\_format, summary\_default, summary\_default\_format, quiz\_always, feedback\_time, display\_feedback, tid, has\_userpoints, allow\_skipping, allow\_resume, allow\_jumping, show\_passed, mark\_doubtful) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4, :db\_insert\_placeholder\_5, :db\_insert\_placeholder\_6, :db\_insert\_placeholder\_7, :db\_insert\_placeholder\_8, :db\_insert\_placeholder\_9, :db\_insert\_placeholder\_10, :db\_insert\_placeholder\_11, :db\_insert\_placeholder\_12, :db\_insert\_placeholder\_13, :db\_insert\_placeholder\_14, :db\_insert\_placeholder\_15, :db\_insert\_placeholder\_16, :db\_insert\_placeholder\_17, :db\_insert\_placeholder\_18, :db\_insert\_placeholder\_19, :db\_insert\_placeholder\_20, :db\_insert\_placeholder\_21, :db\_insert\_placeholder\_22, :db\_insert\_placeholder\_23, :db\_insert\_placeholder\_24, :db\_insert\_placeholder\_25, :db\_insert\_placeholder\_26, :db\_insert\_placeholder\_27); Array ( \[:db\_insert\_placeholder\_0\] =\> 24 \[:db\_insert\_placeholder\_1\] =\> 22 \[:db\_insert\_placeholder\_2\] =\> 0 \[:db\_insert\_placeholder\_3\] =\> 0 \[:db\_insert\_placeholder\_4\] =\> 2 \[:db\_insert\_placeholder\_5\] =\> 1 \[:db\_insert\_placeholder\_6\] =\> 0 \[:db\_insert\_placeholder\_7\] =\> 2013-08-03 01:02 \[:db\_insert\_placeholder\_8\] =\> 2013-09-02 15:13 \[:db\_insert\_placeholder\_9\] =\> 1 \[:db\_insert\_placeholder\_10\] =\> 1 \[:db\_insert\_placeholder\_11\] =\> 2 \[:db\_insert\_placeholder\_12\] =\> 0 \[:db\_insert\_placeholder\_13\] =\> 75 \[:db\_insert\_placeholder\_14\] =\> \[:db\_insert\_placeholder\_15\] =\> plain\_text \[:db\_insert\_placeholder\_16\] =\> \[:db\_insert\_placeholder\_17\] =\> plain\_text \[:db\_insert\_placeholder\_18\] =\> 1 \[:db\_insert\_placeholder\_19\] =\> 1 \[:db\_insert\_placeholder\_20\] =\> 1 \[:db\_insert\_placeholder\_21\] =\> 0 \[:db\_insert\_placeholder\_22\] =\> 0 \[:db\_insert\_placeholder\_23\] =\> 1 \[:db\_insert\_placeholder\_24\] =\> 1 \[:db\_insert\_placeholder\_25\] =\> 1 \[:db\_insert\_placeholder\_26\] =\> 1 \[:db\_insert\_placeholder\_27\] =\> 0 ) in quiz\_insert() (in line 739 /home/...../public\_html/...../sites/all/modules/quiz-7.x-4.0-beta1/quiz/quiz.module).

# Answer
When you want to override forms created by core or custom modules you should implement hook\_form\_alter() in a custom module.

It will look something like

```
/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, $form_state, $form_id)  {
  if ($form_id == 'quiz_form') {
    $form['quiz_availability']['quiz_open']['#type'] = 'date_select';
  }
}

```

Or as a hook\_form\_FORM\_ID\_alter() and then it would look like this

```
function mymodule_form_quiz_form_alter(&$form, &$form_state, $form_id) {
  $form['quiz_availability']['quiz_open']['#type'] = 'date_select';
}

```
> 0 votes

---
Tags: 7
---


# Question
Title: How to display search results in admin theme?
I want to start using the search function in my admin area. I googled quite a lot, but i couldn't find away to display the search results in the admin theme. Anyone any idea's how to accomplish this?

# Answer
At the code level you can use `hook_admin_paths()`, e.g.

```
function MYMODULE_admin_paths() {
  return array(
    'search/*',
  );
}

```

Or if you'd rather use a non-code solution, you could install a module like ThemeKey

> ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties.
> 0 votes

---
Tags: search
---


# Question
Title: How to change field label name in a view programmatically
I want to change the views field label name programtically? I have written a views-view-field.tpl.php. but dont know to change the $output variable.

# Answer
You can use hook\_views\_pre\_render() for that.

Add this function to your `template.php` file:

```
function YOURTHEME_views_pre_render(&$view) {

  switch ($view->name) {
    case 'name_of_your_view':

      // do some logic for your label
      $label = 'My dynamic label';

      // define the label value
      $view->field['fieldname']->options['label'] = $label;
      break;
  }
}

```

Now, the label value will be always as the logic result. No matter whether the label is defined via Views Ui or not, it will be altered by your logic anyway.
> 7 votes

# Answer
When you want to have control over any output at the theme layer, you will have to understand the flow which generate the output.

At first lets see how the output for a field get structured at theme.inc inside view/theme folder. You can have a look at it here. Where you will see `$label` & `$label_html` getting prepared for *tpl* files.

So you a option to do your work with help of this preprocess function also, which you will have to implement in your `template.php`. You will prepare label name before it goes to *tpl* file to be printed.

Other way is, when you visit your views-view-fields.tpl.php inside same folder of views/theme, you will see `$label_html` to be printed in there. You will have to work on it to achieve what you want as this contains full HTML structure of label of the field.

I believe there are way to do this by help of `field--FIELDNAME.tpl.php` also if you are looking to change the label for being displayed the same at every place..

Note - This is not the exact solution but guideline to follow & get your own solution. I have never done this exactly for view but for field label where ever it appears, so if you need, I can post exact solution for that.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Adding custom functions PHP to use in a views template
I want to use a custom function in `views-view-fields--field-name.tpl.php` template file. Where do I have to put it? Is it possible to use it in template.php in some preprocess functions?

# Answer
You can use a preprocess function in your `template.php` file. For example:

```
function YOURTHEME_preprocess_views_view_fields__field_name(&$vars) {
  // Do your changes for the field here
}

```
> 4 votes

# Answer
In Drupal 7, you can achieve this using module\_load\_include OR include\_once.

* Create a .inc file in the custom module, which will keep all the template files functions, or if you have only one function then just add the function in your custom module.
* Go to your template file (views-view-fields--field-name.tpl.php) and include the file using `module_load_include()` or `include_once()`
    + If it is a .inc file, use `module_load_include('file_type', 'module_name', 'base_file_name');`
    + If it is a function in a custom module, use `include_once 'FILE_PATH';`
> 1 votes

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


# Question
Title: How to make possible to flag only one node
I have a view with lists of 10 nodes with a node display type (not rows). Every node has a flag. How to make possible to flag ONLY one node of these 10 nodes, for example if you have flagged one node - you cannot flag another one untill you unflag flagged one. Just like a best answer functionality on this site. Thanks :)

# Answer
> 8 votes
You're looking for the *Flag trim* action, which you can implement with Rules.

If you make a rule that is activated on the event "Node is flagged" with "Trim the flag" for the relevant user to "1", then the other flags will be cancelled and only the most recent flag will remain.

# Answer
> 0 votes
Is Flag Limit module what you are looking for?

> This module allows any flag (for example: bookmarks) to have a limited number of items.
> ...
> There is a new feature in the 7.x-1.x branch that optionally lets you limit the number of flaggings each item can have. Once the limit is reached, nobody else can flag the item.

---
Tags: 7, flags
---


title: Products Display

text:
# Question
Title: Products Display
I am working on converting commerce theme to Drupal Template and have difficulty understand how the Product attribute selection works in the product display.

i have one product display type for multiple products. There is wide variation of products(i.e. runner shoes, tennis shoes,etc). For each product display instance i have selected few of those variations(i.e for Runner shoes i have red runner shoes small , blue runner shoes small, blue runner shoes large, etc). It works nice where user are able to select the attributes and the particular product is displayed.

In the template.php, i load the product display instance:

```
$node = $vars['node'];

```

This instance has reference to the products($node-\>field\_product). So far so good:) The difficulty is to determine which product of these referenced is currently displayed. How can i do that? In what variable is the object or its id is stored? I see in the default html things like:

```
attributes[field_template_type]

```

How is this all thing working? Any help or source of reference much appreciated

# Answer
I'm not sure the currently displayed product would be found at the $node level in the template. Typically, when a page is first loaded, it's going to be the product referenced in the field at delta 0. This is alterable, though, so you could invoke the API function, commerce\_product\_reference\_default\_product(), in template.php and enrich the $node with that information.

After the page has been initially loaded and displayed, the "currently displayed product" may change based on user input. We store this as the "default product" in the form state variabel $form\_state\['default\_product'\] of the Add to Cart form. I assume you'd be able to propagate this from there through to your template somehow, likely through a combination of form alter and preprocess in your template file.
> 2 votes

---
Tags: theming, commerce
---


# Question
Title: How can I track order details (products, quantities) in PayPal?
**BACKGROUND**

I have an online store. Previously, I used PayPal "Buy it now" buttons, and I had a button for each product. I would then periodically export the data from PayPal (download history as CSV) and it would have the following field/value pairs:

**Item Title**: *Type of product* (e.g., Nintendo DS)

**Option 1 Name**: *Type of product* (e.g., Nintendo DS)

**Option 1 Value**: *Color* (e.g., red)

Users were limited to ordering one item per order. I used this information to analyze what are the top selling products/variations in the store in Excel, and I have a few years of historical data.

**DRUPAL COMMERCE**

I recently moved the store to Drupal Commerce, although I am still using PayPal for payment (PayPal Payments Standard/WPS) via the Commerce PayPal module. This works very well, and users are still limited to one item per order. However, when I export the transaction data from PayPal, it now looks like this:

**Item Title**: *Shopping Cart*

**Option 1 Name**: *null*

**Option 1 Value**: *null*

Is it possible to set the **Item Title** and options somehow during checkout with Commerce? If not, how can I analyze my new sales data in Excel in a way that is (at least mostly) consistent with the years of PayPal exports I already have?

# Answer
> 2 votes
Right now, Commerce PayPal does not itemize order information for PayPal WPS. We implemented itemized order details for Express Checkout in the 2.0 branch, but we currently just have a patch in a feature request to add this support to WPS. If you'd like to review it or follow along, the issue is here: https://drupal.org/node/1301570

In the meantime, your alternative could be to create a View inside your Drupal site that uses Views Bonus Pack to generate a CSV in the same format for your completed orders. That might even be a preferable long term solution, as it will work regardless of what payment method a customer uses to buy from you (in the event that you add additional methods).

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


# Question
Title: How do I access the node's uid in hook_node_access()?
I have implemented hook\_node access so that two users cannot view each other's posts if they do not have the right permission (I implemented the permission in hook\_permission). I use a comparison with $node-\>uid as follows:

```
 function mymodule_node_access( $node, $op, $account)
 {
   global $user;
   $type = is_string($node) ? $node : $node->type;

   switch($type)
   {
    case "myCustomType":

      if ( ($user->uid != $node->uid) && !user_access("view other's posts"))
       {
              return NODE_ACCESS_DENY;

       }
       break;

   }

}

```

Everything works fine but I do get the following warning:

> Notice: Trying to get property of non-object in `mymodule_node_access()`.

This is caused by this: $node-\>uid. Drupal complains that $node is a not a stdobject (it seems to actually be string containing the node's type). Yet the code still works which I do not understand why.

What is the proper way to access the node's uid from hook\_node\_access?

# Answer
The `$node` parameter is

> Either a node object or the machine name of the content type on which to perform the access check.

When that hook is invoked with the *create* op, there's no node object available, so `$node` is a string.

You're already handling that bit, but you're missing a check on the `$op` parameter. The reason it's working is because when your function is invoked with the op you're trying to target (probably *view*), `$node` is an object and has a `uid` property.

With your current code, you'll get one of those notices every time someone other than user 1 tries to create a node, because `$node` is not an object.

Try re-working your code like this:

```
function mymodule_node_access( $node, $op, $account)
 {
   if ($op == 'create') {
     $type = $node;
     // You can be reasonably sure that $account is the user who's trying to create the node here.
     // You'll probably want to ignore this bit and check $op specifically for the
     // actions you're looking for; this is just here to show the workflow.
   }
   else {
     if ($node->type == 'myCustomType') {
       // Be sure to use the $account var here, not the global $user object
       if ( ($account->uid != $node->uid) && !user_access("view other's posts", $account)) {
       return NODE_ACCESS_DENY;
     }
   }

   return NODE_ACCESS_IGNORE;

```
> 4 votes

# Answer
You'll find the uid in the `$account` object with `$account->uid`.
> 0 votes

# Answer
The value passed in `$node` could also be the content type of the node being created; that is why the following line is necessary to get the content type.

```
$type = is_string($node) ? $node : $node->type;

```

The reason the code works is that a non initialized variable, or object property, is set to `NULL`. In your case, the control statement is really executing the following code, when the node is being created.

```
  if (($user->uid != NULL) && !user_access("view other's posts")) {
    return NODE_ACCESS_DENY;
  }

```

Since `$user->uid` is never `NULL`, that is the reason why the code work the same, even if it raises a PHP warning.

To avoid the warning message, it is enough to execute code similar to the following one.

```
 function mymodule_node_access( $node, $op, $account) {
   if (($op == 'view') && ($node->type == "myCustomType") && ($user->uid != $node->uid)) {
     return user_access("view other's posts") ? NODE_ACCESS_ALLOW : NODE_ACCESS_DENY;
   }

   // Returning nothing from this function would have the same effect.
   return NODE_ACCESS_IGNORE;
 }

```

I changed the code because I think that what you are trying to do is the following:

* When the content type is myCustomType, the user is viewing a node created by another user, and the user who is watching the node has the *view other's posts* permission, allow that user to see the node
* When the content type is myCustomType, the user is viewing a node created by another user, and the user who is watching the node doesn't have the *view other's posts* permission, don't allow that user to see the node

What your code is doing is:

* When the content type is myCustomType, the user is viewing/editing/deleting a node created by another user, and the user who is acting on the node doesn't have the *view other's posts* permission, don't allow that user to do anything on that node the node
* In the other cases, let the other modules decide about the access permission

What I notice is that:

* Despite the permission is "view other's posts," it is applied even when the currently logged-in user is doing something else than viewing the node
* In the case the currently logged-in user has the *view other's posts* permission and is doing something on the node created by somebody else, it lets other modules decide the user's permission to access the node

If the permission is really about any operation done on a node, then it should be renamed, or the code should use more than one permission. The latter is what the Node module does, since for every content type there are a permission to create a node of that content type, to edit nodes of that content type, and to delete nodes of that content type.
> 0 votes

---
Tags: nodes, users
---


title: Posting from Drupal to WordPress

text:
# Question
Title: Posting from Drupal to WordPress
Basically I'm looking for a module/tool/mechanism that I could use to post to a WordPress install from my Drupal install. Ideally this would be filtered per post type and on/off per post. My scenario. I've got a custom post type in my Drupal site which I post to frequently. Sometimes (depending on the post) I'd like to to post to WordPress also, without the hassle of having to login to another platform. Apparently there was this module: https://drupal.org/project/wp\_publish

But it seems is not ported to D7. Any knows anything else?

Many thanks

PS: Its not a migration. Some posts will only go to D7, and some will be posted on D7 and WP. PPS: Both sites have very different objectives and only share some content, so no need for a joint solution/migration/etc.

# Answer
> 0 votes
Now nothing about wp, but in drupal you will have to fire the event when the node is saved and your form field, "save into wp" is active.

Basically I'd do this with hook node api. Use case "save", check then the field and then fire the function or api which allows you to save the content into wp

# Answer
> 0 votes
The solution I have is actually the other way around. For the Dupal only articles you should post to Drupal but for the Wordpress and Drupal articles, post those to Wordpress, you should allow wordpress to create an RSS feed then Drupal can consume that feed and create content on the Drupal site automagically using the feeds module

---
Tags: 7
---


title: User Management Question

text:
# Question
Title: User Management Question
I realize the title of the post probably made everyone roll their eyes...but bear with me...please.

I need some very advanced user management where some users can be assigned as the admin of a group that can add users to that group, make sub groups and assign admins to it to add users...all the users need to have permissions to add edit and view some info that will be part of a large module I am creating...but unique to each user/subuser.

I think Organic groups, but I don't need, or want the content management/viewing aspects, just strictly user management and permissions, but permissions being restricted only to allowed permissions within my specific module...not system wide permissions...

I am looking for a slimmer solution than Organic groups, if possible.

Thoughts? Thanks for any input.

# Answer
What I am seeing here is an entity with a bunch of other entity reference fields. This followed by a bunch of access permission settings.

> some users can be assigned as the admin of a group that can add users to that group

Create a "group" entity that has 2 entity references fields (multivalue) one for users and one for admins. Each referencing the users and the admins who can have privileges.

> make sub groups and assign admins to it to add users...

Add another entity reference field to reference the same group entity type as the parent

> all the users need to have permissions to add edit and view some info that will be part of a large module I am creating...but unique to each user/subuser.

You would just need to play around the access control for that particular entity using a module like https://drupal.org/project/content\_access or other ACL modules
> 0 votes

---
Tags: users
---


# Question
Title: Is there a way to let every user can choose (e.g. on registration) whether their field is private or public?
I have an address field for every user on my website. Now, not everyone is happy with having his address visible to other users. I'm currently using field\_permissions to control the visibility of the single fields. Is it possible to let the user decide which visibility he chooses (without code)?

# Answer
> 2 votes
Field permissions is role based, so I think it's not good choice to work with for this certain scenario. You can simple add another field to indicate whether others can see value of the field.

Then you can use hook\_field\_prepare\_view to hide selected field value or try to find better hook.

If you want to have more advance solution you can create your own field type with two inputs: text field (value) and checkbox (value private or public).

You can use Field Permissions for higher level of access control too.

# Answer
> 5 votes
If you want to do this without writing any custom code, you could use Panels.

Create a boolean field, *Show my address publicly*, and add it to the user profile.

Then override the user profile display with Panels. Add all of the fields that you want to display, including the address field. Then, add a *Visibility rule* to the address field and set the condition to be *Show my address publicly == TRUE*.

This is a bit complicated to set up if toggling the display of the address is all you want to do, but Panels offers a lot of flexibility (without writing code) that could be used for other things, too.

---
Tags: 7, entities, users
---