# Question
Title: Is Node a superclass of all content type?
I have been trying to understand drupal 7 internals. It seems to me that the concept of node is like a superclass in OO languages. All other content types are the derived classes of Node.

Please let me know if this wrong. Thanks. DB

# Answer
> 2 votes
From drupal.org: An Introduction to Entities

> If you come from an OOD/P background and are trying to better understand what these key D7 concepts are, the following suggested mapping might help (albeit not strictly true from a purist’s perspective) :-
>
> ```
> An entity type is a base class
> A bundle is an extended class
> A field is a class member, property, variable or field instance
>     (depending on your naming preference)
> An entity is an object or instance of a base or extended class
>
> ```
>
> All these four OOD/P concepts are special in that they are serialisable (stored - e.g. to a database or file). Serialisation takes place via the Entity API.

---
Tags: nodes
---


title: Setting a date to be empty by default

text:
# Question
Title: Setting a date to be empty by default
I have an event dates field that allows the user entering content to put in a start and and end date. By default it just shows them the start date. If they check a box it shows an end date and they can fill that out. So far so good.

However, I'm noticing that if they don't check the box and don't put in an end date it auto-sets the end date to be the same as the start date. This is not what I want. I want the result to be empty (mainly for Views so I can set it to not display if its empty).

Any idea how to fix this?

# Answer
> 1 votes
You can change this under the field settings for your date field. If you edit your date field, you should see a "More Settings and Values" section:

You'll just have to set the default end date to "No default value"

---
Tags: nodes, datetime
---


# Question
Title: How to create inline node-add forms using a block with content type names
The following page setup is needed: A block (at the left, see image) with links to node-add forms, which open inline (the area at the right) in the current page.

The reason why the form needs to appear inline, is that this page is part of a group and the layout of the group and group menu and all must stay the same

I tried to create a Panel page variant for the node add form, but the minipanels that I use in node panels are not available there.

I thought about using an iframe, but that is not recommended generally, especially not for mobile use.

I can't find modules that are specifically suitable for this purpose, but I might have missed some.

What way could I accomplish this setup using javascript/jquery ?

# Answer
> 1 votes
Panels is definitely the way to go here.

1. Using Page Manager set up a URL with an argument, like `mypath/%node-type`
2. Set the argument to be `Node add form: content type`
3. In the content area you can rearrange the form how you like or just add the whole node creation form by using the elements under **form** in the add content screen
4. Make either a custom pane or a menu of links that point to the various node types:

* `mypath/article`
    * `mypath/event`
    * `mypath/document`
    * `mypath/video`

---
Tags: panels, javascript
---


# Question
Title: Drupal validation for nested field element
I have written some custom validation for each element in a form. I use the following method to display errors. It automatically highlights the required fields.

```
form_set_error('field_athletes_male', 'Athletes Male field is required.');

```

My problem is that there are nested element names like this:

```
 field_coaching_programme[und][0][field_organisation_delivered_by][und][0][value]

```

The validation message is shown successfully but the element is not highlighted.

# Answer
> 1 votes
Its working now, code as follows

```
form_set_error('field_coaching_programme][und][0][field_organisation_delivered_by', 'Organisation delivered by field is required.');

```

---
Tags: forms
---


# Question
Title: how to create hook for send email to profile2 type user
In my project there are two types of user.Using profile2 module i creates 2 profiles. 1) normal user 2) Lawyer

So i have to send promotion email to lawyer after registration. i created following rule.

1) Event \- After saving a new profile

2) condition \- user has roles

a\]After selecting they ask for **Data selector**. i don't know what i select for my lawyer account

b\]i select "lawyer" Roles

c\]match roles - all)

3) Event In event i select send-email

a\]email function $to - how i can put current user registration email

b\] body is static

c\] subject is static

I am really confuse. Can i create hook for send email to lawyer after registration.

# Answer
In condition `add data comparison instead of user role` if want to send mail only basis of profile type as below.

Edit:

In Action Section Select Send Main or Send Html Mail under System and follow as below png file.

This may help it..
> 1 votes

---
Tags: users
---


# Question
Title: Importing and filtering RSS feeds into nodes
I'm looking for the best way to import a feed, say BBC News, and filter through all the content so only articles containing a keyword are stored in the database. I'd like each item to be shown as a node of a specific content type and for it to be updated every given time interval. Is there a straightforward way to do this? I don't have much experience in PHP at all, so please be specific.

# Answer
The friendliest UI driven way to do this is probably with the Feeds module. Make your content type(s) using Drupal Fields and use Feeds to ingest the content via Cron or job\_scheduler module. You might still need to code a simple module to do some things ... but it would require little coding I think.

The less friendly way would be the Migrate module (has a status-indicator UI, but no helpful UI for creating/moving fields). You'd end up coding alot of php to rip through XML and create X nodes in some content type. But, you'd still get a way to import/update/rollback items from RSS. They do have XML "News" examples I think in the Migrate modules example folder in the project.

I'd go with Feeds if you're new to this and stumble your way through that ... I haven't used it. I can only recommend it.
> 3 votes

# Answer
You can filter your import by keyword with the feeds\_tamper module. Also in order to import RSS, you can configure an importer with the xpathparser module in order to select what content / fields to import.
> 1 votes

---
Tags: nodes, feeds, importing-exporting
---


# Question
Title: how to apply tag functionality on drupal 7 nodes?
I want to show tag in my news content type and want to show these tag for specific node in front end with the help of views.

# Answer
> 0 votes
You must add a term reference field to the content type, and choose your vocabulary.

See the below screenshot of a view to see how to show tags for nodes in a view.

---
Tags: views
---


# Question
Title: Domain access domain menu show default values
The problem: We have a main site with 70 subsites. On these subsites are users who have access to the menu settings. When they add a menu item they need to check the box near their own subsite. If they forget this the menu item will be shown on all the other domains. Sometimes resulting in multiple menu items with the same title.

The proposed solution: Alter the menu\_edit\_item form so that the $form\['domain\_menu\_access'\]\['manage'\]\['domain\_menu\_access\_show'\]\['#default\_value'\] is set to the domains the current user has access to.

My question: How do I set the default value for these checkboxes? Here is my code:

```
// Alter the edit menu item form

if($form_id == 'menu_edit_item'){
    $domains = array();
    if($user->uid > 1){
      $form['domain_menu_access']['manage']['#collapsed'] = false;
      foreach($user->domain_user as $domain){

    $form['domain_menu_access']['manage']['domain_menu_access_show']['#default_value'] = array((string)'d'.$domain);
  }
}

```

I have tried several variations with the $domain. (array($domain), array($domain =\> $domain), etc)

# Answer
> 0 votes
I found a workaround. I just rebuild the options array with the domains the user has admin access to. Here is my code:

```
// Alter the edit menu item form

if($form_id == 'menu_edit_item'){
    $form['domain_menu_access']['manage']['#collapsed'] = false;
    $domains = array();
    if($user->uid > 1){

  // We don't need to hide any menu items on other domains so we don't show this option.
  $form['domain_menu_access']['manage']['domain_menu_access_hide']['#access'] = false;

  // Loop the user object for all the domains current user is connected to
  foreach($user->domain_user as $domain){
    // Get the domain data
    $domains[] = domain_lookup($domain);

    // First unset all the options of the form element so we can rebuild it with our own values
    unset($form['domain_menu_access']['manage']['domain_menu_access_show']['#options']);
    //Rebuild the #options array
    $form['domain_menu_access']['manage']['domain_menu_access_show']['#options']['d'.$domain] = $domains[0]['sitename'];

    // Set the default value(s)
    $form['domain_menu_access']['manage']['domain_menu_access_show']['#default_value'] = array('d'.$domain);
  }
}

```

}

---
Tags: domain-access
---


# Question
Title: Set different pricing attributes for each product
here is the thing:
On my drupal commerce site I added a term reference field 'sizes' to line item, and make it to be an attribute on 'add to cart' form.
Also I added a field collection in to my product, wich has two fields: Margin(price) and size(term reference). So when I add some product I can choose a size and some extra margin to price.
What I want to do is when user add product to cart he chose some size, this size would compare with a size in field collection and the price for this item will update relatively to margin field collection field.
Anyone have any idea how can I do this?
Thanks

# Answer
> 1 votes
Thanks, Neograph734, but it's not exectly what I tryed to do. Maybe it isn't a proper way to do it but I solve this problem using custom \_add\_to\_cart\_form\_submit() function and hook\_commerce\_cart\_line\_item\_refresh(). So it looks something like this (maybe it will help someone):

```
function custom_add_to_cart_form_submit($form, &$form_state){
  // line item field_size_pick
  $line_item = $form_state['line_item'];

  $field_size_pick = field_get_items('commerce_line_item', $line_item, 'field_size_pick');
  $size_pick = $field_size_pick[0]['tid'];

  //get product
  $product_id = $form_state['values']['product_id'];
  $product = commerce_product_load($product_id);

  //fc sizes
  $field_fc_product_sizes = field_get_items('commerce_product', $product, 'field_fc_product_sizes');
  foreach ($field_fc_product_sizes as $key => $value) {
    $item_id = $value['value'];
    $fc_item = field_collection_item_load($item_id);

    $field_fc_size = field_get_items('field_collection_item', $fc_item, 'field_fc_size');
    $size = $field_fc_size[0]['tid'];

    if ($size == $size_pick) {
      $field_fc_margin = field_get_items('field_collection_item', $fc_item, 'field_fc_margin');
      $margin = $field_fc_margin[0]['amount'];
      break;
    }
  }

  if (isset($margin)) {
    $commerce_unit_price = field_get_items('commerce_line_item', $line_item, 'commerce_unit_price');
    $price = $commerce_unit_price[0]['amount'];
    $price += $margin;

    $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
    $line_item_wrapper->commerce_unit_price->amount->set($price);
    $line_item_wrapper->save();
    commerce_line_item_rebase_unit_price($line_item_wrapper->value());
    commerce_line_item_save($line_item_wrapper->value());
  }

  $form_state['rebuild'] = TRUE;
}

function custom_commerce_cart_line_item_refresh($line_item, $order_wrapper) {

  $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);

  $field_size_pick = $line_item_wrapper->field_size_pick->value();
  $size_pick = $field_size_pick[0]->tid;

  $field_fc_product_sizes = $line_item_wrapper->commerce_product->field_fc_product_sizes->value();
  foreach ($field_fc_product_sizes as $key => $fc_item) {
    $field_fc_size = field_get_items('field_collection_item', $fc_item, 'field_fc_size');
    $fc_size = $field_fc_size[0]['tid'];

    if ($size_pick == $fc_size) {
      $field_fc_margin = field_get_items('field_collection_item', $fc_item, 'field_fc_margin');
      $fc_margin = $field_fc_margin[0]['amount'];
      break;
    }
  }

  if (isset($fc_margin)) {
    $price = $line_item_wrapper->commerce_unit_price->amount->value();
    $price += $fc_margin;
    $line_item_wrapper->commerce_unit_price->amount->set($price);
    $line_item_wrapper->save();

    commerce_line_item_rebase_unit_price($line_item_wrapper->value());
    commerce_line_item_save($line_item_wrapper->value());
  }
  $order_wrapper->save();
}

```

