# Question
Title: Getting data out of Profile2 with field_get_items()
I am trying to access my profile2 fields in template.php. I get profiledata, but I also get an error message:

> EntityMalformedException: Missing type profile2. in entity\_extract\_ids() (row 7663 of /includes/common.inc).

Should not the entity type in `field_get_items()` be `'profile2'`, or is it another value?

```
$profiledata = profile2_load_by_user($variables['comment']->uid);
$lastname = field_get_items('profile2', $profiledata, 'field_lastname');

```

# Answer
> 4 votes
`profile2_load_by_user()` takes a user account (not just a uid) as its first argument, so you'll need to use:

```
$account = user_load($variables['comment']->uid);
$profiledata = profile2_load_by_user($account);
$lastname = field_get_items('profile2',$profiledata,'field_lastname');

```

# Answer
> 5 votes
As @Clive mentioned `profile2_load_by_user()` takes user account object not uid, but you also need type name as second argument to retrieve `field_lastname` using `field_get_items` function.

I recommend you to use this function `profile2_by_uid_load` instead of `profile2_load_by_user`

So your code should look like the following:

```
$profiledata = profile2_by_uid_load($variables['comment']->uid, 'profile_type_name');

$lastname = '';

if($profiledata) {

  $lastname  = field_get_items('profile2', $profiledata, 'field_lastname');
}

```

---
Tags: users
---


# Question
Title: How to make sure you're not on the production website in Drupal 7?
I remember seeing some kind of module where it lets you know that your on a staging / dev site without the risk of you editing the main production site. Or is there other methods that others use to prevent accidents from happening.

# Answer
> 3 votes
Environment Indicator is designed to do that:

> This module will help you to keep sane while working on your different environments by adding a configurable color bar to each one of your environments. The Environment Indicator adds a coloured bar on the site informing you which environment you're currently in (Development, Staging, Production, etc.). This is incredibly useful if you have multiple environments for each of your sites, and like me, are prone to forgetting which version of the site you are currently looking at.

---
Tags: staging
---


# Question
Title: How to replace internal links with a view (similar like the Open Graph feature)?
I would like to have the feature, that if users on my site post internal links within a text, this links are replaced by a thumbnail, node title etc. For choosing what to show instead of the link I would like to use Views. What would be the best method to do so?

* I think, a simple replacement with hook\_node\_submit() or something, is not a good solution: If the user edits his content, I want him to see only what he added himself.
* I could do it within the template, but this is not very elegant, I guess.
* What is about hook\_url\_outbound\_alter(), would that be the best way?

Please give me a hint.

# Answer
The correct way to do this is to write text filter and add it to input formats your users will be using. Here you have Basic description of filters and formats \- for Drupal 5 and 6, but concept is still valid. They are applied on display - Drupal agrees with you that you should save just what user wrote.

You need to use hook\_filter\_info(). Read about it, and then about rest of filter hooks family and you will have an idea.

To provide proper content for filter, well, there is no definitive solution. If users will only input node id, simple node\_load is enough. Every set of scenarios and every use case calls for it own methods. Views are elastic tools, I guess for pretty big part of use cases they can be the tool.
> 4 votes

---
Tags: views, theming, navigation
---


# Question
Title: Use drush to sync core &/or modules directory only
I've just discovered the wonderful world of drush aliases, and I'd like to use drush to keep a dev site in sync with the live site (and visa versa). So far I've figured out that the following command does it pretty well for a site in the `sites/` folder:

```
drush rsync @mysite.com.live @mysite.com.dev

```

I'd like to be able to sync modules and core the same way. Is there a way to do that with drush?

# Answer
> 4 votes
To sync contrib:

```
drush rsync @mysite.com.live:%modules @mysite.com.dev:%modules

```

%modules will be rewritten to sites/all/modules.

Drush does not have a path alias for the core modules folder, but you could do this:

```
[REDACTED]

```

The answer I gave before only sync'ed the core modules folder; what you really want is all of core, minus any sites or contrib modules. To do that, use the following rsync command:

```
drush rsync @mysite.com.live @mysite.com.dev --exclude="sites/*"

```

To sync core and contrib together:

```
drush rsync @mysite.com.live @mysite.com.dev --include="sites/all" --exclude="sites/*"

```

Add '-s' prior to the rsync to run in simulated mode (i.e. `drush -s rsync ...`); if you do this, Drush will print out the rsync command that it would run for those parameters without actually executing it.

**Update:**

Yes, the rsync command shown in the question will sync the entire Drupal root. If you want to sync only the sites folder for one particular Drupal site, you could try this:

```
drush rsync @mysite.com.live:%site @mysite.com.dev:%site

```

At this point, you might be tempted to chain together all of the commands shown above, and drop it into a script to sync everything that one site needs to run. If that's your intention, you might want to try the following variant, which rsync's everything *except* the other multisites:

```
drush --exclude-other-sites rsync @mysite.com.live @mysite.com.dev

```

Again, run with -s to see what it's going to do with that command.

---
Tags: drush
---


# Question
Title: How to customize user edit page drupal 7?
I need to change the order in which things are on the user edit page in Drupal 7. I have tried modifying `page-user-edit.tpl.php` and `user-profile-edit.tpl.php`, but it doesn't seem to ever get there. What can I do?

# Answer
It's a little different for Drupal 7... The structure of the file name would be `page--user--edit.tpl.php` (for D7) as opposed to `page-user-edit.tpl.php` (for D6).

Also, remember to clear the cache after you make any such changes so that they're recognized.

Hope that helps... :)
> 7 votes

# Answer
If you just want to change the order of the fields in the user profile as they appear on the user profile edit page in Drupal 7, navigate to "Administration » Configuration » People » Account settings" and then click on the "Manage Fields" tab. You can the use the slider (or row weights) to rearrange the order of the fields.

If you also want to change the order these fields appear in the profile when it is displayed (as opposed to edited), use the "Manage Display" tab.

Remember to save when you're done.
> 4 votes

---
Tags: users
---


# Question
Title: Is it possible to allow duplicate usernames ?
I'm working on a **Community Website** and 99% of the time a new user has an unique username. But for my requirement, it is required to allow duplicate usernames.

Is there a way to change drupal default behavior from unique username+email+pass to unique email+pass?

# Answer
> 5 votes
There is no setting or existing module that will do this for you. I do not think it is a good idea to let two users share the same username, because there is so much in Drupal that depends on usernames being unique, and this will break if you make two usernames identical.

You do not tell us *why* you want to have this feature. However, if you are content with letting users authenticate using their email address (which is guaranteed to be unique), rather than their username, the **Email registration** module may solve your problem.

However, the **Email registration** module does not let the user pick his or her own username, but generates an unique username based upon the email address. I want my users to pick their own username, so I use a variant of **Email registration** that does this. It is named **RealnameReg**. It is a sandbox, but since it is based on **Email registration** it is stable. I am using it myself on several production sites.

# Answer
> 4 votes
Usenames cannot be duplicate. Alternatively you can use Email Registration module if you want login based on email and password.

> Allow users to register and login using only an email address. Users can then log-in using their email address and password for authentication.

Also have a look on LoginToboggan module

> The LoginToboggan module offers several modifications of the Drupal login system in an external module by offering the following features and usability improvements:

# Answer
> 4 votes
I think @GisleHannemyr has a good solution, but I am going to throw out an alternate.

If you look at `user_schema()` you will see that the `name` column on `{users}` is a unique key. So, to have duplicate username, a solution would have to alter the schema and remove this index. While I can't say this for certain, I am pretty sure **Bad Things** would happen if you do this.

My suggestion would be to work within the unique username requirement, but field out the user entity (admin/config/people/accounts/fields) and add a screen name. Then you can implement `hook_username_alter()` to use this field instead of `$account->name`.

# Answer
> 3 votes
Username needs to be unique - Drupal needs to know who to log in. Having that said, you can separate login user name from display user name. Simply add non-unique "display name" text field, and in templates use it instead of built-in username.

# Answer
> 1 votes
I think ultimately what you want is the Email Registration module, as mentioned in several of the other answers. However, you can allow users to create their own display names by using the Real Name module. This will allow several users to choose the same screenname to be displayed throughout the site. The actual username will be automatically generated by the Email Registration module, but never displayed (this module will also ensure that the underlying usernames are unique). The Real Name module will handle displaying the user's chosen screenname (which can be anything the user chooses).

After installing and enabling both modules, you'll need to add a "Username" text field to the user accounts (on the page `admin/config/people/accounts/fields`). Then use the token for that field in the Real Name configuration (page `admin/config/people/realname`). The token will look something like `[user:field-username]` (the token browser should help you find the correct token).

---
Tags: users
---


title: How do I override superfish styles?

text:
# Question
Title: How do I override superfish styles?
Do I copy the css files I want to override to a theme I am using?

# Answer
> 3 votes
This depends the implementation. If the super-fish functionality is already included in a theme (Example: Danland, Danblog), there is most probably already a .css section in the style sheet or a separate .css file related to superfish. If you modify these files, they might be overwritten if you make an update. Thus you optimally make the modification in a local file (local.css in our Example) by copying and modifying the css code.

If you install superfish separately you find all the instructions in the readme.txt of the module:

"How to style

If you know CSS, even basics of it, designing won't be a big challenge.

Here are some tips and tricks:

A) Always use a DOM inspector utility (such as Firebug).

B) Set the "Menu delay" option to a very high number such as 99999999. This will give you enough time to work with sub-menus.

C) If you are not using the built-in styles, set the "Style" option to "None".

D) Utilise the "Simple" style as reference; add the newly-created CSS file either to your theme CSS or as a new CSS file under the styles directory in the Superfish library (probably "sites/all/libraries/superfish/style"); putting it in the styles folder will automatically add it to the styles list in the block configuration."

More information can be found in the Superfish documentation at http://drupal.org/node/1125896"

i.p. 4. within the Installation section

"Upgrade users need to delete the module folder (sites/all/modules/superfish) before uploading the new one. Also, if having any modified CSS files, just move them from sites/all/modules/superfish/css/extra to sites/all/libraries/superfish/style"

---
Tags: theming, navigation
---


# Question
Title: Views: Create a block with terms marked (reference field) by the term viewing
I am having two vocabularies, for example, styles and artists. Each of the artists term has a term reference field to styles voc.

