# Question
Title: When/where to include my own function library (like common.inc)?
When, hence where, should I include my own library of functions that I will use throughout my whole project.

Drupal has it's common.inc that is included in drupal\_bootstrap during the fase DRUPAL\_BOOTSTRAP\_FULL. I also have a common.inc with functions that I use all the time, in different modules. I want to include this file once so I can use it everywhere without having to include it in each file separatlely.

So what is the right location/hook to do it?

# Answer
> 5 votes
Probably best to put it in it's own custom module, e.g

```
sites/all/modules/custom/mymodule_common

```

and enable it as required.

You can make it a dependency of other modules by adding it to those module's .info file, e.g

```
dependencies[] = mymodule_common

```

You could also use subfolder and standalone file in `sites/all/libraries/common` though the module route is recommended.

# Answer
> -1 votes
As requested by Randell here is my own solution:

* Make a subdirectory in you site directory, call it "includes" (for example).
* Put your file with general functions in this directory (for example common.inc).
* Now, in one of your existing modules (I have a module called 'main', where I do all of the general things) add a hook\_init function.
* In this init function you include your general function file, like so:

```
require_once DRUPAL_ROOT . '/' . conf_path() . '/includes/common.inc';

```

The common.inc functions will be available throughout your project.

---
Tags: bootstrapping
---


title: Combining two columns in Views table

text:
# Question
Title: Combining two columns in Views table
I keep on having different requirements and I always get stuck in Views. This time the requirement is to combine the two columns/fields of a views table but display it in different rows.

The eg: fields I currently have: (Below is the added Picture)

The output of the View in Table (Nickname Multivalue separated by comma)

While Putting the Multiple value field in different rows

In the table settings I did combine two fields like

i.e. **Name** and **Nick Name** but that only gives result like:

(Here Nick Name is displayed after Name)

But **the requirements I need to display** is: (Name and Nick Name in Separate Row but at the same column). The Column needs to be sortable like normal Views Table Sort function.

Is there any settings in Views which lets me perform this? Or How can I accomplish this ?

**Edit:** If this is not possible and anybody could guide me to build custom query for this then I'd be very thankful.

**Edit 2**: SQL Query from Views Log is: (This query outputs the 2nd Image from above)

```
SELECT node.title AS node_title, node.nid AS nid, field_data_field_nick_names.delta AS field_data_field_nick_names_delta, field_data_field_nick_names.language AS field_data_field_nick_names_language, field_data_field_nick_names.bundle AS field_data_field_nick_names_bundle, field_data_field_nick_names.field_nick_names_value AS field_data_field_nick_names_field_nick_names_value, field_data_field_nick_names.field_nick_names_format AS field_data_field_nick_names_field_nick_names_format, node.created AS node_created, 'node' AS field_data_field_nick_names_node_entity_type, 'node' AS field_data_field_ages_node_entity_type, 'girls:page' AS view_name
FROM
{node} node
LEFT JOIN {field_data_field_nick_names} field_data_field_nick_names ON node.nid = field_data_field_nick_names.entity_id AND (field_data_field_nick_names.entity_type = 'node' AND field_data_field_nick_names.deleted = '0')
WHERE (( (node.status = '1') AND (node.type IN  ('girlss')) ))
ORDER BY node_created DESC

```

# Answer
You've structured your data in such a way that this can't be done with a single SQL query. You'll always be asking the database for two separate things: (1) a list of people based on their real names, and (2) a list based on their nick names.

But it doesn't have to be this way.

**The easiest way to accomplish Picture 4, by far, is to always represent a person's "Name" as an additional "Nick Name".**

So "Daina" should have 4 Nick Names: "Kristi", "Rita", "Sweetie", and "Daina". Then, all you need to ask the database for is a list of nick names.

This probably isn't the answer you're looking for. But I would argue that it's a more correct way to store your data. Think of the "Nick Name" field not as a list of alternate names, but rather as a list of all names that the person is known as. Based on the requirements of your situation, that's what it sounds like you're really after, anyway. It's a more complete model for your name data.
> 4 votes

# Answer
It would be possible to achieve this with overriding the views template file: `views-view-table.tpl.php`.

First you need to put multiple values in different rows.

Then in template file you should check for each row if Name is the same with the previous row. If not print the name and the age and add a new row in the code which includes the nickname and the age. If the name is the same with the previous one, then print only the nickname and the age.

I tried to explain it theoretically, but I can help with the implementation if you have difficulties.

**Steps:**

1. Override the views template: You need to copy the `views-view-table.tpl.php` file under your theme folder. This file is located under the Views module `views/theme/views-view-table.tpl.php`.
2. Rename the template file so that it only applies to that specific view: `views-view-table--YOUR-VIEW.tpl.php`. You should place the machine name of your view separated with 2 dashes.
3. You need to modify the following code block in this template file:

Code

```
<?php foreach ($rows as $row_count => $row): ?>
  <?php // dpm($row) // You can use dpm() function to print out the contents of $row array. ?>
  <tr <?php if ($row_classes[$row_count]) { print 'class="' . implode(' ', $row_classes[$row_count]) .'"';  } ?>>
    <?php foreach ($row as $field => $content): ?>
      <td <?php if ($field_classes[$field][$row_count]) { print 'class="'. $field_classes[$field][$row_count] . '" '; } ?><?php print drupal_attributes($field_attributes[$field][$row_count]); ?>>
        <?php print $content; ?>
      </td>
    <?php endforeach; ?>
  </tr>
<?php endforeach; ?>

```
> 1 votes

# Answer
OK, it looks like you are having the three columns combine into one, and then be split into the two you require, and as such are getting arbitrary data. Try going to "Style Settings" with the options you have now, alter the format to "unformatted", and save. Now go back in and reset it to Table. There should be the option to combine columns, and just choose the two that you wish.

I hope this helps.
> 0 votes

# Answer
In Structure -\> Views -\> settings -\> Check on "Show the SQL query". Go to your view, it displays query.

FORMAT - Show:fields, and then use "Global: PHP" for writing custom query. If you not installed use this link, https://drupal.org/project/views\_php .

After selecting Global: PHP - You can use the query already shown and then we can do as we like. All above fields should be checked with "Exclude from display" (i.e., Name, age, etc..).
> 0 votes

# Answer
Sorry I don't have a Drupal 7 testbed handy, but if you don't mind the age being grouped together, you can do something like this (screenshots here are in Drupal 6) that I assume is pretty much the same in Drupal 7.

First, off, grab the fields you need, in this case I created a content type called `name_nick_age` along with three fields `nna_name`, `nna_nick` and `nna_age` and then created a View:

And then inside the Style Settings for the Table, you by default have something like this:

That I changed to this:

The only change is placing the Name in the Nick column. This then created this table:

You gain access to the style settings by clicking on the little gear to the right of Style: Table and while the screen shots for Drupal 7 will be different, I am betting the functionality is in there for this.
> 0 votes

# Answer
```
   <?php $result = db_query("SELECT node.title AS node_title, node.nid AS nid, field_data_field_nick_names.delta AS field_data_field_nick_names_delta, field_data_field_nick_names.language AS field_data_field_nick_names_language, field_data_field_nick_names.bundle AS field_data_field_nick_names_bundle, field_data_field_nick_names.field_nick_names_value AS field_data_field_nick_names_field_nick_names_value, field_data_field_nick_names.field_nick_names_format AS field_data_field_nick_names_field_nick_names_format, node.created AS node_created, 'node' AS field_data_field_nick_names_node_entity_type, 'node' AS field_data_field_ages_node_entity_type, 'girls:page' AS view_name
    FROM
    {node} node
    LEFT JOIN {field_data_field_nick_names} field_data_field_nick_names ON node.nid = field_data_field_nick_names.entity_id AND (field_data_field_nick_names.entity_type = 'node' AND field_data_field_nick_names.deleted = '0')
    WHERE (( (node.status = '1') AND (node.type IN  ('girlss')) ))
    ORDER BY node_created DESC");

    $fullname = "";
    $nickname = "";
    foreach($result as $rec)
    {
        $fullname .= $rec->node_title.",";
        $nickname .= $rec->field_data_field_nick_names_delta.",";
    }
    echo $fullname;
    echo "<br>";
    echo $nickname;
?>

```

Check if results are displaying or not?
> 0 votes

---
Tags: 7, views
---


title: Editing Theme In Existing Drupal Site

text:
# Question
Title: Editing Theme In Existing Drupal Site
I work at a non-profit, and the person in charge of the website has left. I have taught myself how to edit the website online through our web log in, but can't figure out how to edit the theme. All I need to do is add a logo to the theme (we use the Zen subtheme). Is this something I can even do online, or do I need to set up a server shell or server test site on my desktop?

# Answer
> 1 votes
Go to /admin/appearance/settings/YOUR\_THEME\_NAME and scroll to the bottom and find the logo field and upload your custom logo

See the following for a nice visual walkthrough.

http://www.inmotionhosting.com/support/edu/drupal-7/customize-theme/upload-custom-logo

---
Tags: installation, theming
---


# Question
Title: Copy site to another domain - XML SiteMap wrong and Theme Settings not the same
I copied my productive site from www.mydomain.com to a testsite www.mytestsite.com on the same server. I did it this way: On productive server:

* Set productive site to offline
* Disabled Clean URL
* Emptied Cache
* created backup with the "backup and migrate" tool. All tables are backuped exept all cache-table and watchdog
* Copy *all* files

On target test server:

* Create new empty DB
* Import SQL script via MySQLAdmin from provider
* Copy all files
* change settings.php
* Login as Admin, set online, enable clean url, empty cache

Now I should have an identical site. But I have two differences (maybe more, which I cannot see):

1. XML Sitemap: Takes still the old domain name ("www.mydomain.com"). I can delete it and rebuild, no change. Why? This means that somewhere in a file the domain name must be written
2. The colors of hyperlinks are blue instead green as in the original site. When I go to "Theme settings" and simply press "save", then all is ok. Also here: Why is there wrong information about theme settings? Is this not saved in the DB?

Any help appreciated, thanks

# Answer
1. Go to admin/config/search/xmlsitemap/settings and set the correct domain. If that does not work look at your variable table in database and make sure xmlsitemap\_base\_url is correct.
2. Make sure your folder permissions are correct. If you have caching enabled and some themes need to write temp files inside sites/default/files so make sure permissions are correct and that Drupal can write there.

If that does not work can you inspect where the styles are coming from using Firebug and also post what theme you are using and I can update my answer.
> 1 votes

