# Question
Title: Shipping amount incorrect when hitting "Go back" on checkout
I am using Drupal Commerce with Commerce Flat Rate and I have setup various different rates depending on the total order amount.

The normal use case works as expected, however if I am at the shipping checkout pane and I hit go back,hit continue, and then arrive again at the shipping pane again, the shipping amount is recalculated based on the previously calculated (order\_total + shipping\_cost), not on the original order\_total if you know what I mean.

What hook and code should I use to remedy this so that the shipping cost is based on the original order\_total the second time around like it was the first time around?

Is it possible to remove the shipping component of the order total on the first checkout page?

Should I try to detect when I am on the first checkout page whether I arrived from the shipping pane, and so try to remove the shipping price component from the order total?

# Answer
> 0 votes
Check out Per Product Shipping Buggy

Import this rule or a variant of it and adapt it to your use case:

```
{ "commerce_shipping_service_free_shipping" : {
"LABEL" : "Rate Free shipping",
"PLUGIN" : "rule",
"OWNER" : "rules",
"REQUIRES" : [ "commerce_shipping" ],
"USES VARIABLES" : { "commerce_order" : { "label" : "Order", "type" : "commerce_order" } },
"DO" : [
{ "commerce_shipping_delete_shipping_line_items" : { "commerce_order" : [ "commerce_order" ] } },
{ "commerce_shipping_service_rate_order" : {
"shipping_service_name" : "free_shipping",
"commerce_order" : [ "commerce-order" ]
}
}
]
}
}

```

---
Tags: commerce
---


# Question
Title: How to display a list of users tagged with taxonomy term, but taxonomy term already used in another display
I have a taxonomy vocabulary . I already have a view set-up that displays each committee's page using the '/taxonomy/term/%' display. This works great.

Committee: \- Committee #1 \- Committee #2

My issue is that I would like to have another display that shows committee members (set up as drupal users) that have been tagged with a committee using the term reference field.

* Committee #1

+ Committee #1's Users
* Committee #2

+ Committee #2's Users

How would I get this work. I can't use the path '/taxonomy/term/%' again.

Thank you in advance for any help!

# Answer
I you just want a view you can use any path you desire, as long as you have the correct contextual filters. Clone the existing view and adapt the path and whatever else you need.
> 0 votes

---
Tags: taxonomy-terms, users
---


# Question
Title: @font-your-face don't work when 'Aggregate and compress CSS files' is enabled
I added font using @font-your-face module and everything works just fine except when 'Aggregate and compress CSS files' is enabled. When I enable css aggregation and compression, whole website use some default font instead imported font in @font-your-face.

Does anyone have problem like this? Some suggestions how to resolve this?

# Answer
> 0 votes
After your compress the CSS using Aggregate option in Drupal, viewing the source code you'll find that there is an syntax error for @font-face.

Check for your syntax, there would be a break-age in that while aggregation.

---
Tags: 7, theming
---


# Question
Title: Commerce-Marketplace : Members tab in store's page doesn't show up
After this clean install :

* Drupal 7.28
* Commerce 7.x-1.9
* Commerce-Marketplace 7.x-1.0-beta2 (same issue with current dev version)
* ECK 7.x-2.0-rc3+15-dev

I create a new store but can't see the "Members" tab as seen on the demo site (I also tried the direct URL "commerce\_store/store/{ID}/people", no error but I stay on store page).

Here is a screenshot

And the demo site

Do I miss a step to activate the store members management tab/pages ?

Thanks for your help or direction to solve this.

# Answer
> -1 votes
Problem resolved after this update : https://www.drupal.org/node/2284457#comment-8962135

---
Tags: 7, commerce
---


# Question
Title: Open Atrium: How to change Task assignment from users to groups?
I'm trying to change the Task content-type to be able to assign tasks to groups, and only show those tasks in Task List that are assigned to your group you are added. I've tried by adding a new field with Entity Reference to groups, to select multiple and this part is okay and working fine.

I'm blocked when I'm trying to set the filters in the Views to get the current user's group and show the task if it's assigned to that group.

Thanks a lot!

# Answer
Edit the Task content-type, add a new Entity Reference field for oa\_group\_ref. Edit the Task List view and set a contextual filter on the added field, and provide the default value for the filter with the OG groups of the current user, and allow multiple values in More options.
In query settings set the Distinct to make it work with multiple assignment.
> 0 votes

---
Tags: nodes, views, distributions
---


# Question
Title: Does the Bootstrap 3 Theme for Drupal meet WCAG 2.0 and ATAG 2.0 standards?
I'm currently creating a new website for work and I would like our drupal website to be accessible to users with disabilities, and I wanted to know if the Bootstrap 3 Theme meets web accessibility standards like the themes Zen and Adaptive.

I wanted to confirm that the Bootstrap 3 theme is accessible before moving forward with adding content. I did not find any information on the Bootstrap 3 page on the drupal website specifying the accessibility aspect of the theme.

# Answer
As you can see in this bugreport: https://github.com/twbs/bootstrap/pull/11757 Bootstrap aims to be WCAG compatible. But it does not claim it already is. Also, there are a lot of WCAG guidelines that are not theme-only. The very first one:

> Guideline 1.1 Provide text alternatives for any non-text content so that it can be changed into other forms people need, such as large print, braille, speech, symbols or simpler language.

Obviously, theme cannot force you to comply with it.

# Audit

WCAG is now, effectively, a part of law in European Union. This means that no one will claim to be WCAG compliant lightly, and specialized law / audit companies charge big bucks to give you a "WCAG compatible" document with their signature on it. From my experience, we talk about 4, 5 digits sums, if you need it for government cooperation purposes (like, you want to sell website to a city). Possibly more. Open Source projects hardly have funding for that, that's why you *"did not find any information on the Bootstrap 3 page"*, and you will not in predictable future.

Pay from your own pocket, or use at your own risk.
> 1 votes

---
Tags: 7
---


