# Question
Title: How to adjust prices depending on quantity and attributes using Drupal Commerce?
I am using Drupal Commerce, and have a question about some of the available price/quantity modules. As an example, if people want to buy 1-5 pictures, the price is $49/each, if 6-10, than it is going to be $39 per each.

I found *Commerce Price Table* (1st) and *Commerce Pricelist* (2nd) modules for that. Looks like 2nd is more functional, but it is very "new" ... Not sure which one I should go for.

Or should I consider some other module(s) that are also popular for that? Or can I do it right from Drupal Commerce?

What I am actually looking for: a way which can adjust the price depending on **quantity** and **attributes**.

# Answer
# Module comparison

I'm not familiar with any other such pricing related modules. It seems to me that you will have to decide between these options:

* A stable module (aka the price "table" module).
* A module that's on the horizon (aka the price "list" module).

Whenever I have to decide between multiple modules, I often use the (23) criteria that I ever documented in "maintenance scorecards" (within the Community documentation). Those scorecards are actually "applied" to charting modules, but the same criteria can be used, I think, to mostly any type of module comparisons.

I'd be happy to provide some more details (via a next iteration of my answer), but if I was to decide I would definitely go for the stable, commonly used price "table" module. The major "red flag" (= no go) for the newer "list" module is criterium nr 26 (downloads vs reported installs ratio). Correct me if I'm wrong, but only like 10 % of downloads seem to have resulted in sites that continue using it.

# Rules is your friend

I would definitely also consider the Rules module, using some custom Rules, something like so:

* Events = Calculate Sell Price of Product.
* Actions = calculate the price, and set the price to the calculated value.

Not sure (yet) if you'd need some extra 'Conditions' added to this.

Refer to Drupal commerce and rules: changing the product price dynamically for an example of dynamically changing product prices.

# Create your own custom Rule

If for some reason you can't get it to work with the Rules module, then I'd consider writing my own custom Rule(s), similar to what is described in Drupal custom Rules how to write your own events conditions, actions and custom object.

The main steps that are detailed in this tutorial are further described below (with the code included below quoted from that link).

## Part 1: Defining the Event, Condition and Action

### Define the Rules Event

```
/**
* Implementation of hook_rules_event_info().
* @ingroup rules
*/
function your_module_rules_event_info() {
  return array(
    'your_module_package_bought' => array(
      'label' => t('A package was bought'),
      'module' => 'your_module',
      'arguments' => array(
        'acting_user' => array('type' => 'user', 'label' => t('The user who bought the package.')),
        'package' => array('type' => 'package', 'label' => t('The purchased package.')),
      ),
    ),
  );
}

```

### Define the Rules Condition

```
/**
 * implementation of hook_rules_condition_info()
 */
function your_module_rules_condition_info() {
  return array(
    'your_module_condition_package_type' => array(
      'label' => t('Type of the package'),
      'arguments' => array(
        'package_id' => array('type' => 'value', 'label' => t('The type of the purchased package.')),
        'package_type' => array('type' => 'string', 'label' => t('The type of the purchased package is')),
      ),
      'module' => 'your_module',
    ),
  );
}

```

### Define the Rules Action

```
/**
 * Implementation of hook_rules_action_info().
 */
function packages_rules_action_info() {
  return array(
    'your_module_action_change_order_status' => array(
      'label' => t('Change the order status'),
      'arguments' => array(
        'order' => array('type' => 'value', 'label' => t('The order object.')),
      ),
      'module' => 'your_module',
    ),
  );
}

```

## Part 2: Coding the custom Event, Condition and Action

### Event:

Somewhere in your custom module, you need to include logic to trigger the event, with something similar to this example (note the `your_module_package_bought` in it):

```
  //here the code for buying a package will be located
  //when that code returns that a package was bought trigger the rule
  $order = order_load($oid);//$oid will be the id of the order made
  $package = package_load($pid);//pid will be the id of the bought package
  global $user;
  rules_invoke_event('your_module_package_bought', $user, $package, $order);

```

### Condition:

To evaluate the Rules condition (to check if it is TRUE or FALSE), the function `your_module_condition_package_type` is executed using the arguments provided. Here is an example of how such function could look like:

```
function your_module_condition_package_type($pid, $type) {
  $package = package_load($pid);
  return ($package->type == $type) ? true : false;
}

```

### Action:

Somewhere in your custom module, you need to include logic to perform the actual action, in this example it should be done within the function named `your_module_action_change_order_status`.
> 2 votes

---
Tags: 7, commerce
---


title: Multiple values in a row

text:
# Question
Title: Multiple values in a row
How do I get multiple values (from one field) in a row in the node template? I have a field where a user can select up to 3 values. I would like that to be displayed this way:

> Industry: industry1, industry2, industry3

I don't want it displayed like this:

> Industry: industry1
> industry2
> industry3

I am using Drupal 7.

# Answer
Could you please post the html structure? We can do it in different way from css(content) to jquery (.after()/.before())

if it's a list you can use

```
$('ul.YOURCLASS li a:not(:last)').append(', ');

```

width the css:

```
li:after
{
content:", ";
}
li.last:after{
  content:none;
}

```
> 0 votes

# Answer
If it's just adding the commas to an array, PHP has `implode()`.

```
implode(', ', $fields).

```

I think iRex is asking how to get the values. In this case, I would use the following code.

```
$fields = array();
foreach ($node->field_name['und'] as $field) {
  $fields[] = $field['value'];
}

```
> 3 votes

# Answer
You should be able to do this in a field template.

If your field is called tester, the template would be called field--field\_tester.tpl.php, and it would have code similar to this (assuming the field is a text field):

```
<?php
  foreach($items as $values => $item) {
    print render($item['#markup']) . ", ";
    }
?>

```

Doing it in a field template lets you manipulate the field as requirements demand, without messing around with the rest of the node's output format.
> 1 votes

# Answer
There is also a module for that: Field Delimiter

> Field Delimiter provides an additional setting for field formatters, allowing multi-value fields to be displayed with a delimiter between the values.
> 1 votes

---
Tags: entities
---


# Question
Title: Does drush up do a database backup/dump?
Does running `drush up` run a database backup? From testing, it looks like it doesn't. Should I be doing a separate database backup before I run `drush up` to update?

# Answer
No it doesn't. It only makes a backup of the current module directories, before it replaces them.

To create a sql dump, use

```
drush sql-dump > filename.sql.

```

But remember to move the file outside of your webroot.
> 8 votes

# Answer
To make gzipped mysql dump with drush:

`drush sql-dump --gzip --result-file={PATH-TO-RESULT-FILE}`

*Update from the wranvaud's comment:* If you don't specify the result file it will be stored on you home folder under: `~/drush-backups/<db_name>/<timestamp>/<database_file>.sql.gz`, otherwise you can specify --result-file='~/Documents/\<my\_backups\_folder\>'
> 10 votes

# Answer
If you have the Backup and Migrate module module installed, you can call it from Drush with

`$ drush bam-backup`
> 5 votes

# Answer
This is a bash script solution to Backup and Restore from command line with **drush** and **Acquia-Drupal**:

* ***Note:** You only have to change basepath,sitename and maybe drushpath in both scripts to fit your needs*
* ***Note 2:** The Backup script will create a .tar containing your site files plus a data.sql file describing your database*
* ***Note3:** The restore script will chose the last .tar backup file created by the backup script*

## **INSTRUCTIONS**

1) Find the drush path (drush is included in acquia), in my case (drushpath="/Applications/acquia-drupal/drush")

2) Create a backup\_*mysite* file and a restore\_*mysite* file and include them in your bin folder path (for example: /usr/local/bin)

3) Edit **backup\_*mysite***

```
#!/bin/bash
# Text color variables
txtgrn=$(tput setaf 2)    # Green
txtylw=$(tput setaf 3)    # Yellow

basepath="path-to-your-server-root" #4ex "/Users/monojones/www"
backuppath="$basepath/backups"
drushpath="/Applications/acquia-drupal/drush"
sitename="your-sitename"
tempdir="$backuppath/backup_$sitename"

if [ -d $backuppath ]; then
 echo "Backup path finded. [ $backuppath ]"
else
  echo "Creating backup path... [ $backuppath ]"
  mkdir $backuppath
fi

echo "${txtylw}Backing up $sitename ... ${txtgrn}"
if [ -d "$backuppath/$sitename" ]; then
 echo "Backup subdir finded."
else
 echo "Creating $backuppath/$sitename"
 mkdir $backuppath/$sitename
fi
echo "${txtylw}"
mkdir $tempdir
$drushpath/drush -r $basepath/$sitename  sql-dump --result-file=$tempdir/data.sql
tar -pczf $tempdir/files.tgz $basepath/$sitename $systempaths
tar -pczf $backuppath/$sitename/$sitename.backup_$(date +%Y%m%d%H%M).tar.gz $tempdir
rm -rf $tempdir

```

4) Edit **restore\_*mysite***

```
#!/bin/bash
# Text color variables
txtred=$(tput setaf 1)    # Red
txtgrn=$(tput setaf 2)    # Green
txtylw=$(tput setaf 3)    # Yellow

basepath="path-to-your-server-root" #4ex "/Users/monojones/www"
backuppath="$basepath/backups"
sitename="your-sitename"
drushpath="/Applications/acquia-drupal/drush"

echo "${txtylw}Restoring ${txtred}$sitename ${txtylw} database: ${txtgrn}"
FILE=`ls -1 $backuppath/$sitename/$sitename.backup_* | tail -n 1`
echo "Last backup file: ${txtpur} $FILE ${txtylw}"
mkdir temp_drupalbackup_$sitename
tar -C temp_drupalbackup_$sitename -zxvf $FILE ${backuppath:1}/backup_$sitename/data.sql
$drushpath/drush sql-drop
drush sql-cli <  temp_drupalbackup_$sitename/${backuppath:1}/backup_$sitename/data.sql
rm -R temp_drupalbackup_$sitename

```
> 2 votes

# Answer
You can also use sql-sync for backup.

```
$ drush sql-sync -v @site1 @site2

```
> 1 votes

# Answer
It is very easy now with Drush 5

“Note: Drush 5 introduced archive-dump and archive-restore commands which allow you to backup your code, files, and database into a single file."

https://drupal.org/upgrade/backing-your-site-command-line
> 1 votes

---
Tags: database, drush
---


title: Custom label and value multiple field

text:
# Question
Title: Custom label and value multiple field
Is there any module that provides a way to implement a custom multiple field that enables user to enters both label and value? For instance I have a product that has a list of features, ie:

* Color: Red
* Size: Large

And I have another product that has completely different features, like:

