title: Issue with db_query related to date

text:
# Question
Title: Issue with db_query related to date
I am using created date of ubercart order to compare with filter selected values of date.

created date is in timestamp with time. Where as filter selected values it is just date and if try to convert the date to timestamp, its not fetching accurate results as per filtered dates.

I have attached the image for clear understanding.

I have used this as query:

`$query = $query->condition('uc.created',array($from_timestamp,$to_timestamp),'BETWEEN');`

Any suggestions ? Thanks in advance.

# Answer
> 0 votes
Instead of using different select boxes for month, date and year, you could use date\_popup type.

```
$form['start'] = array(
    '#title' => t('Arrive'),
    '#type' => 'date_popup',
    '#default_value' => 'YYYY-MM-DD 00:00:00',
    '#date_year_range' => '0:+3',
    '#size' => 12,
    '#required' => true,
  );

```

Which comes with time field, so you will have the timestamp. Thats it, now you can compare the timestamp input to the database value.

---
Tags: 7, ubercart, datetime, database
---


title: Commerce Kickstart won't install

text:
# Question
Title: Commerce Kickstart won't install
Running latest versions of Drupal, modules and Commerce Kickstart with Ubuntu, 4 GB RAM Low Free Hard Drive Space, Swap file 2installs50 MB

I have read the posted how to installs but it still won't install. I have only 1 GB of free space but I'm not sure that is the problem. I suspect Kickstart unpacks itself and installs all at once, but I do not know. Any suggestions?

# Answer
> 1 votes
Commerce Kickstart is a profile of Drupal and so you just have to select commerce kickstart radio button during your installation of Drupal. After selecting this, Drupal will start installing default products and all. Download Commerce Kickstart and install it same as you install Drupal.

# Answer
> 0 votes
Commerce Kickstart has drupal core installed and so you dont need to install drupal core. You should directly install commerce kickstart.

The commerce Kickstart has the drupal core.

---
Tags: commerce
---


# Question
Title: Drupal 7 how can I alter page content generated with module?
I have one module:

```
function MYMODULE_menu() {
    $items = array();
    $items['mymodule'] = array(
      'title' => t('My Module'),
      'page callback' => 'MYMODULE_view',
      'access arguments' => array('access content'),
      'page arguments' => array(1),
      'type' => MENU_NORMAL_ITEM,
    );

    return $items;
}
function MYMODULE_view() {
   return array(
        '#theme' => 'my_module_theme',
        '#variable' => 'some variable'
    );
}

```

In the other module I want to alter this content to change the theme and add some variables. How can I do it?

# Answer
You can change the variables of the page content implementing the template\_preprocess\_page() function in your module or theme. As of Clive's comment, I want to update that you can preferably use hook\_page\_alter(), which is called earlier than preprocess function.

```
function YOURMODULE_preprocess_page(&$variables) {
  // Do your changes here
  // If have Devel module installed
  // You can use dpm() function to print the contents of $variables array.
  // dpm($variables)
}

```

or

```
function YOURMODULE_page_alter(&$page) {
  // Do your changes here
  // If have Devel module installed
  // You can use dpm() function to print the contents of $variables array.
  // dpm($page)
}

```

Additional Reference:

> A page callback should return a render array, as should hook\_block\_view()'s $block\['content'\]. This allows your module and other modules to treat the content as data for as long as possible in the page generation process.
> 3 votes

# Answer
You can use module\_load\_include($type, $module, $name = NULL) to include other module;s content.

> $type: The include file's type (file extension).
>
> $module: The module to which the include file belongs.
>
> $name: (optional) The base file name (without the $type extension). If omitted, $module is used; i.e., resulting in "$module.$type" by default.
> 0 votes

# Answer
If you want to alter your menu link item you can use hook\_menu\_alter(&$items) function and change your 'page callback' with it. E.g:

```
function myAnotherModule_menu_alter(&$items) {
  $items['mymodule']['page callback'] = 'MYMODULE_another_view';
}

function MYMODULE_another_view() {
  return array(
    '#theme' => 'my_module_another_theme',
    '#variable' => 'some variable'
  );
}

```

p.s// Don't forget to flush your cache after implementing the hook
> 0 votes

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


# Question
Title: Drupal 7 Commons 3 Vs Drupal Core + Commons modules
I read Drupal Commons 3 and Original Drupal Core Updates and I wonder what the difference between installing the Drupal Commons 7 distributions and installing Drupal 7 plus the Drupal Commons modules available freely on Drupal.org is.

It seems to be safer to use Drupal core and the modules, and not to rely on entire distro updates.

# Answer
Commons 2.x really had a lot of customizations in the install profile, deploying a well organized social network, but when i installed Commons 3.x, i had a sense of "hey, does it really customized anything?", that seems to be your feeling too.

I don't know the roadmap of the project, but it seems a little "naked" in this first version, compared to what they had inside the last Commons 2.x version.

For a project starting now, with what Commons 3.0 has to offer in the install profile(they can improve it, but if you install now, the newer versions of it will not came to you by just upgrading the modules), i think that what you're proposing could be a good thing, because my experience with Commons 2.x updates were really painful just to get some more views and panels improvements(and had to deal with so many Feature overrides), so it could be easier if YOU mantain your own profile, maybe creating one or using the Minimal or Standard themselves.
> 3 votes

# Answer
Recently I had to work on a project, based on Commons v3 (the distribution itself).

My personal observations:

-Some functions have different functionality.

-Generally, less documentation.

-Organic groups module: different functionality.

-Bug with Rules module ;) (Contributed Rules are not visible if you edit them).

For some functionalities we had to tweak Commons core functions (to revert to normal Drupal behaviour).

At the project evaluation we (the team) concluded we shouldn't have used Commons, but normal Drupal core + Commons modules.

That was my humble opinion.
> 2 votes

---
Tags: 7
---


# Question
Title: How to fetch the existing value of a form field in the form?
I have a minimal form with a single field to add an image to an entity and a save button. I have used `managed_file` to add the image.

After adding the image from form the image gets saved in db.

Next time the user opens the form, it shows blank field and after adding a value current one gets replaced. What I want to do is user should see the existing value of the field when reopening the form.

How do I do this?

\[Edit\]:

Code for my form is:

```
// Form Definition
function custom_profile_form($form, &$form_state){
  $form = array();
  $form['picture'] = array(
    '#title' => t('File'),
    '#type' => 'managed_file',
    '#description' => t('The uploaded file will be processed.'),
  );

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

  return $form;
}

// Form Validation
function custom_profile_form_validate(&$form, &$form_state) {
  $file = file_save_upload('picture');
  $file->status = FILE_STATUS_PERMANENT;
  $uploaded = file_save($file);
  $upl = file_move($uploaded, "public://");
  $form_state['storage']['fid'] = $upl->fid;
}

// Form Submission
function custom_profile_form_submit(&$form, &$form_state) {
    global $user;
    $user1 = user_load($user->uid);
    $file = file_load($form_state['storage']['fid']);
    $edit = array(
      'picture' => $file,
    );
    user_save($user1, $edit);
}

```

# Answer
> 0 votes
You can use `#default_value` attribute of the `managed_file` to show the existing value of the field.

You can get the value of `fid` from database and set value into `#default_value`.

Example:

```
$form['picture'] = array(
  '#title' => t('Image'),
  '#type' => 'managed_file',
  '#description' => '',
  '#default_value' => 1, //fid from database
  '#upload_location' => 'public://image_example_images/',
);

```

---
Tags: forms, files
---


# Question
Title: Disable Ubercart download limits accumulation
By default the Ubercart module, accumulate the download limit of a file if this one is purchased twice. How can i disable this ?. I just want to notify the user that he already have privilege to download the file and prevent him from downloading it again.

# Answer
Set the download limit as **Unlimited**, then at the next time user click on add to cart button, then check this product is he already checkout or not (for this you can use order table). If it is already purchased by that user, then you can redirect him separate page or you can display a message about the same.
> 0 votes

---
Tags: ubercart, files
---


title: Contextual links for node blocks

text:
# Question
Title: Contextual links for node blocks
I have the Nodeblock and the Contextual links modules installed. They work fine, but I want to add the "Edit node" link in the contextual links for node blocks. For views, there is a "Edit view" link, but not for nodes. Is there a way to do that, maybe with a preprocess block function?

# Answer
> 0 votes
Ok, it looks like you have to hover the actual body of the block to see those links. It doesn't display them if you hover just the title.

# Answer
> 0 votes
You could add contextual link with a little piece of code very easily.

You have to use `block_contextual_links_view_alter` hook to add a link to a block.

```
function my_module_block_contextual_links_view_alter(&$element, &$items) {

            $element['#links']['edit_f_block'] = array(
            'title' => 'Change Content',
            'href' => url('admin/config/front/block', array('absolute' => TRUE)),
            );

}

```

This adds to all blocks, you should probably check which block it is and also if element is a block. See this post for a detailed understanding.

# Answer
> 0 votes
Try the Custom Contextual Links module. Here is an excerpt about it from the module's project page:

> The Custom Contextual Links module allows you to add your own links to the contextual drop down widgets of blocks and nodes.
>
> Contextual links are really great for quick access to settings pages within your Drupal install. They cut down the time required to click through the sometimes cumbersome Drupal administrative navigation. However, the links displayed in the contextual widget need to be defined through a module. This is where CCL comes in. This module allows you to add and manage custom links through a UI that will be displayed in the contextual widgets.

---
Tags: 6, views
---


# Question
Title: Panel pane visibility based on user entity reference
I have a content type called 'company' with an entity reference field called 'company\_managers' referencing users who will be allowed to add and edit other content types relating to this company.

The company node is displayed using panels. What I am struggling with is to create a visibility rule which will only show a panel-pane if the logged in user is referenced in the entity field 'company\_managers' this will allow me to show panel panes specific to users in the 'company\_managers' field.

So the psudo logic for the visibility rule would be: Check if logged in user is contained in 'company\_managers' If yes show panel-pane if no dont show pane.

This seems such a simple use case that i dont want to create custom code it must be achievable 'out the box' I just cant seem to get to the answer. So after two days of researching am asking for help.

NOTE: have spoofed this behavior using the visibility rule content manager and manually selecting a user on this site. All I would need is to put in the logged in user but I dont think you can put in dynamic variables or tokens.

Help much appreciated.

# Answer
> 0 votes
Ok figured this out. On the relevant panel pane used:

> Add New Rule:
>
> Select PHP Code:

Then put in the following:

```
foreach( $contexts['argument_entity_id:node_1']->data->field_managers['und'] as $key => $value) { $array []=  $value['target_id']; }
return in_array($contexts['logged-in-user']->data->uid ,$array);

```

Commentary: This piece of code loops through my entity reference field called field\_managers on this node which references users and creates an array of user IDS.

```
foreach( $contexts['argument_entity_id:node_1']->data->field_managers['und'] as $key => $value) { $array []=  $value['target_id']; }

```

This line returns true if the logged-in-user ID is part of the array created by the code above. Uses the `in_array` php function.

```
return in_array($contexts['logged-in-user']->data->uid ,$array);

```

The following discussion was useful to finding the solution listed above. https://drupal.org/node/1198282

NOTE: in the above example if you replace field\_managers with the name of your user entity reference field that should be the only alteration you will need to make this work for you.

---
Tags: panels
---


# Question
Title: How to remove Submission information from webfrom module
I am using webform module and when I get an email from a user it is displayed with this information:

Submitted on

Submitted by user:

Submitted values are:

I don't want to this information I just want to display form information only .

# Answer
> 3 votes
Follow these steps to modify the email content, which comes to you on webform submission :

* Login to the system by Admin credentials.
* Go to webform page.
* Click the **Webform** tab.
* Click the **E-Mails** tab inside **Webform** tab.
* Click **Edit** in Operation column infront of email address set by you for mail.
* Find **E-mail template** & edit the content which goes to the email address set by you.

Check it as you are done.

---
Tags: 7
---


# Question
Title: theme_image_style() doesn't output what is expected
I have a module that doesn't seems to work correctly, so I dived into its code, and there is something that I don't understand:

The module does something like this: (I replaced the 'path' key with an hardcoded value to show the problem)

```
$params = array(
    'style_name' => $presetname,
    //'path' => $image_url,
    'path' => "public://images/image.jpg",
    'attributes' => $attributes,
    );

```

Then $param is sent to the theme\_image\_style() hook

```
$img = theme('image_style', $params);

```

The problem is that if i dump the output of theme\_image\_style():

```
dpm( $img);

```

then i get

```
<img typeof="foaf:Image" src="http://mysite.local/sites/default/files/styles//public/images/image.jpg?itok=qZxUAGIS" alt="" data-thmr="thmr_99 thmr_100" />

```

In **admin/config/media/file-system**, my public path is set as: *sites/default/files*

I should have:

```
src="http://mysite.local/sites/default/files/images/image.jpg

```

instead of:

```
src="http://mysite.local/sites/default/files/styles//public/images/image.jpg

```

Why does the theme function add 'styles//public' and where could I remove this?

Thanx in advance for your help

# Answer
`Drupal 7` provide `Image style` functionality which allow administrator to set predefined size and can apply `image style` to any image in site.

> Using image styles you can scale, crop, resize, rotate and desaturate images without affecting the original image. By default three sizes are defined: 'thumbnail,' 'medium', and 'large'. The thumbnail style, for example, is shown with the teaser for image posts and when browsing image galleries.

In your code, you have defined `$img = theme('image_style', $params);` which mean that you are applying `image style` to your image.

When we apply `image style` to any image, it will create a new `image` in `styles/[stylename]/public` directory and does not affect the `original` image source.

There is no `stylename` in your `http://mysite.local/sites/default/files/styles//public/images/image.jpg` url after `style` part of url, so I guess `$presetname` is not properly defined in your code.

You can try below exammple:

```
$params = array(
    'style_name' => 'thumbnail',
    //'path' => $image_url,
    'path' => "public://images/image.jpg",
    'attributes' => $attributes,
    );
$img = theme('image_style', $params);

```
> 2 votes

---
Tags: theming, media, uri
---


# Question
Title: Saving date field programmatically on node, but not on profile
I'm saving some date field on the code both on node and profile entity. I'm success on saving it for nodes, but when I try to save for profile2 entity, using the same chunck of code, no data is saved.

I'm doing this to nodes (after creating a new node with entity API):

```
// Creating a node and an entity wrapper
$entity = entity_create('node', $values);
$ewrapper = entity_metadata_wrapper('node', $entity);
// Saving the date field
$entity->field_date[LANGUAGE_NONE][0] = array(
   'value' => strtotime($date),
   'timezone' => date_default_timezone(),
   'timezone_db' => date_default_timezone(),
   'date_type' => 'datestamp'
 );
//Saving the node
$ewrapper->save();

```

And almost the same way with profiles:

```
//Creating a profile2 'info' bundle
$profile_info = profile2_create(array('type' => 'info', 'uid' => $user->uid));
// Trying to save the date field, same way as above
$profile_info->field_date[LANGUAGE_NONE][0] = array(
   'value' => strtotime($mydate),
   'timezone' => date_default_timezone(),
   'timezone_db' => date_default_timezone(),
   'date_type' => 'datestamp'
 );
// Saving the profile
profile2_save($profile_info);

```

If someone knows what is happening I'd appreciate!

# Answer
> 1 votes
This might or might not fix your problem but since you're using entity metadata wrappers, you should use them fully:

```
$profile = profile2_create(...);
$profile_wrapper = entity_metadata_wrapper('profile2', $profile);
$profile_wrapper->field_date = array(...);
$profile_wrapper->save();

```

The above snippet can also be used with nodes, just replacing the creation & wrapper instantiation.

Also, if you're using a single timezone, you can safely omit it and just specify the actual timestamp value. You should probably omit the 'date\_type' key too, that's inferred by the field config and could be causing issues.

**In fact, you should just do:** `$profile_wrapper->field_date = 123456; // (timestamp)`

Tested locally and it works!

You shouldn't use LANGUAGE\_NONE or \[0\] indices because not only might it break i18n if you're translating fields but it's also not very robust.

---
Tags: datetime, users, entities
---


# Question
Title: Drupal Commerce - Out of Stock, customer clicks to notify store owner to order more
When a product is out of stock, the store owner wants customers to have the ability to pre-order, without paying. Similar to stock notify, but the store owner will manually email back customers once the stock arrives. Something like'This product is out of stock, notify us, and we will order it in for you within 1 week.'

So it needs to collect: customer email and product SKU. As many customers will be non-registered users, what would be the best way of capturing this data, and emailing it to the store owner?

I was thinking flags/rules module, or do you think a custom module would be simpler?

Thanks in advance.

# Answer
> 1 votes
There are two similar kind of sandbox module for this particular functionality.

One was started by me - Commerce Stock Notify

Another by itamar - Commerce Stocklist.

Both can be starting point for further development. As I left doing anything else for this as he started it before me, but my module do what you want except mail template which I was supposed to do later.

But now I think, I will spend some time on it & try to release stable soon :)

---
Tags: commerce
---


# Question
Title: How can I use stemmer with Search API Solr but show non-stemmed results in the autocomplete form?
I'm trying to use the Greek stemmer with Apache Solr. If I edit the schema.xml and add the lines:

```
    <filter class="solr.GreekLowerCaseFilterFactory"/>
    <filter class="solr.GreekStemFilterFactory"/>

```

in both analyzers (index and query) of the text fieldType, the stemming works without problems and proper results are being returned. However, the suggestions that are created both in the facets and in the autocomplete form, include the stemmed version of the various keywords. I suppose that this makes sense from a developer's point of view, but the stems that are produced have no actual meaning in Greek.

I did a lot of research (I'm not a Solr expert but I'm starting to learn the basic stuff due to this issue) and I'm hitting a wall. I tried to use many variations of the solution that is described in the question: "How to index fulltext fields with and without stemming" but I can't get solr to copy the fields that I'm interested in, into the dynamic fields that I create (I can see the dynamic fields in the solr interface but no content is copied to them). I even tried to use the filter only in the query analyzer and only in the index analyzer (you can guess how that went).

Any ideas on how I can get this to work properly?

# Answer
> 0 votes
This is not a "best practice" answer but it might help you get an acceptable result (at least till you figure out how to solve this):

* Enable just the GreekLowerCaseFilterFactory in your schema.xml (not the stemmer).
* Use the NGramFilterFactory to get partial results in your keywords. You can find information on how to do this here.

---
Tags: 7, search
---


# Question
Title: Facet API : How to change some behaviors like having input radio instead of checkbox
I need to change some default behavior from the facet API.

I am searching for documentation about the hook from the Facet API module, but I have not found anything for now, except a very good tutorial about Apache Solr and Facet API.

I downloaded the Facet API bonus module because I thought it would help me.

There are some very good features like **Rewrite facet items via callback function**, but it seems it only works for the markup; I can't change the input.

```
function custom_facet_facet_items_alter(&$build, &$settings) {
  dsm($build);
  dsm($settings);
  if ($settings->facet == "field_produit_dev_durable") {
    foreach($build as $key => $item) {
      $build[$key]["#markup"] = drupal_strtoupper($item["#markup"]);
    }
  }
}

```

I tried to use the Devel modutle o see the content of the variables **build**, and **setting**, but there is nothing interesting for me.

So I need two things

* Understand how to change the checkbox input
* Understand how to remove the count number aside the Yes or No

I made my module and use this, but weirdly it doesn't remove the number.

```
$build[$key]["#markup"] = drupal_strtoupper($item["#markup"]);

```

I used the fist tutorial I linked at the beginning of my post, but I found a problem I don't understand.

When I used my code on two different facets I got an error:

> An illegal choice has been detected. Please contact the site administrator.

My code is the same code shown in this article, but I replace the select field with a radio field. I think there is a conflict between the two form, when I validate.

# Answer
> 2 votes
What you're doing to change the markup should just *work*, here's a working example I have from a project that does just that:

```
function foo_facet_items_alter(&$build, &$settings) {
  if ($settings->facet === 'my_facet') {
    foreach($build as $key => $item) {
      $build[$key]["#markup"] = drupal_ucfirst($item["#markup"]);
    }
  }
}

```

I can confirm that it works as expected.

As far as switching the select for a radio, the error you get is pretty common and you're probably not removing/adding extra Form API options that aren't allowed for one of the types.

Radio buttons behave a bit different than selects, you might not be able to just switch the #type and have it work, if this is still relevant, please post the code you're using to alter that form... thanks!

# Answer
> -2 votes
On this page you find a paragraph about creating a custom facet api widget:

http://www.trellon.com/content/blog/apachesolr-and-facetapi

