# Question
Title: How to create global pattern for terms title (not page title)?
I'm trying to override the titles of taxonomy terms. Not the page title, the heading tag at the top of the taxonomy term page.

I found the Taxonomy Title module that created to control the title individually for every term.

> This module was designed to update the heading tag at the top of the taxonomy term page. The contents of this H1 (or sometimes H2) tag are *extremely* important for SEO (Search Engine Optimization).

This module seems good but it doesn't give us the option to set global patterns for taxonomy terms, we can only set titles individually for each term.

There is an issue opened about global pattern but there is no solution presented.

**How can I create global patterns for taxonomy terms?**

**Example** (from the issue):

A real estate company is listing its offerings and each property is tagged with location.

Then for the location vocabulary I could set a pattern "Properties in the \[term\] area".

Note 1: the Page Title module doesn't give us the opportunity I wanted but we can set global patterns for *page title* with that module.

Note 2: It's possible to set global title pattern with the Automatic Nodetitles module for only nodes. I wonder if it is possible to use this kind of module (or piece of code) to set global pattern for taxonomy terms.

# Answer
> 3 votes
As I said above (in the question), there isn't any module for overriding the H1 heading (title).

I could do this as explained here:

1. I copied (and pasted) the page.tpl.php into my theme folder.
2. I renamed it page--vocabulary--\[machine name\].tpl.php