# Answer
> 0 votes
In drupal commerce this goes by the name of product variants. There is quite some information on it, but this article from Drupal commerce should get you started: https://drupalcommerce.org/user-guide/product-attributes-variations

---
Tags: commerce
---


# Question
Title: How can I hide one commerce specific shipping option without deleting?
I am trying to hide a couple of Commerce shipping options we no longer use.

I can't figure out the proper syntax for addressing the individual form radio options.

Here is what I have so far:

`function MYMODULE_form_commerce_checkout_form_shipping_alter(&$form, &$form_state, $form_id) {
 $form['commerce_shipping']['shipping_service']['#options']['express_shipping']['#access'] = FALSE;
}`

...this throws an error ' Illegal string offset #access'. Am I addressing the wrong member of the array? I've used this code before successfully for text and select fields, but never a radio.

Thanks so much!

# Answer
You could try to remove the value from the form by using `unset($form['commerce_shipping']['shipping_service']['#options']['express_shipping']);`.

Also note that most of commerce's actions are handled by rules, there might be something there as well.
> 1 votes

# Answer
Since shipping service availability is determined by Rules, as mentioned in Neograph734's answer, you can simply add a condition that is guaranteed to be FALSE to the component for the relevant shipping services. I don't believe we'd considered "disabling" shipping services in the past, so you might consider adding that as a feature request to the module's issue queue.
> 0 votes

---
Tags: 7, forms, commerce
---


# Question
Title: Appache solr results multi sites search sorting based on specific feild
i have four sites and use appache solr module to execute search indexing in these four sites , all is ok with me , but the results sort not as i want

i want to sort by fields ......for ex:- get all result that have \[field 1\] first , then get all results that have \[ field 2\] ....

in my case , i have some results from \[ field 1\] then \[ field 2\] then \[field 1\] , .... for note (my field type is taxonomy term and all contents in all four sites are the same )

Thanks

# Answer
> 0 votes
A **quick Solution** may be to use Apache Solr Sort Module.

> Per environment setting of grouping per content type/taxonomy/field value/... Allow for a custom amount of items per group (global)

**But the best way is to setup a Apache Solr View :**

Search API, has a Solr integration module, which will allow you to setup a View with exposed filters and full text search. With the flexibility of Views, you should be able to setup the view to allow the users to sort as they wish.

---
Tags: search
---


# Question
Title: How can you gitignore items in a Drupal project without modifying core?
I have a Drupal project, and we want to use Git for version control, but we need to have some folders that are ignored by Git. The problem is that .gitignore seems to be a core file. After the last "drush up" command, the gitignore file was replaced.

So, other than asking each developer to manually add entries to his or her global .gitignore file, is there a good way to effectively .gitignore a path in Drupal?

# Answer
> 6 votes
While `.gitignore`, `.htaccess` and `robots.txt` will come as part of the package when you clone Drupal, they should not be considered part of core and you should not feel that they cannot be changed or replaced with your own files.

This is what I do: Prior to updating (`drush up`), I make a backup of those three files. After updating, I use the CLI program `diff` to compare the newly updated version with my backup (typically, my `.gitignore` have more entries at the end than those that come with Drupal). If nothing else has changed, I just overwrite the one that came with Drupal with the backup. If `diff` shows that the "drupal part" of `.gitignore` has changed, I copy those changes into my backup version before overwriting. (Same procedure with `.htaccess` and `robots.txt`.)

# Answer
> 4 votes
I use a global gitignore file https://www.drupal.org/node/1054616#comment-4139810

Place the following in ~/.gitignore:

```
*~
*.orig
*.rej
*.patch
*.diff
LICENSE.txt
.directory

```

Then run this:

```
git config --global core.excludesfile ~/.gitignore

```

To add a file that is in the ignore list (like a .patch file) do this

```
git add --force awesome-sauce.patch

```

Side note: To clean up all files that are not committed you can run this

```
git clean -x -f -d

```

`-x` : This allows removing all untracked files.
`-f` : git clean will refuse to delete files or directories unless given -f, -n or -i.
`-d` : Remove untracked directories in addition to untracked files.

# Answer
> 2 votes
It turns out that we solved the issue by creating a new repository with the Drupal site being a subdirectory. Because this was a new repository, that wasn't complicated to do.

# Answer
> 2 votes
Although the .gitignore file is included in Drupal core releases, the general rule of thumb to **never modify core** does not apply to it. It **is** intended to be modified on an as-needed basis, and comments in the .gitignore file itself call this out.

As stated in the question, since the .gitignore file is included in the Drupal release package, your customized version of it can be unintentionally overwritten when an update is performed. One solution to this is to place your modified .gitignore file itself under version control. This can be done simply by commenting-out the `.gitignore` entry in the .gitignore file, and performing a commit to your repository.

This solution has several advantages:

1. Your customized version of .gitignore won't be lost if accidentally overwritten.
2. You can *intentionally* overwrite .gitignore with the version included in the Drupal release package, and then use git's diff and merge functionality to combine any changes made in the official release in a manner in which you're probably already familiar with.
3. As your project evolves, having a way of tracking changes to any file in your project (including development-related files like .gitignore) can, of course, be very advantageous.

# Answer
> 0 votes
You can add `.gitignore` itself to your local copy of `.gitignore`.

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


# Question
Title: Hide Price by Role for a Content Type in Drupal 7
I am trying to achieve the following: 1\> Hide Price Field for a Role only on a specific content type.

I am using Drupal Commerce.

Things I tried: 1\> Field Permissions for the commerce\_price field on a product. But because we using the same field across all product types the settings do not apply to just 1 product type.

2\> preprocess\_node But could not access the price componenet. As it is a component inside the product reference field.

Could you please help me figure this out. Any help would be really appreciated!!

Links referred: https://www.drupal.org/node/1496450 Is there a way to hide the price on a product using Drupal Commerce?

# Answer
> 0 votes
I have never used Drupal Commerce, however I understand that you want to hide a field according to a role. That is doable through hook\_field\_access().

```
hook_field_access($op, $field, $entity_type, $entity, $account)

```

> Determine whether the user has access to a given field. This hook is invoked from field\_access() to let modules block access to operations on fields. If no module returns FALSE, the operation is allowed.

https://api.drupal.org/api/drupal/modules%21field%21field.api.php/function/hook\_field\_access/7

---
Tags: commerce, entities
---


# Question
Title: Duplicate alias for different nodes after submitting form twice - Pathauto?
I have found this issue, in many different installations of Drupal (I'm running 7.35, but problem occurs even in 7.34 and I think every other previous ones): if I click many times quickly on submit button in node creation forms (be it in administration pages or in forum topic creation pages, I have double-checked it and it occurs in both situations), Drupal creates n nodes with the same content, generating the same alias for different nodes in the same language (content is exactly the same), I checked with this other issue Drupal duplicate alias for same node but no changes, the problem remains. I noticed that even if I don't click so quickly there are many cases in which many of the created nodes have the same URL alias.

Nodes created with "shared" alias does have "Generate automatic URL alias" unchecked, those nodes which get a different (nnnn-0, nnnn-1 and so on) have this option checked.

Another strange thing is that creation timestamp delta of nodes with the same alias is of exactly of 2ms; I think this generates some kind of problem in pathauto module.

# Answer
You can use unique\_field module to prevent node creation on the basis of field value(unique field).

if this do not help then you can try to use hide\_submit module to disable the submit button after first click.
> 1 votes

---
Tags: nodes, path-aliases
---


# Question
Title: Display NOT a title field in Entity Reference field but my own field
By default 'Entity Reference' field uses 'Title' field to resolve Nodes. Is there any good way to change that behavior so it use another field to do that?

What if I want to use URL field or my own custom field what should I do?

I just would like to know what are the good ways to do that.

Thanks.

# Answer
> 0 votes
If by "resolve" you mean what is searchable in the entity reference autocomplete field, then yes you can change the entity selection mode in the fields settings from simple to view and create a custom view to populate options. There is a good step by step tutorial on how to do that here: http://www.jackrabbithanna.com/articles/creating-entity-reference-view

---
Tags: entities
---


# Question
Title: Styling first results from a View differently from the rest
We have a page that needs to render an unspecified number of nodes, newest one first. The first result needs to be displayed as a very large "hero unit", the next 4 results as a group of four large results and the rest in a more compact form.

```
#########################
#                       #
#       Result 1        #
#                       #
#########################

############ ############
#          # #          #
# Result 2 # # Result 3 #
#          # #          #
############ ############

############ ############
#          # #          #
# Result 4 # # Result 5 #
#          # #          #
############ ############

Result 6      Result 7
Result 8      Result 9
Result 10     Result 11

```

I've been trying to style this by displaying the View as unformatted fields, but the nodes are still rendered separately from the structure, making it hard (or impossible?) to specify how we need them rendered.

Is there some module that will help us style the View with more precision or is there some feature in Views that I have overlooked?

# Answer
You can do that by adding a "result counter field" (Global: View result counter) on your view. With this value you can edit your template file and build the conditions.

Hope that helps. Have a nice day.
> 1 votes

# Answer
You can do this in views with the pager offset option. Based on your example above, create a view like normal as a page or block then under the Pager set "Display a specified number of items" and set to 4 and then under the pager's options set offset to 1. This will skip the first item. Then add an attachment display to the view and attach it to your page or block before and set pager to "Display a specified number of items" and 1. Next add another attachment display and attach after and set "Display a specified number of items" to 6 and then under the pager's options set offset to 5. Now you override each display and output only the fields you need for each one.
> 2 votes

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


# Question
Title: text formats - not allowed tags are saved anyway
I have filtered html text format set to limit allowed html tags (`<a> <em> <strong> <ul> <ol> <li><p>`), I use also CKeditor with this format. I expected that Drupal would clean any other tags. This is happening after I save a node with text with some not-allowed tags and look at yet unpublished node's html - everything is stripped the way it should be.
However, if I open the node again and look on the code using ckeditors source button - the tags are there.
Were not the tags supposed to be deleted by Drupal? If not, what module can provide such functionality? Thank you.

# Answer
> Were not the tags supposed to be deleted by drupal?

No, the mantra in Drupal is "save the raw string, sanitise on output".

What you're seeing is the filter system working as designed.

As you mentioned in the comments, the Sanitizable (formatted text) module does exactly what you're looking for.

> The Sanitize module allows administrators to configure a text format to be applied to formatted text before storage. This is useful to ensure clean and valid data in the database.
> 0 votes

---
Tags: 7, wysiwyg
---


# Question
Title: How do I trigger an event when a button is clicked on a user profile?
Let's say I want to make a bunch of nodes based on what's in a specific field when someone clicks a button on their user profile.

Is this possible with a custom built module? And if so what hook would I use to display that button on the user profile, and how would I get it to call a custom function on click?

# Answer
Yes a custom module could accomplish this. I'd use drupal's form api to create a simple form and output it to a block that you display on user profile pages. The code below should get you started.

Create the form. The hidden element is grabbing the users id from the url.

```
function my_module_form($form, &$form_state) {
  $form = array();

  $form['uid'] = array(
    '#type' => 'hidden',
    '#value' => arg(1),
  );

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

  return $form;
}

function my_module_form_submit($form, &$form_state) {
  $uid = $form_state['values']['uid'];
  // do some stuff
}

```

Now use hook\_block\_info and hook\_block\_view to create a new block containing your form.

```
/**
 * Implementation of hook_block_info().
 */
function my_module_block_info() {
  $blocks['my_module'] = array(
    'info' => t('My Name'),
  );
  return $blocks;
}

/**
 * Implementation of hook_block_view().
 */
function my_module_block_view($delta='') {
  $block = array();
  switch ($delta) {
    case 'my_module':
      $block['subject'] = t('My Title');
      $my_form = drupal_get_form('my_module_form');
      $block['content'] = drupal_render($my_form);

      break;
  }
  return $block;
}

```

Here's an article on creating a module in D7 if you are not familiar with how to do that. http://www.justinphelan.com/post/how-write-your-own-module-drupal-7
> 1 votes

# Answer
Wow, this is a question with many solutions. Some stuff I can quickly think of:

**Developers** way:

1. create a custom module: https://www.drupal.org/developing/modules/7
2. implement hook\_menu to create callbacks for your links
3. implement your logic in the callback functions defined for your entries in hook\_menu.
4. "presentation layer". Depending on the structure of your website and your profiles:

a) Create a block with your links in it, references: block\_example, link function