---
Tags: backups
---


title: Having views respect hook_node_access

text:
# Question
Title: Having views respect hook_node_access
I am using `hook_node_access()` to deny users access to some nodes based on a custom criteria. However, I do not want this content to show up in a view that lists it if the user does not pass the criteria. Is there any way to have views respect `hook_node_access()` implementations?

# Answer
> 8 votes
I had the same question a while ago here.

`hook_node_access` is not recognized by `views` or `menus`. It should only be used as the last line of defense.

A better way to control node access is through `hook_node_access_records` and `hook_node_grants` as described here and here .

# Answer
> 5 votes
hook\_node\_access() only is invoked when trying to view the full node. What you need to do is implement hook\_node\_access\_records() and hook\_node\_grants().

# Answer
> 1 votes
Views uses SQL determine the nodes to display. Sadly, for performance reasons it simply would not be feasible for Drupal to perform a node\_load on all potential candidates and then call hook\_node\_access on each one of those of all of them. Imagine a view which shows thousands of nodes (especially when using a pager). If the logic isn't done in SQL then the pagers would have very unusual functionalty thus Drupal forces you do it as rik mentioned using access records in your database.

Making access\_records is a fair amount more work but will make it work with SQL. Thus I recommend using an existing node\_access module to solve your functionality wherever possible because it will probably be implemented using access records and thus will work with views.

By the way the access records are stored in the table **node\_access** table as seen below: Through the comments for each column you can get an understanding of their purpose. Think of the realm as the system used for node access and the gid as the group within a realm. That group can have view, update, and delete permissions. In general each node\_access module defines one or more realms (sometimes multiple node\_access modules can also work in parallel). A user has one or more gids in each of the realms.

In Drupal all queries that have the "node\_access" tag will automatically have some special logic added. See the documentation to learn more about tagging. This special logic joins the "node\_access" table for each realm and adds the condition that where the "gid" is equal to one of the gids applied to a user, the user has the appropriate permission.

This whole system allows all queries to properly handle node\_access, even count queries, etc. It is very powerful but has a higher learning curve that just the simple hook\_node\_access. Whenever possible, using an existing node\_access module can save you this whole headache.

---
Tags: views, hooks, users
---


# Question
Title: Overriding Pathologic when it comes to img src
I have Pathologic installed and it is working great from normal links in a document, but for anything that points to the file system ( img src for example) I can't get it to not use ?q= in the url.

# Answer
You could alternatively use the scanner module or export the DB and use a text editor to replace the domains. Therefore getting rid of pathologic.
> 0 votes

# Answer
If you know how to write a custom module, you can implement hook\_pathologic\_alter() and tell Pathologic to not modify certain paths. See pathologic.api.php for examples.
> 0 votes

---
Tags: input-formats
---


# Question
Title: Theming node add form: "An unrecoverable error occurred" when uploading file
I am theming the node add form in drupal 7 for a custom content type. I have proceeded as indicated here.

As a test I managed to write my custom tpl.php file and get everything displayed correctly as it was in the original version without that tpl.php file. One of the field in the form is a file which gets uploaded with file widget.

My problem with my new form is that: when I click the "Upload" button for the file field in my form I get the following error:

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

But the file I am trying to upload is only about 100k!

I do *not* get this error when I use the regular form (i.e without using my custom tpl.php) file.

Here are the functions I implemented in my module:

```
/**
 * implements hook_theme
 *  to theme node add form
 *
 */
function mymodule_theme($existing, $type, $theme, $path) {
  return array(
               'mycontenttype_request_node_form' => array(
                                            'render element' => 'form',
                                            'template' => 'templates/mycontenttype-request-node-form',
                                            // this will set to module/theme path by default:
                                            'path' => drupal_get_path('theme', 'bootstrap_subtheme'),
                                            ),
               );
  }

/**
 * Preprocessor for theming ('mycontenttype_request_node_form').
 *
 */

function mymodule_preprocess_softsound_request_node_form(&$variables) {

  $variables['myreq'] = array();
  $hidden = array();

    foreach(element_children($variables['form']) as $key) {
          $type = $variables['form'][$key]['#type'];
    if($type == 'hidden' || $type == 'token'){
      $hidden[]= drupal_render($variables['form'][$key]);
    }
    else {
      $variables['myreq'][$key] = drupal_render($variables['form'][$key]);
    }
  }

    //$variables['myreq']['hidden'] = implode($hidden);
    //$variables['myreq'] = implode($variables['myreq']);

}

```

And here is my mycontenttype-request-node-form.tpl.php file:

```
 <div class="row-fluid">
    <div class="span8 offset2">
      <?php  print $myreq['title']; ?>
    </div>
  </div>

<div class="row-fluid">
    <div class="span8 offset2">
   <?php print $ssreq['field_description']; ?>
    </div>
  </div>

  <div class="row-fluid">
    <div class="span8 offset2" >
   <?php print $myreq['field_myfile']; ?>
    </div>
  </div>

  <div class="row-fluid">
    <div class="span8 offset2">
   <?php print $myreq['additional_settings']; ?>
    </div>
  </div>

  <div class="row-fluid">
    <div class="span8 offset2">
   <?php print $myreq['actions']; ?>
    </div>
  </div>

<?php print drupal_render_children($form); ?>

</div>

```

Any hints as to why I get the unrecoverable error relating to file size I mentioned above and how to get rid of it?

Thanks,

baba

# Answer
The problem was that i called drupal render on all elements of the form in my preprocess function and that I also called drupal\_render\_children in my tpl. This was redundant and caused errors.

my preprocess function now reads:

```
function mymodule_preprocess_softsound_request_node_form(&$variables) {

   $variables['myreq'] = array();

  $variables['myreq']['title'] = drupal_render($variables['form']['title']);
  $variables['myreq']['field_description'] = drupal_render($variables['form']['field_description']);
  $variables['myreq']['field_myfile'] = drupal_render($variables['form']['field_wavfile']);

}

```

and my tpl.php now reads:

```
<div class="row-fluid"  >
      <div class="span8 offset2" >
           <?php print $myreq['title']; ?>
           <?php print $myreq['field_description']; ?>
       </div>
  </div>

  <div class="row-fluid">
    <div class="span8 offset2" >
   <?php print $myreq['field_myfile']; ?>
    </div>
  </div>

<?php print drupal_render_children($form); ?>

</div>

```

thanks to Rashad Majali for the answer
> 0 votes

---
Tags: theming, forms, nodes
---


# Question
Title: How to add .current class into menu link when page is being viewed
I have a custom menu - its a module with html links in the .tpl file, set on the website as a block. I wanted to know is it possible to configure drupal so it dynamically add .current class to those links so I can style it when particular page is being viewed. Thanks for help.

# Answer
> 2 votes
If you create a new menu and make it a block then it will set a class called "active" when you are on the current page. You will also get a class called "active-trail" for each parent item. If you want to create something more custom then you can check and see if the url matches the link you are building.

You can see here how the menu is being built to get some ideas:

https://api.drupal.org/api/drupal/includes%21menu.inc/function/menu\_tree\_output/7

If you want to do something custom then you will need to compare $\_GET\['q'\] to the link that you are building in order to set an active class.

I am pretty sure you can also use theme\_item list and the active class will be set:

https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme\_item\_list/7

# Answer
> 0 votes
Also you can use the module menu attributes and at the same time create a custom token that print the class that you need.

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


# Question
Title: Relationships between nodes and display in a special order
I have two content types: 1) Team member and 2) office

There are about 150 team member nodes that need to be associated with 50 offices. When a team member is added to the site, there should be an auto complete field, where the name of the office, the member is in, can be selected.