* Style: Tuxedos
* Gender: Male

So I like to be able to make these flexible for the editor to enter as many as features as they need mentioning the labels as well.

Thank you in advance

# Answer
> 4 votes
Using Field Collection module must serve your purpose.

After installing the module, create a field collection with two text fields - label and value.

Now attach this field collection to a content type and set its value to unlimited.

in essence what you will have is: 1. When the form loads, you have two fields, a label and a value 2. An add more button, which when clicked will generate another set of label value pair.

Hope this helps.

# Answer
> 1 votes
If you only have two values, as in this case label and value, than Double Field could be very handy:

> Double field is a small module written to provide extensions to Drupal's core Fields. By this module you can split your fields up into two separate parts.

For more values there is also the Composed Field, which:

> is an implementation of core's Field UI that allows you to split a single field into as many sub-fields as you like.

To have the data serialized it makes it hard to get it for example in views to filter. In this cases I would prefer either Multifield or Field Collection.

# Answer
> 0 votes
There is the Multifield module, but it may not be as mature. Here is a quote about it (from the module's project page):

> ... seeks to provide a true compound field solution for Drupal 7. As much as I love Field collection, it still has to save actual entities, and can cause performance problems due to having to load all the referenced field collection entities on node, or parent entity load.

---
Tags: entities
---


# Question
Title: Private nodes in Private group are visible to non-members by their URL
I have a private group with private content which I set up with group visibility and group content visibility. Logged in as a non-member of this group I get access denied on the group page however when I enter the url of a node within that group I can see it fine.

I am using views cloned from the original OG views and I even tested it with the OG views and it is still allowing a non-member to see the nodes.

I have also rebuilt permissions a number of times.

I am unsure whether this is a bug in OG or a problem with my settings?

# Answer
Do you have any other access control modules installed? The access control mechanism assumes that only one module will be specifying the access control rules for nodes. Try disabling any modules like TAC, Workflow, etc. and see if that solves your problem.
> 1 votes

# Answer
I had a similar issue too. In the end, my mistake was having "group visibility" set as a field for the Post content type when it should have been "group content visibility."
> 3 votes

# Answer
the group page is by default viewable to only the group members. secondly in global or group permission it has a coloumn for members, this column settings provides the setting for all logined users and not just group members. so if your are using the global permission than i suggest u use group permissions , in group permisssions disable all check boxes for members now add role type in global or group roles and use this role to provide the access.
> 0 votes

# Answer
We had a similar issue. It was a conflict with Content Access and OG Access Control. After a bit of digging, Content Access has a weight option under it's advanced group. (The tab is found while editing Content Types).

So Kudos to the above answer of module conflict.

**Note:** We had to rebuild permissions by disabling and then later re-enabling Content Access.
> 0 votes

# Answer
I know this is a few years later, but I just went through this, too, and figured I'd add where my issue was for someone else. In my case the problem turned out to be an issue with the Taxonomy Tools module (even though I didn't have the taxonomy\_role\_access part enabled). Once I disabled it, my groups/group content began to act as expected.
> 0 votes

---
Tags: 7, organic-groups
---


title: Webform as a block only

text:
# Question
Title: Webform as a block only
When I crate a Webform I do have an option to make it available as a block as well. But in this case it creates a node as well. How can I create a Webform as a block only?

# Answer
You will need to create a webform as node. Edit the node and navigate to:

Webform tab -\> Form Settings tab -\> Advance Settings (located at the bottom of the page).
Check the checkbox for **Available as block** and your webform will be a block.
> 1 votes

# Answer
I'm not aware of a solution different from the "create a webform as node" (+ make available as block).

However, to avoid anybody would want to visit that "node of the webform" (cfr. your "*I don't need people get on node of this Webform*"), you migt want to consider a variation of the approach detailed in the answer to my question "How to specify a Rules event like "Content is 'going to be' viewed"?". All you'd need to change to that "rule" is:

* the actual path to be checked (matching the path of your node of the webform, instead of node/\*).
* and the no\_access path (replace it by an appropriate path in your site).
> 0 votes

---
Tags: webforms
---


# Question
Title: Proper directory permisions for module installation?
So I'm trying to understand the correct permissions for file directories in order to install a module. I've installed drupal, and I try to install a module, which looks like so:

But When I click install it takes me here:

I then wanted to test if it was permissions preventing it from installing, so I chmod'd everything to 777 in the sites folder just to see, and yes, the module then installed easily and correctly. But of course, 777 on everything is insecure, so I quickly installed drupal again from scratch. So now when I check the permissions they look like this

```
html/sites$ ls -l
total 16
drwxr-xr-x 5 6226 6226 4096 Jun 17 18:38 all
dr-xr-xr-x 3 6226 6226 4096 Jul 19 20:08 default
-rw-r--r-- 1 6226 6226 2365 Jun 17 18:38 example.sites.php
-rw-r--r-- 1 6226 6226  904 Jun 17 18:38 README.txt

```

So after an installation the all folder has r-x permissions and the default has r-x as well for group and other. (A side question being, what do I make of the user and group, "6226", "4096","2365", and "904"?)

The "modules" folder, inside "all" folder where they get downloaded is also set to r-x.

```
html/sites/all$ ls -l
total 12
drwxr-xr-x 2 6226 6226 4096 Jun 17 18:38 libraries
drwxr-xr-x 2 6226 6226 4096 Jun 17 18:38 modules
drwxr-xr-x 2 6226 6226 4096 Jun 17 18:38 themes

```

I don't know if this seems right to me. Shouldn't it be able to write to the folder to download the module from an external source?

Thanks for all the feedback in advance, I look forward to hearing what people have to say.

Edit, more details:

`Linux myhostname 3.13.0-24-generic #46-Ubuntu SMP Thu Apr 10 19:11:08 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux`

`ubuntu@myhostname:/var/www/html/sites/all/modules$ ls -la
total 12
drwxr-xr-x 2 www-data 6226 4096 Jun 17 18:38 .
drwxr-xr-x 5 6226 6226 4096 Jun 17 18:38 ..
-rw-r--r-- 1 www-data 6226 952 Jun 17 18:38 README.txt`

Okay! So. after reinstalling and repeatedly chowning folders until I made it past that request for FTP details, I finally got it to ATTEMPT to download the file. All I had to do after a fresh install was `sudo chown www-data /var/www/html/sites/default`. What confuses me is why that would work. Beause before and after chowning, the permissions were `dr-xr-xr-x 3 www-data 6226 4096 Jul 20 09:03 default` for the default folder. So my understanding is that the owner, group, and others could all all read and execute, so why would changing the owner even matter? Now when attempting to "Install from a URL" after chowning default, a loading bar appears and says "Completed 100%", and then this screen appears instead of the FTP login request:

# Answer
> 0 votes
The module directory has contested ownership. In your case, **using the FTP set up from the browser**, the modules directory (and subdirectories and files) need to be owned by the FTP user you are logging in with.

For example: if you are ftp-ing in with `myusername` then the ownership on the directories and files are most likely be `myusername`. That is the default configuration for most FTP servers (*ProFTPd* for example).

```
$ chown -R [myusername] [pathtomodules]

```

If you are **updating Features** (or configuration in Drupal 8) from the Drupal backend you'll want the modules directory owned by the same user as your web service runs as. Then you can have your permissions set to something more reasonable. If you `grep ps` for Apache, nginx or httpd you should discover the user that's running the process.

```
$ ps aux | grep -i 'www\|apache\|nginx'
$ chown -R [username] [pathtomodules]

```

And finally if you are using `drush dl` you'll need the owner to be your SSH user.

**In all cases** you can set the strongest permissions with the following. Remember the webserver needs read on all files and execute on all directories. This command will give you 755 on directories and 644 on files.

`$ chmod -R u+rwX,go+rX,go-w [pathtomodules]`

The first two numbers in your `ls` command are user and group. That may be a numeric match for your web service user above. The third column is size.

---
Tags: 7, installation
---


title: how to modify field of a node?

text:
# Question
Title: how to modify field of a node?
I have a custom text field which I use to display some voucher code to users. I have it in a custom content type named (machine name) : 'add\_deal'.

What I want to do is to style the field when the node is displayed and add a link/button next to that field to copy the text in that field.

I created a field--field-type--cotent-type.tpl.php file, but how do I use it, and I dont think its working for me either. Is there any hook function I need to use to make use of that tpl file?

How could I achieve it?

# Answer
> 2 votes
I think you have to use your field name instead of field type in the name of your .tpl.php file. Assuming the label of your field is 'Voucher code', then the machine name of this field would normally be `field_voucher_code` and your template file should be named `field--field-voucher-code--add-deal.tpl.php` See theme\_field documentation for more details.

Don't forget to clear the caches (i.e., rebuild the theme registry) after creating this file in your (custom) theme.

---
Tags: entities, nodes
---


title: Inserting custom HTML using tokens

text:
# Question
Title: Inserting custom HTML using tokens
I'm trying to reduce repetitive coding by adding my own static HTML content into some form of reusable token that can be added into page bodies amongst regular code, but can't find a method. Here's what I'm looking for:

**Desired content to be inserted into page body**

```
<div class="my-repetitive-div">
    <p>I type this all the time and want to automate it</p>
</div>

```

**Token idea to insert this into a page Body**

```
<p>Here is some regular content</p>

[token:my-repetivie-div]

<p>and some more content appearing after my-repetitive-div</p>

```

**End result**

```
<p>Here is some regular content</p>

<div class="my-repetitive-div">
    <p>I type this all the time and want to automate it</p>
</div>

<p>and some more content appearing after my-repetitive-div</p>

```

This question is similar to this one, but he didn't quite get a straight answer, so I'm spelling it out here.

The **Token Filter module** wasn't what is needed, as it only addresses using pre-existing Tokens not creating custom ones. Would the **Custom Token module** achieve this?

If there's a better way to achieve this other than Tokens, i'm all ears!

# Answer
It looks like the Custom token module was what I needed. It delivers the exact functionality I described, with slightly different syntax:

```
[custom:token-machine-name]

```

Once installed, you can create your own tokens to allow referencing repeatable content under `/admin/structure/token-custom`. Changes to your tokens are immediately propagated everywhere the token is referenced.

**Note** that the Custom Token module requires the Token Filter module to operate, and for your chosen text format to have the `Replace tokens` option checked to process the tokens correctly.

This option can be found under the 'Filter' heading on `/admin/config/content/formats/`*my\_chosen\_text\_format*
> 0 votes

# Answer
I would recommend you to use Wysiwyg API template plugin module