---
Tags: 7, search
---


# Question
Title: Migrating compound data structures from XML
How would you migrate a complex data structure in XML format, such as:

```
<products>
  <product>
    <name>Product 1</name>
    <price>3.99</price>
    <colour-options>
      <colour>red</colour>
      <colour>blue></colour>
    <colour-options>
  </product>
</products>

```

How would you migrate data in this format, into a content type? I'm guessing that the best way would be using the Migrate module.

# Answer
> 2 votes
Migrate can help you with this.

You can extend XMLMigration and use MigrateSourceXML.

I have a partial stack exchange data import which uses this with code on github.

# Answer
> 1 votes
I don't think that Migrate can help you on that case. I think you should give a look into Feeds and other modules helper.

If you can find a submodule that will help you parse your XML, you can easier create your own with the great API that Feeds provide.

---
Tags: migrations
---


title: Form theming with templates

text:
# Question
Title: Form theming with templates
Please could someone explain why the following doesn't work?

This is in the form build:

```
$form['#theme'] = 'some_form';

```

Here's the hook\_theme function:

```
function MYMODULE_theme($existing, $type, $theme, $path) {
    return array(
      'some_form' => array(
        'template' => 'some-form',
        'variables' => array('form' => NULL),
      ),
    );
}

```

The template (some-form.tpl.php):

```
<div id="some-form">
<?php print render($form); ?>
</div>

```

You can see the wrapper markup from the template file but the form is not being output.

# Answer
Since you're attaching the `#theme` to an element, you need to user `render element` in your theme declaration in place of `variables`:

```
function MYMODULE_theme($existing, $type, $theme, $path) {
  return array(
    'some_form' => array(
      'template' => 'some-form',
      'render element' => 'form'
    ),
  );
}

```

After you clear the caches your template should start being used for that form.

See `hook_theme()` for more information.

Just another thought, if your template file is as trivial as just wrapping the form in a tag you can use the `#prefix` and `#suffix` properties on the `$form` object instead of using a theme at all:

```
$form['#prefix'] = '<div id="some-form">';
$form['#suffix'] = '</div>';

```
> 5 votes

# Answer
Can you try to insert at the beginning of your TEMPLATE file.

```
<?php
  echo render( $form['form_id']);
  echo render( $form['form_build_id']);
  echo render( $form['form_token']);
  echo render( $form['options']['status']);
?>

```
> 0 votes

---
Tags: 7, theming, forms
---


# Question
Title: "Add link" attempt for a Menu yields 500 error
I have tested with fresh installs of Commerce Kickstart down to version 2.6, the error happened. I even disabled all modules related to the Menu module or with menu in the name, no luck. I also disabled and then enabled the Menu module, no luck. However, I tested version 1.19 and it did no yield this error.

# Answer
Change MYSQL max\_allow\_packet\_size.

Incase you are on MAMP you can add `--max_allowed_packet=32M to /Applications/mamp/bin/startMysql.sh` and restart MAMP.
> 0 votes

---
Tags: routes, commerce
---


# Question
Title: Content type with multiple different flavours
I want to create content type (document) with title, comment and file attachment (PDF or doc). I don't want to create different content types (for each document type form, policy, abuse etc..) because if i need to add/remove/change field in it it's need to be repeated on all content types. I'm thinking about taxonomy but I'm not sure.

What's the best solution for one content type with multiple different "flavours"?

# Answer
> 3 votes
You can use taxonomy to categorize the content. If you want categorize the content like form, policy, abuse etc... create a taxonomy vocabulary name as **Document Type** then add form, policy, abuse etc... as terms in it. Then Add a term reference field(in D7) in manage field settings. And also you can use Conditional Fields for display fields according to the document type.

# Answer
> 0 votes
An alternate method of accomplishing this result would be to use Panels, and use taxonomy (or some other field) to display or hide parts of the panel, which may include fields or related views, as appropriate.

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


title: Where does PEAR install Drush?

text:
# Question
Title: Where does PEAR install Drush?
I installed Drush using the PEAR option mentioned on the Drush project page, but I can't find the location of where it was installed.

Does anybody know the default installation location?

Specifically, I can't find the location of the drush.rc.php file to edit and add multiple sites to.

# Answer
On Unix or OS X, you can use `which drush` to learn the location. On Windows, it is `where drush` from the command line.
> 13 votes

# Answer
See the file examples/example.drushrc.php for instructions on where to put your drushrc.php configuration files. $HOME/.drush is a good location.

The `drush status` command will show you your active drushrc.php files, but it will not help you until you have created the file for the first time.
> 5 votes

# Answer
I have installed drush using pear as described here http://drupal.org/project/drush

```
pear channel-discover pear.drush.org
pear install drush/drush

```

Once installed, drush is can be founded here

```
/usr/lib/php/pear/drush

```
> 4 votes

# Answer
The drush site alias command gives more complete information about where pear has put drush files. CD to the directory of your site, and:

drush site-alias @self --full --with-optional

```
$aliases["pkus"] = array (
  'root' => '/Users/tstermitz/Sites/pkus',
  'uri' => 'http://Sites',
  '#name' => 'pkus',
  'path-aliases' =>
  array (
    '%drush' => '/usr/local/pear/share/pear/drush',
    '%site' => 'sites/Sites/',
  ),
  '#file' => '/Users/tstermitz/.drush/aliases.drushrc.php',
);

```
> 4 votes

# Answer
Type `drush status` and check for "Drush configuration" in the output. That should be the path to drush.
> 3 votes

# Answer
If you are in a Linux based system, then you can run the following command:

```
cat `which drush` | grep -A1 "# Build the path to drush.php." | grep "SCRIPT"

```

You should get something that gets like:

```
/usr/share/php/drush/drush.php

```

Your configuration files should be (in this case) in `/usr/share/php/drush`.

This command simply looks at the drush command currently being sourced by your path, searches the executable file for the path to the drush.php file.

This command should work regardless of how drush was installed provided drush is in your $PATH. If you don't know what a $PATH environment is, all you need to know for now is that DRUSH is in your path if you can type `drush` into the terminal and it will return something like:

```
Execute a drush command. Run `drush help [command]` to view command-specific help.
Run `drush topic` to read even more documentation...

```
> 3 votes

# Answer
I used `pear` to install `drush` and sources are located on my Unix machine in `/usr/share/php/drush`

`which` or `where` commands will only give you the location of the execution file?

PEAR Version: 1.9.4
Drush version: 5.7
> 2 votes

# Answer
On my MAMP setup, it is in /Applications/MAMP/bin/php/php5.3.14/lib/php/drush

I am not positive, but I probably installed it with pear.
> 1 votes

# Answer
I too got lost a bit after installing Drush on CentOS 6.4 via PEAR. Here was my solution:

```
cat `which drush` | grep SCRIPT_PATH -m1

```

After installation, `which drush` will return the path to the drush shell script, which is a readable text file. The SCRIPT\_PATH variable in this shell script contains a hardcoded path to the drush.php file. In the directory where this file is located the rest of the downloaded drush library resides.

Example:

```
cat `which drush` | grep SCRIPT_PATH -m1
SCRIPT_PATH=/usr/share/pear/drush/drush.php
ls /usr/share/pear/drush
classes        docs               drush_logo-black.png  includes  README.txt
commands       drush.complete.sh  drush.php             lib       tests
composer.json  drush.info         examples

```

This worked for drush version 6.0.
> 1 votes

# Answer
Pear creates the drush files in the pear/share/pear directory within your pear installation. You choose the pear install location(s) when you first install pear. Use "pear config-show" to see all these settings.

So, if you set pear to install its binaries in `/Users/local/pear/bin` (a pretty good choice!) then that's where running "pear install drush/drush" would put the drush directory.

A good choice might be: `/Users/local/pear/bin` . Then it is simple to link that directory to your preferred bin directory like so:

```
sudo ln -fs /Users/local/pear/bin/drush /usr/local/bin/drush

```

I'm on OS X using MAMP, so I also needed to add the alias in my .bash\_profile:

```
alias drush='/Applications/MAMP/bin/php/php5.4.10/bin/php /usr/local/bin/drush/drush.php'

```

Now the "which drush" command works for me.

(You should probably install pear in `/usr/local/pear` and the pear executables in `/usr/local/bin` ).
> 1 votes

---
Tags: drush
---


# Question
Title: How do I add captcha validation in my D6 html content type form?
in our **Drupal6** site, one of the previous developers created a html form inside of one of the content types, so in the body of the content type, there is thml form code. Users click submit and the values from the fields within that form are sent off via a url in the "

This method is being used in several places. We want to add captcha to these older forms.

Going forward, we are using the webforms module and adding the captcha module to add a bit of security, but for these older html injected forms, I am not sure how to incorporate captcha.

I've added the captcha library, added the public key code in with the php code, captcha block appears on my page, but where i'm stuck is how to add the validation and private key for captcha.

In reading, it saids this validation code should be added on the other end. This is not possible because the other end is a separate company that just takes our info/data.

The form action tag is like this https://wallacesales/main/memberstat/?......the rest of the url grabs the data from the fields so my question, on my end, in my D6 content type that uses html to create the form, how do I validate the captcha, if incorrect, tell user so they can reenter - if correct, then send it on to the above url

**Here is an example** In content type the following html code resides to create the form. I have added the captcha php that you see. **So in this same form, how do I validate the captcha and then send the field values to the url you see in the form**

```
<!DOCTYPE html><html>
<body>
<h3>Send e-mail to someone@example.com:</h3>
<form action="https://wallacesales/main/memberstat/?…." method="post" enctype="text/plain">
Name:<br>
<input type="text" name="name" value="your name"><br>
E-mail:<br>
<input type="text" name="mail" value="your email"><br>
Comment:<br>
<input type="text" name="comment" value="your comment" size="50"><br><br>
<?php
          require_once('sites/all/libraries/recaptchalib.php');
          $publickey = "lkjadkfj897d9s09dskdjfk09d9d9d";
          echo recaptcha_get_html($publickey);
        ?>
<input type="submit" value="Send"><input type="reset" value="Reset">
</form>
</body></html>

```

# Answer
To me I see two solutions you could take.

One - you could client side validate using javascript.

Two - Two step the submit process. Change your form action to Submit to captcha installed on your site then submit to the url in the form.
> 0 votes

---
Tags: captcha
---


# Question
Title: is there supposed to be a default folder in sites/default?
Just noticed I have a default folder in my sites/default folder so that I have sites/default/files and sites/default/default/files