After saving, the team member information should show up at the office which she has just been associated with. (Name, title and photo should be displayed - which could be done with Display Suite's view modes.)

In addition, each team member is associated with a specific function (head, partner, principal, consultant). This is done with taxonomy. On the office page, however, the team members associated with that office should be ordered according to the team members' taxonomy function. Those team members with the taxonomy term "head" should be displayed first, those with taxonomy term "partner" second, "principal" third etc.

How can this best be achieved? I have taken Entity Reference and Nodereference modules into consideration. Can this be done with Display Suite only or do I need to create a Views block?

# Answer
I solved this with the modules: entity reference and corresponding entity reference, setting up a relationship between the "team member" and "office" content type.

Then I created a view and added A Contextual Filter choosing the reference field from the "team member" content type as a contextual filter. Then I added: "Provide default value" "Content ID from URL" in the "When the filter value is no available" option.

After that I chose "Content: Function" field as a sort criteria so that the team members will be displayed according to the taxonomy order. Finally I added the block, which I created with the view, to the office page content type under manage display.
> 0 votes

---
Tags: nodes
---


# Question
Title: How can I show two users what taxonomy terms they have selected in common?
I have a taxonomy vocabulary, **Hobbies**. Users can select their hobbies from a list of about 300. Many users select a few dozen hobbies, which makes for an extremely long list.

What I'd like to do is show a special list of those hobbies that the logged-in user has in common with the user being viewed.

I'm using Panels to override the user profile page, so I can easily attach views/content panes, blocks, etc. I also have access to the logged-in user and the user being viewed through Panels contexts.

Is it possible to use Views to filter out taxonomy values in this way? If not, how might I show users those terms that they have in common?

# Answer
You are looking for Taxonomy Filter module

> if vocabulary A is set to be 'filtered' by vocabulary B (which may be vocabulary A), then whenever someone views the taxonomy listing of a term in vocabulary A they will see a 'filter' menu of terms from vocabularies A and B. This allows the visitor to narrow down the listing by choosing another term - effectively showing them the ***intersection*** set of nodes from the two terms.
> 0 votes

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


# Question
Title: How to programmatically duplicate a node reference field during rendering?
I am working on a node type which contains node references to other types. I want to programmatically duplicate a few node reference fields based on a set of conditions during rendering of the node. I have not been able to figure that out.

# Answer
You have total control over the layout of nodes within your theme via the `node.tpl.php` file and its variants and overrides. Check out a lot of information about node.tpl.php here and template files in general here.

By creating a specific template, you can customize it to your purposes along these lines:

```
function YOURTHEME_preprocess_node(&$vars) {

  if ( /* whatever condition you have that returns true for printing */ ) {
    $vars['template_files'][]='node-printing';
  }

  // any other node preprocessing goes here

}

```

Then, you put a `node-printing.tpl.php` file in your theme directory next to the default `node.tpl.php` for your theme, and in there, customize it as you like.

The key variables to be looking at are `$content` and `$node`. If you goto `admin/content/node-type/NODE_TYPE/display` on your system you can see how `$content` is built and customized, while the latter is it as an object containing all of its fields that you can rework and so forth.

Putting a `drupal_set_message('<pre>' . print_r($node, TRUE) . '</pre>');` at the top of your new template file will show you what you have to work with.

And, as always, just remember to clear caches after creating this new template so that the theme registry picks it up, but now you should be able put anything anywhere you want in your node display.
> 0 votes

---
Tags: 6, nodes
---


title: Capturing Views AJAX pager click

text:
# Question
Title: Capturing Views AJAX pager click
I am on Drupal 7.

I have a Views block with a pager sitting on the bottom part of it. I am using AJAX pager, meaning the page isn't reloaded. When the pager is clicked, the block reloads all the elements inside of it to display elements on the second page. But because my block is kind of long, when the pager is triggered, I would like to take my user again to the top of the block. I can do that with an anchor that will slowly scroll the page to the anchor that sits on top of that block. There is no issue with this. My doubt is: how can I add a javascript listener that will capture a Views AJAX pager click so that my code can be executed? What is the right Drupal way of doing this? Thank you so much.

# Answer
> 1 votes
In ajax view, by default this functionality is already there. When you click on ajax pager it will automatically scroll to top of content. If it is not working check your console for is there any error showing.

---
Tags: views, ajax, javascript, paging
---


title: Why render funcion hide img tags?

text:
# Question
Title: Why render funcion hide img tags?
I have a simple text that contains tags but when I try to render the field, the img tags disappear!

```
<?php print render($content['field_with_img_tags']); ?>

```

Why?

# Answer
> 1 votes
What type of field are you using ? If it is a `body_format` using a format (i.e.: Filtered HTML, Full HTML) verify the filter settings. Probably `Limit allowed HTML tags` is enabled and the tag is not part of the allowed tags.

To verify / change settings, it is under `admin/config/content/formats` and click on `configure` link of your used format.

# Answer
> -1 votes
try

```
print drupal_render($content['field_with_img_tags']);

```

---
Tags: theming, 7
---


title: Drupal 7 views grid format slideshow

text:
# Question
Title: Drupal 7 views grid format slideshow
I am using drupal 7, I want to show the two columns of image with previous and next button on the top. The previous and next button will be used to show the grid format images. I can tried with views grid format, but how can i show the previous and next link of the view? Thanks in advance.

Regards, Sathish

# Answer
> 1 votes
You can create slideshows using Views Slideshow module. You can add thumbnail images below the main slide image. There is a setting already there in views slide show settings.

See this : Create an Image Slideshow with Drupal using Views

# Answer
> 0 votes
I think this will only work with the slideshow format, not grid format. You can have a pager at the bottom when you hit more than a specified number of grid images.

---
Tags: javascript
---


title: hook_menu_alter not working

text:
# Question
Title: hook_menu_alter not working
I'm trying to alter tab names ("view current" and "edit current") but it is just not working.

```
function MY_MODULE_custom_menu_alter(&$items) {
    $items['node/%node/view']['title'] = t('View Event');
    $items['node/%node/edit']['title'] = t('Edit Event');
}

```

Module implementation is good. Cache is cleared. Tried it milion times, but still nothing!

Wondering is it possible that this code is being overriden somewhere, and how can I check that?

# Answer
If your hook implementation is definitely being fired then it does seem likely that another module (or even a theme, potentially) is overriding your changes.

To ensure your module's implementation runs last, you can implement `hook_module_implements_alter()`:

```
function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'menu_alter') {
    $group = $implementations['my_module'];
    unset($implementations['my_module']);
    $implementations['my_module'] = $group;
  }
}

```

If that isn't the problem, it might be something simpler...if your code is copied verbatim then you're setting the title twice for the same path. You might have meant

```
$items['node/%node/view']['title'] = t('View Event');

```

Or it might even be a combination of both of those.
> 3 votes

# Answer
The {menu\_router} table contains the compiled result of hook\_menu() and hook\_menu\_alter() implementations throughout your enabled modules. You can look at the entry for "node/%/edit" to see what's actually stored there for the "title" column; if it's "Edit Event", then your code is fine, and your problem is elsewhere.

If you suspect another hook\_menu\_alter() implementation is overriding you, you might try to grep for "node/%node/edit" throughout your codebase. You might also see if you have any Views page displays that are set with a path of "node/%/edit" - Views registers those routes programmatically using hook\_menu\_alter().
> 1 votes

# Answer
All right guys, I fixed it by installing Tab Name Tweaker module.

I still do not understand what is wrong with my code though. Note that Tab name tweaker module **did not** work all until I removed my custom hook\_menu\_alter(). That leads to conclusion that something must be wrong with this implementation:

```
    function MY_MODULE_menu_alter(&$items) {
        $items['node/%node/view']['title'] = t('Blah View');
        $items['node/%node/edit']['title'] = t('Blah Edit');
     }

```

I had also installed Modules Weight module, and tried putting my custom module at the end of list. No effect!

And even more strange, I use exactly the same code above to alter User profile tabs (in separate module), and it works there. Go figure out that! Insane!
> 1 votes

# Answer
Once I have the same problem and I solved it in an ugly way, but it works. I think that @Clive is right, some module is overriding your implementation so basically you have to update the module weight to run it at the end. To do it you can run:

```
update schema.system set weight = '99' WHERE name = "MODULE_NAME";

```

If this is working, you may look for some hooks to change the module weight.
> 0 votes

---
Tags: routes
---


# Question
Title: How to prevent actions using Flag (or similar) module?
The Goal: I'm trying to setup functionality similar to a library with downloadable files. Only one user can download a file at a time.

The Solution: Use the Flag module.

Open to suggestions but through my research it seems like people are using the Flag module for this type of functionality. My question is how do I actually get this to work? I'm using a file field to add a file to a node. An admin comes along, wants to "checkout" that file, and they click the checkout flag, and then download the file. Now no other admin can download that file.

Once the original admin comes back, they can just click the flag again, setting it to open. (I know, they aren't really returning a digital file.) They just need to simulate returning it by basically just telling the system someone else can get this file.

Anyone set up something similar to this or just have an idea of how I would do this? Thanks for any suggestions and help.

# Answer
> 1 votes
I haven't done this, but if you want a library check in/check out system this is the approach I would try. Create a flag (here I'll call it *Check out*) that allows users to "check out" files. Make sure this is a global flag. Name the unflag link "Check in" or something similar. (You could also automatically have files checked back in after a certain interval with Rules Scheduler.)

Then, I would create views so that users cannot see the nodes that are checked out. To actually enforce security, I would also add a rule that automatically redirects users away from the page of any node that they did not flag that has been flagged (this probably will cause a performance hit and may not be the most secure way but will probably work for general cases).

# Answer
> 0 votes
Well the maintainer of the module said it probably isn't possible to do what I want without writing a custom module. The maintainer also stated you can't flag files out of the box like I'm referring to here. Since I want to disable the file download on flag, I can't add the flag to the node and disable because that will disable the node--not my intention.

So since my php skills are virtually equal to nothing I accomplished this via javascript. First, I added the flag to the node. Then I added some js:

```
$(".flagged").each(function(){
    $(".checkout-file").remove();
});

```

Easy to get around, I know, but I don't really need to protect the files at all and only admin will be perusing these files anyway. I only wanted to disable the download as an extra measure in case they don't notice the flag. The purpose being to state, "Don't bother wasting your time downloading this file since someone else is already reviewing it." So maybe someone else will need something like this.

# Answer
> 0 votes
you should consider a less popular module called "conditional flags" - you can create two flags that effectively represent "checked out" and "available" and make the "available" set to "not available" when a user "checks out" an item.

there are also code examples on the project page and so it may be possible to customize the module for a more elaborate need (e.g. a rule/trigger/action linked to a download or something more robust) enter link description here

---
Tags: 7, rules, flags, files
---


# Question
Title: views exposed filter: Prevent a user from searching default Paceholder Text
i have been looking for a solution all day, i need some help. I created a single search box using views combine exposed filters. i am using bartik theme. On the exposed filter, i have added some default text using the following code in my template.php file as per this code snippet:

```
function bartik_form_views_exposed_form_alter(&$form, &$form_state) {
  if (!isset($form_state['view']->exposed_input['combine'])) {
    // OK to set the default value
    $form_state['input']['combine'] = 'Find Professionals';
  }
}

```

So far, my default text is showing, but i need to achieve 2 things:

1. Make default text to disappear when user clicks on the search box
2. Prevent user from searching default text.

ps: "combine" is the name of my views exposed filter, while "views\_exposed\_form" is the form id.

Thanks for your help in achieving this.

# Answer
@Bala You actually pointed me in the right direction by mentioning "placeholder", I have also added that word to the question, Thanks for the help, so i did more research since i wanted to avoid enabling 2 modules because of only one exposed filter (i have many modules enabled already), so adding this code to my theme's template.php file as per this comment worked perfectly for me:

```
<?php
function yourtheme_form_alter(&$form, &$form_state, $form_id){
  if($form_id == "views_exposed_form"){
    if (isset($form['combine'])) {
            $form['combine']['#attributes'] = array('placeholder' => array(t('Find Professionals')));
    }
  }
}
?>

```

For benefit of novices, "yourtheme" in the function should be replaced with the name of your theme, 'combine' is the name of my exposed filter (You Can find yours by right-clicking the form on firefox or google chrome and clicking "inspect element").

This solution works for drupal 7
> 2 votes

---
Tags: 7, views
---


title: how to remove empty rows from view

text:
# Question
Title: how to remove empty rows from view
how to remove empty rows from view(block) ? I have a created a View block using field collection even empty condition are enabled in the fields settings still im getting empty rows PFA for image 2 in that only view-row-95 has values rest all the view-row are empty .

# Answer
In this given image(second image), it is clear that there is a value " "(space) coming for the field **Footer Col3**.

Check in **Footer Col3** field settings or in any custom module if you are set any default value for that field.
> 2 votes

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


# Question
Title: Fivestar rating for anonymous user should redirect to login or register
When anonymous users tries to rate a node with fivestar rating, they will be asked to either login or register to continue. How to achieve it???

# Answer
> -2 votes
You can use the Rules module to achieve this.

Check out this Great tutorial.

---
Tags: rating
---


# Question
Title: How can I have drupal commerce create a sku and adjust prices on the fly?
This is something I've done in the past outside of Drupal but I can't seem to figure out how to do this with Drupal Commerce.

I need the ability to do the following:

1. Allow the user to create parts via category (this could be a taxonomy term with fields like name, image, sku component, description, price markup...)
2. Allow the user to create a new product and select which parts can be placed on this product.
3. When the end user is looking at the product page, they will select which parts they want for this product.
4. When they select their parts the PHP script, on submission, will create a line item with sku comprised of the parts selected and a price made up of the base price of the product + any additional cost per part.

So, for instance, part category A has 5 parts. Standard and 4 upgrades. If the user selects an upgrade from Category A, it will modify the SKU on submission AND update the price based on the markup price of the part's price field.

Anybody following me here? How do I do this? I'll code it myself if I have to, I just need to know where to begin.

# Answer
> 0 votes
Try this rule, it will alter the line item's label based on tokens specified when a product type "Product" is added to cart. This is how you can keep it specific to a certain product type. A line item's label is defaulted to the product's SKU.

All of your term-reference attributes will be exposed as tokens. For formatting ideas, check out Commerce AutoSKU which generates product SKUs at product creation (not line item.)

```
{ "rules_alter_line_item_sku" : {
"LABEL" : "Alter line item label",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "commerce_cart" ],
"ON" : { "commerce_cart_product_add" : [] },
"IF" : [
  { "entity_is_of_type" : { "entity" : [ "commerce-line-item" ], "type" : "commerce_line_item" } },
  { "data_is" : { "data" : [ "commerce-product:type" ], "value" : "product" } }
],
"DO" : [
  { "data_set" : {
      "data" : [ "commerce-line-item:line-item-label" ],
      "value" : "[commerce-product:type]-[commerce-order:uid]"
    }
  }
]
  }
}

```

---
Tags: commerce
---


# Question
Title: Create Relation between two vocabulary terms in views expose filter
Suppose if i have 2 vocabularies in which first vocabulary name is "Country" which contain some country names and Second is "Cities" which contain some cities names. If i want to select a particular country from "country" expose filter and i want that only few selected cities will automatically appear in "cities" expose filter. So that user dont have to go through all the list of cities of all the countries.

Is it possible with drupal views or any contributed module ? otherwise i have to do it with jquery hide/show .

# Answer
I am posting answer to this question, as it might help somebody. I havent got any suitable module which can create relation between two taxonomy vocabularies as i want, But i have modified my taxonomy a little bit to do this from a module.

I have merged my 2 vocabularies into single . I have placed country as parent term and all the cities as sub-term. So my structure is like this :

India

* Delhi
* Rajashtan
* Chandigarh
* Gujrat

USA

* Alabama
* Alaska
* Georgia
* Illinois

Then I have used a simple module called "Simple Hierarchical Select" https://drupal.org/project/shs or you can also use Hierarchical Select" https://drupal.org/project/hierarchical\_select But hierarchical select has more functions but if you have taxonomy related task only then you can use only SHS as in my case.

Now go to the content type -\> manage fields -\> select term reference-\> simple hierarchical select .

Now go to your views =\> select the "your-field-name" (hierarchical select ) from filters and force it to some depth.

Then it will show first country name and then child term which are city names.
> 1 votes

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


# Question
Title: Is there a means for telling which module or template files generated a block?
I am trying to find out what code generated a faulty looking devel block and want to know if there is a module that can tell where a block was generated or some other means.

Is there a module for that, something like the Module Summary, but with info on blocks?

# Answer
If you haven't greatly overwritten the default block.tpl.php, you can tell by looking at the HTML attributes of the block DIV, which follow this naming convention:

```
<div id="block-MODULENAME-DELTA" class="block block-MODULENAME">
  ...
</div>

```
> 2 votes

---
Tags: 7, theming, hooks, blocks, files
---


# Question
Title: Not able to make simple node path show up in "crumbs module"
I have read all the documentation, and I have been clicking about wildly for hours, and I have used the "debug" tab for the Crumbs module, and I still cannot get the simplest path to show up:

Home \> Content type \> Node title

It always gives me: Home \> Node title

This seems a simple task. Someone please give me the steps...

Many thanks.

# Answer
What is the path you want to link to for "Content type" ? Do you have e.g. a view at this url?

You need to have *something* at this url, and Crumbs needs to be able to determine a title at this url. Otherwise it won't appear in the breadcrumb.

So, what you can do:

* Create a view at path "events" or "news" or whatever.
* Let the title of the view be "Events" or "News". There are two ways to do this:
    + In the Views admin, "Page settings", click "Menu", and set it to something where you can specify a title. OR
    + Choose your favourite menu, and create a link to the Views page.
    + It is NOT enough for the view to have a title by itself. It needs to have a title in the menu/routing system. (\*)
* In Crumbs "Entity parent" settings, set "events" or "news" as the parent path for the respective node type.

There are other ways to create a parent page like "news" or "events". For instance, I like to use a "page" content type with a "blockreference" field to embed a views block.

(\*) Maybe I should create a plugin that uses the real page title of the View as the title of the breadcrumb link.
> 0 votes

---
Tags: breadcrumbs
---


title: Trouble with Form API and #states

text:
# Question
Title: Trouble with Form API and #states
I have a form built and need a fieldset to collapse/expand based on the value of another checkbox field.

The checkbox code is:

```
$form[$serving_key] = array(
        '#type' => 'checkbox',
        '#title' => t($serve_size)
);

```

The fieldset is:

```
$form[$fieldset_key] = array(
        '#type' => 'fieldset',
        '#collapsible' => TRUE,
        '#collapsed' => TRUE,
        '#states' => array(
            'expanded' => array(
                ':input[name="' . $serving_key . '"]' => array('checked' => TRUE)
            )
        )
);

```

These are in a foreach loop, and $serving\_key at any point is 'serving\_large', 'serving\_small', etc. The corresponding $fieldset\_key is 'fieldset\_large', 'fieldset\_small', etc.

This looks like it should work in the form\_example\_states\_form example code. What am I missing?

# Answer
> 3 votes
You forgot about unique keys in your form elements. Here is a working example:

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

  // your size options
  $options = array('small', 'medium', 'big');

  $form['checkboxes'] = array(
    '#type' => 'fieldset',
  );

  foreach ($options as $size) {

    $form['checkboxes'][$size . '_checkbox'] = array(
      '#type' => 'checkbox',
      '#title' => t($size . ' size'),
    );

    $form[$size . '_field'] = array(
      '#type' => 'fieldset',
      '#title' => t($size . ' size'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
      '#states' => array(
        'expanded' => array(
          ':input[name="' . $size. '_checkbox"]' => array('checked' => TRUE),
        ),
      ),
    );

    $form[$size . '_field']['some_info'] = array(
      '#type' => 'textarea',
      '#title' => t($size . ' size textarea'),
    );
  }
  return $form;
}

```

**Result:**

---
Tags: 7, forms
---


# Question
Title: Remove trimmed version form preview screen?
When I preview a node before creating it I get this message:

```
'The trimmed version of your post shows what your post looks like when promoted to the main page or when exported for syndication. You can insert the delimiter "<!--break-->" (without the quotes) to fine-tune where your post gets split.'

```

And I also get a trimmed and full version in the preview. This has no relivance for my site and is actually quite confusing. How can I remove it?

I dont want to hide the message with CSS (as in the linked method) as im assuming other messages can be shown in the same div. How to hide the "trimmed version" from the preview page?

Ive tried removing the teaser display for the content type under 'custom display settings'.

The field is a text area, not a text area with summary.

Ive tried using the String Overrides module.

Ive tried this theme function but it didnt do anything. http://drupal.org/node/1355962

# Answer
> 2 votes
Ah, the linked template.php override method (code below) does work but you need a sub theme for it to do so.

```
/**
 * Override node preview to remove trimmed teaser version.
 */
function theme_node_preview($variables) {
  $node = $variables['node'];

  $output = '<div class="preview">';

  $preview_trimmed_version = FALSE;

  $elements = node_view(clone $node, 'teaser');
  $trimmed = drupal_render($elements);
  $elements = node_view($node, 'full');
  $full = drupal_render($elements);

  // Do we need to preview trimmed version of post as well as full version?
  if ($trimmed != $full) {
   // drupal_set_message(t('The trimmed version of your post shows what your post looks like when promoted to the main page or when exported for syndication.<span class="no-js"> You can insert the delimiter "<!--break-->" (without the quotes) to fine-tune where your post gets split.</span>'));
    //$output .= '<h3>' . t('Preview trimmed version') . '</h3>';
    //$output .= $trimmed;
    //$output .= '<h3>' . t('Preview full version') . '</h3>';
    $output .= $full;
  }
  else {
    $output .= $full;
  }
  $output .= "</div>\n";

  return $output;
}

```

UPDATE this has stopped working for me. It seems the code doenst work properly with my zen template.

UPDATE This code worked for me:

```
            /**
             * Returns HTML for a node preview for display during node creation and editing.
             *
             * @param $variables
             *   An associative array containing:
             *   - node: The node object which is being previewed.
             *
             * @ingroup themeable
             */
            function THEMENAME_node_preview($variables) {
              $node = $variables['node'];

              $output = '<div class="preview">';

              $preview_trimmed_version = FALSE;

              $elements = node_view(clone $node, 'teaser');
              $trimmed = drupal_render($elements);
              $elements = node_view($node, 'full');
              $full = drupal_render($elements);

              // Do we need to preview trimmed version of post as well as full version?
              if ($trimmed != $full) {
               // drupal_set_message(t('The trimmed version of your post shows what your post looks like when promoted to the main page or when exported for syndication.<span class="no-js"> You can insert the delimiter "<!--break-->" (without the quotes) to fine-tune where your post gets split.</span>'));
               // $output .= '<h3>' . t('Preview trimmed version') . '</h3>';
               // $output .= $trimmed;
               // $output .= '<h3>' . t('Preview full version') . '</h3>';
                $output .= $full;
              }
              else {
                $output .= $full;
              }
              $output .= "</div>\n";

              return $output;
            }

```

# Answer
> 0 votes
Here's a slightly better version, which will execute more quickly because it doesn't render the node twice. Put the following in the template.php file of your theme, renaming the function to match your theme name:

```
/**
 * Returns HTML for a node preview for display during node creation and editing.
 * Customized version removes the trimmed/teaser version and any links from the     preview
 *
 * @param $variables
 *   An associative array containing:
 *   - node: The node object which is being previewed.
 *
 * @see node_preview()
 * @ingroup themeable
 */
function THEMENAME_node_preview($variables) {
  $node = $variables['node'];

  $output = '<div class="preview">';

  $output .= '<h3>' . t('Preview full version') . '</h3>';

  $elements = node_view($node, 'full');
  unset($elements['links']);  //this is optional, but I think links are distracting when previewing a node
  $output .= drupal_render($elements);
  $output .= "</div>\n";

  return $output;
}

```

---
Tags: 7
---


# Question
Title: What is the difference between Microdata or Schema.org (or can I use both)?
I am building a community site in Drupal 7.

I am using the SEO checklist, which suggest to use the microdata module.

Other places I read are suggesting to use Schema.org module.

what is difference between them? Can I use both modules?

# Answer
> 6 votes
They are different things:

If you want to use the Schema.org vocabulary, you can use the syntax Microdata, or RDFa (Lite), or JSON-LD (or any other RDF serialization, but the three mentioned syntaxes are supported by the big search engines that sponsor Schema.org).

---

The schemaorg module integrates the Schema.org vocabulary into Drupal 7 by using RDFa 1.0, which is the syntax used by Drupal 7 for other vocabularies, too.

The microdata integrates the Schema.org vocabulary by using Microdata (without this module, Drupal 7 does not output any Microdata).

If you can’t decide between these two modules: Go with schemaorg, because Drupal 7 already uses RDFa, RDFa is more powerful than Microdata, and parts of this module were ported into the Drupal 8 core.

# Answer
> 1 votes
From what I've experienced Google picks up all of these formats. Sites I build use the default RDF module. I would not recommend running both modules as I could only it imagine adding a lot of bloat to your system.

I would visit Google's Structured Data Testing Tool: http://www.google.com/webmasters/tools/richsnippets

Give all three modules a try, experiment with different pages and make a decision based off of those results. In the end there is no perfect SEO equation beyond what you think is proper.

---
Tags: 7
---


title: Automated Drupal issue queue workflow

text:
# Question
Title: Automated Drupal issue queue workflow
Working in the issue queue on any busy project can be quite a bit of work.

Lots of files (patches) to manage, interdiffs, and ideally a branch for piece of work, moving patches forward with rebase etc.

What (if any) automated workflows are there to ease these tasks? This could either be code, such as some form of git wrapper, or perhaps just an explanation of how to use existing tools.

# Answer
> 1 votes
As well as drush\_iq, you might consider patch manager.

---
Tags: workflows, community-official-site, queue
---


# Question
Title: How can I enable HTML output for checkbox options?
I am adding theme styling settings and I would like to have associated color to the checkbox in themes setting form. So far, i haven't been able to do so, because the output strips inline styling and then external styling is being reset for the admin view. How do you enable html output of the text next to the checkbox?

Here is my code so far:

```
function THEMENAME_form_system_theme_settings_alter(&$form, &$form_state){
       $form['theme_style'] = array(
        '#title' => 'Theme Style',
        '#type' => 'fieldset',
        '#collapsible' => FALSE,
        '#collapsed' => FALSE,
    );
    $form['theme_style']['color'] = array(
        '#title' => t('Color Skin'),
        '#type' => 'checkboxes',
        '#options' => color_schemas(),
//        '#process' => array(),
        '#pre_render' => array(),
        '#post_render' => array(),
        '#format' => array('text_format' => 'full_html'),
    );
}

function color_schemas(){
   $colors = array(
        'blue' => htmlentities('<span style="display:inline-block;width:20px;height:20px;background-color:#DDD;vertical-align:middle;border-radius:0">Blue</span>'),
        'black' => '<span id="black-skin">Black</span>',
        'maroon' => t('Maroon'),
        'grey' => t('Grey'),
        'white' => t('White'),
    );
    return $colors;
}

```

Here i try different things. To set the text format in '#format' attribute. I also attach 'id' element so could style in external style sheet but those are reset by admin imported CSS. I also try convert all html entities and output which works but it doesn't render the html correctly

# Answer
> 0 votes
For starters, if you're using an admin theme like Seven for your administration pages, nothing on those pages will ever be affected by another theme's code. If you need to write code that applies across any theme, then you should be putting that in a module.

Inline styles are an attack vector for XSS, which is why they're generally not allowed in any kind of markup that is the result of user input. That includes the label text for a form element, such as a checkbox: the label is constructed by theme\_form\_element\_label(), which sanitizes the text with filter\_xss\_admin(). That's absolutely the correct thing to do.

The proper way to do this is to put your styles in an external spreadsheet, as you've mentioned. Consider whether you could implement your code as a module instead.

# Answer
> 0 votes
You can use simple markup in the `t()` function, look at especially this comment, which indicates to this source: Dynamic or static links and HTML in translatable strings.

> The general rule of thumb for translatable strings is that we keep inline markup for translation but avoid block tags (but do read the whole story before you make this your mantra).

According to this documentation, your code should be look like:

```
function color_schemas() {
  $colors = array(
    'blue' => t('<span style="display:inline-block;width:20px;height:20px;background-color:#DDD;vertical-align:middle;border-radius:0">Blue</span>'),
    'black' => t('<span id="black-skin">Black</span>'),
    'maroon' => t('Maroon'),
    'grey' => t('Grey'),
    'white' => t('White'),
  );
  return $colors;
}

```

Though I would suggest you to use css classes for `span` instead of inline styling.

---
Tags: 7, forms
---


# Question
Title: Printing taxonomy terms as an un-ordered list
How to print taxonomy terms as an un-ordered list in `page.tpl.php`. Where i want to print a taxonomy term called "Article Category" and all its vocabularies one by one as a un-ordered list, so it can be used as a menu. Can't understand, please give me ideas?

* **EDIT:** I know about a module "Taxonomy Menu" but looking for a programmatic direction, idea or any kind of reference that will help me to get started.

Thanks

# Answer
> 2 votes
OK, there is a module for that! Taxonomy Menu. Once installed, you can quite simply turn your vocabulary into a menu by going to admin \> structure \> taxonomy \> {your vocabulary} \> edit

You can also play around with it and get multi-level menus, which I think is what you are after/asking for.

Hope this helps!

# Answer
> 1 votes
You can try https://drupal.org/project/taxonomy\_menu. This module helps you print any taxonomy vocabulary as menu. More details from the module's project page:

> * Custom Menu per vocabulary
> * Uses the default taxonomy term path or custom paths
> * Integrate with Views
> * Integrate with Pathauto: use URL/path aliases
> * Does not interfere with other menu modules

# Answer
> 1 votes
I pulled this from here:

```
$terms = taxonomy_get_tree(1); // Use the correct vocabulary id.

// Get the active trail tid-s.
$active = arg(2);
$active_parents = taxonomy_get_parents_all($active);
$active_parents_tids = array();
foreach ($active_parents as $parent) {
  $active_parents_tids[] = $parent->tid;
}

// Build the menu.
$term_count = count($terms);
$cont = '<ul class="taxonomy_menu">';
for ($i = 0; $i < $term_count; $i++) {
  // Build the classes string.
  $classes = '';
  $children = taxonomy_get_children($terms[$i]->tid);
  $active_trail = in_array($terms[$i]->tid, $active_parents_tids);
  if ($active_trail && $children) $classes .= 'expanded active-trail ';
  elseif ($active_trail) $classes .= 'active-trail ';
  elseif ($children) $classes .= 'collapsed ';

  if ($i == 0) $cont .= '<li class="first '.$classes.'">'.l($terms[$i]->name, 'taxonomy/term/'.$terms[$i]->tid);
  else {
    if ($terms[$i]->depth == $depth) $cont .= '</li><li class="'.$classes.'">'.l($terms[$i]->name, 'taxonomy/term/'.$terms[$i]->tid);
    elseif ($terms[$i]->depth > $depth) $cont .= '<ul class="level-'.$terms[$i]->depth.'"><li class="first '.$classes.'">'.l($terms[$i]->name, 'taxonomy/term/'.$terms[$i]->tid);
    elseif ($terms[$i]->depth < $depth) {
      // Add missing end-tags depending of depth level difference.
      for ($j = $terms[$i]->depth; $j < $depth; $j++) {
        $cont .= '</li></ul>';
      }
      $cont .= '</li><li class="'.$classes.'">'.l($terms[$i]->name, 'taxonomy/term/'.$terms[$i]->tid);
    }
    // If we have reached the last element add all possibly missing end-tags.
    if (!isset($terms[$i+1])) {
      for ($j = 0; $j < $terms[$i]->depth; $j++) {
        $cont .= '</li></ul>';
      }
    }
  }
  $depth = $terms[$i]->depth;
}
$cont .= '</li></ul>';

```

Finding the $vid can be a bit tricky, start with 1 and go from there.

# Answer
> 0 votes
I think Views is the right and the best way to go. There are lots of tutorials on net about this; but if you need help please ask.

# Answer
> 0 votes
If I understood correctly, you are looking to print the taxonomy term for the page, below is the code you can place it in your page.tpl.

```
<?php
foreach($node->taxonomy as $tid => $taxo)
   $taxo_links[] = l($taxo->name,"taxonomy/term/$taxo->tid", array('title' => $taxo->name));
print t('Located : '). implode('  >  ',$taxo_links);
 ?>

```

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


# Question
Title: Show certain slides only on specific urls on views slideshow
Using views slideshow I want to be able to control what nodes of content type "slides" show depending on what URL, any ideas? for example on page-front I would like to show slide1 and slide2, on node/43 I would like to show slide3 and slide4.

Having separate views is not an option because this is a slider that is on hundreds of pages and different content types.

# Answer
Would you be better off having two separate views for the two URLs? If you do need this done in a single view, you will need to write custom module that adds filters to the view. Try using contrib module called views\_arg\_context
> 0 votes

# Answer
Normally answer is Contextual Filters; but i am not sure that i understood your problem definately. What is your criterion (nid, content type, date, taxonomy etc.) to relate node/43 and slides 3-4? If there is a relation between node/43 and slides 3-4, then you can filter them using Contextual Filters (Or, if possible, you could need to create a Relationship first.). If there is no relation/criterion, you could add an additional field to relevant content type(s) and fill it manually or automatically, then filter by its value.
> 0 votes

---
Tags: 7, views
---


# Question
Title: problems with caching - only (performance) Clear cached data - will load my page correctly after an edit
On a (drupal 6 based) website that is used as a database to track product information:

I have a page that starts a number of SQL to correctly sort the data, but after a page **edit** of the product information, these SQL scripts don't start, and the new data isn't displayed properly.

If I go to admin/settings/performance everything reloads, the SQL scripts run and the page displays data as it should.

How do I get around having to after each edit.

I have tried: 1. admin/settings/performance Caching mode： Disabled

\*maybe with caching disabled the page needs to reload each time - it didn't work

Minimum cache lifetime：

\*changed to 1min - it didn't work

2. installed (seemingly perfectly suited to my purpose) module: Cache Exclude 6.x-2.2 https://drupal.org/project/cacheexclude

\*this didn't seem to have any effect either

---

The SQL scripts are run from a tpl file for the page, there are many scripts which might be the problem, and it could definitely be done more efficiently. But previously I've been using scripts on the page successfully, its just the new ones that don't seem to work after an edit to the record/page

Here is the TPL - modified from the garland theme (not the full tpl):

```
<?php
drupal_add_css($directory .'/node-fixing.css');
//delta no match reordering
 db_set_active($db_name);
$qry = "drop table if exists deltanomatch;";

db_query($qry);
$qry = "create table deltanomatch as (

SELECT distinct content_field_itemnum.vid, content_field_itemnum.nid, content_field_itemnum.field_itemnum_value - 1 as delta, content_field_itemnum.field_itemnum_value, field_item_value,  field_remarks_value, field_trepair_value, field_tretail_value
FROM content_field_itemnum
left join content_field_item on content_field_itemnum.nid=content_field_item.nid and content_field_itemnum.delta=content_field_item.delta
left join content_field_remarks on content_field_itemnum.nid=content_field_remarks.nid and content_field_remarks.delta=content_field_item.delta
left join content_field_trepair on content_field_itemnum.nid=content_field_trepair.nid and content_field_remarks.delta=content_field_trepair.delta
left join content_field_tretail on content_field_itemnum.nid=content_field_tretail.nid and content_field_remarks.delta=content_field_tretail.delta
where content_field_itemnum.nid in (SELECT distinct nid
FROM content_field_itemnum
where (delta + 1)  != field_itemnum_value) and field_item_value is not null
order by nid desc, field_itemnum_value asc);";