> In TinyMCE, CK Editor and FCK Editor, there is a template function, which allows a user to select a HTML template from a drop-down and insert it into the WYSIWYG text-area. This module supports those features for use with the WYSIWYG API.
> 1 votes

---
Tags: theming, tokens
---


title: Access .html file only if logged in

text:
# Question
Title: Access .html file only if logged in
How do you restrict a .html file/page with drupal so that only logged in users can access it?

Basically I have this .html file I need to put up, I don't care whether or not it's a content-page or just simply a file - but I need only those who are logged in to be able to access it.

I've tried simply pasting the html-code in content-creator (read; /?q=node/add/page), but that crashed my site and I had to manually remove the node from the database to get it working again - so that's not an option.

# Answer
> 1 votes
As Shawn Conn said Content Access module works here but the Working with files in Drupal 7 documentation is also useful. check it out.

# Answer
> 1 votes
The Drupal way of doing this is to pull out the content from your HTML file; you don't need to paste the entire contents into the node body, that will break your site's theme.

Once you've created the node with the content you've pulled out of the HTML file, you can use the Content Access module to restrict viewing of the node to only authenticated users.

---
Tags: 7, files
---


# Question
Title: View that link to content in other languages
I have a multilingual site where some content types are translated, and others will remain English only. I'd like to have lists of English content on other language sites. I've created a view that will list content from types that can not be translated, but the path variable is putting forward a translated link (e.g. **/fr/node/123**) even though it doesn't exist.

How do I get the link to the English version? If i have the node title "Link this field to the original piece of content " it links to the URL i am expecting, but I can't use that in rewriting...

# Answer
> 0 votes
You have to add `NID` field before the *Title* in *Fields* and make it *Exclude From Display*, I mean this

Then click on *Title* and in *Show Rewrite results*, check the *Output this field as a link* and use the following configuration

Now the *Title*s are linked to `/en/node/[nid]`

---
Tags: views, uri, i18n-l10n
---


# Question
Title: Hiding a drupal block on particular page
I am trying to hide a Drupal block on a View page.

The View url is http://localhost/alphabetical

And name of the block is family tree. So I went to `Structure ->Block ->Configure(for Family tree)` and added `/alphabetical` to Show block on specific pages(with Radio button All pages except those listed) But it didn't work. Then I cleared all the caches.Still it didn't work.

# Answer
In the block configuration page, in the *Pages* tab select *All pages except those listed*; in the text area below, write *alphabetical*. As the example shown in the description for the text area, you don't need the slash at the beginning of the path.
> 2 votes

---
Tags: blocks
---


# Question
Title: How to save content type before saving an exported view through code?
I am using a module that defines a content type and view. When I install my module, the view is saved before the content type. So, my view states that fields of that content type are not available.

Is there any way to save content type first and then view?

### .install

```
function _productcustomtype_installed_fields() {
    $t = get_t();
    return array(
        'example_date' => array(
            'field_name' => 'example_date',
            'label' => $t('example Date'),
            'type' => 'date'
        ),
        'example_slot' => array(
            'field_name' => 'example_slot',
            'label' => $t('example Slot '),
            'type' => 'list_text'
        )
    );
}

function _productcustomtype_installed_instances() {
    $t = get_t();
    return array(
        'example_date' => array(
            'field_name' => 'example_date',
            'type' => 'text',
            'label' => $t('example Date'),
            'widget' => array(
                'type' => 'date_popup'
            ),
            'date_format' => 'Y-m-d',
            'display' => array(
                'default' => array(
                    'label' => $t('example Date'),
                    'type' => 'date_popup'
                )
            )
        ),
        'example_slot' => array(
            'field_name' => 'example_slot',
            'type' => 'text',
            'label' => $t('example Slot'),
            'widget' => array(
                'type' => 'list_text'
            ),
            'display' => array(
                'default' => array(
                    'label' => $t('example Slot'),
                    'type' => 'list_text'
                )
            )
        )
    );
}

function add_custom_fields() {
    foreach (_productcustomtype_installed_fields() as $field) {
        field_create_field($field);
    }
    foreach (_productcustomtype_installed_instances() as $fieldinstance) {
        $fieldinstance['entity_type'] = 'node';
        $fieldinstance['bundle'] = 'example_calendar';
        print_r($fieldinstance);
        field_create_instance($fieldinstance);
    }
}

function example_install() {
    node_types_rebuild();
    $types = node_type_get_types();
    add_custom_fields();
}

```

### .module file

```
/**
 *
 * @return type
 * Implements hook_node_info
 */
function example_node_info() {
  return array(
    'example_calendar' => array(
      'name' => t('example Calendar'),
      'base' => 'example',
      'description' => t('A example content type'),
      'has_title' => TRUE,
      'locked' => FALSE,
    ),
  );
}

/**
 *
 * @param type $node
 * @param type $form_state
 * @return type
 * Implements hook_form
 */
function example_form($node, $form_state) {
  $type = node_type_get_type($node);
  $form['title'] = array(
    '#type' => 'textfield',
    '#title' => check_plain($type->title_label),
    '#default_value' => !empty($node->title) ? $node->title : '',
    '#required' => TRUE, '#weight' => -5
  );

  return $form;
}

/**
 *
 * @return type
 * Implements hook_views_api
 */
function example_views_api() {
  return array(
    'api' => 3.0,
  );
}

/**
 *
 * @return type
 * Implements hook_views_default_views
 */
function example_views_default_views() {
//node View code goes here
}

```

# Answer
Change your install function to

```
$name = 'your content type Machine name';

// Define the node type.
$jobs = array(
'type' => $name,
'name' => $t('your content type name'),
'base' => 'node_content',
'title_label' => $t(' Title'),
'description' => $t('Description.'),
'custom' => TRUE,
);

// Set other node defaults not declared above.
$content_type = node_type_set_defaults($jobs);

```

Remove node info hook from ***.module*** file and start your function name in ***.module*** file with your module name.
> 0 votes

---
Tags: views, nodes
---


title: Re-Theme Private Message Function

text:
# Question
Title: Re-Theme Private Message Function
I would like to rewrite the original function code for the Private messages block module. The original code displays a text message for no messages or messages in the inbox. I would like to change it to an image but am no where near on the right track. Here is the coded that I am trying to change

```
 /**
 * Theme a block which displays the number of new messages a user has.
 */
function theme_privatemsg_new_block($count) {
  $count = $count['count'];
  if ($count == 0) {
    $text = t('0 Messages');
  }
  else {
    $text = format_plural($count, 'You have a new message!',
                        'You have @count new messages!');
  }

  return l($text, 'messages', array('attributes' => array('id' => 'privatemsg-new-link')));
}

```

I was trying the following replacement:

```
/**
 * Theme a block which displays the number of new messages a user has.
 */
function theme_privatemsg_new_block($count) {
  $count = $count['count'];
  if ($count == 0) {
    /*$text = t('0 Messages');*/
    $text = l('<img src="messages.png" height="40"/>);
  }
  else {
    /*$text = format_plural($count, 'You have a new message!',
                        'You have @count new messages!');*/
    $text = l('<img src="messages.png" height="40"/>');
  }

  return l($text, 'messages', array('attributes' => array('id' => 'privatemsg-new-link')));
}

```

I suspect there are issues with the fact that it is designated as a text string instead of code that should be rendered. What do you think?

Using PHP I am trying:

```
/**
 * Theme a block which displays the number of new messages a user has.
 */
function theme_privatemsg_new_block($count) {
  $count = $count['count'];
  if ($count == 0) {
    /*$text = t('0 Messages');*/
    $theme_path = drupal_get_path('theme', 'eternal'));
    $text = '<img src="' . $base_path . '/' . $theme_path . '/images/messages.png" width="50"/>';
  }
  else {
    /*$text = format_plural($count, 'You have a new message!',
                        'You have @count new messages!');*/
    $theme_path = drupal_get_path('theme', 'eternal'));
    $text = '<img src="' . $base_path . '/' . $theme_path . '/images/messages.png" width="50"/>';
  }

  return l($text, 'messages', array('attributes' => array('id' => 'privatemsg-new-link'), 'html' => TRUE));
}

```

# Answer
`$text = l('<img src="messages.png" height="40"/>);` looks wrong. "l" is function to create links, i guess thats what is failing here. Try to remove it and leave just `$text = '<img src="messages.png" height="40"/>';`.

For reference on "l" see drupal api page \- please note that there is also 'HTML' parametr in "l" function that you should set to true, since you are passing HTLM code in $text to that returning "l".

> 'html' (default FALSE): Whether $text is HTML or just plain-text. For example, to make an image tag into a link, this must be set to TRUE, or you will see the escaped HTML image tag. $text is not sanitized if 'html' is TRUE. The calling function must ensure that $text is already safe.
> 1 votes

---
Tags: privatemsg
---


# Question
Title: Extra text field for Status order in Commerce
I do have extra order status (Available for download) in Commerce. And when I choose this status I want to add a link to download a file. How can I add extra field for the order?

Probably, I even need two fields: "link" for the link and "text" for the description of link.

# Answer
Consider using the Conditional Fields module. Excerpt from its project page:

> Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.
>
> When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API.
>
> You can, for example, define a custom “Article teaser" field that is shown only if a "Has teaser" checkbox is checked.
> 0 votes

---
Tags: commerce
---


# Question
Title: Group items in Views by value in Field Collection
I have a content type (content type X) containing a Field Collection field. This Field Collection field consists of a Node Reference (content type Y) field and a text field.

I would like to create a view where I group items based on the nodes selected in the field collection field.

An example:

**Node 1:**

Field collection:

* Node ABC : text here
* Node BCA : text here

**Node 2:**

Field collection:

* Node BCA : text here
* Node CDE : text here

---

The view showing these items would look like the following:

**ABC**

* Node 1

**BCA**

* Node 1
* Node 2

**CDE**

* Node 2

---

How would I be able to create a view like this? I'm sure I need to use relations, but honestly I have no idea where to start.

Thanks for any help in advance!

# Answer
> 2 votes
*Very nice question!*

I give you every detail step by step, including the structure of content types.

First install Field Collection Views module. This will add a default View in Views menu. Its name is `field_collection_view`. Clone this view (recommended) or edit the existing one.

# Content Type X

This is the *Manage Fields* of this content type

It contains a `Title` and a Field Collection field that I called `xxx`. This is the `xxx`

It only contains an Entity reference to `y`, I called it `field_reference_xxx` (you can also include other fields, for our purpose it is unnecessary).

# Content Type y

It only has `Title` field and nothing else.

I inserted the exact content you included in the question.

Node1 (`x`) to `abd` and `bca`

Node2 (`x`) to `bca` and `cde`

# field\_collection\_view View