(for me it was: page--vocabulary--cities.tpl.php
3. Opened the template.php file in the theme folder. And added this function:

(I've already had the preprocess\_page function in the template.php file and I didn't add the preprocess\_page function again, I added the if (arg(0) ... part. Don't forget to change the THEME to your theme name.)

```
function THEME_preprocess_page(&$vars) {
  if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
    $term = taxonomy_term_load(arg(2));
    $vars['theme_hook_suggestions'][] = 'page__vocabulary__' . $term->vocabulary_machine_name;
  }
}

```
4. Opened the page--vocabulary--cities.tpl.php file and found that line:

(Your theme's template.php file may be different but the main structure is the same.)

```
<?php if ($title): ?><h1 class="title" id="page-title"><?php print $title; ?> CUSTOM TEXT</h1> <?php endif; ?>

```
5. Cleared all caches.

**Done! It works :)**

*(Note: This solution is per vocabulary solution and if you've got a large amount of vocabularies this solution maybe not very for you.)*

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


# Question
Title: Nested select with Drupals DataBase interface
I have the following SQL query and need to translate it to the drupal API:

```
SELECT
  *,
  (SELECT COUNT(*)
    FROM newsletter
    WHERE email = pupils.email
  ) AS newsletter_flag
FROM
  memberdata.pupils
LEFT JOIN
  memberdata.pupil_profiles
ON
  memberdata.pupils.id = memberdata.pupil_profiles."pupils.id"
WHERE
  pupils.status != 'u'
ORDER BY
  pupils.timestamp DESC
LIMIT 10;

```

Background: There is a table with *pupils* (some basic info including mail adress) and a table *newsletter* containing the email addresses of pupils that registered for the newsletter. I need a list of all pupil with their fields and additionally the field *newsletter\_flag*, indicating if the pupils email adress is in the newsletter table or not. Additionally I need a join to another table with primary foreign key. I've come this far:

```
$query = Database::getConnection('default', 'for_migration')
->select('memberdata.pupils', 'pupils')
->fields('pupils', array('id', 'firstname', 'lastname', 'birthday', 'gender'))
->condition('status', 'u', '!=')
->range(0, 10)
->orderBy('pupils.timestamp', 'DESC');

$alias = $query->leftjoin('newsletter', 'nl', 'pupils.email = nl.email');
$query->addExpression("COUNT($alias.email)", 'newsletter_flag');

```

But it does not what I want (the pupil\_profiles join is still missing of course, but the newsletter flag is the bigger problem I guess). The source database is a PostgreSQL one and the query itself is part of a Migration subclass, in which a MigrateSourceSQL is used as source. Therefore the query needs to be a *SelectQueryInterface*.

# Answer
Ok, figured it out but do not like it:

```
$query = Database::getConnection('default', 'for_migration')
   ->select('memberdata.pupils', 'p')
   ->fields('p', array('id', 'firstname', 'lastname', 'birthday', 'gender'))
   ->condition('status', 'u', '!=')
   ->range(0, 10);
$query->addExpression("(SELECT COUNT(*) FROM newsletter WHERE email = p.email)", 'newsletter_flag');

```

There should be a smoother way for the newsletter\_flag problem.
> 0 votes

---
Tags: migrations, database
---


# Question
Title: views query alter not working when view appears in sidebar
I have a block view, and I want to change my query, to add contextual filter. I made a views query alter but when the view appears in sidebar as block view this function doesn't work.

```
function bpm_views_query_alter(&$view, &$query) {
   if ($view->name == 'single_job' && $view->display_handler->display->id =='block_1' ){
      $nid = _get_job_nid_from_url();
      $query->where[1]['conditions'][2]['value'] = $nid;
   }
}

```

If I add the same block view in page content then views query alter work as expected. The page is created by page callback and this is following code how i add block view in page content

```
$output = views_embed_view('single_job', $display_id = 'block_1', $category);

```

# Answer
> 1 votes
I think you problem is there that $nid not passed correctly,edit your views, instead of your filter, set filter by contextual filter then in your page passed it by contextual filter parameter with

```
$view= views_embed_view('single_job', $display_id = 'block_1', $category);
$view->set_arguments(array($node->nid));
$output = $view->preview();
print $output;

```

not longer need query alter function

```
/*
function bpm_views_query_alter(&$view, &$query) {
  if ($view->name == 'single_job' && $view->display_handler->display->id =='block_1' ){
    $nid = _get_job_nid_from_url();
  $query->where[1]['conditions'][2]['value'] = $nid;
 }
}*/

```

# Answer
> 0 votes
You can get the values from the url with $view-\>args\[0\] or $\_GET\['q'\].

---
Tags: blocks, views
---


# Question
Title: running "drush @remote status" gives "bash: drush: command not found"
I tried to follow solution here: Why does drush say "command not found" when I try to execute remote commands?

But it did not work for me, the url /usr/local/zend/bin does not exists in my hosting provider.

I can't run any remote command from my local, I dould test the connection doing

```
drush @remote ssh

```

and it correctly connects through ssh, so the problem is not in the connection. Please help me with this =( Thanks

# Answer
The other question that you reference answers your question perfectly, except for the fact that Drush is located in a different location on that user's remote system. Since `drush @remote ssh` works for you, type `which drush` on the remote system, to find out where your Drush is located. You are likely to get an answer similar to `/home/USER/.composer/vendor/bin/drush`. You need to insure that the directory `/home/USER/.composer/vendor/bin` is in your PATH. This directory might vary if you did not install Drush using Composer, as recommended in the Drush README.

If `which drush` produces no output at all, this means that you forgot to install Drush on the remote machine. Use composer, following the same instructions you would for your local machine, in the above-referenced README file.

Pay particular attention to the following part of the installation instructions:

> Add Composer's global bin directory to the system PATH (recommended):
>
> ```
> sed -i '1i export PATH="$HOME/.composer/vendor/bin:$PATH"' $HOME/.bashrc
> source $HOME/.bashrc
>
> ```

The 'sed' line shown above adds an `export PATH` statement to the TOP of your .bashrc file. It is important to set your PATH early, because .bashrc exits just a few lines in when running in non-interactive mode on most Linux distributions. Most of the other places you might be tempted to set the PATH (.profile, etc.) are not sourced at all in non-interactive mode. So, if you do not set the PATH in the right place, then Drush will work from an interactive shell (e.g. after `drush @remote ssh`), but most remote Drush commands (e.g. `drush @remote status`) will not.
> 4 votes

---
Tags: 7, drush
---


title: Views: Rewrite Results Broken?

text:
# Question
Title: Views: Rewrite Results Broken?
I've just installed the Views Slideshow Module and gone threw some tutorials to see how it is installed and how it works. Everything works just fine except that Rewrite Result don't work. No Textbox for editing is showing up when I check *Rewrite the output of this field*. I've tried both in Firefox and Chrome to see if there was some JavaScript thingy but it wasn't. Anyone else is having this very annoying problem?

Checked status report and found no errors. Cleared all cache too.

Also tried with some old Views that I've created and it don't work on those either now. I've tried to disable Views Slideshow but no change. So this might be some other issue that occurred before I installed Views Slideshow.

Using D7, Views 3 and Views Slideshow 3.1

EDIT: It turns out that it's all settings that can be done from checkboxes are disabled somehow. I've even re-installed the Views Module but no luck. Don't know what's causing this behavior.

# Answer
> 2 votes
This is a problem that raises it head in some or other form quite regularly. The answer is to change the jQuery version. Use jQuery Update. Set it to 1.7 or 1.8 for admin pages.

---
Tags: views
---


# Question
Title: How to show different Views for the same URL with contextual filters
I have 1 View with contextual filter: /catalog/% % - is taxonomy term and it can be several terms (I use them for Porducts groups) like: Phones, Accesoiries, Tablets, etc. So, when Views get URL with Phones argument it show all its stuff on /catalog/phones page.

Problem is, that I also want to have another Views for Tablets, which should have the same address with contextual filters: /catalog/%. It should show Tablets staff after getting Tablets as arguments.

I can not use only 1 Views for both product categories, because Phones and tablets will have different set of fields to show.

Right now only 1 Views is shown. Second is empty. How to fix it?

# Answer
> 0 votes
This can be done via a zero-coding solution using Page Manager (CTools), Views Content Panes (CTools) and Panels.

1. Delete your current view as we want to re-use its path.
2. Install the three modules.
3. Create a view as follows:

Create a view of type content (nodes) that shows content of your product type. Add a relationship to the 'taxonomy terms on node' and set it to your 'catalog' vocabulary.

Add a contextual filter of 'Taxonomy term name.' It will automatically select the relationship of 'term'. Hide the view when the filter value is not available.

Now add two 'Content pane' displays to this view.

**Content pane 1:** This is the view that will show **tablets only**. Click on 'edit' next to argument input in 'Pane setting' column. Select 'from context', and for the required context, select Taxonomy term-\>name.

Just above 'argument input' is a setting for 'Category'. Set it to something meaningful, such as 'View Panes - Catalog'.

This first pane will show 'tablets', so add fields that you want on this pane, and change its display Name to Tablets.

**Content pane 2:** Duplicate pane 1 exactly. It will show **all the other terms**, so alter the fields and display name.

4. Add a custom page at `admin/structure/pages/add`

Set it's path to : `catalog/%term`

During the wizard setup it will ask you to define the arguments (%term in our case). Set it to term name and limit to vocabulary 'Catalog' so that it looks like this:

Basically what we have done is to tell page manager what the argument `%term` represents, namely a taxonomy term that belongs to vocabulary 'catalog'.

When selecting a panel layout select single column.

Eventually you will get to the screen where you can add content to the single panel. Add content, and select 'View Panes - Catalog' (remember we defined a meaningful name for the category of our view panes. This is it). This will further display two content panes. You select the content pane you added first, ie the one to show tablets.

Now we need to limit it to only show for terms of type tablet. Select selection rules for your variant, and 'Taxonomy Term.'

Set it up so that it looks like this:

Now update and save your page and you can test that for the path that has an argument of tablet, it will show the view.

Now you need to add a second variant to this panel. To do this you can clone the first variant.

And all that remains now is for you to change this second panel variant slightly.

First, you need to remove the selection rule. As this is a catch-all variant, we do not need a selection rule at all.

Second, you need to remove the view from the panel pane single-column content, and replace it with the second pane that you added.

Now update and save. Make sure that the two variants are in the order: top variant has a selection rule and shows first view pane, and the second variant does not have a selection rule and shows second view pane. Page Variants are selected from top to bottom, with the first variant that matches being used.

---
Tags: views
---


# Question
Title: how to correctly write drush sql-sycn using drush_invoke_process()
I need to execute a drush command from a custom module, Im using drush\_invoke\_process() but I do not know how to write it correctly

How would you write this command for use with drush\_invoke\_process() ?

```
drush sql-sync @site1 @site2 --tables-list table1,table2,tableN

```

How to write the above command in drush\_invoke\_process() syntax?

Thanks

# Answer
> 2 votes
From your php code:

```
$values = drush_invoke_process('@none', 'sql-sync', array('@site1', '@site2'), array('tables-list' => 'table1,table2,tableN'));

```

`$values` will be an array containing various interesting information about the Drush call. In particular, check `$values['error']` to see if the command succeeded or not.

---
Tags: 7, drush
---


# Question
Title: commerce multicurrency module currency menu selector not switching currency in Shopping cart
I am using commerce\_multicurrency module for multi currency support. This module provide two blocks for switching currency of site. One currency menu selector which give enabled currency as links and another block which give enabled currency as select list. I enabled both of the block in header block of site. When i choose any of the currency from these blocks it switch currency of all the products displayed in pages either through views or any other way.

Selecting currency also switch the currency of the cart page in `<site-url>/cart` but it doesn't switch the currency of shopping cart block placed in header of site. Currency switching in this block is very inconsistent. Sometime it display the selected currency sometime it not. Sometime it show the previous selected currency when i switch any of the currency. This currency switching behavior in shopping cart block works fine when i switch currency on `/cart` page. It switch the currency of the cart at both places

1. Total displayed in cart page with individual product price.
2. Total displayed in header shopping cart block.

But on other pages of site this shopping cart block on header doesn't work as expected. I searched for this issue but didn't find any. I googled this issue also searched the module issue queue and https://drupalcommerce.org/discussions

Thanks in advance.

# Answer
Here is answer which finally worked for me.

https://www.drupal.org/node/1853638#comment-9385053
> 0 votes

---
Tags: commerce
---


# Question
Title: How to display the number of images contained in a node using Views?
I have a content type that has an image field (among other fields).
When creating a node, users can upload up to five files.
What i'm trying to do is to display how many images are uploaded in each node when listing node teasers using views ?

Thanks

# Answer
> 0 votes
Install the module: Field Count Formatter

> A very simple module to provide a formatter for all field types. The output is simply a count of the number of items in that field. This is most useful on fields which have multiple values as it will show how many values are in this field.

Then in the teaser display for your content type, add the image field and set the formatter to count.

---
Tags: 7, views
---


title: Disable past dates in date_combo

text:
# Question
Title: Disable past dates in date_combo
Is there a way to disable the past dates in the date pop-up while using the date combo form api? Specifically, I have a date type field in a content type, on which I want to do this.

Help appreciated...

# Answer
> 1 votes
Use hook\_date\_combo\_process\_alter(&$element, &$form\_state, $context).

I have used it in commerce discount module: while adding discount.

Example :

```
  $current_path = current_path();
  if ($current_path == "admin/commerce/store/discounts/add") {
   $element["value"]['#datepicker_options'] = array(
     'minDate' => 0,
   );
   $element["value2"]['#datepicker_options'] = array(
    'minDate' => 0,
   );
  }

```

---
Tags: forms, datetime
---


# Question
Title: How to create a Notification system in D7?
I am new to Drupal and was wondering if there is a module that can serve as a Notification system for logged-in users on my site?

Since my nodes consist mainly of images generated by users, I would like for logged in users to be able to see how many members liked their images, made a comment, followed them, etc.

P.S. I read almost all similar posts here and none of them provided any clear explanation. Pointing to active sites that already use "these module(s)" would be of great help.

Thanks in advance, Milos

# Answer
> 1 votes
In the Drupal community, "notifications" are usually referring to *email* notifications sent to users.

Messages sent to users to indicate "likes", etc. are usually called "messages". So you should probably search for "messages" and "messaging" (instead of "notifications") to locate stuff about *this* type of user interaction.

One of the most popular Drupal modules for messages is **HeartBeat**:

> Heartbeat displays user activity on a website. This module is an API to log activity. The logged data contains message structures, attributes and variables. Once the activity messages exist in the database, they will be parsed and build into activity streams.

However, the maintainer of **Heatbeat** has recently announced:

> This project will be deprecated. The future would be in the module **Message**. It's much smaller and it cannot be compared to heartbeat when it comes to features. However the possibilities as API would be the same.

At the time of writing, **Message** is an API that you can use to build the required flagging and messaging by combining it with other modules in the message stack. As for social messaging functions, you need to add those. The **Heartbeat** API already has all the necessary functionality built-in. Today, it will take much less effort to get something working with **Heartbeat** than with **Message**, but maybe **Message** is still a better option than putting efforts into working with a module about to be depreciated,

---
Tags: 7
---


# Question
Title: Prevent a date from happening in the past
I have a CCK field that is a date. I want to prevent people entering a date that has happend in the past. I know you can set **Years back and forward** and I have set this to *-0:+2* but this just limits the calendar. Any ideas what I can do?

# Answer
Drupal's Form API allows you to add your own validation functions to a form. There is an example for a date field validation function in this forum topic. Documentation is here.
> 3 votes

# Answer
I have been involved on a patch that would add this feature to the JavaScript popup, you can see more on issue queue. Right now there is a working patch, but it's not quite there yet IMO.

You shouldn't rely on the JavaScript alone as that can be circumvented and should add a custom validation like marcvangend describes. This can be done by adding a validation handler and checking the value for the data and comparing it with the current data.
> 2 votes

# Answer
I think, What you are looking for is

1) `hook_date_combo_process_alter(&$element, &$form_state, $context)`

This hook let you alter the calender's element for "date combo" field type.

2) `hook_date_popup_process_alter(&$element, &$form_state, $context)`

This hook let you alter the calender's element for "date popup" field type.

In both the cases, to prevent a user from enter past dates, all you need to do is - define "minDate = 0" inside #datepicker\_options array.
> 0 votes

---
Tags: 7, entities, datetime
---


title: Flagging Referenced Entities

text:
# Question
Title: Flagging Referenced Entities
I have two node types (one is galleries, one is images). The node types are referenced to eachother via entity reference (which is providing a field on the image node which references a gallery).

I want a user to be able to flag one image in a gallery which will become the 'cover' of the gallery. I am attempting to do this from a combination of rules + flags; I have a flag set up which can flag images.

The tricky part here is referencing the image to the gallery entity, and only allowing each gallery to have one flagged image. (i.e. galleries can't have two covers).

The rules part is tricky, and it would be awesome if I could get some assistance.

I am aware that the first step is the 'event'. Once an image is flagged, it should unflag other images that reference that gallery (via trim a flag). Haven't been able to get it set up. Anyone have experience with this? Thanks!

# Answer
This is not a straight-forward flag trim. Trim works on all content in the set of a content type, and I don't see how you can do it on a subset.

This answer uses Views bulk Operations, so please install that. I also assume the flag is global (or if not then only one user flags)

We will create a view that will get the list of images to unflag. Then we will create a rule component that will unflag the images, and lastly we will create a rule that will initiate all of this when an image is flagged.

---

1. Create a view that will fetch the images that belong to a certain gallery and that have been flagged.

To do that, create a view (master display only) on content (node), and filter on content type (image). Add three relationships:

**Relationship 1:** Add a relationship 'Flags: Node flag', include only flagged content, set the flag to the desired flag, and set it to 'Any User'. This will ensure that only flagged images show up.

**Relationship 2:** 'A bridge to the Content entity that is referenced via field\_gallery'. This will bring in the referenced 'gallery'.

**Relationship 3:** This one may seem weird, but bear with me. Add 'A bridge to the Content entity that is referencing Content via field\_gallery', and set its relationship to the previous one, ie 'Content entity referenced from field\_gallery'. This links back to the image type. The reason for this will become apparent in the next step.

Add a contextual filter of 'Content nid' and set its relationship to the third relationship you added above, ie 'Content referencing Content from field\_gallery'. We will pass in an image nid, get the associated gallery, and then get all the associated images belonging to that gallery that are flagged. So now we have our list that we will use in rules.

The last step is to add a new field (the only field we need). Add a field 'Bulk operations: Content'. Do not use a relationship. This will allow us to use the view with rules.

Finally, remove the pager as it is not needed.

Now we need to add a rule component and a rule.

---

2. Create a rule component. Add a new rule component called 'Unflag Image'. It is of plugin type 'Rule'. Add two variables.

**First variable:** Data type -\> node, Label -\> previously flagged image, Machine name -\> prev\_image

**Second variable:** Data type -\> node, Label -\> newly flagged image, Machine name -\> new\_image

Now add a condition: Data comparison. Compare 'prev-image:nid' equal 'new-image:nid' and tick 'Negate'. This will check that the previously flagged image does not equal the newly flagged image.

Add an action: Unlag a node, and set the node to flag as 'prev-image'. Set user on whose behalf to flag as 'site:current-user', and select skip permission check: false.

---

3. Create a Rule. Add a rule that has event: 'A node has been flagged' and select your flag.

There is no condition.

Add an action to the rule: Load a list of entity objects from a VBO View. For its value select the view that you added previously. For the argument select the flagged-node:nid. Leave the provide variables as is.

Add a loop, and select 'entity list' (the provided variable from previous step), and leave defaults for current list item.

Inside the loop, add an action: Component: Rule: Unflag image. This is the component we added earlier. For previously added image, select 'list-item' (provided variable of previous step), and for newly flagged image, select 'flagged node'.

And that is it. You should now debug it as I have not checked it, but the logic is more or less there and you can take it further.
> 0 votes

---
Tags: rules, entities, flags
---


# Question
Title: Users can choose image style on content type?
I want to display image style list in particular content type. Users can choose their image style from the list provided.

Is it possible to achieve this?

# Answer
Hopefully I've understood you properly; I think you're looking for the Formatter Field module:

> The formatter field module provides a mechanism for specifying a formatter and formatter settings to be used for displaying a field, on a per-entity basis. By default, Drupal provides formatters and settings per entity bundle, but in certain situations it is necessary to choose the formatter at the entity level.
>
> For example, say you have a page node with an image field. Normally, you would select an image style as the formatter, and all page nodes would use that same image style. With this module, you can add a formatter field to page nodes, which is hooked up to the image field. Then when the node is created or edited, the image style can be selected per-node.
> 5 votes

# Answer
If you want an user to select an image style when he/she uploads an image, take a look at the Image Style Selector module. The list of image styles that the user can select from is configurable by the website administrator.

The screenshot below shows the (basic) functionality of this module.
> 3 votes

---
Tags: 7, nodes, media
---


# Question
Title: drupal 7 Ubercart recurring fee settings tab is blank
I get an error on my screen There are no payment methods configured for orders with recurring fees, enable one from recurring fee admin settings.

I then go to the link cart/checkout#overlay=admin/store/settings/products/edit/features

Next i try and choose the Reccuring fee settings tab but it is completely blank.

Version of UC Recurring Payments and Subscriptions module is 7.x-2.0-alpha3

I am wondering if down grade will that fix the problem.

# Answer
You may have to enable the module "Recurring - Hosted Gateways". This should be available under section "UBERCART - RECURRING" in the path admin/modules. In my case this is Paypal WPS.

Once the module is enabled you can see the option at admin/store/settings/recurring. You may also need to enable the required payment methods at admin/store/settings/payment.
> 1 votes

# Answer
You can find the configuration under 'admin/store/settings/recurring'
> -2 votes

---
Tags: ubercart
---


# Question
Title: User can't change language after redirection from custom module
I'm using custom module to redirect users from Serbia on Serbian language. So, if user comes from Serbia on front page, in URL will be added '/sr'. The problem is that user can't change the language on front page because it always will be redirected.

Can someone help me to fix this issue and make visitor able to change language on front page?

There is the code of custom module:

```
global $user;
function smart_ip_redirect_init() {

  if(
    // if country is detected
    !empty($_SESSION['smart_ip']['location']['country_code']) &&
    // if is front page and anonymous user
    drupal_is_front_page() && user_is_anonymous()
  ) {
    // load some global variables, language contains information about current language, base_url is base url
    global $language, $base_url;
    // load all active languages
    $languages = language_list();
    // resolve the country code to language, you have to make cases for your needs
    function country_to_language() {
    switch ($_SESSION['smart_ip']['location']['country_code']) {
        case 'RS':
            return 'sr';
        break;

        default:
            return '';
        break;
    }
    }

    // if the URL have no lang parameter
    if(strtoupper(request_uri()) == strtoupper("/")  )
    {
         // does the visitors language exist in our Drupal
      if(array_key_exists(strtolower(country_to_language()), $languages))
      {
        // redirect user to the designated language
        drupal_goto($base_url.'/'.strtolower(country_to_language()));
      }
    }

  }

}

```

# Answer
> 1 votes
Now your code redirect always, and you only want to redirect once. It means you need implement logic similar to the one below:

1. Test `$_SESSION` to see if redirection evaluation took place already. If yes, end.
2. Create element in `$_SESSION`, to mark this session as already evaluated against redirection
3. Decide if you want to redirect or not.
4. Perform redirect if needed.

That way you will run code responsible for redirection once and only once per user session, and that's seems what you want to do.

---
Tags: 7, redirection
---


# Question
Title: How can I have different image size for a content type
I have 3 type of products that I want to put their image in my site. I have define a content type for them. there is a field that I put the image of my products and I've use imagefield crop module to crop my images but the problem is I don't want any specific ratio for my pictures or at least I have 3 define ratio for my images(each for a product). I would appreciate if you tell me how can I set the different image size for my product with just one content type? TNX

Edit: for example I have chosen the "Image with cropping" as a widget of my field in a content type and because in its option I should fill the blank of the "resolution of cropped image" I set 300x300 like this:

Then when I crop my product option it gave me this: for 136x65

After Cropping

or for 170x300

After

And I should decide whether my image is square size or rectangular ??

# Answer
The Image Style Selector module allows you to select a predefined image style and apply it to the uploaded image. In this way when you create a node (or any other fieldable entity), upload an image, you can choose which image style to apply to that image.
> 1 votes

---
Tags: media
---


title: dynamic image style

text:
# Question
Title: dynamic image style
I would like to create a custom content type where the editor can choose his preferred image size.

For example I would have a field\_image\_style with the three options small/large/huge and in my node template I would like to have an if-clause which then dynamically outputs the node's images (which are provided in another field) in the wanted size.

What's the best way to achieve this? Can someone point me in the right direction?

# Answer
1. Create the required three image styles at www.yoursite.com/admin/config/media/image-styles; let say you added three image styles with name as small, large, huge
2. Create your content type
3. Add the file field
4. Add another field (machine name as 'field\_image\_style') of type select with options as key value as small|small, large|large, and huge|huge
5. In your theme template.php add the following code

```
function mytheme_preprocess_node(&$variables) {
  $node = $variables['node'];
  $node->language = isset($node->language) ? $node->language : LANGUAGE_NONE;
  if (!empty($node->field_image_style[$node->language]) {
    // Get image style value, must correspond to image style machine name
    $style = $node->field_image_style[$node->language][0]['value'];
    // First image
    $image = $node->field_images[$node->language][0];
    $variables = array(
      'style_name' => $style,
      'path' => $image['uri'],
      'alt' => $image['alt'],
      'title' => $image['title'],
     );
    $variables['dynamic_image_style'] = theme('image_style',$variables);
  }
}

```
6. In your node.tpl.php put this snippet wherever you want to print the image

```
<?php if ($dynamic_image_style) print $dynamic_image_style; ?>

```

It will be better to have a separate node template for this content type. In order to do that, copy the node.tpl.php to your theme name it node--YOUR-CONTENT-TYPE.tpl.php, and put this snippet wherever you want to print the image.

```
  <?php if ($dynamic_image_style) print $dynamic_image_style; ?>

```
> 1 votes

# Answer
Something like this should help achieve that, e.g in a `node.tpl.php` or assigned to a var in a `hook_preprocess_node` function:

```
$node->language = isset($node->language) ? $node->language : LANGUAGE_NONE;
if (!empty($node->field_image_style[$node->language]) {
  // Get image style value, must correspond to image style machine name
  $style = $node->field_image_style[$node->language][0]['value'];
  // First image
  $image = $node->field_images[$node->language][0];
  $variables = array(
    'style_name' => $style,
    'path' => $image['uri'],
    'alt' => $image['alt'],
    'title' => $image['title'],
    );
  print theme('image_style',$variables);
}

```
> 2 votes

# Answer
Imagecache Proportions

> This module provides a CCK formatter for imagefields that allows the user to select between three different imagecache presets depending on the proportions of the original image. So you can use this module for altering the display proportions of a image field or similar in the display field screen, in Views, etc.

**or**

Using Insert module you can choose the image styles during upload.

> Insert is a utility that makes inserting images and links to files into text areas or WYSIWYGs much easier. It adds a simple JavaScript-based button to FileField and ImageField widgets. When used with ImageField and ImageCache, images may be inserted into text areas with a specific ImageCache preset.
> 2 votes

# Answer
The module Image Style Selector does exactly what you are asking. The site administrator can select the image styles that the content editor can apply to the recently uploaded image.

The screenshot below shows the basic functionality.
> 0 votes

---
Tags: nodes, media
---


# Question
Title: Tab field formatter for Entity Reference field?
I'm looking for similar module to this: Reference Tabs but to work with the Entity Reference module

The Reference Tabs module works with the References module, I need the same functionallity but for the Entity Reference module

If there is no module for this, then: can I get this with the Field formatter settings using UI jquery tabs?

# Answer
> 1 votes
You can find this functionality in my sandbox.

https://www.drupal.org/sandbox/legolasbo/2383347

Please submit issues if you find any.

---
Tags: entities
---


# Question
Title: Searching for a user details (including custom fields) in People Administration Page
I want to search people on my people page in admin. I searched around and found this great plugin :-

User search to People Admin \- This helps me search user through their email, usernames perfectly.

The only problem is that I want to search users through additional User fields I added later into the admin. As an example, each person has a Full Name as a custom field but this module is unable to search through it.

Any idea how I can achieve that?

Thanks

# Answer
> 1 votes
I recommend using Views. With this you can create a searchable, sortable and filterable display using any format you desire, and including any fields you want.

> You need Views if
>
> You like the default front page view, but you find you want to sort it differently. You like the default taxonomy/term view, but you find you want to sort it differently; for example, alphabetically. You use /tracker, but you want to restrict it to posts of a certain type. You like the idea of the 'article' module, but it doesn't display articles the way you like. You want a way to display a block with the 5 most recent posts of some particular type. You want to provide 'unread forum posts'. You want a monthly archive similar to the typical Movable Type/Wordpress archives that displays a link to the in the form of "Month, YYYY (X)" where X is the number of posts that month, and displays them in a block. The links lead to a simple list of posts for that month. Views can do a lot more than that, but those are some of the obvious uses of Views.

---
Tags: users, search
---


# Question
Title: Failed opening install.inc' when upgrading Drupal 7.x core with Drush 7.x
I have Drush 7.x installed and when I run 'drush up', on a Drupal 7.x codebase, I get the following error:

```
Drush command terminated abnormally due to an unrecoverable error.
[error]Error: require_once(): Failed opening required '/home/user/public_html/core/includes/install.inc'

```

It seems like Drush 7.x may be looking for Drupal 8.x file structure. How should I be running this command?

# Answer
I managed to get it fixed after tracking the issue in drush 7, this is caused as you said by trying to load install.inc as Drupal 8 folder structure while you have Drupla 7 structure

I simply modified DRUSH\_ROOT/commands/core/core.drush.inc line 1120

```
require_once DRUPAL_ROOT . '/core/includes/install.inc';

```

to be like

```
require_once DRUPAL_ROOT . '/includes/install.inc';

```

I hope this help you.
> 2 votes

---
Tags: 7, drush
---


title: User course listings with contact forms

text:
# Question
Title: User course listings with contact forms
I'm very new to drupal and trying to get my head around how things are setup.

I'm attempting to create a training course listings website where a user can join as a course provider and add listings for upcoming courses. I have this ability sorted but, I'm struggling to find a way for visitors to fill in a contact form attached to the course listing node, which will go into an admin panel for the main administrator. Once approved by the admin an email alert will be sent to the listing's author/course provider and they can go into their own panel to view the message with a link to the course where it was submitted. I have played around with webforms, panels but as far as I can tell all messages get attached to the form and not the node itself. Hope this makes sense :)

If you know of any guides, tutorials on this type of setup or if you could advice in any way that would be great, thanks

# Answer
> 0 votes
FYI - asking for guides and tutorials is off-topic here. If I was to attempt this, I would first try something like this:

* create a content type with the relevant fields you want a prospective user to fill out
* create a hidden field that includes the email address of the course provider
* include another "hidden" field using the Field Permissions module something along the lines of "approved" so that only Admin can access or view this field. This would be a boolean type field
* create a custom View visible only to Admin that shows ONLY that content type, filtered by those where the approved field is false

The Admin can then go through each item, check and set the 'approved' field to true if appropriate

* Create a Rule, based on that content being saved that checks the value of the approved field - if it has changed and is now true, send an email using the hidden email field to the course provider

It's pretty involved, but should work.

Field Permissions

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

Views

> You need Views if
>
> You like the default front page view, but you find you want to sort it differently. You like the default taxonomy/term view, but you find you want to sort it differently; for example, alphabetically. You use /tracker, but you want to restrict it to posts of a certain type. You like the idea of the 'article' module, but it doesn't display articles the way you like. You want a way to display a block with the 5 most recent posts of some particular type. You want to provide 'unread forum posts'. You want a monthly archive similar to the typical Movable Type/Wordpress archives that displays a link to the in the form of "Month, YYYY (X)" where X is the number of posts that month, and displays them in a block. The links lead to a simple list of posts for that month. Views can do a lot more than that, but those are some of the obvious uses of Views.

Rules

> The Rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules). It's a replacement with more features for the trigger module in core and the successor of the Drupal 5 workflow-ng module.

---
Tags: nodes, webforms, panels, emails
---


# Question
Title: Best way of including a View without extra modules as Panels, CTools, Context, etc
I have a View which shows a list of nodes of a certain type. If I don't want to use additional modules as Panels, CTools, Context, etc... which is the faster and better way of including it in a landing page? I have made a new kind of content for the landing page, with its own URL in PathAuto, and in the template.tpl I embed the Views with views\_embed\_view. Is it a good idea? Is it the simplest way of doing it? I have managed to get all working but the method seems very cumbersome and strange.

# Answer
> 1 votes
*views\_embed\_view* is a common method of doing it with highly degree of flexibility. Make sure that the type of the view's display (of the embedded view) is **Embed**. This display type can be made accessible in views UI by enabling it inside view's advanced settings.

# Answer
> 1 votes
probably the most flexible method is to create the View as a block, and then put the block in the appropriate place restricted by content type, url, user, or any other restrictions you wish to impose.

---
Tags: views
---


# Question
Title: Views global text area replacement patterns for multiple values
I have a views block that is listing the similar nodes (based on taxonomy terms).

I want to show some custom text and the taxonomy term field's value(s) on the footer of the block.

I added **Global: Text area** to footer of the views and selected the **Use replacement tokens from the first row option**.

What I want to show is that **My Term's other nodes** and I'm using that for what I wanted:

> \[field\_my\_taxonomy\_term\]'s other nodes.

It works correctly if the field\_my\_taxonomy\_term field has **only one** value but if it has multiple values (multiple terms) it only shows the first taxonomy term value.

## How can I show multiple values on Global: Text area?

---

This is the replacement patterns part of the Global: Text area:

* \[title\] == Content: Title
* \[field\_my\_taxonomy\_term\] == Content: My Term
* %1 == Content: Nid title
* !1 == Content: Nid input
* %2 == Content: Has taxonomy term ID title
* !2 == Content: Has taxonomy term ID input

# Answer
You need to either display as a table, or change the settings to force fields to be included in the View.

When you add a field to Views, you can alter how it is represented, including Rewrite, Style and if it contains multiples, how to display those values.

Adjust the field settings for the field you want and then that should be represented in the replacement pattern further down the chain
> 0 votes

---
Tags: views
---


# Question
Title: Create a view for a specific content(Not for a specific content type!)
I have two content types: *departments* and *teachers*. Every teacher node has an entity reference field which points to the department to which that teacher belongs.

I want to create a view that shows the list of all teachers from the particular department and I want the link of that view to be shown on the department page. So, each department page will have a link of a view page which will show the list of all teachers from that department.

I can create a view for a content type, but how can I create a view for a specific node of a content type (e.g Computer Engg department)?

# Answer
It sounds like you want to put a teacher tab on a node page of type department.

Create a view that shows content (nodes). Filter it to only show teachers. Add a relationship to the department.

Add a contextual filter of nid, and set the relationship (to department) you created on that contextual filter. Hide the view when the filter value is not available, and add validation to it that confirms that it is a node nid belonging to a department.

Add a path to the view: node/%/teachers. Add a menu entry. Set it to menu tab, and give it a title of 'Teachers'.
> 1 votes

---
Tags: 7, views
---


# Question
Title: how to find image style url from themed image
I've a code which theme & print the original image to specific image style.

```
print theme('image_style', array(
  'path' => $node->field_theme_image[$node->language][0]['uri'],
  'style_name' => 'home_theme',
));

```

I don't figure out how to get url of this new theme. I don't need to print the image but I need just url. Please suggest.

# Answer
You need to use the `image_style_url` function instead of `theme`.

```
$path = image_style_url('home_theme', $node->field_theme_image[$node->language][0]['uri']);

```
> 0 votes

---
Tags: 7, theming, media
---


# Question
Title: Which external frameworks does Drupal use, if any?
I'm looking for ways to prepare and ease a transition to Drupal.

My department is planning on completely rebuilding our custom CMS in Drupal. There are 4 members on the team, two programmers. I've been researching ways to ease the learning process, as only our manager is familiar with it and he's not a developer.

My question is this: Is it possible to integrate any of the specific technologies or practices that Drupal uses in generic PHP-based websites? For instance, Drupal 8 will use Twig.

Are there other technologies or plugin components that we can learn and use before we start the process of moving to Drupal?

# Answer
Theme-wise there are a couple of very good base themes that make use of SASS/Compass (and therefore Ruby) such as

(I prefer Omega, having just discovered its power).

There are some good integration modules such as LDAP for single sign on, and loads of third party service integrations from paid services such as MailChimp.

But, when it comes to handling the database and rendering pages, the core system really shines. I'd really recommend learning Drupal's database API because it does an excellent job of defusing potentially unsafe queries and is quite easy to use once you get the hang of it.

\[edit\] Another resource I keep going back to time and again is the form API.
> 1 votes

---
Tags: theming, nodes
---


# Question
Title: Application of patches after core/module updates
What is the recommended way to automate application of patches after updating core or contrib modules? For now, I'm doing this manually but it gets tedious for sites with a large number of modules that need to be patched. There seems to be a myriad of methods one can do this but I was wondering if there is a particular method which is the "industry-standard"?

# Answer
> 1 votes
If you find yourself doing this often then it might be beneficial to use a make file for the project. Then you can have your make file contain all the patches and just rebuild the codebase instead of updating in place.

Also, be sure to mark patches that you are using in production as "Reviewed and tested by community" this will make them more likely to be committed to the next release which will stop you from having to include that patch in the future.

---
Tags: updating, version-control
---


# Question
Title: How can I send an email to site admin and vice-versa when user returns a product using commerce_rma?
I am using the Commerce Return Merchandise Authorization module for handling returns. It is working fine .

But one thing I want that when a user returns an order using commerce\_rma then a notification mail should be triggered to the site admin, and also when the admin accepts user request or declines user request a notification mail should go to the user.

How can I do this ?

# Answer
You could use Rules Module

> The Rules module allows site administrators to define conditionally executed actions based on occurring events

* There are events created in rules when Commerce RMA is installed such as `After creating a new return`
> 1 votes

---
Tags: commerce
---


# Question
Title: How do I change a product variaton through an image field?
Using Drupal Commerce you can set fields in the product entity which can function as attribute selection fields. The visitor can use them to switch the variations of a product.

I created a field called SIZE which allows the visitor to switch the variations of a product. This works fine. Now I need to allow to change the variation by clicking in a image of the variation. See my capture to get the idea.

I create an image field and set it to 1 value, but the "Attribute field settings" area didn't show up. In this area you can check "Enable this field to function as an attribute field on Add to Cart forms."

I thought this module could help, but as far as I see it is not useful for this: https://www.drupal.org/project/commerce\_fancy\_attributes

# Answer
> 0 votes
Try using Commerce Fancy Attributes along with Field Extractor Module

This module provides:

* A formatter for reference fields
* A views field for reference fields (called "Field extracted from entity referenced through $field")

This module uses field\_view\_field hook

> Returns a renderable array for the value of a single field in an entity.
>
> The resulting output is a fully themed field with label and multiple values.

---
Tags: commerce
---


# Question
Title: How to change order of custom module theme output?
I need to add some top links and sub top links . I altered hook\_theme function and created two templates for these code is like this-

```
function acts_theme() {
    return array(
            'acts_top_links' => array(
                    'variables' => array(
                            'links' => NULL,
                            'activelink' => NULL,
                        ),
                    'template' => 'acts-topmenu',
            ),
            'acts_submenu_links' => array(
                    'variables' => array(
                            'links' => NULL,
                            'activelink' => NULL,
                        ),
                    'template' => 'acts-submenu',
            ),
    );
}
function template_preprocess_acts_top_links(&$variables){
    $toplinks=$variables['links'];
    $activelink=$variables['activelink'];
    $variables['toplinks']=$toplinks;
    $variables['activelink']=$activelink;

}
function template_preprocess_acts_submenu_links(&$variables){
    $toplinks=$variables['links'];
    $activelink=$variables['activelink'];
    $variables['sublinks']=$toplinks;
    $variables['activelink']=$activelink;
}

```

Now I am using these theme output as-

```
function acts_display(){
    $build['acts_toplinks'] = array(
            '#theme' => 'acts_top_links',
            '#links' => $toplinks,
            '#activelink'=>'Company Law',
    );
    $build['acts_sublinks'] = array(
            '#theme' => 'acts_submenu_links',
            '#links' => $submenulinks,
            '#activelink'=>'/companylaw/acts',
    );

    $build['acts_table_rows'] = array(
            '#theme' => 'table',
            '#rows' => $rows,
            '#empty' => t('Currently there are no active content'),
    );
return $build;
}

```

I expect output as - first to show- top links, then sub menu links and then table but output exactly reverse- first I get table,then sub menu links and then top links How can I achieve this?

# Answer
If you add the `#weight` property to the arrays in $build() then that will allow you to order them e.g.:

```
$build['acts_table_rows'] = array(
        '#theme' => 'table',
        '#rows' => $rows,
        '#empty' => t('Currently there are no active content'),
        '#weight' => 99,
);

```
> 0 votes

---
Tags: theming
---


# Question
Title: How to add custom class in body tag on form submit?
I have created custom module with custom form, in which I have added input type select. Form submission is working fine, but I wanted set select option value as custom class for BODY tag.

# Answer
You can add through custom hook.

```
 function mytheme_preprocess_html(&$vars) {
  $vars['classes_array'][] = 'new-class';
}

```

**OR**

```
function YOUR_THEME_preprocess_html(&$vars) {
  $path = 'your-drupal-page';
  if (drupal_match_path($_GET['q'], $path) || drupal_match_path(drupal_get_path_alias($_GET['q']), $path)) {
    $vars['classes_array'][] = 'page-my-css-class';
  }
}

```

If you have any query related how to create then you can check this LINK.
> 0 votes

# Answer
Seems a pretty odd request and there might be a better way, please explain exactly what you're trying to achieve so a better solution could be offered.

Based upon your original post this could probably be achieved with the combination of Webform, Webform Rules, Rules, Context Rules & Context
> 0 votes

---
Tags: theming
---


# Question
Title: Views url paths not using proper url on localhost
When running site on localhost and using field rewrite I construct a link like this for example

```
<a href="/[uid]/addresses/shipping/default/[profile_id_1]">Set as default</a>

```

I get a path that is not proper. Something like this

```
http://localhost/1/addresses/shipping/default/284

```

and it is missing a site part in url and should be like

```
http://localhost/MY-SITE/1/addresses/shipping/default/284

```

I have set a $base\_url in settings.php but doesnt help. When I put site online this works fine, but what should I do for localhost?

# Answer
> 0 votes
You need to alter your .htaccess file:

```
# Modify the RewriteBase if you are using Drupal in a subdirectory or in a
# VirtualDocumentRoot and the rewrite rules are not working properly.
# For example if your site is at http://example.com/drupal uncomment and
# modify the following line:
# RewriteBase /drupal

```

---
Tags: views
---


title: Image styles not creating files

text:
# Question
Title: Image styles not creating files
I am seeing a problem on my Drupal 7 site relating to image styles.

A bit of background - This site was built by migrating the content and config from a previous site, using the Migrate and Features modules, after the previous site fell victim to Drupalgeddon. The new site seems now to be 99% working. (After fixing a *lot* of stuff that wasn't properly copied across by Migrate and Features - whether that was due to my inexperience in using these modules, or shortcomings of the modules, I don't know.)

One thing that isn't working is uploading image files into fields of type Image.

The Image gets uploaded successfully and is accessible from /sites/default/files/. But no files are being created in any of the subfolders below /sites/default/files/styles. So the thumbnails don't display.

I've tried a lot of the advice I've found while Googling - the UNIX file permissions seem to be OK, the Drupal permissions seem to be correct, I can't seen anything wrong in the .htaccess files, but perhaps someone out there can give me better guidance on what to look for here.

# Answer
Have you tried deleting the styles folder? The folder and everything below it should be created automatically by Drupal.
> 0 votes

---
Tags: media
---


# Question
Title: Added a new field to user profile, how do I set a value for existing users?
I have added a new field to the user profile on my site (i.e. in /admin/config/people/accounts/fields), a boolean value that can be either 0 or 1. Existing users have no value. How can I easily set a value for all existing users?

# Answer
Use Views Bulk Operations Module to update field values

> This module augments Views by allowing bulk operations to be executed on the displayed rows. It does so by showing a checkbox in front of each node, and adding a select box containing operations that can be applied.

* Create a view of type `users`
* Add `Bulk operations: User` field and choose `Modify entity values` checkbox to select your boolean field
> 3 votes

---
Tags: entities, users
---


# Question
Title: Different rankings in a view based on geolocation
I'm currently building a site which has a ranking table. I'd need the rankings to be different based on geolocation so what i'v done so far is building a different view for each country. So the question is - how do i display them based on the session's location? (different home page and navigation for different countries)

Any explanation would be more than welcomed.

Edit: I'm using Zen theme.

# Answer
I think Smart IP module is help you to solve your query.

**OR**

Check IP Geolocation Views & Maps or Session Cache API module.
> 0 votes

---
Tags: views, 7, location
---


# Question
Title: What hook can I use for post-save actions?
I've found several posts with this same question, but the answers always diverge to some other topic or they don't work for my needs.

After a node is saved, I want my custom module to insert a row into one of my custom tables which contains the nid of the new node. When `hook_node_submit` is called, the nid doesn't exist yet. `hook_node_insert` does have the nid, but only gets called the first time the node is saved, but I potentially need to take action each time the node is saved.

My plan is to separate my functionality into its own method and implement both hooks, but I'm trying to learn to do things properly with Drupal and so I'm wondering if there is a hook that actually fits with my requirements.

Is there a hook which is called every time a node is saved and called AFTER the save is complete?

# Answer
Looking at the comments on the question, it looks like the obvious solution is to use the hooks `hook_node_insert()` and `hook_node_update()`.

I actually just did something very similar as described in the answer: I wrote a function that does what I want to be done every time a node is created/updated and then call it from each of those hooks. It works just fine.
> 8 votes

# Answer
The correct way of doing this is to respect Drupal's db transaction. If you want to do any database action in hook\_node\_insert you must consider that the node is not actually saved yet. which means if it fails and rolled back you end up with orphaned data in your database. So Drupal database API should be used and not direct query execution.

If you want to update the node itself in hook\_node\_insert, you can't because it's not possible to use node\_save since the node is not yet saved in the database and calling it causes exception. One solution is to use register\_shutdown\_function function and passing nid, you can use node\_load to make sure that it's really saved and then do any other action you may want on the new node.

```
function your_module_node_update($node){
  if($node->type == 'your_node'){
    register_shutdown_function('_your_module_post_insert',$node->nid);
  }
}

function _your_module_post_insert($nid) {
  $node = node_load($nid);
  if ($node) {
      node_save($node);
  }
}

```

**UPDATE:** You can also find an easier alternative here https://stackoverflow.com/a/24035797/1726778
> 14 votes

# Answer
There is a new drupal module, Hook Post Action, which adds the post save hooks. Let's try it to see if it works.
> 7 votes

---
Tags: 7, hooks, nodes
---


# Question
Title: Display full webform submission on submission page
I'm using Drupal 7 and I'm learning PHP at the same time.

I'm using the **webform module** and when users submit a webform on my site, they can see their submission answers on the submission page but **they can't see the whole webform with all the components.**

I've read the THEMING.txt file in the webform module and I've copied webform-submission.tpl.php to my theme folder and have been trying to edit it but I can't figure out the code I need to use. I think it's probably quite a simple snippet but I'm not advanced enough yet to work it out.

Could someone help me out please?

# Answer
It's the webform-confirmation.tpl.php that you'd want to edit.

There's an article here explaining exactly what you want to achieve. https://www.drupal.org/node/1515548
> 0 votes

---
Tags: webforms
---


# Question
Title: can't programatically update line item on drupal commerce order
I want 'sell' a donation for custom donation amounts, and I know that to do this, I will need to use line items. I wrote the following code which I thought would do the trick, but when I go to /cart, I see that the price has remained the same.

```
global $user;
  if(user_is_logged_in()) {
    //$order_id = commerce_cart_order_id($user->uid);
    //$order = commerce_order_load($order_id);
    $order = commerce_cart_order_load($user->uid);
  }
  else {
    $order = commerce_cart_order_load();  //no uid since user is not logged in. attempts to load an anonymous order from the session.
  }
  //var_dump($form_state['values']['donation-custom-amount']);
  $lineItem = commerce_line_item_load($order->commerce_line_items['und'][0]['line_item_id']);
  if($form_state['values']['donation-custom-amount'] !== "") {  //if the user entered a custom amount
    $lineItem->commerce_unit_price['und'][0]['amount'] = $form_state['values']['donation-custom-amount'];
    $lineItem->commerce_total_price['und'][0]['amount'] = $form_state['values']['donation-custom-amount'];
  }
  else {
    $lineItem->commerce_unit_price['und'][0]['amount'] = $form_state['values']['donation-amount'];
  }
  commerce_line_item_save($lineItem);
```

I checked that $form\_state\['values'\] was giving me the form data, and there are no errors, just no price change.

# Answer
Recently I've updated some other line item fields on commerce\_add\_to\_cart\_submit() via this code:

```
$line_item = commerce_line_item_load($lit_id);
$line_item->field_product_options[LANGUAGE_NONE][0]['value'] = $size;
commerce_line_item_save($line_item);
entity_get_controller('commerce_line_item')->resetCache(array($line_item->line_item_id));

```

I hope this will help someone.
> 6 votes

# Answer
The requirement which I see from your code is, you want to user's input for amount & update the cart. You can easily achieve this by using - Commerce Donate & Commerce Custom Product.

If it doesn't suit your requirement, please specify for further lookout.
> 0 votes

---
Tags: commerce
---


# Question
Title: Automating module activation during installation of Drupal
I want to add some modules in an installation profile, so that they are automatically installed during installation. Some modules need to be configured before using them.

Is it possible to do it?

# Answer
You can create a custom installation profile

> Installation profiles combine core Drupal, contributed modules, themes, and pre-defined configuration into one download. Installation profiles provide specific site features and functions for a specific purpose or type of site. They make it possible to quickly set up a complex, use-specific site in fewer steps than if installing and configuring elements individually.

See How to write a Drupal 7 installation profile and the Install profile API for more info.
> 6 votes

# Answer
You can set up dependencies for your profile like you would for a module in YOUR\_PROFILE.info.

Have a look at the standard profile included in drupal core. standard.info

If you want to make configurations upon install you can use hook\_install() in YOUR\_PROFILE.install

I would advice you to have a look at the profiles in drupal core for examples.
> 1 votes

# Answer
You could pack a group of dependencies using the Features Module.

> The features module enables the capture and management of features in Drupal. A feature is a collection of Drupal entities which taken together satisfy a certain use-case.
>
> Features provides a UI and API for taking different site building components from modules with exportables and bundling them together in a single feature module. A feature module is like any other Drupal module except that it declares its components (e.g. views, contexts, CCK fields, etc.) in its .info file so that it can be checked, updated, or reverted programmatically.

Under the Dependencies dropdown select the modules and even their associated settings. In this way, you can build a archive file that you can transfer to a new install and active as you would a normal module.
> 1 votes

---
Tags: hooks
---


# Question
Title: How to choose to which group new content will be visible?
I have a content type: Event. I put instances of Event inside the Calendar(everything works great). I also have Organic Groups installed and set up(I have a group called: employees).

Now, the problem is that when I create an Event I can't find dropdown list where I can choose to whom this content will be visible(to which group).

How to make it show up?

This is Drupal 7.

# Answer
> 0 votes
One have to add a field to content type: `og_group_ref`.

---
Tags: nodes, organic-groups
---


title: How to create separate user types?

text:
# Question
Title: How to create separate user types?
I want to create separate user types. By "type", I don't mean just roles. Let me explain by an example.

User comes to my website and he wants to register either as "User" or "Editor". Both these profiles will have very different fields and different permissions.

Now, I can use profile2 module to create different profiles and restrict them to different roles. Furthermore, I can use Autoassignrole module to assign the desired role to the user during registration. This is all fine.

Now, what I want is separate links for registration for both roles. When user clicks on any one of them, only the relevant "profile2" profile should be shown in the form. The problem is that on the default registration form, both profiles are shown.

One could say that I could just uncheck the option in the "profile2" profiles and not show them during registration, and user can enter his profile after registration. But here is the thing: I want some of the profile fields to be entered during registration itself. This is required for my case.

So, now you get what I mean by "type"? It is surprising there is no straightforward solution to this basic functionality. How are you achieving this?

# Answer
This should work (at least it did for me). Put this code in your template.php and adjust accordingly.

I created a user field called 'type' as a select list (for future consideration). You could just as easily use a hidden field or a text field if you don't want the user to be aware of a difference (NOT FOR SECURITY PURPOSES - THIS IS VERY INSECURE). Make it mandatory.

given a url of mysite.com/user/register?type=one this will assign the field named 'type' to 'one', otherwise it will assign it 'two' by default.

I added some comments to help with the code, but you can remove that later. Obviously you will need to adapt this to the profile selection - I don't profile2 setup on my test site so I can't really get into that, but this is the basics, and I can help guide through the rest.

```
function theme_form_alter(&$form, &$form_state, $form_id) // change theme to your theme name
{
    if($form_id == 'user_register_form')  // only check on user registration form
    {
      $urlGet = drupal_get_query_parameters(); // get URL parameters ?type=one, etc
      if($urlGet['type'] == 'one') // check ?type= against expected
      {
        $form['field_type']['und']['#options'] = array('One' => 'One'); // set select list option(s)
        //$form['field_type']['und']['#options'] = array('One' => 'One', 'Three' => 'Three'); // for multiple values
      } else
      {
        $form['field_type']['und']['#options'] = array('Two' => 'Two'); // default value
      }
    }
}

```
> 1 votes

---
Tags: users
---


# Question
Title: How to add a javascript field to custom content type
I have a custom content type called 'Visualisation'. I would like a user to be able to upload their own javascript file for each instance of the content type. I would then like to load this script on the page in which the content is displayed.

I have tried adding a custom field 'file', however Drupal doesn't allow javascript files and appends the file with 'txt'. How can I add a javascript file and then load when the content is displayed?

EDIT

As it seems unsafe to achieve this the way I've mentioned above I'll try and elaborate on what I'm trying to do.

The content type is for HTML5 canvas visualisations. Each visualisation will use a custom created script file. The whole content will consist of a title, canvas element, javascript file and description. I therefore need to attach a script to each visualisation.

Would it be better to have a field with just the name of the file and load it in the page template?

Many thanks for any help.

# Answer
> 2 votes
First things first: a warning. This sounds like an extremely dangerous idea. If you do this, please at least make sure that you're only opening this up to trusted users (as allowing people to place javascript on your page could lead to some very, very bad things, much like the php filter.)

That being said, if your sure you want to do this, your gonna need to add the js to your page programmaticly. You could easily do this through your theme functions of template\_preprocess\_node.

Find that function in your template.php file. You'll want to add a condition to check for the content type, then grab the js file and use drupal\_add\_js to grab the attached js file and attach it to the head.

---
Tags: entities, nodes, javascript, files
---


# Question
Title: Adding a class to a menu item where the class name is set in the node
I want to add a field to a content type where the editor can select a class name from a drop down or simply enter a class name into a text field. I want this class name to then be added to the menu item's li tag.

The purpose is so that the editor can select an icon (based on Font awesome) when they are authoring a page of content.

The class should be added on the content authoring page, and not via a secondary step by editing the menu item itself from the menu manager. Note, I'm also using taxonomy menu to build the links.

Any suggestions would be appreciated.

# Answer
> 0 votes
How comfortable are you with code?

This sounds like a job for hook\_preprecess() inside template.php to get the value of drop down field and store it to something like `$var['my_class_to_insert']=`. Then inside of whatever.tpl.php used for this situation, have `<div class='$my_class_to_insert'>Content goes here</div>`. See https://stackoverflow.com/questions/8124089/ for how to get the value of a field in the template.php file.

The drawbacks to this second approach is that you are coupling functionality to the theme layer and adding to "Drupal's Div Soup."

***Or*** I'd look at two other modules before you open up a code editor. You could try to use logic in the Context Module

> Context allows you to manage contextual conditions and reactions for different portions of your site. You can think of each context as representing a "section" of your site. For each context, you can choose the conditions that trigger this context to be active and choose different aspects of Drupal that should react to this active context.

***And*** Rules may help out...

> The Rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules). It's a replacement with more features for the trigger module in core and the successor of the Drupal 5 workflow-ng module.

Rules and Context also have a world of other modules that add additional pieces of functionality.

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


# Question
Title: How do I include tax and discount in computed field?
I use the Commerce price by components module to display products' commerce\_price field with tax and discount included. It works as expected (I'm displaying the products' prices with a view in a panel)

I have another field, which is a Computed field, that I use to calculate the discount between the commerce\_price field and a custom price field (MSRP).

**Unfortunately**, while the commerce\_price is displayed with tax and discount included, the value sent to the computed field (from the commerce\_price token) is the original value, without tax or discount applied, or any information related to the price components.

I can't figure out a clean way to apply the tax and the discount to the commerce\_field value used for the calculation in the *Computed field*. How can I make the computed field receive the same token value as the one displayed?

I'm aware of the module Drupal Commerce Extra Price Formatters but using the Computed field gives me way more flexibility to calculate discount and special prices captions.

# Answer
> 0 votes
Surprising I did not find this function before, but this is what I needed:

commerce\_product\_calculate\_sell\_price($product, $precalc = FALSE)

Returns a price field data array as returned by entity\_metadata\_wrapper().

---
Tags: entities, commerce
---


# Question
Title: how to unset admin menu links programmatically?
how to unset admin menu links programmatically ?

I have created a module with this hook in it

```
function myModuleName_menu_link_alter(&$item)
{

//  dpm($item['link_path']);
     if($item['link_path']=="/admin/config/people")
    {
     $item=FALSE;
    }
}

```

the link path

```
  "/admin/config/people"

```

is listed with dpm.

how can i remove it from the admin menu?

I have also tried with this hook

```
  function my module_menu_alter(&$items) {

       // dpm($items['user/%user/cas']);
        unset($items['user/%user/cas']);
  }

```

# Answer
> 0 votes
this is how i have done it

```
 /**
 * Implements hook_menu_alter.
 */

function people_manage_menu_alter(&$items) {
    $items['admin/people/create']['access callback'] = 'menu_people_access_callback';
   $items['admin/config/people/accounts']['access callback'] = 'menu_people_access_callback';
   $items['admin/config/user-interface']['access callback'] = 'menu_people_access_callback';

}

 function menu_people_access_callback($arg) {

       global $user;

        if(!in_array('administrator', $user->roles)) {
           return false ;
         }
      else{
         return true;
       }

   }

```

# Answer
> 2 votes
**hook\_menu\_alter** is want you are looking for. The usage is exactly the same as your example, just don't forget to clear the caches afterwards.

Cheers!

---
Tags: hooks
---


# Question
Title: role delegation module : how to fine-tune the 'edit-administer-users' permissions?
Using role delegation module , i allow a user say 'mat' with a 'site\_admin' role to assign other users to a 'VIP\_role'.

The problem is role delegation needs apparentely 'administer users permission' being selected for 'assign' actions to work.

When logging in with 'mat' credentials that's been set with 'administer users permission', it gives some back office links that i would like to restrict.

How could I restrict 'role delegate' to editing existing users and assign them roles ?

# Answer
> 0 votes
i did it this way , unsetting menu links depending on role

```
  http://drupal.stackexchange.com/questions/136399/how-to-unset-admin-menu-links-programmatically

```

# Answer
> 1 votes
The two modules you will need:

Rules:

> The Rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules). It's a replacement with more features for the trigger module in core and the successor of the Drupal 5 workflow-ng module.

and Context Redirect:

> This module provides a Context reaction which redirects to a given internal or external url if the context conditions are met.
>
> You could use this module to redirect users of specific roles to a page of your choice, or redirect them based on a path in the site (node/2, 'page.htm') to another page or external URL (ht-p://www.google.com). Dozens of conditions can be cooked up with Context and redirect users to where they need to go.

* set up a new rule, have it react on a url (based on whatever url you want to restrict)
* set a condition that the user be of the role for which you are trying to limit access
* set an action - presumably a redirect to a different page, or perhaps a custom page that tells them they don't have permission to view that url

---
Tags: users
---


# Question
Title: Show profile2 fields on users page through panels
I would like to select profile2 fields on users page.

Elements:

* Profile2: artist + fields
* User: role artist

If the user is being viewed is an artist the panel should show its fields.

Actions:

* Created the profile2 for a custom user (if I do not panelize the user/%user page the user can view the profile2 fields).
* Activated the user\_view pane
* Added relatioship with profile 2
* Now the profile2 fields appears on the UI.
* Select the field header\_img
* Save the pane

I must have forgotten something because the profile (panelized) fields does not show any content of the profile2 fields..

Attaching some screenshots!

Thanks!!

# Answer
> 0 votes
It looks like you are doing it ok, but there is an issue related that you can check at https://www.drupal.org/node/1011370#comment-9332247.

If you update to the latest dev version of profile2, it should work, and you could select the profile context and the profile type.

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


# Question
Title: Settings vs Code: Can I turn off Broadcast Message through settings?
I manage a Drupal Commons site (that relies heavily on OG). I've a request to **turn off** the ability to broadcast to groups. Is there a box that somewhere that I can un-check or is it better to use `hook_menu_alter()` in a custom theme to disable the `og/users/%/invite` path?

# Answer
> 1 votes
Well, I can do this via `hook_menu_alter()`:

```
if (variable_get('custom_no_broadcast', true)) {
  unset($items['node/%/broadcast']);
}

```

And in I take the link out via `hook_preprocess_block()`:

```
// If set, attempts to surpess the link to broadcast messages to all group members.
if (variable_get('custom_no_broadcast', true)) {
    $variables['block']->content  = preg_replace("/<a\shref=\"\/node\/\d+\/broadcast\">Broadcast message<\/a>/", '', $variables['block']->
}

```

Or just turn off the Commons Notifications module.

---
Tags: 7
---


# Question
Title: Using webservice to popolute/search Address Field fields
I'm busy developing a custom shipping module and want to have an auto-complete/select list of towns but the available data for the list is from a webservice (the reason for this is so that the shipping company can update their details without me having to update on my side the whole time).

How do I interact/modify/manipulate Address Field fields? I tried to modify field.tpl.php to hide a country but it does not affect the address section in checkout, only the products section of the cart (and somehow I don't think this is the way to go anyway). I also looked at addressfield.api.php but that looks very limited. Should I just use normal fields one by one (street, town, zip code etc) and try and modify them. I'm not sure where to even start researching what to do to accomplish this so any pointers in some direction will be appreciated.

# Answer
I managed to do this by adding a plugin to Address Field. I added the following to my .module file - this plugin has to be enabled in the UI by going to admin -\> store -\> customer profiles -\> profile types - billing info and edit the field Postal Address

```
function commerce_shipping_mds_ctools_plugin_directory($module, $plugin) {
 if ($module == 'addressfield') {
return 'plugins/' . $plugin;
  }
}

```

and then create an .inc in the plugins folder with the following code

```
$plugin = array(
  'title' => t('Commerce shipping MDS integration'),
  'format callback' => 'mds_addressfield_format_address_generate',
  'type' => 'address',
  'weight' => -80,
);

function mds_addressfield_format_address_generate(&$format, $address, $context = array()) {

  /**
  *  Use MDS API to get towns and populate select list
  **/

  $format['locality_block']['locality'] = array(
    '#title' => t('City'),
    '#options' => commerce_shipping_mds_getTowns(),
    '#required' => TRUE,
    '#prefix' => ' ',
    '#attributes' => array('class' => array('locality')),
    '#ajax' => array(
      'event' => 'change',
      'wrapper' => 'suburbs-div',
      'callback' => 'commerce_shipping_mds_ajax_getSuburbs_callback',
      'method' => 'replace',
     ),
  );

if (isset($address['locality'])) {
      $mds_suburbs = commerce_shipping_mds_getSuburbs($address['locality']);
      $format['locality_block']['dependent_locality'] = array(
        '#title' => t('Suburb'),
        '#options' => $mds_suburbs,
        '#required' => TRUE,
        '#prefix' => '<div id="suburbs-div">',
        '#suffix' => '</div>',
        '#type' => 'select',
        //'#attributes' => array('class' => array('locality')),
         );
}

/**
*  Add the Ajax
**/

function commerce_shipping_mds_ajax_getSuburbs_callback($form, $form_state) {
    return $form['locality_block']['dependent_locality'];
 }
}

```

It is working fine on the 1st drop-down list but the AJAX for the second drop down list (suburbs) is not working properly yet . Will post another question for that and update with the link in case someone else has the same issue.
> 0 votes

# Answer
More than likely, the best approach you can take here would be to add the AddressField reference to wherever it needs to be, and then add in logic to poll and collect address data inside a form validation call inside a module, using a `hook_form_FORM_ID_alter()`  call, when new Entity is created or edited.

This guide provides additional information on using validation calls in Forms: https://api.drupal.org/api/examples/form\_example!form\_example\_tutorial.inc/7
> 0 votes

---
Tags: commerce, entities
---


title: Print node tags in html header

text:
# Question
Title: Print node tags in html header
I am trying to print the articles tags in the meta area of the html. I am able to print them, however, they contain all the markup, where as I just need the plain text, comma separated list, much like it prints when using the meta module. Here is what I am using.

```
function mytheme_preprocess_html(&$variables) {
if ($node = menu_get_object()) {
  if ($node && isset($node->nid)) {
  $node = node_load($node->nid);
   node_build_content($node);
   $variables['field_tags'] = render($node->content['field_tags']);
   }
 }
}

```

# Answer
The reason your getting html in your output is because your using render(), which is just a wrapper for drupal\_render. Per that function's documentation, it "Renders HTML given a structured array tree."

If you want just something like: Cats, Dogs, Otters

it would probably be better to just pull out those values, ether by looping through the field\_tags array and pulling out the value into an array and then imploding your array, or simply looping through and creating a string. So instead of `render()`, use something like:

```
$tags = array();
foreach($node->field_tags['und'] as $tag){
  $tags[] = $tag['value'];
}
$variables['field_tags'] = implode(',', $tags);

```
> 1 votes

---
Tags: theming, meta-tags
---


# Question
Title: No default selection in a select item on commerce checkout pages using hook_form_alter
Thanks to the help I received in my previous question, I was able to change the HTML of shipping service from radios to a select field. This was done, as suggested, by means of a custom module implementing `hook_form_alter`.

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id){
    if ($form_id=='commerce_checkout_form_checkout') {
        $form['commerce_shipping']['shipping_service']['#type']='select';
    }
}

```

Now what i need is to have an empty option ("select the proper value") in it, so that the user would be forced to actively choose one of the shipping methods. What I get from

```
print_r($form);

```

is

```
    [shipping_service] => Array
                (
                [#type] => radios
                [#options] => Array
                    (
                        [deli] => Delivery : 5,00
                        [pickup] => Pickup: 0,00
                    )
                [#ajax] => Array
                    (
                        [callback] => commerce_shipping_pane_service_details_refresh
                        [wrapper] => commerce-shipping-service-details
                    )

                [deli] => Array
                    (
                        [#description] =>
                    )

                [pickup] => Array
                    (
                        [#description] =>
                    )

                [#default_value] => deli
            )

        [service_details] => Array
            (
                [#type] => container
                [#prefix] =>

                [#suffix] =>

            )

```

I tried to tinker with dafault value, inserting another option, like

```
$form['commerce_shipping']['shipping_service']['#options']['_none']='['-select-']';
$form['commerce_shipping']['shipping_service']['#options']['#default_value']='['_none']';

```

(which was somewhat randomly inspired by the 'print\_r' output from a taxonomy term field on the same form but brought no results and did cause AJAX errors. Any ideas?

# Answer
The documentation says:

> If #required is TRUE and there is no #default\_value, an empty option is added to the select control to force the user to make an active choice.

So take the default value out and make sure that the form code includes `'#required' => TRUE,`

I also read somewhere that you must use drupal\_get\_form() to build the output for a form otherwise the additional form processing functions will not run. I did not use hook\_form\_alter() to modify shipping services but instead used hook\_commerce\_shipping\_service\_info() in a custom module to give me more flexibility.
> 1 votes

---
Tags: commerce
---


# Question
Title: Can I use Emoji as icon in navigation bar?
Emoji icons are 4byte UTF8 characters, the characters are not accepted in PDO, it would show errors like this question: How can I remove emoji from all user input?

Instead, I used menu\_icons plugin to prepend icons as picture before the navigation text, it uses picture background in CSS, but by using this method the text and picture will be overlapped.

If emoji is not an option, is there another way to prepend an icon before navigation text?

If emoji is an option, please help me bypass the PDO exception.

Thanks.

# Answer
Can't help with the PDO exception, but .. Have you looked at IconAPI ? It has a sub module for use with menu items which doesn't cause overlapping as you described.

You can then use Fontello as an icon provider and create a font set from the emoticons there, or import your own emoji icons into Fontello and download them as a font set.
> 1 votes

# Answer
You can **switch my MySQL to utf8mb4 charset**, that supports all utf8 as it ought to be supported. You need MySQL 5.5.3 or greater to do this.

* make a backup (obvious, but hey)
* upgrade if needed
* for each database, table and column that has it set already, change to `CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci`
* Set `default-character-set = utf8mb4` for `[client]` and `[mysql]` in my.cnf
* Set (in the same file)

```
[mysqld]
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci

```
* Hack Drupal to use it. What you want is around line 53 of /includes/database/mysql/database.inc \- read comments there and replace "regular" UTF with the kind you need.

Hacking Drupal is usually not encouraged, but in this particular case we cannot expect a patch, so this is the only way to give users what they want. Also, it's method way less CPU consuming that altering all inputs.
> 0 votes

---
Tags: navigation
---


title: Pathauto not workin

text:
# Question
Title: Pathauto not workin
Suddenly I discover that Pathauto is not working for my website and generate urls like node/89 .
I didn't made any update or installed any new module that could interfer with it.
Have you any suggestion for that?

# Answer
You might want to double check to make sure your patterns didn't get wiped somehow. Or that pathauto is still switched on. Also, make sure token is enabled, as pathauto requires this running as well. Might be some simple places to start looking.
> 0 votes

---
Tags: path-aliases
---


# Question
Title: Attaching Callbacks to Standard Drush Commands
I would like to add a callback to fire after anyone runs`drush cc all`. Ideally this behaviour would be enabled in a drush alias file. Is this possible?

**By way of example**, in this particular instance I am managing multiple developers across several environments. Each environment is capable of flushing one or more CDN caches, and will do so during various system routines.

I don't want dev, qa, or local environments flushing production caches. Given that `drush cc all` is an integral part of the deploy and local build processes, which runs right at the beginning no less, I would like to have calls to `cc all` (other than those against @prod) call a method to disable any CDN modules before exit.

Additionally, I may wish to run patch files or other bash scripts to ensure certain environments are up to date in situations where a developer may not be able to merge a dev branch but has resources accessible online which must be updated against security vulnerabilities. And so on.

# Answer
> 3 votes
Take a look at the sync\_enable.drush.inc example file. If you configure this example as it describes, then your alias file can be configured to disable any modules that you do not want to have enabled on staging or dev sites. This is presuming that you are copying your database from @prod down to @stage or @dev. Disabling as sql-sync time is probably best, as this will protect you if, for example, someone clears the caches through the admin interface on a dev machine.

If you do need to run code prior to the cache-clear command, you can easily do so, as Drush does provide a general callback mechanism that can be used to hook any Drush command. sync\_enable is just one example of this; a policy file is another example of the same thing.

To get started, first you will need a Drush commandfile. We'll call it mycf.drush.inc in this example. Drush will tell you what hooks are available for a command if you specify the --show-invoke global option. There are many many possible hook functions, so you'll probably want to pipe the output through grep, and filter on your commandfile name.

$ drush cc all --show-invoke 2\>&1 | grep mycf

drush\_mycf\_cache\_clear\_pre\_validate drush\_mycf\_cache\_clear\_validate drush\_mycf\_pre\_cache\_clear drush\_mycf\_cache\_clear drush\_mycf\_post\_cache\_clear

In your case, you would want to implement the function `drush_mycf_pre_cache_clear()`, and put whatever guard function you wanted in there.

I'm not sure what you are asking vis-a-vis patch files and bash scripts & c.; perhaps ask this part in another question with more specific details, if the Drush pre-and-post command hooks do not solve the problem for you.

---
Tags: drush
---