title: OG - Apply membership to children

text:
# Question
Title: OG - Apply membership to children
I'm wondering if there is en option to apply og membership to all the entity referenced children of an node.

I have a content type 'Enterprise' which can reference itself to create a structure of enterprises. F.e. (Enterprise 1 --\> Subenterprise 1 --\> Subsubenterprise 1)

When enterprise 1 is added to a group all dependent nodes should be added also.

Thanks in advance for your advice

# Answer
You can do that with Views Rules.

1. Create a view that gives all directly referred children of a node (with the node as contextual filter), give it a "Rules" display.
2. Now create a Rules component that takes as argument a node, runs a "View Loop" (you'll see what that is as soon as you've installed the above mentioned module) over your newly created view.
3. To this loop, add an action that adds the current loop item to your organic group. Save the component.
4. Add a second action to the loop, which is the component itself, with the current loop item as an argument. (I haven't actually tried this.)
5. You can call this rule component from within other rules that you can trigger in many ways, say by clicking a simple button or by performing a bulk operation.

My two cents:

* Be careful with this, since it is recursive. If you have two enterprises linking each other, then this will recurse infinitely and crash. Maybe add as a precondition in the rule component that the node is not yet a member of the group.
* Decide whether you want to use entity references or organic groups for this, but don't use both. What you're trying to do sounds a lot like you have a network of enterprises and sub-enterprises and you want to translate your existing network into organic groups. If someone adds new references, you'll have to update your groups, which is annoying. Decide between entity references and organic groups and get rid of the other.
> 0 votes

---
Tags: organic-groups
---


# Question
Title: How to access Views administration in Commerce Kickstart 7.x-2.9
I can't seem to get into the Views administration panel from any place in Commerce Kickstart 7.x-2.9. There is no menu entry even with Administration menu installed. Trying to configure via the link for Views on the modules admin page simply sends the page to the Administration menu with no "Views" option. Likewise directly entering siteurl/admin/views goes to the same place.

I guess the Views access is overridden by the Kickstart configuration.

Does anyone know a way around this?

# Answer
I eventually figured this out. With Administration Menu Module installed, views is not available - it seems like the menu links do not get built.

There is a big problem with simply uninstalling the Administration Menu and re-enabling the Commerce Kickstart Menu module. According to https://drupal.org/node/1877594#comment-7500586. "When Commerce Kickstart Menus gets disabled, due to #550254: Menu links are sometimes not properly re-parented Management menu is not being properly rebuilt, hence it will look broken."

In order to get to views I had to uninstall Commerce Kickstart Menu module, apply the patch discussed, then reinstall and re-enable it.
> 1 votes

# Answer
If you have not made any changes and are logged in as admin then the menu link should be under `Site Settings -> Visual and Layout -> Views`
> 1 votes

# Answer
The original chosen solution is old and now outdated it seems. All I had to do was go to modules page and disable Commerce Kickstart Menus (if not already disabled) then go to modules uninstall page and uninstall Commerce Kickstart Menus. Now from the `/admin/structure/menu/manage/management` I can just re-adjust any menus that seem out of place and all control has been relinquished to the UI as would be expected.
> 0 votes

---
Tags: views, 7, commerce
---


title: Can I rename a module?

text:
# Question
Title: Can I rename a module?
I foolishly created a `features` module and named it `events`. This is bad because, of course, there is a registered module with that same name. So the update status report is always in error and `drush` has to lock the module so it doesn't attempt to "update" it.

I would rather not uninstall, recreate, reinstall because I will have to recreate content (yes, I have backup/restore installed).

Is it possible (advisable) to rename the directory and files, edit the `.info`, and edit the record in `system`?

```
     ericx ** drupal_addicted ** Wed Sep  3 15:26:29 2014
     sql> select * from system where name='events'\G
    *************************** 1. row ***************************
          filename: sites/dev.addictedtoagility.com/modules/custom/events/events.module
              name: events
              type: module
             owner:
            status: 1
         bootstrap: 0
    schema_version: 0
            weight: 0
              info: a:11:{s:4:"name";s:6:"Events";s:11:"description";s:49:"Adds the Events content type and supporting stuff";s:4:"core";s:3:"7.x";s:7:"package";s:8:"addicted";s:7:"version";s:7:"7.x-0.1";s:7:"project";s:6:"events";s:12:"dependencies";a:8:{i:0;s:4:"date";i:1;s:11:"event_sites";i:2;s:8:"fe_block";i:3;s:4:"file";i:4;s:4:"list";i:5;s:14:"node_reference";i:6;s:9:"strongarm";i:7;s:5:"views";}s:8:"features";a:7:{s:6:"ctools";a:2:{i:0;s:21:"strongarm:strongarm:1";i:1;s:23:"views:views_default:3.0";}s:17:"fe_block_settings";a:1:{i:0;s:20:"views-events-block_1";}s:12:"features_api";a:1:{i:0;s:5:"api:1";}s:5:"field";a:5:{i:0;s:22:"node-event-field_dates";i:1;s:33:"node-event-field_event_event_site";i:2;s:22:"node-event-field_judge";i:3;s:24:"node-event-field_premium";i:4;s:27:"node-event-field_start_time";}s:4:"node";a:1:{i:0;s:5:"event";}s:8:"variable";a:14:{i:0;s:23:"comment_anonymous_event";i:1;s:26:"comment_default_mode_event";i:2;s:30:"comment_default_per_page_event";i:3;s:13:"comment_event";i:4;s:27:"comment_form_location_event";i:5;s:21:"comment_preview_event";i:6;s:27:"comment_subject_field_event";i:7;s:25:"date_format_month_and_day";i:8;s:33:"field_bundle_settings_node__event";i:9;s:18:"menu_options_event";i:10;s:17:"menu_parent_event";i:11;s:18:"node_options_event";i:12;s:18:"node_preview_event";i:13;s:20:"node_submitted_event";}s:10:"views_view";a:1:{i:0;s:6:"events";}}s:3:"php";s:5:"5.2.4";s:5:"files";a:0:{}s:9:"bootstrap";i:0;}

```

1 row in set (0.00 sec)

# Answer
Renaming a Drupal feature requires additional steps than rename a custom module.

## Solution 1 (without un/install)

1. **Backup the DB.**
2. Put the site on maintenance mode.
3. Rename the feature with an IDE or bash script (don't access/edit any content of the site while you are doing this).
4. Run:

* `drush php-eval 'registry_rebuild();'`
    * `drush updb -n`. (forces drupal to reload caches related to module/features)
    * `drush cc all`

## Solution 2 (more proved but requires un/install)

1. **Backup the DB.**
2. Follow the steps to rename the feature on this thread.

To replace the new name (the human and the machine name) on each file, I suggest you to use an IDE like NetBeans (or similar).

You can also use cool unix commands like sed and find to do it.

Try to make a code review after the changes to make sure that the rename was done on the right places.

Note: to make sure that the name I choose for a module/feature is not already used, I use the following command:

```
drush pm-list --type=Module --no-core --status=enabled --pipe | sort

```
> 3 votes

---
Tags: 7, database, features
---


# Question
Title: /README.txt: UTF-8 Unicode (with BOM) English text, with CRLF line terminators
I have been working on a Drupal.org project and I want to make sure that pass all the coding standards. For some reason I got these problem with the README.txt encoding and I dont know how to solve it.

```
 ./README.txt: UTF-8 Unicode (with BOM) English text, with CRLF line terminators README.txt

```
* Bad line endings were found, always use unix style terminators
* ./README.txt: the byte order mark at the beginning of UTF-8 files is discouraged, you should remove it.

Can anyone tell me how to solve this problem ? I'm currently using Sublime Text 2 and I save my README.txt as UTF-8 Unicode with BOM and this did not fix my problem.

Here is the README.txt https://gist.github.com/darol100/e24059dbacc4f7e205ad http://pareview.sh/pareview/httpgitdrupalorgsandboxdarol1002309319git

# Answer
In Settings - User config, you should set

```
"default_line_ending": "unix",

```

Also, when saving file, select UTF-8 Unicode **without** BOM - that's exactly what you were told here:

> the **b**yte **o**rder **m**ark at the beginning of UTF-8 files is discouraged

Emphasis mine.

Taken from Fixing Sublime Text 2 line endings?
> 3 votes

---
Tags: coding-standards
---


title: Views ajax not enabling

text:
# Question
Title: Views ajax not enabling
i'm trying to use an exposed filter with my views but i'm not getting my ajax to enable under the advanced link so my content can be dynamic. I try jquery update module to fix it but didn't work tried another browser didn't work too i really need help here...

# Answer
The "use ajax" checkbox in Views refers to the pager only. Any other magic you may want to work with ajax would require some custom code or additional modules, depending on what you're doing.
> 0 votes

---
Tags: 7, views
---


title: Multilingual homepage

text:
# Question
Title: Multilingual homepage
I am currently in the proses of making my first multilingual Drupal site. Using the i18n module I have been able to get separate menus and their respective pages.

My problem is that the content on the home page, with the theme that I'm using is created/edited via a page.tpl.php file. Do I need to duplicate this file and have one for each language? If so how to I go about this?

This is the site: http://www.lac-de-montbel.com/

Thanks in advance.

# Answer
No, you don't need to duplicate file, just go to `/admin/config/regional/translate/translate` and search for what you want to translate.

To be able to translate strings or variables from custom page.tpl.php file, all of them in the file need to be translatable, ie. to be in `t()` function, so if you can't find words that are from some custom .tpl.php file, make sure that particular string or variable in the file is translatable (in form like I mention).

For more information about using function `t()` look this.
> 0 votes

---
Tags: i18n-l10n
---


# Question
Title: How to show an Inline Entity Form on a PM page or panel?
I'm trying to include an Inline Entity Form on a panels display (via ctools Page Manager).

The Inline Entity Form field is attached to users, and the page in question has the user's context.

The Inline Entity Form field does appear in the panels interface, in two different ways, but neither work:

* As a "User" field content type
    + It simply displays the text `1`
* As a "User (tokens)" content type
    + It simply displays the text `1`
* As a "Form" content type
    + It simply display the text `Entity info`

# Answer
This is a very crude, brute force answer. Basically, it's: create a PHP block that loads the user edit form with all fields except the Inline Entity Form field hidden, then display it.

* Enable PHP Filter module (part of Core but disabled by default)
* Create a new block with this code:

..

```
<?php
global $user;
module_load_include('inc', 'user', 'user.pages');
$account = user_load($user->uid);
$form = drupal_get_form('user_profile_form', $account);
print render( $form );
?>

```
* Hide the fields except the ones you want. Two ways to do this:

+ The tricky, 'proper' way: in the block, hide the array elements in `$form` by either unsetting or setting type to hidden. There could be complications with this.
    + The quick and dirty but safe way: just set them to `display: none;` with CSS. This way the full form is present and unadulterated, but invisible.

---

This is fine unless you're adding a multiple values Inline Form to a user profile. If that's the case, when you try to add a new item to the multiple value field, you'll hit this error:

> **Call to undefined function user\_profile\_form\_validate()**

It's because the AJAX doesn't know it's dealing with a user form and so doesn't think to load the necessary pages from the user module. The only way around that I can find is to create a custom module with the following (then flush caches etc):

```
function custom_module_name_init() {
    module_load_include('inc', 'user', 'user.pages');
}

```

This isn't ideal since it loads a page of code which is normally unnecessary everywhere - but the overheads for PHP scanning then ignoring one sheet of code are pretty small. If anyone knows a cleaner way to do this, however, please share it!
> 0 votes

---
Tags: entities
---


# Question
Title: drupal_add_js settings and working around the anonymous page cache
What I'm trying to do is allow registered users to configure a few colors on public facing pages (profiles, etc.) and to do so I'm using the ColorField module and a few theme functions.

My problem is that the anonymous page cache is caching values stored in Drupal.settings, preventing changes from being visible until the page cache is cleared.

Here is the code I currently use to set Drupal.settings:

```
<?php
function themeName_preprocess_page(&$vars) {
  $branding = array(
      'header_bg' => '#ffffff',
      'accent' => '#0b40ac'
  );
  drupal_add_js(array('pageRebranding' => $branding), array('type' => 'setting'));
  drupal_add_js(drupal_get_path('theme', 'themeName') .'/js/branding.js');
}
?>

```

Disabling the anonymous page cache (globally or selectively) is not an option.

Is there a way I can pass values to Drupal.behaviors using ajax on page load, or another method to get around the anonymous page cache?

Here is my JS:

```
(function ($) {

    Drupal.behaviors.pageRebranding = {
        attach: function (context, settings) {
            var header_bg = Drupal.settings.pageRebranding.header_bg;
            var accent = Drupal.settings.pageRebranding.accent;
            /* Do Stuff */
        }
    };

})(jQuery);

```

# Answer
> 0 votes
Using jQuery and an AJAX callback can be used to get and apply changes to a page even if it is already in the anonymous page cache.

First create a callback function that will return JSON results.

```
function hook_menu() {
  $items['branding/ajax/%'] = array(
    'page callback' => '_branding_ajax_callback',
    'page arguments' => array(2),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function _branding_ajax_callback($uid) {

  //Branding Defaults
  $branding = array(
      'header_bg' => '#ffffff',
      'accent' => '#0b40ac',
      'logo' => theme_get_setting('logo', 'theme'),
      'logo_url' => 'http://example.com',
  );

  return drupal_json_output($branding);
}

```

Next, create the JavaScript that will make the AJAX call and then apply the changes over the cached page.

```
(function ($) {
    Drupal.behaviors.hookRebranding = {
        attach: function (context, settings) {
            var json_url = 'http://example.com/branding/ajax/' + user_brand_id;

            $.ajax({
                dataType: "json",
                url: json_url,
                cache: false,
                success: function(data) {

                    $("#footer-wrapper").css( "border-top", data['accent'] + " 6px solid" );
                    $(".header-group-wrapper").css( "border-bottom", data['accent'] + " 3px solid");
                    $("#logo a img").attr("src", data['logo']);
                    $("#header-group-wrapper").css( "background-color", data['header_bg']);
                    $("h1, h2, h3, h4, h5, h6, a, a:link, a:visited").css( "color", data['accent']);
                }
            });

        }
    };
})(jQuery);

```

Don't forget to include the JavaScript in your theme.

```
function THEME_preprocess_page(&$vars) {
  drupal_add_js(drupal_get_path('theme', 'omr') .'/js/branding.js');
}

```

# Answer
> 0 votes
You can avoid the cache by calling your file using

```
drupal_add_js(drupal_get_path('theme', 'themeName') .'/js/branding.js', array('cache' => FALSE));

```

---
Tags: javascript
---


# Question
Title: How to actually set a maxlength for textarea field in contact form
I need to limit the textarea message of the core module contact form to a certain number of characters.

Here are the facts

1. The Form API does not allow one to set a maxlength on textarea field types \[while plain HTML does\]
2. The Maxlength module , doesn't allow you to actually set a maximum length. It gets its max length from the field's max length, defined on each content type's manage field section
3. Creating a new form element type using hook\_element\_info, still doesn't gurantee I can add the `#maxlength` to the textarea. Besides if I succeed I need to alter again the contact form module to overrride actual message textarea field with mine.

So I can I alter it plain and straightforward?

What is the best idea to alter all textarea fields in the website?

# Answer
Firstly off I defined a setting form, then made a hook form alter:

```
function contact_form_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'contact_site_form') {
    $maximum_limit = (int) variable_get('contact_form_maxlength', 500);
    if($maximum_limit && is_numeric($maximum_limit)) {
    $form['message']['#title'] = $form['message']['#title'] . t(' (maximum @max characters)', array( '@max' => $maximum_limit));
    $form['message']['#maxlength'] = $maximum_limit ;
    }
  }
}

```

This seems to be working fine.
> 4 votes

# Answer
> The Form API does not allow to set a maxlength on textarea field types \[while plain HTML does\]

That's not strictly true....HTML5 introduced a maxlength property for textareas, previous versions do not have it (see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea).

The default templates that come with Drupal 7 all use XHTML, so the lack of explicit support for HTML5 makes perfect sense.

As long as your doctype *is* HTML5, this will probably work:

```
$form['element'] = array(
  '#type' => 'textarea',
  '#attributes' => array('maxlength' => 200),
);

```
> 6 votes

# Answer
You can use Maxlength module like this, put both #maxlength and #maxlength\_js properties on the elements you want to control.

```
$form['comments'] = array(
  '#type' => 'textarea',
  '#title' => t('Comments'),
  '#maxlength_js' => TRUE,
  '#maxlength' => 1000,
);

```
> 6 votes

---
Tags: forms, emails
---


title: Ready-Only Select

text:
# Question
Title: Ready-Only Select
On select of one dropbox, I have the values of 2 others updating automatically via Ajax/JS. This works, well, but I also want to disable the ability for users to change these values/

I tried setting these two fields to 'disabled', but when I do this - the auto-select values don't save.

# Answer
There's nothing such as read only in select tag. If you want to disallow user from changing the select tag's selected option, then you can disable it and enable it using javascript before the form is submitted.

If you want to disable the select box, then you can use a javascript code to enable it back before the form submits. So on the onsubmit event of the form, you can enable the select box so that its value is also submitted when the form is submitted.

Hope it will work for you!
> 0 votes

# Answer
**Disable** attribute does exist for **select tag** also. Rest of the process is already explained by above answer. By default select box will be disabled with the choosen value, Now add a click event on the submit button to remove disable attribute from select box so its value should post successfully.

Hope it will help!
> 0 votes

---
Tags: forms
---


# Question
Title: Change Login Form:Username to Select Text
Is it possible to change the login form? Specifically the Textbox for username to select text?

Let's say I have 4 users named: User1,User2,User3,User4 and when select text is clicked. All users will be listed as a choice?

PS: I'm very new to drupal detailed help will be appreciated.

# Answer
Yes we can do it using function **hook\_form\_alter(&$form, &$form\_state, $form\_id)** {}

Just include this function in **template.php** of your theme or in you module.

If you theme name is "testtheme" then replace **hook** with you theme name(**testtheme**).

OR you can include it in your custom module. If you have custom module with name "testmod" then just add this code in your module and replace the **hook** with your module name (**testmod**)

```
function **hook**_custom_form_alter(&$form, $form_state, $form_id){

    //Get the users  from database or keep it static according to requirement
    $users  =   array("user1"=>"User 1","user2"=>"User 2","user3"=>"User 3");
    if($form_id=="user_login"){
    $form['name']['#type'] = "select";
    $form['name']['#options'] = $users;
    $form['name']['#required'] = true;
   $form['name']['#size']='auto';

    }

    }

```

Don't forget to clear drupal cache. Hope it will help!
> 0 votes

---
Tags: users, forms
---


# Question
Title: Turn off responsive behavior for Bootstrap 3
I know how to turn off responsive in bootrap. but how it can be in drupal theme. As i am using Drupal Bootstrap and created a subtheme. can that subtheme be non-responsive ??

# Answer
You can reset Media queries breakpoints, it will not work. Here is path: bootstrap/bootstrap\_subtheme/less/variable.less at line number 209.

Check it.
> 1 votes

---
Tags: bootstrap-theme
---


# Question
Title: Module is shown as installed but I can't access its settings
I have Drupal 7 installed and I am trying to install Webform module. Firstly the page shows " The website has faced some unexpected error" and then after re-accessing the Modules page, it shows the Module to be enabled and links to it's settings as well.

But when I go to Create Content, I don't see any Webform option.

This is the error generated in the Reports / Log.

> DatabaseSchemaObjectExistsException: Table webform already exists. in DatabaseSchema-\>createTable() (line 657 of /home/evosysgr/public\_html/includes/database/schema.inc).

Kindly suggest what is to be done.

# Answer
> 0 votes
Generic way when you face

> The website has faced some unexpected error

when enabling module is:

1. Find in logs what error was it
2. Fix it's cause
3. Disable and uninstall module you was enabling
4. Enable it again

Alternatively, if you have backups, **better** way would be:

1. Find in logs what error was it
2. Fix it's cause
3. Restore site from backup to it's state from just before error
4. Try again

If you have *specific* problem with this way, ask new question, explaining exactly what you need to know, what you did, what was in logs and so on.

---
Tags: 7
---


# Question
Title: Filter criteria according to the get variable user/*
have allowed certain roles user pages to been seen by an anonymous user. I have then created a block that displays the latest post of the role user pages.

Is there a way in views to create a filter criteria from the get variable of the anonymous users URL

For example user/30 profile page is requested from the anonymous user. The view gets the id 30 from the url and then sorts the posts in the block view according to that users id

**Below I have added some images on the view.**

When an anonymous user accesses the authors user profile via the url it needs to display the content the author has created in the block view. The block itself only displays on the user pages by the use of user/\* in the block configuration.

I hope this helps thanks again

# Answer
Here are the steps to achieve your requirement

Go to view and add contextual filter User: uid

Then select 'Provide default value' and select Type : 'Raw value from URL' and Path component: 2 (as URL is user/\* .we select second component to get User ID)

That's it. I've tested this and working perfect.

Hope it helps.
> 1 votes

---
Tags: views
---


title: Export node to Ms Word file

text:
# Question
Title: Export node to Ms Word file
I would need to export nodes in Ms Word format.

I would need to mantain the node structure or to apply a template.

I don't want to export data in a table like "Views data export" module does.

In Drupal 6 it was done using "node to word" module (https://drupal.org/project/node\_to\_word), but the module doesn't exist for Drupal 7.

thank you in advance

# Answer
The module Views data export claims to do it:

> Style plugins are included that support exporting in the following types:
>
> ```
> CSV
> Microsoft XLS
> Microsoft DOC
> Basic TXT
> XML.
>
> ```

So you should be able to construct a view of fields or rendered entities and select the display for a doc file.

See a similar question here: Export node report base on Word and Excel template
> 2 votes

# Answer
In stead of including all fields used in the content type you want to export to Doc with Views Data Export you gotta choose the 'Rendered Content' field, set display to 'show complete entity' and view mode to 'full content'.

That way the entire node gets rendered into one column of the table:

```
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  </head>
  <body>
    <table>
    <thead><tr><th>Rendered Content</th></tr></thead>    <tbody>      </tbody>
    </table>
  </body>
</html>

```
> 1 votes

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


# Question
Title: How can I replace certain strings in variable table all at once?
I would like to replace all the 'aaaa' strings with 'bbbbbb' in value column of variable table.

I was initially trying to do that with just a simple query like this.

```
UPDATE variable SET `value` = replace(`value`,'aaaa','bbbbbb')

```

But this didn't work properly and I was taught that also the number between `s: and :"` in value column has to be changed accordingly.

So variable\_set seems to be the way to go but I'm not able to get it work.

https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/variable\_set/6

How can I do this?

# Answer
The variable holds serialized data, so you can't modify what you want with a simple query. You have you to get every variable value with variable\_get, process the value making the needed replacement and the save the variable using varaable\_set.

You can get all vlaues with this snippet:

```
$variables = db_query('SELECT name FROM {variable}');

foreach ($variables as $variable_name) {
  $variable_value = variable_get($variable_name, NULL);
  $fixed_variable_value = your_replace_function($variable_value);
  variable_set($variable_name, $fixed_variable_value);
}

```

You will need the your\_replace\_function(). This function must deal with all possible values because $variable\_value can be a number, a string, an array, object or any other PHP type. In case of arrays and object the function must process its nested components.
> 2 votes

---
Tags: 6
---


# Question
Title: Form API: fomatting the date select lists?
I'd like to format my date select input, using the following time formats:

* *12-hour format of an hour without leading zeros*
* *Minutes with leading zeros*

Here's my form definition:

```
  $form['scheduled_for'] = array(
    '#type' => 'date_select',
    '#title' => t('Scheduled for'),
    '#date_label_position' => 'within',
    '#date_format' => 'd-F-Y g:i',
    '#date_increment' => 15,
    '#date_year_range' => '-0:+3',
    '#default_value' => time(),
  );

```

However, the hours format as *24-hour format of an hour without leading zeros* (code G).

It's as if 'g' is being turned into 'G'. Any ideas? Thanks.

# Answer
In `date_parts_element()` there's the line

```
$hours_format  = strpos(strtolower($element['#date_format']), 'a') ? 'g': 'G';

```

This is deciding on whether to be 24 hour on the presence of the AM/PM specifier. If you change the format to `d-F-Y g:i a` it should work I think.

If you don't want to display the AM/PM specifier, but fix it at a particular value, you can do something like this

```
  ...
  // Add a new process function to this date_select to hardcode am/pm.
  $info = element_info('date_select');
  $process = $info['#process'];
  $process[]= 'MYMODULE_date_select_process_am_only';

  $form['scheduled_for'] = array(
    '#type' => 'date_select',
    '#title' => t('Scheduled for'),
    '#date_label_position' => 'within',
    '#date_format' => 'd-F-Y g:i a',
    '#date_increment' => 15,
    '#date_year_range' => '-0:+3',
    '#default_value' => time(),
    '#process' => $process,
  );
  ...

/**
 * #process callback for a date_select element that removes the AM/PM specifier
 * and hardcodes its value to AM.
 */
function MYMODULE_date_select_process_am_only($element) {
  $element['ampm']['#type'] = 'value';
  $element['ampm']['#value'] = 'am';

  return $element;
}

```

It's untested but works in my head (: If you wanted to do the same thing on a number of different forms, there's a more elegant way (let me know if you're interested).
> 4 votes

---
Tags: forms, datetime
---


# Question
Title: Drupal Commerce: Number of a sales per product
How can I find the number of sales for a particular product in Drupal commerce?

# Answer
With this view I solved: https://www.drupal.org/node/1292104#comment-8524109 Just import it and play around for get what you want.
> 2 votes

# Answer
Use the Commerce Reporting module and get a lot of other relevant shop stats

> This module provides a reporting system for Drupal Commerce.
> 2 votes

---
Tags: 7, commerce
---


# Question
Title: Drush - "Failed to get available update data" for all modules
**Problem**

I'm trying to use drush to update a module. However all updates fail and automatically rolled back because it can't find any update data:

```
Failed to get available update data for one project. [18.1 sec, 70.14 MB]   [error]

```

It's a brand new environment, but I've migrated in my dev environment using Backup and Migrate.

The problem is documented here, apparently it is something to do with migration for a new domain. (Although somehow I've never bumped into it before).

The solution mentioned is manually dump the cache\_update table, however I dumped it and I'm still getting the error.

On wiping the table and then re-running `drush up modulename`

I get an output like this (I've shown two segments, I get 15 on running it, left out for brevity):

```
Bootstrap to phase 0. [0.03 sec, 2.79 MB]                            [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drush() [0.03 sec, 3.01 MB] [bootstrap]
Bootstrap to phase 6. [0.08 sec, 6.7 MB]                                                                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_root() [0.08 sec, 6.7 MB]                                                                                [bootstrap]
Initialized Drupal 7.31 root directory at /srv/www/mysite.net/public [0.11 sec, 8.32 MB]                                                                                [notice]
Drush bootstrap phase : _drush_bootstrap_drupal_site() [0.11 sec, 8.33 MB]                                                                                [bootstrap]
Initialized Drupal site default at sites/default [0.11 sec, 8.33 MB]                                                                                [notice]
Drush bootstrap phase : _drush_bootstrap_drupal_configuration() [0.14 sec, 8.8 MB]                                                                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_database() [0.14 sec, 8.82 MB]                                                                                [bootstrap]
Successfully connected to the Drupal database. [0.14 sec, 8.82 MB]                                                                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_full() [0.15 sec, 9.92 MB]                                                                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_login() [0.72 sec, 63.3 MB]                                                                                [bootstrap]
Successfully logged into Drupal as Anonymous (uid=0) [0.72 sec, 63.31 MB]                                                                                [bootstrap]
Found command: pm-update (commandfile=pm) [0.72 sec, 63.31 MB]                                                                                [bootstrap]
Initializing drush commandfile: user [0.72 sec, 63.31 MB]                                                                                [bootstrap]
Including /usr/share/drush/commands/pm/updatecode.pm.inc [0.74 sec, 64.06 MB]                                                                                [bootstrap]
Executing: wget --version
Running: /usr/share/drush/drush.php  --root='/srv/www/mysite.net/public' --uri='http://default' batch-process '923' --backend  2>&1 [1.77 sec, 69.6 MB]                                                                          [command]
Bootstrap to phase 0. [2.87 sec, 69.65 MB]                                                                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drush() [2.87 sec, 69.65 MB]                                                                                [bootstrap]
Bootstrap to phase 6. [2.87 sec, 69.65 MB]                                                                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_root() [2.87 sec, 69.65 MB]                                                                                [bootstrap]
Initialized Drupal 7.31 root directory at /srv/www/mysite.net/public [2.87 sec, 69.65 MB]                                                                                [notice]
Drush bootstrap phase : _drush_bootstrap_drupal_site() [2.87 sec, 69.65 MB]                                                                                [bootstrap]
Initialized Drupal site default at sites/default [2.87 sec, 69.66 MB]                                                                                [notice]
Drush bootstrap phase : _drush_bootstrap_drupal_configuration() [2.87 sec, 69.66 MB]                                                                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_database() [2.87 sec, 69.66 MB]                                                                                [bootstrap]
Successfully connected to the Drupal database. [2.87 sec, 69.66 MB]                                                                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_full() [2.87 sec, 69.66 MB]                                                                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_login() [2.87 sec, 69.66 MB]                                                                                [bootstrap]
Successfully logged into Drupal as Anonymous (uid=0) [2.87 sec, 69.67 MB]                                                                                [bootstrap]
Found command: batch-process (commandfile=core) [2.87 sec, 69.67 MB]                                                                                [bootstrap]
Initializing drush commandfile: user [2.87 sec, 69.67 MB]                                                                                [bootstrap]
Batch process has consumed in excess of 50% of available memory. Starting new thread [2.87 sec, 69.67 MB]                                                                                [batch]
Command dispatch complete [2.87 sec, 69.67 MB]                                                                                [notice]
Peak memory usage was 64.05 MB [2.87 sec, 69.67 MB]                                                                                [memory]
Undefined index: drush_batch_process_finished batch.inc:61 [2.87 sec, 69.67 MB]

```

Which is presumably it refilling the table before going back to normal behavior. Has anyone else found the cache\_update solution didn't work? Am I misunderstanding what I need to do?

# Answer
I "solved this" by updating drush from its default apt-get version (4.5) to the latest dev branch (5.0-dev).

I did this by running:

`sudo drush self-update`

By this point I'd already flushed `cache_update` so it's entirely possible both steps are needed to solve the problem.
> 1 votes

---
Tags: 7, drush, updating
---


# Question
Title: How can I create a birthday calendar using the Date and Calendar modules?
I have a content type that represents a person, and this content type has a CCK Date field "birthday". I'd now like to add a list of upcoming birthdays and a calendar where they are displayed.

I'm already using the Calendar module for events on that site, but the birthday stuff seems to be more difficult. I can't use the Birtdays module as I'm working with nodes, not user profiles. And the Date field doesn't seem to support this use case, I can't create a view that only shows upcoming birthdays because I see no way to ignore the year for that calculation.

What would be the easiest way to implement such a birthday calendar?

# Answer
You can try with Birthdays module. It allows users to add their birthday to their profile.

> The Birthdays module allows users to add their birthday to their profile. It also lists birthdays on a seperate page and in different blocks. Users can receive an e-mail on their birthday automatically, and the administrator can receive periodic reminders of who are having their birthday. Uses Profile module from core.
> 2 votes

# Answer
The only way I've been able to accomplish this is by having two fields. One I've called field\_born and the other called field\_birthday.

Using the node\_presave hook, field\_birthday is a copy of the field\_born date replacing the year with the current year. Then you use that field in your calendar display.

The only problem I've run into is what will happen next year. I'll have to recalculate all my birthdays. Using SQL wouldn't be tough. But, it would be nice to have it be automatic. Maybe something can be done with an annual cron job on Jan 1st?

Also, this limits your calendar view to the current year. Otherwise, future and past years are empty.

So, hopefully this is closer to what you want. But there's still problems with it. What would be nice is a way to save a date where the year was dynamic somehow. Or if the event was repeated annually. Not sure how to do it, though.
> 0 votes

---
Tags: views, 6, entities, datetime
---


# Question
Title: Views Filters: find nodes that have more than one term in taxonomy vocabulary
How can I set a filter to find nodes that have **more than one term** in a particular taxonomy vocabulary?

*Note: The vocabulary allow unlimited values and is required field. So, nodes can have 1-∞ terms.*

# Answer
In order to list down only those nodes of a specific content type that has more than one taxonomy term, I did the following and could only see nodes with more than one taxonomy term:

1. Create content type with taxonomy term field
2. Create views with following filter criterias

A. Published=Yes

B. Content Type={Your Content type}

C. taxonomy term field:delta (= 1)

For "C" I have clicked on Add filter criteria, then searched for the (content type's) field that contains taxonomy term and selected the one that has :delta (i.e. my field name is field\_taxonomy\_term and I choose field\_taxonomy\_term:delta), Once you selected the delta of your taxonomy term field then choose the operator as ***is equal to*** and provide the value as ***1*** and save.

If a content type has exactly one taxonomy term then the delta field will never have index 1 but, will always have index 0. If a node has more than one taxonomy term (i.e. 2) then there is index 1 (Index 1 is always present for content types with more than one taxonomy term), that is why the filtering works.

See the screenshots for more info:

The page is configured to show only nodes with more than one taxonomy temr

The following attachment is configured to show all nodes (it is then attached to the page)

The result of the above page and attachment is as follow

In case you are interested in the view, here is the export code:

```
$view = new view();
$view->name = 'viewfornodewithtaxonomy';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'ViewForNodeWithTaxonomy';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Attachment display all nodes with any taxonomy terms';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '20';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['pager']['options']['id'] = '0';
$handler->display->display_options['pager']['options']['quantity'] = '9';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: taxonomy terms */
$handler->display->display_options['fields']['field_taxonomy_terms']['id'] = 'field_taxonomy_terms';
$handler->display->display_options['fields']['field_taxonomy_terms']['table'] = 'field_data_field_taxonomy_terms';
$handler->display->display_options['fields']['field_taxonomy_terms']['field'] = 'field_taxonomy_terms';
$handler->display->display_options['fields']['field_taxonomy_terms']['delta_offset'] = '0';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'nodewithtaxonomy' => 'nodewithtaxonomy',
);
$handler->display->display_options['filters']['type']['group'] = 1;
/* Filter criterion: Content: taxonomy terms (field_taxonomy_terms:delta) */
$handler->display->display_options['filters']['delta']['id'] = 'delta';
$handler->display->display_options['filters']['delta']['table'] = 'field_data_field_taxonomy_terms';
$handler->display->display_options['filters']['delta']['field'] = 'delta';
$handler->display->display_options['filters']['delta']['value']['value'] = '1';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['defaults']['title'] = FALSE;
$handler->display->display_options['title'] = 'page display node with at least one taxonomy term';
$handler->display->display_options['path'] = 'viewfornodewithtaxonomy';

/* Display: Attachment */
$handler = $view->new_display('attachment', 'Attachment', 'attachment_1');
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['defaults']['filter_groups'] = FALSE;
$handler->display->display_options['defaults']['filters'] = FALSE;
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'nodewithtaxonomy' => 'nodewithtaxonomy',
);
$handler->display->display_options['filters']['type']['group'] = 1;
$handler->display->display_options['displays'] = array(
  'page' => 'page',
  'default' => 0,
);
$handler->display->display_options['attachment_position'] = 'after';

```

Don't forget to mark your question as resolved if the answer helped you.
> 6 votes

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


# Question
Title: What is the recommended way to structure Sass with Zen theme?
I have just started using Sass and decided to go ahead and build a theme with Zen for the first time. My very first task is to split the header region into 3 separate regions: header-left, header-main, header-right. From what I've read so far, the best practice to do this is to go in your subtheme's .info file and declare the region and then go to the page.tpl.php file and use the corresponding variables.

I also understand that I will probably have to write Sass that looks like this:

```
.header-container {
 @include zen-grid-container;
}

.header-left {
 @include zen-grid-item(3, 1);
}

.header-main {
 @include zen-grid-item(3, 2);
}

.header-right {
 @include zen-grid-item(3, 3);
}

```

My questions are the following:

1) Where do I add my Sass? Defining the structure of a new region seems like a good fit for the layouts directory. Do I add Sass in the layouts/\_responsive.scss file or do I create a new file like layouts/\_custom.scss?

2) How do I organize my custom styling in a Zen subtheme? Is there a "best-practices" guide that describes how things should be ordered?

# Answer
> 1 votes
> Do I add Sass in the layouts/\_responsive.scss file or do I create a new file like layouts/\_custom.scss?

Completely up to you. Modularisation is always a good thing, how far you go with implementing that as partials depends on your tastes, and how much code you actually need to write.

> How do I organize my custom styling in a Zen subtheme? Is there a "best-practices" guide that describes how things should be ordered?

I wouldn't have thought so. There isn't an industry standard for structuring a Sass project, so any claims of "best practice" or "this should be done like this" that you see must be taken with a pinch of salt.

It's mostly common sense in my experience. If a file's getting too big, split it up. If natural groups start to form (views, node, users) then you might want to split those up into sub-folders. If you're not already using it, Sass globbing will take the pain out of including partials if you have a lot of them.

---
Tags: 7, theming
---


# Question
Title: Submit handler doesn't work after theming the form
I have a form:

```
function payment_system_coeff_form($form, &$form_state) {
  list($_SESSION['payment_systems'], $_SESSION['coefficients']) = payment_system_table();

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

  return $form;
}

function payment_system_coeff_form_submit($form, &$form_state) {
  var_dump($form_state['input']);
  exit;
}

```

It works, when I submit it - I get the text printed.

But when I add the theme for it:

```
function payment_system_theme($existing, $type, $theme, $path) {
  $path = drupal_get_path('module', 'payment_system');

  return array(
    'payment_system_coeff_form' => array(
      'render element' => 'form',
      'path' => $path,
      'template' => 'table',
    ),
  );
}

```

### table.tpl.php

```
<table cellspacing="0" cellpadding="4" border="1">
  <tr>
    <th></th>
    <?php
      foreach ($_SESSION['payment_systems'] as $name) {
        print "<th>$name</th>";
      }
    ?>
  </tr>
  <?php
    $i = 0;
    foreach ($_SESSION['payment_systems'] as $index1 => $name) {
      print '<tr>';
      print "<th>" . $_SESSION['payment_systems'][$index1] . "</th>";

      $j = 0;
      foreach ($_SESSION['payment_systems'] as $index2 => $name) {
        if ($j < $i) {
          print '<td></td>';
        }
        else if ($j === $i) {
          print '<td>X</td>';
        }
        else {
          if (isset($_SESSION['coefficients'][$index1][$index2])) {
            $form["coefficients[$index1][$index2]"] = array(
              '#type' => 'textfield',
              '#required' => FALSE,
              '#size' => 10,
              '#attributes' => array(
                'name' => "coefficients[$index1][$index2]",
                'style' => 'text-align: right;'
              ),
              '#value' => $_SESSION['coefficients'][$index1][$index2],
             );

            print "<td>" . render($form["coefficients[$index1][$index2]"]) . "</td>";
          }
          else {
            print "<td><input type='text' name='coeffitient[$index1][$index2]' value='' /></td>";
          }
        }
        ++$j;
      }

      print '</tr>';
      ++$i;
    }
  ?>
</table>
<div style="text-align: center;"><?php print render($form['submit']); ?></div>

```

Output of the form looks like this:

It stops working: I don't get any text when submitting the form. How to fix?

# Answer
> 2 votes
I know you've found an answer to your question, but I just want to explain why did you get that problem.

Drupal adds `form_build_id`, `form_token`, `form_id` (hidden fields) for security reasons and it's some purposes, while you're theming the form with template file and render its fields manually usually miss to include those fields, after that you form submission stops working. Recently this problem happened in my Symfony project (I'd found the solution) and after few days in my Drupal project, the solution was the same;

If you render the fields manually and also call `drupal_render_children` function, you will find that fields can be duplicated, my solution was rendering those fields also, like this:

```
print render($form['form_build_id']);
print render($form['form_token']);
print render($form['form_id']);

```

In my case for some reason `drupal_render_children` duplicated my form fields (I think this is normal, because I manually rendered the fields plus called `drupal_render_children`), that's why I ended up with this solution.

# Answer
> 1 votes
I added `print drupal_render_children($form);` to the end of the template file, and it works now.

---
Tags: theming, forms
---


# Question
Title: How to show validate error of a node listing page
i am trying to save form state in database and want to view in a listing page with its error validation.

i.e, i want to validate a previously saved form state from my database.

this is a node type form .

i had already tried `node_validate` its not working because i fetch the data before submitting the node . so there is no nid and for that it is not working

and also tried `drupal_validate_form` but it is showing

```
[form_token] => The form has become outdated. Copy any unsaved work in the form below and then reload this page

```

Any help is most Appreciable.

EDIT :

Can any one just say How To save my form and retrieve it from database and load all result in a page .

# Answer
This may not quite answer your question, but I think it might help with whatever you're trying to do.

You can alter the node creation form to have extra validation and display it on the screen using the devel module, along with a custom module that calls hook\_form\_alter

```
function mymodule_form_alter(&$form, &$form_state){
    //add a function in #validate to read form_state and show it on screen
    $form[#validate][] = mymodule_read_values($form_state);
    //or if you want to make it happen before any of the other form validation, uncomment the next line and comment the one above
    //array_unshift($form[#validate], mymodule_read_values($form_state));
}

function mymodule_read_values(&$form_state){
    // make sure you have devel module installed or this will cause WSOD
    dpm($form_state);
    // if you want to prevent form submission you can uncomment the next line
    // throw new Exception('Cancelling form submit - see mymodule');
}

```

Remember of course, to replace any instance of 'mymodule' with the name of your module, particularly the first one, or the hook won't work.

Doing this will show the structure of the form\_state on the screen when you try to save the node.

If you want to target a specific form you can change the first line to

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

```
> 1 votes

---
Tags: forms, nodes
---


title: Change a heading?

text:
# Question
Title: Change a heading?
A panel has an article title that is wrong and I'd like to make it right, but; I can't find where the wrong data is coming from. I'm having a little difficulty identifying the components of Drupal, but; hopefully this question won't be too confusing or improperly described.

On my home page I have a object that has "View, Edit, Panel layout, Panel content" which seems to contain a Welcome Block and Featured Article. The Welcome Block pane-title is something like "Welcome to City Name Library" and I want to change City Name. But, I can't figure out where City Name is coming from.

None of the "View, Edit, Panel layout or Panel content" tabs has that data. Contained within this panel is the Welcome Block which "Configure block" does not show me "City Name" either.

How do I find where "City Name" is located?

# Answer
> 0 votes
What a wretched hassle fixing this with Drupal has been. I resorted to using phpmyadmin to Export the DB, locate the data, edit the panels\_pane table pid=3, correct for string length count now everything is hunkydory.

---
Tags: 7, blocks, panels
---


# Question
Title: How can I add menu items when importing nodes into Drupal 7 (with the Feeds module)?
I'm importing a site using the Feeds module, and I do not see any way to specify which nodes should get a menu item. How can I do this?

If the Feeds module cannot do this, is there another way?

# Answer
> 1 votes
You can try the sandbox project Feeds Menu

> Adds mapping elements for menu entries for feeds

---
Tags: 7, routes, feeds, importing-exporting
---


title: Popup slide of galleries

text:
# Question
Title: Popup slide of galleries
I need to create a slide in popup where the user can list the galleries.

In short, the left and right arrows is navigation for previous and next gallery (as well as numbers for navigation), each gallery has a number of images that can be changed by clicking on the thumbnail image.

My idea is to create a content type for the gallery, and then using Views Slideshow to list only body of that content type. Is such a thing possible? Could there be another way in which this can be done?

Any suggestion is welcome...

# Answer
This is step by step solution that I use to get this done:

1. Create new content type with image field
2. Install Field Slideshow and View Slideshow modules
3. Create new View of type Slideshow
4. Add image field from created content type in View, than set 'Slideshow' for 'Formatter' of that field and choose settings that you want for slideshow
5. That's it, you have slideshow of images inside slidedeshow...
> 0 votes

---
Tags: media, views, javascript
---


# Question
Title: How to hide a user profile based on custom field?
I need to allow users to turn off the public display of their profile if they wish too. I created a Boolean field to store whether the user wanted the profile shown or hidden. According to this (old!!) documentation on d.o., I should add an if statement at the beginning of the user profile template.

Specifically, is this the proper way to access the value?
*Edit: Proper, but must account for possibility that value hasn't been set in existing profiles, thanks!*

```
<?php //check to see that user has chosen to show profile
  if(!isset($field_profile_display) || $field_profile_display[0][value] == 1): ?>

```

If I put the if statement at the very beginning of user-profile.tpl.php, I see all the fields set to display (with Display Suite), unthemed. If I put it after , I get a profile page, blank but fo the username as the title.

Where do I put the code to actually prevent the page from displaying? Does it need to go in page.tpl?

Generally, is this really still the best practice? Would it be better to implement this in a preprocess hook?

# Answer
> 1 votes
This way is absolutely okay. There is definitely the possibility to achieve the same result with the preprocess hook, but doing it in the template file is also a common "drupalish" way and has (as far as i know) no disadvantages.

One thing: Do you have already existing users? if so you should check if the variable exists before comparing it with a value... otherwise you could get a php-warning.

# Answer
> 0 votes
After implementing the code in a node template, I ran into errors running cron and site search. (This is a well known situation, see cron breaks on drupal\_goto.) Ultimately, I think I will follow the advice given here in a question about an alternative Drupal goto function: Do not place 'custom' PHP code in nodes. I'm going to rewrite it as a preprocess hook.

---
Tags: theming
---


# Question
Title: Menu link on hover is showing & instead of &
I have a Webform that provides a menu link. The webform is available in three languages (dutch, french, english).

For the dutch version I have a **menu title** of `Informatie` and **description** `Vragen & Antwoorden`.

But when I hover the link I don't get `Vragen & Antwoorden`. But i get `Vragen & Antwoorden`.

He changes the & symbol to  . I also got this with `'` . He changed it in `'`.

How can I fix this?

**UPDATE:**

These are the menu settings of my webform:

**UPDATE 2:**

This only happens when I try to translate and use `'` (apostrophe) in my translation. He will form the `'` to `'`.

Like this:

# Answer
Try to turn off `Provide a menu link` in `Menu settings` of your webform and to add menu link to webform page in your menu, `/admin/structure/menu > list links (of your menu) > Add link` instead.

If this doesn't work you can override themable output in your theme template.php file or in a custom module. Look at this post.
> 1 votes

---
Tags: entities, routes, i18n-l10n, theming, navigation
---


# Question
Title: Tweet a published content on twitter from Drupal 7
My goal is tweeting content from a Drupal site as soon as a node / content is posted on the Drupal 7 site.

I follow all the instruction from this post "How to automatically tweet a published content on twitter from Drupal 7?" and did not work. What they recommend is to use the Twitter Module, this module you need to created an app at Twitter to make authentic it. I created the app and I'm able to pull all the tweets from Twitter to my site. Also, I'm able to sign in with Twitter however, I'm not able to automatic post a tweet after a node its created.

I can see the Twitter tab on my content type before I create a node. After I created the node a message said "Successfully posted to Twitter" but on twitter I cant see anything. Can anyone tell me how to troubleshoot this ? Or do I'm missing something ?

# Answer
> 1 votes
Have you created the Twitter app with the correct permissions? By default apps are only created with read-only permissions

---
Tags: social-network
---


# Question
Title: Create Node contains Field collection with restws + services
I am trying to create a node with RESTFULL api using restws and services modules (latest versions) on Druapl 7 - openpublish destro. the node contains a Field collection (images field collection field) i was trying to attache the fid returned from the /backbone/rest/files.json \[POST\] but the field accept nothing

JSON Sample for the field

> "field\_op\_gallery\_image": {
>
> > "und": \[
> >
> > > ```
> > >  {
> > >    "value": "3",
> > >    "revision_id": "3"
> > >  },
> > >  {
> > >    "value": "4",
> > >    "revision_id": "4"
> > >  },
> > >  {
> > >    "value": "5",
> > >    "revision_id": "5"
> > >  },
> > >  {
> > >    "value": "6",
> > >    "revision_id": "6"
> > >  },
> > >  {
> > >    "value": "7",
> > >    "revision_id": "7"
> > >  },
> > >  {
> > >    "value": "8",
> > >    "revision_id": "8"
> > >  }
> > >
> > > ```
> > >
> > > \] },

Can any one help , thanks in advance

# Answer
This sandbox will implement a field\_collection service for services 3.x: https://www.drupal.org/sandbox/graber/2141747
> 2 votes

---
Tags: services, entities, 8
---


# Question
Title: "Your command line PHP installation is too old" But it's not?
I was trying to install Drush version 7.x-5.9 when it gave me the following error (whenever I try to use the drush command):

Your command line PHP installation is too old. Drush requires at \[error\] least PHP 5.3.0. To suppress this check, set the environment variable DRUSH\_NO\_MIN\_PHP=1

My HostMonster Info: Apache version 2.2.26 PHP version 5.4.24 MySQL version 5.5.35-log

I've reverted back to version 7.x-5.4 of Drush and the command line is working but I would like to use the newest version if possible.

# Answer
> 2 votes
The command line version of php (CLI) and the one used by your webserver (reported by hostmonster info) are not necessarily the same. Run `php -v` in a terminal to see which php command line version is installed.

# Answer
> -1 votes
If you have this problem with connecting to Acquia, it's worth noting that the acquia ssh path given from their console:

```
ssh user@srv-3923.devcloud.hosting.acquia.com

```

uses a different user than the remote-user provided by the Acquia drush alias file:

```
$aliases['dev'] = array(
  'root' => '/var/www/html/site.dev/docroot',
  'ac-site' => 'user',
  'ac-env' => 'dev',
  'ac-realm' => 'devcloud',
  'uri' => 'userdev.devcloud.acquia-sites.com',
  'remote-host' => 'srv-3923.devcloud.hosting.acquia.com',
  'remote-user' => 'user.dev',
  'path-aliases' => array(
    '%drush-script' => 'drush' . $drush_major_version,
  )
);

```

, which in our case had a different version of command-line php (3.1 vs 2.9). You can verify that this is your problem by doing a drush ssh.

To fix, we had to change the remote-user in the drush file by removing the environment extension.

```
  'remote-user' => 'user.dev',

```

to

```
  'remote-user' => 'user',

```

I do not know if there is any reason to keep the environment-specific user, but this was enough for us to pull the database through.

---
Tags: drush
---


# Question
Title: Does Drupal have a collaborative editing module?
What I would like to offer my users is the ability to propose a writing project to a group of people (users and non users) and the people who want to join the writing project are able to edit the same node together in separate locations.

# Answer
> 0 votes
Drupal has the Etherpad Integration module to provide a collaborative realtime editor, replacing the normal WYSIWYG one. It requires installing Etherpad Lite on your own server.

If you cannot or do not want to install Etherpad Lite, you could use the Piratepad Drupal module, which accesses the Etherpad Lite installation on piratepad.net or similar sites. (Of this, there is also an unpublished D7 port.)

(Source: drupal.stackexchange.com answer #53188)

# Answer
> 0 votes
The answer from knowledges33ker is a good start.

However the workbench module - https://drupal.org/project/workbench \- might also help with this and add further functionality.

Particularly in that it offers good tracking of edits that have been made to content and you can revert content to previous revisions etc.

With the user reference field set up, you could also, if you wanted, use the Rules module - https://drupal.org/project/rules \- to fire emails or notifications to users when the content is edited/updated.

# Answer
> -1 votes
You could install the references module, then add a user reference field to the content type. Then, install the Node Access User Reference Module (https://drupal.org/project/nodeaccess\_userreference). You can set your configuration so that users of a given role can add another user(s) to the node and you can specify what permissions those editors can have (e.g. edit but not delete the node, etc). This gives you (and/or your users) more control over when specific people get to "join" a writing project with editing permissions.

You could also try the drupal wiki install profile: https://drupal.org/project/drupal\_wiki

---
Tags: 7
---


title: Hook_node_view() to print a table?

text:
# Question
Title: Hook_node_view() to print a table?
I'm working on my first module. What I'd like to do is add this table http://pastebin.com/A1cbya5m function's output to the bottom of nodes. I'm not sure how to do this using hook\_node\_view()'s '#markup' field. I can do one line but nothing this complicated. I tried doing '#markup' =\> print\_payment\_table(), but it didn't work.

Any ideas?

# Answer
First of all in your function (`print_payment_table()`) you need to return a string, do not print anything (or an array which will be rendered with a theme function but this a different stuff).

Now in your `{yourmodule}.module` implement:

```
/**
 * Implements hook_node_view().
 */
function {yourmodule}_node_view($node, $view_mode, $langcode) {

  if (...) { // Check your node->type or whatever.

    $node->content['mykey'] = array(
      '#markup' => print_payment_table($node),
    );
  }
}

```

If you want to sort this element by UI (on the node type tab as a field):

```
/**
 * Implements hook_field_extra_fields().
 */
function {yourmodule}_field_extra_fields() {
  $extra = array();

  $extra['node'][{yourcustomcontenttype}] = array(
        'display' => array(
          'mykey' => array(
            'label' => t('Payment table'),
            'description' => t('Payment table'),
            'weight' => 10, // Default weight
          ),
        )
      );
  }

  return $extra;
}

```
> 1 votes

# Answer
Your function isn't actually returning anything. So

```
'#markup' => print_payment_table()

```

will result in markup being empty. I've noticed in your function you have a lot of print statements. It would better to build a string variable in your table construction. Like:

```
$string = "<table>";
$string .= "<tr><td>".$stuff"</td></tr>";
$string .= </table>;

```

then at the end of the function, return $string.

EDIT: ----------------------- your functions should be seperated, not defined iside of each other.

So:

```
function table_builder($node){
//do stuff
   return $stuff;
}

function *my_mod*_node_view($node, $view_mode, $langcode){
   $node->'#markup' .= table_builder($node);
}

```
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: Services Entity REST Application - Update (via put) Field Collection Data
I am trying to figure out what the format and required parameters are for an update request to a field collection via the Services Module's REST API. I have installed the Services Entity API Module to allow interaction via Services with additional entity types.

I was able to save to a field collection when I first set everything up, using a PUT request, the CSRF token and properly formatted JSON.

```
{"field_fivestar_value":[
      {
         "rating":"100",
         "target":"0"
      }
   ]
}

```

which gave me this to access: `field_fivestar_value['und'][0]['value']` which seemed to work perfect in the past, but now it seems that something is interfering/wrong as i get a notice after submitting a PUT request that $revision\_id and/or $field\_name aren't set, which never happened before...

# Answer
It appears that something to do with revisions is causing the problem as if I provide specific (required?) data in my PUT request it works. Working PUT request JSON:

```
{
    "field_primary_aircraft": {
        "und": [
            {
                "value": "1"
            }
        ]
    },
    "field_name": "field_aircraft",
    "item_id": "5929",
    "revision_id": "5929",
    "default_revision": true,
    "field_aircraft_registration": {
        "und": [
            {
                "value": "testing12355"
            }
        ]
    }
}

```

That JSON plus a working CSRF token allowed me to save data back to a field collection that is part of a users Profile2 profile.

The `revision_id` and `default_revision` were the trickiest parts to track down and supply, I don't have revisions enabled as far as I can tell also, so why this problem started suddenly I have no idea...at least it is solved and hopefully this info helps someone else.
> 1 votes

# Answer
This sandbox will implement a field\_collection service for services 3.x: https://www.drupal.org/sandbox/graber/2141747

Work is still in progress for entity api support for field \_collections here: https://www.drupal.org/node/2044833
> 0 votes

---
Tags: services, entities, 8
---


# Question
Title: Configuring PayPal Express Checkout to accept BRL currency
When configuring PayPal Express Checkout on Payment Methods, the Default Currency selector don't show BRL as an option.

In the FAQ page https://www.drupal.org/node/1902660#comment-9118725, where we read

> PayPal only supports a small set of currencies, and these vary by service. This module uses the most up to date documentation to populate currency option lists.

on documentation link there are more currencies that Express Checkout accepts. So isn't it necessary to update the set of currencies in Default currency selector?

When I go to paypal site through checkout button I can't complete transaction because the currency send from Drupal is in USD instead of BRL.

# Answer
> 1 votes
There is a patch in Issues for Commerce Paypal module. I have applied that patch and now BRL is showed. Going to PayPal page from my site's checkout section now works fine.

---
Tags: commerce, payment-gateways
---


title: how to run "cd" command in drush

text:
# Question
Title: how to run "cd" command in drush
I like to have drush command 'go\_to' that will move my shell into different directory. My custom implementation does not move the shell directory. How come? here is the script so far:

```
#!/usr/bin/env drush
<?php

$dir = '/dir/to/move/my/shell';
drush_op('chdir', $dir);
drush_op_system('cd '.$dir);
//drush_shell_exec('cd '.$dir);
//print_r(drush_shell_exec_output());

```

Thank you for help

# Answer
> 5 votes
The "cd" command in your commandfile is working correctly; however, it is a standard behavior for \*nix (and Windows) that environment variables, such as the current working directory variable set by the 'cd' command apply only to the process that they are set in. Drush runs in a separate process from the shell that you launch it from, so your current working directory will revert to its original value when Drush terminates. (It actually never changed, since each process has its own environment.)

Instead of using a Drush alias (site alias or shell alias), what you might actually prefer is a bash alias. For example:

```
$ alias go='cd /dir/to/move/my/shell'
$ go
$ pwd
/dir/to/move/my/shell

```

There's a lot more you can do here if you define site aliases for your site, and source the example bashrc file that Drush provides; see the Drush README file, and the examples folder.

If you want to write fancy php code change your working directory, you need to put only the code that calculates the destination path, and then call 'cd' from a shell alais. For example (from bash):

```
$ alias go='cd $(drush dd @mysite)'
$ go
$ pwd
/path/to/drupal/root/of/mysite

```

This one liner will also do the trick:

```
$ cd `drush @mysite dd`

```

zsh aliases have the same syntax as bash aliases:

```
http://zsh.sourceforge.net/Intro/intro_8.html

```

It also looks like process substitution has the same syntax in zsh as well:

```
http://zsh.sourceforge.net/Intro/intro_7.html#SEC7

```

However, I haven't tried any of this in zsh.

# Answer
> 1 votes
You might want to check out aliases:

http://befused.com/drupal/drush-site-aliases

---
Tags: drush
---


# Question
Title: How to force migrations to not copy files
I have a migration with an image field and the files already exist on the server where I want them.

There is a file, some\_file.jpg that already exists at sites/default/files/some\_file.jpg but when I run the migration, it tries to copy the file from sites/default/files/some\_file.jpg to sites/default/files/node\_type/some\_file.jpg and then also creates another file entity for it. I just want it to re-use the file and file entity that already exist for it. The destination field type is an image field.

I have this on the field mapping for the file field:

```
$this->addFieldMapping('field_upload_image', 'field_res_upload_photo');
$this->addFieldMapping('field_upload_image:preserve_files')
     ->defaultValue(TRUE);
$this->addFieldMapping('field_upload_image:file_replace')
     ->defaultValue(MigrateFile::FILE_EXISTS_REUSE);

```

# Answer
> 0 votes
Well if thats not working do a scan for the file on the destination location to set or unset the field value (so it's not updated on save). You can do this in the `prepare` function of your migration class. See the commonly implemented migration methods page for example implementations.

Also have you tried setting the `preserved_files` key:

```
    $this->addFieldMapping('field_images:preserve_files')
  ->defaultValue(TRUE);

```

I haven't done any file migrations myself lately, but I stumbled across that in this thread: https://www.drupal.org/node/1886404 it looks like you got the field ordering correct (well from the issue the source field primary and sub-field ordering now no longer matters).

# Answer
> -1 votes
I normally use file\_copy function to update this manually. Set target folder to be same as copy from folder.

1. Use drupal\_realpath function to transfer directory path to image into drupal file path. e.g /sites/default/node\_type/some\_file.jpg into public://node\_type/some\_file.jpg
2. set file object
3. use file\_copy($file, 'public://node\_type',FILE\_EXISTS\_REPLACE); this will not copy file if file is exists.
4. set this file into your node. and update it. something like this

$node-\>field\_category\_image = array(LANGUAGE\_NONE =\> array( (array) $file)); node\_save($node);

whole code

```
$filepath = drupal_realpath('/sites/default/node_type/some_file.jpg');
      $file = (object) array(
        'uid' => 1,
        'uri' => $filepath,
        'filemime' => file_get_mimetype($filepath),
        'status' => 1,
      );

$file = file_copy($file, 'public://node_type',FILE_EXISTS_REPLACE);
$node->field_image = array(LANGUAGE_NONE => array( (array) $file));
node_save($node);

```

---
Tags: media, migrations, files
---


# Question
Title: How to provide template for particular view mode?
I want to theme the search result view mode with a template.

I had it in my head that naming a template file node--article--search-result.tpl.php would do the trick, but I'm obviously wrong about that.

I realise I can do node--article.tpl.php and within this check $view\_mode, but this is awkward with all the other view modes that I don't want to template.

Ideas?

# Answer
Adding theme hook suggestions in a node preprocess function should do the trick:

```
function MYMODULE_preprocess_node(&$vars) {
  if ($vars['node']->type == 'article' && $vars['view_mode'] == 'search_result') {
    $vars['theme_hook_suggestions'][] = 'node__article__search_result';
  }
}

```

After clearing the caches you should be able to use node--article--search-result.tpl.php for your template file name.

NB. You could also do this in your theme's template.php file by calling the function `MYTHEME_preprocess_node()` instead.
> 47 votes

# Answer
The Entity view modes module adds these template suggestions automatically

> The Drupal 7 successor to Build modes which will allow administrators to define custom view modes for entities. Custom entities are added to the entity registry via hook\_entity\_info\_alter() so they are available to any code that uses entity\_get\_info() to provide a list of view modes for an entity. This includes node and user reference fields, Views, etc.
> 3 votes

# Answer
Here is a function that allows you to add new ones dynamically. It also calls the corresponding preprocess function if you have one declared.

Then call `drush cache-clear theme-registry` to get it working.

To use it replace THEME with your theme's name, and place it in your themes template.php file.

e.g. For a theme named Droid you would call it `droid_preprocess_node(&$variables, $hook) {`...

```
function THEME_preprocess_node(&$variables, $hook) {
  $view_mode = $variables['view_mode'];
  $content_type = $variables['type'];
  $variables['theme_hook_suggestions'][] = 'node__' . $view_mode;
  $variables['theme_hook_suggestions'][] = 'node__' . $view_mode . '_' . $content_type;

  $view_mode_preprocess = 'THEME_preprocess_node_' . $view_mode . '_' . $content_type;
  if (function_exists($view_mode_preprocess)) {
    $view_mode_preprocess($variables, $hook);
  }

  $view_mode_preprocess = 'THEME_preprocess_node_' . $view_mode;
  if (function_exists($view_mode_preprocess)) {
    $view_mode_preprocess($variables, $hook);
  }
}

```
> 2 votes

---
Tags: 7, theming, entities
---


title: Menu highlight vs. taxonomy

text:
# Question
Title: Menu highlight vs. taxonomy
My site (running D7) is divided into four sections to organise its content. This is implemented via a taxonomy vocabulary, and my main menu lists each term in this vocabulary. So when a user clicks a main menu item, it is highlighted and all articles in that section (nodes with that term) are shown. Brilliant.

But, when a user then clicks one of these articles to view the whole thing, the main menu item is no longer highlighted. Although the article does display the taxonomy term, I would very much like to keep the main menu item highlighted so it's obvious to the user which section she's browsing.

How can I achieve this?

Edit: Clarified that I'm using Drupal v7. Also, managing the menu itself is not a goal (that's easy enough), the goal is only keeping the menu highlighted when viewing an article node as opposed to the term node.

# Answer
> 0 votes
You can use Taxonomy Menu module. I've used it on one site, and it works ok. It allows you to create menu automatically based on your taxonomy vocabulary. It puts all your content tagged with term under term's menu. One tricky thing is, that it works on changing or creation of terms - when you just turn module on, it will seems not to work.

# Answer
> 1 votes
I'm sure there is a better way to do it but the context module will allow this.

You can set up a condition for each term which sets the menu item as the reaction.

# Answer
> 0 votes
You can use Taxonomy Menu and Taxonomy Menu Trails by setting Term references for setting active trail when editing content type.

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


# Question
Title: Commerce Product Collection View Block: What Determines CSS For Each Header Link?
In Kickstart 2 there is a view called collection\_products which displays a list of products in a given collection, grouped by category.

There is a header which uses a Block display to give anchor links to each Category Header on the page. The format of the fields is 'Unordered List' yet the fields are styled as

```
<div><h3><a>

```

...not

```
<ul><li><a>

```

...as I would like.

How do I change the generated styling of these? I've searched all over the view and can't find it.

HEAVY EDIT. Big Thanks to J. Reynolds!

The issue is that this view is actually a list of group headings. The reason it displays as it does is that it's showing a list of all categories... each as a 'Title'...

...for each category and then a -hidden- list of the products.

So it's not that each 'row' is being themed not as a list, but that what I -thought- was a 'row' is actually a 'title'.

So: What I need to do is create an unordered list with the -title- of each category (the Grouping No. 1) as the actual li using each of these headings.

How do I do this?

BONUS: Is there a way to get Drupal to not even generate that hidden UL of products? It seems wasteful, not just for the client, but at the server.

# Answer
> 0 votes
It is the same as with any view: You have to override the view template.

In your views UI click on 'Theme:information'. This will open up a dialog with views templates and suggestions. As the block is using grouping, you need to override the 'Style output' theme template:

```
views-view-list.tpl.php

```

If you override that template it will override it for all views of HTML List format, so you now have to select a suggestion. Second in the list is:

```
views-view-list--collection-products.tpl.php

```

which will be fine.

Create a new file in your theme templates folder called

```
views-view-list--collection-products.tpl.php

```

Then click on the 'Style output' link back in the view theming information. It will open up a file and you copy everything from the

Now you can edit that file to get the markup you want. You can take out the h3 tag for example and replace with a div.

---
Tags: views, theming, commerce
---


title: How to save file as a settings

text:
# Question
Title: How to save file as a settings
How can i use settings form http://api.drupal.org/api/drupal/modules%21system%21system.module/function/system\_settings\_form/7 to make a file saved and retrieved using variable\_get() ?

I am using Drupal 7.

# Answer
> 1 votes
The settings form does not save entries to a file, but stores the value in the database. It can only be called from a custom module you will have to build.

Below you will find a link to Drupal's own module tutorial. Follow the steps and you will come across the usage of the settings page. (configuration form)

http://drupal.org/node/361112

# Answer
> 0 votes
System settings will only save the file temporarily, to keep files permanently you will need to process and save the file yourself with `file_save()`.

You can save the file (fid) with `variable_set()`, and use `variable_get()` followed by `file_load($fid)` to load your file.

Here is a code example (link to source below):

```
<?php
function custom_settings_form($form, &$form_state) {
  $form['files'] = array(
    '#type' => 'fieldset',
    '#title' => t('Files'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );
  $form['files']['custom_file_1'] = array(
    '#title' => t('File 1'),
    '#type' => 'managed_file',
    '#default_value' => variable_get('custom_file_1', ''),
    '#upload_location' => 'public://custom/',
  );

  // Perform our custom submit before system submit.
  $form['#submit'][] = 'custom_settings_form_submit';
  return system_settings_form($form);
}
?>

```

And the custom submit:

```
<?php
function custom_settings_form_submit($form, &$form_state) {
  global $user;
  // Load the file via file fid.
  $file = file_load($form_state['values']['custom_file_1']);
  if ($file) {
    // Change status to permanent.
    $file->status = FILE_STATUS_PERMANENT;
    // Save.
    file_save($file);
    // Optionally record that the module (e.g. user module) is using the file.
    file_usage_add($file, 'user', 'user', $user->uid);
  }
}
?>

```

See https://www.drupal.org/node/1090198 for full explanation and code examples.

---
Tags: 7
---


# Question
Title: I need a function to set a menu item's class to active based on if a keyword is in the URL
Weird i know but as per the clients request i need to do the following:

if node being view is in a directory like this /panelist/panelist-name

or this

/moderator/moderator-name

i need to set the a menu link in the main menu to active and also a sidebar menu item too.

now i know how to do the javascript part but i don't know to determine if /panelist/ or /moderator/ are in the URL, and also where i would put such code? i guess in template.php?

i tried doing in Rules but it didn't seem possible (still kind of new though!)

pseudo code would be if node being viewed contains 'panelist' or 'moderator' in URL then echo out some javacript or set some menu item class to 'active'

much thanks!

# Answer
> 1 votes
Something like this in your theme template can work:

```
function MYTHEME_preprocess_menu_link(&$variables) {
  if (menu_get_object()) {
    $parsed_path = explode('/', drupal_get_path_alias());
    $parsed_link = explode('/', drupal_get_path_alias($variables['element']['#href']));

    if (some_compare_func($parsed_path, $parsed_link)) {
      $variables['element']['#attributes']['class'][] ='active-trail';
    }
  }
}

```

You will have to implement some\_compare\_func yourself, or use a regular expression instead of exploding items, to do whatever matching needs to be done.

You can also check which menu the link belongs to (\['#original\_link'\]\['menu\_name'\])

This is just a primer to get you going.

---
Tags: theming, routes
---


# Question
Title: How do I alter the file link of an uploaded image in edit/create node form?
When I upload an image in drupal, a file icon and a file name that links it to original file is created.

For example, I upload "foo.jpg" then

```
 <a href=path-to-file>foo.jpg</a>

```

is generated.

I want to change the path-to-file url because it's put putting base\_url() + path-to-file which results in Not Found. I'm using amazon s3 for file storage.

I only want the path-to-file url without the base\_url. Can anyone share some wisdom?

# Answer
You could try implementing your own theme\_file\_link.

> Returns HTML for a link to a file.
>
> Parameters
>
> $variables: An associative array containing:
>
> file: A file object to which the link will be created. icon\_directory: (optional) A path to a directory of icons to be used for files. Defaults to the value of the "file\_icon\_directory" variable.

Put this into your theme's template.php file:

```
function MYTHEME_file_link($variables){
  $file = $variables['file'];
  $icon_directory = $variables['icon_directory'];

  $url = file_create_url($file->uri);
  $icon = theme('file_icon', array('file' => $file, 'icon_directory' => $icon_directory));

  // Set options as per anchor format described at
  // http://microformats.org/wiki/file-format-examples
  $options = array(
    'attributes' => array(
      'type' => $file->filemime . '; length=' . $file->filesize,
    ),
  );

  // Use the description as the link text if available.
  if (empty($file->description)) {
    $link_text = $file->filename;
  }
  else {
    $link_text = $file->description;
    $options['attributes']['title'] = check_plain($file->filename);
  }

  return '<span class="file">' . $icon . ' ' . l($link_text, $url, $options) . '</span>';
}

```

Clear the cache, and then modify the code.

I would also investigate Amazon S3 Stream Wrapper
> 0 votes

---
Tags: 7, uri
---


# Question
Title: Adding icons from the right or left to menu H2 or Li
Let's say I want to add Icons from the right\left of a Drupal menu H2 or li (such as in the place in the picture)... Actually I would also like to put a picture as a menu item by itself...

What is a good, veteran, and trusted module you could recommend for achieving all of these targets?

Thanks.

# Answer
> 0 votes
What a coincidence. I made good use of this module today because I needed to have bolded text in my menu items:

https://www.drupal.org/project/menu\_html

After enabling you'll get a checkbox on each menu item that allows you to add HTML to the menu title (anything inside the anchor essentially). So this is where you would put your `<img>` tag or the markup necessary for your icons.

Note for security, make sure *only trusted users* have the ability to use this option, as you can imagine it creates an opportunity to embed malicious code.

EDIT: OP asked how you might add icons using this technique. I would use an icon font. For example with Font Awesome you can put in some markup like `<i class="fa fa-refresh"></i>` and it will use CSS to display the icon there. Font Awesome covers most bases. If you can't find something specific try icoMoon or Fontastic.

It's really up to you how you implement this. See the other poster's answer for a pure CSS solution.

# Answer
> 0 votes
I've done something similar using the Menu attributes module

This allows CMS users to add a class to a menu item.

Then certain classes in the theme CSS are set to have a background image, with text hidden, or an image in the :before or :after pseudo-element.

---
Tags: routes
---


# Question
Title: Panelizer page manager variants not selected
I have installed the page manager, panels everywhere and Panelizer. A long time ago I set up a few content types and managed them with Panelizer, it all works fine. I've made a *site\_template* variant, just once at this time and it all works also fine. Now I wan't to make different site templates for different content types.

So I've made a *node\_view* "Panelizer"-variant for each content type. I've also made the different *site\_templates* variants. Then I select the *site\_template* for each *node\_view* variant. But it din't work's as I expected it!!

It always tooks the site\_template variant at the top and not the selected. It seems that the *node\_view* panelizer variant is never selected, because the panelizer overrides the page manager (? !).

Please help me, thanks!

# Answer
> 0 votes
I found a workaround. In the site\_template variants i made a selection rule on the node type. Problem was, that i have pages that arent nodes, just simple pages. I cloned the Variants and removed the selection rule. Then i choosed this site\_template in de pages.

Now i've got a lot of site\_template variants wich is not so nice, but it works.

---
Tags: chaos-tool-suite, panels
---


# Question
Title: drupal /?q=user is working but /user not working
I have recently moved my files from dev server to test server. same setting and db of dev server were copied to test server. In dev server all is working fine but when I have am checking in test sever `/user` not working but `/?q=user` is working

I have checked with `mod_rewrite in test server apache setting` and it is enabled. I also checked my `clean url drupal setting` it is also enabled

`/user` throws 404 error for me

```
Not Found

The requested URL /user was not found on this server.

```

Can someone help me find the issue

# Answer
As you have checked mod\_rewrite settings for your server and .htaccess both it sems that you may have mis-configured RewriteBase in your .htaccess file.

Please check comments in .htaccess file

\# Modify the RewriteBase if you are using Drupal in a subdirectory or in a VirtualDocumentRoot and the rewrite rules are not working properly. For example if your site is at http://example.com/drupal then its value should be:

```
RewriteBase /drupal

```

If your site is running in a VirtualDocumentRoot at http://example.com/, then its value should be:

```
RewriteBase /

```

Try and see if you have something wrong here.
> 4 votes

# Answer
I'd recommend reading https://www.drupal.org/getting-started/clean-urls \- this has a lot more information on setting up clean URLs.

It's likely that the .htaccess file is not set up properly, or the server doesn't allow the commands in the .htaccess
> 3 votes

---
Tags: 7, users, uri
---


title: User with uid=0 in database

text:
# Question
Title: User with uid=0 in database
I had to build a **form** with a **select** field populated with **all the users** registered in database. There are 10 users that I can see in `admin>people`.

To get all the users, I used `entity_load('user')`.

But in my select, I have **one empty option** in addition to my 10 users.

I checked in my database, and I found this empty UID=0 record:

I searched the Internet but I didn't find a satisfying answer. I read something about **Anonymous user** but I didn't get it.

* Is this record important?
* Does it have to be there?
* If yes, I'll do some trick to ignore it in my select.
* If not, can I just delete it?

Thank you in advance for this little trivial question.

# Answer
> Is this record important?

Yes, it prevents some queries from failing if it's anonymous user who caused them.

> Does it have to be there?

There is a possibility site would stay browsable you remove it... but it would mess your login functionality and may prevent sessions from persisting.

> If yes, I'll do some trick to ignore it in my select.

Consider using EntityFieldQuery. Omit UIDs lower than 1, or select only users with name, etc.
> 4 votes

---
Tags: 7, forms, database, users
---


# Question
Title: How to make the Admin interface language switch based on node content?
How can I make the Administration interface language be the same as the Editing content?

By example. If I edit a French content, I would like my interface in French. If I edit an English content, I would like my interface in English.

# Answer
On D7 you'll find a language **detection and selection** page at `admin/config/regional/language/configure`:

If you enable and put "**URL** Determine the language from the URL (Path prefix or domain)" on top the system will show the interface in French for nodes (and other content) in French and it will be English for English content.
> 1 votes

# Answer
Are you using the Admin Language module? Otherwise by default the interface and everything should be according the current chosen language.

`Administration Language` module lets the administrator see all administration pages in her preferred language. It is used to display the frontend of the site in one language and still keep most of the backend in English (or another language of your choice).

Other than this you may check if you have imported the translation packages for your language from https://localize.drupal.org/translate for the required languages. It will provide the translation for most of the strings.

For installing the translation for all the languages you may give a try to localization update module: Automatically download and update your translations fetching them from localize.drupal.org or any other Localization server.
> 0 votes

---
Tags: users, i18n-l10n
---


# Question
Title: File upload error. Could not move uploaded file
I am getting this error while changing the logo of my site,

i have tried changing the permission through hosting provider, added `php_value safe mode 0` in .htaccess file and even added one file in drupal folder named php.ini with

```
safe_mode = Off
file_uploads = On
upload_max_filesize = 256M

```

but still i am unable to change the logo and getting the error

> File upload error. Could not move uploaded file.

# Answer
Had a same problem. The best way to fix it is to:

1. Update the folder permissions on /sites/default to 777
2. Remove /sites/default/files folder
3. Go to /admin/config/media/file-system and click save so drupal re-creates the files folder.
4. Update the folder permissions back to 755 on /sites/default.

On my server when website creates a file or folder, the owner is set to nobody.nobody and since I already had a lot of files in my /sites/default/files folder all I had to do is update the ownership and permissions:

1. chown -R nobody.nobody ./sites/default/files
2. chmod -R 755 ./sites/default/files

Good luck!
> 2 votes

# Answer
It seems you have directory permissions issues on your server. Please go to `Configuration > Media> File system` `"admin/config/media/file-system "` and change Temporary directory or leave empty and save configuration( test it by leave it empty ,system set it to default that it can use as temp directory).
> 1 votes

---
Tags: files
---


# Question
Title: How do I disable the cache clear on comment form submission?
Unless I'm reading this incorrectly, it looks as if the last thing comment\_form\_submit does is clear the cache. All of it. This is done so anonymous users see the comment they posted.

I have a site that does, at times, receives high comment volume and the site does not allow anonymous users to post comments, so this behavior is suboptimal for me to say the least.

What's the Drupal way to override/kill the call to `cache_clear_all()` when comments are submitted? Can I do this in a module?

# Answer
> 2 votes
Should be reasonably straight forward with a form alter (mileage may vary slightly here but this is the general idea):

```
function MYMODULE_form_comment_form_alter(&$form, &$form_state, $form_id) {
  $key = array_search('comment_form_submit', $form['#submit']);
  if ($key !== FALSE) {
    $form['#submit'][$key] = 'MYMODULE_comment_form_submit';
  }
}

function MYMODULE_comment_form_submit($form, &$form_state) {
  // Copy code from comment_form() here, remove what you don't need.
}

```

---
Tags: 7, hooks, caching
---


# Question
Title: Change date formate in drupal admin tables (log, content listing, edit pages, etc)
I've looked everywhere but can't find out how to change the date format in the admin/content/ table and the recent log table.

Current it is displayed as '09/05/2014 - 00:18'' but I just wanted to make it YYYY-mm-dd - hh:mm'

What's the best way to make this happen?

# Answer
> 2 votes
From `/admin/config/regional/date-time` you can change the way dates are shown. This applies to the whole site though.

---
Tags: datetime, users
---