Found out-
The node with audio file upload is HIDING the file as protection from third party download.That is why only occurring with that particular content type.

# Answer
> 2 votes
It depends what you mean by 'supposed to'.

Drupal core doesn't place that folder there, no. But that doesn't mean that someone/something else hasn't. You'd have to give us that information, we couldn't possibly know.

What I will say is that no module should be writing to that path unless you've explicitly told it to, and if you have your permissions set up correctly, then the web server won't have been responsible for creating the folder.

Again, though, impossible to say from here.

# Answer
> 2 votes
A sites/default/default/\* structure is certainly a-typical of a standard install.

A possible source for this odd behavior is accidentally configuring your Drupal installation's public or private files directories that way.

It's not necessarily wrong, but it could be an indicator of misbehaving modules. If module code introduced the extra default directory it could be possible the same module is ignoring other expected/appropriate methods to handle files.

---
Tags: subsites
---


title: How to apply patches on Pantheon?

text:
# Question
Title: How to apply patches on Pantheon?
This is specifically a question about Pantheon best-practice workflow, which I'm new to.

I run from a Win7 machine and do not have a full dev environment set up locally: it's just too much hassle to get Windows to play usefully and smoothly as a dev space behind my hosted \*nix worlds. So, I am in the habit of developing online.

With Pantheon there is no shell access, but there is git and drush.

I don't use git because the workflow there asssumes that I want to move something off of my local repository up to Pantheon (eg, if I have a local working environment I would apply the patch, then push the patched code to my Pantheon dev), but this is not my usecase.

Using drush seems like an option, but I can't figure out how/if applying a patch is supported.

So...

How to patch a contrib module on Pantheon given no local dev environment?

# Answer
> 4 votes
I'm not sure what you mean by moving something off of your local, but I really think your best bet is to use git and push the patch up, even if you don't have a local environment set up. You don't need a local server or database running, you're just altering code in the repo.

1. clone Pantheon dev environment locally
2. patch -p1 \< name\_of.patch
3. commit and push

You could edit the files manually using the SFTP mode, but I wouldn't recommend that.

Using Git with Pantheon

---
Tags: drush, version-control
---


# Question
Title: a single field from reference entity causing memory error
I have a field in my articles content type that is an entity reference to a people type. Editors can select the "author" from the list. This is all working great. We are using panels to display the article, so I have some view blocks to display some of the related information. When trying to display the author information, I get an out of memory error once I've included this one particular field. So, in narrowing it down, when creating the view, all fields from the referenced entity display fine if this field is not included. Once I add this field, the view preview gets the error as well. The strange thing is that this field is not a duplicate field from the article type. I tried changing the view format to show content instead of fields - same error. I also tried rendered entity - same error. I'm not sure what other steps I can use to track down and fix the issue with this one field.

# Answer
> 0 votes
Should anyone come across this, I had failed to mention that it was an image field. The problem what the image style that I had used. I have the imagecache\_actions module for the aspect switcher functionality. Somehow the style I was using had the circular reference. I had to copy another style to that style in features in order to event edit the style. Then I was able to recreate the style properly and the problem is fully gone.

---
Tags: entities
---


title: extraneous css file request generated

text:
# Question
Title: extraneous css file request generated
Something within my site is generating a request to a css file called "none". It is using the path of our theme. Our theme does not have any such style sheet called as part of our stylesheets array.

Our definition:

stylesheets\[all\]\[\] = css/mods.css

stylesheets\[all\]\[\] = css/main.css

request on page load:

/sites/all/themes/our\_bootstrap/css/none

Since there is no such file, a 404 is served for that file. Where can I look to track down what is generating the request?

# Answer
> 0 votes
You may have something like `url('none');` specified for a background (or list image, etc.) in your stylesheets.

---
Tags: theming
---


# Question
Title: Notice: Use of undefined constant FIELD_LOAD_CURRENT
Attempting to use EFQ for the first time. I'm following a couple walk throughs.

I'm trying to query for the content type banner which has an image field:

```
<?php
$query = new EntityFieldQuery;
$result = $query
  ->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'banner')
  ->propertyCondition('status', 1)
  ->execute();

```

But after doing so the result of this is an error:

`Notice: Use of undefined constant FIELD_LOAD_CURRENT`

What is the cause of this particular error?

# Answer
> 0 votes
Discovered that this happens when you're executing this particular function outside of drupal being bootstrapped.

Source: https://drupal.org/node/1286964

---
Tags: 7
---


# Question
Title: Need a simple Google Maps solution; lost in the labyrinth of modules
First of all, let me just state that I don't care which version of Drupal I'd have to use (6 or 7). I have experience with both versions I just didn't need to work with Google Maps till now. The requirements are pretty basic (from what I understand):

1) Have a node for every company that I want to add in the map

2) In the node edit form I would like to add an address and have it added in a custom google map (or maybe copy-paste the link of a google map location)

3) Have a search function to find the nearest company for a given location

There are like tons of different modules out there, and I would like to be pointed to the right direction instead of looking through 15+ different modules just to finally realize that I need to write a custom module for myself.

Thanks in advance.

# Answer
> 35 votes
I have created a Drupal feature that implements this using OpenLayers ( See http://drupal.org/project/ol\_locator ) or you can use the following walk-through to set up your own.

1. Download and enable the following Modules:
2. Enable sub-modules:

* Geofield Map 7.x-1.0-alpha5
    * Views UI 7.x-3.0-rc1
    * OpenLayers UI 7.x-2.0-alpha2
    * OpenLayers Views 7.x-2.0-alpha2
3. Go to `admin/structure/types/add` and create new content type called "`Location`"
4. Go to `admin/structure/types/manage/location/fields` and add the following fields:

* Label: Address \> Field name: address \> Field type: Postal address \> Widget: Dynamic address form
5. Select which available countries you would prefer from the list. Leave blank to allow all of them.
6. Check off "Address form (country-specific)"

* Note: The countries and their associated fields are handled by the Addressfield module. If you do not see your country or if it does not have the appropriate fields you need to file an issue with that module http://drupal.org/project/addressfield (Check to see if there is an issue in the queue about your missing country first before posting)
7. Label: Geofield \> Field name: geofield \> Field type: Geofield \> Widget: Geocode from another field
8. Go to `admin/structure/types/manage/ol_locator_location/display` and change the `Default` display for Geofield:

* Label: Hidden \> Format: OpenLayers
9. Click on gear icon and select the following:

* OpenLayers Preset: Geofield Formater Map \> Data options: Use full geometry
10. Go to `admin/structure/openlayers/layers/settings` and set the following:

* Google Maps API version: v3.2
11. Let's test to see if the Geocoding is working by creating a Test Location

* When creating a test content type, make sure you are using a well established address. If Google doesn't know about your address, then neither will your new site.
12. Go to `admin/structure/views/add` and create a new view with the following information

* View name: Proximity Search \> Description: Displays geocoded locations on a dynamic map for users to do proximity searches. \> Show: Content of type: Location sorted by: Unsorted \> Continue & edit
13. Add the following fields and keep their default values, except where noted:

1. *Content: Title* \> Check off Create a label: *"Title"*
    2. *Content: Address* (Address)
    3. *Content: Geofield* (Geofield) \> Exclude from display
    4. *Proximity: Distance* (Distance)
14. Add the following **Filter Criteria** to the existing:

* *Content: Published* (Yes) and
    * *Content: Type* (= Location)
    * *Proximity: Great-circle* (exposed) \> Expose this filter to visitors, to allow them to change it \> Label: Proximity \> add "10" to Value field \> Unlock unit of measurement \> Unlock location
15. **Header** \> Global:Text area \> Display even if view has no result

* *"Find a location near you. You can search using your city, province/state or a postal/zip code."*
16. **No results behavior** \> Global: Text area and add the following:

* *"Sorry, no results found.
1.) Verify the accuracy of your postal/zip code
2.) Check the spelling of your city, province or state
3.) Increase the proximity distance"*
17. **Submit button text**: Search
18. Add new display: "*OpenLayers Data Overlay*"
19. **Format**:

* Settings \> Apply this openlayers (override) \> Map Data Sources: WKT \> WKT Field: Geofield \> Description Field \> \> Apply (this display)
20. Save the view
21. Go to `admin/structure/openlayers/maps`
22. Clone the default map
23. General information \> Name: location\_map . Title: Location Map \> Map Description: This is the default location map.
24. Layer & styles \> Overlay layers (select the view we just created) Locations "Enabled" "Activated" Do the same for Placeholder for Geofield Formatter
25. Behaviours \> Pop Up (have to come back and *"Select layer to apply popups to."* later) \> Zoom to Layer *"Select layer to zoom to when the map is loaded"* \> Point Zoom Level : 20 **\******
26. Save the map
27. Go back to the view we just created

* `admin/structure/views/view/proximity_search/edit`
28. Add display *"Page"*

* Path: `/locator`
    * Format: OpenLayers Map \> Apply (this display) \> Map: Locations Map (The one we just created in OpenLayers) \> Apply