This is the main work to do. The default View of field collection is in `/admin/structure/views/view/field_collection_view` path. Open it.

First you need to add two *Relationships* :

> **Entity Reference: Referenced Entity**
>
> A bridge to the Content entity that is referenced via field\_reference\_xxx

*Make sure to select **referenced** not **referencing***

and the second one:

> **Field collection item: Entity with the xxx (field\_field\_collection)**
>
> Relate each Content using xxx.

I supposed the *Contextual Filter* for selecting is *Title* of content type `y`, right? so let's do it. add Title as contextual filter and make it to use `(Content entity referenced from field_reference_xxx) Content: Title` relationships.

So far so good. Now go to **Fields** section. select `Title` as a field and make it to use **(field\_field\_collection)** relationships. I mean this

**AND NOW OUR WORK IS DONE!**

In the aggregate This should be your configuration

For testing I give you the following screenshots to make sure it works

**Without any value**

**With bca**

**With abc**

**and cde**

Good Luck!

---
Tags: views, entities
---


# Question
Title: How programmatically assign selected menu to superfish menu...?
In my custom theme there is an option to choose navigation menu and type of navigation menu (TB Megamenu and Superfish Menu) from a select list in theme settings page. In my tpl file am able to pass selected menu into TB Megamenu using the following piece of code.

```
if (module_exists('tb_megamenu')) {
$block = block_load('tb_megamenu','SELECTED Menu');
$output =   _block_get_renderable_array(_block_render_blocks(array($block)));
print render($output);
}

```

From my research i didn't any methods to assign a selected menu to superfish. By using following code my **main-menu** is changed to **superfish**.

```
$block = block_load('superfish', 1);

```

How can i assign a selected nagivation menu as superfish menu..?? I am using Superfish Module version = "7.x-1.9" Welcome for all suggestions...

# Answer
> 0 votes
We can done it by using following code..

```
variable_set('superfish_menu_1', 'MENU MACHINE NAME');

```

Using this we are updating the default menu value in superfish block 1

---
Tags: theming, routes, navigation
---


title: Drush not working on Mac OSX

text:
# Question
Title: Drush not working on Mac OSX
I am developing on Mac OSX 10.10. I am not using MAMP, Aquia Desktop or anything like that. Instead, I am using the built in PHP/MySql in Mac (set up using this tutorial).

When I run Drush, I get this error:

```
Command pm-enable needs a higher bootstrap level to run - you will   [error]
need to invoke drush from a more functional Drupal environment to run
this command.
The drush command 'en views' could not be executed.

```

(No other text is displayed).

If I do Drush status, I get the following:

```
 Drupal version         :  7.37
 Site URI               :  http://mysite.local
 Database driver        :  mysql
 Database hostname      :  127.0.0.1
 Database username      :  dbuser
 Database name          :  dbname
 PHP executable         :  /usr/local/bin/php
 PHP configuration      :  /usr/local/etc/php/7.0/php.ini
 PHP OS                 :  Darwin
 Drush script           :  /Users/myname/.composer/vendor/drush/drush/drus
                           h.php
 Drush version          :  8.0-dev
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /Users/myname/Sites/mysite
 Site path              :  sites/site1

```

---

## Steps I have tried

**1. Re-installing Drush via this tutorial**

The tutorial says to install Drush via Composer. The install works, but when I re-run Drush, I get the same error.

**2. Install Drush via this tutorial**

This tutorial recommends to install it via Homebrew. When I do this, I get this error:

```
  Problem 1
    - Installation request for d11wtq/boris v1.0.10 -> satisfiable by d11wtq/boris[v1.0.10].
    - d11wtq/boris v1.0.10 requires ext-pcntl * -> the requested PHP extension pcntl is missing from your system.

```

I've looked extensively on the Internet for how to fix this, but I just find sites saying I need to compile from source. They provide no steps on how to to do this, and I don't know what it means.

**3. Using the 127.0.0.1 trick**

(Changing host to 127.0.0.1 in settings.php).

Thanks for any help

# Answer
> 2 votes
A "possible" reason might be because Drush commands must be issued from the appropriate subdirectory of your website (change to the directory where your Drupal site is installed and try again).

So try navigating to the sites/default folder (assuming this is NOT a multi-site), and then retry your Drush comand.

If that doesn't help, it could well be an issue with the version of Drush that you are using. Would it be an option to downgrade to a lower version of Drush? FYI: Drush 6.x does support D7 also ...

# Answer
> 2 votes
Pierre.Vrines answer is correct, Drush needs to be at version 7.0 when using a multisite that has a shared database (in my case shared user tables).

There aren't many good tutorials on rolling back, so here is how I did it as it might help someone:

**1. Remove the symbolic link to Drush.**

Because I had followed both the Drupal.org tutorial *and* the composer installation tutorial, I had Drush 8 installed in my Mac home directory. To remove it, I simply did this in the terminal:

```
unlink /Users/madhusharma/drush/drush

```

then

```
 nano ~/.bash_profile

```

Once bash\_profile is open, delete the Drush reference and save.

Next restart the server.

```
 sudo apachectl restart

```

Finally, move the Drush folder out of the home directory.

**2. Downgrade via composer**

Just one line in the terminal, taken from here:

```
composer global require drush/drush:7.*

```

Restart again:

```
 sudo apachectl restart

```

---

**Optional: Uninstall Via composer**

Before doing step 2, it might be an idea to uninstall Drush 8 via composer. There's a Stack exchange thread that explains how here. Basically:

1. Edit your composer.json file, e.g. (in terminal)

nano ~/.composer/composer.json

and remove line containing drush. Save the file.

Update Composer PHP packages by:

```
composer global update

```

It will remove the globally installed drush.

---

**Install Drush properly in the future**

The reason I got into this mess was because there are so many conflicting Drush installation tutorials for Mac. The best way of doing it is by using the following in the terminal:

```
sudo mkdir /usr/local

sudo mkdir /user/local/bin

sudo curl -sS https://getcomposer.org/installer| php

sudo mv composer.phar /usr/local/bin/composer

~/

nano ~/.bash_profile

```

This will open nano, so enter `export PATH="$HOME/.composer/vendor/bin:$PATH"` Then press `Ctrl+X` and Save

```
source ~/.bash_profile

```

---
Tags: 7, drush
---


# Question
Title: Calling another function using drupal_get_form
How can I call a function using `drupal_get_form` when a submit button is clicked. My situation is that i have a custom module where there is only a submit button. So when that submit button is clicked I want to call a particular function. How can I achieve it through `drupal_get_form`.

# Answer
> 2 votes
```
$form['#submit'][] = 'myform_form_submit';

```

You can call your function as above. Or

```
function myform_form_submit($form, &$form_state) {
  //execute your function here
}

```

---
Tags: hooks
---


# Question
Title: Custom Path Alias with Initial Letter as Token
For various reasons, I need to change my custom path alias for a taxonomy type as follows...

FROM: /composers/aardvark

TO: composers/a/aardvark

So I'm looking at either creating a custom token, or a computed field to figure out the first letter of the term and feed into the pathauto module...

I'm having trouble figuring out either... Could anyone suggest the correct code to use for either of these? Most of the examples I am finding are node specific, and not taxonomy term specific...

The reason I'm looking to do this, is to provide a contextual filter to a views block... But if anyone could suggest a good way to pass 'a' *from* 'aardvark' into the block - so that both of these paths passes the same contextual filter, that would be equally good!

/composers/a

/composers/aardvark

Thanks in advance for your help!

# Answer
> 1 votes
There are many ways to achieve this, as you said.

The less-coding way I see is to use Custom Token and create for each node a token using the following code :

```
return substr($node->title, 0);

```

Then you use this token in your URL alias pattern like \[yournewtoken\]/\[node:title\].

If you have a multi-lingual site, the first letter might not be the same in all languages, you may update this code to fit this.

# Answer
> 0 votes
I found this page searching for a solution to add the first character (letter) of the node title in the breadcrumb path. The full and correct code should be

```
$node = node_load(arg(1));
return substr($node->title, 0);

```

See the screen shot

---
Tags: taxonomy-terms, views, tokens, path-aliases
---


# Question
Title: how to get the submitted value of tableselect
```
function test($form, &$form_state){
   $form = array();

   $header = array(.............);

   $values = array(.............);

   $form['table'] = array(
      '#type' => 'tableselect',
      '#header' => $header,
      '#options' => $rows,
      '#multiple' => $IsCheckbox,
      '#empty' => t('No users found'),
    );
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Submit'),
    );
  return $form;
} // end of function test()

function test_submit($form, &$form_state){

$selected = $form_state['values']['table'];

drupal_set_message($selected)  // displays array index (0,1,2 etc)

return;
}

```

How to get the selected table row values in Drupal form. Need assistance on the issue. Any help would be appreciated.

# Answer
You can exclude unselected options with `array_filter`, e.g.

```
$selected = array_filter($form_state['values']['table']);

```
> 0 votes

---
Tags: 7, forms
---


# Question
Title: How to create a global language selector page at domain root with i18n when the global language has a prefix?
I am looking for a solution to create a language selector at www.domain.com. My site has multiple languages (en, de, fr). All the languages are using a domain prefix. This results in:

* www.domain.com/en (default language)
* www.domain.com/de
* www.domain.com/fr

Now I want a global language selector at www.domain.com without any redirects. The module https://www.drupal.org/project/language\_selection\_page is almost what I'm trying to accomplish, but this is using a redirect. I was told this is bad for SEO (redirect).

What is the best way to accomplish this?

# Answer
I solved this by creating an index.html file. Then in the .htaccess I changed the default handler from

DirectoryIndex index.php index.html index.htm

to

DirectoryIndex index.html index.php index.htm

This way I am able to create a custom page at the domain root.
> 0 votes

# Answer
Consider creating a special "homepage" node, for which you set the "language" to "Language Neutral" (any path will do, even no path if that's what you'd prefer). And use its node ID (preceeded by 'Node/') as the value for "\*Default front page \*" within `admin/config/system/site-information`.

From then on, you can create any content for that node as your language selection page, which of course should include a link to each language specific "starting page".
> 0 votes

---
Tags: i18n-l10n
---


title: Can't access private files

text:
# Question
Title: Can't access private files
I have implemented a private file system for users to upload files. This appears to be working as I can see that the file is uploaded into the proper directory. The problem I have is that no one has permission to view the file (including user 1 which seems odd to me). The error message is:

You are not authorized to access this page.

From what I have read in the documentation, I believe I have everything set up correctly. The file path is outside of the web root directory and accessible by Drupal (as evidenced by the successful file upload). The page that displays the link to the file is in the form of:

/system/files/private/test.pdf

Which is the correct link.

The file permissions set on the directory is: drwxrwxr-x

Which looks right to me as well.

So I am completely stumped. I followed the Drupal 7 documentation page on setting up private directories so I am not sure what I missed. I have obviously overlooked something and hope that someone can tell me what it is or what I should be looking for or what I need to implement to get this working. This is for Drupal 7 by the way.

Thanks

# Answer
> 4 votes
After digging around some more I have found the solution. In your module you need to implement the hook\_file\_download() function. This function determines whether a user has the permission to view the file. It should look something similar to this:

```
function my_module_file_download($uri) {

  // Get the file record based on the URI. If not in the database just return.
  $files = file_load_multiple(array(), array('uri' => $uri));
  if (count($files)) {
    foreach ($files as $item) {
      // Since some database servers sometimes use a case-insensitive comparison
      // by default, double check that the filename is an exact match.
      if ($item->uri === $uri) {
        $file = $item;
        break;
      }
    }
  }

  if (!isset($file)) {
    return;
  }

  // Put your permission check code here.
  $can_access_file = check user permission function

  // When done perform the following code
  if ($can_access_file) {
    $headers = file_get_content_headers($file);
    return $headers;
  }
  return -1; // return that user does not have access
}

```

Hopefully this will help others with similar problems.

# Answer
> 2 votes
In my case, I could access private image files on my stage server but not on live. The cause was the live server's settings.php file, where fast 404 pages were enabled.

I needed to replace `$conf['404_fast_paths_exclude'] = '/\/(?:styles)\//';` with `$conf['404_fast_paths_exclude'] = '/\/(?:styles)|(?:system\/files)\//';` .

See also Fix fast 404 settings for private image files.

---
Tags: 7, files
---


# Question
Title: Any way to export webform node to other installation?
Is there anyway to export a webform node to another installation in D7? I need to export a webform node with all its components and webform settings.

**Updated:** I already tried with Webform Share, but I can't get the "email" setting exported, this settings are just ignored. I have a very complex emails setting that I'd like to export as well.

# Answer
> 2 votes
Have you tried the Webform share module (it is a helper module to prepopulate newly created webforms and to export / import webforms between sites), it may be helpful for this scenario as it provides the following feature:

> Example usage 1: Prepopulated webforms

Create a webform with the required components. Export the webform Edit the webform content type and paste in the content from the export (under Publishing options) Use the standard node add content links and each new content item created should be prepopulated with the exported webform.

> Example usage 2: Synchronization of webforms

Export the webform that has the settings you want Import these over the existing webform.

**Note**: Existing webform components are replaced with the new webform components. If a component is dropped or the key is renamed, you will no longer have access to any user submitted data.

# Answer
> 2 votes
We have had a lot of success exporting webforms just using Node Export module - https://www.drupal.org/project/node\_export

# Answer
> 1 votes
You may try to use Webform Features which aim is to ease webforms exportation. It currently is in beta release and it works only with webform 3.x.

---
Tags: webforms
---


title: how to change views output