db_query($qry);
$qry = "delete FROM content_field_item
where nid in (select nid from deltanomatch);";

db_query($qry);
$qry = "delete FROM content_field_itemnum
where nid in (select nid from deltanomatch);";

db_query($qry);
$qry = "delete FROM content_field_remarks
where nid in (select nid from deltanomatch);";

db_query($qry);
$qry = "delete FROM content_field_trepair
where nid in (select nid from deltanomatch);";

db_query($qry);
$qry = "delete FROM content_field_tretail
where nid in (select nid from deltanomatch);";

db_query($qry);
$qry = "insert into content_field_item
select vid, nid, delta, field_item_value from deltanomatch;";

db_query($qry);
$qry = "insert into content_field_itemnum
select vid, nid, delta, field_itemnum_value from deltanomatch;";

db_query($qry);
$qry = "insert into content_field_remarks
select vid, nid, delta, field_remarks_value from deltanomatch;";

db_query($qry);
$qry = "insert into content_field_trepair
select vid, nid, delta, field_trepair_value from deltanomatch;";

db_query($qry);
$qry = "insert into content_field_tretail
select vid, nid, delta, field_tretail_value from deltanomatch;";

```

# Answer
Never put logic in `.tpl` files, unless it's purely "display logic". Move your logic to `hook_field_attach_submit()` or use Computed Field if you want to reliably update field values. Or find any other way, as long as you keep business logic out of your themes.
> 2 votes

---
Tags: caching
---


title: white page in taxonomy terms url

text:
# Question
Title: white page in taxonomy terms url
I am using drupal 7, when I am going to path of terms I see only white page, no error and nothing in another page I have not this problem, some php properties are :

```
error_reporting = E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED & ~E_WARNING
max_execution_time = 360
max_input_time = 120
memory_limit = 32M
upload_max_filesize = 32M
post_max_size = 32M
mbstring.func_overload = 2
mbstring.internal_encoding = UTF-8