29. Save the view (We should now see our map in the preview pane at the bottom of our view, with any test content
30. Add display: *"attachment"*

* Format: Table \> Apply (this display)
    * Attach to: Page
    * Inherit exposed filters: Yes
    * Remove the Header \> Global: Text area \> Apply (this display)
    * Items to display: Display a specified number of items | 5 items
    * Inherit pager: Yes
    * Render pager: Yes
31. Save View
32. Behaviours \> Pop Up \> Layers \> proximity\_search\_openlayers\_1 (The views Openlayers map we just created)
33. Zoom to Layer \> Zooms to the extent of a given layer on map loading. \> `proximity_search_openlayers_1`
34. Return back to `admin/structure/types/manage/location/display` \> click gear icon and change *Open Layers Preset* to the *Location Map* that we just created \> Update \> Save

Voila! Done

# Answer
> 2 votes
Use simple google maps module. It is very simple and easy to use.

---
Tags: 7, google-maps
---


# Question
Title: How to show preview of entered values in previous steps in webform with multiple steps
I am configuring a "**Webform**". In my webform field components, I am using "**page break**" in order to create Multiple step forms.

But I like to show the entered value in previous steps in current step.

for example, if user is in step 2, I want to print entered value of step 1 bellow the form. or if user is in step 3, I like to print the entered value of step 2 and step 1 bellow the form.

is there any module to run this scenario? or I have to program a custom module?

Please guide me.

Thanks a lot

# Answer
You can try Webform Bonus Pack module, it have the option to preview webform fields before submission.

> which allows you to add a summary component directly to your form in the same way you would add a textfield or any other component type. Install that module and add a summary field to your form, selecting which fields you would like to include in the summary. If you would like it on its own page, make sure to add a pagebreak component first.

also take a look at this https://drupal.org/node/435232
> 1 votes

---
Tags: webforms, forms
---


# Question
Title: Is there a module for google maps in drupal 7?
On a site that I am building (using drupal 7), there is a feature that I need to include that I can't seem to find; Google maps. I am looking for two things;

1: something that will allow you to put in your home address, and it will give you directions to a preset location

2: something that will allow you to imbed a map of the surrounding area of a preset destination by stating the location in a CCK

do either of these exist? if so, where can I find them?

I need it to look like this:
where instead of an image, the map is actually an embedded google map.

# Answer
There is the GMap Module module, but there is just a development snapshot, for Drupal 7.
> 5 votes

# Answer
There is the Simple Google Maps module.

> This module is about the simplest way to get a Google Map, and/or a link to a Google Map, displayed with your content. It provides a field formatter for Drupal 7 text fields. With this formatter, you can enter a single-line address that Google Maps would recognize into a plain text field, such as: 100 Madison Ave, New York, NY.
> And then on your Manage Display screen (or in Views field setup), you can choose to display the field with an embedded iframe Google Map, a link to a Google Maps map, or both; with or without the original address text.
> -1 votes

---
Tags: 7, entities, google-maps
---


title: Bulk updating image alt and title tags

text:
# Question
Title: Bulk updating image alt and title tags
I'm trying to bulk update image alt and title tags for about 1,500 images on a site.

I've tried a number of methods and I will outline them all. I've also tried with the media module enabled and disabled. I think my issue is something to do with not being able to save the changes through to the image itself.

The relevant part of my image array (the image field - called "field\_meeme\_image" can hold mulitple values) is as follows:

```
 [field_meeme_image] => Array (
        [und] => Array (
              [0] => Array ( [fid] => 131 [alt] => Test [title] => [width] => 500

```

Currently I am trying Devel Execute PHP to just change one node as follows:

```
$node = node_load(63);
$node->log = 'Test2';
$node->field_meeme_image[$node->language][0]['title'] = $node->title;
node_save($node);

```

Using \['und'\]\[0\]\['title'\] doesn't work either

I also tried using both methods from this post

And neither one worked for me. I have confirmed that VBO is working. For example if I simply set:

```
$entity->log = $entity->title;
node_save($entity);

```

The log gets changed fine but if I try:

```
$entity->field_meeme_image[$entity->language][0]['title'] = $entity->title;
$entity->field_meeme_image['und'][0]['title'] = $entity->title;
node_save($entity);

```

The change doesn't get saved.

I've even tried using a preprocess function in my template (I've tried everything I can think of)

```
function footheme_preprocess_node(&$vars) {
    $node = $vars['node'];
    $user = $vars['user'];
    if ($node->type == 'meeme') {
    if (in_array('administrator', array_values($user->roles))) {
        $node->field_meeme_image[$node->language][0]['alt'] = $node->title;
        node_save($node);
        }
    }

```

This makes the change in the $node array but it doesn't actually show up as the alt tag for the image and it doesn't save.

Any help would be massively appreciated. Cheers.

# Answer
> 1 votes
Hope my below answer helps you.

if you are using Image field, then Image field provides an option to insert "Alt" and "Title" tags. When enabled, you can insert the values in the fields. When you are saving if yourself, custom save, then the image field array needs to look something like below.

```
[field_image] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [alt] => alt text
                        [title] => title text
                        [fid] => 12
                        [display] => 1
                        [width] => 220
                        [height] => 169
                        [description] =>
                        [upload_button] => Upload
                        [remove_button] => Remove
                        [upload] =>
                    )

            )

    )

```

However, the above is from the node presave, but when tested for empty values, and changing values in node presave, this worked flawless. Try that out, curious to know why It wont work, Should be simple (If I understand this correctly :) )

Now, you also need to see at what point you want to implement it. Node presave, node view or any other point in time.

# Answer
> 0 votes
Okay,

I found out everything should work but I was just trying to do this at a bad time as there is a bug in core that needs to be patched in 7.24

https://drupal.org/node/2066275

Phew that was driving me nuts!

Thanks for all your help

---
Tags: entities, media, views
---


# Question
Title: Prevent anonymous to input a registered email during commerce checkout through Rules?
In Drupal Commerce, how to prompt a warning message and keep it in `checkout` process if an anonymous inputs a registered email? I know there is a `Commerce Checkout Login`, but it is just an AJAX addon.

I believe I can do it through Rules and that's what I did.

* Event: Process checkout pane
* Conditions:
    + Data comparison: \[commerce-order:uid\] == 0
    + NOT Data value is empty: \[commerce-order:mail\]
    + Entity exists by property: User/Email, \[commerce-order:mail\]
* Actions:
    + Show a message on the site: Warning, ...
    + Update checkout status: checkout

In first trial, it seems work well. But the weird thing is, when I change the email field to an unregistered one, I can still spot the warning message generated by `Show a message on the site`. Is there something wrong in my rule setup?

Refer to this Anonymous can use registered email address: intended behavior?.

# Answer
> 2 votes
With @RyanSzrama's suggestion, I pursue a form validation solution. What I finally use is to implement a `hook_commerce_checkout_pane_info_alter`. The following is a simplified code snippet for that.

```
/**
 * Implements hook_commerce_checkout_pane_info_alter
 */
function MYMODULE_commerce_checkout_pane_info_alter(&$checkout_panes) {
  if(isset($checkout_panes['account'])){
    $checkout_panes['account']['callbacks']['checkout_form_validate'] = 'MYMODULE_form_validate';
  }
}

function MYMODULE_form_validate($form, &$form_state, $checkout_pane, $order) {
  if (!user_is_logged_in()) {
    $mail = $form['account']['login']['mail']['#value'];
    $query = sprintf("SELECT COUNT(*) FROM {users} WHERE mail = '%s';", $mail);
    if (db_query($query)->fetchField()) {
      $msg = t('The email address is registered to an account!');
      form_set_error('[account][login][mail]', $msg);
      return FALSE;
    }
  }
  return TRUE;
}

```

Hope that also provides some hint or help to others. For form validation, please refer to Adding validation to commerce pane form.

---
Tags: rules, commerce
---


# Question
Title: How to display menu in view Block in drupal 7
I am creating a website in which i am trying to display the submenu into view block . how can i do this.

menu is Like

A -B-c

D -E-F

I have to display in block view

like This is view block

B C | E F

this have to display in views block using view.

# Answer
> 0 votes
If you use Views 3 then install Views Menu Area module, you can show any menu in the views block.

* Enable the module
* Edit your preferred view
* Click "Add" link in header/footer section
* Check "Global: Menu area" and click "Add and configure footer" button
* Enter label and select the menu you wish to list links from
* Click "Apply" button and save the view

also take a look at Menu Views module.

---
Tags: views, routes
---


# Question
Title: sub directory multisite just redirecting to default after first page
I have a sub directory multisite setup on a sub domain. (locally with mamp everything is running fine), but on my live server, i can only reach the first (home) page of the multisite site, and when going anywhere (q?=user/login), i get directed to the default site.

site is ***dev.mysite.com/www.example.com***