When one of the styles term page is open i want to show all terms from artists vocabulary marked with this term.

Can't figure out why my contextual filter with term id doesn't work. Could you please help me to achieve it?

# Answer
> 2 votes
2 steps are needed to achieve this with Views:

Relationship:

1. Add a relationship
2. 1st screen on the popup: Choose Taxonomy term: Styles
3. 2nd Screen on the popup: Choose Require this relationship
4. Apply

Contextual Filter:

1. Add a contextual filter
2. 1st screen on the popup: Choose Taxonomy term: Term ID
3. On the Relationship dropdown choose the relationship you configured above
4. Choose When the filter value is not available -\> Provide default value -\> Type dropdown = Taxonomy term ID from URL
5. Apply

And you're done.

# Answer
> 1 votes
If you simply add a block in your page, it won't work, as **blocks don't receive arguments**. There are several ways to bypass that :

* Use Panels and re-build your page in a taxonomy/term/% page
* Use Views URL Path Arguments
* Trick your contextual argument by using custom php code in which you'll search your `tid` by using `current_path()` that should return `taxonomy/term/[%tid]`.

---
Tags: 7, views
---


# Question
Title: What is the proper way to uninstall a module that adds a content type
I heard that when uninstalling a module that is a content type, you should not use `node_type_delete('my_module')` in `hook_uninstall()`. Instead, you should let it be handled by Drupal that just disables the content type in the database. Is this right? Apparently Drupal handles it in `hook_node_info()`.

Wouldn't it be better to delete this node type in the database, or does Drupal handle uninstallation process in an other way?

I am using Drupal 7.

# Answer
> 2 votes
You should not delete content types in hook\_disable(). Instead, you should make sure callbacks are left sane, and all data you will need on hook\_enable() is properly archived and secured from modification by other modules. Good idea is to use drupal\_set\_message() to warn about content type that should no longer be used or displayed, but that's site admin's responsibility.

On hook\_uninstall() you are supposed to left the database as if your module was never there. Thus, feel free to delete content types that was created using node\_type\_save(), if there are any. The ones created with hook\_node\_info() will be deleted automatically. Again, setting message about orphanted content is good idea, but it's site admin's responsibility not to uninstall module he is still using, after all.

If your hook\_node\_info() defined content type is not deleted, just disabled, you can decide to explicitly delete it, but you are responsible for cleaning all the mess it may cause, like orphaned content. You risk serious site failure if you don't.

*Edited to incorporate information from Clive's comments under other answer*

# Answer
> 0 votes
There are two functions which can help you out of this problem with writing `hook_uninstall()`:

1. node\_type\_delete is for deleting the content type
2. node\_delete is for deleting the associated nodes

---
Tags: nodes, installation
---


# Question
Title: How does the Search synonyms module work?
I've just activated the search synonyms module for D7, but I don't get how it works at all. Where do I set synonyms, I've tried editing forms or check the settings, but I can't find any new input where synonyms could be added. Also I could not find any documentation for the module. Probably me overlooking things but some help would be greatly appreciated.

# Answer
Jasper, I had a look at the code in the module. There is only one function in the module, and I don't think the module does what is says in the description on the Drupal project page.
> 3 votes

---
Tags: 7
---


# Question
Title: In Drupal 7, how do I allow users to see their own unpublished content?
This Drupal page says that for Drupal 7 to allow users to view their own unpublished content to check "view own unpublished content" in permissions.

I have this checked, yet when someone clicks on 'admin/content' it says permission denied. Of course I don't want to give them permissions related to admin content.

Currently I have the `override node options` module enabled, and when a user unpublishes their content, they can no longer get back to it to continue editing and then publish it.

I cannot use the 'view unpublished' module as many threads suggest as it gives an entire role access to all unpublished content related to that role.

What I am leaning towards is a view. Currently I have a very good working block that allows people to view their PUBLISHED content while on their profile page. I cloned this and simply switched the filter "published: yes" to "published: no" and it won't work. I tried setting the view permission to view own unpublished content, and it will not work.

Is 'view own unpublished content' broken in D7? Drupal core says I should be able to allow users to view their own unpublished content. How can I do this without all this hakery and dependency on a 3rd party modules?

# Answer
> 3 votes
`view own unpublished content` permission allows just that - to see /node/%nid even if it is unpublished. Test it, I'm sure it will work.

If you want your users to be able to **list** their content, well, that's other topic. Easiest way is to use Views to create listings filtered by authors, with filters like `is_published or author == current_user)`.

---
Tags: 7, nodes
---


# Question
Title: Using different markup for views last item
I need to use different markup for last item displayed by views. Using first last css item does not do the job for me. I assume I would need custom php template probably views-view-fields.tpl.php. What would be the way of doing it?

# Answer
To do this:

* Find template file that adds "last" class
* Override it in your custom theme
* Expand if responsible for "last" class, to make it contain all element's markup
* in if block write markup for last element, in else block - for all other elements.
> 0 votes

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


# Question
Title: determine value differences between form submissions
I have an entity form that user can submit multiple times. What i would like to do is during validation get current values in the database and compare with the once that user just entered. I'm using

`$form['#validate'][] = 'my_function';`.

So really the questions is how do I get 'current values' that are already stored in the database to one array and 'about to be submitted values' (just updated by user) to the other array. The reason why I want those to be saved, temporary only, in the array is to do comparison.