```

where is the problem? and how can I solve it?

# Answer
One thing to do when you get the WSOD is to turn on all error reporting to see what led up to the failure to produce output. The `error_reporting` setting you show is turning of a lot of reporting.

You'll get more runtime error reporting by adding this to the start of `settings.php` on your site (you add it just below `<?php`):

```
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

```

In addition, navigate to: Administration→ Configuration→ Development → logging and errors and select All messages. This sets `$conf['error_level'] = 2;`.

Also, check the logs (in particular most recent log messages).

If I should try to guess, I would say you're out of memory. Having a 32M `memory_limit` when running Drupal 7 does sound like a source for trouble (I've no Drupal 7 site with less than 128M).
> 2 votes

---
Tags: 7, taxonomy-terms, uri, wsod
---


title: Form submition don't work

text:
# Question
Title: Form submition don't work
I will build a form for register new team on drupal 7 website.

In my custom module i use this code :

tournament.module :

```
function tournament_menu() {
    $items['tournament/newteam'] = array(
        'title' => 'Créer une nouvelle équipe',
        'page callback' => 'form_newteam',
        'access callback' => TRUE,
        'file' => 'form_tournament.inc',
    );
}

```

form\_tournament.inc :

```
function form_newteam ($form, &$form_state) {
    $form['description'] = array(
        '#type' => 'item',
        '#title' => 'Créer une nouvelle équipe'
    );

    $form['name'] = array(
        '#type' => 'fieldset',
        '#title' => t('Name'),
        '#collapsible' => TRUE,
        '#collapsed' => FALSE,
    );
    $form['name']['name_team'] = array(
        '#type' => 'textfield',
        '#title' => 'Nom de l\'équipe',
        '#required' => TRUE,
        '#description' => "Entrez le nom de votre équipe.",
        '#size' => 20,
        '#maxlength' => 25,
    );
    $form['name']['tag_team'] = array(
        '#type' => 'textfield',
        '#title' => 'Tag de l\'équipe',
        '#required' => TRUE,
        '#description' => "Entrez le tag de votre équipe (version courte du nom de votre     équipe ex : 'FrR').",
        '#size' => 4,
        '#maxlength' => 4,
    );

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

    $form['contact'] = array(
        '#type' => 'fieldset',
        '#title' => t('Contact'),
        '#collapsible' => TRUE,
        '#collapsed' => FALSE,
    );
    $form['contact']['contact_email_team'] = array(
        '#type' => 'textfield',
        '#title' => 'Email de contact de l\'équipe',
        '#required' => TRUE,
        '#description' => "Entrez l'email de contact de la team.",
        '#size' => 20,
    );
    $form['contact']['contact_name_team'] = array(
        '#type' => 'textfield',
        '#title' => 'Nom du contact',
        '#required' => TRUE,
        '#description' => "Entrez le nom du contact de l'équipe.",
        '#size' => 20,
        '#maxlength' => 64,
   );

    [...]

    return $form;
}