text:
# Question
Title: how to change views output
I need to create a block with eg the latest comments on the site. when using views, concegui select the data I wanted, but the problem is that I need to edit the output of view (specify the html). I tried to make a tpl, but the fields when they get to this, are already formatted (\[#markup\]). also tried to make a block programmatically by accessing the fields of view, via `$comments = views_get_view('last_opinions');`, but so the fields do not bring content, but for example, ids (for referrals), or integers (in the case of dates), ....

basically, how to change views output?

# Answer
> 1 votes
Views out but can be changed at every stage of the process upto the field level.

You can check the theme information in the other section towards the bottom of the right vertical tabs. There you would see the list of theme templates you can use. The last one is where the fields get themed. and moving upwards each of the wrapping themes such as the row theme the entire page theme etc. The name suggestion are also there in the same place.

You can make the template as specific as you want.

# Answer
> 1 votes
Views has a set of hooks that you can use as well as template files.

If you don't want to use tpl.php files then use hooks.

This is probably what you want but there are plenty of others that are easy to find on api.drupal.org:

http://api.drupal.org/api/views/views.api.php/function/hook\_views\_pre\_render/7

If that's not powerful enough for you then you can also write your own Views handlers that extend the existing handler classes OOP-style and just change how things are rendered there.

# Answer
> 1 votes
If you want to change exposed filter form in view then use **hook\_views\_exposed\_form** to Change the exposed form output.

if your view is for listing some content type data then you can use tpl and tpl naming convension is in theme information on bottom of right side in advance.

then in tpl you can get $rows variable and iterate over this for data but you can change the listing design like table or div layout.

---
Tags: views, theming
---


# Question
Title: How does one add revision information to custom built entities?
I'm looking for help in gentle/simple terms for how to add revision information to my custom entities. This is maybe my fifth or sixth attempt to do this and every time I get lost and overwhelmed by all the info in the various online knowledgebases about the various ways of doing things for various iterations of Drupal.

I've used the `EntityAPIController` (sites/all/modules/entity/includes/entity.controller.inc) from the Entity API module and seen that this has the following method:

```
  /**
   * Saves an entity revision.
   *
   * @param Entity $entity
   *   Entity revision to save.
   */
  protected function saveRevision($entity) {
    // Convert the entity into an array as it might not have the same properties
    // as the entity, it is just a raw structure.
    $record = (array) $entity;
    // File fields assumes we are using $entity->revision instead of
    // $entity->is_new_revision, so we also support it and make sure it's set to
    // the same value.
    $entity->is_new_revision = !empty($entity->is_new_revision) || !empty($entity->revision) || $entity->is_new;
    $entity->revision = &$entity->is_new_revision;
    $entity->{$this->defaultRevisionKey} = !empty($entity->{$this->defaultRevisionKey}) || $entity->is_new;

    // When saving a new revision, set any existing revision ID to NULL so as to
    // ensure that a new revision will actually be created.
    if ($entity->is_new_revision && isset($record[$this->revisionKey])) {
      $record[$this->revisionKey] = NULL;
    }

    if ($entity->is_new_revision) {
      drupal_write_record($this->revisionTable, $record);
      $update_default_revision = $entity->{$this->defaultRevisionKey};
    }
    else {
      drupal_write_record($this->revisionTable, $record, $this->revisionKey);
      // @todo: Fix original entity to be of the same revision and check whether
      // the default revision key has been set.
      $update_default_revision = $entity->{$this->defaultRevisionKey} && $entity->{$this->revisionKey} != $entity->original->{$this->revisionKey};
    }
    // Make sure to update the new revision key for the entity.
    $entity->{$this->revisionKey} = $record[$this->revisionKey];

    // Mark this revision as the default one.
    if ($update_default_revision) {
      db_update($this->entityInfo['base table'])
        ->fields(array($this->revisionKey => $record[$this->revisionKey]))
        ->condition($this->idKey, $entity->{$this->idKey})
        ->execute();
    }
    return $entity->is_new_revision ? SAVED_NEW : SAVED_UPDATED;
  }

```

But with all the various sources of information out there on developing for Drupal I'm in a total tangle with my understanding. Am I just supposed to say "is revisionable" this link and others kind of gloss over it as though all one needs to do is set the `"revision table"` and `"entity keys" "revision"` element in the `hook_entity_info` implementation

This is where I'm unstuck - just as with `node` and `node_revision` in the db, can't entity and entity revision tables be different? Surely we need to overwrite something in one of the entity/controller/wrapper classes because it's not as simple as just copying all fields from one db table to another and auto incrementing a version id?

This post has lots of info, but I started reading through the links under "documentation" and I'm worried that I might be looking at some module which has hijacked the term revision in some higher layer.

# Answer
> 1 votes
So far this seems to be the best example to follow/debug and learn from, others just seem to lack that crucial sentance that actually helps to see what's going on: https://www.drupal.org/project/typical\_entity\_example

Use typical\_entity\_example\_5 and note the work on .install and .module. The key elements are in hook\_entity\_info (.module)/ hook\_schema (.install) and the typical\_entity\_example\_5\_form\_submit(...) (.admin.inc) function where we have:

```
$entity = $form_state['typical_entity_example_5'];
entity_form_submit_build_entity('typical_entity_example_5', $entity, $form, $form_state);
$entity->is_new_revision = TRUE;
$wrapper = entity_metadata_wrapper('typical_entity_example_5', $entity);
$wrapper->save();

```

The power of this example is that the form of the schemas are more or less the same, but with differences in the columns used as primary keys.

I'm still trying to work out though whether it's better to have it in -\>save() rather than using it in the admin form submit as above. So that any and every save invocation creates a new entity. Programmatical (non aforementioned admin UI) editing of an entity would presumably not create a new revision unless manually coded in.

NOTE: you can put it in either the custom entity class:

```
class YourClass extends Entity {
    public function save() {
        $this->is_new_revision = TRUE;
        parent::save();
    }
}

```

or custom controller:

```
class YourClassController extends EntityAPIController {
    public function save($entity, $transaction = NULL) {
        $entity->is_new_revision = TRUE;
        return parent::save($entity, $transaction);
    }
}

```

Or both, I guess. I'm still not 100% sure if there are use cases which neglect one way or another as from what I've seen so far it goes `YourClass->save()` \>\> into \>\> `YourClassController->save()` so I suppose I'll probably just put it in both just to be sure...

---
Tags: entities, nodes
---


title: How to attach node into panelized node?

text:
# Question
Title: How to attach node into panelized node?
I've got content type which panelized using Full page override. So I would like to attach an existing node into newly created node and assign it into the region as normally you would do this at `/node/%/panelizer/page_manager/content`.

How this can be achieved programatically?

---

So far I've the following code:

```
<?php
# Usage: drush scr panelizer-test.drush.php

# Input variables.
$content_type = 'my_content_type';
$node_title = 'Content 1';
$did = 811; // Hardcoded display id from panels_display table (e.g. bootstrap_threecol_stacked).

# Load ctools includes.
ctools_include('plugins', 'panels');
ctools_include('common', 'panelizer');
ctools_include('context');

// Find the node in order to attach it to panelizer.
$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', $content_type)
  ->propertyCondition('title', $node_title)
  ->propertyCondition('status', 1)
  ->range(0,1)
  ->execute();

if (!empty($entities['node'])) {
  // Load the node.
  $nid = current(array_keys($entities['node']));
  $node = node_load($nid);

  // Create an empty context object.
  $node_context = ctools_context_create('node', $node);
  $node_uuid = $node_context->data->uuid;
}

// Submit Panelizer content form (/node/%/panelizer/page_manager/content).
$new_pane = panels_new_pane('node', 'node');
$plugin = ctools_get_plugins('ctools', 'content_types', 'node');
$form_state = array(
  'contexts' => array( 'panelizer' => $node_context),
  'pane' => $new_pane,
  'plugin' => $plugin,
  'values' => array(
    'nid' => "$node_title [id: $nid]",
    'override_title' => TRUE,
    'override_title_text' => 'FOOBAR',
    'override_title_heading' => 'h2',
    'links' => FALSE,
    'build_mode' => 'teaser', // or: 'full'
    'op' => 'Finish',
  ),
  'op' => 'add',
  'subtype' => array('title' => 'Existing node'),
  'subtype_name' => 'node',
  'step' => 'form',
  'wrapper_callback' => 'ctools_wizard_wrapper',
  'conf' => array(
    'build_mode' => 'teaser',
    ),
  'no_redirect' => TRUE,
);
drupal_form_submit('ctools_node_content_type_edit_form', $form_state); // And save it.
if ($errors = form_get_errors()) print_r($errors);

// Submit Panelizer main form (/admin/structure/types/manage/%/panelizer/page_manager/content)
$display = panels_load_display($did);
$layout = ctools_get_plugins('panels', 'layouts', 'bootstrap_threecol_stacked');
$renderer = panels_get_renderer_handler('editor', $layout);
$form_state = array(
  'values' => array(
    'display_title[hide_title]' => '0',
    'display_title[title]' => '%node:title (foo-bar)',
    //'panel[pane][top]' => '12867,12868,12869,12870', // See: pids from panels_pane table
    //'panel[pane][left]' => '12860',
    'panel[pane][middle]' => "12861,12862,12863,new-$node_uuid", // We need to use new pane uuid, not node's uuid.
    //'panel[pane][right]' => '12865,12866',
    //'panel[pane][bottom]' => '',
    'op' => 'Save',
  ),
  'display' => $display,
  'renderer' => $renderer,
  'layout' => $layout,
  'no_redirect' => TRUE,
);
drupal_form_submit('panelizer_edit_content_form', $form_state); // And save it.
if ($errors = form_get_errors()) print_r($errors);

```

# Answer
Here is a better approach by using the following function which uses modifies display in node it-self:

```
/**
 * Attach node into panelized node.
 *
 */
function example_attach_node_to_panelized_node($pnid, $nid, $region = 'middle') {
  $result = FALSE;
  $node = node_load($pnid);

  // Set default region based on layout.
  if (!$region) {
    switch ($node->panelizer['page_manager']->display->layout) {
      case 'landing_page':
        $region = 'primary';
        break;
      case 'sub_landing_page':
        $region = 'main';
        break;
      case 'bootstrap_threecol_stacked':
      case 'onecol':
        $region = 'middle';
        break;
    }
  }

  if (!$region) return; // Check if matching type.

  $panes = array();
  $my_block_pane_exists = FALSE;

  // Load the display.
  $display = $node->panelizer['page_manager']->display;
  $did = is_numeric($display->did) ? $display->did : example_resave_display($node);
  if ($display = panels_load_display($did)) {

    // Check if our pane is already there, if so, ignore the further processing.
    $panes = $display->content; // Get this display's panes.
    foreach ($panes as $pid => $pane) { // Loop through and add in our new pane.
      if ($pane->type == 'node' && $pane->subtype == 'node' && $pane->configuration['nid'] == $nid) {
        // If our node already exists we can skip this.
        $my_block_pane_exists = TRUE;
        return FALSE;
      }
    }

    // Attach our new panel.
    $uuid = ctools_uuid_generate();
    $new_pane = panels_new_pane('node', 'my_node', TRUE);
    $new_pane->uuid = $uuid;
    $new_pane->pid = "new-" . $uuid;
    $new_pane->panel = $region;
    $new_pane->shown = 1;
    $new_pane->configuration['nid'] = $nid;
    $new_pane->configuration['build_mode'] = 'teaser';
    $new_pane->configuration['link_node_title'] = FALSE;
    $new_pane->configuration['links'] = FALSE;
    $display->panels[$region][] = $new_pane->pid;
    $display->content[$new_pane->pid] = $new_pane;
    // Or: $display->add_pane($new_pane, $sourcePane->panel);

    if (!$my_block_pane_exists) {
      // Finished reordering pane's and save the panelized node.
      $node->panelizer['page_manager']->display = $display;
      $node->panelizer['page_manager']->display_is_modified = TRUE;
      $result = node_save($node);
      // Clear ctools caches.
      ctools_include('object-cache');
      ctools_object_cache_clear('panels_node_display_cache', $pnid);
    }
  }
  return $result;
}

```

In case the display is not initialized yet (it's in `new` state), you've to re-save the display in order to perform above operations.

```
/**
 * Re-save panelizer display.
 * See: https://www.drupal.org/node/2537006
 *
 * @param
 *   $nid (integer)
 *     panelized node id
 *
 */
function example_resave_display($node) {
  $node = is_numeric($node) ? node_load($node) : $node;
  $display = !empty($node->panelizer) ? $node->panelizer['page_manager']->display : FALSE;
  if ($display && !is_numeric($display->did)) {
    $new_display = panels_save_display($display);
    $node->panelizer['page_manager']->display = $new_display;
    $node->panelizer['page_manager']->display_is_modified = TRUE;
    node_save($node);
    ctools_include('object-cache');
    ctools_object_cache_clear('panels_node_display_cache', $node->nid);
  }
  return is_numeric($new_display->did) ? $new_display->did : FALSE;
}

```

Sample usage:

```
example_resave_display(800); // Use only in case the node is new.
example_attach_node_to_panelized_node(800, 123);
example_attach_node_to_panelized_node(800, 124);

```

See also: Updating Panelizer content programmatically which the above functions were based on it.
> 0 votes

---
Tags: 7, panels
---


# Question
Title: ACL, Node, and User exists in DB, but still no access
Trying to write a custom module tying in ACL with commerce\_license (to purchase access to content), but I'm not sure I'm implementing the ACL API correctly. Everything seams to be in the database, however. I'm probably missing a step, but I'm not sure what that is.

User is uid 3. Node I'm trying to access is node/23. ACL is 16.

ACL is listed in acl table. Node is listed in acl\_node table, with grant view only. User is listed in acl\_user table.

```
mysql> select * from acl WHERE acl_id = 16;
+--------+----------------------+-----------+--------+
| acl_id | module               | name      | number |
+--------+----------------------+-----------+--------+
|     16 | commerce_license_acl | ACL_4_23  |   NULL |
+--------+----------------------+-----------+--------+

mysql> select * from acl_node WHERE acl_id = 16;
+--------+-----+------------+--------------+--------------+----------+
| acl_id | nid | grant_view | grant_update | grant_delete | priority |
+--------+-----+------------+--------------+--------------+----------+
|     16 |  23 |          1 |            0 |            0 |        0 |
+--------+-----+------------+--------------+--------------+----------+

mysql> select * from acl_user WHERE acl_id = 16;
+--------+-----+
| acl_id | uid |
+--------+-----+
|     16 |   3 |
+--------+-----+

```

I've noticed that in the modules that use ACL, there are calls to "node\_access\_acquire\_grants($node)" after the calls to acl\_create\_acl($module\_name, $acl\_name), acl\_add\_user($acl\_id, $uid), and acl\_node\_add\_acl($nid, $acl\_id, $read, $update, $delete, $priority), so I've added that, too. However, I'm still missing something. The acl data seems to be being recorded, but the node access records are not. I'm using content\_access (which also uses the acl module), but not getting the behavior I want.

What am I missing?

# Answer
The issue that I was having was that my module didn't correctly implement one of ACL's hooks, \[module\_name\]\_enabled().

Prior to returning the grants, acl\_node\_access\_records() checks to see if the module is enabled by firing off that hook, and does nothing if it doesn't exist.
> 0 votes

---
Tags: users
---


# Question
Title: Increase memory limit doesn't help in Fatal error: Allowed memory size of .../modules/views/views.module on line 416
I've switched from Drupal 7.14 to 7.15 three weeks ago and therefore, I'm encountering a series of very sophisticated (for me) **memory limit errors**. Those errors occur any time I'm trying to clear cache in performance or to run update scripts.

My hosting company has increased my memory limit in php.ini up to 126 M, 256 M, 512 M, and even 1024 M. But the errors still occur. I've migrated my site from shared to VPS, But the error incredibly still occurs. I have no way and no idea how to move forward.

Here are the errors:

* Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 30 bytes) in /home/example/public\_html/sites/all/modules/views/views.module on line 416
* Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 108 bytes) in /home/example/public\_html/includes/menu.inc on line 2736
* Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 71 bytes) in /home/example/public\_html/sites/all/modules/chain\_menu\_access/chain\_menu\_access.module on line 59
* allocate 64 bytes) in /home/example/public\_html/sites/all/modules/views/includes/base.inc on line 93

# Answer
> 13 votes
I've also been beating my head against a wall the last while with Drupal memory issues. Here's my collected knowledge on the topic:

# 1. Views (can) use a lot of memory

I love me some Views (and Panels and CTools and everything merlinofchaos touches with his mighty, mighty fingers), but it's possible to create configurations with multiple relationships that use a lot of memory. If you disable your Views and the memory issue goes away, it's likely a badly-constructed View causing the issue.

What to do if it is a View, and you really need that View to work? Try putting it into code (Via Bulk Exporter or Features; see below. I've hand-coded Views-like functionality in order to improve performance with very little success) for a start. Another thought is to redo the View a different way -- if ultimately what you're getting at is taxonomy terms, make sure the type of View is a Taxonomy View when creating it; don't create a Content View that uses relationships to get at taxonomy terms.

Could also be worth mentioning here that Panels also supposedly uses a lot of memory -- I haven't really benchmarked it so can't confirm this.

# 2. Moving stuff from database into code is a very good practice

It took me several Drupal sites to realize this, but keeping everything that's created via a UI in the database (Views and Panels configurations especially) is a Drupal worst practice. Why? It increases load on the database and cannot be version controlled. The first point is particularly problematic in terms of memory usage -- instead of just loading the content from the View from database, the site must also load the view components itself. This is exacerbated by how Drupal uses tables: by abstracting everything to the nth degree, each bit of Drupal's functionality uses a new table, resulting in some requests joining a bajillion tables together. This gives Computer Science people hernias (caveat: link is silly), but can't really be avoided with a piece of software as modular and user-friendly as Drupal is.

The solution? Use Bulk Exporter (Included with CTools) or Features to package up bits of code currently residing in the database as module code.

# 3. Themes can also eat memory

Does your theme have a lot of template files (I.e., files in themename/templates/)? If so, memory is consumed each time one of those files is loaded. If you're creating templates specifically to suppress bits of Drupal from being displayed, try either:

1. Changing permissions so that bit doesn't show up for specific non-admin user roles.
2. Using CSS to hide elements.

The first choice is obviously what you want to do for stuff affecting security -- you don't want to use CSS to hide an "edit" button for certain users, only to have them then unhide it via Firebug or whatever.

# 4. Don't go overboard on contrib modules

While sometimes a site needs a lot of contrib modules, don't go overboard. Each enabled (note: enabled. Disabled modules don't use any memory) module uses memory. This is a bit obvious, but worth noting regardless.