i have softlink in the drupal root - ***www.example.com -\> ./***

in sites.php i have

`$sites = array('dev.mysite.com.www.example.com' => 'example.com',);`

and of course the structure is ***sites/example.com***

nothing like a cookie address in the settings... i dont know what else could be wrong. Using the same htaccess, the default, that was working locally for me.

---

i did notice something interesting that could be a clue. I have a logo image embedded in the page template. (`img src="<?php print base_path().path_to_theme(); ?>/img/logo.png"`)

so locally the source prints as:

`img src="/www.mysite.com/sites/example.com/themes/example/img/logo.png"`

and on the server it looks like

`img src="http://dev.mysite.com/www.example.com/sites/example.com/themes/example/logo.png"`

# Answer
> 0 votes
Incase someone happens upon this... This was a case of mod\_rewrite not being enabled on the new server. :D

# Answer
> 0 votes
Any caching turned on? (varnish/memcache/...)

If using memcache make sure to separate the memory buckets in each site's config.

```
$conf['memcache_key_prefix'] = 'Example_Memcached_Key';

```

---
Tags: multi-sites
---


# Question
Title: Redirect from node page after form submission?
When editing some fields, after I click the save button, I want the page to redirect to a particular page. Is there any module for this requirement?

# Answer
check the module Node save redirect

> This module provides a method of specifying a location to take the user after saving a piece of content. A set of radios buttons are added to the submission vertical tab on the content type edit form. The available options are. Default - Default behaviour Return to Edit page after saving Return to content overview page (assuming the user has access permissions Re-redirect to another location. (any valid drupal path)
> 4 votes

# Answer
Another approach is to simply implement hook\_form\_alter and put this code into it:

```
    function MY_THEME_OR_MODULE_form_alter(&$form, &$form_state, $form_id) {
      // dpm($form_id)
      // dpm($form)
      if($form_id == 'article_node_form') {
        $form['actions']['submit']['#submit'][] = 'my_node_form_submit';
      }
    }

    function my_node_form_submit($form, &$form_state) {
      $form_state['redirect'] = 'MY_URL';
    }

```
> 6 votes

# Answer
You can use rules. Go to admin/config/workflow/rules. Add a new rule \-

react on event = saving new content.

Specify the content type this rule will work on.

Add an action to the rule -

in this case redirect page (under system - page redirect) -

and then add in the url of the redirect or use tokens. Plus rules has the added benefit of being useful for other things than just redirects.
> 4 votes

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


# Question
Title: Show 'submitted by' date in a language different from English
I want to change the "submitted by" field. I want to show the date in another language. When I use views to display dates, the date shown is in the correct language.

When I add this to node.tpl.php, the date is in English.

```
echo date("j F Y", $node->created);

```

What is the correct way in Drupal to show the date like "17 december 1978" when the language set in Drupal is Dutch?

# Answer
You need to format the date correctly using Drupals format\_date() function.

```
    print format_date(time(), 'custom', 'l j F Y');

```

http://api.drupal.org/api/drupal/includes%21common.inc/function/format\_date/7

```
format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL)

```

The $langcode argument is the language code to translate to. Defaults to the language used to display the page.
> 0 votes

# Answer
Month names are not added automatically.

An elegant way to do this is described here:

https://drupal.org/comment/8251325#comment-8251325

```
function monthname_install() {
  $months = array(
    'January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'September',
    'October',
    'November',
    'December',
  );

  $options['context'] = 'Long month name';

  foreach($months as $m) {
    t($m, array(), $options);
  }

  drupal_set_message(t('Month names have been made available for translation. The rest is up to the translation team :-)'));
}

```
> 2 votes

# Answer
The correct function to use is format\_date().

Keep in mind that, when you don't pass the `$langcode` parameter, it uses the language currently set in the global `$language`. If that is not the correct value, you could try using the following code.

```
echo format_date($node->created, 'custom', "j F Y", NULL, $GLOBALS['language_content']->language);

```

`format_date()` translates the strings used for the following format characters: *A*, *a*, *e*, *D*, *l*, *M*, *T*, and *F*. (In other words, the name of the months, and the weekdays are translated.)

The code that translates those formats is the following one.

```
  // Encode markers that should be translated. 'A' becomes '\xEF\AA\xFF'.
  // xEF and xFF are invalid UTF-8 sequences, and we assume they are not in the
  // input string.
  // Paired backslashes are isolated to prevent errors in read-ahead evaluation.
  // The read-ahead expression ensures that A matches, but not \A.
  $format = preg_replace(array('/\\\\\\\\/', '/(?<!\\\\)([AaeDlMTF])/'), array("\xEF\\\\\\\\\xFF", "\xEF\\\\\$1\$1\xFF"), $format);

  // Call date_format().
  $format = date_format($date_time, $format);

  // Pass the langcode to _format_date_callback().
  _format_date_callback(NULL, $langcode);

  // Translate the marked sequences.
  return preg_replace_callback('/\xEF([AaeDlMTF]?)(.*?)\xFF/', '_format_date_callback', $format);

```

`format_date()` wraps the format characters it can translate with two characters that allows `format_date()` to find the replaced string, calls `date_format()`, then translates the strings wrapped with those two characters it added.
The code of \_format\_date\_callback() is then the following one.

```
  // We cache translations to avoid redundant and rather costly calls to t().
  static $cache, $langcode;

  if (!isset($matches)) {
    $langcode = $new_langcode;
    return;
  }

  $code = $matches[1];
  $string = $matches[2];

  if (!isset($cache[$langcode][$code][$string])) {
    $options = array(
      'langcode' => $langcode,
    );

    if ($code == 'F') {
      $options['context'] = 'Long month name';
    }

    if ($code == '') {
      $cache[$langcode][$code][$string] = $string;
    }
    else {
      $cache[$langcode][$code][$string] = t($string, array(), $options);
    }
  }
  return $cache[$langcode][$code][$string];

```

Notice that using `t(date("j F Y", $node->created))` would only work if somebody called `t()` as `t('23 January 2013')`, and made a call for each possible date.
> 1 votes

---
Tags: 7, nodes, datetime
---


# Question
Title: View module diplaying wrong content type extra
I am having a problem with the views module in Drupal. Everytime I add a new content type, views will display an other content type. I have tried different things, but I can't figure it out. Any help will be appreciated.

Here is the link: http://carlosgandara.com

Here is my view settings... Quotes is the only content type that I want to display.

Here is the quote block, but every time I add an other content type. For some reason, it replaces the content with the other content type.

# Answer
> 1 votes
You need to set up a filter - filter by content and choose the content type you want to show or use a contextual filter(advanced settings) to show only the content type you want to show. Right now youre not filtering so your view is set to show all content types.

In the example below I have a relationship of author. I have a contextual filter set up with this relationship so that it will only show content with this relationship and finally i have a filter that only shows content types of the kind flashcard and only the content where the logged in user is the author of the content.

There is a great set of tutorials about views here at nodeone

---
Tags: views, nodes
---


title: Node teasers break my layout

text:
# Question
Title: Node teasers break my layout
Node teasers are breaking my layout by not closing div and span tags.

The nodes are being written using WYSIWYG and CKEditor 3.4.2.6041.

An example of this broken layout is: http://www.energyjustice.net/node?page=2

# Answer
> 1 votes
Most probably `Correct faulty and chopped off HTML` is not checked in the input format used. Goto `admin/config/content/formats` and then look at the format used for this and make sure that it's last, eg:

If this doesn't work, check out How to get teaser break to work with WYSIWYG + CKEDITOR? for more things to look into.

---
Tags: wysiwyg, nodes
---


# Question
Title: Webform - Submit values from Drupal 7 from to external url
I am a self-proclaimed newbie to creating forms in Drupal. I have a form hosted on a Drupal 7 website (using the webform module) and need to submit the form values to an external url. I've been researching this for awhile now and wrote a custom module that uses the webform module to submit externally using hook\_form\_alter and custom submit handler/function (code pasted below).

I've been using the following pages as guides, but I haven't been able to get the form to work: https://drupal.org/node/1357136 Using drupal\_http\_post() to submit to external site: What am I doing wrong?

Can someone let me know if I'm on the right track? Any guidance would be helpful!

```
<?php
function webform_extra_form_alter(&$form, &$form_state, $form_id)
{
   //only want form with nid 1171 to submit externally
   //Note that "webform_client_form_1171" means modify the Webform form for the node with NID "1171". Adjust to match whichever webform node's form you're modifying
   if($form_id == 'webform_client_form_1171')
       {
            $form['#action'] = url('https://[url path to external site]');
            $form['#attributes'] = array('enctype' => "application/x-www-form-urlencoded");
            $form['#submit'][] = 'webform_extra_submit';
       }
}

// Adds a submit handler/function for the app signup form (Webform ID #1171)

function webform_extra_submit($form, &$form_state)
{
     // Changes can be made to the Webform node settings by modifying this variable
    //$form['#node']->webform;

    // Insert values into other database table using same input IDs as external db
    $option['query'] = array(
        $firstName => $form_state['values']['firstName'],
        $lastName => $form_state['values']['lastName'],
        $email => $form_state['values']['email'],
        $name => $form_state['values']['name'],
        $phone => $form_state['values']['phone'],
    );
    $url = url('https://[url path to external site]', $option);
    $form_state['redirect'] = $url;
   //$form['#action'] = url('https:[url path to external site]');
   //$url = 'https://[url path to external site]';
   //$headers = array('Content-Type' => 'application/x-www-form-urlencoded',);
   //$response = drupal_http_request($url, $headers, 'POST', http_build_query($form_state['values'], '', '&'));
}
?>

```

# Answer
In Drupal forms, form\_alter hooks can be used to change almost anything in the form. Additional submit handlers can be handled, validation can be done, elements can be added, etc.

But for all of these to work, Drupal need to be the responsible party in both form build phase and the form submit phase.

When you set `$form['#action'] = url('https://[url path to external site]');`, you are actually removing Drupal from that latter responsibility.

Check the altered form - you will see that the form tag's `action` is set to the external site. When the form is submitted, browser sends all its data to **that external site, and Drupal no longer can validate or perform submit functions in the form**. I think this is the misconception happens.

If you don't want Drupal to validate the form, record the webform submission or do **anything** after the form submission and let the remote site do **everything** for that submission, your code will work just fine. You can remove `$form['#submit'][] = 'webform_extra_submit';` part and the `webform_extra_submit` function itself.

**However,** if you do want to record the submission and submit the data to that remote site as well, you can do it like this:

```
function webform_extra_form_alter(&$form, &$form_state, $form_id)
{
   //only want form with nid 1171 to submit externally
   //Note that "webform_client_form_1171" means modify the Webform form for the node with NID "1171". Adjust to match whichever webform node's form you're modifying
   if($form_id == 'webform_client_form_1171')
       {
            $form['#submit'][] = 'webform_extra_submit';
       }
}

// Adds a submit handler/function for the app signup form (Webform ID #1171)

function webform_extra_submit($form, &$form_state) {

    $options = array();
    // Array keys are matching the key that the remote site accepts. URL encoding will be taken care later.
    $options['data'] = array(
        'firstName' => $form_state['values']['firstName'],
        'lastName' => $form_state['values']['lastName'],
        'email' => $form_state['values']['email'],
        'name' => $form_state['values']['name'],
        'phone' => $form_state['values']['phone'],
    );
    $options['data'] = http_build_query($options['data']);
    $options['method'] => 'POST';
    $url = 'https://[url path to external site]';

    // Put your additional headers here. Cookie can be set as well.
    $headers = array('Content-Type' => 'application/x-www-form-urlencoded');

    $options['headers'] => $headers;

    // Submits data to the remote server from the drupal server. User will remain in the Drupal form submission chain.
    $response = drupal_http_request($url, $options);

}

```
> 17 votes

# Answer
I have been trying to find a way to tackle this problem and I finally found the Webform Remote Post module

> Webform Remote Post is a module that works along the Webform module. It eases the integration between Webforms and other web applications (including systems like Salesforce and Eloqua).

Hope it saves someone hours of looking!
> 4 votes

---
Tags: 7, hooks, webforms, forms
---


# Question
Title: What is efficient way of updating drupal commerce product prices when your on a product display page?
What are some fast ways of updating the product prices for drupal commerce? Right now i have to go into the product list and search for the items I want to change prices on. I know inline entity form solves the issue, but was wondering what other methods are other people doing?

# Answer
> 1 votes
You can make a nice edit contextual links with custom\_contextual\_links module in any view you would like to use this functionality.

# Answer
> 0 votes
I would prefer to use Commerce backoffice module to manage product and order in admin.

> Provides a better experience for stores using nodes as product displays for grouping product variations (commerce\_product entities).
>
> * The node/add screen is now split into two tabs, "Create content" (ordinary node types), and "Create product" (product display node
> types).
> * The products view is now a view of nodes, showing product displays. Contains special exposed filters for filtering by product
> display type, and product display categories.
> * Uses the megarow pattern to provide a "Quick Edit" link in the view, that shows all product variations for that product display,
> right underneath the triggering row. The status and price can be
> modified directly.
> * Modifies the "Content types" screen by adding additional help text for understanding product displays, and adds a column to the table
> that indicates whether the node type is a product display node type\*.
> * Disables the Commerce-provided "Product types" UI, and provides a custom "Product variation types" UI that contains additional help
> text, hides fields that are not used by the Inline Entity Form (help, description for each type), and provides the ability to create a
> matching node type for each created product variation type.

It would provide the quick edit product in product display list in admin.

---
Tags: 7, commerce
---


# Question
Title: Slow "Add another item" with unlimited valued fields
In Drupal 7, when you have node with field which has unlimited values (let's say, image field), "add another item" response time becomes very slow after you added 10 - 20 items. How do you fight this problem? Have you ever encountered this problem?

I created a project, where user can add up to 100 values of an image field which in theory has unlimited values setting. But, after you add a dozen of images, every new click on "Add another item" becomes slower than previous. I know this happens because of the fact, that Drupal rebuilds this field and all its values after each ajax request, so the more values you added the more work Drupal has to do on every "ajax" request, but, actually, this is not quite great thing.

Are there any approaches on how to change/override such a behaviour?

# Answer
> 3 votes
building on the answer by Charlie, I found that it takes about the same amount of time to reload the block if you are adding 1 or 100 items, so here is a trick to add a select list of numbers in the form next to 'add more' so you can choose how many you are adding. This saves a lot of time and is still flexible. Could be wrapped in to a little module

```
<?php
/**
* Implements hook_field_attach_form()
*/
function village_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode){
  $options = array('language' => field_valid_language($langcode));
  // Merge default options.
  $default_options = array(
    'default' => FALSE,
    'deleted' => FALSE,
    'language' => NULL,
  );
  $options += $default_options;
  list(, , $bundle) = entity_extract_ids($entity_type, $entity);
  $instances = _field_invoke_get_instances($entity_type, $bundle, $options);
  // Iterate through the instances.
  $return = array();
  foreach ($instances as $instance) {
    // field_info_field() is not available for deleted fields, so use
    // field_info_field_by_id().
    $field = field_info_field_by_id($instance['field_id']);
    $field_name = $field['field_name'];
    //If we are looking at our field type and specific widget type, and we are multiple entries
    if($field['cardinality'] == FIELD_CARDINALITY_UNLIMITED){
      //Check just in case the button is here, and add another #submit function
      if(isset($form[$field['field_name']]['und']['add_more'])){
        // add a simple select list, this defaults to numb 3
        $form[$field['field_name']]['add_more_number'] = array(
          '#type' => 'select',
          '#title' => t('Add more no.'),
          '#options' => drupal_map_assoc(range(0, 50)),
          '#default_value' => 2,
        );
        $form[$field['field_name']]['und']['add_more']['#submit'][] = 'village_field_add_more_submit';
        $form[$field['field_name']]['und']['add_more']['#value'] = 'Add more rows';
      }
    }
  }
}
function village_field_add_more_submit($form, &$form_state){
  $button = $form_state['triggering_element'];
  // Go one level up in the form, to the widgets container.
  $element = drupal_array_get_nested_value($form, array_slice($button['#array_parents'], 0, -1));
  $field_name = $element['#field_name'];
  $langcode = $element['#language'];
  $parents = $element['#field_parents'];
  // Alter the number of widgets to show. items_count = 0 means 1.
  $field_state = field_form_get_state($parents, $field_name, $langcode, $form_state);
  //get the number from the select
  $numbtoadd = $form[$field_name]['add_more_number']['#value'];
  if($numbtoadd){
    $field_state['items_count'] += $numbtoadd;
    field_form_set_state($parents, $field_name, $langcode, $form_state, $field_state);
    $form_state['rebuild'] = TRUE;
  }
}
?>