# Question
Title: Can I get the raw value of arbitrary tokens?
This site I'm working on is using tokens in such a way that the escaped (`check_plain()`'d) values provided by the tokens as is is problematic (they're getting double-escaped). Is there some way to specify that I want the raw values for those tokens? I tried just appending ":raw" to the token name, but that didn't seem to work.

I could just write my own tokens for this purpose which only provide the raw values, but I want to see if that's really necessary first.

# Answer
> 1 votes
Garrett,

From your question I can see that you have appended ":raw" to the list of tokens that you are using.

I think that will be "-raw" instead of ":raw". As example, \[user:name-raw\] instead of \[user:name:raw\].

---
Tags: 7, tokens
---


# Question
Title: Override Access Permissions from View in Drupal 6
I have a `ticket` node that can only be accessed by the creator, or an administrator. I would like to display select fields from the ticket to other users in a view.

The problem is that, since the other users do not have access to the `ticket` node, the entries do not appear in the view.

How can I restrict access to the full ticket, but display selected fields from that ticket in a new view?

# Answer
Since I hate dangling answers, I solved this by creating a new content-type and hard coding the query and page content.

The content-type provides the query parameters.
> 0 votes

# Answer
In CCK there is a sub module named `content_permissions`, With this you can set role wise permissions for fields
> 1 votes

# Answer
http://drupal.org/project/views\_ignore\_node\_permissions Drupal 6

> This module allows you to add a filter to views that will completely ignore node permissions. This is useful for displaying info to a user that cannot view the node normally (such as premium content in teaser format)
> 1 votes

# Answer
In Drupal 7, here is how to ignore node permissions in a view:

```
Edit Query | Advanced | Other | Query settings | Disable SQL rewriting

```

https://www.drupal.org/node/1210272
> 0 votes

---
Tags: views, 6, users
---


# Question
Title: Apachesolr searching is not working with cck field
I am working in Drupal 6 website with apachesolr. I have added a cck field (text field) in a content type.

When I am searching the value of textfield, apachesolr showing empty result.

The field is indexed properly into apachesolr index.

How can I implement apachesolr searching for cck text field?

# Answer
> 1 votes
Once you add a CCK field then the CCK will not by default get indexed. You have to delete all the existing index and have to re-index all items. This is because, CCK fields are properties of all the documents (nodes) that goes to the SOLR index.

Once all the items are index then you can find those by sis\_cck\_field\_\* names where sis\_\* is a type of dynamic field provided by SOLR itself. You can find the CCK index status in `admin/reports/apachesolr/index` page or in SOLR admin `(http://127.0.0.1:8983/solr/admin/schema.jsp)` page.

**EDIT -- 1** As mentioned, the field is indexed properly then try to search by the value of the CCK field in Apache Solr's admin search (`http://localhost:8983/solr/admin/form.jsp`). If you see the search results appear as per your desire then there may be a permission issue. If your field is called "field\_example" then in permission page check whether "view field\_example" is checked for desired roles.

**Edit -- 2** In that case I think the cck field is not at all being indexed. I had the same problem once with CCk fields that stores "multiple" values. In that case what I had to do is to create a new field in SOLR index and index the item again. This may solve your problem but may not be a proper way. However you will find this way is excepted in Drupal also in this link.

You have 2 ways to achieve this.

1. Append the item in the body field in time of content indexing hook.
2. Add a new dynamic field to the document object while indexing and fetch the field while searching.

For the 1st one,

```
function MYMODULE_apachesolr_update_index(&$document, $node, $namespace) {
  $document->body .= ' '. $node->field_MY_CCK_FIELD[0]['view'];
}

```

For the 2nd one,

```
function MYMODULE_apachesolr_update_index(&$document, $node, $namespace) {
  // For multiple values.
  foreach ($array as $value) {
    $document->setMultiValue('sm_multiple_value', $value);
  }
  // For text field.
  $document->addField('ts_element_name', $value);
}

```

And while searching,

```
function MYMODULE_apachesolr_modify_query(&$query, &$params, $caller) {
  $params['fl'] .= ',ts_element_name'; //Add the field name to the select query.
}

```

---
Tags: 6, entities, search
---


# Question
Title: How do I make a twitter scheduler on drupal 7?
I basically want to make a twitter scheduler. What it does is ,it fetches the old tweets from my twitter account and queues them so that I can schedule them to be sent at a later time. So the **three** main jobs of this would be --

1. Fetch tweets from my account.
2. Queue them
3. Schedule them to be tweeted as per the user.

Could someone please tell me what all modules Id require for the same?

Thanks Appreciate it.

# Answer
1. Create a node type ‘Tweet’
2. Create a Feed Importer
3. Add JSON mappings
4. Add the Import URL
5. Use some custom code or perhaps Rules in combination with Tweet module api to schedule and send tweets

Modules:

1. Feeds
2. Tweet
3. JSONPath Parser
4. Rules

Credits: http://www.bariswanschers.com/blog/easily-import-tweets-drupal-using-json-and-feeds
> 0 votes

---
Tags: nodes, social-network
---


# Question
Title: Why doesn't my form submission handler work?
I am new to drupal and require help from Gurus.

I am adding some form elements in the status share form by using `hook_form_alter()`. These elements are getting displayed in the form, but my submission handler is not working. I am using `$form['#submit'][] = 'my_module_form_submit';` to add it to the form.

```
function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "statuses_box") {
    $form['tech2'] = array(
      '#type'=>'select',
      '#title' => '',
      '#attributes' => array('class' => array('tech2')),
      '#options' => array('All'=>'All','New'=>'New',),
      '#multiple' => false,
    );

    $form['#submit'][] = 'my_module_form_submit';
  }
}

function my_module_form_submit($form, &$form_state) {
  // Do something here.
}

```
1. The issue I am getting is `my_module_form_submit` is not getting called. The debugger break-point is not getting hit in this function
2. I am not getting error message neither on page nor in admin/reports/dblog
3. What I want is to add a new row in my custom data table, which this code is supposed to create.
4. Default form handling is running perfectly.

# Answer
> -1 votes
Check your form id. I doubt your form id is not correct. Even you can try this also -

```
function my_module_form_submit($form, &$form_state) {
  // Do something here.
  echo "<pre>";
  print_r($form);
  exit;
}

```

---
Tags: forms
---


title: Form API AJAX refreshes page

text:
# Question
Title: Form API AJAX refreshes page
I need to add some AJAX functionality to a node form. Using hook\_form\_alter I'm overriding form elements. In this particular case I need to add a callback on the 'language' element provided by the translation module (Core, Content Translation).

However, when selecting a different option in the 'language' listbox, the page refreshes. What could trigger this behaviour?

This is the code I'm using:

```
function foo_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'bar_node_form') {
    $form['#prefix'] = '<div id="bar-form-wrapper">';
    $form['#suffix'] = '</div>';

    $form['language']['#ajax'] = array(
      'callback' => 'bar_form_callback',
      'wrapper' => 'bar-form-wrapper',
    );

    if (isset($form_state['values'])) {
      drupal_set_message('ajax callback');
    }
  }
}

function bar_form_callback($form, $form_state) {
  return $form;
}

```

# Answer
> 1 votes
What exactly are you trying to do? Is the page refreshing or the entire $form? What you're asking it to do is by attaching #ajax to the select is that when it changes a value resubmit the entire $form, which would probably include any submit handlers. Typically #ajax would be directed at a form element rather than the entire form.

# Answer
> 1 votes
since the callback is acting as a form submit, your callback (\_submit) should have the same naming convention as your form id.

"bar\_node\_form" is your form id so:

```
'callback' => 'bar_node_form_submit',

```

# Answer
> -1 votes
When you specify `'callback' => 'bar_form_callback'`, it's not referring to a PHP callback per se. **Callback** in this case refers to a `hook_menu()` callback, in other words, the URL that JavaScript will call when the AJAX trigger is fired.

You need to define a `bar_form_callback` path in your custom\_module\_menu() function. That menu callback then call `function bar_form_callback()`.

D.O. FAPI reference.

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


# Question
Title: how to comment individual image in popup form drupal 7?
I have created view to display images and when I click on the image it gets displayed in pop-up form. I want to allow user to comment on image in pop-up form only so i have displayed comment form with php code. But its not working properly. It displaying preview button instead of comment. And when I click on preview it redirects to the image node page which should not be happened. I want it to work properly please help me suggesting solution. Hope image below will help you to understand what actually I have done.

# Answer
First, in your content type edit page, make the "Preview Before Submit" option disabled or optional. Once you do that you will see the Submit button.

Even you make the Submit button appear, the same will happen and user will be redirected to the actual page with no modal display. From the pattern of your modal window, I guess you are using colorbox plugin. If yes then you need to open this colorbox as an iframe option.

```
<script>
    $(function () {
        $(".example6").colorbox({iframe:true, innerWidth:425, innerHeight:344});
    })
</script>

```

So even you submit the page, the page will not be redirected outside of modal.

**EDIT #1**
Then I think you may have to alter the form you are using and check for form elements with a debug() function. Then I guess in your form\_alter you can do the following,

```
<?php
  function mymodule_form_alter(&$form, &$form_state, $form_id) {
    if (isset($form['type']) && $form_id == 'mymodule_node_form') {
      // Hide the preview/submit button.
      $form['actions']['preview']['#access'] = FALSE;
  }
}
?>

```

Have a check on the variable that sets the preview, by

```
variable_get('comment_preview_' . $node_type);

```

If it's set then can be disabled via,

```
variable_set('comment_preview_' . $node_type, DRUPAL_DISABLED);

```

I hope this will be helpful to your cause.
> 0 votes

---
Tags: views, comments, javascript
---


title: Embedded view doesn't appear in node

text:
# Question
Title: Embedded view doesn't appear in node
I have node **golosuizaprognoz\_lenta** with hidden field **argument-lenta**, node **golosuizaprognoz** with field **field\_argument**, view of table with Rating wiget:

The node have title with date, for example **21/06/14 Голосуй за прогноз!!!**

I need that in node was view only with date equal date in title.

What I have done:

I add to node **golosuizaprognoz\_lenta** hidden field **argument-lenta** where I add url of result node, for example **210614-golosuy-za-prognoz**.

I make EVA display:

with contextual filter:

when I insert content of field **field\_argument** wich equal of url node **golosuizaprognoz\_lenta** , for example all OK, I get what I want, but in node I have no this view (without contectual filters view is shown so I attached it).

How I need to fit contextual filters that in node I will see only views with content wich have field **field\_argument** wich equal of url node **golosuizaprognoz\_lenta**.

http://myforecast.esy.es/**210614-golosuy-za-prognoz**/

# Answer
> 0 votes
You should be able to accomplish this by using Auto Node Title . This will generate automatic node titles, and allows PHP to define that title. Using str\_replace you can remove the slashes from a date field and replacing them with nothing, creating the desired effect. Then use a token or static text in the title for the rest of it

> "auto\_nodetitle" is a small and efficient module that allows hiding of the content title field in the form. To prevent empty content title fields one can configure it to generate the title by a given pattern.

---
Tags: views, nodes
---


# Question
Title: Can a subgroup of a public group be private and hidden?
I'm building my first Drupal Organic Groups site, and running into problems.

## Problem:

My goal is to have top-level Groups that are visible to the public, but only members can participate in them. There will be public subgroups too. Additionally, there must be invisible private groups that only members can see. All non-members, even logged-in site users, should not even see the group exists.

Since OG doesn't support sub-groups in the core and the OG subgroups module is an alpha release, I tried making my own sub-group solution. (see description below)

A browser session not logged into the site does not show the private subgroup, as needed. However, a logged in user who is not a member of the group can see, not only the group name, but the member list and description (body field). The content is successfully hidden, stating "There is no content in this group."

Does OG support what I am trying to accomplish?

I have read these and other pages:

My configuration matches what is shown on those two references. (See screen captures below)

## System and method description:

Fresh install of Drupal 7.26 and OG 7.x-2.5.

I created a new content type called "Subgroup" and assigned it all the OG fields (group\_access, og\_roles\_permissions, group\_register, group\_content\_access, group\_theme), and marked both "Group" and "Group Content" in the Organic Groups tab in the Content Type creation form. The Subgroup content type also has an Entity Reference field type named "Parent Group." That is set to Target type "node"; Entity Selection -\> Mode = Organic Groups; Target Bundles = Group; no sorting; OG membership type = default. "OG behavior" is checked under "Additional Behaviors.

To test, I created a Subgroup node titled "Drupal theming (PRIVATE)", with both Group Visibility and Group Content Visibility set to "Private - accessible only to group members". Other OG settings were: "Override default roles and permissions" (since my site OG default is to be public) and "Do not show on registration page." The site is using the default OG Node template panel for Groups.

I verified that the "non-member" role of the private subgroup has no permissions boxes checked in Subgroup \> Group tab \> Permissions panel.

In case it may be a clue, whenever I try to save an update to a Subgroup content type node, the system displays this error:

> Notice: Undefined index: field\_mode in OgBehaviorHandler-\>validate() (line 254 of /my/domain/path/sites/all/modules/og/plugins/entityreference/behavior/OgBehaviorHandler.class.php).

##

##

# Answer
I recently experienced this same "Undefined index: field\_mode in OgBehaviorHandler..." error when trying to set the og\_group\_ref field widget to select list. It appears that it doesn't work if it's not set to "OG Reference". In the "Additional behaviors" field, you can set it to select there, but the widget needs to be left as the default value. Try that and see if it's of any help.
> 0 votes

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


title: FAPI Fivestar settings in custom form

text:
# Question
Title: FAPI Fivestar settings in custom form
I have a multistep form with mforms in forth step my form have fivestar field from a review node content type. All fivestar field display option are set to basic, but fields are displaying differently.

I tried to change the display widget in my module, with no luck. If i try to change the widget it returns to defaults.

Any suggestion are welcome. thx

```
function _reviewform_step4(&$form_state, &$next_step, $params) {

    $form = array();

    //attaching existing content type fields
    $review = new stdClass();
    $review->type = 'review'; //content type

    field_attach_form('node', $review, $form, $form_state);

    foreach ($form_state['field'] as $field) {
        if ($field['und']['field']['type'] == 'fivestar') {
            $field_name = $field['und']['field']['field_name'];
            // not working
            $form[$field_name]['und'][0]['rating']['#settings']['widget']['name'] = 'flames';
            $form[$field_name]['und'][0]['rating']['#settings']['widget']['css'] =     'sites/all/modules/fivestar/widgets/flames/flames.css';
            // not working to
            $form[$field_name]['und'][0]['rating']['#widget']['name'] = 'flames';
            $form[$field_name]['und'][0]['rating']['#widget']['css'] = 'sites/all/modules/fivestar/widgets/flames/flames.css';
        }
    }

```

# Answer
Finally i used another concept. Instead of attaching all field with `field_attach_form()` i used

`field_info_field()`, `field_info_instance()` and `field_default_form()` to attache field one by one. Here i could override the instance widget settings.

```
 $rel_field = field_info_field('field_reliability');
 $rel_instance = field_info_instance('node', 'field_reliability', 'review');

 $rel_instance['widget']['settings']['widget']['fivestar_widget'] = drupal_get_path('module', 'fivestar') . 'widgets/flames/flames.css';

 $my_reliability = field_default_form('node', $review, $rel_field, $rel_instance, LANGUAGE_NONE, array(), $form, $form_state);
 $form['field_reliability'] = $my_reliability;

```
> 0 votes

# Answer
I am not familiar with mforms, but I see a few potential issues:

1) your form doesn't have a standard signature ($form, &$form\_state, ...). I obviously can't see how you're calling it, but this is not a typical thing to do.