# 5. The VPS is (sometimes) a lie

In my experience, some unscrupulous hosting companies love trying to push Drupal sites to VPS servers -- they're more expensive and it frees up shared hosting space for ever-more WordPress websites. The situation is worsened by the fact that webhosts often don't advertise (Or even willingly tell you if asked) what the upper memory limit is for shared hosting.

Alas, often if a site isn't under heavy traffic and is still crashing, the issue likely has something more to do with Drupal's configuration than anything else. Pushing a user to VPS just muddies the waters and adds more variables to deal with (Is it the webserver config? PHP config? VPS guest config? VPS host config, even?).

# 6. When all else fails, clone to localhost and beat it with a stick

This is a big reason why people use the dev-staging-production methodology with version control -- when all else fails, you can do a DB dump, git clone the site to a local testing server and then royally mess up the site on the testing server without worrying about actually breaking anything on the production server.

For memory issues, this generally means disabling modules one by one until the one causing the issue is exposed. It can also point to webhost-related issues -- if the site runs perfectly fine on a local install with memory set to something reasonable like 128MB, then you know your webhost is on crack.

# tl;dr

My gut is that it's chain\_menu\_access that's causing the issue. Try disabling that and clearing the cache, see if it works.

I'll also add to this answer as I think of other things to try...

# Answer
> 2 votes
You can try putting PHP profiler like XHProf or Xdebug's built in profiler to inspect what is happening in the request.

# Answer
> 1 votes
Views is a memory hog. Drupal's caching can help. Drupal only loads modules active however if they create tables or have other objects those can hang around. Only uninstalling will remove most of the artifacts. We use drupal's authorization/permissions and write our own modules within. Not the best but the performance is much better and easier to tune. We do the same for WP too.

# Answer
> 0 votes
I my case the memory limit problem was generate by cache system (Boost and Boost Expire modules). This give me issue to update module or views. Once disabled Boost modules all work fine.

---
Tags: views, routes
---


title: Custom Text in Views

text:
# Question
Title: Custom Text in Views
In drupal 7, I created block in views and add field **Global: Custom text**, and write some text in this field.

When display this block and inspect show **Global: Custom text** in **span** tag.

How to display **Global: Custom text** but not in **span** tag.

# Answer
You can turn them off in "**Global: Custom Text**" field setting. Just check the "**Customize field HTML**" and "**Customize field and label wrapper HTML**", and set both elements to "**None**" in "**Style Settings**". See below screenshot for details.
> 2 votes

# Answer
you can choose **Global Php** variable from listing when add different varible of content type from listed variables in view.
> 0 votes

---
Tags: views
---


title: Drush command errors

text:
# Question
Title: Drush command errors
Drush on work machine doesn't seem to work at all for me.

Executing `drush up` returns:

```
Command pm-update needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.                                                                             [error]
Command pm-update needs the following modules installed/enabled to run: update.                                                                                [error]
The drush command 'up' could not be executed.                                                                                [error]
Drush was not able to start (bootstrap) the Drupal database.                                                                                [error]
Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a configured database. In this case you can select another site with a working database setup by specifying the URI to use with the --uri parameter on the command line. See `drush topic docs-aliases` for details.
 * connect the database through a socket. The socket file may be wrong or the php-cli may have no access to it in a jailed shell. See http://drupal.org/node/1428638 for details.

Drush was attempting to connect to:
  Drupal version    : 7.23
  Site URI          : http://default
  Database driver   : mysql
  Database hostname : localhost
  Database username : root
  Database name     : drupal
  Default theme     : garland
  Administration theme: garland
  PHP configuration : /opt/local/etc/php5/php.ini
  Drush version     : 5.9
  Drush configuration:
  Drupal root       : /Library/WebServer/Documents/drupal
  Site path         : sites/default
  Modules path      : sites/all/modules
  Themes path       : sites/all/themes
  File directory path: sites/default/files
  %paths            : Array

```

and executing `drush cc all` returns success too fast, as if it's being executed out side a project directory, without making any effect (no cache clearance).

I've been searching and looking all over the web with no answer to my problem. Please don't tell me to execute the command from my project directory, because I already am. the settings file is in the `sites/default`.

Tip: I copied the entire site to my laptop, and executed the same commands, and all worked perfectly, it's only my work machine. Could there be any mistaken drush setup? Though, I replicated the same setup on both machines, drush directory in my home directory, with exactly the same permissions, and drush alias installed in the ~/.profile as it is where I put all my bash profile scripts.

Edit 1:

Drupal directory where I execute drush command:

```
total 496
drwxr-xr-x@ 31 mmss  wheel   1.0K May  4 21:24 .
drwxr-xr-x  48 mmss  wheel   1.6K May  1 12:49 ..
-rw-r--r--@  1 mmss  wheel    12K Jan 20 18:42 .DS_Store
drwxr-xr-x  15 mmss  wheel   510B May  4 21:24 .git
-rw-r--r--@  1 mmss  wheel   104B Oct 21  2013 .gitignore
-rw-r--r--@  1 mmss  wheel   5.6K Aug  8  2013 .htaccess
-rw-r--r--@  1 mmss  wheel    80K Aug  8  2013 CHANGELOG.txt
-rw-r--r--@  1 mmss  wheel   1.4K Aug  8  2013 COPYRIGHT.txt
-rw-r--r--@  1 mmss  wheel   1.4K Aug  8  2013 INSTALL.mysql.txt
-rw-r--r--@  1 mmss  wheel   1.8K Aug  8  2013 INSTALL.pgsql.txt
-rw-r--r--@  1 mmss  wheel   1.3K Aug  8  2013 INSTALL.sqlite.txt
-rw-r--r--@  1 mmss  wheel    17K Aug  8  2013 INSTALL.txt
-rw-r--r--@  1 mmss  wheel    18K Sep 18  2011 LICENSE.txt
-rw-r--r--@  1 mmss  wheel   8.0K Aug  8  2013 MAINTAINERS.txt
-rw-r--r--@  1 mmss  wheel   5.3K Aug  8  2013 README.txt
-rw-r--r--@  1 mmss  wheel   9.4K Aug  8  2013 UPGRADE.txt
-rw-r--r--@  1 mmss  wheel   6.4K Aug  8  2013 authorize.php
-rw-r--r--@  1 mmss  wheel   720B Aug  8  2013 cron.php
drwxr-xr-x@ 49 mmss  wheel   1.6K Aug  8  2013 includes
-rw-r--r--@  1 mmss  wheel   529B Aug  8  2013 index.php
-rw-r--r--@  1 mmss  wheel   703B Aug  8  2013 install.php
drwxr-xr-x@ 70 mmss  wheel   2.3K Aug  8  2013 misc
drwxr-xr-x@ 44 mmss  wheel   1.5K Nov 11 17:24 modules
drwxr-xr-x@  5 mmss  wheel   170B Aug  8  2013 profiles
-rw-r--r--@  1 mmss  wheel   1.5K Aug  8  2013 robots.txt
drwxr-xr-x@ 13 mmss  wheel   442B Aug  8  2013 scripts
drwxr-xr-x@  7 mmss  wheel   238B Jan 20 18:42 sites
drwxr-xr-x@  8 mmss  wheel   272B Aug  8  2013 themes
-rw-r--r--@  1 mmss  wheel    19K Aug  8  2013 update.php
-rw-r--r--@  1 mmss  wheel   2.1K Aug  8  2013 web.config
-rw-r--r--@  1 mmss  wheel   417B Aug  8  2013 xmlrpc.php

```

# Answer
> 1 votes
Thanks to all for your efforts to help me, I figured out the issue I had finally, and here's the solution to the issue in case someone else went through the same.

The issue was that I had two versions of PHP installed, the default php command in bash was invoking a different version from that invoked by apache. Each php version had its own php.ini file, which made drush unable to connect the db, therefore, unable to do drupal update.

If anyone had a similar issue, check on the location of php.ini in both bash and apache: In bash write the following:

```
php -i | grep php.ini

```

You will get something like:

```
Configuration File (php.ini) Path => /etc

```

Next make your own phpinfo.php file in your document root to test your configuration:

```
phpinfo();

```

and open http://exmaple.com/phpinfo.php check on the "Configuration File (php.ini)" if it has a different location drush won't work.

# Answer
> -1 votes
i had DRUSH update issues and after trying EVERYTHING I found it to be related to multi site setup.... this worked for me

```
drush -l example.com pm-update

```

---
Tags: drush
---


# Question
Title: How can I make more than 50 product variation types?
I have an online printing shop where each product can have different variations which can change the price. To make different product variations, I have to add all the different variation types as products, then add them to the product display.

It works fine in this way, but I have many variations.

How can I make more than 50 product variation types?

# Answer
> 4 votes
# Commerce Bulk Product Creation

Consider using the Commerce Bulk Product Creation module. Excerpt from its project page:

> ... facilitates the creation of groups of related products in bulk. Product administrators can select a number of options for various fields, and a product will be created for all possible combinations of these values. Out of the box, only list fields are supported for this, but an API exists to enable other types of fields for 'combination creation'.

**Attention**: this module doesn't have an official release yet (only an RC6), though with over 1.600 reported installs, it seems it is pretty stable / trustworthy.

# Commerce Backoffice

Another option to consider is using the Commerce Backoffice module, e.g. because of the ***auto creation of product display nodes***. It provides the backoffice functionality present in Commerce Kickstart (V2), and contains these sub-modules:

* Commerce Backoffice **Product** (commerce\_backoffice\_product).
* Commerce Backoffice **Order** (commerce\_backoffice\_order).
* Commerce Backoffice **Content** (commerce\_backoffice\_content).

This module (and a few dependencies) provides the rich store owner experience that has made Commerce Kickstart 2 so popular (and prevents that you have to install the entire Commerce Kickstart distribution). And there is a great video introduction about it also.

**Note**: if you use Commerce Backoffice, you most probably also want to use the Shiny administration theme, also used in Commerce Kickstart (V2).

---
Tags: 7, commerce
---