```

I also posted the suggestion on Drupal.org at https://drupal.org/node/1394184#comment-8252701 where the op had a similar issue.

# Answer
> 2 votes
It's blowback from the nature of the form API and how it makes the entire `$form` and `$form_state` available back on the server. This is a cool thing for a lot of reasons, although I agree that it can be quite annoying from a performance perspective. Some stats on an Ubuntu 12.04 server running Apache2 with PHP-FPM:

* I added 30 items to a file field, adding and uploading 1 at a time, and the total time for the upload + server response + javascript insertion of the new element went from 414 milliseconds, increasing on each successive upload by anywhere from 0-20 milliseconds, ending up at 800 milliseconds for trip number 30.
* I clicked "Add another item" for an unlimited text field 100 times, and the total time went from 337 milliseconds up to 1.3 seconds. If my form was more complex, these numbers would only increase.

In `$form_state['fields']['your_field_name']['und']` exists a property called `items_count`. This is used to calculate the number of field widgets that should be displayed for a given field. I would recommend you use `hook_field_attach_form()` to alter the `$form_state` *before* the field's widget is constructed and set the field's `items_count` property to be a larger number, thus giving you the number of fields you need right away. The user will still be able to add more items. It would be up to you to find a better way to hide the extra items from making the form 10 pages long; perhaps a div with `overflow: scroll;` could work. Anyway, this may be a starting point for you to find something that allows your workflow to go faster:

```
function mymodule_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode) {
  $form_state['field']['field_my_field'][$langcode]['items_count'] = 100;
}

```

**Edit:** The sample code is missing some logic to ensure it only runs for the appropriate form and won't allow you to 'add another item'. I will revise this when I have a better working example locally.

---
Tags: 7, ajax, entities
---


# Question
Title: Change image style in view depending on node type
I have a view which shows a list of nodes of two different node types. Both have an image field.

Now I would like to have the image style to be different for the two node types.

I can't use `hook_views_pre_render()`, because then I would change the image style for all the nodes displayed. I also think I can't use a tpl.php file, because then I already have a URL, and can't retrieve another image style URL based on that that URL. Another option would be to define the image field twice in the view, and hide one depending on the node type, but I wouldn't know how to do that.

I'm using Drupal 7.

Any idea I overlooked?

# Answer
> 1 votes
I found a way. A bit hacky I guess, but it does the trick:

In "views-view-field--viewname--viewpage--field-img.tpl.php" put the following code:

```
if ($row->node_type == 'nodetype_with_text') {
  print $output;
}
else {
  $url = image_style_url('imagestyle_for_nodetype_without_text', $row->field_field_img[0]['raw']['uri']);
  $output = preg_replace('/src=".*" *width=".*" *height=".*"/', 'src="'.$url.'"', $output);
  print $output;
}

```

The width and height of the image style could be retrieved, but I think it isn't worth the hassle, the images are resized anyway.

# Answer
> 2 votes
Here is a better way to format your image or check out this post http://drupal.org/node/958726

```
$hero_image = array(
  'style_name' => 'case_study_teaser',
  'path' => $image['uri'],
  'width' => '',
  'height' => '',
  'alt' => $image['alt'],
  'title' => $image['title'],
  );
print theme('image_style',$hero_image);

```

# Answer
> 1 votes
At http://your\_drupal\_site/admin/config/media/image-styles You can add an image style.

When you create the view configure the field under the image style choose the style you created.

# Answer
> 1 votes
You can use this module,

Views Conditional,

Suppose your image field is called field\_my\_image.

Add this image two times AND exclude them from display.

-\>the first instance will display the field with an image style A

-\>the second instance will display the field with an image style B

Add content-\>type as a field AND exclude from display.

While in the view add "Views conditional field".

Add a condition:

if content-type: A{

```
  output First instance of field_my_image

```

}else{

```
  output Second instance of field_my_image

```

}

# Answer
> -1 votes
I would load the field as raw URL, and then load the image style according to the node type. I do believe this is the right way, if no module provides this out of the box.

# Answer
> -2 votes
If you only have a few images and the file size is small you could resize them with css. Not the most elegant solution but a quick one ;-)

---
Tags: 7, views, media
---


# Question
Title: Is it possible to include countdowns in nodes?
I need to include countdowns in nodes of a particular content type

I looked around but couldn't find a countdown module that allows simultaneous active countdowns.

Any ideas, suggestions are welcome

# Answer
> 1 votes
If you are looking for a countdown timer, the Javascript Timer module is what you need.

> The Javascript Timer module provides a timer api that can hook html elements to javascript widget objects. This is useful if you want a moving timer/clock or a widget that updates every second. It comes with widgets for a count-down timer, a count-up timer, and a clock. It uses jQuery and a single event loop to handle as many timers as you need on a single page.

# Answer
> 1 votes
There is jquery\_countdown for general purpose countdown display, though the way you would integrate this depends on what you want to countdown. Using this module it is quite easy to display a countdown based on a node field value. Unfortunately there is no display configuration in the UI. But you could use `hook_node_view()` to add a countdown to a node view like this:

```
$node->content['countdown'] = theme('jquery_countdown', array(
  'id' => 'jquery_countdown-' . $node->nid,
  'options' => array(
    'until' => date("F d, Y g:i:s a", $some_timestamp),
    'format' => 'dHMS',
    'compact' => TRUE,
  ),
));