2) when getting the path of the css, you should be using drupal\_get\_path https://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7#attached

3) widget is not a property of #settings
> 0 votes

---
Tags: 7, forms
---


# Question
Title: How do I get the generated HTML ID of a form element?
I have fields called

* 'title'
* 'field\_article\_summary'

The HTML IDs of the form elements are

* edit-title
* edit-field-article-summary-und-0

Is there a way to programmatically get these HTML IDs? (without writing the code myself to do it - Drupal must have something that is creating them)

# Answer
> 2 votes
I know this is two years late but for anyone looking back at this, a way to get the element IDs is to use Drupal Form API's `#after_build` attribute to add a callback once the form has rendered.

```
$form['#after_build'] = array('mymodule_afterbuild'); // The callback can be called anything.

```

Then your function would look something like:

```
function mymodule_afterbuild(&$form, $form_state) {
  // Get the element ID.
  $id = $form['title']['#id'];
  // Then do something, such as passing it into Drupal settings to access with Javascript.
  drupal_add_js(array('mymodule_js_settings' => array('title_id' => $id)), 'setting');
  return $form;
}

```

Edit to say that the `#after_build` attribute can be used on individual elements in a form like so:

```
$form['title']['#after_build'] = array('mymodule_afterbuild');

```

This actually makes it easier to get the IDs, especially if you're using fieldsets, field collections or other complex field data structures.

# Answer
> 1 votes
Drupal uses the following two functions to prepare HTML classes and IDs:

* `drupal_html_class()`, for generating a valid class name for an element
* `drupal_html_id()`, for generating a valid ID for an element. This method also guarantees that the returned ID is unique.

---
Tags: forms
---


# Question
Title: How to migrate nodes from a dev site to a production site?
I have a staging site and a production site.

For an error some nodes was updated on the production site and now I have to update it but, if I will do that I will lose the production site changes.

What is the best \[and faster\] approach to migrate some nodes from production to staging before migrate staging to production?

# Answer
> 1 votes
Sounds like Node Export to export your nodes from dev and then re-import them on your live site.

Node Export provides several ways to export nodes:

* Through a tab that appears on the node page.
* Using update options on the Content page.
* In a command line using Drush.
* Using the Features module.
* Using the Views Bulk Operations module.

and the Node export package comes with the following formats:

* JSON
* Drupal var export
* Node code
* CSV
* Serialize
* XML

---
Tags: nodes, importing-exporting, migrations
---


# Question
Title: Define a resource of Service module, But 'access callback' cannot work
This following is my resource:

For clearly read, I delete some line.

```
/**
 * Implementation of hook_services_resources().
 */

function baidu_push_services_services_resources() {
  $resources = array();

  $resources['message']['actions']['send'] = [
    'file' => array(
      'type' => 'inc',
      'module' => 'baidu_push_services',
      'name' => 'baidu_push_services',
    ),
    'access callback' => '_message_access',
    'callback' => 'baidu_push_services_send',
    'args' => array(
      array(
        'name' => 'uid',
        'type' => 'string',
        'source' => 'data',
        'optional' => FALSE,
      ),
  ];

  return $resources;
}

```

In order to test my `'access callback'` function will be invoked, I always return `FALSE` in my `'access callback'` function:

```
function _message_access($op = 'view', $args = array()) {
  return FALSE;
}

```

But when I try to use `curl` command line to test with no SESSION and no Token, but It work!(return the right result to me), Did that mean `'access callback'` not be invoked?

So I try to use `drush cc all` to clear cache, But still above problem.

# Answer
> 0 votes
Is your access callback in the same file? If not, you'd have to add: "access callback file" to your definition, and point to it.

I'd also clear cache within Drupal, as I've seen drush cc all not always clear all caches.

Also, I'd name-space your access callback function, as it could be conflicting with something else in the system. \_message\_access is a pretty generic name. You should rename it to: \_baidu\_push\_services\_message\_access().

Otherwise, your syntax looks correct.

Or, if you solved your issue, perhaps post it in here, to help others.

---
Tags: users, services
---


title: Drupal commerce price markup field

text:
# Question
Title: Drupal commerce price markup field
I need to calculate product sell price as gross price * markup (i.e. 1.4) Gross price is stored in field\_data\_commerce\_price table (standard commerce price field). Markup value should be associated with every single product, so I can manage it with views using filters and VBO. I have many product types, so maually created markup field is not a good solution.

Is there any out-of-the-box solution?

and if not:

What is the best way to add new product field using API? (should be added by default for all product types)

# Answer
If you need a per product price modificator, your best solution is to have a field with this information, you can probably use a normal numeric field for this purpose.

You've got many examples on how to create a field using the API, for example, drupal commerce itself adds a price field every time a product type is generated by using hook\_modules\_enabled hook.

```
/**
 * Implements hook_modules_enabled().
 */
function commerce_product_modules_enabled($modules) {
  commerce_product_configure_product_fields($modules);
}

```

Then in this function

```
function commerce_product_configure_product_fields($modules = NULL) {
(...)
      // Loop through and configure the product types defined by the module.
      foreach ($product_types as $type => $product_type) {
        commerce_product_configure_product_type($type);
      }

```

Next

```
/**
 * Ensures a base price field is present on a product type bundle.
 */
function commerce_product_configure_product_type($type) {
  commerce_price_create_instance('commerce_price', 'commerce_product', $type, t('Price'), 0, 'calculated_sell_price');
}

```

And finally

```
function commerce_price_create_instance($field_name, $entity_type, $bundle, $label, $weight = 0, $calculation = FALSE, $display = array()) {
  // Look for or add the specified price field to the requested entity bundle.
  commerce_activate_field($field_name);
  field_cache_clear();

  $field = field_info_field($field_name);
  $instance = field_info_instance($entity_type, $field_name, $bundle);

  if (empty($field)) {
    $field = array(
      'field_name' => $field_name,
      'type' => 'commerce_price',
      'cardinality' => 1,
      'entity_types' => array($entity_type),
      'translatable' => FALSE,
      'locked' => TRUE,
    );
    $field = field_create_field($field);
  }

  if (empty($instance)) {
    $instance = array(
      'field_name' => $field_name,
      'entity_type' => $entity_type,
      'bundle' => $bundle,

      'label' => $label,
      'required' => TRUE,
      'settings' => array(),

      // Because this widget is locked, we need it to use the full price widget
      // since the currency option can't be adjusted at the moment.
      'widget' => array(
        'type' => 'commerce_price_full',
        'weight' => $weight,
        'settings' => array(
          'currency_code' => 'default',
        ),
      ),

      'display' => array(),
    );

    $entity_info = entity_get_info($entity_type);

    // Spoof the default view mode and node teaser so its display type is set.
    $entity_info['view modes'] += array(
      'default' => array(),
      'node_teaser' => array(),
    );

    foreach ($entity_info['view modes'] as $view_mode => $data) {
      $instance['display'][$view_mode] = $display + array(
        'label' => 'hidden',
        'type' => 'commerce_price_formatted_amount',
        'settings' => array(
          'calculation' => $calculation,
        ),
        'weight' => $weight,
      );
    }

    field_create_instance($instance);
  }
}

```

So you in summary can use hook\_modules\_enabled to react and loop the product types and create your field and instance. Another examples of this procedure can be found in commerce recurring, commerce discount, commerce coupon and more.
> 3 votes

---
Tags: commerce
---


# Question
Title: Results in view page with search api having multiple duplicate result
I am in a dilly of a pickle. I have a view that returns indexed content types. The problem is that the view is returning multiple instances of the same content. All of these are indexed nodes.

I read about someone else having the same problem here: Results in view page having multiple duplicate result They say you can use hook\_views\_pre\_render() in your template.php file to filter the extra content types out of your view.

Specifically the article said to

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

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

    $view->result = $new_view_result;
  }
}

```

This did not work for me. There was no $row-\>nid property. I think this is because they are using regular nodes and I am using indexed nodes.

Here is an example of my "$row printed out. (from $row above)

```
object(stdClass)[489]
      public 'entity' => int 4
      public '_entity_properties' =>
        array (size=2)
          'search_api_relevance' => string '1' (length=1)
          'search_api_excerpt' => string '' (length=0)

```

I altered this to try and filter by the property on "$row" called entity, which holds the id of the indexed item.

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

  if ($view->name == 'search_the_mangroves') {
    $count = 0;
    foreach ($view->result as $row) {

        if (!in_array($row->entity, $used_nids)) {

          $new_view_result[$count] = $row;

          $used_nids[$count] = $row->entity;
          $count++;
        }
    }

    $view->result = $new_view_result;
  }
}

```

Indeed this does filter out the extra content. I know this because in template.php I printed it out to be sure, but when I set the view to use the new content ie: $view-\>result = $new\_view\_result; I get no content type back from the view. Any idea what might be the issue?

Please help me.

Sincerely,

David Pugh

PS: if you need any more info, let me know.

# Answer
> 1 votes
I solved my issue. Turns out the filter TEMPLATE\_views\_pre\_render function I programmed in was working, the problem was in the template it's self. I had tried to solve this problem on the template before trying this issue. Before I was trying to only allow $row 1 to return, which didn't solve my problem. I then tried the \_views\_pre\_render function, and saw that it was filtering but my view was not showing any data. That is because only one row was being returned due to the \_views\_pre\_render function, but the only row being returned was row #0, and in the template below I was specifying to only show row 1.

So, in conclusion, if you have views with search api and find that

```
<div class="row-fluid container-folio">

        <div class="thumbnails">
        <?php $lastItem = 0;?>
            <?php foreach ($rows as $row_number => $columns): ?>
                <?php if($row_number == 1):?>
                <?php $array = array();?>
                <?php foreach ($columns as $column_number => $item): ?>

                    <?php if($item != null && $item != "" && strlen($item) != $lastItem):?>
                        <div class="span3">
                            <div class="thumbnail2">
                                <?php print $item?>
                            </div>
                        </div>
                        <?php $lastItem = strlen($item) ?>
                    <?php endif ?>

                <?php endforeach; ?>
                <?php endif ?>
            <?php endforeach; ?>
        </div>
    </div>

```