b) Implement a "pseudo field" on fieldable entities (e.g. user, profile2)

c) Use link function in your profile template file e.g. user-profile.tpl.php

extra points might be awarded if you use the link function and your hook menu implementation together with the ajax framework. example.

**Site builders** way (one way.. there are many):

1. create a flag
2. create a rule for flagging items
3. in that rule implement your logic
4. optional: undo the flagging (so the user can do this action again)

All of the mentioned solutions will probably require some logic for **handling the access and display** of that button as well.

(one) **developer way**, if this button appears on user/id:

```
<?php
global $user;
if (arg(0) == 'user' && arg(1) == $user->uid && null === arg(2) {
  print l('do something', 'yourcallballback/' . arg(1));
}

```

**site builders** way (for the example from above):

usually there's no additional access check required here, you can setup that flag to be global and only clickable once if you want to make sure that it's only available once. for the display part you probably really have to use code to only show that flag if the current user visits his own profile.
> 0 votes

---
Tags: 7, users, hooks
---


# Question
Title: How to add the proper javascript to a page for using the Chartbeat module?
Has anyone successfully used the Chartbeat module with Drupal to get the analytics statistics?

It doesn't seem to work for me. I don't get the proper javascript added to the page.

# Answer
> 0 votes
the module doesn't work for me, I ended up putting the required javascript code into the template files.

---
Tags: javascript
---


# Question
Title: Fieldgroup accordion does not open to first field of group
I am using the accordion group and item via the Field Groups module. If I open an accordion group, scroll to the bottom of the group and then click on the next one to open, the new group opens in the same place in the browser as I was left at. But the new group header goes to the top of the page. So I'm left in the middle or at the end of the group I'm trying to access, rather than at the top of the new group.

Very confusing to describe!

# Answer
> 1 votes
This is the solution I ended up using. I got it from I got it here: https://stackoverflow.com/questions/3621161/jquery-accordion-will-it-scroll-to-the-top-of-the-open-item.

I tested it at modules/contrib/field\_group/field\_group.js file at line 66. We then created a patch for it.

Not sure if this is the best solution, but it worked for us, so I thought I'd share the info.

```
activate: function( event, ui ) {
                    if(!$.isEmptyObject(ui.newHeader.offset())) {
                        $('html:not(:animated), body:not(:animated)').animate({ scrollTop: ui.newHeader.offset().top -150}, 'slow');
                    }
                }

```

---
Tags: javascript, entities, navigation
---


# Question
Title: Can't get Ajax data sent to my PHP function
I recently took over an existing Drupal project and I tried to add a new PHP function (which works regularly) and link it with an Ajax query. There were already some in place that worked, and I wanted to add one that when you press a link, it sends the ID in the link to a PHP function which generates an info field. By copying the working code I got to this:

In my module, I added a `menu` hook referring to the PHP function in the module and the Ajax link:

```
$items['api/feedback'] = array(
  'page callback' => 'admin_user_feedback',
  'access arguments' => array('access feedback'),
  'access callback' => TRUE
);

return $items;

```

This is my Ajax code:

```
function getFeedback(id){
    $.ajax({
        type: "POST",
        url: 'api/feedback',
        dataType: 'json',
        data: {
            'id': id,
        },
        success: function(data){

            alert("success");
        },
        error: function(){

            alert("error");
        },
    });
}

```

I know the function gets called on, but the console gives this error:

> POST http://localhost:8080/site/api/feedback 404 (Not Found)

The URL is correct, the other APIs with similar URLs do work, so somehow he doesn't recognise this API, I must have missed something. Does anybody know?

# Answer
Check your URL again... should it have `/site/` ? I am guessing not, unless you have something going on it should be: http://localhost:8080/api/feedback

```
url: '/api/feedback',

```
> 0 votes

# Answer
I guess you need to attach `Drupal.settings.basePath` at the beginning of the url, it should be

```
url: Drupal.settings.basePath + 'api/feedback',

```
> 0 votes

---
Tags: 7, ajax
---


# Question
Title: Disable profile field when module that created it is disabled?
I have created a module that adds a field to the user profile. When I disable the module, I want the field to no longer be shown on the user profile. I do not want to wipe it out completely, since I do that on uninstall. I want it to come back with the original data when the module is reenabled I just want to have it not display when the module is disabled. Is there a way to do this? I am using Drupal 7 and the field is a text field and it is set to the default formatter when I create the instance. Is there a setting I can set the instance to in hook\_uninstall that will hide it?

# Answer
> 1 votes
I managed to accomplish it through code by setting the field instance:

```
    'display'       => array
      'default'     => array(
        'label'     => 'above',
        'type'      => 'hidden',
        'weight'    => '1',
        'settings'  => array(),
      ),
    ),

```

# Answer
> 0 votes
You would probably need to do something with your theme in order to hide the filed. Obviously you can't use your module, as it is disabled. You could do a check with module\_exists to see if the module is installed, and if it is, print the info, if not, ignore it.

---
Tags: entities, installation
---


title: Create OS user specific Drush commands

text:
# Question
Title: Create OS user specific Drush commands
I know how to create `drush` commands in a *project*, but there are a number of commands which I would like to add *to my local system* simply because they affect my particular workflow a lot.

In Clisp, I can define this in `.clisprc.lisp`. In `git` I can add commands to the `~/.gitconfig` command, I'm looking for similar for Drush.

So, for example, I might like to have a locally defined Drush command, `add-squeeky-table`:

```
drush add-squeeky-table

```

And I would be able to call that on all Drupal 7 projects installed on my system.

# Answer
Put your extensions in ~/.drush.

If add-squeeky-table is a drush command, put it in ~/.drush/squeekytable.drush.inc. See drushify.

If you want to define add-squeeky-table as a shell alias, put it in ~/.drush/drushrc.php. See the example Drush configuration file.
> 5 votes

---
Tags: drush
---


# Question
Title: Drupal Commons: Active sub theme of Commons Origins is intermittently not working (base theme is showing)
I have a staging site and a production site. The production site does not currently have a DNS record and I currently have a hosts entry for it (134.x.x.x subdomain.example.com).

I have a subtheme of Commons Origins theme called exampletheme. Exampletheme works fine on the staging server (which has a DNS record and no hosts file entry); but, when I migrated it over to the production server, I can only sporadically get the subtheme to show. Sometimes it reappears if I activate random themes (including commons origins), when I re-activate exampletheme, it will show for a while. But, eventually it goes away and I am back to looking at Commons Origins theme.

Two other factors, while the problem is existing, a drush status shows that the current theme is exampletheme. Also I have an error\_log in commons\_origins\_preprocess\_html and exampletheme\_preprocess\_html. It shows that commons\_origins\_preprocess\_html does fire , while exampletheme\_preprocess\_html does not.

In addition, I have made a copy of exampletheme with a different name, activated it and it has the same problems.

I have checked the permissions on the theme files and they are the same as the commons\_origins theme.

Any insight into this issue would be appreciated.

# Answer
Turns out the theme\_registry... entries in the cache table were not getting cleared for some reason. I ran the following in mysql prompt:

delete from cache where cid like 'theme\_%';

It's been working fine for hours now
> 0 votes

---
Tags: theming, 7
---


title: How to create a union of two views?

text:
# Question
Title: How to create a union of two views?
I'm trying to get a union of a user's nodes and comments sorted by "post date". This post links to sandbox projects for D6 but there is nothing for 7.

This post has an example of using hook\_views\_pre\_execute() and a SQL UNION in D6. This doesn't work for D7 with views 3.

I came across merlinofchaos' comment

> Because we're now using Drupal's new query generator, the query is a SelectQuery object which you will have to modify or replace. Look up Drupal 7's new database layer for more information.

Does anyone have an example of how to do this or any other solution to combine two views?

# Answer
> 16 votes
Here's a working and tested example:

```
/**
 * Implements hook_views_pre_execute().
 */
function mymodule_views_pre_execute(view &$view) {
  if ($view->name == 'my_view') {
    $query1 = &$view->build_info['query'];

    // Basic setup of the second query.
    $query2 = db_select('another_table', 'at')
      ->condition('some_field', 0, '>')
      ->condition('some_other_field', 12345);

    // The number of fields (and their aliases) must match query1.
    // Get the details with:
    // dpm($query1->getFields());
    $query2->addField('at', 'some_field', 'alias1');
    $query2->addField('at', 'some_other_field', 'alias2');
    $query2->addField('at', 'some_other_field2', 'alias3');
    $query2->addField('at', 'some_other_field3', 'alias4');

    // Verify that queries are very similar.
    // dpq($query1);
    // dpq($query2);

    // Matrimony.
    $query1 = $query2->union($query1, 'UNION ALL');

    // Manual test.
    // dpm($query1->execute()->fetchAll());

  }
}

```

This works for most views. However some style plugins may do fancy stuff that won't work with this technique (Calendar module I'm looking at you).

# Answer
> 3 votes
You can use the Views extra handlers module to generate SQL UNION queries from two different views/displays.

A detailed tutorial on drupal.org here

https://www.drupal.org/project/views\_extra\_handlers

# Answer
> 2 votes
I ended up using db\_query() to create the SQL UNIONs and then rendering it into a table layout including pagers using the theme() function.

To the user it looks like default views. The other benefit was that I could optimize the query a lot. I'm showing "my friend's activities" and if you would use views for that it would create a list of your friends and use it in a SQL "IN" clause which is very slow if you have more than 50 or a 100 records.

I could narrow that list of friends to only the ones who have been logged into the site in the last x days.

This is a code sample:

```
  // Two queries are required (friendships can be represented in 2 ways in the
  // same table). No point making two db calls though so a UNION it is.

  // Build up the first query.
  $query = db_select('flag_friend', 'f')
    ->condition('f.uid', $account->uid)
    ->condition('u.login', $timestamp, '>');
  $query->addExpression('f.friend_uid', 'uid');
  $query->innerJoin('users', 'u', 'u.uid = f.friend_uid');

  // Build up the second query.
  $query2 = db_select('flag_friend', 'f')
    ->condition('f.friend_uid', $account->uid)
    ->condition('u.login', $timestamp, '>');
  $query2->addExpression('f.uid', 'uid');
  $query2->innerJoin('users', 'u', 'u.uid = f.uid');

  // Return the results of the UNIONed queries.
  return $query->union($query2)->execute()->fetchCol();

```

# Answer
> 1 votes
For future reference, this is how I combined two views basing on same table together. Same principles should also apply on views basing on different tables with same amount of fields.

In below case only id is selected since the format is set to rendered entity. But if you are going with fields you can always add additional dummy fields to the query that has less fields as I added timestamp below.

```
/**
 * Implements hook_views_pre_execute().
 */
function MY_MODULE_views_pre_execute(&$view) {
  if ($view->name == 'VIEW_1' && $view->current_display == 'DISPLAY_OF_VIEW_1') {

    $view2 = views_get_view('VIEW_2');
    $view2->build('DISPLAY_OF_VIEW_2');

    $view->build_info['query']
    ->fields('table_alias', array('timestamp'))
    ->union(
        $view2->build_info['query']
        ->range()
        ->fields('table_alias', array('timestamp'))
        ->orderBy('timestamp', 'DESC')
    );

    $view->build_info['count_query']
    ->union(
        $view2->build_info['count_query']
        ->range()
    );
  };
}

```

# Answer
> 0 votes
I imagine its something along these lines:

```
/**
* Implements hook_views_pre_execute().
*/
function mymodule_views_pre_execute(&$view) {
  if ($view->name == 'myview') {
    $query = $view->query;
    $other_view = views_get_view('otherview');
    $other_query = $other_view->query;
    $query = $query->union($other_query);
    $view->query = $query;
  }
}

```

Although I haven't tested it.

Some links that may help:

http://api.drupal.org/api/drupal/includes!database!select.inc/function/SelectQueryInterface%3A%3Aunion/7

http://drupal.org/node/557318#comment-1991910

# Answer
> 0 votes
I came across a module called Views Field View, which allows you to embed a view as a field in another view. I haven't tried this out yet myself yet, but it might be helpful to you.

# Answer
> 0 votes
The EntityFieldQuery Views Backend support querying for multiple entity types at the same time. So it should be usable to query for both nodes and comments. Both entity types uses a `uid` property to link to their author so at the API level EntityFieldQuery::propertyCondition() should be usable to select the nodes and comments from a single user. I guess the views backend provides the same feature.