function form_newteam_validate($form, &$form_state) {
    $syntaxe_email = '#^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,6}$#';

    if (!preg_match($syntaxe_email, $email)) {
        form_set_error('contact_email_team', "Entrez une adresse email valide !");
    }
}

function form_newteam_submit($form, &$form_state) {

    drupal_set_message('OK : team : @team, tag : @tag, email : @email, contact : @contact, site_web : @site, logo : @filename. ',
        array(
            '@team' => $form_state['name']['name_team'],
            '@tag' => $form_state['name']['tag_team'],
            '@email' => $form_state['contact']['contact_email_team'],
        )
    );
}

```

This form appears correctly, but when i submit it, nothing is happening...

Any idea ?

Thank !

# Answer
> 2 votes
drupal\_get\_form has to be called to render a correct form.

Alter the hook\_menu definition to this:

```
function tournament_menu() {
    $items['tournament/newteam'] = array(
        'title' => t('Créer une nouvelle équipe'),
        'page callback' => 'drupal_get_form',
        'page arguments' => array('form_newteam')
        'access callback' => TRUE,
        'file' => 'form_tournament.inc',
    );
}

```

---
Tags: 7, forms
---


# Question
Title: adding extra tab to user's profile using hook
I am trying to add a `Send email` tab to all user's profile using hook\_menu(). However, it's not working. My custom module name is `page_callback_test` and here's the code in it.

```
function page_callback_test_menu() {
$items['/user/%user/email_user'] = array(
    'title' => t('Send email'),
    'page callback' => '_send_email_touser',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_LOCAL_TASK,
    );

return $items;

```

}

```
function _send_email_touser(){
    return t("let's send email to this user");
}

```

# Answer
> 1 votes
Your code works - just remove the first forward-slash from the URL you are passing to `hook_menu()`.

Correct: `$items['user/%user/email_user'] = array(`
Not correct: `$items['/user/%user/email_user'] = array(`

Be sure to clean cache after you update this.

---
Tags: routes
---


# Question
Title: How can I center a logo image in an Omega theme?
I'm using Omega (a subtheme obviously) and am having trouble centering my logo image. I tried adding a `.logo-img` CSS class to my global.css file but it isn't doing anything. I added the following, but results are weird:

```
margin-left: auto;
margin-right: auto;
border: 4px solid;

```

I added the border to see the image field because when I save these settings, the image stays on the left, but the border extends all the way to the right.

So those settings end up in the logo image resulting like this: https://i.stack.imgur.com/eMIsW.jpg (sorry I can't post images)

If I comment out the margin lines in the css file, the image stays the same.

I honestly don't know how to fix this. Is there a way to do this within my theme's settings? I can't find anything online or in the documentation.

# Answer
> 1 votes
By default the Omega theme CSS floats the image within branding left. You'll have to set it to float none.

# Answer
> 0 votes
You have to check the region your logo is in. normally it comes in the branding region.

You have to set the position of region from the theme settings. you can set your region to appear in center. For that you have to change prefix columns in the branding region configuration.

For more info on weight, position, columns of regions : https://drupal.org/node/1416128

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


# Question
Title: update user's profile field from another form
Here is what I need to achieve:

1. There is field "linkedIn url" in user's profile entity.
2. There is **Event registration** form on the website.
3. In the Event Registration form I would like to render field "linkedIn url" with value from the user's profile entity.
4. When user submits the Event Registration I want to save a value of the field to the database (to user profile entity of course).

Any suggestions? thx!

---

EDIT: I implemented this functionality. For those interested, complete source code is below: (Note that I'm saving data to profile2!)

```
/**
*
* Implements hook_form_alter
*
*/
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
    global $user;
    if ($form_id == 'registration_form') {
            $profile = profile2_load_by_user($user->uid); // Load profile2 data
            if ($profile['main']->field_linkedin_url) {
                $linkedin_url = $profile['main']->field_linkedin_url['und'][0]['value'];
            }
            $form['linkedin_url'] = array( // Add field to form
                '#type' => 'textfield',
                '#title' => t('Your LinkedIn profile'),
                '#default_value' => isset($linkedin_url) ? $linkedin_url : '',
                '#maxlength' => 255,
                '#size' => 60,
                '#description' => t('Please enter your LinkedIn profile URL'),
                '#weight' => 10,
            );
            $form['#submit'][] = 'entity_registration_custom_registration_form_submit'; // Call custom submit handler

    }
}

/**
*
* Custom Form Submit Handler
*
*/
function  MYMODULE_MYFORM_submit($form, &$form_state){
    global $user;
    $profile = profile2_load_by_user($user->uid); // Load profile2 data
    $profile['main']->field_linkedin_url['und'][0]['value'] =  $form_state['values']['linkedin_url']; // Set new value for Profile2 field
    profile2_save($profile['main']);
    drupal_set_message(t('Submit handler works!'));
}

```

# Answer
> 1 votes
You have to modify your form in a hook\_form\_alter : and the linked\_in url will appear in the event registration form

```
function mymodule_form_alter(&$form, &$form_state, $form_id){
   if ($form_id == 'eventregistration_node_form'){

      // Find the user obj
      global $user;
      // Load all profile fields
      $account = user_load($user->uid);
      // Add the linked_in url in the event registration form
      // Supposing your field madhine name is ; linkedin_url
      // Supposing you use the link module for this field (if not, change ['url'] to ['value']
      $form['linkedin_url']['und'][0]['url']['#default_value'] = $user->linkedin_url['und'][0]['url'];
   }
}

```

If you don't want to expose the linked\_in field during the form do this :

```
function mymodule_form_alter(&$form, &$form_state, $form_id){
   if ($form_id == 'eventregistration_node_form'){
     // Hide your field
     $form['linkedin_url'][und]['#access']  = false;
     //Add another submit function
      $form['actions']['submit']['#validate'][] = 'mymodule_eventregistration_validate_form_alter';
   }
}

// Your submit function
function mymodule_eventregistration_validate_form_alter($form, $form_alter){

     // Find the user obj
      global $user;
      // Load all profile fields
      $account = user_load($user->uid);
      // Add the linked_in url in the event registration form
      // Supposing your field madhine name is ; linkedin_url
      // Supposing you use the link module for this field (if not, change ['url'] to ['value']
      $linkedin_url = $user->linkedin_url['und'][0]['url'];

    form_set_value($form['linkedin_url'], array('und' => array(0 => array('url' => $linkedin_url))), $form_state);
}

```

---
Tags: forms, users
---


# Question
Title: Custom module to delete webform entries working but receiving notices and warnings
I have a little webform to collect email addresses for a newsletter (not handled by my website) with a user language preference and an option to either "subscribe" or "unsubscribe" the email that's being submitted. I want to delete all submissions for a given email if it is submitted with the "unsubscribe" option. So I wrote a module using some webform APIs to do that. It works and deletes the already submitted entries of the webform with an "unsubscribed" email. However I keep receiving these errors:

> Notice: Trying to get property of non-object in \_webform\_filter\_values() (line 2946 in /home/test/public\_html/sites/all/modules/webform/webform.module).
>
> Notice: Trying to get property of non-object in \_webform\_filter\_values() (line 2952 in /home/test/public\_html/sites/all/modules/webform/webform.module).
>
> Warning: Invalid argument supplied for foreach() in \_webform\_filter\_values() (line 2952 in /home/test/public\_html/sites/all/modules/webform/webform.module).
>
> Notice: Trying to get property of non-object in \_webform\_filter\_values() (line 2975 in /home/test/public\_html/sites/all/modules/webform/webform.module).
>
> Warning: array\_diff\_key(): Argument #2 is not an array in \_webform\_filter\_values() (line 2975 in /home/test/public\_html/sites/all/modules/webform/webform.module).
>
> Warning: Invalid argument supplied for foreach() in \_webform\_filter\_values() (line 2976 in /home/test/public\_html/sites/all/modules/webform/webform.module).
>
> Notice: Trying to get property of non-object in \_webform\_filter\_values() (line 2984 in /home/test/public\_html/sites/all/modules/webform/webform.module).

This is my module's code:

```
function unsubscriber_webform_submission_insert($node, $submission) {
    if ($node->nid == 49) {
        // Find the keys of the components
        foreach ($node->webform['components'] as $key => $value) {
            if ($value['form_key'] == 'email') {
                $email_key = $key;
            }
            if ($value['form_key'] == 'opzione') { // this is the unsubscribe option
                $opzione_key = $key;
            }
        }
        // Get the submitted email
        $usermail = $submission->data[$email_key]['value'][0];

        if ($submission->data[$opzione_key]['value'][0] == 'unsubscribe') {

            $submissions = webform_get_submissions($node->nid);

            foreach ($submissions as $sub) {
                if ($sub->data[$email_key]['value'][0] == $usermail) {
                    webform_submission_delete($node, $sub);
                }
            }
        }

    }
}

```

I'd like some advice about what could be wrong.

# Answer
You shouldn't have to resort to hacking webform module. Instead, adjust the `hook_webform_submission_insert()` implementation so that you're only deleting submissions where `$opzione_key == "subscribe"`. That means you won't have to worry about deleting the current submission. If you need to clean out "unsubscribe" submissions too, write a `hook_cron()` implementation to do that.
> 1 votes

---
Tags: webforms
---


# Question
Title: Mini pager work with ajax but not full pager?
I don't know if someone has ever expected this error but i can't find "why" it's not working.

In the same page, i have 2 blocks. Each block represent a different view.

The first have mini pager, the second, full pager.

Mini pager is working well, full pager reload the page each time (Yes, i have Use AJAX to Yes).

The only differences i can see are into the HTML (The mini pager UL have class "pager" and the LI have class "pager-prev" and "pager-next"). In the full pager, UL have no class and LI have classes "next" and "prev".

Full pager is suppose to use ajax?

Thanks for your help folks!

# Answer
> 1 votes
This sounds like a theme issue, try switching to Bartik and seeing if the issue is resolved. For example Omega provides its own theme() function for full and mini pagers.

The class pager is required on the UL element for pager AJAX to work properly. Review your theme and make sure it is properly theming the full pager, or open an issue on the Drupal.org project page.

# Answer
> 0 votes
If you're having issues with multiple Views pagers on the same page, try adjusting the "Pager ID" ( e.g "1" ) in the View pager settings:

---
Tags: ajax, paging
---


# Question
Title: Entity reference to user doesn't work without 'administer users' permission
**EDIT:** I have most probably found out the reason thy it works (or doesn't work actually) this way. The problem is that I don't have legitimate access to the user node that is being edited. I only 'hacked' the menu system so it let me through but don't really have the real access. Unfortunately I have no idea how to resolve this problem...

I have reworked the system that handles permission to user edit pages so that it allowed editing certain users even without the 'administer users' permission.

The system itself works well, the only problems are entity reference fields on the user. To be more specific, there are two entity reference fields attached to user bundle -\> one that references another user 'supervisor' and another that references certain content type.

The problem with these two fields is that the autocomplete feature (I use autocomplete widgets) in the widgets not only doesn't work but even throws a 'access denied' error (in AJAX response).

It works well when current user has the 'administer users' permission but I can't give every user this permission.

BTW: To make it perfectly clear, not even the field that references a normal content type (node) works so the problem can't be in access to user entities as the answer below suggests.

I have tried to look into the entity reference code but have not found anything that would explain this strange behaviour (there's literally zero calling of user\_access that might lead to this kind of behaviour).

# Answer
Ok, I've found where the problem was. There's an entity\_access call in the entityreference module that caused the access denied error.

```
function entityreference_autocomplete_callback_get_matches($type, $field, $instance, $entity_type, $entity_id = '', $string = '') {
          $matches = array();

          $entity = NULL;
          if ($entity_id !== 'NULL') {
            $entity = entity_load_single($entity_type, $entity_id);
            if (!$entity || !entity_access('view', $entity_type, $entity)) {
              return MENU_ACCESS_DENIED;
            }
          }
        ...
}

```

The entity access then called entity\_metadata\_user\_access which implements traditional way of handling user access.

To solve this problem I just altered the entity\_info, more specifically the access\_callback function of user entity.
> 0 votes

# Answer
You could try creating an entityreference display in views which, with the 'access' options defined in views, handle user access however you please.

Here is an example view display to get you started: https://gist.github.com/acao/7297342

Just configure the field settings to use this view instead of the default handler, and see if that gets you around your problem!
> 0 votes

---
Tags: 7, entities, ajax, users
---


# Question
Title: Passing a contextual filter value to a view via a link with entityreference prepopulate?
I have two content types, **Ad** and **Reply** (think of how posting works on Craigslist for the **Ad**, and the **Reply** is an on-site form to reply). I am using Entity Reference Prepopulate to automatically create an entity reference back to the **Ad** when users click a link to make a **Reply**. The link looks like this:

> node/add/reply?field\_reply\_orig\_node=NID

Where NID is the node ID (filled in with a token using Panels).

Using Panels, I'd like to display the original **Ad** on the **Reply** edit page (to make it easier for users to write their message. I have overriden the node edit page (using Page Manager) and I added a view that has a contextual filter (NID). However, I don't understand how to pass a value for NID to the content pane using the reply link.

Ideally, I could make use of the `?field_reply_orig_node=NID` that is already present in the link (how?), but if that is not possible, I could rewrite the link in Panels. I just don't understand how to rewrite it so that the contextual filter can pick up the value.

# Answer
One solution would be to add a custom panel to a panel page overriding the node edit form.

To do so you'll want to go into Panels Page Manager (/admin/structure/pages) and enable node\_edit adding a variant that uses context to evaluate Node: type where Node being viewed is type "Your Content Type"

Then go into the panel page content section and choose "New Custom Content" from the panel selection dialog.

In the dialog that opens, makes sure to choose and input format that allows hyperlinks.

Make sure "Use context keywords" is checked and in the substitution choices you'll see %node:nid

You can use this to build the url:

`<a href="/node/add/reply?field_reply_orig_node=%node:nid" title="Add Reply>Reply</a>`
> 1 votes

---
Tags: views, uri, entities
---


title: plupload submit routine is not called

text:
# Question
Title: plupload submit routine is not called
I'm having a problem with the plupload module. The normal upload works perfect, the files are stored in sites\default\files\tmp. I'd like to "walk" through the uploaded files using the hook\_submit. It seems, this hook is not called, when pressing start upload on the plupload form. I'm using almost the same hook\_submit as the test form in the plupload.module.

What am I doing wrong?

Here is my form definition:

```
 $form['my_element'] = array(
'#type' => 'plupload',
'#title' => t('Upload files'),
'#description' => t('This multi-upload widget uses Plupload library.'),
'#upload_validators' => array(
  'file_validate_extensions' => array('jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp'),
  'my_custom_file_validator' => array('some validation criteria'),
),
'#plupload_settings' => array(
  'runtimes' => 'flash,html4',
  'url' => url('plupload-handle-uploads', array('query' => array('plupload_token' => drupal_get_token('plupload-handle-uploads')))),
  'max_file_size' => file_upload_max_size() . 'b',
  'chunk_size' => '1mb',
  'unique_names' => TRUE,
  'flash_swf_url' => file_create_url('sites/all/libraries/plupload/js/plupload.flash.swf'),
  'silverlight_xap_url' => file_create_url('sites/all/libraries/plupload/js/plupload.silverlight.xap')
),
);

```

Here is the submit function:

```
function get_upload_form_submit($form_id, &$form_state) {
//handle file uploading
global $user;

$saved_files = array(); //Array to capture file objects
$scheme = variable_get('file_default_scheme', 'public') . '://';
$directoryname = 'imagebank'; // Directory where images are collected
$imagebankpath = $scheme . $directoryname;
dpm($imagebankpath);
file_prepare_directory($imagebankpath, FILE_CREATE_DIRECTORY); // Create the folder if   it doesn't exist
// We can't use file_save_upload() because of
// http://www.jacobsingh.name/content/tight-coupling-no-not
// file_uri_to_object();
foreach ($form_state['values']['uploadfiles'] as $uploaded_file) {
if ($uploaded_file['status'] == 'done') {
  $source = $uploaded_file['tmppath'];
  $destination = file_stream_wrapper_uri_normalize($imagebankpath .'/'. $uploaded_file['name']);
  // Rename it to its original name, and put it in its final home.
  // Note - not using file_move here because if we call file_get_mime
  // (in file_uri_to_object) while it has a .tmp extension, it horks.
  $destination = file_unmanaged_move($source, $destination, FILE_EXISTS_RENAME);
  $file = plupload_file_uri_to_object($destination);
  file_save($file);
  $saved_files[] = $file;
}
else {
  form_set_error('uploadfiles', "Upload of {$uploaded_file['name']} failed");
}
}
}

```

Did I forgot anything? Thx.

# Answer
> 1 votes
The `submit` handler is not executed when clicking on the `start upload` of the Plupload widget form, this only executes the ajax upload of the files (and the file validators).

To have a submit callback, and handle the logic of the uploaded files (i.e.: move files to a certain directory), you should add a button to the form.

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

```

The uploaded files are stored in the form\_state under `$form_state['values']['my_element']` (the name of your Plupload form field)

**Update #1**

Some sample code to trigger the form `submit` callback once the upload of the files is finished by the Plupload uploader. Basically what you need:

1. A submit button attached to the form to have a submit callback (which handles the uploaded files)
2. A custom javascript which intercepts the `UploadComplete` event triggered by the Plupload component
3. On the `UploadComplete` interception, trigger a `click` on the submit button

```
function YOURMODULE_form($form, &$form_state)
{
    // your form elements with plupload form element

    // add a submit button
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Save file(s)'),
        '#submit' => array('YOURMODULE_form_submit'),
        '#attributes' => array(
            'class' => array('file-upload-submit'),
        ),
    );

    // attach the custom js to the form
    $form['#attached'] = array(
        'js' => array(
            drupal_get_path('module', 'YOURMODULE') . '/js/YOURMODULE.js',
        ),
    );

    return $form
}

function YOURMODULE_form_submit($form, &$form_state)
{
    // put uploaded files in a 'uploads' directory
    $directory = sprintf('%s://%s',
        variable_get('file_default_scheme', 'public'), 'uploads');

    // be sure directory exists (and create it)
    file_prepare_directory($directory, FILE_CREATE_DIRECTORY);

    // loop through each uploaded file
    $saved_files = array();
    foreach ($form_state['values']['files'] as $file) {
        if ($file['status'] !== 'done') {
            //handle error on upload fail
            continue;
        }

        // move files from tmp directory to defined directory
        $destination = file_unmanaged_move(
            $file['tmppath'],
            file_stream_wrapper_uri_normalize($directory . '/' . $file['name']),
            FILE_EXISTS_RENAME
        );

        $saved_file = plupload_file_uri_to_object($destination);
        file_save($saved_file);

        $saved_files[] = $saved_file;
    }

    // keep saved files in form state to be able to stuff afterwards (if needed)
    $form_state['saved_files'] = $saved_files;

    drupal_set_message(t('Files have been uploaded and saved.'));
}

```

The javascript (under js/YOURMODULE.js)

```
(function ($) {
    Drupal.behaviors.YOURMODULE = {
        context: null,
        attach: function (context) {
            var that = this,
                uploader = $('.plupload-element', context).pluploadQueue();

            this.context = context;

            if (!uploader) {
                return false;
            }

            uploader.bind('FilesAdded', function() {
                // start upload automatically once files have been added to queue
                that.start();
            });

            uploader.bind('UploadComplete', function() {
                // trigger click on submit button to submit form once upload completed
                that.complete();
            });

            return this;
        },
        start: function() {
            $('.file-upload-submit', this.context)
                .attr('disabled', 'disabled');
        },
        complete: function() {
            $('.file-upload-submit', this.context)
                .removeAttr('disabled')
                .click();
        }
    };

})(jQuery);

```

---
Tags: forms
---


title: Exclude /ru/ in links

text:
# Question
Title: Exclude /ru/ in links
I have site http://diamant-group.com/. It has two languages RU and EN, I want that it will monolingual, with Russian default language. I turn off EN language in Configuration, turn on RU as default, but problem is still exist http://diamant-group.com/ru/catalog. When I begin to research I have opened that many code for multilingual function was added inside theme template. When I turn off module Content translate i have error of function diamant\_link\_lang.

How to correct this code, that links do not consist /ru/ (for example site/ru/catalog/watches/mechanical/omega/ - \> site/catalog/watches/mechanical/omega/), but language of the result pages must be Russian:

```
function diamant_link_lang($language, $path, $path_alt) {
    $path_lang = translation_path_get_translations($path_alt[0] . '/' . $path_alt[1], $language);
    file_put_contents(DRUPAL_ROOT . '/sites/default/files/text.txt', 'path_lang: ' . print_r($path_lang, true) . "\n");
    if ($language == 'ru' && isset($path_lang['en']))
 {
        return 'en/' . drupal_get_path_alias($path_lang['en'], 'en');
    }
    if ($language == 'en' && isset($path_lang['ru'])) {
        return drupal_get_path_alias($path_lang['ru'], 'ru');
    }
    return $language == 'ru' ? 'en' : 'ru';
}

```

# Answer
> 0 votes
You can change the way the language is added to the url. For the Russian language (your default language), you can remove it completely from the url by setting the `path prefix` to empty value.

This can be done under `admin/config/regional/language/edit/ru`, set empty value on `Path prefix language code`.

Theoretically you don't need to have custom code the generate URL (with language checks), just let Drupal handle the url generation.

---
Tags: theming
---


# Question
Title: Rearranging subfields with the Address Field module
Is there a way to rearrange the fields within the widget with a specific hook? Should I use `hook_form_alter()`?

To be more specific, I want to put the country field below the zip-code field when using the Address Field module.

# Answer
> 10 votes
I have two solutions for it:

1. hook\_field\_widget\_form\_alter()
2. Ctools plugin

**Solution 1. hook\_field\_widget\_form\_alter().**

```
/**
 * Implements hook_field_widget_form_alter().
 */
function MYMODULE_field_widget_form_alter(&$element, $form_state, $context) {
  if(!empty($element['#addressfield'])) {
    $element['country']['#weight'] = 100;
  }
}

```

Use `$element` and `$context` arrays and implement own `IF` statement. You can find all the information about the field and user here.

**Solution 2. Ctools plugin**

It's possible with ctools plugins. Review `addressfield/plugins/format/` or https://drupal.org/project/addressfield\_vn as an example.

Just add your custom plugin with addressfield alter in 5 steps:

Step 1: Create `MYMODULE/plugins/format/` folders structure.

Step 2: Add next code to your `MYMODULE.module` file:

```
/**
 * Implements hook_ctools_plugin_directory().
 */
function MYMODULE_ctools_plugin_directory($module, $plugin) {
  if ($module == 'addressfield') {
    return 'plugins/' . $plugin;
  }
}

/**
 * Implements hook_ctools_plugin_type().
 */
function MYMODULE_ctools_plugin_type() {
  $plugins['format'] = array(
    'load themes' => TRUE,
  );
  return $plugins;
}

```

Step 3: Add file with alter code. E.g.: `MYMODULE/plugins/format/address-alter.inc`:

```
/**
 * @file
 * Move country field to the very end.
 */

$plugin = array(
  'title' => t('Alter addressfield'),
  'format callback' => 'MYMODULE_format_address_alter_country',
  'type' => 'address',
  'weight' => -80,
);

/**
 * Format callback.
 *
 * @see CALLBACK_addressfield_format_callback()
 */
function MYMODULE_format_address_alter_country(&$format, $address, $context = array()) {
  // Move country field to the very end.
  $format['country']['#weight'] = 100;
}

```

Step 4: `drush cc all`

Step 5: Enable your plugin for addressfield in customer profile fields settings. E.g. at `/admin/commerce/customer-profiles/types/billing/fields/commerce_customer_address`

In the current example all the alter code will be inside the `MYMODULE_format_address_alter_country()` function. Just play with weights of your fields and you'll get the form rearranged.

# Answer
> 2 votes
It makes sense to keep the country field in the first place, as the other fields change depending on the selected country.

---
Tags: entities
---