So, in conclusion, if you have views with search api and find that the solution listed here, Does not work for you, then your data returned to the \_views\_pre\_render function is probably different due to your search api, and you should follow my BootstrapBlocks\_views\_pre\_render function above, and you should be filtering out the duplicates.

# Answer
> 0 votes
I recently found that for the Search API I had set under "Use As" Search keys

I changed this to Search filter and the duplication problem went away. This seems like a bug because using the search string as a key (breaking up the words and searching with each independently) should not have caused a duplication issue.

---
Tags: 7, views
---


# Question
Title: How do you sql-sync a site with multiple databases?
I have a site that uses two databases. I would like to sql-sync both of those databases to the development version of the site. Is this possible?

```
// Default
drush sql-sync @prod @dev

// Optional?
drush sql-sync @prod @dev --database=my_other_db

```

# Answer
```
drush sql-sync @prod @dev --source-database=my_other_db --target-database=my_other_db

```
> 3 votes

---
Tags: drush
---


# Question
Title: Drupal 7 views 3 add custom filter handler for an existing field
How can you implement custom filter handler for an existing field in Views 3? With hook\_views\_data() you can expose a new table to views but how can you alter the handler for an existing field?

# Answer
> 4 votes
To add a Drupal 7 views custom filter handler for an existing field, you should implement the following hooks.

```
//in yourmodule.module
/**
 * Implements hook_views_api().
 */
function yourmodule_views_api() {
  return array(
    'api' => 3,
  );
}

// in yourmodule.views.inc
/**
 * Implements hook_field_views_data_alter().
 */
function yourmodule_field_views_data_alter(&$result, $field, $module) {
  if($field['field_name'] == 'field_your_existing_field'){
    $name = $field['field_name'];
    foreach ($result as $table_name => $table_data) {
      if (isset($table_data[$field['field_name']]['field'])) {
        $result[$table_name][$field['field_name'] . '_value']['filter']['handler'] = 'your_custom_handler_in_separate_inc_file';
      }
    }
  }
}

//your custom handler class in separate file
class your_custom_handler_in_separate_inc_file extends existing_handler_class{
// your code goes here
}

```

//Don't forget to add your\_custom\_handler\_in\_separate\_inc\_file.inc file in your module's .info file like.

```
files[] = your_custom_handler_in_separate_inc_file.inc

```

---
Tags: hooks, views
---


title: how to add content to a menu

text:
# Question
Title: how to add content to a menu
I want to publish a node to a custom menu page like "people" rather than the front page "Home." I tried many ways, but I cannot deal with this matter.

Could somebody tell me how to do it?

# Answer
> 0 votes
Have you reviewed the standard method of creating menus and adding nodes to menus? Take a look at Working with Menus.

# Answer
> 0 votes
you can specify a menu item for this node when you edit the node under the "Menu settings" when you click on "Provide a menu link" it will allow you to provide menu link title where you can specify like "people" and you can choose parent menu item of this menu item. Under "publishing options" you can uncheck " Promoted to front page" option to prevent this node being published at front page.

---
Tags: nodes, routes
---


title: hook_form_alter to create table field

text:
# Question
Title: hook_form_alter to create table field
I created a form which takes user input for fields: title, link, date and description, however I have another field which is guid and it cannot be user created. This field needs to be created with hook\_form\_alter() which takes the user inputted link and concatenates a string to the front and then return it to the submit handler for db\_insert. How can I go onto doing this? here is my submit handler

```
function rss_list_creator_form_submit($form, &$form_alter) {
//$GUID = returns GUID from hook_form_alter()
$query = db_merge('rss_table')
->key( array('GUID' => $GUID))
->fields( array(
'title' => $form_state['values']['title'],
'link' => $form_state['values']['url'],
//'GUID' => $GUID,
'date' => $form_state['values']['date'],
'description' => $form_state['values']['description'],
))
->execute();
}

```

\**I solved my problem, since I have two forms available I needed to enclose the code in a switch statement. Here is the code block:

```
function rss_list_form_alter(&$form, &$form_state, $form_id) {
 switch ($form_id) {
  case 'rss_list_creator_form':
  if(isset($form_state['values']['url'])){
    $guid = 'tag:news.google.com,2005:cluster=' . $form_state['values']['url'];
  }
  $form['guid'] = array(
    '#type' => 'hidden',
    '#default_value' => !empty($guid) ? $guid : '',
  );
  break;
 }
}

```

# Answer
> 0 votes
you can try with hidden field. You can make #guid field a hidden field. in your hook\_form\_alter() #guid initially will hold the default value to empty on submission, you can make #guid fields value to whatever you want to make.

```
funciton mymodule_form_alter(&$form, &$form_state, $form_id){
  if(isset($form_state['values']['url']){
    $guid = 'extra string' . $form_state['values']['url'];
  }
  $form['#guid'] = array(
    '#type' => 'hidden',
    '#default_value' => !empty($guid) ? $guid : '';
    );
}

```

---
Tags: forms
---


# Question
Title: Expand +/- button for taxonomy display in a page
I've a taxonomy with years as its terms. It has some content within each terms. Now, I want to display the terms in a list like structure with a `+` as its suffix. So, when a user clicks the `+` button, the content within the terms will be displayed as expanded.

The taxonomy term list should appear as below

I'm using Drupal-7, tried to install `Advanced book block module`, but it works with drupal-6.

Thanks in advance..

# Answer
> 2 votes
You want to try to use Views Accordion:

> Views Accordion provides a display style plugin for the Views module. It will take the results and display them as a JQuery accordion, using the first field as the header for the accordion rows.
>
> For Drupal 7 the module integrates the jQuery UI Accordion plugin as a views style plugin. You can configure the options provided by the jQuery UI plugin.
>
> For Drupal 6 the module used it's own jQuery code, so a different set of features is available for D6.

Views can override the default taxonomy pages, or you can try to create your own grouped taxonomy listing which uses this display plugin.

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


# Question
Title: Exporting a group of pages as a single or multiple PDF programatically
I would appreciate any pointers on this problem.

I have a site which have a set of pages with a given content type, I would like to take all these pages and generate a single (if possible) PDF with the content of each page.

I'm able to write some PHP code but I'm not sure where to start or what modules would help me with this issue. I have checked other answers but they talk more about having an option to click and export a single page where I want to export a dozen/hundreds of pages.

Thanks

# Answer
> 0 votes
I think your best choice here is Views Bulk Operations, you can create a view that lists your content and add the filters and fields you want and then generate the pdf using one of the modules for that matter, such as Views PDF or the Print module. You could generate actions that will be executed by the Bulk operations, one option to do this is to use Rules and Rule sets that are automatically exposed as VBO actions.

You've got a screencast on how to do this in https://www.youtube.com/watch?v=PszjYSq7xQQ and step by step here: http://blog.hsl.virginia.edu/drupalpress/views-pdf-vbo-rule-sets-thousands-of-custom-forms/

---
Tags: importing-exporting, files
---


title: Memcached - Saving Custom Array

text:
# Question
Title: Memcached - Saving Custom Array
I have the memcache module installed on Drupal 7. While it works fine I would like to implement some custom caching in some of my modules. For example, if I want to store the array:

```
$data = array('hi'=>1,'bye'=>2);

```

I can normally do the following:

```
$memcache_obj = memcache_connect('memcache_host', 11211);
memcache_set($memcache_obj, 'var_key', $data, 0, 30);

```

How can I do the equivalent in Drupal using the memcache module. I am trying to avoid having to declare the $memcache\_obj each time and just use the one designated by the module.

# Answer
> 2 votes
With Drupal you are not supposed to manage the cache backend by yourself. Once memcached is set as your cache backend, you can just use the cache functions cache\_set(), cache\_get(), etc. and this data will go to cache.

---
Tags: caching
---


# Question
Title: CKeditor: Allow choosing CSS classes from a select menu in dialogs
The idea is to make it easier for content managers, restricting them to choose a CSS class between a preconfigured list.

This feature is already available using the WYSIWYG module (see screenshot https://groups.drupal.org/files/ckeditor-css-config.png) but not using the CKEditor module.

I'm not sure if there is already a contrib solution for this (based on http://docs.cksource.com/CKEditor\_3.x/Developers\_Guide/Styles for example).

What would be the best approach?

# Answer
> 1 votes
You can specify a custom "ckeditor.styles.js" editing the profile \> CSS \> Predefined styles and also the Predefined Styles Path fields.

Additionally, you can override any other CKEditor configuration in Advanced Options \> Custom JavaScript configuration

---
Tags: wysiwyg
---


title: Scald get usage for an atom

text:
# Question
Title: Scald get usage for an atom
In Drupal 7 with the Scald, is it possible to get the usage for a given atom, for example the nodes which are referencing it?

# Answer
> 1 votes
There is a module for that https://www.drupal.org/sandbox/pascalt/2128697. It also has Views integration.

---
Tags: 7, scald
---


# Question
Title: Calling a grandparent JS function that includes jquery from a nested iFrame. D7
I'm calling the grandparent\_func from a second-level nested iframe like so. This works in a non-Drupal environment, but am getting the following errors when running in drupal. (yes. I did remember to include the jquery file ;-)

```
parent.parent.grandparent_func( Date.now(), Date.now());

```

ERRORS:

For the following, I get a "TypeError: $ is not a function" error

```
<script>
    function grandparent_func(){
        $("#fancy_regit_link").attr("href", "/my/actual/path");
        $("#fancy_regit_link").trigger('click');

    }
</script>

```

So, I enclosed jquery like so to make it drupal-friendly and get: TypeError: parent.grandparent\_func is not a function

```
<script>
(function($) {
    function grandparent_func(){
        $("#fancy_regit_link").attr("href", "/my/actual/path");
        $("#fancy_regit_link").trigger('click');

    }
})(jQuery);
</script>

```

For good measure, I double enclose it with jquery's ready function. TypeError: parent.grandparent\_func is not a function

```
<script>
(function($) {
    $( document ).ready(function() {
        function grandparent_func(){
            $("#fancy_regit_link").attr("href", "/my/actual/path");
            $("#fancy_regit_link").trigger('click');

        }
    });
})(jQuery);
</script>

```

Any thoughts?

Thanks.

# Answer
> 0 votes
Introducing a closure around the whole function (as in your 2nd and 3rd examples) will take it out of the global scope, so it won't be available on the `window`, and subsequently the iframe's `parent` (which are the same thing).

What you're looking for is more like:

```
function grandparent_func() {
  (function($) {
    $("#fancy_regit_link").attr("href", "/my/actual/path");
    $("#fancy_regit_link").trigger('click');
  })(jQuery);
}

```

That makes sure `grandparent_func` is global, while still providing you the jQuery object.

---
Tags: javascript
---


# Question
Title: Result accessibility based on field value for specific group
Is there a way to hide nodes or results if it has field "restricted" type bool with value 1 if the logged in user not in admin group without writing custom code. i could do that with views hooks like "hook\_views\_post\_execute" with writing custom code but it will decrease the performance because i will load the node field in "foreach", so is there module can handle that from the back end !?

# Answer
> 0 votes
The field permissions module lets you assign permissions to individual fields.

# Answer
> 0 votes
This helped me better as its global solution for the view i want to hook.

```
function rcreee_helper_views_post_execute(&$view){
$views_name = array('country_profile_item_energy_efficiency',
                    'country_profile_item_renewable_energy',
                    'country_profile_item_fuel_prices',
                    'country_profile_item_power_sector',
                    'country_profile_item_energy_system_overview'
                    );
$restricted_groups = array(3=>'administrator',9=>'Premium Registered');
global $user, $restricted_groups;
$has_access = count(array_intersect_key($restricted_groups , $user->roles));
if($has_access<=0){
    if(in_array($view->name,$views_name)){
        foreach ($view->result as $result_k => $result_v){

            if(isset($result_v->_field_data['nid']['entity']->field_visibility)
                && $result_v->_field_data['nid']['entity']->field_visibility['und'][0]['value']==1)
            {
                unset($view->result[$result_k]);
            }
        }
    }

}

```

}