```

# Answer
> 0 votes
Take a look at JQuery Countdown Timer module.

> This is a lightweight module that provides a block with a jQuery countdown timer. This module uses only jQuery and css and does not use any images.

also check this https://drupal.org/project/countdown

---
Tags: javascript
---


# Question
Title: Load Hierarchical list automatically from Hierarchical select option
I have this Hierarchical taxonomy structure

In content type, I have a taxonomy term reference to this vocabulary using Hierarchical List provided by Hierarchical Select Module. When I want to add the content, I get the default Select Option as:

***(Note the Update Button Above)***. When I hit Update then only I get child terms of **iPhone**

Now, if I want to select **Nokia** instead of **Apple**

I **don't** get that ***Update Button***, or I cannot change it until I refresh the page.

Is there any way the Child list *(list in hierarchy)* would load without hitting Update and change whenever I change the Parent list?

**In short :** I want to get rid of ***Update Button*** and load the Hierarchy List automatically when I change the value in the list.

* If I select Apple, the list in the Apple would show.
* If I select Nokia then Phones under Nokia would show without having to hit Update or Refresh the Page.

# Answer
Instead use Simple hierarchical select module, It actually load child terms without button.

> Simple hierarchical select defines a new form widget for taxonomy fields to select a term by "browsing" through the vocabularies hierarchy. The widget is available in node forms and as Views exposed filter.
> 0 votes

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


title: Superfish menu - Responsive problems

text:
# Question
Title: Superfish menu - Responsive problems
I am building my site using drupal 7 and adaptivetheme.

Before I used superfish module, my main menu was very responsive and works great across all sizes.

Now, I started to use superfish (latest version) for the dropdown in my horizontal main menu, and the menu is not responsive. when I am resizing the window, the right tab of the menu is moving below the menu, instead of the text will get smaller. but, If I resize just a little more it looks like the text is getting smaller for less then a seconed, and than all the horizontal menu (6 tabs) become one dropdown with all the tabs inside. I know that in a very small screen the menu is collapsing to one drop down, but why does it happen in a size of landscape tablet (and even a little bigger)?

How can I make my superfish main menu responsive, and become smaller (like the rest of the site) when the window size is getting smaller?

# Answer
> 6 votes
Get into your Superfish menu block (find from the block admin page: `/admin/structure/block` usually the specific address is: `/admin/structure/block/manage/superfish/1/configure`.

There under "Superfish plugins" -\> "sf-smallscreen" -\> "window width settings" and change the breakpoint value; make it smaller (default is 768 pixels).

---
Tags: theming, navigation
---


# Question
Title: whats the best way to run 2 sites but use same database with same prefix on Drupal 7?
basically i want to create a duplicate of the site and place it in a separate folder to the main site on the same domain, and have both sites use the **same database**, so that if one site changes something it changes on the other site too

basically im gonna be developing on one version of the site, while a designer works on the design and CSS on the other site, but he may also want to edit menu links, blocks etc so he will need to be able to write to the database as admin, once both dev and styling are complete we would copy the theme folder from the designers site in to the dev site and delete the other site and use just one for launch

what would be the best way to do this?

# Answer
It is quite possible in Drupal. Make sure *settings.php* on both the instances are identical (I assume both the instances are hosted on a single server).

However, better way to manage such a scenario is to use version control.
> 2 votes

---
Tags: database
---


# Question
Title: spamspan not working, how to apply patch?
http://drupalcode.org/project/email.git/commitdiff/523cd0d

This is the link to the patch but looking up how to apply a patch I understand the command to use in terminal but I don't understand how to dload the patch?

What type of file is it saved as? and do you apply within modules folder or sites folder?

# Answer
There's nothing too sophisticated about a patch file -- you can copy the commit code in the above link to your clipboard and paste it into a text editor. This link might make it easier:

http://drupalcode.org/project/email.git/patch/523cd0d

Then, you want to save your new file in the same folder as the module file you're trying to patch (based on the path in the actual patch file) and run the patch script as outlined here:

https://drupal.org/patch/apply
> 1 votes

---
Tags: emails
---


# Question
Title: Block display using wildcard, non-greedy
I have a block that I have configured to display "Only on the listed pages"

```
commerce_store/store/*

```

The problem is, it displays not only on the view link, which I want it to, but on the edit and other menu tabs

```
commerce_store/store/1        <-- good
commerce_store/store/1/edit   <-- bad
commerce_store/store/1/sales  <-- bad

```

I've tried switching to PHP code, but this doesn't seem to have any effect whatsoever. I've even changed the code to `var_dump($path); exit;` and it doesn't exit.

**Edit**: This code works, just enclose it in `<?php` and `?>`

```
$path = current_path();
$url_parts = explode('/', $path);
if( $url_parts[0] == 'commerce_store' && $url_parts[1] == 'store' && count($url_parts) == 3 ) {
  return TRUE;
}

```

# Answer
Note that you can use `arg(x)` where `x` is the position in the path starting from 0, so you could do something like this as well:

```
<?php
if (arg(0) . arg(1) == 'commerce_storestore' && !arg(3)) {
  return TRUE;
}
?>

```

You could also use drupal\_match\_path() like so:

```
<?php
if (drupal_match_path(current_path(), "commerce_store/store/*") && !arg(3)) {
  return TRUE;
}
?>

```

Cheers,
> 1 votes

# Answer
Okay, dumb question. I didn't notice that `<?php` and `?>` are required. Funky how they're required in some places and not in others. I guess I'll leave the question up in case the PHP code helps anyone else.
> 0 votes

---
Tags: blocks
---


# Question
Title: Force profile2 field display based on current user's role
I am using the profile2 and the profile2 page modules. I have 2 profiles called user and advanced\_user and corresponding roles associated to them. The advanced\_user has more fields available in his profile.

The problem: when I strip an advanced\_user of his role (aka demote him to user), the extra fields that he previously filled in his profile form remain in his profile page and so is the "Advanced User" title. How can I remove the additional information that was added in the advanced profile?

Note: I wouldn't mind if the extra fields' information was kept stored (so that if I ever "promote" her again she would have the fields already populated) but I definitely want to keep them from showing in the user's profile page.

# Answer
> 0 votes
Try implementing hook\_profile2\_view\_alter(). Below is a sample code:

```
/**
 * Implements hook_profile2_view_alter().
 */
function example_profile2_view_alter(&$build) {
  global $user;
  $rid = <advance_user_role_id>;

  if (!array_key_exists($rid, $user->roles)) {

    $advance_fields = array(); // List of field ID's that should only be displayed
                               // for advance users.

    foreach (element_children($build) as $id) {
      if (in_array($id, $advance_fields)) {
        $build[$id]['#access'] = FALSE;
      }
    }
  }
}

```

---
Tags: 7, users
---


title: Create chapter titles within a view

text:
# Question
Title: Create chapter titles within a view
Hoping for some ideas on how I can create chapter titles to a group of videos that I have on my Drupal 7 site.

Currently each video series is shows with a custom view and grouped with a taxonomy term. I have each video weighted to then display them in the order that I want. Everything works fine. I just need to break them up and create "chapters" to better organize them.

An example of a page on my site can be seen here.

And example of what I am looking for:

```
Heading
-Video 1
-Video 2
-Video 3
Heading
-Video 4
Heading
-Video 5
-Video 6

```

# Answer
What I would is to use another field (assuming that the chapter names are unique) to identify which chapter it is a part of and do a secondary grouping with the field in views.
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to display a author picture in comment form?
As the title, I try to display a user picture IN comment form. But I'm not familiar with Form function. Below is my code and I don't know how to do next?

```
function btmentry_form_comment_form_alter(&$form, &$form_state) {
global $user;
$user_picture = user_load($user->picture);

//What should I do next?

}

```

My purpose is style my comment form as Facebook. Thanks.

# Answer
> 3 votes
I don't think you need to do coding for your requirement. You can take help from this documentation for same - https://drupal.org/node/22271. It says for D7 :

Enable user pictures for Drupal 7

1. Navigate to Configuration \> People \> Account settings.
2. In the Personalization settings, select Enable user pictures.
3. For Picture directory type pictures
4. Under Picture display style, select thumbnail (you can change the size settings
5. Click "Save configuration".

Next, ensure your user pictures display in your theme. These are enabled by default in Bartik, the default theme of Drupal 7 , so you may have to check this with any new theme you add.

1. Go to Appearance and click "Settings" for the theme you have enabled as default.
2. In the Toggle display settings, select User pictures in posts and/or User pictures in comments.
3. Click "Save configuration".

If your theme doesn't support user pictures, then you should look for bartik & apply same structure for TPL.

---
Tags: forms, comments
---


# Question
Title: How to filter views result using the views_php module?
I have 2 integer fields in views , first field is 'field\_code' and second field is 'field\_rank', Finally I want filter views result, with views\_php module. I use this code but it does not work,

```
$math = ($row->field_code / $row->field_rank) * 100;
if ($math < '30') { return TRUE; }

```

Please can someone help me to fix this problem.

# Answer
> 5 votes
It is a Drupal bug that is in active state until date but there are some work-arounds, one of them I am sharing with, if it could help you out. Use `$data` variable to access your fields value because `$row` only gives numbers, which appear to be node ID's (Drupal Bug).

Use the following code I wrote in Global:PHP 'filter code' text area

```
$field_code = $data->_field_data['nid']['entity']->field_code['und']['0']['value'];
$field_rank = $data->_field_data['nid']['entity']->field_rank['und']['0']['value'];

$math = ($field_code / $field_rank) * 100;
if ($math < '30') {
  return TRUE;
  // If you dont want to display the result otherwise use FALSE in place of TRUE
}

```

Use this code as it is in your view. It works perfect; I have tested it.

# Answer
> 1 votes
As I understand, you are facing the problem due to the D7 issue with $row values of returning NID instead of the expected field values. So, check once by printing if you are getting the expected values in the PHP field. If not then you can go for the below approach :

1. Pass the field information through $view object like say, $view-\>RELEVANT\_NAME = $data-\>RELEVANT\_PATH
2. Access these values in the PHP filter and write your conditions there

Hope it helps

---
Tags: 7, views
---


title: User Permission to a Certain Page

text:
# Question
Title: User Permission to a Certain Page
I want to give registered users permission to access, but not edit a certain page. Ideally what I want is this: create a link or a menu item that is only seen and or accessible by certain signed in users. I would like to create a role to give to these people as they sign up, but I have noticed that Drupal is not quite like other content management systems I have used in the past. On a platform such as DotNetNuke you were able to assign a permission for a user to access a web page but not edit it. It appears from what I have seen that you can only add permissions for users to edit the webpage/content of which you give them. Is it possible to give someone access to a page without giving them any administrative privileges? Any modules that could help me out? Thanks!

# Answer
It is correct that Drupal has only a very course access control structure for individual nodes (the basic access control system in Drupal is by content type). For more fine-grained access control than content type, you need to add a node access control module to your site.

There is a page at the Drupal.org wiki giving an overview of node access modules. You may start by reading that and try to find a suitable module. This page also provides a gentle introduction to node access control in Drupal.

One of these modules is Nodeaccess (also suggested by Ursula). It lets you control node access (i.e. view, edit, delete) by user *and* by role.

A simpler alternative is a module named Flexi access. This only let you set up lists of users (Access Control Lists) that indicate type of access (i.e. view, edit, delete) these users shall have. It may be simpler to set up and use than Nodeaccess if you don't need to control access by role.

Disclosure: I am a co-maintainer of Flexi access.
> 1 votes

# Answer
You are looking for the nodeaccess module: http://drupal.org/project/nodeaccess.

Once the module is installed and enabled, you can grant permissions - view, edit, delete, etc. with some granularity to the different roles - types of users (anonymous, authenticated, administrator, or roles you define and name yourself).

Permissions: https://example.com/admin/people/permissions

Menu items are also only visible for users associated with roles that have view permissions.
> 0 votes

# Answer
The way to pass without installing additional modules is to create views page. It has built-in access control by role, permission. And menu item will be hidden.
> 0 votes

---
Tags: nodes, users
---