# Answer
> 0 votes
A different approach could be to create *feeds* of nodes and comments (with a contextual filter of the user's identifier in the URL) and then combine the two feeds into a new feed, and display this by post date.

# Answer
> -2 votes
Used Global: PHP fields? You can use them to duct tape together a View that combines the two.

Create a View of content with Content: Title and Content: Comments fields (Excluded from display).

Add a PHP field that calculates which is more recent, the date last updated, or the date of the last comment by the user, and set the field's value to be that date. Add that field as a sort condition.

Add a similar field that outputs either a link to the comment or to the node.

It sounds good to me!

---
Tags: 7, views
---


# Question
Title: Getting errors trying to upgrade Commerce Kickstart 1.24 to 1.34
I’m trying to upgrade my install of Drupal Commerce version 7.x-1.24 to 7.x-1.34 but am getting an update failed notice that reads:

Commerce\_kickstart-7.x-1.34-core.tar.gz does not contain any .info files.

but when opening that package i see there is indeed an info file, Commerce\_Kickstart.info

I’ve been Googling this message to see if other’s are having the same issue but curiously i’m not finding anything.

Is doing this manually an option? if so, do i just replace what is in the profiles folder?

# Answer
I always did this manually. You don't need to replace whole profiles folder. Replace commerce\_kickstart folder inside profiles only if you have not hacked or changed any file within. If you have changed any module or theme file. First move the folder to sites/all/modules or sites/all/themes folder, then replace that and run update.php.
> 1 votes

---
Tags: commerce, upgrading
---


title: How to add diffent makers on the image

text:
# Question
Title: How to add diffent makers on the image
How to add a marker in different part of the image (please look at the attached photo),

There is a module Imagefield marker which is not working. is there any other similar module?

Thank for the help.

# Answer
ImageCache Actions is the right module which you're looking for. Enable `Imagecache Actions` and `Image Effects Text` module

Go and edit the image style at admin/config/media/image-styles and select effect `Text`.
> 0 votes

---
Tags: media, theming
---


title: Add class in sub menu

text:
# Question
Title: Add class in sub menu
I am trying to convert html to Drupal 7 theme.

`function theme_menu_tree($variables){
 return '
' . $variables['tree'] . '
';
}`

simply returns the entire menu how to make it like following `

Item

Link1

Link2

`

# Answer
> 0 votes
Use theme\_item\_list function for it, see the below code

```
$title = 'Title';
$type = 'ol';
$items = array(
  'one',
  'two',
  'three',
  'four',
  'five',
);
$items[] = array(
  'data' => 'something',
  'class' => array('dummy'=>'category'),
  'children' => array('1.1','1.2',array('data'=>'1.3','class' => array('dummy'=>'category'),'children'=>array('1.3.1','1.3.2')))
);
$attributes = array('class' => array('test-class', 'demo-class'));

print theme_item_list(array(
  'items' => $items,
  'title' => $title,
  'type' => $type,
  'attributes' => $attributes
));

```

This will give you following HTML output:

```
<div class="item-list"><h3>Title</h3>
  <ol class="test-class demo-class">
    <li class="first">one</li>
    <li>two</li>
    <li>three</li>
    <li>four</li>
    <li>five</li>
    <li class="category last">something
      <div class="item-list">
        <ol class="category">
          <li class="first">1.1</li>
          <li>1.2</li>
          <li class="category last">1.3
            <div class="item-list">
              <ol class="category">
                <li class="first">1.3.1</li>
                <li class="last">1.3.2</li>
              </ol>
            </div>
          </li>
        </ol>
      </div>
    </li>
  </ol>
</div>

```

---
Tags: theming, navigation
---


title: Is there a live video feed module?

text:
# Question
Title: Is there a live video feed module?
Is there a way to let visitors to my site watch a video via a live stream?

For example, I want to let students watch a course in which a professor lectures live?

How can I do this easily?

# Answer
> 3 votes
Try BigBlueButton

BigBlueButton Demo, http://demo.bigbluebutton.org/

# Answer
> 3 votes
A stable module for streaming live videos for drupal 7 is VideoWhisper Live Streaming. You could try using it.

# Answer
> 2 votes
Live Stream A Drupal 7 Site Free No Hosting Fees

CREATE LIVE STREAMING WEB PAGE IN DRUPAL USING CKEDITOR

Required Modules:

CKeditor

Admin Menu

GET STARTED

1. Go to your Drupal Website and hover over content and create a basic page
2. Click the Green Film Icon at the top in the toolbar section of your editor and keep the window open

Note: If you do not have the green film icon then you will need to add it to your CKeditor. Go to modules and click the configure link on your ckeditor. You will need to drag the icon in both the Advanced and Full Profile section. First click edit in the advanced section and click the editor appearance dropdown. Now drag the green film icon from the available buttons section to the current toolbar section. Do the same for the full profile section as well

INSTALL ADOBE FLASH MEDIA ENCODER 3.2

1. Download the Adobe Flash Media Live Encoder 3.2 at this link http://www.adobe.com/products/flash-media-encoder.html
2. Once Downloaded open the player

YOUTUBE SETTINGS

3. Go to adobe.com/products/flash-media-encoder.html
4. Sign in to your gmail (make sure your gmail is loaded and open)
5. Open a new tab and paste this link https://www.youtube.com/my\_live\_events
6. Click Schedule New Event
7. Enter the event, title, time and description in the appropriate slots. Make sure that “custom” is clicked in the Type Section on the right hand top side of the page and then click Create Event
8. You will then be asked to upload a thumbnail that will be used to advertise the event. Click browse and locate the file that you wish to use and click open when you select the file.
9. Directly under where you uploaded your picture you will see a dropdown that says Choose maximum sustained bitrate of your encoder. Click “Basic ingestion” and select your video size in the dropdown
10. Next you will see the dropdown that says “Select your encoder” select the Flash Media Live Encoder option in the dropdown menu.
11. In the next dropdown go to number two and click “Download file primary” (do not close your youtube browser window.)
12. Download and save the file and go to your newly installed Adobe Flash Media Live Encoder 3.2 that you just installed and hover over the word "File."
13. A dropdown will pop up that says “open profile” and upload the file from step 11 to your media encoder.
14. Make sure your bitrate is 2000kbs and make sure your output and input size is 640x480 and frame rate is 1fps
15. Click the tab that says connect in the right panel or your Adobe Flash Media Live Encoder 3.2 and then click the green “Start” button at the bottom of the encoder.
16. Go back to your youtube window and scroll to the top and click the “Live Control Room” link
17. Stream status should be Good if not go to the encoder and click the red stop button at the bottom of the page and then click start again
18. Click the blue “Preview Stream” button
19. Left click the “View on Watch Page Button near the top right corner of the youtube page and open link in new tab
20. Copy the URL at the top of the page in your Navigation Bar
21. Go to embedresponsively.com
22. Paste the Youtube URL that you just copied
23. Copy the embed code from embedresponsively.com
24. Go to the drupal page that you created at the beginning of this tutorial
25. Paste the embed code

YOU ARE NOW LIVE STREAMING USING DRUPAL AND YOUTUBE

Rod J. BelieveLogix.com

---
Tags: 7
---


# Question
Title: How to set the path to images in ckeditor?
I have a recurrent problem I can't solve.

when working in localhost I use ckeditor to upload images to the body field. These images are shown correctly.

Then after, I upload the site to the remote host and all those images links are broken.

The problem is that the drupal installation on my localhost is inside a folder in localhost like: `http://localhost/mysite.com/`

In the remote host all the images links have the `mysite.com`part of the url which of course is wrong. This is not solved by clearing caches.

**Localhost** (works fine)

`http://localhost/mysite.com/sites/default/files/resize/icon-questions-180x127.png`

**Remote** (with the wrong "mysite.com")

`http://mysite.dde.oneserver.com/mysite.com/sites/default/files/resize/icon-questions-180x127.png`

With no luck I tried with several configurations at: **admin/config/content/ckeditor/edit/Full**

**UPDATE (trying with Pathologic module)** I added these lines in "All base paths for this site" in Pathologic setting at `admin/config/content/formats/full_html`:

```
http://localhost/mysite.com/ (this one is where the site was developed)
http://mysite.dde.oneserver.com (this one is where the site lives now)

```

I ALSO tried adding:

`http://mysite.dde.oneserver.com/mysite.com`

look the capture:

# Answer
You might want to try Pathologic module to see if that works for you.

> Pathologic is an input filter which can correct paths in links and images in your Drupal content in situations which would otherwise cause them to “break;” for example, if the URL of the site changes, or the content was moved to a different server. Pathologic can also solve the problem of missing images and broken links in your site’s RSS feeds.
> 3 votes

# Answer
May be there was a configuration missing! Have you ever try the following way to resolve the problem? I think it might be a good choice for you (this CKEditor add-on will automatically calculate correct URL for your images: in my projects I leave in not configured and it successfully understands what URL prefix must be used):

http://doksoft.com/soft/ckutils/bundle-install.html
> 0 votes

---
Tags: wysiwyg, input-formats
---


# Question
Title: How can I add a CSS class to a View Field programmatically?
Using template\_preprocess\_field doesn't work, I assume, because this is a field from a View, not a node.

I've looked at this answer however that only seems to apply to the field value not the markup and styles surrounding it.

For example: The output of the field in markup is currently:

```
<div class="views-field views-field-field-status">
    <div class="field-content">
        Active
    </div>
</div>

```

I'd like to conditionally add classes:

```
<div class="views-field views-field-field-status">
    <div class="field-content my-conditionally-added-class">
        Active
    </div>
</div>

```

# Answer
You can add any css class, HTML tag to any field through views admin UI, why don't you add the class from there?

---

**UPDATE**

Because you need add the css class based on some condition, you have to use the following preprocess function. your code is going to be some thing like this (maybe a few modification will be needed )

```
function mytheme_preprocess_views_view_field(&$vars){
     $view = $vars['view'];
    if($YOUR_CUSTOM_CONDITION == TRUE && $view->name == VIEW_NAME)
           $vars['classes_array'] = 'my-conditionally-added-class';
}

```

because you output the content on views you have to use `mytheme_preprocess_views_view_field` function.

For more information visit Themeing Views field output with Preprocess function.
> 2 votes

---
Tags: theming, entities, views
---


# Question
Title: How to allow integer and decimal fields with default values to be saved as empty.
If I set a default value on a decimal or integer field, the user cannot delete the default value and save the node.

They can set the value to another value including zero, and that is saved correctly.

But if the contents of the field is deleted, on save, the field is automatically populated with the default value again.

This doesn't seem right. I guess I could intercept the empty field and set it to zero, but surely that's not necessary? Am I missing something?

# Answer
> 2 votes
This is a bug in D7. Checkout https://www.drupal.org/node/1253820. I checked it works while editing content but not while creating. This has been fixed in D8. For D7, you can write custom code to handle this.

---
Tags: entities
---


title: String Manipulations in Drupal

text:
# Question
Title: String Manipulations in Drupal
I've been retrieving information from a database for display.

```
function myid_user_page_form(){
    $query = db_select('student', 't1',array('target' => 'import'));
    $result = $query->fields('t1', array('firstname','middlename'));

    foreach ($result as $record) {
        $info['firstname'] = $record->firstname;
        $info['middlename'] = $record->middlename;
    }
}

```

In my case, all data stored in my database is all uppercase. For example:

```
$info['firstname'] = "ALYSSA"
$info['middlename'] = "ENGANIO"

```

I want to make "ALYSSA" to "Alyssa" and make "ENGANIO" to "E.". How will I do that in Drupal?

# Answer
> 2 votes
Drupal can help you doing this by its unicode functions.

https://api.drupal.org/api/drupal/includes%21unicode.inc/7

"ALYSSA" to "Alyssa" would be

```
<?php
  $name = drupal_ucfirst(drupal_strtolower($name));
?>

```

And "ENGANIO" to "E." would be:

```
<?php
  $name = drupal_strtoupper(drupal_substr($name, 0, 1)) . '.';
?>

```

# Answer
> 0 votes
not a Drupal question, but here you go..

```
<?php
// proudly found elsewhere: http://stackoverflow.com/a/2518021/1158887
function mb_ucfirst($string, $encoding)
{
    $strlen = mb_strlen($string, $encoding);
    $firstChar = mb_substr($string, 0, 1, $encoding);
    $then = mb_substr($string, 1, $strlen - 1, $encoding);
    return mb_strtoupper($firstChar, $encoding) . $then;
}

function myid_user_page_form(){
    $query = db_select('student', 't1',array('target' => 'import'));
    $result = $query->fields('t1', array('firstname','middlename'));

    foreach ($result as $record) {
        $info['firstname'] = mb_ucfirst(mb_strtolower($record->firstname, 'UTF-8'));
        $info['middlename'] = mb_substr(mb_ucfirst($record->middlename, 'UTF-8'), 0, 1) . '.';
    }
}

```

---
Tags: 7
---


# Question
Title: Update fails because directories are locked by php-cgi.exe
I have some problem when using the Update manager. Some directories get locked by php-cgi.exe, and thus the replacement of the original directories with the newly downloaded ones (which are fresher) is not successful.
It's not a permission issue, since modules can be installed via *Install from a URL* on /admin/modules/install, and that works without problems.

Let's take an example:

1. **Available updates** page (`/admin/reports/updates/update`):

Now I check *Select (or other)* module to be updated (**it doesn't matter which module I choose**, the results are the same!! so it's just an example).
2. I hit **"Download these updates"** button.
3. OK, the module's updated instance gets downloaded without a problem:
"**Updates downloaded successfully**":
4. Now I click on **Continue**.
5. Here comes the error. The result:
*"**Update failed!** See the log below for more information.*
*select\_or\_other*

* *Error installing / updating*
    * *File Transfer failed, reason: Cannot copy `D:/Projects/web/drupal-7/tmp/update-extraction-6d8993ac/select_or_other/LICENSE.txt` to `/Projects/web/drupal-7/htdocs/sites/all/modules/select_or_other/LICENSE.txt`.*"
6. OK, I'm starting to try to inspect the possible reasons.

* Here's what my Drupal directory structure looks like: . I set `../tmp` to be the temporary directory (in `/admin/config/media/file-system`), the Drupal files are in `htdocs`. This is correct, as I can install modules via the GUI, as I mentioned above.
    * When I try to enter the `htdocs/sites/all/modules/select_or_other` directory, I can't, because I get an *"Access denied on file `......sites/all/modules/select_or_other`!"* when opening in Total Commander, and *"`...sites/all/modules/select_or_other` is not accessible. Access is denied"* when opening in Windows Explorer: ,
    * OK, I right click the folder, and open Unlocker via its assistant in the context menu. It says this directory is locked by `php-cgi.exe`: I click on "Unlock All", and the folder can now get deleted of itself (as it's not locked anymore by `php-cgi.exe`), so it simply
    * I can find the updated select\_or\_other module's directory in `tmp`:
    * so I have to manually move it to `sites/all/modules` directory.

**What can be the possible reasons of the lockup of the directory by `php-cgi.exe`?** (Maybe Windows Cache Extension 1.1 for PHP 5.3 installed via Web Platform Installer? But if yes, why is that for example the deletion of images or similar via the GUI works correctly?)
**What can I do to avoid this problem, and let "Update manager" work?**

# Answer
The reason for php-cgi for having the Lock is because of the "peculiar" way windows handles file access, and php/iis handles "caching". Basically you just created the directory and tried to access it, but the handle that created it was not released (so it was still locked). This is not a drupal issue, its an IIS/PHP issue And there is no known workaround that I could find.

Basicly, do the base advise of not using IIS is the best, I have seen this problem in more than just drupal with IIS that I solved by moving to apache HTTPD (on win32). Mind you that was for back at school, with a project where I was required to use windows 2000.

the best way I know of running drupal on windows is through apache (because of the internal handling of php).
> 1 votes

# Answer
this is not secure that allow to write file from Drupal user interface for updating modules, instead of this use ftp.

but if you want then go to plesk panel of hosting explore httpdocs directory right click and then on permission, now in permission give write permission to Application pool user,

Thanks
> 1 votes

# Answer
Some ideas to dig in the right direction:

If you have the same problem from Drush, then I am not sure if this is an IIS problem. Is Drush not just executing PHP from the command line without IIS? You can try this by stopping IIS (iisreset /stop) and then running the Drush update command and I would expect you to get the same result.

The other thing (sorry, I don't have enough reputation to directly comment on Lawri's answer):

> "Basically you just created the directory and tried to access it, but the handle that created it was not released"

Is this really true? From the the original post it looks like he created the folder in "tmp", but the lock is on the already existing folder in "httpdocs".

My guess is that php-cgi tries to copy from tmp to httpdocs, fails for a reason and doesn't remove the lock. So when you investigate after the failure, you see a lock on httpdocs, but I think the initial reason for failing is not a lock, it might be a permission issue on the tmp folder after all!
> 0 votes

---
Tags: 7, iis, updating
---


# Question
Title: Views and empty parameter in Path to link
I know my title isn't explicit, but i will explain my problem. I created a view that displays me all documents(content) of my website, some documents are linked to a project(content) via entity reference, and in my `view` I display a link to a document. if there is a project the link looks like : `node/100?project=5` . If there is no project the link needs to look like : `node/100`.

So in my view I added field excluded from display with the id of the project, and a second field which is the id of the node document and I rewrite the link to :

```
node/[nid]?project=[field_doc_project]

```

My problem is: This works fine for document with projects only. good url: `node/100?project=5` bad url, without project: `node/100?project=`.

Can I check in view if the project id exists and rewrite the url to `node/100`?

thanks

# Answer
> 0 votes
almost there,

1. add a link to the original content as a field, exclude it from display
2. add a path to the original content as a field, exclude it from display
3. rewrite the term reference to the full url you want to have using replacements \[path\]?something=\[someid\]
4. add a no results behavior and output the link from 1) \[view\_node\]

---
Tags: views, nodes, uri
---


# Question
Title: unable to add,edit,delete content types in drupal 7?
I'm unable to add, edit, delete content types and content also in Drupal 7, the button links are not working. If I click add, edit, delete button below an error happens. What could be wrong here?

# Answer
> 2 votes
Try following steps.

1. Make sure clean URLs working first. If you need any help for clean URL visit this link
2. Try clear cache and then disable all contributed modules. I see there is a problem due to commerce line items module. Disable all contributed modules. Don't disable core modules.
3. Clear cache and check.

Tell me in comments if you still face problem.

# Answer
> 0 votes
Please try increasing your `max_allowed_packet` setting in MySQL.

Open `my.cnf` file & update `max_allowed_packet = 16M` or more

**Or**

In `settings.php` and add a line inside file :

`$conf['error_level'] = 1;`

# Answer
> 0 votes
I had same issue, i can sense you installed commerce module, i disabled the commerce report module which causing some problem. Try disable that commerce report module, If you can go to module page, then try disable in phpmyadmin in "system" table

# Answer
> 0 votes
I think you uninstalled the commerce module and now you want to remove the related content-types. Right?

You probably need to re-install drupal commerce, then remove the undesired content types and uninstall drupal commerce again.

---
Tags: nodes, commerce
---


# Question
Title: How can I get the translated path to the current node?
How to get path to current node but of another language?

Available languages:

* English (URL prefix: en)
* Polish (default, no URL prefix)

Enabled detection methods:

* URL (by prefix)
* Session (parameter: language)
* Browser
* Default

I created translation of taxonomy and translations of some basic page nodes. However, none of the following codes work.

```
drupal_get_path_alias(null, 'en')
drupal_get_normal_path('', 'en')
drupal_get_path_alias('hardcoded-existing-path', 'en')
url(current_path(), array('language'=>'en'))

```

How to make it work? All internalization modules are enabled.

# Answer
> 0 votes
The problem is the lack of a language string / prefix for polish. By this URL detection is skipped.

Look into locale\_language\_from\_url() line 275

```
<?php
 case LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX:
   // $_GET['q'] might not be available at this time, because
   // path initialization runs after the language bootstrap phase.
  list($language, $_GET['q']) = language_url_split_prefix(isset($_GET['q']) ? $_GET['q'] : NULL, $languages);
  if ($language !== FALSE) {
    $language_url = $language->language;
  }
 ?>

```

If there is no language found in the URL is skips. Now the language detection is by session and so on. The only real option is that all languages you use have a prefix. The only real problem that than occurs is that the homepage would always redirect wich is not that nice for bots. But still better than fall back to language detection you don't want.

Besides that you could mode "default" just below "URL (prefix)" so Drupal won't use the session or the browser. But even this is not reliable from my experience.

---
Tags: 7, nodes, i18n-l10n, path-aliases
---


title: Override login form submisssion

text:
# Question
Title: Override login form submisssion
I try to call a SOAP web service before an users authentication. I've try this

```
function beneficiaire_user_login(&$edit, $account){
    die('hello from login override'); }

```

Unfortunately, if my SOAP request is bad I cannot prevent the authentication.

What I want to do is: click the login \> check via a WS is the user exists \> if yes create the user on Drupal, else show an error message. Can I perform this action before the session opening ?

With a form\_alter hook, it doesn't works, I do not see the "form alter" text

```
function beneficiaire_form_alter(&$form, $form_state, $form_id){
    exit('form alter');
}

```

Thanks

# Answer
I'm working on something similar. I think you can do this using a validation rule.

```
/**
 * Implements hook_form_alter().
 * We replace the local login validation handler with our own.
 */
 function beneficiaire_form_alter(&$form, &$form_state, $form_id) {
    // In this simple example we authenticate on username to see whether starts with dave
    if ($form_id == 'user_login' || $form_id == 'user_login_block') {
        $form['#validate'][] = 'beneficiaire_user_form_validate';
    }
 }

/**
 * Perform validation rules and set error states
 */
function beneficiaire_user_form_validate($form, &$form_state) {
    if (!beneficiaire_authenticate($form_state)) {
        form_set_error('name', t('You are not on our super-secret list.'));
    }
}

/**
 * Custom user authentication function
 */
 function beneficiaire_authenticate(&$form_state) {
     // Check the webservice here and return false if user not found.
 }

```
> 0 votes

---
Tags: hooks, users
---


# Question
Title: Change Drupal Views Rows before they were rendered
I want to change the output of a view. More precisely i want to reduce the resulting list to exact 3 matches: one specific row and its previous and next row.

As far as I understand I need to generate the whole list first, because otherwise i cant find the previous row. So I thought I have to do something in the views-view.tpl where all the rows will printed.

My question then is: How can I get the content of a specific field in each row in $rows so i can check for that specific row and its surrounding rows?

Or is there any better way?

ps. ( i am a php noob )

# Answer
A custom module which implements hook\_views\_pre\_render() will give your that ability:

```
<?php
MYMODULE_views_pre_render(&$view) {
  if ($view->name=='myview') {
    // limit the results to 3
    array_splice($view->result, 3);

    //other modifications can be done as well:
    foreach($view->result as $r => $result) {
      // do something
    }
  }
}

```

to find a specific row you'll have to code a bit, but that's not drupal related, check https://stackoverflow.com/questions/1019076/how-to-search-by-key-value-in-a-multidimensional-array-in-php for further informations.
> 1 votes

# Answer
Try to avoid under all circumstances to iterate over an unknown result set to find three unspecific items.

By this this is not really a question about Drupal and Views but about SQL Query Performance.

It maybe sound like a good idea to select one item by ID and than the one "before" and the "next" one but for SQL and growing databases this is a very bad idea. Now you created a view that always selects a list of unknown and probably growing size. This might kill your system in the future.

Please change the query and by this the view to something you can order. Maybe the creation time and than just 3 items. By this you have a much more reliable query that gets you three items from your database and hopefully can use an index to find them.
> 0 votes

---
Tags: views, theming, hooks
---


# Question
Title: Drupal 7 How to make the value of a user field (site_path/admin/people) dependent on user role
I am using the module Administration Views (https://www.drupal.org/project/admin\_views) to change the layout and content of the Drupal users view at "site\_path/admin/people". The site I am working on requires that users pay yearly for membership using Ubercart. Using Ubercart's add user role on purchase functionality, I have added the "Paid User" role to the site. When any registered user makes an Ubercart purchase of a "Membership", he/she is given this Paid User role.

The site admins want to be able to track users by whether or not they have made their yearly payments to ensure that their privileges within the organization for which I am producing this site reflect their membership payments. Therefore, I have added a "Dues Status" field to the "user" node type and displayed it in the Drupal users view at "site\_path/admin/people" using the Administration Views module.

However, as the tracker for "Paid Dues" is whether or not the user has the role "Paid User" rather than a user edit, I have been unable to make the value of the "Dues Status" field update in the view. Since Administration Views has access to each user node in their respective views rows, I considered using Views PHP (https://www.drupal.org/project/views\_php) to try to access the data in the "User Roles" field and check for the presence of the role "Paid User", but I did not know how to do this and change the value of the "Paid Dues" field.

I am familiar with re-writing fields using HTML, just not with PHP. Could someone explain how to use Views PHP to rewrite the value of a user field by checking for a user role on that user? Or, if there is a module I have been unable to find that can do this, please let me know.

# Answer
> 1 votes
Please never ever use something that uses eval(). Even if you don't migh related security problems because nobody else has access to your site eval() is very very slow.

What you are looking for is hook\_views\_pre\_render()

or a preprocess hok for the specific field. There are plenty examples if you use google.

---
Tags: users, views
---


title: Cant create a taxonamy menu block

text:
# Question
Title: Cant create a taxonamy menu block
Steps i followed

1. Created a vocabulary (V) and added 5 taxonomy terms to it.
2. Created a new menu (M).
3. In edit vocabulary (created before), selected Menu M as Menu location from Taxonomy menu settings.
4. Hit Save button.

Getting this error

The Taxonomy Menu rebuild process encountered an error.

An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging information follows. Path: /batch?id=688&op=do StatusText: OK ResponseText:

# Answer
I don't think this can be answered here. It seems to be a call to Drupals Batch API that fails. But why can't be answered without some debugging and is not in the scope of your question.

Basically you are doing it right. You can try the otherway round and add menu items to you desired menu and than let them point to taxonomy/term/123. This should give you the same result.
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: "access ckeditor" permission missing - buttons inactive
I have my ckeditor basically up and running. Users with the role 'editor' however can see and use it, but the buttons appear to be inactive. Just the "Source" and "Format" are accessible for editors.

And in under permissions \> ckeditor I have no permission for "access ckeditor". Any help / pointers welcome! Thank you!

ps: Editors do have permission to use the related text format "full html".

# Answer
Thank you for your suggestions. I suppose it probably is some permissions problem. I now granted the "Customize CKEditor appearance" permission for the role *Editor* and the toolbar is now functional. However it leaves me puzzled why *this* paprticular permission would trigger whether a user / role is allowed to use the toolbar buttons or not.

> Customize CKEditor appearance
>
> Allow users to customize CKEditor appearance.

Either it's a wording problem and granting that permission is the right thing to to – or I now actually have granted permission to customize the CKEditor appearance (as the wording would suggest) and I have a slight security problem However – i'll submit a request for support issue over at drupal.org and edit this post once I know more…

PS: Even thought this question might leave the impression – it's not my first time on drupal. It's just the first time I'm using CKEditor instead of WYSIWYG.
> 1 votes

---
Tags: users, wysiwyg
---


title: Features can export everything?

text:
# Question
Title: Features can export everything?
Built all blocks, menu, taxonomies, view etc in Drupal CMS on localhost machine, but I need to export everything to the live server. Is it possible to use features or just export sql?

# Answer
The Features module allows you to **export all the configurations in code** (instead of DB). It is very usefull when you have 2 separated versions of database, in example one for your localhost or test installation, and one for your live/production website.

*However, if you want to deploy the local database to the live server too, it is not necessary to export everything with Features.*
> 1 votes

# Answer
I love using features for just what you're describing you need. I admit it's a bit challenging at first, and doesn't always appear to work as expected. Here are some videos that I think may be helpful:

https://www.youtube.com/watch?v=P874hgin5xI https://www.youtube.com/watch?v=ZHbOh9bf1dg&list=PL-Ve2ZZ1kZNTykHOLO0jzRADq8iZxvzkU (several by Shane Thomas, codekarate)

If you want to export individual content, you have modules such as https://www.drupal.org/project/uuid\_features, but that's not for large scale use. I think you'll want this: https://www.drupal.org/project/node\_export. It makes import/export of nodes pretty easy.

Hope this helps some.
> 0 votes

---
Tags: theming
---


# Question
Title: How can i populate data from a reference node into another content type?
I have two content types. hospitals and referral form. I would like to pull data from the hospital form automatically, example hospital name, address, contact etc when the user fills in the name of the hospital in the referral form.

I have used entity reference but i cant get it to work. It only gets the URL of the node but not the other fields. And also i have used autofill but it only works for a single content type. If any one has done this before or if anyone has an idea, please do help. looking forward to your responses.

# Answer
> 0 votes
Take a look at entityreference\_autofill

> The Entity reference autofill module gives Entity reference fields an option to populate other form fields with data from selected referenced entities.

---
Tags: rules, nodes, entities
---


title: Drush error cygintl-2.dll is missing

text:
# Question
Title: Drush error cygintl-2.dll is missing
So I get the following error "the program can't start because cygintl-2.dll is missing from your computer. try re installing the program to fix this problem" I am getting this error when I try to run a ls command. I have re installed like the pop up suggests. I used the windows installer to install this.

# Answer
> 1 votes
Apparently you have somehow broken your Cygwin installation. In the Cygwin setup.exe, go through the setup sequence until you get to the "Select Packages" screen, then type "intl" in the Search box. Open the Libs section, and click the third column on the "libintl2" line until it says Reinstall. Proceed.

That should fix this one particular problem, but chances are good that if you've lost that one library, you've broken other things, too. A complete Cygwin reinstallation might be in order.

You too can follow this steps for install drush properly:

Installing Drush on Windows

or

Installing Drush on Windows using Cygwin

---
Tags: drush
---


title: content type field not printing

text:
# Question
Title: content type field not printing
In drupal 7, I defined a field for a custom content type and am trying to display its value via page.tpl.php. Nothing is appearing in the rendered page.

Here's the relevant piece of page.tpl.php. The field is 'field\_mast". Note that I added print $title just so I could be sure that this template is being used. It is.

```
    <h1>Perinote™ <?php print $content['field_mast'] ?><br>
       <?php print $title ?> <br>Organize Your Way</h1>

```

My content type fields are:

```
Label  machine name field type            widget
Title  title        Node module element
mast   field_mast   Text                  Text field
Body   body         Long text and summary Text area with a summary

```

And for Manage Display, I have:

```
Field   Label        Format
Body    <Hidden>     Default
mast    Above        Default

```

Finally, for my actual content, I have:

```
Title: Notes contacts....
mast: User Guide
Body <p>This user guide...
Text format: Full HTML

```

Any ideas on what I need to do to get 'mast' to print?

# Answer
> 0 votes
try

```
<h1>Perinote™ <?php print render($content['field_mast']); ?><br>

```

or this one

```
<h1>Perinote™ <?php print render($content['field_mast']->value); ?><br>

```

I recommend you to download and install devel module and write

```
<?php kpr ($content);?>

```

to see what `$content` contains. you can also call this function in `hook_preprocess_page` as well.

---
Tags: 7, nodes
---


# Question
Title: How to change non-color-related CSS after the color module has been used?
I haven't used the color module in years, since I try to avoid it because I know it kind of freezes your CSS changes.

I have a client who has been using color module with a customized version of the Scholarly theme, but does not seem to have the color picker enabled for it.

I'm trying to make some CSS changes for them that have nothing to do with changing colors, but my changes are not reflected on the site. It's pulling in an old version of styles.css. I've cleared the CSS cache and made sure aggregation is turned off on development so I'm pretty sure the color module is the culprit.

How do I clear or regenerate Color module's version of my site CSS?

# Answer
Resave the color settings in the theme; see color\_scheme\_form\_submit().

I'll look into what can be done inside the AdvAgg module: https://www.drupal.org/node/2461039

Edit: I've added this into advagg now. It will regenerate the color css.
> 2 votes

---
Tags: theming, caching
---


# Question
Title: Use drupal.settings variables on javascript
I'm using the Google Maps API on my website regarding restaurants. The map loads when a restaurant has been selected. I was initially using the google embed map, but I got some errors (e.g. markers not showing), so I switched to gm API.

How do I use a drupal.setting variable to a javascript? This is my code.

```
var myCenter = new google.maps.LatLng(Drupal.settings.eatery_geo.address);
function initialize() {
  var mapProp = {
    center:myCenter,
    zoom:16,
    mapTypeId:google.maps.MapTypeId.ROADMAP
  };

  var map = new google.maps.Map(document.getElementById("map-canvas"),mapProp);

  var marker = new google.maps.Marker({
    position:myCenter,
  });

  marker.setMap(map);
}

google.maps.event.addDomListener(window, 'load', initialize);

```

Where **Drupal.settings.eatery\_geo.address** has the variable?

This doesn't seem to work; it only shows a blank `<div>`.

# Answer
It gets its value from your PHP code. Here is an example of using drupal\_add\_js:

```
//Your module.php
$settings = array(
  'helloWorld' => array(
    'display' => 'alert',
    'message' => 'Hello World!',
  ),
);
drupal_add_js($settings, 'setting');

```

You can access the message in your JavaScript with `Drupal.settings.helloWorld.message`.
> 4 votes

# Answer
I was receiving the following error:

> Warning: Illegal offset type in drupal\_add\_js() (line 4230 of /var/www/drupal/includes/common.inc).

Changing the word 'settings' to 'setting' in the drupal\_add\_js() line seemed to fix it for me:

```
 <?php

 $settings = array(
   'helloWorld' => array(
     'display' => 'alert',
     'message' => 'Hello World!',
   ),
 );
 drupal_add_js(array('my_custom_module_name' => $settings), 'setting');

```

I put the above code in a custom module, let's call it my\_custom\_module\_name for this example.

Then put the following in my javascript file:

```
Drupal.behaviors.my_custom_module_name = {
  attach: function(context, settings) {

    // Place your code here.
    // alert(Drupal.settings.my_custom_module_name.helloWorld.message);
    console.log(Drupal.settings.my_custom_module_name.helloWorld.message);

  }
};

```

Make sure your\_theme\_name.info references your js file in order for it to load, for example:

```
scripts[] = js/script.js

```
> 0 votes

---
Tags: javascript
---


# Question
Title: How to alter combined filter value programatically?
When taxonomy terms are combined, the values searched are term id instead of term name. So I tried to alter the query using views\_query\_alter. But it seems the values are coming from object.

```
function MYMODULE_views_query_alter(&$view, &$query) {
 if ($view->name == 'my_view') {
   if (is_object($query->where[1]['conditions'][0]['field'])) {
     foreach ($query->where[1]['conditions'][0]['field']->conditions() as $key => $value) {
        if (is_numeric($key)) {
          $possible_terms[] = $value['value'][':views_combine'];
        }
      }
     // here i was planning to load the term id from the partial
     // term search key from combined filter
     // once the term is identified, i would like to update the query.
   }
 }
}

```

The problem is `$query->where[1]['conditions'][0]['field']->conditions()` is a function and I don't know how to substitute value to it.

# Answer
> 1 votes
The example on the hook\_views\_query\_alter page should get you started. Whet they do here is changing the node title into the node id, by redefining the $condition variable.

```
function hook_views_query_alter(&$view, &$query) {
  // (Example assuming a view with an exposed filter on node title.)
  // If the input for the title filter is a positive integer, filter against
  // node ID instead of node title.
  if ($view->name == 'my_view' && is_numeric($view->exposed_raw_input['title']) && $view->exposed_raw_input['title'] > 0) {
    // Traverse through the 'where' part of the query.
    foreach ($query->where as &$condition_group) {]

// Run through all conditions and pass them by reference.
// (Altering the value here will change it for all things later on.)

      foreach ($condition_group['conditions'] as &$condition) {
        // If this is the part of the query filtering on title, chang the
        // condition to filter on node ID.

//If there is a condition on the title field

        if ($condition['field'] == 'node.title') {

// Overwrite the condition

          $condition = array(
            'field' => 'node.nid',
            'value' => $view->exposed_raw_input['title'],
            'operator' => '=',
          );
        }
      }
    }
  }
}

```

You should be able to copy quite a lot of this function, tweak the initial if statement a bit so it does not filter on title, and substitute your own values.

I have not used a combined filter, but the Views API converts into similar to this. If you add some debug code to find out what the initial array is, you should be able to substitute that.

# Answer
> 0 votes
Don't use ...query\_alter. That will just lead to headaches...

Use HOOK\_form\_alter(&$form, &$form\_state, $form\_id) and in this, assign to $form your new value via something like $form\['#new\_value'\] = "whatever your value is" (which you'll need to do to pass your value on to your validate callback). After that, you then indicate that you need a validation callback by doing the following:

```
$form['#validate'][] = 'nameofyourmodule_validate';

```

Now outside of your ..form\_alter hook, setup your callback as so:

```
function nameofyourmodule_validate(&$form, &$form_state){}

```

...and in that, call form\_set\_value as follows:

```
form_set_value($form['<name of your field you're combine field>'], $form['#new_value'], $form_state);

```

Remember to keep clearing your cache during development / testing. It's so easy to forget doing that when you sometimes need to.

Best of luck and if you need more information, feel free to shoot me a message.

---
Tags: 7, views
---


# Question
Title: Multiple File Uploads fail when webform is placed in a block
I'm in Internet Explorer support hell.

I have a webform which uses Multiple File Uploads. When the form is displayed as a regular node (e.g. www.example.com/node/4), file uploads work as expected.

When the node is shown as a block on another node, file uploads fail with the message:

> An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (20 MB) that this server supports.

Needless to say, all `php.ini` configuration options are in order, (`post_max_size=128M`, `upload_max_size=20M`, etc) and the temp folder is writable.

Uploads fail specifically on Internet Explorer 8 and 9. There is no indication in the log of anything going wrong, just the error message above.

Any ideas?

# Answer
Turns out that I had, due to custom markup added to the `webform`, nested `<form>` tags. Per the spec, this is a big no-no. What happens in the older browsers appeared to have been that the form AJAX submission tried to use the form ID of the most recent `<form>` tag, which, in my case, was empty. It triggered this in `file.module`:

```
if (empty($_POST['form_build_id']) || $form_build_id != $_POST['form_build_id']) {
  // Invalid request.
  drupal_set_message(t('An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (@size) that this server supports.',
    array('@size' => format_size(file_upload_max_size()))), 'error');
  ...
  ...

```

Removing the unneeded `<form>` tags resolved the issue.
> 0 votes

---
Tags: webforms
---


title: Omega 4: Export settings to .info

text:
# Question
Title: Omega 4: Export settings to .info
I'm sure its a simple question but i cannot find any resource to the solution.

In Omega 4, i keep getting this message "The settings for this theme are currently served from a variable. You might want to export them to your .info file".

So how do i do that?

# Answer
> 9 votes
drush omega-export drush omega-revert

or

omega-export --revert

See: http://friendlymachine.net/posts/getting-started-omega-4

# Answer
> 1 votes
I don't have drush on my machine (issues with installation), so i copied theme-settings from Omega and placed it in to the sub-theme and then opened it in Notepad++ and copied and replaced with my new theme name. That message has now gone.

# Answer
> -2 votes
you have to run 'drush omega-guard' and the error will desapear

---
Tags: theming
---


title: MENU_CALLBACK with parent tabs

text:
# Question
Title: MENU_CALLBACK with parent tabs
I have a module with a bunch of menu-items. Is it somehow possible to show the MENU\_LOCAL\_TASK's when a MENU\_CALLBACK is called? The structure basically is like this:

* A normal menuitem in the user-menu
* Some local tasks
* 'test/%user\_uid\_optional/test2' in this example would be an overview-Page with several links as defined in in the last item.

This all works great, except I want the local tasks to be visible when the user clicks on 'test/%user\_uid\_optional/test2/%test'. Since I don't have breadcrumbs that's the only easy way for the user to get back to the overview page. Any idea?

```
function test_menu(){
  $items = array();
  $items['test/%user_uid_optional'] = array(
    'title' => 'test',
    'page callback' => 'test_whatever',
    'page arguments' => array(1),
    'access callback' => 'user_view_access',
    'access arguments' => array(1),
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'user-menu',
  );

  $items['test/%user_uid_optional/test1'] = array(
    'title' => '...',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -20,
  );
  $items['test/%user_uid_optional/test2'] = array(
    'title' => 'test2',
    'page callback' => 'test_whatever_b',
    'page arguments' => array(1),
    'access callback' => 'user_view_access',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => -15,
  );
  $items['test/%user_uid_optional/test2/%test'] = array(
    'title' => '...',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('test_whatever_d', 1, 3),
    'access callback' => 'user_view_access',
    'access arguments' => array(1),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

```

# Answer
never mind, menu\_set\_active\_item('test/%user\_uid\_optional/test2') in test\_whatever (last callback in example) seems to work.

Both item, 'test/%user\_uid\_optional' and 'test/%user\_uid\_optional/test2', are active and visible, and the drupal\_get\_form is executed, so who cares about beauty :)?
> 0 votes

---
Tags: routes
---


# Question
Title: How do you automate text file upload daily to a Drupal Page?
Im trying to create a plugin, possibly through IFTTT, where i can forward an e-mail with a text attachement that will replace a current file on a Drupal page. Has anyone had any success in automating this process? Bascially we're getting a text file sent to us daily that we would otherwise have to manually upload to the page.

# Answer
> 2 votes
it's much more simple, use Mailhandler

https://www.drupal.org/project/mailhandler

Mailhandler can connect your inbox and with feed you fetch the messages, so basically you need to run the feed using cron job. you will find all of that in the configuration of the feed and mailhandler.

Also you can map the attachment with the field where you keep your text file, I don't think there is need to create any plugins, everything you need in mailhandler & feed.

---
Tags: files
---


# Question
Title: Using Rules and Content access to restrict node access after date
**The Goal**

I am working on a way to shut off access to all nodes of a given type by setting their Content Access permissions to off, after a certain date has passed (and presuming that their access levels are not presently set to not allow anyone to see them, as I don't want this to trigger every time the rules run in a date range). Rules + Content Access was suggested to me in the #drupal IRC channel, but I'm not totally sure it is going to work.

**What I've done so far**

* I have added a rule to be triggered when Cron Maintenance tasks run.
* I added a "Data Comparison" rule to check site:current-date and see if it is past a certain value.

**The Issue**

When I go in to add the action of "Revoke Access By Role", I do not have the option to set on which content types I want the access revoked by. In fact, the only option in the selector is site:.

I have also attempted to add a node condition, but there is also no way to select any node fields, presumably because it's wanting to act on whatever triggered the event (i.e. Content Updated in the case of nodes), and since I've selected a cron I only have access to the site: parameters.

**My Question**

Is there a way to tell rules to change the content permissions for all nodes of a content type via a cron maintenance run, or will I need to write a custom method to be triggered via the rules condition? (Or a completely separate module for that matter).

# Answer
> 1 votes
A proposition:

1. Enable "Rules Sheduler" at `/admin/modules`.
2. Go to `/admin/config/workflow/rules/components` and create a component
    * Add new component:
        + Component plugin =\> `Action set`
        + "Continue"
    * Component plugin:
        + Specify the component name (e.g. Revoke node access component)
    * choose in the table:
        + Data type =\> Content
        + Label =\> `Node:Component` or `Node` or what you want
        + Machine name =\> `node_component` or `node` or what you want
        + Usage =\> `Parameter`
        + "Continue"
    * Add actions:
        + Select actions to add =\> `Revoke access by role`
        + Data selector: *is set as `node-component` by default; this is the selector name you have specified in the table in the step above*
        + In "Role-based access control settings" **check** roles you want to revoke access for view/edit/delete content
        + "Save"
3. Go to `admin/config/workflow/rules` and add new rule (Add new rule):
    * Add new rule:
        + specify the rule name (e.g. Revoke node access rule)
        + React on event =\> `After saving new content`
        + Restrict by type =\> *optionally, choose a node type you want to apply this rule to*
        + "Save"
    * Events:
        + (optionally) you may also add here "After updating existing content" event if the rule has to triggered on existing nodes
    * Conditions:
        + (optionally) add your additional conditions here
    * Actions:
        + Add action
        + Select the *action* to add =\> `Schedule component evaluation`
        + Component: Select yor component you have already created (Revoke node access component)
        + Continue
        + Scheduled evaluation date:
        + click the "Switch to data selection and specify" button and specify:
            - Data selector: `node:created` (or other date-based condition)
            - Add offset: optionally specfify an offset for the chosen data selector (e.g. `1 seconds`)
        + Identifier: Specify an identifer ("A string used for identifying this task") which is visible (Rules) "Scheduler" (`/admin/config/workflow/rules/schedule`) and in "Recent log messages" (`/admin/reports/dblog`). You may use tokens/replacement patterns.
        + Node:Component:
        + Data selector =\> `node`
        + Save

**What's this?**

This solution triggers a rule **after** a *new* and/or *existing* node has been saved. The rule "schedules" the component with an action set - in our case, the action is to revoke node access to the **checked** user roles. After content has been added as new and or edited, the component revokes node access on nodes for specified roles as scheduled **on cron run**, e.g. adding new article now +1 sec makes it unaccessible (view/edit/delete) on next cron on \> (`node:created` +1 sec).

**Hint:**

It is also possible to add `Schedule component evaluation` as an action into a component. For example: you want this rule to be triggered using `node:changed` date, so every time you edit a node, the date for the action "Revoke node access" will be moved forward (e.g: node is changed now =\> the rule triggers in 1 day (offset in component settings); the node will be changed tomorrow, so the rule will be trigerred on tomorrow date +1 day and so on).

---

You can import and test the component:

```
{ "rules_revoke_node_access_component" : {
    "LABEL" : "Revoke node access component",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "content_access_rules" ],
    "USES VARIABLES" : { "node_component" : { "label" : "Node:Component", "type" : "node" } },
    "ACTION SET" : [
      { "content_access_action_revoke_node_permissions" : {
          "node" : [ "node-component" ],
          "permissions" : { "value" : [
              "view:2",
              "view:1",
              "view:3",
              "view_own:2",
              "view_own:1",
              "view_own:3",
              "update:2",
              "update:1",
              "update:3",
              "update_own:2",
              "update_own:1",
              "update_own:3",
              "delete:2",
              "delete:1",
              "delete:3",
              "delete_own:2",
              "delete_own:1",
              "delete_own:3"
            ]
          }
        }
      }
    ]
  }

```

## }

You can import and test the rule:

```
{ "rules_revoke_node_access_rule" : {
    "LABEL" : "Revoke node access rule",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "node_insert" : [], "node_update" : [] },
    "DO" : [
      { "schedule" : {
          "component" : "rules_revoke_node_access_component",
          "date" : { "select" : "node:created", "date_offset" : { "value" : 1 } },
          "identifier" : "Revoke node access",
          "param_node_component" : [ "node" ]
        }
      }
    ]
  }
}

```

# Answer
> 0 votes
You should create rule invoked by cron run, list all nodes what you want to change and in loop for every node set permissions you want.

---
Tags: nodes, rules, users
---