---
Tags: users
---


# Question
Title: How do I get navigation menu on top with narrow viewport?
I'm running Drupal 7.28 with Zen 7.x-5.5. In the default setup, there is a region on the right side named "First sidebar" which contains a block named "Navigation". I have put my navigation links there. When shrinking the width of the browser to see how my site will be rendered on a mobile the navigation block gets positioned at the bottom of the page.

I want the navigation to be at the top in a mobile scenario, ideally with a bootstrap-esque collapsed menu. How can I achieve this?

# Answer
1. @media width queries in CSS http://css-tricks.com/css-media-queries/
At a certain width, you could use a different positioning tactic, forcing it up top.
2. Via Javascript, checking against: window.innerWidth or body .clientWidth
Many things you could do here, from changing CSS rules, to actually moving it in the DOM.
3. Using a Drupal module for responsive menus like: https://www.drupal.org/project/responsive\_navigation or https://www.drupal.org/project/responsive\_menus
> 0 votes

---
Tags: 7, blocks, theming
---


# Question
Title: Entityform - "The form has become outdated." error
I have an entityform that appears on a page, for some reason the form will not submit ...

```
// implement hook_menu

function foiagen_menu() {
  $items['node/%node/foiagen'] = array(
    'title' => 'Foia Generator',
      'description' => 'A foia generator form.',
      'page callback' => 'drupal_get_form',
      'page arguments' => array('foiagen_form', 1),
      'access callback' => TRUE,
  );
return $items;
}

// embed the form (it's an entityform).

function foiagen_form($form, &$form_state) {
  module_load_include('inc', 'entityform', 'entityform.admin');
  $entity_form_name = 'foia_generator';
  $render_estimate_form =
    entityform_form_wrapper(entityform_empty_load($entity_form_name), 'submit', 'embedded');
  $form['foiagen'] = $render_estimate_form;
  return $form;
}

function foiagen_form_validate($form, &$form_state) {
}

function foiagen_form_submit($form, &$form_state) {
}

```

I have tried to wrap my head around this solution but cannot figure out where, once my form is rendered, filled and the submit button pressed the 'update' occurs that makes the input void...

I have seen the comment here and tried adding

```
 $form['#token'] = NULL;

```

to my 'function foiagen\_form' that does circumvent the 'The form has become outdated.' error but leads to a blank page. Indicating that perhaps something else altogether is malfunctioning.

> following direction from answer came up with this:

```
function foia_generator_form($form, &$form_state) {
  form_load_include($form_state, 'inc', 'entityform', 'entityform.admin');
  $entityform = entity_create('entityform', array(
    'type' => "foia_generator",
  ));
  $form = entityform_form_wrapper($entityform);
  return $form;
}

```

# Answer
> 1 votes
It looks like you may have a hook namespace collision with `hook_form()`.

Although that might only be called if you're defining a node type, it's probably worth using a more specific function name for your form builder (e.g `function foiagen_generator_form`). Also make sure you're returning the form build array (array of elements), and not the rendered form in your form build function.

---
Tags: forms, routes
---


# Question
Title: How do you switch a site's language by using GET variables? Is there a module?
Currently I'm using a module that displays a bunch of nodes on a single page.

And I also have translated content in different languages.

The core functionality to switch a sites language currently creates a prefix in the URL, but is there one for switching the language via a GET variable like www.example.com/node/8?lang=german?

# Answer
Use the Language Switcher module for multiple Language.

> Language Switcher for Drupal 7 is an enhancement for core language switcher block in local module. It's very useful for websites with multi-languages where you want to display content in different languages side-by-side
> 0 votes

# Answer
If you have any custom module installed in your Drupal site then I'd suggest to add 3-4 lines of code that can do this trick for you. Though you have to switch the language in the **hook\_init** function in your module. Just reducing the overhead of installing new module.

In your custom module you can override the default language global object,

```
/**
 * Implements hook_init().
 */
function CUSTOM_MODULE_hook_init() {
  if (isset($_GET['lang'])) {
    $lang_code = check_plain($_GET['lang']);
    // Get the list of languages present in site.
    $languages = language_list();
    if (isset($languages[$lang_code])) {
      // Overwrite the global language object.
      global $language;
      $language = $languages[$lang_code];
    }
  }
}

```
> 0 votes

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


title: Drupal 7 Members Directory Problem

text:
# Question
Title: Drupal 7 Members Directory Problem
I created a member directory using view and it works well but I tried enable "Exposed form". I changed "Exposed form in block" to Yes & also "Use AJAX" to Yes. I defined "Contextual filters" to " User: Name ". then I went to Blocks and Enabled the new block and edited Only the listed pages and put the path but nothing shows up there. here's my View : here's my block: final demo:

ok, I created that with Filter Criteria, now the search fields show up at the top of the view, how can i put them in sidebar of this view? final result:

# Answer
> 0 votes
You do not have any exposed filters. Under "Filter criteria" you need to define a filter which is exposed to the user. The block will then show up

EDIT You already set the exposed filters to be shown in a block in your views administration on the right side. Now you find a block with the exposed filters in your block administration page. Here you can set the visibility of the block - maybe just show the block under the path of this view.

---
Tags: 7, views, blocks
---


# Question
Title: How to pull node reference into view on a search index?
I'm wondering how to pull the node reference into a view based on a search index. I did this with my earlier product catalog by adding a relationship to the product referenced node, adding the node reference, and then rewriting my image's output as a link.

With the view set on my search index, I don't have the option to add a relationship to the referenced node, so I'm not sure where to pull the node reference from to link the images back to their product displays.

Any advice would be appreciated. Thanks in advance.

# Answer
A search API based view can just take fields and information which are put into the index. Go to the index settings page and add the reference field. Then you can add addtional fields and relations connected to the reference.
> 1 votes

---
Tags: nodes, search
---


title: Wrap form field

text:
# Question
Title: Wrap form field
I want to render a form element like this:

```
<div class="form-group clearfix">
  <label>Title: <span class="red">*</span></label>
  <div class="pull-left">
    <input type="text" placeholder="Title">
    <a href="javascript:void(0);" class="hint hint--right" data-hint="Tooltip text goes here!!!"></a>
  </div>
</div>

```

I have tried something like this:

```
$form['title']['#prefix'] = '<div class="form-group clearfix">';
$form['title']['#title'] = '<label>Title: </label>';
$form['title']['#attributes'] = array('placeholder'=> array('Title'));
$form['title']['#suffix'] = '<div class="pull-left"><a href="javascript:void(0);" class="hint hint--right" data-hint="Enter the title."></a></div></div>';

```

But it gives me:

```
<div class="form-group clearfix">
  <div class="form-item form-type-textfield form-item-title">
    <label for="edit-title">Title:  <span class="form-required" title="This field is required.">*</span></label>
    <input placeholder="Title" type="text" id="edit-title" name="title" value="" size="60" maxlength="255" class="form-text required uniqueness-processed">
  </div>
  <div class="pull-left">
    <a href="javascript:void(0);" class="hint hint--right" data-hint="Enter the title."></a>
  </div>
</div>

```

So you see, there a basic structural difference after it is rendered by Drupal. What am I doing wrong? It will be better if I can manage the structure through form api only and dont have to create a template page for this form.

Any suggestions?

# Answer
check it out this code:

```
$form['title']=array();
    $form['title']['#prefix'] = '<div class="form-group clearfix"> <label>Title: <span class="red">*</span></label><div class="pull-left">';
    $form['title']['#type']='textfield';
    $form['title']['#attributes'] = array('placeholder'=> array('Title'));
    $form['title']['#suffix'] = '<a href="javascript:void(0);" class="hint hint--right" data-hint="Enter the title."></a></div></div>';

```

May this will help you
> 2 votes

---
Tags: theming, forms
---


# Question
Title: Using drush to install multiple sites, how?
I'm executing the following commands in /var/www/html on a clean Ubuntu 14.04 installation:

```
drush dl --drupal-project-rename=Platform
cd Platform
drush site install standard -y --db-url=[mysql connection string]/drupal --site-name=Example1

```

This sets up the site and it's awesome (especially after fighting for two days with the web interface and silly errors).

But now I want to install a 2nd site on this installation:

```
drush site install standard -y --db-url=[mysql connection string]/drupal2 --site-name=Example2

```

I get an exception that says, "To start over, you must empty you existing database. To install to a different database, edit the appropriate settings.php file in the sites folder. To upgrade an existing installation etc. etc.".

Is it still trying to install to the original database, thus the reason why I'm getting this error? I created drupal2 prior to running this command, so there's an empty database that exists.

How would I go about fixing this error?

Is it possible to use 1 database for all sites with crush?

Note: Creating a subdirectory in sites and using the --sites-subdir option in the site install command seems to have worked. Not sure how to point my browser to the site or how to use one database yet, but baby steps!