# Answer
> 0 votes
If you're looking for a non-SQL way to get data out of the database the `db_select()` function (which returns an `SelectQuery`) is the way to go. For obvious reasons there's no implicit API implemented for your custom data tables (you'd need to create that yourself).

Without knowing your schema this can't be totally accurate, but the basics are:

```
$query = db_select('my_table', 't')
  ->fields('t', array('field1', 'field2'))
  ->condition('some_column', 'some_value');

$results = $query->execute();
foreach ($results as $result) {
  // $result is an object, use it...
}

```

`SelectQuery` has a bunch of helper methods to get specifically formatted data out of the database, so chances are you won't need to loop over the data. You can find a list of those helper functions (and info on the alternative, SQL based approach that still uses the API) here

---
Tags: 7, forms, entities
---


# Question
Title: how to create the pagination for customized portfolio template
I will create the portfolio gallery page using custom content types with thumbnail and bigimage image fields. then i am using the following code for rendering content types

```
<?php
$content_type = 'websiteportfolio';
$query = new EntityFieldQuery();

$entities = $query->entityCondition('entity_type', 'node')
->entityCondition('bundle', $content_type)
->propertyCondition('status', 1)
->pager(9)
->execute();
$nodes = entity_load('node', array_keys($entities['node']));?>

<?php
  $i = 1;
  foreach($nodes as $val=>$key1)

  {

 ?>

 <div class="thumbnail-box">
<a href=<?='sites/default/files/'. $key1->field_bigimage['und']['0']['filename']; ?> rel="lightbox[portfolio]"  title="<?= 'Portfolio'.$i ?>"><img src=<?='sites/default/files/websiteportfolio/'. $key1->field_images['und']['0']['filename']; ?> alt="<?= 'Portfolio'.$i ?>" /></a>

</div>

 <?php
$i++;
}

 ?>

```

finally i got the 9 thumbnail images in my page and also light box functionality working well.My issue Only show first 9 images I need pagination for showing the remaining images how can fix this issue..

# Answer
> 1 votes
First things first, that code shouldn't be in the template file; it should be in a preprocess function. The reasons for this have been documented at great length both on this site and the internet in general so I won't go into them here.

You might also find the `l()` function interesting, as well as `theme_image()`...API replacements for the custom HTML you're building up.

Other than that, the only thing you're missing is the code to actually render the pager; that would entail adding this to your preprocess function, after the query has been run:

```
$vars['pager'] = theme('pager');

```

And in the template file simply outputting it wherever you'd like it:

```
<?php echo $pager; ?>

```

---
Tags: 7, paging
---


# Question
Title: Display a block when a view doesn't return any result
On node/48, the page is composed from a text and a view. I would like to display a block when the view does not return any result.

How can I achieve this?

# Answer
> 1 votes
After enabling PHP filter module, you could edit the visibility settings of this block and write some PHP there to return TRUE only if this view has NO result, something like:

```
<?php
  $view = views_get_view('foo');
  $view->set_display('your_displays');
  if (!$view->result) {// or another check (empty()..) that will do the job
   return TRUE;
  }
?>

```

or something like that..

# Answer
> 4 votes
You can call your block inside "No results behavior", using a "Global: Text area" and the "PHP" Text format. But you won't be able to display it where you want, it will have to be at the same place as the view.

---
Tags: blocks
---


# Question
Title: Show "Log in" link all the time (even for logged in users)
I have a menu item "My Shop" which redirects to the `user/login` page. But custom Drupal behavior hides this link whenever a user is logged in.
I would like to show this menu-item **all the time**. Is there a way to do so?

The reason why I do this is the following. It's a site with a webshop-portal. To access this portal, users need to log in. Whenever they are on *their portal/webshop*, he should keep seing the menu-link and when they return to the front-end of the site, the user should be able to go his webshop without loggin in again.
I hope I make myself clear on this one. If I don't, please let me know!

# Answer
If you're trying to show a link called "My Shop" which takes anonymous users to the log in page and logged-in users somewhere else, you can just create a second menu item also called "My Shop" and set it to display only for users that have the authenticated user role. Then set the destination to whatever you want; that way both logged in users and anonymous users will have "My Shop" links pointing different places.

You can have multiple menu items on the same menu with the same name (Drupal doesn't check for uniqueness in order to allow for situations like this).

As long as you give the two "My Shop" menu items the same weight (or drag them so that they are next to each other), they will appear to be the same menu item.
> 4 votes

---
Tags: 7, users
---


title: EntityFieldQuery display pager

text:
# Question
Title: EntityFieldQuery display pager
How do I display pager using EntityFieldQuery for fetch results? I can't find complete example.

I am doing simmilar to: Sortable, paged table retrieved using EntityFieldQuery

But I miss part to output simple pagination links (1,2,3... for every next page).

# Answer
I suspect the only thing you're missing is adding the return from `theme('pager')` to the content you're building.

This is a small example that shows teasers for all nodes in the system, with 10 per page. You would use this in a page callback function:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->pager(10);

$results = $query->execute();

$content = node_view_multiple(node_load_multiple(array_keys($results['node'])));

$build = array(
  'content' => $content,
  'pager' => array(
    '#theme' => 'pager',
    '#weight' => 10
  )
);

return $build;

```

More specific based on your comments:

```
if ($type == 21) {
  $query = new EntityFieldQuery();

  $entities = $query->entityCondition('entity_type', 'node')
    ->propertyCondition('type', 'product')
    ->fieldCondition('field_razred', 'tid', array (607,608,609,610), 'IN')
    ->pager(10) // this is the bit you're missing
    ->execute();

  $nodes = node_load_multiple(array_keys($entities['node']));
  print render(node_view_multiple($nodes, 'teaser')) . theme('pager');
}

```
> 8 votes

# Answer
Also been having some trouble with this - debugging statements initializePager showed that the optional $element parameter was being set to 1 rather than 0.

If there is only one pager being displayed, try setting it explicitly to 0. `$query->pager(10, 0);`
> 4 votes

---
Tags: 7, paging, database
---


# Question
Title: How to call a module in a block or give a module a block or put module form into a block?
I have a module, and I would like its add form to be put into a block. So my question is, how would you take a modules page (admin/build/mymodule/add) and give it a block? So this module will now have its own block in the blocks admin page. Do you do this by its url, by module, or by form id?

# Answer
> 2 votes
You can do this with the $form\_id and the function `drupal_get_form();`

You need to create a module and use `hook_block()`:

```
function mysecondmodule_block($op = 'list', $delta = 0, $edit = array()) {
  switch($op) {
    case 'list':
      return array(array('info' => 'mymodule add block'));
    break;
    case 'view':
      if($delta == 0) {
        return array(
         'subject' => 'Mymodule Add',
         'content' => drupal_get_form('form-id');
        );
      }
    break;
  }
}

```

# Answer
> 0 votes
```
function mysecondmodule_block($op='list',$delta=0,$edit=array()){
  switch($op) {
    case 'list':
       return array(array('info'=>'mymodule add block'));
       break;
    case'view';
       if($delta==0){
         return array(
          'subject'=>'Mymodule Add',
          'content'=> drupal_get_form('form-id');
           );
       }

```

---
Tags: 6, blocks
---


# Question
Title: Is making a feature of literally everything available actually a smart thing to do?
I love features for all the benefits they have, especially for performance.

It now seems like a logical step forward to make a feature out of everything available on the "create feature" page on a launch site and enable it (of course so that it doesn't interfere with other features, but you get my point).

Does that seem like a smart idea? I don't see anything problematic with this if I assume I won't change anything on the site for the next couple of days and it's frequented by many visitors.

If you have any best practices to share, I'd be glad as well.

# Answer
## Yes.

Combined with placing your Feature module(s) in version control and carefully reviewing the diffs, this is a good way to keep track of administrative changes to the sites you maintain. I do this on most sites I maintain.

## However:

* If you're using Strongarm, you shouldn't export literally *everything*. Some system variables are caches, and will change frequently; exporting these caches to a Feature module will just cause the Feature to appear overridden all the time, without providing any maintenance value. Over on this answer I provided a list of variables to exclude.
* I wouldn't expect Features to *increase* performance, though. I elaborated on that over here.
> 3 votes

# Answer
Feature is a good thing as long as you are using it limitedly. Every new feature is basically a module in your site and if you are having many features, then you will get into performance issues.

One way to overcome these by maintaining 1 single module and copy/paste the features code form other files into this one.

However it has its own disadvantages and best option is to write db scripts and update hooks to take care of database updates which can be easily deployed on any new instance easily.
> 0 votes

---
Tags: performance, features
---


title: Looking for a tpl.php cheat

text:
# Question
Title: Looking for a tpl.php cheat
I am wanting to develop some VERY simple tpl.php files. I would like to just open a WYSIWYG and edit them quickly, outputting the html that I can then copy-n-paste into the specific tpl.php files for my custom theme.

I know that I could do this in Dreamweaver or similar application.

I'm looking for a free service, online app, etc. I'm hoping that I am NOT the only person that would like to do this and someone else has figured out a quick way to do this.

I would rather avoid building this non-visually, strictly in code. It would be nice to move some objects around on a screen, maybe adjust some CSS properties visually, and then, when I am done -\> Dump to code. Copy-n-paste. Modify for Drupal variables. Go.

Anyone have a suggestion?

# Answer
> 1 votes
Learning to design something by code might be a bit daunting at first, however it is possible to view a themes' regions in Drupal which makes life much easier when you know what the dimensions are (and can test responsive design if you resize your window or use a bookmarklet of some javascript or better yet use the Web Developer extensions that all good browsers have).

Drupal Gardens explains a bit about Regions, I believe they also have a decent Theme Builder: http://www.drupalgardens.com/documentation/themebuilder/regions http://www.drupalgardens.com/themebuilder

Anyway, I came across Light Table a while back which can help when you're writing some JavaScript for a HTML5 Canvas animation, as the IDE allows you to view the changes almost instantly (after you press the shortcut to run the code): http://www.lighttable.com/

However I've not used it with a Drupal site, so I'm not sure if it'd work well.

There were others I've seen posts about recently such as TopStyle: http://topstyle4.com/

Though I have no experience with it as I prefer Sublime Text and Vim.

---
Tags: theming
---


# Question
Title: Boost not updating without www site after clearing cache
Boost is working good on my website but the problem is that after making any changes to my website I clear all cache from performance page. The changes I have done are reflecting if I am accessing site with www but not updating if I am accessing website without www

# Answer
> 2 votes
You need to clear the Boost cached pages, i.e. the static pages. You can do that on the Boost settings page at the bottom under `Clear Boost's Database & File Cache`. If you only have changed one page you can just clear this page by enabling the boost block `Boost: Pages cache configuration`.

**Edit:** After a bit more thinking I am not sure clearing the Boost cache will fix your issue. However, do yourself a favor and change your `.htaccess` rules to redirect users to either with www or without www. I would suggest with as that is working for you. Having both counts as duplicated content in search engines and you risk to loose ranking.

To fix this, uncomment the following part in your `.htaccess` file (around line 81), or add it if it's missing:

```
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

```

# Answer
> 1 votes
Boost actually caches the pages by url. So it treats www and without www are 2 unique urls and cache them separately. So as suggested above, you can redirect all urls without www to www urls so that users access only 1 url any time. Or else you need to clear cache for both the urls.

# Answer
> 0 votes
You can also implement some hooks to automatically clear the cache.

The below code is a bit aggressive, and just clears everything at any node change. It could be done more sophisticated, only clearing what is necessary.

```
/**
* Flush all Boost's cache when any change is made.
*/
if (function_exists('_boost_rmdir')) {
  function your_module_clear_cache($flush=true) {
    _boost_rmdir(boost_get_normal_cache_dir(), $flush);
  }
  function your_module_node_update($node) {
    your_module_clear_cache();
  }
  function your_module_node_delete($node) {
    your_module_clear_cache();
  }
  function your_module_node_insert($node) {
    your_module_clear_cache();
  }
  function your_module_entity_translation_save($node) {
    your_module_clear_cache();
  }
}

```

---
Tags: caching
---


# Question
Title: New Relic: "Application Code (in /theme)"
I have several Drupal sites with which I'm using New Relic to help monitor and debug performance issues.

I've been finding that when viewing the "Web Transactions" section under "Monitoring", that a large percentage of time is spent in "/theme". When I click in to view a trace, then view the Trace details, I often find that the majority of the time is listed in a rows named "Application Code (in /theme)".

The help link beside "Application Code (in /theme)" takes me to New Relic's PHP Custom Metrics Collection page. The documentation is clear enough, but what I don't understand is how to make this useful in Drupal. I'm guessing this is difficult for me because of Drupal's hook system, and (again guessing) that the "Application Code" that New Relic is referring to in this case are calls to theme() functions.

Is there something that I can do to get more useful information out of New Relic? First thing that comes to mind is "killing a kitten" and hacking core's theme() function to insert a New Relic Custom Metric, but I'd prefer not to do that (nor do I know for certain it will help!).

# Answer
> 0 votes
New Relic offers Drupal monitoring as part of their paid Standard plan to collect metrics for Modules, Hooks, and Views.

> The collection of Drupal-specific metrics can be controlled by the ini setting newrelic.framework.drupal.modules. It is enabled by default (in versions 3.0 and higher), and can be disabled with:
>
> `newrelic.framework.drupal.modules = 0` Though this setting uses the word "modules", it controls the collection of all Drupal metrics: modules, views, and hooks.
>
> The PHP agent collects metrics for the following:
>
> **Modules**: Versions 2.5+. These metrics indicate time spent within each Drupal module. In versions 3.5+, time is calculated from the hook dispatch functions module\_invoke and module\_invoke\_all. In previous versions, time was calculated from functions from a file with the ".module" extension where the file name and function prefix were a match. **Hooks**: Versions 3.5+. These metrics indicate time spent within each Drupal hook. Time is calculated from the hook dispatch functions module\_invoke and module\_invoke\_all. **Views**: Versions 3.5+. These metrics indicate time spent within a view's view::execute method.

You are correct that New Relic: “Application Code (in /theme)” refers to the execution of the theme() function. Given the throughput you referenced, this seems to be a minor issue, though there is definitely room for optimization if you're seeing ~7000ms response time. I typically see around 400-500ms with similar throughput.

---
Tags: 6, performance
---


title: Add arguments to custom submit

text:
# Question
Title: Add arguments to custom submit
I added an extra submit-function to my form:

```
$submit = array('_check_value_public_catalog');
$form['actions']['submit']['#submit'] = array_merge($submit, $form['actions']['submit']['#submit']);

```

So the form looks like:

```
array
  0 => string '_check_value_public_catalogue'
  1 => string 'node_form_submit'

```

But I would like to pass some arguments to my `_check_value_public_catalog` function. How do I do this?

# Answer
You can't as such but you can store the values in the form somewhere and pick them up in your submit handler:

```
function mymodule_my_form($form, &$form_state) {
  $form['saved_value_1'] = array(
    '#type' => 'value',
    '#value' => 'The Value'
  );

  $form['#submit'][] = 'mymodule_my_form_submit';

  return $form;
}

function mymodule_my_form_submit(&$form, &$form_state) {
  $saved_value_1 = $form_state['values']['saved_value_1'];
}

```

Exactly the same principle applies if you're doing this in a form alter hook.
> 9 votes

# Answer
Submit handlers have `$form` and `$form_state` automatically passed to them as arguments (`$form_state` will contain the submitted values for your form).

Assuming there are no arguments already supplied, your submit handler should look like below:

```
_check_value_public_catalog($form, $form_state) {
 //do funky stuff here
}

```

If you need specific arguments sent to the function, you could either write a different submit callback to pull the data out of `$form_state` and send it to your `_check_value_public_catalog` function, or re-write your submit function as below (before arguments are assumed).

Before:

```
function _check_value_public_catalog($foo, $bar) {
//cool stuff here with $foo and $bar
}

```

After:

```
function _check_value_public_catalog($form, $form_state) {
 $foo = $form_state['values']['foo'];
 $bar = $form_state['values']['bar'];

//cool stuff with $foo and $bar
}

```

See here for some more information.
> 3 votes

# Answer
Form submission handlers don't use anymore custom parameters as reported in $form\['#submit'\] and $form\['#validate'\] and $form\['#process'\] no longer support custom parameters. In that page, which is for converting modules from Drupal 5 to Drupal 6, it is suggested to use `$form['#custom_parameter']`, where "#custom\_parameter" is a string that doesn't conflict with one already used by Drupal.

```
function my_form() {
  // form definition code goes here...
  $form['#submit'][] = 'my_submit_function';
  $form['#my_form_param1'] = $param1;
  $form['#my_form_param2'] = $param2;
}

```

As alternative, the arguments passed to the form builder are available in `$form_state['build_info']['args']`. (See drupal\_build\_form(), which describes the values contained in `$form_state`.)
If the form builder is defined as in the following code, then `$form_state['build_info']['args']` is an array containing `"this is"`, and `"a test"`.

```
$item['mymodule/test'] = array(
  'title' => 'Test',
  'description' => 'This is a test menu.',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('node_admin_content', 'this is', 'a test'),
  'access arguments' => array('access test pages'),
);

```

In fact the code of drupal\_get\_form() is the following one:

```
function drupal_get_form($form_id) {
  $form_state = array();

  $args = func_get_args();
  // Remove $form_id from the arguments.
  array_shift($args);
  $form_state['build_info']['args'] = $args;

  return drupal_build_form($form_id, $form_state);
}

```

The function removes the first argument it gets, which is the form ID, and put the other arguments in `$form_state['build_info']['args']`.
> 3 votes

# Answer
found a good way to do this by attaching the parameters to the button:

when generating from

```
/**
* Implements hook_form_alter
*/
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  $nrbuttons = 10;
  for($i = 0; $i < $nrbuttons; $i++){
    $form['button_' . $i] = array(
      '#type' => 'submit',
      '#value' => t('button ' . $i),
      '#submit' => array('MYMODULE_form_submited'),
      '#attributes' => array(
         'button_index' => $i,
         'other_parameter'=>'value',
      ),
    );
  }
}

/**
* Custom submit handler
*/
function MYMODULE_form_submited($form, &$form_state){
    $i           = $form_state['clicked_button']['#attributes']['button_index'];
    $other_param = $form_state['clicked_button']['#attributes']['other_parameter'];
}

```
> 1 votes

---
Tags: 7, forms
---


# Question
Title: How can I trigger a rules event by code ?
I'm using Commerce for the website I'm building right now. I want to trigger the event "Calculate the sell price" after an order is updated to a status, I made one called "Approved". The reason I want to do that is that the Tax is calculated at this event and at the "Checkout: Checkout" page, but the store manager wants to choose if the customer should pay tax or not, he wants to do that manually not using billing or shipping conditions.

I added a boolean field "Apply VAT?" to the order page and added a condition if that entity exists and is true to apply the VAT tax, but this is:not done at the checkout page and I noticed that if I change the status back to "Checkout: Checkout" the VAT tax is applied and this is because of the "Calculate the sell price" event (tell me if I'm wrong).

I was thinking to build a rule with the event "Order is updated" and the action to be a PHP code to invoke the event again, I know about rules\_invoke\_event, but I can't get it working.

I also have problems with the tax not being applied to the shipping cost, but this is another problem (maybe I will open another question of this)

I will appreciate any answers, thanks!

# Answer
> 6 votes
I managed to invoke the event "calculate sell price" by adding a rule with the event "When existin line item is updated" and then adding a call to rules\_invoke\_event() in PHP code like this:

```
rules_invoke_event("commerce_product_calculate_sell_price", $commerce_line_item);

```

I was previously calling this rule incorrectly, without adding the `$commerce_line_item` so this problem is resolved, now the shipping remained.
Thanks for your time!

---
Tags: rules, commerce
---


# Question
Title: Starts with a larger ubercart order number
Ubercart order number start at 1. How can I set the order number to start with a larger number, e.g. 100001?

# Answer
Run this query against your database:

```
ALTER TABLE uc_orders AUTO_INCREMENT = 100001;

```

The next record added will use 100001 as the ID.

Or for Postgres (Thanks @Mołot for the heads up):

```
SELECT setval('SEQUENCE_ID', 100001, FALSE);

```

You'll need to replace `SEQUENCE_ID` with the appropriate sequence id for the `uc_orders` table.

For sequence-enabled databases that lack setval (like Oracle, at least in some versions), you can:

```
ALTER SEQUENCE schema.sequence_id INCREMENT BY 1000;
SELECT schema.sequence_id.NEXTVAL FROM dual;
ALTER SEQUENCE schema.sequence_id INCREMENT BY 1;

```
> 3 votes

# Answer
Other approach is to make order number not sequential. You may dislike the idea that user can count total orders between his orders - if he orders some minor stuff every month, he knows your monthly order volume, and that's bad. "Sanitization" of order number to prevent this was discussed here on ubercart.org.
> 0 votes

---
Tags: ubercart
---


title: Custom template for view page

text:
# Question
Title: Custom template for view page
When i created custom template for view page using 'theme information' in views,it's not affecting the page.What is the proper way to create template for view pages?

# Answer
> 1 votes
I think this pretty well covers it: Views template files

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


# Question
Title: Cookies change when I navigate to another page (Using jquery cookie)
For example, the user can change the font size, and it is remembered in the cookies. Say I am on the product page and change the font size there and add the cookie. Everything looks fine, but when I go to the front page, the font size is back to normal. Going back to the product page, the cookie is applied. How can I make the cookies work site-wide instead of per page? Or is there something wrong with what I am doing?

How I do it is, when the user checks a checkbox:

```
$.cookie('font', 'x2');

```

And on `$(document).ready()` I simply check the cookie and apply the css so:

```
if($.cookie('font') == 'x2') {
  $(body).css('font-size', '200%');
}

```

Or something like that. I don't think the problem is in my code though anyway, since it works, is this some kind of Drupal behaviour or...?

# Answer
Not really Drupal related, but it sounds to me like you are only setting the cookie for the current path.

Change:

```
$.cookie('font', 'x2');

```

to:

```
$.cookie('font', 'x2', { path: Drupal.settings.basePath });

```
> 2 votes

# Answer
Set a timeout of a certain number of days on the cookie:

```
$.cookie('font', 'x2', { expires : 10 });

```
> 0 votes

---
Tags: cookies
---


# Question
Title: Using ColorBox to popup "iFrame" shows original page content after the "iFrame" data?
I have a basic module that parses a JSON feed, stores it in cache, then shows a "gallery" of the objects - I know I should have maybe stored these as Nodes but it was supposed to be a quick simple module...

Anyway, it works well except, when I click on one of the objects in the gallery, I have it linked to an "iFrame" (which I cached too, but it's not really a real page) found at: the\_page?iFrame-id="theDataID" - these all popup in ColorBox and the HTML from the cache for the "iFrame" is displayed.

This worked well on the dev site, however for the production site - it uses different modules and templates (which I didn't have access to for setting up the dev site).

Now when you click on an object, the ColorBox popup shows the data, except it then shows the original pages' content and I haven't been able to figure out why it does that. I assume the prod site must try to always load the "original content" based on the URL and therefore "ignores" the ?iFrame-id part?

So basically, in my code for the iFrame, I do:

```
echo $data;
return;

```

Which causes the data to be printed above the normal pages' content in the popup. So I changed it to:

```
return $data;

```

But that caused the data to show up as the pages' content, and I still had the header/footer for Drupal.

Anyone have any ideas?

Another way I could do this is by using ColorBox's inline option instead of the iframe option, however I assume that would require all the data for the objects to be on the page? As right now, the content is loaded dynamically on popup (it doesn't exist anywhere in the DOM before hand).

# Answer
> 0 votes
OK, so originally I had tried `echo $data;` then `return;`

I then tried: `return $data;` but that kept showing the header/footer.

I've found that this works well:

```
echo $data;
die;

```

Though it's probably not the best way to do it, but it works for the way the module was wrote... should really use the Node/Entity API next time :)

---
Tags: 7, javascript
---


title: $body variable not working

text:
# Question
Title: $body variable not working
I am in a custom tpl.php file \[node--netrunner-card--Operation--full.tpl.php\]. This is for a custom content type \[netrunner\_card\].

I am trying to output the contents of the $body variable and unable to do so via the prescribed avenue. I copied node.tpl.php into my theme and renamed it. I can output the contents of body but I have to do this like so:

```
print render($body[0]['value']);

```

I should be able to do it like so:

```
print render($body);

```

But the second option renders nothing.

Any ideas?

# Answer
> 1 votes
Actually, the documentation for node.tpl.php says, in the description for the `$content` variable.

> An array of node items. Use render($content) to print them all, or print a subset such as render($content\['field\_example'\]). Use hide($content\['field\_example'\]) to temporarily suppress the printing of a given element.

The node body is a field, and you should use `render($content['body'])` to render it.

The note about field variables is the following one:

> Field variables: for each field instance attached to the node a corresponding variable is defined; for example, $node-\>body becomes $body. When needing to **access a field's raw values, developers/themers are strongly encouraged to use these variables**. Otherwise they will have to explicitly specify the desired field language; for example, $node-\>body\['en'\], thus overriding any language negotiation rule that was previously applied.

You should use `$body` only when you need to access the field's raw values, not to render the field.

# Answer
> 0 votes
I decided to ignore the notes in the node.tpl.php file and output like I did for all of my other fields, treating body like any other field instead of one of the two fields auto-created for all content types.

```
print render( $content['body'] );

```

This gives me the output I need!

---
Tags: theming
---


title: Hooking into a contrib module

text:
# Question
Title: Hooking into a contrib module
I've installed a contrib module in Drupal 7 and would like to hook into it. However, the documentation for the contrib module is sparse and doesn't list the available hooks, though it implies that there are some.

Is there a standard "Drupal way" of seeing what hooks a contrib module exposes?

(I've deliberately not mentioned which module this is as I'd like a generic answer if one exists.)

# Answer
By convention a lot of modules include a `modulename.api.php` file in the root folder, which describes the hooks implemented.

They may also implement `hook_hook_info()` to programatically describe the hooks to Drupal.

If that file isn't there, have a look at the other documentation/non-code files included. Sometimes you'll find examples elsewhere in the folder structure.

There's nothing enforced, though, so there isn't a generic all-encompassing answer. For a low tech solution you could grep the module folders for patterns like

* `module_invoke('modulename`
* `module_invoke_all('modulename`
* `module_implements('modulename`

If you use the grep method, remember to add a conditional for the quote before the module name, it could be single or double.

In case the above causes confusion:

By convention most hooks are prefixed with the module's name, so that method will work 99% of the time, and avoid false-positives when a module invokes hooks for anything other than itself.

There will be the odd instance when it doesn't, but since there's no formally enforced way for a module to define hooks, anything non-manual here is going to be a best effort however you look at it.
> 8 votes

# Answer
The only way to know which hooks are used from a module is looking for any of the following function calls.

Some modules have their own function that calls one of those functions. For example, the User module uses user\_module\_invoke(), and the Node module uses node\_invoke().
> 3 votes

---
Tags: hooks
---


title: Context path conditions

text:
# Question
Title: Context path conditions
I am using Context with Delta and Omega3. I am trying to make the Drupal Commerce Checkout, Review and Complete pages each appear differently. These are their default paths:

```
checkout/*
checkout/*/review
checkout/*/complete

```

The problem is that if you set a condition path to 'checkout/\*' in one context then the 'review' and 'complete' condition paths will both be overridden by it.

Is there a way to get separate contexts for each of the 3 pages?

# Answer
> 4 votes
Create 3 different contexts, in each context add path condition and set the paths as follow:

**First Context:**

```
checkout/*
~checkout/*/review
~checkout/*/complete

```

**Second Context:**

```
~checkout/*
checkout/*/review
~checkout/*/complete

```

**Third Context:**

```
~checkout/*
~checkout/*/review
checkout/*/complete

```

According to Context documentation **~** character (tilde) can be used to exclude one or more paths.

---
Tags: commerce, nodes, theming
---


# Question
Title: URL contains a number after node/nid: why?
I have just inherited a site to maintain.

The site has many pages ending with /node/$nid. I notice that appending /x to the end of this URL seems to change nothing. That is, if I browse to http://example.com/node/123/1, I get the same result as if I browse to http://example.com/node/123/2.

What are those numbers typically used for? I notice that in my sidebar, it seems to be sending people to the /2 version.

# Answer
> 3 votes
Drupal's path-matching is greedy. The path `node/%nid` will match anything with that string at the start, that has a separator after it. e.g

* node/%nid/1
* node/%nid/giraffe
* node/%nid/barack-obama
* node/%nid/this/is/just/too/much

The 'extra' path segments are passed on as extra parameters to the item's page callback, whether it wants/uses them or not.

The page that you see at `node/%nid/1` isn't different at all from the standard `node/%nid` page.

You'd do well to keep those URLs out of the page source at all costs, or make sure you have an appropriate canonical URL set, as Google will consider them duplicate content otherwise.

# Answer
> 2 votes
That is the behavior of Drupal: When a module doesn't define a menu path matching the URL passed to Drupal, Drupal uses the closer menu path defined by a module. That behavior is caused by menu\_get\_item(), which contains the following code.

```
$parts = array_slice($original_map, 0, MENU_MAX_PARTS);
$ancestors = menu_get_ancestors($parts);
$router_item = db_query_range('SELECT * FROM {menu_router} WHERE path IN (:ancestors) ORDER BY fit DESC', 0, 1, array(':ancestors' => $ancestors))->fetchAssoc();

```

In your case, the closer menu path matching the URL you are using is node/%nid, which shows the node content. If you would use http://example.com/node/123/edit, the matching path would be node/%nid/edit, which shows the node edit form.

A module implementing hook\_menu\_get\_item\_alter() could easily change that behavior, since `menu_get_item()` contains the following code.

```
if ($router_item) {
  // Allow modules to alter the router item before it is translated and
  // checked for access.
  drupal_alter('menu_get_item', $router_item, $path, $original_map);

  $map = _menu_translate($router_item, $original_map);
  $router_item['original_map'] = $original_map;
  if ($map === FALSE) {
    $router_items[$path] = FALSE;
    return FALSE;
  }
  if ($router_item['access']) {
    // …
  }

  // …
}

```

---
Tags: nodes, uri
---


title: Need help styling a field in a view

text:
# Question
Title: Need help styling a field in a view
I am using D7 and subtheming the commerce kickstart theme.

There is a view named Collection Products. I have added a field to the view called Product category: Description (indexed) that pulls in the taxonomy term description and places it above the product list. You can see the page here: http://freelance-graphic-designer.us/barmaiddev2/product-category/commercial-juicers

When it pulls this taxonomy term, all styling from the original content is lost. You can see how it comes in as one big block as h3. I have tried wrapping it in div containers in the wysiwyg editor on the original content page, but they just don't stay with it when it is pulled in by the view.

I have tried to style it within the view style settings with no luck.

I would like style the headings and body copy in my css style sheet and make it look more like the same content on its node here http://freelance-graphic-designer.us/barmaiddev2/commercial-juicers

Any suggestions? I am in a desperate hurry.

# Answer
How I edited the Collection Products view

I needed to get rid of the surrounding the field. Did so by editing the view template file:

Copied the file views-view-list.tpl.php to a Template folder inside my theme folder and renamed it views-view-list--collection-products--page.tpl.php

Removed the around

See these sources on view templates:

http://drupal.org/node/352970

http://www.templatezine.com/2010/03/views-styles-and-theming-how-to-redefine-html-output/

---

In the View:

I added the field Taxonomy term: Rendered Taxonomy term Check "Exclude from display" View mode "Taxonomy Term Page"

Under Format \> Settings Made Taxonomy term: Rendered Taxonomy term a Grouping Field

---

I also removed the header from the view since I had an image in the Rendered Taxonomy Term.

I also removed the 2 Taxonomy Term Name fields since the name came in with the Rendered Taxonomy Term.
> 1 votes

# Answer
Have you checked the configuration in the view for that field under "Rewrite Results" to make sure you don't have the box "Strip HTML tags" checked?
> 0 votes

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


# Question
Title: Migrate files from directory to Drupal using Migrate
I have a folder with a large amount of files in. I need to migrate this into Drupals file system so I can then reference them in the content.

The ID of the file is the actual name e.g. 1234.jpg

What's the best method of doing this? I think I have the destination method set using MigrateDestinationFile()

I could write a script to create an xml document which defines every file in the folder and then extend the XMLMigration class and use that but it seems a bit overkill? Are there any source methods that would help with this?

# Answer
Drupal manages files on "usage" basis - files imported to it's managed files table but not used by anything will get deleted on next file garbage collector, or what it's official name is, run.

There are modules like Media supposed to act as an owners and browsers for files like that. And this one actually supports both mass import and inserting it to content, too.

This will not, however, assure you predictable ID. Hardly any solution can, as your filesystem don't know about IDs currently used in your file table, and your Drupal don't know about your filesytem. Thus, modules like Node Export only looks for an actual file name in files directory on import, and then create needed file information in system tables, letting other files to get deleted. So, if your need is one-time import, check the docs of a tool you are using for import. It should be covered there.
> 1 votes

# Answer
If you are now using migrate\_extras to set media as destination, you can take a look to the following links:

1. An useful example to import images using media as destination
2. A thread on drupal.org that deals a question very similar to yours
> 3 votes

---
Tags: 7, migrations
---


# Question
Title: Will disabling the Form Builder UI do anything to my webforms?
I want to disable the form builder UI so that I can select "multiple option" for a select list in the default webforms editor. This feature is missing in form builder. Can I do this or will it clear out all the work I've done building the forms within the form builder UI?

# Answer
Form builder is just a user interface. It does nothing to the forms themselves. The display and use of the forms is dependent upon the modules that implement the forms. so, yes, you can disable it with no effect on your existing forms.
> 2 votes

---
Tags: 7, webforms
---


# Question
Title: How to get Drupal 7 installed in a sub-folder / sub-directory properly?
Currently i'm trying to installing a drupal 7 installation in a subfolder of another drupal public\_html folder, but it doesnt seem to work. I am getting a redirect loop error in chrome. I already modified the .htaccess in the parent drupal installation to ignore the sub-folder and i also set the $base\_url in the sub-directory drupal installation.

# Answer
> -1 votes
Okay after fiddling around some more. I finally solved the issue. First off the .htaccess in the subdirectory override's the root's .htaccess. so that means you dont have to worry about the root's .htaccess file

Therefore, anything that needs to be adjusted is within the subdirectory and you shouldn't need to touch anything in the root directory where you have your other drupal installed.

**What i did was:**

1. Comment out line 81 and line 82 of the subdirectory drupal installation .htaccess file.
2. Un-comment the line 94 RewriteBase to where you have your subdirectory drupal installed
3. Add in the $drupal\_base variable in your sites/default/settings.php file to fix any file path issues you might have.

If this worked for you let me know! +1! :)

# Answer
> 2 votes
When I do this, provided I have a clean install, I do not modify *anything*. Take the domain `http://diw.ifi.uio.no/`, where Drupal is installed in both `/www/`, and `/www/gruppe01/`, etc. (I just create the number of subdomains I need for various experiments). My DocumentRoot is set to be `/www/`. I just direct my browser to `http://diw.ifi.uio.no/` for the main site, and `http://diw.ifi.uio.no/gruppe01/` for the first subfolder site, etc. and it works - just like that.

Have you tried starting with a clean install and just install Drupal in the subfolder using the standard install procedure *without* changing `.htaccess`? (While not always necessary, I recommend that you have `$base_url` set correctly in the site's `settings.php`.)

In my experience, Drupal works fine out of the box when installed in a subdirectory of a vhost. The fact that there is *another* Drupal in the `DocumentRoot` does not make this any different, as long as each Drupal site has its own `.htaccess`, it will not try to read the `.htaccess` in any superior directory.

Examples:

# Answer
> 0 votes
If possible, it's better to setup the new site in it's own virtualhost, e.g a subdomain site1.example.com, site2.example.com etc..

If you want to install in a subfolder under a single vhost, you will find other odd configuration may be required (e.g embedded image paths etc.. )

If you want to go down the install in subfolder route, you've done some of the special conf and may just require `RewriteBase` in .htaccess to be set to the subfolder path for that site.

---
Tags: installation
---


# Question
Title: Are there any disadvantages in placing form elements in custom containers?
I've got a form layout in which form elements are separated between 2 divs: one with `float: left`, the other with `float: right`. I have to keep it that way.

Is it fine to place form elements in different containers? Could I get any troubles with form validation or submitting?

What's the best way to do it, via hook\_form\_alter(), or something else?

P.S. I'm not developing a custom module, but a theme. Here is an example of the form HTML; it's not precisely what it's going to be, but it gives an idea.

```
<div class="custom-holder">
    <div class="custom-box">
        <div>
            <input type="text" id="name" />
            <label for="name">First name:</label>
        </div>
    </div>
    <div class="custom-block">
        <div>
            <input type="text" id="surname" />
            <label for="surname">Surname:</label>
        </div>
    <div>
</div>

```

# Answer
> 1 votes
I can't comment yet so I'll try to be broad. First, there are not any disadvantages to customizing your output html, the form process and validation will work just fine as long as you're not adding form tags to your html that you are hoping Drupal will also process.

You don't need hook\_form\_alter if you only want to modify the html. You can use, in your template.php file, hook\_theme().

The first thing you would need is the id of the form. You can get this via viewing source or using the devel and devel themer modules.

Once you have your form id, within template.php:

```
/**
 * Implementation of hook_theme
 */
function yourthemename_theme($existing, $type, $theme, $path) {
  return array(
    'user_login' => array( // to modify user_login form, for example
      'render element' => 'form'
      )
  );
}
/**
 * Theme function
 */
function yourthemename_user_login($variables) {
  $user = drupal_render($variables['form']['name']); // use the devel module:kpr($variables), or print_r($variables) to look at the $variables['form'] element
  $pass = drupal_render($variables['form']['pass']);
  $remainder = drupal_render_children($variables['form']);
  // put the user field and pass field inside a custom div
  $output = '<div class="custom-block">' . $user . $pass . '</div>';
  $output .= $remainder;
  return $output;
}

```

Take a look at drupal\_render() and drupal\_render\_children() but, basically, when you call drupal\_render it 'renders' the element and remembers that it was already rendered. You use that with as many elements as you need to but always remember to render the children as well so that all of your hidden fields and drupal form stuff doesn't get left out.

Alternatively, I don't think I've come across a Drupal form I couldn't wrangle with some well-targeted CSS, if you'd rather go that way.

---
Tags: 7, forms
---


# Question
Title: How to have exposed filters not displayed on search results
This is hard to explain so I'm attaching an image.

When someone clicks on a filter to search for something, I would like the resulting page to show results but not the filter. Maybe simply a link like "back to search".

Or possibly a small search box, like basic search but not every filter.

# Answer
> 0 votes
This is pretty simple to do with a little coding:

First create a "Display output" template inside your theme folder that will only target the relevant view (check options using "Theme: Information" bottom right under "Advanced" when you are on your view administration page). Copy the contents of "views-view.tpl.php" inside the file and clear the caches.

After that modify the original filter output:

```
<?php if ($exposed): ?>
  <div class="view-filters">
    <?php print $exposed; ?>
  </div>
<?php endif; ?>

```

to what you need:

```
<?php if ($exposed): ?>
  <div class="view-filters">
    <?php if (!isset($_GET['something'])): ?>
    <?php print $exposed; ?>
    <?php else: ?>
    <?php print l(t('Back to search'), $_GET['q']); ?>
    <?php endif; ?>
  </div>
<?php endif; ?>

```

You will just have to replace "something" inside that $\_GET to a value that is actually used in your filters (check the URL when you have a search performed - it will look like `example.com?something=value1&somethingelse=value2`). Since views adds all the filter keys to the URL when a search if performed you can pick any of them.

---
Tags: views, search
---


title: login redirect for anonymous users

text:
# Question
Title: login redirect for anonymous users
I would like my homepage to seen by every user. But anonymous users should be redirected to a login page if they click on any link. How can I achieve this?

# Answer
There are many specific ways to do this, but here's the general idea:

Create a special content type for your home page that allows Anonymous access.

Then, set your other content types to require an authenticated user.

If you get stuck on a specific part of this process, or have more specific questions you may get better responses.
> 0 votes

# Answer
If I understand correctly, you want to have a front page with links to premium content. The front page should be visible to everyone, including the anonymous user role, while all other content should be premium (i.e. only be available to logged-in users, i.e. the authenticated user role). Users who are not authenticated should be redirected to a login page if they click on these links.

In Drupal, the default *View* access control is very crude. The permission *View published content* covers *all* content types. In order to have premium content on your site, you need to install a role based node access control module. Out of old habit, I use Content Access for role based access control. Some people think it is too marignally supported to be used on a production site, but it works for me. However, you may want to consider the alternatives.

With role based noded access in place, you can create a specific content type that everyone can see for use on the front page, and make all other content types premium.

You then need to set up the redirection to login. For this, I suggest you use the CustomError module. Clicking on a link to premium content will throw a so-called 403 error, and with CustomError, you can design your own 403 error page, which can be a login page.

Disclosure: I am co-maintainer for CustomError.
> 0 votes

---
Tags: users, redirection
---


# Question
Title: Is there a module that shows when you last updated or modified an installed module?
From time to time I update my modules and I would like to see when they were last updated. Is there such a module that adds this information?

# Answer
AFAIK, no module, but `ls -l` in your module directory should give you the dates of last updates.

Btw. it is trivial to create a module that does this. Just throw a module wrapper around something like:

```
$modules = '/www/sites/all/modules/'; // Path to your module directory.
$output = shell_exec('ls -l ' . $modules);
echo "<pre>$output</pre>";

```
> 2 votes

---
Tags: 7
---


# Question
Title: How do I localize menu items added to the Main menu by a views page?
I have a multilingual site setup where the pages in the Main menu are all created by Views. Main Menu is configured to 'Translate and Localize.'

When clicking 'edit' for a menu item the 'Translate' tab does not appear in the top right hand corner when the Language selection box is set to Language Neutral.

(This, however, does appear when I change the language selection in the drop down box to something specific; however, I want to Localize, not create a translation set.)

I know I have done this before. What am I missing? Note I am using node translation (content translation) and not entity translation.

# Answer
If I understand your question correctly:

Go to Structure \> Menu \> List links Assign the correct language to the link and then you can add a translation for the term.

One of your languages is to be set as the source language for translation. As far as I know a language neutral entity (menu, node, whatever) can not have a translated counterpart, because there is no source language for translation available.

Hope this helps.
> 0 votes

# Answer
I have solved the same problem you have with the Multiple Node Menu module: http://drupal.org/project/multiple\_node\_menu.

Some details from the module's project page:

> This module modifies the "Menu settings" in standard node editing form to allow managing multiple menu links to a node. The Drupal standard behavior is to only care about a single menu link for anode, all other menu links must be added through menu administration.
> 0 votes

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


title: Using a framework like Backbone

text:
# Question
Title: Using a framework like Backbone
I currently have a page http://proctors.org/tv that is driven by several views and attachments with tons of jQuery and hacked-together JavaScript spaghetti, and I would like to clean it up. I understand that newer Javascript "MVC" frameworks make use of templates, and don't strictly store all the data in the DOM as you might do with jQuery.

I believe you would use something like Services and/or Views as the backend, with Backbone on the front.

There is a D.o project for Backbone, and I remember there being a BoF or Session at DrupalCon Denver about it...

I am hoping to discover if it is worth my time to try and rewrite this in a new framework or just clean up what I have here.

# Answer
I have used both Ember and Backbone along with Drupal - but not in the way you would think.

Ember and Backbone are both fine tools to create a web application - but Drupal is not really a good tool to be used along with them. What you desire when you built a web app is something light and fast. You want it to be fast to be able to give your users the feeling if immediate response times. You want it to be light to make it scale better. Drupal is not fast - the full Drupal bootstrap takes a long time (compared to a lot of other options) if all you want to do is provide a REST API for your web app. Drupal is PHP, which also makes it quite RAM hungry limiting the number of concurrent users.

## So if Drupal is so bad for this why use it?

You should really use Drupal for what Drupal excels at - a CMS. What I've done in the past with projects that needed a web app is to use Drupal to create the CMS around the web app. To build stuff like blogs, content lists and the likes. I also created modules to define some backend stuff - like schema definitions, and other stuff where it made sense to use Drupal - because it made my development much easier.

Instead of using Drupal to create the REST API that the webapp needed - I used Node.js to create the actual REST API and other checks AJAX calls that the webapp needed to make. Node.js excels in doing just this. It's blazing fast (response times as low as 30ms for a list of objects). It's also very lightweight, since JavaScript on the server uses asynchronous actions, a Node.js server can usually handle thousands of concurrent users where PHP can handle maybe 100. In addition to that - since Node.js is JavaScript, you can reuse a lot of the code server and client side. You can literally write the same validation code, instead of having to implement both client side in JavaScript and server side in PHP. If you are going to Drupal con in Münich in a few weeks - you should consider watching the node.js presentation.

So if you are a developer, I would strongly recommend doing a similar setup, and only use Drupal for what it is really good at. If you want to make a simple webapp and you don't expect a lot of user, using Drupal as a backend could be an option if it helps your development time.

---

## Update Drupal 8

So with the release of Drupal 8 some of the above still holds true but not in the same extend as earlier. Drupal 8 is like Drupal 7 not a light weight tool, like Node.js, Rails, Django etc. Since JavaScript apps mainly consume various services, you still should consider if Drupal is the best tool for this.

With Drupal 8 a lot of things have been improved. Services is a lot more native, with Symphony driving the request/response. Drupal 8 has a lot of interesting possibilities with with the advanced caching and all of the great features. But even with all of the greatness of Drupal 8, it still is a lot heavier than light weight applications. It's hard to tell how successful Drupal 8 can be used as a fast webservice provider.

So still, with all being said and done, my general recommendation stays the same. Being a Drupal developer, it's easy to use Drupal for everything, since we're familiar with it. It feels safe and Drupal *can* be used for just about anything. Remember while it's possible to use Drupal for anything, it doesn't mean that it's the best tool for everything. Doing a sound analysis and understanding the strengths and weaknesses of the tools you want to use on an IT project, will always be a great help and can help you avoid ending in a deadlocked position with a result that doesn't live up to your expectations.
> 18 votes

# Answer
I have recently begun developing my first backbone + drupal application and am really enjoying it. Using the Backbone module along with Services, Services Views, and the required libraries. The project is quite simple: To create a content manageable carousel of 6 pages that display various data, along with an additional News slider that displays different content. This page sits on various screens without user interaction so required the ability to update the front end content without refreshing the browser. I thought this fit perfectly into a Drupal + Backbone app with Drupal managing the content and backbone controlling and syncing with the db. I integrated in jquery.cycle 2 which has an awesome API and fits well into the MVC style of coding.

I can see why people might stick their nose up at using Drupal as the backend framework but for a small application like this Drupal **is light and fast**. I achieved this by starting with a minimal install and carefully picking contrib and core modules. I'm now at around 50 modules with just under 150 lines of custom JS code for the backbone stuff and I'm pretty much done.

Eventually I will try to commit this back as an example to the backbone module as there is currently no example which shows how to use Views as collections etc.

**In conclusion:**

It is worth your time to look into this if your project matches well. In my opinion, performance issues derived from the heaviness of Drupal can be easily combated by using caching mechanisms like Varnish, or even boost or core page caching. The flexibility and speed of development from using Drupal completely outweighs the negatives for me.
> 6 votes

# Answer
The basic answer is yes, some people are using it. I have not used it myself (haven't found a good project match yet), but there is currently a Drupal group for it, and it would also fit in with the Web Services and Context Core Initiative which is one of the Drupal 8 Initiatives. There is also a session at DrupalCon Munich 2012, Backbone.js in the Frontend.

I don't know if it is ready for prime time yet, but in my opinion it is worth creating a proof of concept for if you have something that could benefit from it, and can design the JS side to an interface and not an implementation. That would help isolate any backend changes should you decide to bail on Drupal, for whatever reason.
> 5 votes

# Answer
You might find this useful : it shows an example of converting a JQuery based script into a backbone script. Obviously you will need to pull in backbone.js, either as a library using drupal\_add\_js or using the module.

https://github.com/kjbekkelund/writings/blob/master/published/understanding-backbone.md/
> 3 votes

---
Tags: javascript
---


# Question
Title: how do i alter comments and comment form
I am trying to change the way comments are displayed in drupal 7 for a specific content type. I am using garland theme. Ideally I would like to modify comment display in my module as opposed to doing it in the theme.

I have successfully implemented hook\_form\_comment\_form\_alter to hide the author name this way:

```
function mymodule_form_comment_form_alter(&$form, &$form_state, $form_id) {
  //  krumo($form_id);
  switch($form_id) {
    case 'comment_node_mycontenttype_form':
      hide($form['author']);
      break;
  }
}

```

Now I would like to alter the comments to:

1. Hide the comment title link
2. Hide the "reply delete edit" links

I tried to implement `hook_comment_view_alter()` and `hook_node_alter()` but these seem not to get called. When I use the following code, nothing happens (no krumo outputs and no modifications).

```
function mymodule_comment_view_alter(&$build) {
  krumo($build);
}

```

```
function mymodule_node_alter(&$build) {
  krumo($build);
  hide($build['links']['comment']['#links']['comment-reply']);
}

```

The only way I found was to modify `garland_preprocess_comment()` in template.php in garland theme. But this applies to all content type and also I would like to have all my code in my module.

Is there a proper way to do this?

How come `hook_comment_view_alter()` and `hook_node_alter()` don't seem to get called?

Note I am using panels to add my content. So I have added the comments and the comment form using panels module. Therefore there is no field to toggle "allow comment title" as there is in structure-\>content type-\>comment settings. Even though the "allow comment title" field is unchecked, titles are still displayed. it seems like panels overrides this setting somehow.

# Answer
> 2 votes
To put this in my module I actually just did put the following code in my module:

```
function mymodule_preprocess_comment(&$vars) {
$vars['submitted'] = $vars['created'] . ' — ' . $vars['author'];
switch( $vars['node']->type )
 {
 case 'myContentType':
 $vars['title'] =FALSE;
 $vars['content']['links']['comment']['#links']['comment-reply'] = FALSE;
 $vars['content']['links']['comment']['#links']['comment-edit'] = FALSE;
 $vars['content']['links']['comment']['#links']['comment-delete'] = FALSE;
 break;
 }
}

```

# Answer
> 0 votes
I can't say this is the "proper" way since technically you'd be modifying a core file, but normally the easiest way would be to create a custom file in your theme's directory called `comment.tpl.php` and make your modifications there. **But**, since you're using the Garland theme from core, which already has a `comment.tpl.php` file... Well, any changes you make to it will be overridden the next time you update to the next release of Drupal. Plus, **don't hack core**.

That said, assuming you were using a different theme, you could use Garland's `comment.tpl.php` file as a point of reference and applying some minor modifications like so:

Garland's `comment.tpl.php` file:

```
<?php
?>
<div class="<?php print $classes . ' ' . $zebra; ?>"<?php print $attributes; ?>>

  <div class="clearfix">

    <span class="submitted"><?php print $submitted ?></span>

  <?php if ($new): ?>
    <span class="new"><?php print drupal_ucfirst($new) ?></span>
  <?php endif; ?>

  <?php print $picture ?>

    <?php print render($title_prefix); ?>
    <h3<?php print $title_attributes; ?>><?php print $title ?></h3>
    <?php print render($title_suffix); ?>

    <div class="content"<?php print $content_attributes; ?>>
      <?php hide($content['links']); print render($content); ?>
      <?php if ($signature): ?>
      <div class="clearfix">
        <div>—</div>
        <?php print $signature ?>
      </div>
      <?php endif; ?>
    </div>
  </div>

  <?php print render($content['links']) ?>
</div>

```

Modified version for your theme:

```
<?php
?>
<div class="<?php print $classes . ' ' . $zebra; ?>"<?php print $attributes; ?>>

  <div class="clearfix">

    <span class="submitted"><?php print $submitted ?></span>

  <?php if ($new): ?>
    <span class="new"><?php print drupal_ucfirst($new) ?></span>
  <?php endif; ?>

  <?php print $picture ?>

    <div class="content"<?php print $content_attributes; ?>>
      <?php hide($content['links']); print render($content); ?>
      <?php if ($signature): ?>
      <div class="clearfix">
        <div>—</div>
        <?php print $signature ?>
      </div>
      <?php endif; ?>
    </div>
  </div>
</div>

```

After you make any such changes, remember to clear the cache so the changes are recognized by the system.

---
Tags: 7, comments
---


# Question
Title: MSAccess to SQLite install and setup custom content types?
I'm looking for information on how I could use or import a MSAccess database into a SQLite install of Drupal 7. Is this possible or will I have to export the MSAccess tables to CSV or something and then add them to the SQLite db slowly?

# Answer
\** Full Disclosure I've Not Tried This Using the Requested Setup!! \**

I've migrated Joomla -\> Drupal and CSV to drupal ... so I have some experience with this. But having not tested your exact request I'm not 100% this will work.

You can install PDO and PDO support for ODBC drivers. I assume your PHP environment is Windows so you can also install MSAccess, which supports an ODBC driver connection. Here is a blog example of how to install/use MsAccess ODBC for a plain PHP webapplication.

You can then configure your `settings.php` file to include a custom database connection using PDO to use an ODBC driver to talk to your MSAccess database. This could look something like:

```
   $databases['remote_msaccess_db']['default'] = array(
     'driver' => 'odbc:DRIVER={Microsoft Access Driver (*.mdb)}',
     'DbQ' => 'C:\some\path\to\your\db.mdb',
     'uid' => '',
     'pwd' => '',
     'host' => 'localhost',
     'prefix' => '',
   );

```

That's actually the hard part :). Which may not work. Assure you have the same 32bit or 64bit ODBC drivers for PHP as whatever version OS MSAccess is running.

After that you can use a tool like Migrate to move the data from MSAccess into Drupal content types, Entities or even a plain old table based migration which Migrate supports (and I've used).
> 1 votes

---
Tags: 7, database
---


title: Custom publish date

text:
# Question
Title: Custom publish date
I need to manipulate the publish date of my nodes on the node entry form. How can I achieve that? Shall I set a date field for my node that will hold the publish date? In case I do that, how can I move the publish date to the node definition? Or do you recommend me to keep this "publish" field apart from the node publish date and have two different things?

# Answer
> 2 votes
If you're using D6, you use a hook\_node\_api($op = 'presave'):

```
function custom_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op) {
    case 'presave':
      if ($node->type == 'story') {
        //use dsm($node) to explore the variables
        //set the created date to the field value, must be a unix timestamp.
        $node->created = $node->field_published[0]['value'];
      }
  }
}

```

D7, hook\_node\_presave:

```
function custom_node_presave($node) {
  if ($node->type == 'story') {
    $node->created = $node->field_published[0]['value'];
  }
}

```

Of course using unix timestamp isn't handy so set a date field and use date\_convert.

```
$node->created = date_convert($node->field_published[0]['value'], DATE_ISO, DATE_UNIX);

```

# Answer
> 0 votes
`date_convert()` apparently doesn't exist under Drupal 7. I used `strtotime()` to convert my `datetime` field to the Unix time string and enter it into the database:

```
function mymodule_node_presave($node) {
  if ($node->type == 'article') {
    $node->created = strtotime($node->field_post_date['und'][0]['value']);
  }
}

```

---
Tags: entities, datetime
---


# Question
Title: Self-hosted development and deployment control panel - does this exist?
My company requires a dev/staging/production environment for a new Drupal project. Plus some kind of control panel for managing development workflow and testing, upgrades and backups of code and content.

An obvious choice would be a platform like Acquia Cloud or Pantheon; their control panels do exactly this. But we are unable to use a hosted service; industry regulation means we must host on our own LAMP environment.

I'm familiar with Drush, Features and GIT, but wondered whether there is any distribution, project or commercial package that provides a management backend that pulls these elements together? I guess one of the reasons why Acquia exist is because the answer is no.

Any tips would be appreciated.

# Answer
Aegir in and of itself is definitely the route I would recommend.

If you want a complete server + Aegir solution (and are willing to consider a LEMP stack), Barracuda-Octopus-Aegir (BOA) is fantastic (and highly maintained).
> 1 votes

---
Tags: 7, deployment, staging
---


# Question
Title: How to I get rid of "Error with menu entry.... " in recent log messages?
I have Taxonomy used to get a menu structure by using the module Taxonomy\_menu. Since a couple of weeks I get "Error with menu entry "Activity" in menu "menu-products" in my "recent log messages" when somebody visits (even myself) our homepage.

Taxonomy\_menu is the type of the report.

I've already tried to "Select to rebuild the menu on submit." via /admin/structure/taxonomy/products/edit and rebuilding taxonomy Menu.

**More details added:**

The lines "Error with menu entry "xxx" in menu menu-products" in the "recent log messages" appears multiple times, for every time the homepage is accessed. I have made a Taxonomy list with 8 productgroups. One of the productgroups ("xxx") appears 6 times each time, another 3 times and a third one 2 times. The other 5 productgroups do not appear in the recent log message so seems to be working ok.

I've also noticed that the sequence of the 11 lines of error messages are exactly the same every time. Also strange that the productgroup that is referenced twice, is not directly repeated but appears later again in the logging.

I have an (almost exact) test version of the same website which doesn't show these message which lead me to the conclusion that this error message is caused by some kind of setting mistake for these 3 productgroups. However I have no idea where to change this so that these messages will be gone nor an idea why the number of times the message appears differs for 3 of them?

So far the website users are not be bothered by this message, but I like to get rid of it, as it fills my log messages very rapidly.

Can somebody please give me some directions?

# Answer
Same problem here:

I just created a Vocabulary and set to sync with the Main Menu. When saving the Main menu doesn't show the terms of the vocabulary.

I get this error in the logs: which is fired by the line 1190 of taxonomy\_menu.module

> Error with menu entry "" in menu "main-menu"

The vocabulary is set to:

> Translate. Different terms will be allowed for each language and they can be translated.
> 0 votes

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


# Question
Title: how to update the order total in checkout page?
I'm calculating discount amount base on total order amount. how can I show the discount amount like something what coupon module has done? (see the picture)

what is the correct way to update the total order amount? I mean how should I subtract the discount amount from the order total so if any products has been removed or added it always works correctly??

# Answer
> 1 votes
You need to use hook\_form\_alter().

First, for integrity purposes, write a validator that will ensure all amounts are correct, and if not - update them & show form to user again.

Second - use AJAX. Drupal allows only for one callback, so your new one will have to take care of calling the original one in the first place, and you may have some problems if you will need to replace more than one form element, but it can be done.

---
Tags: commerce
---


# Question
Title: How to automate database table access as objects and provide common operations, like CRUD and views integraion?
I think this is a pretty normal use-case: Developer has a database. Tables and columns have meaningful names and helpful comments, possibly also sane set of relations. Now he needs a module to be build on it.

Is there any automated way to provide CRUD and views integration, either dynamically or by creating a module backbone for developers to edit? Like scaffolding available in Cake PHP and other frameworks and languages? Doing it by hand for large number of tables is repetitive and boring, and that's both waste of time and source of errors.

# Answer
Automatically, no (although if someone want to prove that wrong I'd be delighted to see the solution). However, everything you've asked for is easily attainable through Drupal's API:

* For the database table, implement `hook_schema()` (no foreign keys are enforced in Drupal 7, though the relationships can be described for documentation)
* For views integration implement `hook_views_data()`
* For CRUD forms use the form API.

I think the closest you'll get to doing that *automatically* is the Entity Construction Kit. You can define your custom data as an entity, and I believe that module will create the appropriate entity forms for you. Integration with the Entity API module and Views means you can also expose that data, and you get field functionality built right in.

However, going that route will probably end up taking more code than doing it manually, and the reliance on the entity/field system will introduce extra overhead.

You might also want to look at the Doctrine ORM module; I haven't used it before, and it's only in dev, but if you can get that working it would give you objects mapped to DB tables as you're looking for. Exactly how that would fit into Drupal I'm not sure.

Things in Drupal 8 should be much better.
> 2 votes

---
Tags: views, database
---


title: Views page showing a user's content

text:
# Question
Title: Views page showing a user's content
I have created a image gallery on Drupal 7 users' profiles, which I would like to present as a separate page, linked to their profiles using views.

so, there would be a page at mysite.com/typical-user/gallery

I am at a loss on how to use the contextual filters to achieve this.

# Answer
> 0 votes
If you want to filter gallery images by user id try "provide default value" and than use arg(1) which is user id in your URL, More on this here : http://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/arg/7

---
Tags: views
---


title: db_insert() returns wrong key

text:
# Question
Title: db_insert() returns wrong key
I'm trying to migrate from drupal\_write\_record() to db\_insert() / db\_update(), but db\_insert() returns a weird key instead of the last inserted key.

On an empty table, I'm doing an insert, and instead of real row number (suppose to be 1, right?), I'm getting a wrong one.

```
$fields['created'] = REQUEST_TIME;
$fields['uid'] = 1;
$insert = db_insert('table')->fields($fields);
$last_insert_id = $insert->execute(); // suppose to be 1, but = 43587087

```

Any ideas? Thanx.

# Answer
> 2 votes
The autonumber isn't related to the number of records in the table, but rather the `AUTO_INCREMENT` value of the table's primary key column.

If you have a completely new table, and add 100 rows, the next ID will be 101. If you just remove all the rows in that table the next ID will *still* be 101, unless you `TRUNCATE` the table, or reset the `AUTO_INCREMENT` column.

For an easy way to test, fire up your preferred DB client, and insert a record into the database. If you get `1` as the next insert ID, there's a bug with your Drupal installation/DB engine. If not, it's just what's mentioned above.

---
Tags: 7, database
---


# Question
Title: showing an image field from solr index on custom solr search page
I use the Apache Solr Views module to create a View that displays only items from a specific content type.

I would like to include an image as well on the view. I managed to get the images on my site indexed in solr using a custom module (field is called ss\_field\_image\_uri). They show up in the solr index and I can add the image field in my custom solr view. So far so good.

The problem is that the field outputs as "public://folder/imagename.jpg". My question is how how I could I get the view to output not the link but the image itself?

Should I somehow rewrite the output of the image field in the view? Or use a custom php field and add some code? I cannot figure out how to do it. I am not a programmer but any pointers as to how to proceed would be very much appreciated.

Best, Gerben

# Answer
> 5 votes
We managed to solve this with help from user Gaele Strootman.

There are three steps to solve this: 1) add the image to the solr index using a custom module 2) add the image field to your apache solr view 3) add a template file for the image field that displays the actual image

## ad 1) create a custom module to add images to the solr index.

You only need two files, my\_module.info and my\_module.module. We name the image field ss\_field\_image\_uri.

my.module.info:

```
name = Apache Solr Image
description = Add image field to the solr index so we can display images in search results
package = Apache Solr
core = 7.x

dependencies[] = apachesolr_search

```

my\_module.module:

```
<?php
/**
 * Add field_image uri to apache solr index, so that we can later display image in search results or custom apache solr views page.
 * @see apachesolr.api.php
 */

function apachesolr_image_apachesolr_index_document_build($document, $node, $namespace) {
  if (isset($node->field_image['und']['0']['uri'])) $document->addField('ss_field_image_uri', $node->field_image['und']['0']['uri']);
}
?>

```

## ad 2) add the image field to your apache solr view

First re-index solr so the images actually get indexed and show up. Then add the image field to your view.

## ad 3) add a template file for the image field that displays the actual image

This is the template we added. Since the field is called ss\_field\_image\_uri the template name is: views-view-field--ss-field-image-uri.tpl.php. This is the code:

```
<?php

/**
 * @file
 * This template is used to print a single field in a view.
 *
 * It is not actually used in default Views, as this is registered as a theme
 * function which has better performance. For single overrides, the template is
 * perfectly okay.
 *
 * Variables available:
 * - $view: The view object
 * - $field: The field handler object that can process the input
 * - $row: The raw SQL result that can be used
 * - $output: The processed output that will normally be used.
 *
 * When fetching output from the $row, this construct should be used:
 * $data = $row->{$field->field_alias}
 *
 * The above will guarantee that you'll always get the correct data,
 * regardless of any changes in the aliasing that might happen if
 * the view is modified.
 */
?>
<?php
/**
 * For additional parameters see
 * http://api.drupal.org/api/drupal/modules!image!image.field.inc/function/theme_image_formatter/7
 */
?>
<?php $variables = array('item' => array('uri' => $row->{$field->field_alias})); ?>
<?php $variables['image_style'] = 'thumbnail'; ?>
<?php print theme_image_formatter($variables); ?>

```

Now clean your caches and the images should show up in your apache solr view. Note that you can change the image style in the code from 'thumbnail' to whatever image style you like.

Hope this helps anyone!

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


# Question
Title: Code comments in TPL file that wont be rendered in HTML?
Can I add code comments to my template files that won't be publicly shown in the HTML?

# Answer
> 5 votes
You can use PHP comments, those will be ignored by the template engine and not rendered to HTML:

```
<div class="something">
  <?php /* This won't be visible in the source. */ ?>
</div>

```

---
Tags: theming
---


title: views attachment title

text:
# Question
Title: views attachment title
I am using a view page with some attachments. For each attachment, I need to display the title : it's right in the preview, I can see the attachment's title, but not in the rendered page. How can I fix this please?

zorglub

# Answer
As a pretty easy workaround, you could set up a `views-view.tpl.php` on your own sites that prints `$view->get_title()` for the title on the attachments.
> 2 votes

---
Tags: views
---