# Question
Title: Why my taxonomy term list in content is not using node languages prefererence
I have a multilingual website, in which I activated the i18n module and every related modules.

I have a taxonomy vocabulary **Colors**.

When I create or edit a content, all my colors are displayed. What I mean is, even if my node are in English, I saw every colors (English and French).

Is there a way to displayed my color based on node languages preference?

# Answer
Check the "translation mode" that you've specified within admin/structure/taxonomy/colors/edit (whereas "colors" is the name of your specific category): by default that is set to "Localize", though it should be set to "translate".

After changing this value, be aware that you then also have to:

* enter a translated value for each of the tags and
* revisit any of the existing nodes that are already using the specific taxonomy, so that they use the (translated) term that corresponds to the language of the node.
> 0 votes

---
Tags: 7, taxonomy-terms, i18n-l10n
---


# Question
Title: How to display 01, 02... instead of Jan, Feb... on Select List with Date
I use Drupal7.
I have a profile2's field, named "Birthday".
I set the `FIELD TYPE` as `Date`. And, I set `Custom input format` as "`Y-m-d`" under "More settings and values" on field edit page. This is because, simply, I want the select list displayed like "2015 07 20(year month day)".
But, on user registration page, it is displayed as "2015 Jul 20". As I wrote, I want to display 01, 02... instead of Jan, Feb... on Select List.
Did I do anything wrong? I apologize if this is an obvious question to you. But, I've been searching the solution for hours and don't find yet. Any tips will be appreciated.
Thank you in advance.

# Answer
I have noticed that same issue that the data entry is not actually showing the data entry points that you want it to when entering items in your form. The data is stored in the data base the way you would like but this is more of a theme item I believe. So since you are using the Data API (I think, if not just turn on the Date API and this should work) you can fix this at the theme level and show the data entry the way you would like. The date API offers a hook that you can use called hook\_date\_select\_process\_alter() and you should be able to show the data the way you would like in the front end using this hook.

I would not use string overrides module for this b/c as you state you will change the months everywhere, that is not a good thing.

The code to do this (Would be placed in your theme's template.php file **Make sure to clear your site cache after adding this**):

```
/**
 * Implements hook_date_select_process_alter().
 */
function THEMENAME_date_select_process_alter(&$element, &$form_state, $context) {
  // dpm($element); // Uncomment to see before render array.
  // Loop through months and change options to numerical options.
  foreach (date_month_names_untranslated() as $key => $month) {
    // Change #options array, key is built with data API function (The same way that the Date API does this).
    // The sprintf() function is used to make things like 1 into 01 since this is technically a string.
    $element['month']['#options'][$key] = sprintf('%02s', $key);
  }
  // dpm($element); // Uncomment to see after render array.
}

```

You can use the `$context` variable above to limit this to certain forms like the node edit form (`$context['form']['#node_edit_form']` is `TRUE` on the node edit form) or the form id (`$context['form']['#form_id']`) would equal your form id. I think that this is almost the way that the Date API intends you to change these items since they offer these hooks.
> 1 votes

# Answer
if you go to Administration \> Structure \> Profile Types \> YOURPROFILE \> Manage fields

Click on Edit for the field of the DOB

Click on 'More Settings and Values' tab

The displays are on this list. If the issue is that using '-' or '/' instead of the spaces, then I am not sure of the solution .
> 0 votes

# Answer
Go to `manage display` in account settings In the right had side of your field you can find a settings icon where you can manage the format. You can add even custom format there. As explained in the image below.

and in the manage field settings format should be as shown in image below
> 0 votes

---
Tags: datetime
---


# Question
Title: Display popup message when i hover on taxonomy link to display description
I used **Hierarchical Select** module in my academic web site for student to select course from dropdown menu and it is works good but i have problem, for each course i want to add course description as a popup message when we click on course link(Course link displayed as taxonomy link). Can you help me to solve this problem. I really appreciate to you.

# Answer
It can be easily done with Simple Dialog module. All instructions you can find at the module page
> 0 votes

# Answer
For what it sounds like, personally, I'd go with the qtip project. I know it's pretty powerful (as far as getting the behavior with hover/click or getting the look how you want it), but I can't speak to if it's good for doing more advanced things; as you said you only want a "description" though, it's what I'd recommend.
> 0 votes

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


title: Print Block heading for $page - section

text:
# Question
Title: Print Block heading for $page - section
In my `page.tpl.php` I have 2 different sections nl. `$page['section_orange']` and `$page['section_contact']`.

What I want is for my `block.tpl.php` to print my heading in `h2` when a block is listed in the `$page['section_orange']` section and in `h4` in the `$page['section_contact']` section.

How can I achieve this from within my `block.tpl.php` template. Or do I need to create a hook within my `template.php`?

# Answer
You can create template file with name `block--section_contact.tpl.php`, put there code from default `block.tpl.php` file, replace h2 tag by h4 and all blocks in section\_contact region will have h4 heading.
> 2 votes

---
Tags: theming, blocks
---


title: Webform Thumbnail Image Not Created

text:
# Question
Title: Webform Thumbnail Image Not Created
I've created a form using D7 Webform 7.x-3.20. This form works in the following manner:

1. Fill out form and attach image.
2. Email is sent to admin to approve where you click through to admin approval pages.
3. Approve information and upload image (no issue).
4. Page generation page where you select the image to thumbnail.
5. Save and publish page which is added automatically to a gallery.

One issue; on step 4 the thumbnail will occasionally break and not generate in the specified folder I've defined after so large a size. I've tested to confirm it's not a file type since all JPG, GIF and PNG work just fine. It is only after about 10MB of size the issue presents itself. I've also checked my form to confirm it allows for larger file uploads than that. Additionally my php.ini file is currently allowing for up to 150 MB file size during this time of testing.

Hopefully we can brainstorm this issue together and come up with a solution.

Thanks in advance!

# Answer
Issue resolved. This was a combination of issues with file compression, max width dimensions and ram allocated to it.
> 0 votes

---
Tags: webforms, files, media
---


# Question
Title: Drupal Commerce - ability to close shop (restaurant/takeaway)
Looking for the best solution for this. Ideally I would like it to be similar to how we put a Drupal website in and out of maintenance mode.

It would need to disable the add to cart button and change the text to Restaurant closed or something similar.

I would then as well like to have a message on the site in the header somewhere that says Open or closed for business.

I have some minimal module development experience so looking to advance my skills with this one and get stuck into some further development.

What I really need is someone with a better understanding of drupal to point me in a good direction so that I can figure this one out.

Appreciate any words of wisdom here.

# Answer
> 0 votes
To do some flip-flopping with the Add to Cart buttons, take a look into the Commerce Stock module(s). I'd imagine it's in the commerce simple stock. When a product goes out of stock, it disables the Add to Cart button on the relevant product displays. Though if even one product is available on that display, it won't disable it. So, I would recommend checking out the commerce\_stock.module and commerce\_stock.rules.inc to see how they are doing that.

I envision a simple admin form page with a Close Store and Open Store buttons, and in their submit handlers, just running through and disabling the Add to Cart(s). I'm sure there's a good way to do the "Restaurant Closed", "Restaurant Open" text, it's escaping me at the moment.

# Answer
> 0 votes
I'd use rules and the submodule rules scheduler to make the open/close work according to a set schedule. Then you could also probably implement a button for adhoc close/open to override the normal schedule. I might do this with a simple form alter that disables/enables the order/checkout button based on an admin flag.

To think further ahead though, what you probably want to do is modify the order to allow "Pre-order" or "Order Now". Thus, when the store is closed allows orders to be accepted in anticipation of when the restaurant will be open next and at all normal/open times allow the orders to be for now (optionally, you could still offer the ability to pre-order/schedule an order when the restaurant is open if desired).This would mean you'd have to implement the ability for an order to have a date/time element (Now = now, Preorder = nominated time/date)

# Answer
> 0 votes
Refer to my answer to the question about How can I put a Drupal Commerce site in 'Shop Closed' mode, similar to Drupal's maintenance mode? for a Rules based suggestion to open/close the restaurant/takeaway.

No "module development experience" required, only sie building (and "Rules").

---
Tags: commerce
---


# Question
Title: Image Style Issue Doesn't Work Every Time
I posted a previous post about this, but it kind of went a different path, so in the interest of exploring another avenue I wanted to start a new topic to try and troubleshoot this a different way.

**ISSUE:** The site runs about 99% perfection, however, there is one issue. One of the image styles doesn't always generate when an image is selected for thumbnail.

**BACKGROUND/EXPERIENCE ON SITE:** I have created a website where I am accepting submissions through Webform version 7.x-3.20 on an installation of Drupal 7.32. The reason for it not being updated is due to a specific need to use Hubspot Drupal Integration 7.x.2.0-rc5. Updating breaks the HubSpot integration, so I've come to terms with the issue of security.

**SUBMISSION EXPERIENCE:** \- User fills out form and attaches an image they want to display. \- I receive an email to review it as admin for approval. I click the link in the email to travel to the submission within Drupal for approval. \- I click "select" on the image to generate a thumbnail image and adjust any copy content that may be inappropriate. \- I publish the page and review to ensure main image on entry page and thumbnails on overview page have been made correctly.

**PROBLEM:** The problem happens in step 3 above. 99% of the time images work without issue and are made into the appropriate thumbnail and entry sizes and crops. However, on occasion the image styles don't work.

**WHAT I KNOW:**

* The uploaded images do make it to the server. I can see the image no issues what so ever before I request it be processed into image styles.
* I can recreate the image styles outside of the website and upload them into their specific folders where the images that do work are placed without issue.
* I have recreated the image styles in different ways and applied them to my form approval process with similar results which makes me believe it's not directly related to the image style itself.
* I've increased the memory limit and max\_execution times for testing purposes to a very high allowability.
* It is not size specific. Many larger files go through just fine, while the occasional small file size will have this issue with the image style being generated.
* It's doesn't seem to be related to the server. I've tried multiple server setups and each has eventually replicated the issue with specific images.

Thanks in advance for helping me continue to trouble shoot this issue.

# Answer
> 0 votes
Issue resolved. This was a combination of issues with file compression, max width dimensions and ram allocated to it and a third-party firewall in place.

# Answer
> 0 votes
My gut is that this is a file permissions issue. Check to make sure that the webserver has the appropriate permissions for the directory in question, and the one above it.

# Answer
> 0 votes
**Update:** So it seems the images are failing apparently due to a max-width. The images that are failing are a particularly large size in one way or another. 4000px wide. Once the image size is reduced and resaved the file works correctly without issue.

Thoughts in regards to how to remove this restriction?

---
Tags: webforms, media
---