# Answer
If you want to use 1 DB for multiple sites you should get https://www.drupal.org/project/domain. I haven't tried it yet, looks complicated to set up, so good luck =)

For pointing your site, this video might help, skip to 15:49 http://www.youtube.com/watch?v=Ea\_Tqd-NrC4 It doesn't cover diff root directories for diff domains tho.
> 0 votes

---
Tags: drush, multi-sites, installation
---


# Question
Title: Programmatically created field doesn't appear in Views fields
Here is my little module that adds "markup" field to commerce\_product table, but I can't select and display it in Views:

```
function comm_markup_schema_alter(&$schema) {
  $schema['commerce_product']['fields']['markup'] = array(
    'type' => 'float',
    'not null' => TRUE,
    'default' => 1,
    'description' => 'Price markup field',
  );
}

function comm_markup_install() {
  $schema = drupal_get_schema('commerce_product');
  db_add_field('commerce_product', 'markup', $schema['fields']['markup']);
}

function comm_markup_uninstall() {
  db_drop_field('commerce_product', 'markup');
}

function comm_markup_entity_property_info_alter(&$info) {
  $properties = &$info['commerce_product']['properties'];
  $properties['markup'] = array(
    'label' => t('Price markup'),
    'type' => 'decimal',
    'description' => 'Gross price multiplier (defines profit amount).',
    'schema field' => 'markup',
    'getter callback' => 'entity_property_verbatim_get',
    'setter callback' => 'entity_property_verbatim_set',
  );
}

```

UPD:

```
function comm_markup_views_data_alter(&$data) {
  $data['commerce_product']['markup'] = array(
    'title' => t('Price markup field'),
    'help' => t('Multiplier. Adds profit to the gross price.'),
    'field' => array(
      'handler' => 'views_handler_field_numeric',
      'click sortable' => TRUE,
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_numeric',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
  );
}

```

# Answer
> 1 votes
Unless you manually describe the new field to views, it won't know about it. You can do that with `hook_view_data_alter()`:

```
function MYMODULE_views_data_alter(&$data) {
  $data['commerce_product']['markup'] = array(
    'title' => t('Price markup field'),
    'help' => t('An amazing field which does something great'),
    // Add the rest of the definition here...
  );
}

```

---
Tags: views, entities
---


# Question
Title: Create a MySQL view table on one database but fill with results from another database
I have 2 databases: `myshop` (the Drupal db) and `myshop_migrate` (the Migrate db). To make things tricky - both databases reside on different AWS instances.

I need to create a `mysql view` on `myshop` to hold a `SELECT *` query from the `myshop_migrate` database.

Currently, I have:

```
db_set_active('myshop_migrate_db'); //reference migrate db
$query = db_query('CREATE OR REPLACE VIEW myshop_migrate_stock_commerce AS SELECT * FROM myshop_migrate.stock_commerce');

```
* but this just creates the VIEW table on the myshop\_migrate database (as the current active db is referencing myshop\_migrate)..

```
db_set_active(); //default drupal db
$query = db_query('CREATE OR REPLACE VIEW myshop_migrate_stock_commerce AS SELECT * FROM myshop_migrate.stock_commerce');

```
* This wont work because `myshop_migrate.stock_commerce` doesn't exist on the myshop database!

Completely lost on this. Can I somehow store the result of the SELECT * from myshop\_migrate in a variable? Switch the active db, create a view table on myshop, then import the variable into the table?

# Answer
> 2 votes
Since that view is only a SELECT on that table, try using a FEDERATED table instead.

I never had the chance to use it so far, but it should go like this:

```
CREATE TABLE myshop_migrate ( exactly like myshop table )
ENGINE=FEDERATED
DEFAULT CHARSET=same of myshop
CONNECTION='mysql://user@host:9306/myshop_migrated/stock_commerce';

```

where user and host are those of the remote server.

create it from phpmyadmin or mysql workbench, just to have additional options and hints that drupal can't give you.

---
Tags: migrations, database
---


# Question
Title: WSOD when trying to configure menu with many items
I have a menu with *many* nested/multi-lingual menu items (I don’t know the exact number, probably something around 2000-3000).

Whenever I try to visit its configuration page in the backend (`/admin/structure/menu/manage/menu-foobar`), I get a WSOD after some loading time.

The site is hosted on a shared webhost (PHP memory limit is at `256M`; max execution time at `120`), so I assume it might work to move to a more powerful VPS, but I wonder:

Is there any way to access the menu configuration page without moving to a better server or changing the site architecture (i.e., using several menus instead of one)?

I tried the **Menu Admin Splitter** module, but it didn’t help.

# Answer
> 1 votes
A fiddly **workaround**:

On the "list links" menu page, you can visit, rearrange, enable/disable, edit, and delete all menu items. Except for visiting the node, all this is possible from a single menu item’s edit page.

But how to access the menu item edit page without being able to access the parent’s menu page listing all those items?

1. Visit the node whose corresponding menu item you want to edit.
2. Open its HTML source code.
3. Search (`Ctrl`+`f`) for `active menu-mlid`. You’ll find a `class` value like `menu-mlid-218`. `218` is the menu item ID.
4. Visit `/admin/structure/menu/item/218/edit`.

---
Tags: 7, routes, performance, wsod
---


# Question
Title: How to lock a node from a certain role after changing state in workflow?
Workflow module lets you set who can change a certain state to what state. What modules can I use to be able to prevent a certain role from editing a node that is in a specific state?

Ex: if a node has been approved and is in Approved state, it should be final and can't be edited anymore by content authors.

# Answer
This can be accomplished using Workflow Access submodule in Workflow.

Steps:

1. Enable Workflow Access submodule (assuming Workflow is already used like in OP)
2. Go admin/config/workflow/workflow/manage
3. Click the **access** link on the workflow that applies to the node type
4. Uncheck the roles that should not be able to edit in the given listed states

When I posted this info, I was using Workflow (and the submodules) version 2.3 and the author could still edit the node after performing the steps above. After updating to 2.4 today, it has worked fine.
> 0 votes

# Answer
For this you should have to implement hook\_node\_grants and hook\_node\_access\_records. It look something like that -

```
 /**
  * Implement @hook_node_grants
  */
 function MODULENAME_node_grants($account, $op) {

  $grants =array();
  $grants['Node_Edit_Permission_Content'][]=array($account->uid);
  $grants['Node_Edit_Permission_OtherRole'][]=array($account->uid);
 return $grants;
}

/**
 * Implement @hook_node_access_records
 */
function MODULENAME_node_access_records($node) {

  $grants = array();

  if ($node->type == 'node_type') {
    $user_id_content = /* list of user id which you want to block */;

     // Revoke Permissions from these Users
    if (!empty($user_id_content ) {
      foreach ($user_id_content as $uid) {
        if (isset($uid)) {

          $grants[] = array(
            'realm' => 'Node_Edit_Permission_Content',
            'gid' => $uid,
            'grant_view' => 1,
            'grant_update' => 0,
            'grant_delete' => 0,
            'priority' => 0,
          );
        }
      }
    }

    $user_id_other_role = /* list of user id which you want to block */;

     // Grant Permissions from these Users
    if (!empty($user_id_other_role ) {
      foreach ($user_id_other_role as $uid) {
        if (isset($uid)) {

          $grants[] = array(
            'realm' => 'Node_Edit_Permission_OtherRole',
            'gid' => $uid,
            'grant_view' => 1,
            'grant_update' => 1,
            'grant_delete' => 0,
            'priority' => 0,
          );
        }
      }
    }
  }

  return $grants;
}

```
> 0 votes

---
Tags: users, workflows
---


title: Edit content before publishing

text:
# Question
Title: Edit content before publishing
How do I give an authenticate user the permission to edit some contents before publishing it. So currently he has the permission to edit it, but he has to publish it first and then he gets the edit button. I tried going to the edit url which is node/nid/edit, but it didn't work before publishing the content.

Any help?

# Answer
I think you need try this module: Workflow
> 1 votes

---
Tags: users, nodes
---


# Question
Title: How to export Views data in separate sheets/tables to Excel file?
I've two content types say Reports-1 and Reports-2. Using views I've displayed them as shown in the image. **Reports-2** is attachment for **Reports-1**.

I used Views Calc to display sum at bottom of the table. (**Total SUM**)

By using Views data export module I could able to export data to Excel format.

Right now the exported excel looks like follows.

But my question is is there any possibility to show the data in separate tables with headers as **Reports-1** and **Reports-2**? (like following image) to recognize the Reports. I need to display sum as well for Individual reports.

I'm also thinking to export views in different sheet of the same Excel. Is it possible?.

Can I do modifications on views-data-export tpl files. Is there any chance to render views output there? Any hints/suggestions!! ?

# Answer
> 0 votes
Finally I could able to resolve my issue using the PHPExcel module.

> The PHPExcel module allows developers to export/import data to/from real Excel files.
>
> The idea behind this module is to have a single module for handling the export or import of Excel files, instead of multiple modules handling specific cases.
>
> The module provides no functionality as-is (the .module file is as good as empty). The phpexcel.inc file must be included to use the export or import functions in your own module.

I've written a custom module using PHPEXcel Hooks (`hook_phpexcel_export()`) and exported views data to Excel file into different sheets (3).

Hope this helps someone. :)

# Answer
> 1 votes
You can do it by using Phpexcel

check out the above link.may it will help you. i have customised my excel and csv files using phpexcel and it works great their.

# Answer
> 0 votes
I guess you can't do that without extending the views data export module. Maybe have a look at the Sheetnode module which can edit and write Multiple Worksheets.

> Sheetnode integrates the JavaScript spreadsheet engine SocialCalc as a new node type in Drupal. SocialCalc was written by Dan Bricklin, co-author of the original VisiCalc spreadsheet app in 1979, and is used in the OLPC XO laptop and the SocialText Collaboration Platform.

It uses Apache POI for that so you will need to install Java and the PHP Java bridge.

Demo for multiple worksheets can be found here: Multiple worksheet demo

---
Tags: 7, views, importing-exporting
---


# Question
Title: Separate panels variants for 'edit' & 'add' nodes of same type
\[D7/Panels 3\]

I have two different panels layouts - one for editing, the other for adding nodes of the same content type ("Contact Details").

A panel page for overriding 'edit' pages exists in Panels (in code), which I have activated. I've made a variant which works for 'edit' pages, but it is also overriding the 'add' page with the same layout.

I've added a context of 'Node add form' with 'Contact Details' as the 'Node type'. Also added a selection rule:

**Node: type / Node add form is type "Contact Details"**

Both forms still appear in the same panel layout (the one for 'edit' pages).

Help much appreciated :)

# Answer
Try using `String: URL path` in variant Selection Rule.

**Edit path:** `"node/*/edit"`

**New path:** use your content type path (`node/add/your-content-type`)
> 2 votes

---
Tags: panels, 7
---


# Question
Title: what is the difference between hook_insert and hook_node_insert
what is the difference between hook\_insert and hook\_node\_insert? How could I use hook\_insert in place of hook\_node\_insert or vice versa

# Answer
The difference is stated in the hook\_insert documentation:

> This hook is invoked only on the module that defines the node's content type (use hook\_node\_insert() to act on all node insertions).

This hook is only fired on the module that defines its own content type for nodes of that content type, so you only should use it in this case for your own content types.
> 3 votes

---
Tags: 7
---


# Question
Title: Trying to pull phone number and combine it with carrier, cannot find phone number variable
I am running a website that has users input phone number and carrier when they register. Using the Phone module to collect the phone number and a select list field to collect the carrier. How can I retrieve these variables so that I can combine them to make a phone email address (eg. 123456789@vzwtxt.com)

I have a plan for combining them I just need to know how to get the phone number out of the array based on the uid so that I can combine it with the carrier.

Thank you!

# Answer
> 0 votes
if you don't already have it, get DEVEL module. In your tpl file, use dpm($account); this will output the array. From there you can determine the proper element names.

it would be $field\_phone\_number\[0\]\['value'\]; a trick to figuring out the exactly lineage is to progressively use dpm, ie: dpm($account), dpm($field\_phone\_number), dpm($field\_phone\_number\[0\]), etc. this is an easy one, but arrays can get in depth and complicated within Drupal

Devel:

> Helper functions for Drupal developers and inquisitive admins. This module can print a summary of all database queries for each page request at the bottom of each page. The summary includes how many times each query was executed on a page (shouldn't run same query multiple times), and how long each query took (short is good - use cache for complex queries). Also a dprint\_r($array) function is provided, which pretty prints arrays. Useful during development. Similarly, a ddebug\_backtrace() is offerred.

---
Tags: users
---


# Question
Title: Can I work with hook_user_login() directly within user.api.php?
Somewhat new to Drupal... this is probably a softball for all you Drupal pros out there.

I need to update a custom table in the database each time a user logs into Drupal. I thought I'd be able to do this within user.api.php and specifically within hook\_user\_login but it's as if none of the code I've put in there works. To debug I added the following 2 lines to try to email myself details about $account and I never get that either.

```
$o = print_r($account, true);
mail("art@geigel.com", "Login Output", $o, "FROM: no-reply@geigel.com");

```

I've also gone into the Drupal admin area and saved the settings page for the modules thinking it was a Drupal caching issue related to its hooks. That didn't do it either.

Can someone tell me what I'm missing? I'd prefer to just take care of the database stuff here instead of creating an entirely new module and implementing the hook there.

Thanks in advance.

AG3

# Answer
The .api.php files are documentation only, they're never included in a request.

`hook_user_login()` can only be implemented in a module, so you'll need to write one for this.

It's pretty straightforward, the Module developer's guide will get you started quickly.
> 0 votes

---
Tags: hooks, users
---


title: Two views one page (sorting, etc)

text:
# Question
Title: Two views one page (sorting, etc)
I am sure this is just by design and not much can be done, but I figured i would ask anyway...

I have a couple views on a dashboard. Each can be sorted, but when I sort one by "Date Submitted" all the others follow suit, which is expected, but not desired.

Is there a way to disconnect the Views, so that query parameters bind to a single view instead of all on screen?

Just curious, Alex

# Answer
Yes, when you configure your view, if you edit the pager settings, there's a Pager ID that if you change it you'll get a different pagination for each view, you can sync some but others not and so on.
> 0 votes

---
Tags: views
---


# Question
Title: Drupal function to convert node into Json object
I would like to know if any drupal function is readily available which converts the node object into Json object so that i can return it in the menu callback function in Ajax call.

thanks, Ahmad

# Answer
> 1 votes
To return on menu callback function in Ajax call you can use drupal\_json\_output(), you can use this function as an example.

On that exampe you can see that you only need to call drupal\_json\_output() function with the object as the parameter, there's no need to return anything from your callback function.

If you need to convert the Drupal node object into JSON object to be returned on a function, you could consider to use drupal\_json\_encode()

# Answer
> 0 votes
Try: drupal\_json\_output($var = NULL)

---
Tags: 8
---


# Question
Title: How can I modify the arguments passed to a core hook?
Due to a recent update of Drupal core, I'm getting the following error:

> Notice: Undefined index: taxonomy\_term in taxonomy\_field\_formatter\_view() (line 1601 of taxonomy.module)

Now, this is caused because the core taxonomy hook `taxonomy_field_formatter_view()` has an argument called `$items` that expects an array of values that have two elements: `tid`, a numeric value, and `taxonomy_term` which is the taxonomy term object.

In the case of my code, each array in `$items` is missing the `taxonomy_term` element.

Now a simple fix would be to hack core and simply set `$item['taxonomy_term'] = taxonomy_term_load($item['tid'])` if it doesn't already exist. But of course, hacking core is a no-no so I'm trying to **find a way to catch the $items argument for `taxonomy_field_formatter_view()` before it is passed to this hook**.

What's the approach here? Would defining `hook_field_formatter_view()` in a custom module and fixing the `$items` argument work? Presumably not because the core hook is going to fall over first, so I'll need to modify it before it's passed into these hooks?

# Answer
Implement hook\_module\_implements\_alter and replace `taxonomy_field_formatter_view()` to your function.
> 1 votes

# Answer
I'd advise to use one of the Field formatter API hooks before modifying a Drupal core hook, even with `hook_module_implements_alter`, you might get unpleasant surprises if someone else is using it.

What I'd do is to prepare your items using hook\_field\_formatter\_prepare\_view and as it's passed by reference, it should arrive fine to your formatter\_view.
> 1 votes

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


# Question
Title: Where to change default translation language for drupal 7 while using entity translation module?
I'm doing some translations, but I'm not sure how to change the "original content" to english. I can't seem to find a setting to change it to english. Anyone knows where to go for this?

# Answer
You have to first delete your translations then you will be able the select another language under the dropdown box for the original content.
> 0 votes

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


# Question
Title: How to apply one AJAX to all form elements?
#ajax is

> used by: button, checkbox, checkboxes, image button, password, radio, radios, select, submit, tableselect, textarea, text\_format, textfield

Sadly, *form* is not on the list. But on one form, I need to apply ajax to all form elements. With possible exception of submit button, but it will be hidden if javascript works, so it is not an issue, literally all elements is OK.

Is there any neat way to do it?

Currently I'm writing something like this:

```
$ajax_code = array(
  'callback' => 'poll_choice_js',
  'wrapper' => 'poll-results',
  'method' => 'replace',
  'effect' => 'fade',
);

```

And then in each element:

```
  '#ajax' => $ajax_code,

```

But it will be easy to forget to add this line to some elements in future, so I'm looking for a way less prone to errors.

**Reason:** My wrapper is actually outside a form and is used for preview, I need to update preview every time *anything* changes. Form will never need to be submitted. Ajax will never change form elements.

# Answer
> 2 votes
I don't believe there's anything 'built in' for that, but a small recursive function would handle it:

```
function _MYMODULE_apply_ajax(&$element, $ajax) {
  $element['#ajax'] = $ajax;
  foreach (element_children($element) as $key) {
    _MYMODULE_apply_ajax($element[$key], $ajax);
  }
}

```

Where you apply this kind of depends what you need. You could add it at the end of the form function itself, but if there's a chance your form could be altered it would be best in `hook_form_alter()`. Either way just call

```
_MYMODULE_apply_ajax($form, $ajax_array);

```

---
Tags: forms
---


# Question
Title: Adding extra attributes to webform input element
I am looking to run javascript for a textbox on a webform. I am looking to add an extra attribute to my webform, but I am not sure how the webform is rendered . I was able to do that for my cck form using hook form alter but unable to do that for a webform.

Simply I have

```
<input type="text" maxlength="128" name="submitted[school_name_cancer]" id="edit-submitted-school-name-cancer" size="32" value="" class="form-text required" />

```

But I would like

```
<input type="text" maxlength="128" name="submitted[school_name_cancer]" id="edit-submitted-school-name-cancer" onkeyup="lookup(this.value);'" size="32" value="" class="form-text required" />

```

Thanks.

# Answer
see this Form API Quickstart Guide http://drupal.org/node/751826 to review how to build forms, know how a form is builded:

> The Drupal Form API provides sophisticated form techniques and also allows for almost unlimited possibilities for custom theming, validation, and execution of forms. Even better, ANY form (even those in core) can be altered in almost any way imaginable--elements can be removed, added, and rearranged.

if your javascript is for validate fields of your form, I guess that this answer (related with validations of fields) could be useful How do I create custom content types in drupal?
> 1 votes

# Answer
I post a solution to that issue at drupal.org, here is the link:

https://www.drupal.org/node/1462436#comment-8974109
> 0 votes

---
Tags: javascript, webforms
---


# Question
Title: Turn off revisions for content types that contain certain types of fields (e.g. Field Collection)
The Field Collection module does not support revisions. Yes there are lots of patches which are still under review. But what I want to do is create a module that on the node edit screen, queries the fields of the content type and removes the Revision Information tab (or disables the "Create new revision" checkbox) if the content type has one or more Field Collection fields. Any help on how which hook to use, how to query the fields of a node, and how to disable the revisions tab would be very helpful. This module needs to be applied to hundreds of sites.

**Thanks to pcambra, here is my module:**

```
function epc_no_revisions_for_fc_form_node_form_alter(&$form, $form_state) {

    $collection_fields = field_read_fields(array('type' => 'field_collection'));

    foreach($collection_fields as $FC){
        if(isset($form['#node']->$FC['field_name'])){
            $form['revision_information']['#access'] = FALSE;
            drupal_set_message("This node cannot accept revisions because it contains the following Field Collection: " . $FC['field_name'],'status');
        }
    }
}

```

**UPDATE:**

The above module didn't handle a fresh node where the fields had not yet been set. So I revised it to first load all the fields in the database and see if any belong to the bundle (content type) in question:

```
function epc_no_revisions_for_fc_form_node_form_alter(&$form, $form_state) {
    if(_epc_no_revisions_for_fc_test_for_fc($form['#node']->type)){
        drupal_set_message("Please note: This node cannot accept revisions because it contains a Field Collection",'status');
        $form['revision_information']['#access'] = FALSE;
    }
}

function epc_no_revisions_for_fc_node_presave($node) {
    if(_epc_no_revisions_for_fc_test_for_fc($node->type)){
        if($node->revision == 1){
            $node->revision = 0;
            drupal_set_message("No revision was created because the content type contains a Field Collection",'status');
        }
    }
}

function _epc_no_revisions_for_fc_test_for_fc($node_type){
    $fields = field_info_fields();
    foreach($fields as $field){
        if($field['type'] == 'field_collection'){
            foreach(array_shift($field['bundles']) as $content_type){
                if($node_type == $content_type){
                    return true;

                }
            }
        }
    }
    return false;
}

```

# Answer
You could use hook\_form\_FORM\_ID\_alter to alter your node forms of the content type (s) you need.

```
function my_module_form_node_form_alter(&$form, $form_state) {
  if ($form['#node']->type == 'my_content_type') {
    // Your code goes here.
  }
}

```

Now you need to know whether or not it has a field collection field on it. You can use one of the field api functions for this, for example, this will give you the field collections in your site:

```
$collection_fields = field_read_fields(array('type' => 'field_collection'));

```

Then you can check if your node has one of these to see if you disable the revision feature or not.

You can disable the checkbox appearance by adding an `#access` FALSE:

```
$form['revision_information']['#access'] = FALSE;

```

It's probably safer to repeat this operation and checks in hook\_node\_presave if that makes sense for your workflow.

Additionally, there are a couple of modules relevant to this issue, Jammer allows you to hide some specifics from the node creation form and so on, but nothing condition based. There's also Field SQL no revisions that will skip saving information for revisions, be careful because there's no come back from this one so you need to be very sure you're not using revisions for your fields in any other content type.
> 3 votes

# Answer
I might be missing something, but: Revisioning is a per content type setting, accessible at admin/structure/types/manage/ Assuming you really mean to turn off revisioning for content types which contain field collections (as opposed to the node you are editing contains field collection data), go there. admin/reports/fields helps you figure out where field collections are used.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: How to prevent node delete for a specific node?
I want to prevent a specific node from being deleted by anyone except admin. For this specific bundle there are two roles that have full access to the node: admin and manager. A manager can delete any nodes of this content type, but I want one specific node to be locked.

I tried hook\_node\_delete and it does not work as the delete hook for the specific content type (node) has already run by then.

I tried the Content Access module and setting of permissions per node, but then when I go to the specific node's edit page the 'delete this content' for the role manager is enabled and greyed out.

I also do not want to just remove the action from the edit form as the node can be deleted in a view bulk operation. Hence I need a catch all solution.

# Answer
I don't think there's a catch all solution.

---

On second though, you maybe can create a new content type, say node2, and set the permissions for that content type to admin only.

and if you will ever need more than one admin-only node, you'll have no problems at all.

however i have no experience whatsoever there :p

---

in hook\_menu\_alter change the 'access callback' for the "node/%nid/delete", since you need it only for a particular node ( say nid=120)

```
$items['node/120/delete'] = $items['node/%nid/delete'];
$items['node/120/delete']['access callback'] = 'custom_function';
unset($items['node/120/delete']['access arguments']);

```

this will prevent that node to be deleted directly.

then you need to remove the delete button from that node form edit (however i don't know the form name).

this should be enough and prevent the deletion "nicely", but you can use hook\_delete like pointed out in the other answer to catch everything and everything else that can't be prevented like that.
> 1 votes

# Answer
I haven't tested this out, so take it for what it's worth, but I would try hook\_delete.

The code for that one's really simple

```
function hook_delete($node) {
   db_delete('mytable')->condition('nid', $node->nid)->execute();
}

```

I would think wrapping the delete statement in a a permissions check should get you where you need to go.
> 0 votes

---
Tags: nodes
---


title: Assign terms to image field items

text:
# Question
Title: Assign terms to image field items
This is what I'm trying to achieve.

1) The website has a gallery page which is made from one node, so each time uploading new images to the gallery, you just edit this one node.

2) EVA is attached to the node page, so images are rendered via Views using EVA on that node page.

3) It all works great and everything. But it needs this feature that some of those images needs to be featured at the home page with a slideshow. So to achieve all that we can use Views and etc. But how do I filter out which images to show? All images cannot be shown.

4) So when uploading images to the image\_field it would be nice if you could somehow select (I was thinking tick/untick boxes for each item in the image field) which ones to show in the homepage slideshow.

5) To be more exact, I was thinking maybe you could somehow assign some taxonomy vocab called 'Featured' which would have terms 'Yes' and 'No'. So you tick 'Yes' to all images you want to be shown in the slideshow and then just apply those filters via Views.

But I cannot figure out how to do that part where you assign terms to image field items without writing custom modules, not a PHP guru, sadly. Also any other alternatives are welcome.

UPDATE: I came up with a nasty workaround by using image field Alt or Title fields for filtering out via Views, it does the job, but from SEO point-of-view this is wrong. I put 'featured' value in Alt field for images I want to show up on the homepage slideshow, but that's wrong from SEO position, because Alt field should contain unique titles for each images for search engines to read it. Tagging them all as 'featured' is misleading.

So that's what I'm looking for, would be nice if you could add tick boxes next to Alt and Title fields. I tried image\_field\_caption module, it adds custom textarea field next to Alt and Title, but has no Views support, and again, you need to write 'feature' for each image instead of ticking it.

All this makes more sense now though.

Cheers

# Answer
Use a field collection instead of the straight up image field. The field collection would have an image field and a term reference, plus maybe more things once you see its power. The trade off is that your views will become a bit more cumbersome to build, but only slightly.
> 2 votes

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


# Question
Title: Fix a constant width for first sidebar and second sidebar
I'm working on `Zero point Theme` in drupal 7. In my home page I've three blocks - `first sidebar`, `content` and `second sidebar` formatted as three columns. Here the width of first sidebar and second sidebar are equal and the content has its own width (I'm ok with that). There are some pages where I have only first sidebar and content.

Previously, I was facing a problem like if I go to other pages(other than home-page) the first sidebar's width will be increased. I don't like the view so I changed the `CSS`.

I gave a fixed width to the blocks by editing the CSS -

```
.block.themed-block{
                    width: 60%;
                   }

```

Now, the first sidebar and second sidebar has `constant width` in all pages.

My Issue is : when I go to other pages where I have only first sidebar and content page, the width of the first sidebar is reduced and the content part doesn't appear from where the first sidebar ends, it leaves some space between the first sidebar and the content part. It shows some odd effect. I want the content part to start from where the first sidebar ends. Is there any way to get rid of that.

Below, I share the screenshot of my Issue.

Highlighted rectangle part is the space, that I want to get rid of.

# Answer
> 1 votes
My guess, before your css editing, the index block filled that white space, right?

you changed the width of the sidebar's content, rather than the sidebar itself (which is a region, not a block)

i don't know of the zero point theme, but look for an outer class, like .sidebar, or .sidebar-first, and set the with of that.

---

i looked into that particular theme.

revert all the css editing and go to the theme settings, under "layout setting -\> sidebars layout" try using the 'fixed' options instead than the 'variable'.

---
Tags: theming, blocks
---


# Question
Title: What is the preferred way to delete la arge amount of data from a Drupal site?
We have a client site that currently has a very, very large data set in Drupal. We are working on generating a 'stripped' copy of the database to be used for testing new code by eliminating the bulk of the site content.

To this end, we need to periodically delete 40 million+ nodes and field collection entities from Drupal to strip down a copy of the production database so it can be used more readily on our staging and local development instances.

This is somewhat beyond what VBO or Bulk Delete (Nodes) or other similar contrib solutions can handle in a reasonable time, not to mention that many of the field collections are not on node objects. I suspect that using node\_delete\_multiple() and entity\_delete\_multiple() for millions of items may be a non-starter time-wise, even if batched through either the queue API or the batch API.

Is there any way to 'cheat' by TRUNCATING the field\_data\_\* and field\_revision\_\* tables in MySQL to speed the record deletions?

# Answer
> 0 votes
I'm not seeing any simple way to truncate (or truncate from X) a table like this. The tables that would contain field data would be all mixed up and not nicely sorted.

In this case I would;

* Start with a view that generated a list of node IDs based on your select criteria (content type, status, older than date published, etc)
* Write a custom module with a drush command
* Load the node IDs
* Either node\_delete($nid) OR...
* Examine what node\_delete() does and `delete * from {table} where nid= $nid`

The tables node\_delete() may touch will largely be dependant on your content types. node\_delete() will do the job, doing it my hand will take more time to prepare but may be faster to run. With the volume of records you're talking about a few milliseconds per delete may save a decent chunk of time.

---
Tags: nodes, entities
---


title: drupal as mobile app backend

text:
# Question
Title: drupal as mobile app backend
Im currently using drupal 7 + commerce for online sales and I have a phonegap app that creates orders. I want to use drupal 7 via a the services module to sync the app sales data with the online store. My concern is speed as drupal requires a full bootstrap for each service call. Is there another recomended way to access the drupal 7 commerce database directly that would perform the crud operations faster?

# Answer
Not sure if "faster" but I'd recommend the integration of Drupal Commerce and Phonegap (I'm guessing you're using DrupalGap already) if you're already using both: https://www.drupal.org/project/commerce\_drupalgap

You've got plenty of resources there to get started such as the Commerce Services module.

It's up to you to decide where you need or not a full bootstrap of your backend, I'm thinking you need it to get advantage of user access, permissions and consistency check in your order status, but it depends a lot on your app and where you're implementing the business logic. If you access the database directly, without any bootstrap is going to be faster, but the same way you build a drupal site, if you bypass Drupal to access directly to the database that'd be faster as well.
> 1 votes

# Answer
I don't think so, you'll always need a full boostrap to access Drupal data.

The fact that Drupal 8 is a RESTfull server should give a hint that is the good way to do it ;-)
> 0 votes

# Answer
This doesnt really help you for services, but if you have any custom data endpoints that you want your app to pull in you can use the High-performance JavaScript callback handler module.

It allows you to specify what parts of drupal you need to load to build your data, without loading the parts you don't need.

The module's README.txt file provides more detailed information on how to use it, but basically you are just implementing one additional hook to tell it what bootstrap level you want, what includes & modules you need loaded, etc.
> 0 votes

---
Tags: commerce, services, performance
---