title: Why do I get the following error?

text:
# Question
Title: Why do I get the following error?
I need to implement `hook_views_query_alter()` to change the value of delta of the field that form a relationship.

As I posted in change delta value, the code is the following one.

```
   function supermama_misc_views_query_alter($view, $query) {
     $view->$query->table_queue['field']['join']->extra[2]['value'] = 1;
   }

```

It gives me the following error:

> Fatal error: Cannot access empty property

The same error appears if I use the following code.

```
    function supermama_misc_views_post_build($view) {
      if ($view->name == 'gallery_images') {
        $view->$query->table_queue['field']['join']->extra[2]['value'] = 1;
      }
    }

```

What's wrong with the code? How do I bypass the error?

# Answer
Thanks a lot molot

the problem was a wrong implementation to the views hooks as this post

and hook\_views\_query\_alter

This hook should be placed in MODULENAME.views.inc and it will be auto-loaded. MODULENAME.views.inc must be in the directory specified by the 'path' key returned by MODULENAME\_views\_api(), or the same directory as the .module file, if 'path' is unspecified.
> 0 votes

---
Tags: views, hooks
---


title: Support Ticketing module - clients

text:
# Question
Title: Support Ticketing module - clients
I want to use the Support Ticketing System module to create a 'help desk' for my site. However, I'm not really sure I understand the 'client' system. All I really need is for the user to be able to submit a support ticket to a department, like 'Pre-Sales' or 'Bug Report', and for a member of staff to be able to respond to their issue. I'm just wondering if the support ticket module is 'overkill' and I could code something more simple?

Or, should I just add each department as a client and let users pick which department they'd like that way?

I was using osTicket and was content with it, however I need a user-login system and all the details are already on the drupal site.

# Answer
Think of "Support Client" as entity that pays for support. Or would pay if you'd charge. On your site you probably want two support clients: your company and external. Or, if you are B2B company, each of your client business should be defined as a support client, plus one for your own company. Then you can tie roles with support clients, like "marketing department" and "sales manager" are roles that belongs to "internal" support client, and "*example company representative*" belongs to "*example support*" support client.

Benefit of this is: all your internal roles can participate in your internal issues, and all roles of one of your clients can participate in theirs, but clients cannot peek at each other's support tickets, or at your internal ones.
> 1 votes

---
Tags: 7, users
---


# Question
Title: Welcome email body not changing to reflect account settings
I'm in `/admin/config/people/accounts` and have changed the text that new users will be sent when signing up accounts, but the body of the messages remain the same, although the subject line is changing, so I know it's having some account. I have cleared the cache many times ;).

I'm using Mailsystem and HTMLmail as well as Profile2... not sure if they would affect these emails.

The password reset email does work, but not the account creation Welcome message.

I have confirmed that `user_mail_register_no_approval_required_body` is set correctly in the `variables` table in the database, but that call is never being made.

I'm looking through user.module and user.admin.inc trying to determine how this is all supposed to work. Even changing the hardcoded message in `_user_mail_text()` (user.module line 2589) hasn't had an affect.

I have a functioning hook\_mail in my module so I added the correct key from user.module to that (`register_no_approval_required_body`) with no luck.

# Answer
I have tried to regenerate the issue you have specified 'Welcome email body not changing to reflect account settings' in D7. Although, particular use case has not been specified, I have tried all the three scinarios releted to 'Welcome email' here 'admin/config/people/accounts' :

1. Welcome (new user created by administrator)
2. Welcome (awaiting approval)
3. Welcome (no approval required)

Also, 'Account activation' for 'Welcome (awaiting approval)' use case.

but could not regenerate the issue. At the most it can be that you have made changes in one scinario & tried to check in another.

Hope it helps.
> 1 votes

---
Tags: 7, users, emails
---


# Question
Title: How can I track statistics on my site's user population?
I have a site with a fairly large number of users and I am trying to track statistics on them over time.

For example, users can have:

* Any combination of four roles
* One of two values for gender
* One of two values for an additional field

I want to track each combination of role, gender, and additional attribute separately.

This has lead me to use Views to create a huge number of content panes, each with filters set to catch a particular combination. I then added all of these to a panel, where I view them once a week and write the numbers down.

However, I now want to add an additional field with 6 additional values. Creating all those combinations in Views is going to be a mess. Is there a more efficient way to do this rather than clicking through the Views UI, creating a content pane for each possible combination, and then adding that in Panels?

# Answer
> 2 votes
Other than the option you present, I think you have two choices.

One is to wire up a `hook_menu()`, and create a path that accepts role, gender, and the other field value. You would then pass this into a `db_select()` or `EntityFieldQuery()`, and return the results in HTML table form.

The other option, and the one I would recommend, would be to make up a View over your users, add in your roles and fields, and then use Views Data Export to export as XLS or CSV. You can then analyze your data in a third-party tool like Excel.

Why do I recommend the later? Leverage your tools for their strengths. Drupal is good an managing and serving up content (raw data counts). Tools like Excel are great at analyzing data. These three fields are what you need to look at *now*, but this could change in the future. Having a full export of the raw data will make this much easier down the road.

# Answer
> 1 votes
If you don't mind some SQL work, Forena might be a module for you. Without all that neat and nice features like report skins (a kind of templating) - which might be unneeded in your case - it's much lighter, cleaner and faster.

Forena can be used to query (not update) any MySQL database table (that includes any Drupal table also).

For more details about Forena, 2 types of documentation are available these days:

* Community documentation.
* Documentation that comes with Forena, which you can access right after install and enable of the module. Checkout the demo site for an online example of the current:

+ **Forena documentation** \- use the link 'Reporting documentation' or visit relative link /reports/help.
    + **Forena samples** \- use the link 'Reporting samples' or visit relative link /reports/samples (these samples are fully functional, so make sure to experiment a bit with it, such as the drill downs available on the SVG Graph sample).

The newest 7.x-4.x version also includes an amazing (I think) UI for either creating your reports (the WYSIWYG report editor) and/or for creating your SQL queries (the Query Builder).

Here are some variations of the **MySQL database** part in my answer:

1. Using a **SQLite** instead of MySQL database: the Forena samples actually get shipped including a (Tiny) SQLite database. Go check it out in the demo site: the data shown there are data contained in the sampledb, which is in SQLite format.
2. Forena comes with a full suite of Supported database connections ... such as MS SQL, Oracle, Postgress or any PDO compliant variation.

Enough reasons for considering giving Forena a try? While doing so, use it's issue queue for any type of support/docu requests you may have.

Disclaimer: Pierre.Vriens (answer editor) is a co-maintainer of Forena.

---
Tags: nodes
---


title: Saving the URL during registration

text:
# Question
Title: Saving the URL during registration
So I have created a drupal multisite install with a shared user database and I would like to store the site the user has signed up on.

I have also created a view of user and I would like to filter them by site. Ideally I would like the view filter to be a dropdown, but it isn't essential.

I am already overriding the user\_register\_form via the template.php file, would it best to create a new text field for the user then hide and set it to the current domain via the template.php file?

# Answer
Hope this will help you,

In Drupal 7

The best way to do is to create a new field for user registration form. Lets call the field as **domain**.

Steps:

1. Go to admin/config + **Account settings** \+ **Manage Fields**
2. Add new field After adding If you want to show this field in registration then check this

**NOTE**: If prefer do not show on registration form. May be there a chance to edit. Even though if your making it as disable, it can be change.

When ever the user registration form load, alter the form using **hook\_form\_alter** and give the **default value** for it.

```
function mymodule_form_alter(&$form, $form_state, $form_id)  {
switch ($form_id)  {
    case 'user_register_form':
       //get field language
       $field_lang = field_language('user', 'field_user_domain');
       //assign default value
       $form['field_user_domain'][$field_lang['field_user_domain']][0]['#default_value'] = $_SERVER['HTTP_HOST'];
    break;
 }
}

```
When ever the users register the domain also saved.

You can use this field in views as per your requirement.
> 1 votes

---
Tags: entities, multi-sites
---


# Question
Title: How do I set a variable in the install profile to enable users to sign up for the website
I am trying to understand about how setting variables works in install profiles. As an example, how would I set the option to enable people to create a website for the account in the install profile? Here is the page on variable\_set https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/variable\_set but how do I retrieve the value.

# Answer
> 4 votes
Variables in install profiles work no differently to variables in a 'normal' bootstrap.

To set a variable use `variable_set()`:

```
variable_set('var_name', 'value');

```

To retrieve it, use `variable_get()`:

```
$var = variable_get('var_name', 'default');

```

To find the names of variables, the easiest method is to install the Devel module and visit the variable editor at /devel/variable

# Answer
> 1 votes
Users can register at your Drupal 7 site by default but you have to disable that. If you want to do this, just put following in your profile.install file:

```
// Only administrators can create user accounts.
variable_set('user_register', USER_REGISTER_ADMINISTRATORS_ONLY);

```

It would make sense to copy the standard installation profile to have a good base and then you just could add these two lines from above :)

---
Tags: configuration
---


# Question
Title: How do I set permissions for user roles in the install profile
I have a content type which I am creating on install profile, and I want to create a user that has permissions to edit that content type. How do I create user roles and permissions for those roles in the install profile?

# Answer
To add a role you can use `user_role_save()`:

```
$role = new stdClass();
$role->name = 'role_name';
$role->weight = 5;
user_role_save($role);

```

To grant specific permissions to a role you can use `user_role_grant_permissions()`:

```
$grant = array('access content', 'access comments', 'etc...');
user_role_grant_permissions($role->rid, $grant);

```
> 3 votes

---
Tags: nodes, installation, users
---


# Question
Title: Is there a way to display some content fields in a separate block?
I would like to display some content fields in a separate block so that I can manage the position of these like other blocks and also put them near to other blocks such as the search widget.

I am using display suite for laying out the content but don't think that this will serve my requirement to position some content fields further away from the the main content. One specific example I have is displaying the content's taxonomy fields below the search widget (which is in a block).

# Answer
> 1 votes
Oh no! Please no Field Blocks or CCK Blocks or Views. Just use Display Suite and enable the "Display Suite Extras" module so that you can create DS Regions. With DS Regions it's possible to create a new region which is exposed as a block.

# Answer
> 2 votes
You could create a view which selects the field you want from a node. Use contextual filters to get the Node Id in your view.

# Answer
> 2 votes
Field as Block is a really simple module that lets you display fields in blocks.

Beyond that, you may want to investigate Panels (and related modules) which is a much more powerful but also much more complicated solution.

---
Tags: 7, theming, nodes, entities, blocks
---


# Question
Title: How to embed a block (with title) in a template file?
I've created some blocks (not related to any other module, just through the "add block" option) and I am attempting to call them in the correct places in my homepage template.

I found the following code:

```
$block = module_invoke('block', 'block', 'view', '1'); //where 1 is block delta
print $block['content'];

```

But this only allows me to display the block content. Is there a way to get the block title too? I did find some people using $block\['title'\] or $block\['subject'\] but my $block array only seems to have the content in and nothing else.

Apologies if this is a common question but I couldn't seem to find an answer for the life of me!

# Answer
http://drupal.org/node/26502 \- A nice write up on displaying a block using code. There are a couple of examples toward the bottom that show displaying the entire block (including the subject).

One in particular you could try, using Drupal's theme() function:

```
<?php
    $block = (object) module_invoke('[target_module]', 'block', 'view', "[target_block_ID]");
    print theme('block', $block);
?>

```
> 3 votes

# Answer
Above is a D6 answer, although the link supplied gives details on solutions for D6 and D7.

Try this for D7.

```
$block = (object) module_invoke('[target_module]', 'block_view', "target_block_ID]");
print theme('block', $block);

```
> 1 votes

---
Tags: 6, blocks
---


# Question
Title: How to add javascript library that does not need a module, but is required by modules?
I have a JavaScript library written for my project. It is just that - helper library without configuration. I don't like the idea of empty `.module` file loading each time. On the other hand, I need it to be versioned and I need to be able to require it in other modules, with version specification. Libraries API looks like a bit of overkill as my script is from the ground written for Drupal and is no way "external" - and using empty `.module` file would be easier and faster anyway.

So, what's the best practice to include JS-only code?

How to include a JavaScript library, with CSS, in Drupal 7 without using a module? is about JavaScript needed by theme, so it looks similar but is unrelated to my question.

# Answer
> 2 votes
A module is really the only appropriate place for something like that; Drupal doesn't provide any way of making a module dependant on a JS library. You can only make a module dependant on another module, so if you want to enforce a dependancy to your JS code you'll have to create a module to contain/reference it.

If you're worried about having an empty module file, don't be...to formalise your library and describe it to the system properly, most likely you should be implementing the core `hook_library()` anyway. Then your dependant modules can simply call

```
drupal_add_library('mymodule', 'library');

```

to add your library. Putting the JS library files themselves into the sites/all/libraries folder, and referring to them from `hook_library()`, would probably be the best solution.

---
Tags: javascript
---


# Question
Title: View to display nodes with lat long in proximity of specific lat long
I have a content type and it has a geolocation field which stores a lat long . If I create one node with some lat / long info, I need to look up / show a view of other nodes that have lat long information which is in the proximity of the former's lat long info. Any idea how to do this?

# Answer
> 3 votes
Geolocation Proximity seems to be exactly a solution for you. You will need to keep location data using Geolocation Field to benefit from it.

Current features are:

> * Views filter that can be used to filter entities (nodes, users, etc.) based on distance from a certain point (defined as lat/lng point). The input widget is very basic at the moment. Patches welcome...
> * Views field to display the calculated distance between the entity and a reference point (can be synced with filters' lat/lng values).
> * User-friendly input widget for exposed filters using Google's reverse geocoder

Big lacking features are:

* HTML 5 Geolocation input
* proximity SQL look ups

It's competitor is Get Locations module. It's a suite that uses Google Maps API. One of it's functions is:

> **Getlocations Search** which uses Google Geocoding on entered search terms and shows nearby locations. The search form is fully configurable with options for **setting the Search distance**, Distance units, Number of locations to show and Restrict the search to a content type.

Emphasis mine.

Last but not least, you can use Computed Field. It can be calculated on access, so it is perfectly possible to make PHP computed field displaying "distance from X" where X is defined on the fly. You will need to write computation in PHP, but you will not be tied to any particular metric.

---
Tags: location
---


# Question
Title: drush make: Specify subdir for make-files provided by contrib modules
Recently I started using `drush make` to pull in Drupal Core, all the required contrib-modules, themes and libraries.

One of the modules I use is the geshifilter-module. This module comes with it's own make-files, so when I run `drush make` to build my entire site, `drush` sees this make-file and also builds that to pull in all the dependencies for the geshifilter-module.

While this is really convenient, I have one small problem with this: I prefer to have all the contrib-modules in `sites/all/modules/contrib`, so I define my modules like this:

```
projects[geshifilter][subdir] = "contrib"

```

However, the make-file inside geshifilter doesn't specify this subdir, so as a result, `drush` downloads the dependencies to just `sites/all/modules` instead of `sites/all/modules/contrib`.

For the moment I have added some commands in my wrapper-script around `drush make` to move those dependencies to the contrib-folder after `drush make` has finished, but I'm wondering if it is somehow possible to override the subdir-property for make-files which are provided by modules (obviously without manually modifying those make-files). I'm using drush 4.5 (default one from Ubuntu 12.04)

# Answer
This doesn't seems to be supported by Drush, you should consider reporting a feature request. The existing "Default path for projects, libraries" issue seems relevant too.

You may also consider reporting an issue for the GeSHi Filter module. Modules are not supposed to bundle a `.make` that download their dependencies. Usually, makefiles for modules are only used to download external libraries. The current makefile seems broken too since it download GeSHi as project while it should be downloaded as a library.
> 2 votes

# Answer
You can specify a default subdir for all projects this way:

```
core = "7.x"
api = 2
defaults[projects][subdir] = contrib
projects[] = views
projects[] = ctools

```

it is a very recent addition to drush 5, only available in the dev release.
> 8 votes

# Answer
here's a patch for the geshifilter make file to not interfere with your work flow https://drupal.org/node/1948852#comment-7602129
> 1 votes

# Answer
just a short notice for who it might concern:

chaining directories:

```
defaults[projects][subdir] = "contrib/projects"

```

or

```
projects[admin_menu][subdir] = "contrib/core"

```
> 0 votes

---
Tags: drush
---


# Question
Title: Custom DatabaseConnection driver does not get found by drupal!
I need to customize a method on the DatabaseConnection\_sqlsrv (MSSQL) driver, so i created a new driver class called DatabaseConnection\_sqlsrvseed and extended all depended classes from the \*_sqlsrv classes.

```
class DatabaseConnection_sqlsrvseed extends DatabaseConnection_sqlsrv {
  public function driver() {
    return 'sqlsrvseed';
  }
  public function databaseType() {
    return 'sqlsrvseed';
  }
}

```

Basically all other classes in the database/sqlsrvseed folder are empty classes that inherit their functionality from their parents like this one:

```
class InsertQuery_sqlsrvseed extends InsertQuery_sqlsrv {}

```

I am doing this because i need a modification on `createFieldSql` in `DatabaseSchema_sqlsrv` to create IDENTITY fields with a Seed value.

However, whenever i set

`$database['default']['default']['driver'] = 'sqlsrvseed'`

i get the error:

> Fatal error: Class 'DatabaseConnection\_sqlsrvseed' not found in C:\[...\]\includes\database\database.inc on line 1686

Although i am pretty sure that the class and all dependencies exist.
I did excactly everything like they did it in the sqlsrv driver:

> Drupal and the SQL Server driver Uncompress Drupal in the web root. Uncompress this driver as sites/all/modules/sqlsrv, and copy or link the sqlsrv directory found inside it in includes/databases.

So I copied the files from database folder as well as the module folder. But there is a strange difference. I can't activate my custom driver module, whereas i can activate sqlsrv one. Any help? How does drupal gets to know this driver, without core modification?

# Answer
> 0 votes
It looks like Drupal's autoload failed. For it to work you should put your classes in `.inc` file in your module, and then mention it in `files` line of module's `.info` file.

If that does not help and your classes are needed even earlier, include them in your `settings.php`:

```
require_once('path/to/module/sqlsrvseed.inc');

```

---
Tags: 7, database
---


# Question
Title: How can I set up roles and allow users to choose which role to be?
I have some users and I want to offer them the chance to choose their role which will have different permissions settings? How can I include a field on their user profile to allow them to choose the role? Is having a select list and then check that value the best option or is their a module that takes care of this kind of 'roles and responsibilities' stuff. For example, there is a 'facilitator' role which I want to give more permissions with regards to messaging users.

# Answer
There is a module that is supposed to cover that https://drupal.org/project/autoassignrole.

Or if you want to make it supper slim, you can add custom code to add dropdown with existing roles to account edit form and update user account on form submit.
> 1 votes

---
Tags: users
---


# Question
Title: Can I use entityreference module with my custom entity to display it?
I've attached a new entityreference field to users that referenced my custom entity type, say it's called `my_entity`. When I `dpm()` the user or view the tokens, I can see my custom entity properties (id, name, etc) but when I view the user I do not see the field label or the entity label.

I threw a `dpm($items)` into `hook_field_formatter_view()` inside `entityreference.module` and discovered that there are 0 items available to be displayed, but they are available in many other places! (as described above)

In `hook_entity_info()`:

```
<?php
return array('my_entity' => array(
  'label' => t('My Entity'),
  'controller class' => 'MyEntityController',
  'base table' => 'my_entity',
  'uri callback' => 'my_entity_uri',
  'load hook' => 'my_entity_load',
  'fieldable' => FALSE,
  'label callback' => 'my_entity_label',
  'entity keys' => array(
    'id' => 'id',
    'label' => 'name',
  ),
);
?>

```

I tried just setting the `entity keys['label']` to the schema field, which is supposed to be adequate to set the label, but I also tried `'label callback'` and even setting up the bundle info, which is not necessary for my entity.

I've also tried adding the property into `hook_entity_property_info()` in the hope that it would be "made aware" to other modules, but no luck:

```
<?php
return array('my_entity' => array(
  'properties' => array(
    'name' => array(
      'label' => 'Name',
      'type' => 'text',
      'schema field' => 'name',
    ),
  ),
);
?>

```

Any ideas?

# Answer
> 1 votes
I figured this one out. Entityreference runs `entity_access()` before returning `$items`:

```
$items[$id][$delta]['access'] = entity_access('view', $field['settings']['target_type'], $target_entities[$item['target_id']]);

```

To get this working, you need to set the `'access callback'` property in `hook_entity_info()`, which is an extended property that is checked by `entity.module`, not by core's entity functionality. So, for example:

```
<?php
return array('my_entity' => array(
  'label' => t('My Entity'),
  'controller class' => 'MyEntityController',
  'base table' => 'my_entity',
  'uri callback' => 'my_entity_uri',
  'load hook' => 'my_entity_load',
  'fieldable' => FALSE,
  'label callback' => 'my_entity_label',
  'access callback' => 'my_access_check',
  'entity keys' => array(
    'id' => 'id',
    'label' => 'name',
  ),
);

function my_access_check($op, $entity, $account, $entity_type) {
  // ...do something
  return TRUE;
}
?>

```

---
Tags: 7, entities
---


# Question
Title: Which module will allow a user to grant another user permissions for editing content of content type
I have a content type of 'project' and I want the creator of this content type to be able to allocate other users to be 'admins' on this project, so they have extended rights to edit the project details, archive the project, approve users attached to that project. Is there a module that sounds like it can achieve some of this stuff? thanks

# Answer
If those are existing permissions on your site already and you just want to control delegation, it sounds like you might want the Roleassign module.

> RoleAssign specifically allows site administrators to further delegate the task of managing user's roles while withholding the Administer permissions permission.
>
> RoleAssign introduces a new permission called Assign roles. Users with this permission are able to assign selected roles to still other users. Only users with the Administer permissions permission may select which roles are available for assignment through this module.

If that is not sufficient for your needs, a combination of Roleassign and Workbench Access would likely serve your needs.

> Workbench Access creates editorial access controls based on hierarchies. It is an extensible system that supports structures created by other Drupal modules.
>
> When creating and editing content, users will be asked to place the content in an editorial section. Other users within that section or its parents will be able to edit the content. A user may be granted editorial rights to a section specific to his account or by his assigned role on the site.

A combination of these two modules would likely be more than adequate for your purposes.
> 2 votes

---
Tags: users, nodes
---


# Question
Title: Add classes to programmatically added fields
I have programmatically created a few content types and fields for said content types in a module I'm building, but I need to add classes to said fields.

So if I have a text field called "background\_color", I would like to add a class to it called "color-picker".

Im added the instance of the field to my bundle like:

```
...
    'background_color' => array(
        'field_name' => $fields['field_background_color']['field_name'],
        'label' => 'The stroke color',
        'bundle' => 'nji_map',
        'entity_type' => 'node',
        'attributes' =>array('class'=>array('minicolors')),
        'widget'      => array(
            'type'    => 'text_textfield',
        ),
        'display' => array(
            'default' => array(
            'label' => 'above',
            'type' => 'text_textfield',
            ),
        ),
        'description' => 'The background color is the color between.',

    )....

```

Edit - Here is more of my code (node the full code snippet because there are too many fields)..

```
        $fields = array(
        'field_map_background_color' => array(
            'field_name' => 'field_map_background_color',
            'type' => 'text'
        ),...

$instances =  array(
    'background_color' => array(
        'field_name' => $fields['field_map_background_color']['field_name'],
        'label' => 'The background color',
        'bundle' => 'nji_map',
        'entity_type' => 'node',
        'attributes' =>array('class'=>array('minicolors')),
        'settings' => array(
            'prefix' => '<div class = "minicolors">',
            'suffix' => '</div>',
        ),
        'widget'      => array(
            'type'    => 'text_textfield',
        ),
        'display' => array(
            'default' => array(
            'label' => 'above',
            'type' => 'text_textfield',
            ),
        ),
        'description' => 'The background color is the color between.',

    ), ....

  foreach ($fields as $field) {
    field_create_field($field);
  }

  foreach ($instances as $instance) {
    field_create_instance($instance);
  }

```

# Answer
> 0 votes
Do something like this to wrap this field in a DIV class --

```
...
    'background_color' => array(
        'field_name' => $fields['field_background_color']['field_name'],
        'label' => 'The stroke color',
        'bundle' => 'nji_map',
        'entity_type' => 'node',
        'attributes' =>array('class'=>array('minicolors')),
        'widget'      => array(
            'type'    => 'text_textfield',
        ),
        'settings' => array(
          'prefix' => '<div class = "my_field_div_class">',
          'suffix' => '</div>',
        ),
        'display' => array(
            'default' => array(
            'label' => 'above',
            'type' => 'text_textfield',
            ),
        ),
        'description' => 'The background color is the color between.',

    )....

```

You would notice I have added **settings** along with other properties of the instance, where we can add `prefix`, `sufix`, `min`, `max` etc. I hope it works..

---
Tags: 7, entities
---


# Question
Title: Drupal 7: can't get ckEditor module configured for inline editing
Drupal 7: I using ckEditor module for editing within the textarea fields and I noticed on the ckeditor website that you can do inline editing like: http://ckeditor.com/demo#inline

I can get the ckEditor module to work for regular editing but I can't seem to get it configured for inline editing like the demo listed above.

# Answer
> 2 votes
I believe you need Quick Edit, which is the Drupal 7 backport of the Spark core initiative for Drupal 8.

---
Tags: wysiwyg
---


# Question
Title: PAReview.sh error, Expected "switch (...) {\n"; found "switch(...) {\n"
In my theme's template.php file, I have a custom function as:

```
function _MYTHEME_content_grid($columns = 1) {

  $class = FALSE;
  switch($columns) {

    // No sidebars, just content.
    case 1:{
      $class = 'grid-100';
      break;
      }

// etc...

```

When I run the code through http://ventral.org/, I get this message in regard to the switch statement line: `switch($columns) {`

```
ERROR | Expected "switch (...) {\n"; found "switch(...) {\n"

```

I googled around but I can't really find anything on this error. My function works perfectly fine though. I'm guessing it's a syntax error but it would seem weird to insert a `;` after the curly brace...

# Answer
The error says it all.

Put `switch ($columns)` instead of `switch($columns)`

> Control statements should have one space between the control keyword and opening parenthesis, to distinguish them from function calls.

For more info refer Drupal coding standards
> 3 votes

# Answer
Put simple switch, why put curly braces.

```
    function _MYTHEME_content_grid($columns = 1) {

      $class = FALSE;
      switch($columns) {

        // No sidebars, just content.
        case 1:
          $class = 'grid-100';
          break;
        case 2:
          //something
          break;

       // etc...
     }
   }

```
> 3 votes

---
Tags: coding-standards
---


# Question
Title: OG, IMCE, CKEditor, and Private files: 404 Images not found
I use Organic Groups, alongside IMCE and CKEditor.

In one content type, I have a text-field that the client will use to add some text and an image. Lets call this content type "**Team Match Analysis**" -\> which is a group content type for the group type of "**Teams**." Thus, we have a **team** named **Arsenal**, with a page of their most recent match analysis.

However whenever I try to add an image via the CKEditor from the OG content type (**Team Match Analysis**), the image is uploaded correctly (but to the users' private area) and then a blank box is shown on the preview.

If I try going to the link it provides (direct link), then it is always a 404 NOT FOUND page error.

I don't know why it's not working, the private Drupal files are in another folder away from /var/www/ and I have chmod set to 775 for the private\_drupal folder.

I know the private files work fine, since I have a File field for uploading PDFs which is set as "private files" but that uses the Multi-upload widget and not CKEditor to upload. That works fine, as the PDF files can only be accessed for people that are in the group.

Ideally what I need is to either set the image uploader/browser for CKEditor to use the "public profile" or find a way so that all the images that are uploaded are shared with the people in the same group and ensure that they can be displayed as an inline image with the tag for the multi-line text field.

**UPDATE: 26/06/13**

I can upload images (using CKEditor) but I can't preview or view them directly. It seems that CKEditor always uses the "private" profile which I've just set to be /private directory (and /public for public directory). All uploaded images are shown as "Not Found" when you try to go to the link, so it's something to do with Drupal not understanding that it needs to load/map the private files directory?

Strange since the "File" fields for PDF work fine.

**UPDATE: 28/06/13**

I assume it must be something to do with the database not being correctly updated when the image is uploaded in the IMCE widget (which is a pop-up when you click on the Add Image icon in the WYSIWYG - CKEditor toolbar for the text area field).

I have the images uploaded to "system/files/groups/**group name**/". If I browse to that directory, I get the Access Denied page from Drupal. However if I go to the direct link for the image which would be: "system/files/groups/**group name**/***image***.png" - then I get the "404 Not Found" page (which I assume is from the fast\_404 module I have installed).

**UPDATE: 1/7/13**

Here's a list of all the modules: http://pastebin.com/vt2g1aPB

My private folder is: /var/private\_drupal

My IMCE profile is set to the default one, with rules to see /main as well as /groups/ - those folders were created correctly and I get the Access Denied if I try to view the directory at: /system/files/groups/ - if I try an invalid group name (i.e. something that doesn't exist) then it gives me the page not found error which is Drupal Themed suggesting it's not provided by the fast 404 module.

I have just tried to upload images to where I would normally upload PDF files and all images show up as the 404 Not Found page (blank, no Drupal Theme), however all the .pdf files work fine still. For my "PDF" field (which accepts images, pdf, docs, etc.) these files get uploaded directly to the private directory and not in any sub-folder. However since none of the images work there it seems to be something wrong with the image/media modules for image files?

I decided to use the WYSIWYG Image uploader button to upload a PDF file, obviously I won't be able to see anything but going to the direct link of the pdf file results in an Access Denied page by Drupal... which is strange since I am in the group and should have access to view that PDF file.

It seems even worse now, the JSON Feeds parser which was working fine and would import the images from the URL for the feed items but no longer works... I've tried removing all image related modules and starting again but no luck, and still no errors in the database log.

EDIT: Fixed the JSON Feeds parser, it now imports the images fine again and uses the Large image style (overridden), all those images are uploaded to the public folder.

I'm wondering if I can maybe "force" WYSIWYG to use the public folder instead of private but to not break the file fields that I use for PDF that need to be private?

# Answer
So I've decided to set the default download method to Public (it was Private), and now I can insert images just fine.

...and the PDFs still seem to be set to use the Private directory so that's not broken either.
> 0 votes

# Answer
If you are using Image Styles, you might be having a problem with core 7.20. To test this, try setting the variable `image_allow_insecure_derivatives` to true, either with Drush or settings.php.
> 0 votes

---
Tags: organic-groups, wysiwyg, files
---


title: Updating content types using Features

text:
# Question
Title: Updating content types using Features
If I have a series of existing content types in a website and I want to update those content types using a new Feature module (I added some fields), what is the correct method?

1. Add the entire node? Will this update the existing content type?
2. Add just the new and/or modified fields?

Also, these content types were originally created by hand and not by a Feature module. I just want to add the new fields using the Features module

# Answer
> 1 votes
With the newest version of Features, it makes it really easy to just add the fields of the content type to the feature. Features are not meant to hold content, like entire nodes. Here's a good example of a feature I've built.

(https://i.stack.imgur.com/rYC7l.png)

---
Tags: 7, features
---


# Question
Title: condition inside template.php (if logged_in/logged_out and else)
Is it possible to perform condition inside template.php (if logged\_in, do these...else do that/ do nothing)?

I am a front-end developer, and as a front-end developer, i like my code clean. So i'm cleaning up my drupal html source code output.

I found some modules out there, that help a lot, and one of then is HTML5 Tools and Metatag (thank you for the team developers). But even with those great tools, i still having the "Drupal.settings" in my html output.

Ocasionally, i found that i can remove the "Drupal.settings" from the html with the hook\_js\_alter :

> function MYTHEME\_js\_alter (&$js) { unset($js\['settings'\]); }

But the problem is: my logged in users still needing this "Drupal.settings" because some modules use it. So that's why i'm asking if there is a way to perform **condition inside template.php** to logged\_in/logged\_out users.

THank you in advance

# Answer
> 3 votes
This should help you out. Drupal user login - How to tell if a Drupal user is logged in (authenticated)

You can also use the utility variable **$logged\_in**: Returns TRUE if the user is registered and signed in.

**Updated answer.**

In **template.php**, you can use `global $user;` to check and see if someone is logged in.

```
global $user;
if (isset($user->roles[1])) {
  //Put code here.
}

```

Checking against Devel, you can see that `$user->roles[1]` means it's an anonymous user.

---
Tags: hooks, database
---


title: Content Types linked to Content Types

text:
# Question
Title: Content Types linked to Content Types
Using Drupal (v7.22) I'm creating a site that lists different cars. The editor of the site wants to be able to add different stats to the cars. But they don't know exactly which stats they will need so want the ability to add stat themselves. So for example they can set up two different stats where they fill in values:

```
Content
  Content Type (Stat)
  Title = Stat A
  Default Value = 10
  Min Value = 0
  Max Value = 50

Content
  Content Type (Stat)
  Title = Stat B
  Default Value = 20
  Min Value = 0
  Max Value = 40

```

Then they can add those stats to a new Content Type that they have created. When they add a type of Stat it will include the Default Value but it can be changed:

```
Content Type
  Title = Car
  Stat A Value = 10
  Stat B Value = 20

Content Type
  Title = Lorry
  Stat B Value = 30

```

Finally they can create Content of that Content Type and the Stats will use the value for that Stat by default but they can change it. I will create rules so that the entered values must be within the min/max set by the Stat.

```
Content
  Content Type = Car
  Title = Car Name
  Stat A Value = 15
  Stat B Value = 18

```

Can this be done with Drupal?

# Answer
> 0 votes
I'm hoping this answer works for you. If you're wondering if you can set a default value for a field in a content type when adding new content, the answer is yes.

---
Tags: entities, nodes
---


title: Keep Summary field deployed

text:
# Question
Title: Keep Summary field deployed
I'm using the node's Summary field for article teasers. Although not mandatory, this field is being constatly populated by content editors for article content types. I'm trying to make it visible instead of Drupal's default collapsed state, but I've hit a wall on identifying the related JS function and how to modify it without hacking core files.

Any idea on achieving the desired UI modification?

**EDIT:** OK, seems like the */modules/text/text.js* is the file in charge of adding the link that shows/hides the Summary field.

Since I don't want to simply comment out or edit core files, I think I'll have to make a custom module to unset this js file and not allow it to be loaded. I'm no JS expert but by looking into the code it seems to me that this file impacts only the text summary. Hence my updated question would be: are there any side effects to unset this file?

# Answer
For the default value for the field (under Field Settings), in the "Summary" field, you can put a blank " ". This will force the summary field to show up. If you want to do it the correct way, then you will have to check the Javascript that shows/hides the field.
> 1 votes

# Answer
You can also do this through template.php.

Functionality: Strip out any js that you specify in an array in your .info file:

```
function mytheme_js_alter(&$javascript) {
  $excludes = _mytheme_alter(mytheme_theme_get_info('exclude'), 'js');
  $javascript = array_diff_key($javascript, $excludes);
}

function _mytheme_alter($files, $type) {
  $output = array();

  foreach($files as $key => $value) {
    if(isset($files[$key][$type])) {
      foreach($files[$key][$type] as $file => $name) {
        $output[$name] = FALSE;
      }
    }
  }
  return $output;
}

```

Then in your .info file:

```
exclude[js][] = 'modules/field/modules/text/text.js'

```

All that text.js contains is the summary show/hide javascript. Without it, summaries always show.

You can alter these functions for css excludes as well (mytheme\_css\_alter), which is handy to clear out Drupal core crud :)
> 0 votes

---
Tags: nodes
---


title: Content types are missing in Features

text:
# Question
Title: Content types are missing in Features
I am trying to create a Features module and include my content types but not all of them are showing when I select "Content Types: node". I am seeing about 80% of them. Why would this be?

# Answer
> 5 votes
If you are using a distribution, etc., it may be the case that there are content types that are provided by another feature or custom module. These will not appear in the Features UI by default in order to prevent conflicts.

---
Tags: 7, features
---


# Question
Title: Selected file gets reset after clicking on +Add More button
am implementing a form and in that form it requires that two form element should be coming under one Add more button, so user can add any number of fields.

Here is the code which i am using to create a form.

```
function ajax_example_add_more($form, &$form_state, $no_js_use = FALSE) {
  $form['description'] = array(
    '#markup' => '<div>' . t('This example shows an add-more and a remove-last button. The <a href="!ajax">AJAX version</a> does it without page reloads; the <a href="!multistep">non-js version</a> is the same code but simulates a non-javascript environment, showing it with page reloads.',
      array('!ajax' => url('examples/ajax_example/add_more'), '!multistep' => url('examples/ajax_example/add_more_no_js')))
    . '</div>',
  );

  $form['#tree'] = TRUE;
  $form['names_fieldset'] = array(
    '#type' => 'fieldset',
    '#title' => t('People coming to the picnic'),
    '#prefix' => '<div id="names-fieldset-wrapper">',
    '#suffix' => '</div>',
  );
  if (empty($form_state['num_names'])) {
    $form_state['num_names'] = 1;
  }
  for ($i = 0; $i < $form_state['num_names']; $i++) {
    $form['names_fieldset'][$i]['name'] = array(
      '#type' => 'textfield',
      '#title' => t('Name'),
    );
    $form['names_fieldset'][$i]['surname'] = array(
      '#type' => 'textfield',
      '#title' => t('SurName'),
    );
    $form['names_fieldset'][$i]['filedepot_file'] = array(
      '#type' => 'managed_file',
      '#title' => t('Choose a file'),
      '#size' => 22,
      '#process' => array('_module_my_file_element_process'),
    );
  }
  $form['names_fieldset']['add_name'] = array(
    '#type' => 'submit',
    '#value' => t('Add one more'),
    '#submit' => array('ajax_example_add_more_add_one'),
    '#ajax' => array(
      'callback' => 'ajax_example_add_more_callback',
      'wrapper' => 'names-fieldset-wrapper',
    ),
  );
  if ($form_state['num_names'] > 1) {
    $form['names_fieldset']['remove_name'] = array(
      '#type' => 'submit',
      '#value' => t('Remove one'),
      '#submit' => array('ajax_example_add_more_remove_one'),
      '#ajax' => array(
        'callback' => 'ajax_example_add_more_callback',
        'wrapper' => 'names-fieldset-wrapper',
      ),
    );
  }
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  if ($no_js_use) {
    // Remove the #ajax from the above, so ajax.js won't be loaded.
    if (!empty($form['names_fieldset']['remove_name']['#ajax'])) {
      unset($form['names_fieldset']['remove_name']['#ajax']);
    }
    unset($form['names_fieldset']['add_name']['#ajax']);
  }

  return $form;
}

/**
 * Callback for both ajax-enabled buttons.
 *
 * Selects and returns the fieldset with the names in it.
 */
function ajax_example_add_more_callback($form, $form_state) {
  return $form['names_fieldset'];
}

/**
 * Submit handler for the "add-one-more" button.
 *
 * Increments the max counter and causes a rebuild.
 */
function ajax_example_add_more_add_one($form, &$form_state) {
  $form_state['num_names']++;
  $form_state['rebuild'] = TRUE;
}

/**
 * Submit handler for the "remove one" button.
 *
 * Decrements the max counter and causes a form rebuild.
 */
function ajax_example_add_more_remove_one($form, &$form_state) {
  if ($form_state['num_names'] > 1) {
    $form_state['num_names']--;
  }
  $form_state['rebuild'] = TRUE;
}

function _module_my_file_element_process($element, &$form_state, $form) {
    $element = file_managed_file_process($element, $form_state, $form);
    $element['upload_button']['#access'] = FALSE;
    return $element;
}

```

Now after adding file when i click on +Add More button at that time all the fields retains their values but filefield gets reset.

Here i am hiding the upload button so that file will be uploaded when user submits the form. After filing on fieldset when i click on +Add more button at that time selected files doesn't come in the appropriate form fields, where as other fields retains their values.

How can i fix the code so that selected file remains as it is in the respected fields.

# Answer
Problem is in `$form_state['rebuild'] = TRUE;` in your `ajax_example_add_more_callback()`. From my experience it sometimes is needed, and sometimes mess up values. So you could try to avoid it (point 1) or save values in a safe place before you rebuild, restore them after you rebuild (point 2).

1. Way I prefer to do it, if feasible, is to prevent submit on a button that's supposed. I used `$form_state['triggering_element']` in form building function to detect AJAX calls and decide what needs to be updated.

```
function ajax_example_add_more($form, &$form_state, $no_js_use = FALSE) {
  if ( $form_state['triggering_element'] == MY_AJAX_ADD_BUTTON ) {
    $form_state['num_names']++;
  }

```

That way you are not rebuilding form, so data has no opportunity to get discarded.
2. The way that would require less changes to you is to save already filled values in some kind of cache inside your add more submit handler, and then set them as defaults in form building function.

```
function ajax_example_add_more($form, &$form_state, $no_js_use = FALSE) {
  // (...)
  $form['names_fieldset'][$i]['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#default' => _mymodule_read_from_cache($i, 'name'),
  );
  // (...)
}

function ajax_example_add_more_add_one($form, &$form_state) {
  $form_state['num_names']++;
  $form_state['rebuild'] = TRUE;
  _mymodule_save_to_cache($form_state['values']);
}

```

This would require you to write `_mymodule_save_to_cache()` and `_mymodule_read_from_cache()` functions, but that's a way to prevent value loss during form rebuild. Not nice, maybe, but works.
> 1 votes

---
Tags: forms, ajax, files
---


# Question
Title: Changing the tite of your page to match the title of your tabs
I have the following function:

```
function cvminterviews_menu() {

  $items = array();

  $items['admin/settings/cvminterviews'] = array(
    'title' => 'Interview Schedule Overview',
    'description' => 'Overview',
    'file' => 'cvminterviews_admin_overview.inc.php',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('cvminterviews_overview_form'),
    'access arguments' => array('administer cvminterviews'),
  );

  $items['admin/settings/cvminterviews/overview'] = array(
    'title' => 'Overview',
    'description' => 'Overview',
    'file' => 'cvminterviews_admin_overview.inc.php',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('cvminterviews_overview_form'),
    'access arguments' => array('administer cvminterviews'),
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );

  $items['admin/settings/cvminterviews/setup'] = array(
    'title' => 'Interview Schedule Setup',
    'description' => 'Setup',
    'file' => 'cvminterviews_admin_setup.inc.php',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('cvminterviews_dateroomsetup_form'),
    'access arguments' => array('administer cvminterviews'),
    'type' => MENU_LOCAL_TASK,
  );

  return $items;
}

```

This outputs two tabs at the top of the page. However, when I click on each tab, it has the same page title as the parent menu item "Interview Schedule Overview".

**Is there a way to set unique page titles for each tab?**

# Answer
> 2 votes
You have to call

```
> 4.6 – 6   drupal_set_title($title = NULL)
> 7 – 8     drupal_set_title($title = NULL, $output = CHECK_PLAIN)

```

You'll have to change your code around a little

```
  $items['admin/settings/cvminterviews/setup'] = array(
    'title' => 'Interview Schedule Setup',
    'description' => 'Setup',
    'file' => 'cvminterviews_admin_setup.inc.php',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('cvminterviews_dateroomsetup_form'),
    'access arguments' => array('administer cvminterviews'),
    'type' => MENU_LOCAL_TASK,
  );

```

to

```
  $items['admin/settings/cvminterviews/setup'] = array(
    'title' => 'Interview Schedule Setup',
    'description' => 'Setup',
    'file' => 'cvminterviews_admin_setup.inc.php',
    'page callback' => '_cvminterviews_admin_page',
    'page arguments' => array(
      'variables' => array(
        'form' => 'cvminterviews_dateroomsetup_form',
        'title' => t('my_title')
      )
    ),
    'access arguments' => array('administer cvminterviews'),
    'type' => MENU_LOCAL_TASK,
  );

function _cvminterviews_admin_page($variables = NULL) {
  if(isset($variables['title'])) {
    drupal_set_title($variables['title']);
  }
  if(isset($variables['form'])) {
    return drupal_get_form($variables['form']);
  }
}

```

Then do the same thing for `$items[admin/settings/cvminterviews']` & `$items['admin/settings/cvminterviews/setup']`

When you are changing your code, there is one more problem that you will need to aware of.

There will be 2 tabs on admin/settings/cvminterviews, one that will be active 'Overview' and 'Interview Schedule Setup'. 'Overview' will link to admin/settings/cvminteviews NOT admin/settings/cvminterviews/overview. admin/settings/cvminterviews/overview will never be called (unless you type that it into the address bar) because it is the default tab set by `'type' => MENU_DEFAULT_LOCAL_TASK`.

# Answer
> 1 votes
I used this code (in my function that set the breadcrumb but this could be used in a page callback too)

```
<?php
// get current menu item informations. This contain the title of the tab.
$item = menu_get_item();
// use it as page title.
drupal_set_title($item['title']);
?>

```

# Answer
> -1 votes
I believe in general you tend to keep the same title when using local tasks - the tasks themselves are meant to be actions you can perform on some common object/area, so in that case it does kinda make sense to keep the same title whichever local task you're on.

---
Tags: routes, 7
---


# Question
Title: How to define content within a custom region?
I'm new to Drupal and I'm only learning. I'm required to add a custom region to my site. I understand what I must add in the .info file and set from Structure \> Blocks to make it show up. What I don't understand is where do I write the content for my "custom region block"?

Say I've a region I want to call "my\_region". What do I do to actually define how the "my\_region" is supposed to look like?

I've tried various online reference sites and most of them just show me how to do this -

```
regions[header] = Header

```

and this-

```
        <?php if ($page['header']): ?>
        <?php print render($page['header']); ?>
        <?php endif; ?>

```

I know all that. What I don't know is how to make regions\['my\_region'\] work.

Any references to tutorials or guides would be deeply appreciated. Thank you

EDIT:

I've set up a region in the info file as `regions['my_region'] = MyRegion`. Now I'm clueless as to where to add the contents that goes in `regions['my_region']` or any other custom content that I define?

Example: If I want `regions['my_region']` to include a slideshow, where do I actually create the file containing the slideshow that `regions['my_region']` refers to?

# Answer
> 0 votes
Regions are nothing more than a block holders. To add content to a region, go to http://example.com/admin/structure/block *(substitute example.com with your real domain of course)*, and just drag and drop slideshow block to "MyRegion" region.

---
Tags: blocks
---


title: Manage statistics with drupal

text:
# Question
Title: Manage statistics with drupal
I have a site that get statistics on products. I get data from an external source to update the Drupal DB to register a buy on a product and the date of that buy to be able to show a flowchart over that product.

I need this statistics for showing the development of the products selling rate. So if one customer buys a product that information will be sent to my Drupal DB, and that's where I wonder how I should construct my DB so it is optimal in speed and storage. Is it a good idea to create a content type that has a product entity reference and a date? So when a product is bought a new node is created that holds the date and product as information.

# Answer
Your data should not be nodes, as they do not keep any readable content on their own, they only make sense in connection to a product and in statistics, summaries et cetera, and shouldn't really be displayed on their own. So, you have two ways of dealing with them:

1. Bad way - make them just a multi-value field in product content type. Not optimal for storage, not really good for filtering.
2. Make them entities. You only need creation date and product reference on them. Making them entities will expose them to Views for easy filtering and aggregation, to search api if you will ever need to sort by "most sold", and, well, to each and every module that knows about entities. There are many answers and tutorials out there. Hint - your entity should not be a fieldable one. Non-fieldable entities always have only fields defined at creation, so storage is much simpler for them. And simpler == faster.
> 0 votes

---
Tags: nodes, log-messages
---


# Question
Title: Is it possible to record user agent information on node creation?
I have a custom content type, **Picture**, which has only a single required image field. Since this field is required, I thought that it should be impossible for users to save a node without uploading a file, but every once in awhile there is a node created that has no file uploaded.

Users have permission to create nodes of type **Picture** but not to edit them.

To try to troubleshoot this problem, I would like to record the user agent information (browser, etc.) of users when they create nodes of this content type. Is there a "standard" way to go about this?

I'm on Drupal 7 if it matters.

# Answer
I would probably use a combination of `hook_node_insert` and `watchdog` (to keep UA info off of nodes and because it is really a logging exercise).

Example (this is totally untested and off the top of my head):

```
function MYMODULE_node_insert($node){
  if ($node->type == 'MY_NODE_TYPE') {
    // Check for the empty value however you want here.
    // e.g. Field API, EntityMetaDataWrapper, or whatever
    if (!isset($node->field_MY_IMAGE_FIELD[$node->language][0])) {
      $user_agent = $_SERVER['HTTP_USER_AGENT'];
      $account = $_GLOBALS['user'];
      $message = t('Empty image field created by !uid using !user_agent',
        array('!uid' => $account->uid, '!user_agent' => $user_agent));
      watchdog('MYMODULE', $message, WATCHDOG_NORMAL);
    }
  }
}

```
> 2 votes

---
Tags: nodes
---


# Question
Title: What's the easiest way to create CRUD interface for custom entities?
What is the fastest way to create admin UI for new entity type? Like at content types. I just need basic list/add/edit/delete actions.

One would think this comes with entity api?

I have found a lot of solutions but all of them included a lot of custom code, which is prone to errors.

is DrupalDefaultUIEntityController the answer? how can one use it?

# Answer
The Entity Construction Kit (ECK) module allows you to create and manage entities through admin.

Here is a quote about it (from the module's project page):

> ... builds upon the entity system to create a flexible and extensible data modeling system both with a UI for site builders, and with useful abstractions (classes, plugins, etc) to help developers use entities with ease.
>
> ECK allows the creation and management of entity types with custom properties; adding bundles to entity types; and fields to bundles, with the help of the Field UI module.
> 5 votes

# Answer
This article looks like a manual for exactly what you need. Basically it describes how to use Entity API module, and extend `EntityAPIController` class to use it's strength but tailor it to your needs.

Example on Drupal.org shows simplest case, without even extending this class, as follows:

> The EntityAPIController automatically provides you with your\_entity\_type\_insert/update/delete/pre\_save hooks. If your entity is defined to be fieldable, EntityAPIController invokes the field API attachers for you. You only have to write the API docs yourself. For that you may make use of this API documentation template. Also note that schema fields marked as 'serialized' are automatically unserialized upon loading as well as serialized on saving.
>
> A simple example hook\_entity\_info() implementation could look like the following:

```
<?php
/**
* Implements hook_entity_info().
*/
function entity_test_entity_info() {
  return array(
    'entity_test' => array(
      'label' => t('Test Entity'),
      'entity class' => 'Entity',
      'controller class' => 'EntityAPIController',
      'base table' => 'entity_test',
      'entity keys' => array(
        'id' => 'id',
      ),
      // Make use the class' label() and uri() implementation by default.
      'label callback' => 'entity_class_label',
      'uri callback' => 'entity_class_uri',
    ),
  );
}
?>

```
> 4 votes

# Answer
The Model Entities module would probably be an excellent place to start - it contains code to get you started with a custom entity, including the admin interface.

> The objective of this module is to provide a model entity *and* entity administration interface to kick-start your entity development.
> 2 votes

---
Tags: entities
---


title: Create OG group on registration

text:
# Question
Title: Create OG group on registration
I have different registration pages for different user roles in drupal, for some users i would like them to be able to create an OG group when there accounts is created.

I have a field in the registration form for group name which i would like to be used in creating the new group.

Im sure this is something you can do with rules but i cant seem to find any good tutorials on seeting it up any help appreciated

# Answer
Use this module http://drupal.org/project/uc\_node\_checkout

You can assign a node/content type to a product in uber cart, so once a visitor has selected a product in the cart they can create an og group node.

for my needs I then just used rules to make the group unpublished until the visitor had a fully paid for the role in the ubercrt
> 1 votes

# Answer
Hope this will help you,

In Drupal 7, after user registration form submit you can create the group.

For this example I'm using **hook\_form\_FORM\_ID\_alter**

* After the configuration of **Organic groups** and **creating group content type**(machine name is **groups**) using **admin/structure/types/add**

```
/**
 * Implement hook_form_user_register_form_alter().
 */
function test_form_user_register_form_alter(&$form, &$form_state) {
  $form['#submit'][] = 'create_group_on_user_registration';
}
/**
 * Custom submit function for user registration form
 */
function create_group_on_user_registration($form, &$form_state) {
  $usr_obj = $form_state['user']; //get registered user object
  if (is_object($usr_obj) && isset($usr_obj->uid) && (your_conditions)) {// dont forget to add your conditions
    $bodytext = "group body";
    $author_id = 1;//you can change author id, i'm making admin as author
    $node = new stdClass(); // Create a new node object
    $node->type = "groups"; // Group content type
    node_object_prepare($node); // Set some default values
    $node->title = "group title2";
    $node->language = LANGUAGE_NONE; // Or e.g. 'en' if locale is enabled
    //for author id I have given admin, you can give any other user id,
    //but  that user should have permission to create group cotent type
    $node->uid = $author_id; // UID of the author of the node; or use $node->name
    $node->body[$node->language][0]['value'] = $bodytext;
    $node->body[$node->language][0]['summary'] = text_summary($bodytext);
    $node->body[$node->language][0]['format'] = 'filtered_html';
    if ($node = node_submit($node)) { // Prepare node for saving
      node_save($node);//$node->nid will have node id
    }
  }
}

```
NOTE :  * Go through all comments
* Make changes as per your requirements
> 1 votes

---
Tags: 7, rules, organic-groups, users
---


title: Views contextual filters by node title

text:
# Question
Title: Views contextual filters by node title
I've created a content type: **seller** and with pathauto module I've set this content type to be **seller/\[node:title\]** so every new seller content will be **www.example.com/seller/\[name\_of\_the\_seller\].**

I want to add gmap objects in every seller page with only their objects will be visible. (for this detail I'll open a new thread, 'cos I'm not sure how to filter that)

With Views module I've added a page with url: **/seller/%**

and in contextual filters I've added **Content: Nid**. In **When the filter value is NOT in the URL** I've selected **Provide default value** and in the field bellow I've put **seller**. That didn't worked, so I've tried with **Raw value from URL** and checked **Use path alias**. That didn't worked too. I've searched couple of other threads, but I didn't find like my problem.

UPDATE

I've solved the problem by creating a block that is displayed seller/\*. The two content types has a same taxonomy terms and with contextual filters **Content: Has taxonomy term ID**, **Provide default value**, **Taxonomy term ID from URL**, I've marked **Load default filter from node page, that's good for related taxonomy blocks** and **Limit terms by vocabulary** and I've selected the **seller** taxonomy.

# Answer
I've solved the problem by creating a block that is displayed seller/\*. The two content types has a same taxonomy terms and with contextual filters **Content: Has taxonomy term ID**, **Provide default value**, **Taxonomy term ID from URL**, I've marked **Load default filter from node page, that's good for related taxonomy blocks** and **Limit terms by vocabulary** and I've selected the **seller** taxonomy.
> 0 votes

# Answer
Since your contextual filter is expecting an **nid** (you said your contextual filter is set up as '**Content: Nid**') - you really have to provide it with an nid even when that filter is not present in the URL. You can't give it 'seller' as an argument or anything like that because that's not an nid, so it won't help it pull up the correct node.

So to get it to work in those cases, what you really want for your view to do is grab the nid of the current node it appears on. It's OK if that page has a custom URL, the nid can still be gotten.

Just select '**Content ID from URL**' as the default value when an URL argument doesn't exist! That'll work even if it has a custom alias for the URL.
> 2 votes

---
Tags: nodes, views
---


# Question
Title: How to identify where a particular block come from?
I have to modify a block that appears on the home page of the website, that I did not make myself. The block appears in `admin/build/block` with the title "Block Title (nodeblock)", so I assume that this has been created by the nodeblock module, but I can't find where I can edit this content.

Can someone help me to find the right administration menu to view and modify this nodeblock content ?

# Answer
UPDATE:

It appears from a quick look at the module source that `nodeblock` uses the node's nid as the block delta.

So, from `admin/build/block` if you click on the `configure` link on the block in question, it should take you to something along the lines of `admin/build/block/configure/nodeblock/###`. That trailing `###` is the nid of the node in the block. So then off you go to `node/###/edit`.

OTHERWISE:

If this is just a one-off thing, a quick look at the default `node-nodeblock-default.tpl.php` template for creating these blocks shows...

```
<div id="node-<?php print $node->nid; ?>" class="node<?php if ($sticky) { print ' sticky'; } ?><?php if (!$status) { print ' node-unpublished'; } ?> clear-block">

```

...so I would just surf over to your home page, and then take a peek at the source generated in your browser, and there it should show a `<div>` wrapping this block with an `id` of `node-###`.

Then, going to `node/###/edit` should take you on your way.
> 2 votes

# Answer
The easiest way for Drupal 6 would probably be to use the Contextual links module.

> Hover over nodes, blocks, and views blocks to expose styled edit/configure/delete tabs.

It's a backport of the same functionality that is in D7 core, but for Drupal 6.

Just hover over the block on the front page, and hit edit to edit that particular block.
> 2 votes

---
Tags: 6, nodes, blocks
---


title: Why can't I disable a module?

text:
# Question
Title: Why can't I disable a module?
I installed Drupal Chat just to try it out. I couldn't get it to work and now I can't disable the module.

In /admin/modules, the check box is selected but not enabled. i.e. it is active and I can't deactivate it.

Can anyone help me?

(and, once disabled, how can I un-instal it?)

---

Update: I forgot to mention that there are no dependencies on the module.

# Answer
usually if conventional uninstall wouldn't work i'd try clearing the module's entry from system table removing tables from the module installation (after backing up the data) clear the cache and reinstall.. hope it works for you ...cheers!!
> 6 votes

# Answer
Other modules might be dependent on it. For example, if you also enabled Drupal Chat Notifications, you would need to disable that first.
> 6 votes

# Answer
I agree with adam; however, if you are using Drush on your server, typing in "drush dis drupalchat" will return a notification of the dependencies, and will allow you to disable them. Make sure to delete the module folder and update your database.
> 4 votes

# Answer
If dependencies are not an issue then may be the module may have been corrupt . Try reinstalling and then uninstalling the module..
> 3 votes

# Answer
This answer is more general than DrupalChat module. Some modules install content types and field types. My solution is for Drupal 7.x. It's likely similar on other versions. To disable:

BE SURE to back up the data base before doing these steps.

1) go to .../admin/structure/types. Look for the content type associated with the module. If it's not there, *this is not the solution*.

2) if there is such content click on manage fields. Remove any field that is also associated with the module. You have to agree to the "this cannot be undone warning".

3) back to admin/structure/types and remove the content type. Again agree to "this cannot be undone warning".

4) go to ../admin/modules and disable the module.

This should work. You may have to work through additional required by modules and any content and fields that those modules added. (Lather, rinse, repeat.)
> 1 votes

---
Tags: 7, installation
---


title: How to find correct hook/preprocessor

text:
# Question
Title: How to find correct hook/preprocessor
Aside from searching the Drupal api, is there a module or an easy way that will allow you to find out which hook or function you need to use to interact with pages in your site?

For example, I am looking to force certain values in a webform setup, to which I was able to use `mymodule_form_webform_configure_form_alter` to change the submission limit, status etc. But I was able to do this because I found the starting point for the script, now I am looking to force a default 'email to' value in the setup, but I don't know what function I need to use

What's the best way of finding out the best hook (etc..) for the job

Kind regards

# Answer
I find the Devel Themer module to be very helpful.

From the description:

> popup display shows which theme function/template outputted the HTML, and what other files could have done so.
> 2 votes

---
Tags: 7, hooks, theming
---


title: Calendar Views: Upcoming or Recent

text:
# Question
Title: Calendar Views: Upcoming or Recent
I'm currently using the default calendar views "Upcoming" block to display upcoming events on my homepage. However, because events are infrequent, its common for there to be no upcoming events. In which case, the block disappears and leaves a big blank spot in the home page.

Is there way to show either the next four events OR the last four events? For example, if there is only one upcoming event, it would add the last three events to the list and display all four in ascending order.

Thanks!

# Answer
FYI, here is how I solved it. Thanks Rock, for the step in the right direction!

Overview: Used a custom module that creates a block that displays one of two view displays.

1. Programmatically created a view (hook\_views\_api, hook\_views\_default\_views) with two displays: one that shows upcoming events (ascending order, up to 4 items without a pager), and one that shows the last four events in the database (descending order, 4 items without a pager)
2. Programmatically created a block (hook\_block\_info) that displays (hook\_block\_view) one of the two view displays based on the number of results in the "Upcoming" display ( $results = views\_get\_view\_result('view\_id', 'display\_id');).
3. Created a custom template file (views-view-unformatted--view-id--display-id.tpl.php) for the second display, which reverses the order of results so that they are still displayed with earliest date first.
> 0 votes

---
Tags: views, datetime
---


# Question
Title: Does views load all nodes in a result or just the ones in each page of results?
I am trying to determine if I am going to see a performance impact. I have a view that can possibly return thousands of results but only displays 50 per page. Each node in the result determines it's proximity to the current user using geofield. I want to know if it's going to try and do it for every node in the result, or just the ones in the current page.

So, does Drupal load all of the nodes in the results or just the ones in the current page?

# Answer
When you display a certain number of records per page it does not load and hide the extra records, it simply never pulls them from the database. So you'd certainly be *helping performance* by limiting the number that are displayed per page.

In fact, if you look at the SQL query generated by the view, it'll say the following if you're showing 20 items per page, for example:

```
...
LIMIT 20 OFFSET 0
...

```

====================== EDIT ====================

**What this means for performance**

As @Clive and I were discussing above in the comments, A LIMITed query will inevitably be faster than one with no LIMIT, but overall performance will also inevitably decrease as the number of nodes you are searching through increases.

Limiting the number of returned records has performance savings on the Drupal side too, though. That's because Drupal wouldn't be running the additional processing on the Drupal side to do things like access checks, pre-processing and other display-related functions for the records that aren't returned by the query.

==============================================

p.s. You can configure whether you want Views to show you the sql query it's generating by going to /admin/structure/views/settings and checking the '**Show the SQL query**' checkbox in the 'Live Preview Settings' section.
> 4 votes

---
Tags: views, performance, database
---


# Question
Title: Emails sent by actions not using html email formatting
I have the HTML email module and it is working for most site emails, however those that are called by actions/triggers don't use the template. How I can I force this behaviour?

# Answer
When you build an action on the settings page (/admin/config/system/actions) you have 2 options. One is 'send e-mail' and the other is 'send HTML e-mail'. 'Send e-mail' is plain text only, as where 'send HTML e-mail' allows the use of HTML templates. Make sure you are using the 'send HTML e-mail' action.
> 1 votes

---
Tags: 7, emails, actions
---


# Question
Title: Can I check a user is logged in using Services
I need to be able to integrate an external PHP script with Drupal 7. However because the script also connects to a MySQL database errors are produced when I include the `bootstrap.inc`, so I'm looking at using the Services module. Will this allow me to determine if the user is logged in to Drupal, and if so get details about the user? If so, could you please show me how this could be done.

Also, is it possible to secure the server/service so that it can only be accessed by scripts on the same host?

# Answer
Services module works with the entity system so you should be able to pull some user data out of the box like email, username etc. I'm not exactly sure if Services modules send you any clue about user data that you can use to determine if the user is online or not but you can add a small custom code that alter the read functionality of the Services for User entity to query and return the current session. See code sample below.

Couple of function you might need in the process is:

```
// you can alter the resources object and use your own
hook_services_resources_alter()

// implement it as below in your custom module
function YOURMODULE_services_resources_alter(){
  $resources['user']['retrieve']['callback'] = '_YOURMODULE_api_user_resource_retrieve';
}

// then implement the retrive
function _YOURMODULE_api_user_resource_retrieve($uid){
    $account = user_load($uid);
  if (empty($account)) {
    return services_error(t('There is no user with ID @uid.', array('@uid' => $uid)), 404);
  }

  services_remove_user_data($account);
  // DO YOUR SQL TO CHECK IF USER IS ONLINE
  // _check_this_user_online($uid);

  // Everything went right.

  return $account;
}

```
> 2 votes

---
Tags: 7, services, users
---


# Question
Title: Best method to clean up database table orphaned data in Drupal 7?
Currently my files and images table has over 100k entries, but I know for a fact that alot of them are orphaned and the files do not exist anymore. What is a best method to cross-reference this data to see if the file exist so i can delete them?

# Answer
> 3 votes
This is a script I use on my own Drupal sites, you can see if it works for yours, it deletes files and records in the file\_managed table that have no references in the Drupal file\_usage table, or things that are no longer being used by the Drupal installation.

```
$result = db_query('SELECT fm.fid, fm.uri FROM {file_managed} fm LEFT JOIN {file_usage} fu ON fm.fid = fu.fid WHERE fu.fid IS NULL ORDER BY fm.fid');
$num_files_deleted = 0;
$num_records_deleted = 0;
$time_before_start = time();

foreach ($result as $record) {
    $file = file_load($record -> fid);

    if ($file != FALSE) {
        if (file_delete($file)) {
            print(drupal_realpath($record -> uri) . " has been successfully deleted.\n");
            $num_files_deleted++;
        }
    }

    db_delete('file_managed') -> condition('fid', $record -> fid) -> execute();
    $num_records_deleted++;
}

$time_after_finish = time();
$total_time = ($time_after_finish - $time_before_start);
$total_time_h = $total_time / 3600 % 24;
$total_time_m = $total_time / 60 % 60;
$total_time_s = $total_time % 60;

if ($num_records_deleted || $num_files_deleted >= 1) {
    print("\n\n");
    print($num_files_deleted . " files purged and " . $num_records_deleted . " in " . $total_time_h . ":" . $total_time_m . ":" . $total_time_s . ".\n");
}
else {
    print("Nothing to purge.\n");
}

```

You can try running that on a dev to see if that's also something you would want.

# Answer
> 2 votes
I think the easiest way would be to code something that loops over all files in the database, checks for the physical file's existence, and deletes the record if it doesn't.

It would be a good idea to break this up into a batch job if you have a lot of records, but the basic code would be something like

```
$files = db_query('SELECT fid, uri FROM {file_managed}')->fetchAllKeyed();
foreach ($files as $fid => $uri) {
  if (!file_exists($uri)) {
    file_delete(file_load($fid), TRUE);

    // file_delete() will fail to clear up the records as it doesn't delete the
    // physical file...
    db_delete('file_managed')->condition('fid', $fid)->execute();
    db_delete('file_usage')->condition('fid', $fid)->execute();
  }
}

```

If you end up using that code make sure you run it on a backed up dev copy first, just to make sure it does exactly what you want.

---
Tags: 7, database
---


title: Set up pathuto to work for me

text:
# Question
Title: Set up pathuto to work for me
I want to set up pathuto to act like this

http://nevia.server2.tabvn.com/blog/mauris-aliquet-ultricies-ante

How do I accomplish this? What I want is to have my site behave like this when an article is clicked: www.domain.com/categorytile/articletitle.

How do I set pathauto to use categorytitle and articletitle like this?

Here is an expanded edition of what I wrote above:

Supposing I have the following 3 categories created on my site:

* healthcare
* technology
* education

Then I post articles in the 3 different categories. When a user clicks on an article posted into category "education", the url will look like this: www.domain.com/education/articletitle

My problem is to make pathauto to automatically insert the category name "education" into the urls of all the articles posted into that category.

I want the same with the articles posted into the other two categories. For example, if a user clicks on an article posted into category "technology", then the url will look like this: www.domain/technology/articletitle

Thanks in advance

# Answer
I suppose you mean content type as category title.

On the Pathauto configuration page `admin/config/search/path/patterns`

Set default pattern as:

```
[node:content-type]/[node:title]

```
> 0 votes

# Answer
If your articles are in only one category, then you can use the replacement token for your category field on the Article. Suppose your Article content type has a field Category (which is a taxonomy term), then your Pathauto pattern would be `[node:field_category]/[node:title]`.
> 0 votes

---
Tags: path-aliases
---


# Question
Title: Assigning custom class to nested menu UL elements
I'm trying to theme my menu to alter the default UL classes. So far I'm working with the following function:

```
function theme_menu_tree($variables){
  return '<ul class="my-class">' . $variables['tree'] . '</ul>';
}

```

This works great but I need to apply a different class to the UL inside a parent item. Right now I get

```
<ul class="my-class">
  <li class="dropdown">Item
    <ul class="my-class">
      <li>Link1</li>
      <li>Link2</li>
    </ul>
  </li>
</ul>

```

How can I target the second UL to give it a different class using the theme\_menu\_tree function?

# Answer
This kind of issues should be managed by CSS, but if you realy need to override the `theme_menu_tree()` and define a custom `ul` class there, you can do that with the help of custom global variable created in `theme_menu_link()`.

Not sure if it's "the right way" to do that, but works:

```
/**
 * Implements theme_menu_tree__[MENU NAME].
 */
function YOURTHEME_menu_tree__[MENU NAME]($variables) {
  global $level;
  $class = ($level == 1) ? 'my-class' : 'my-class-for-depth-' . $level;
  return '<ul class="'.$class.'">' . $variables['tree'] . '</ul>';
}

/**
 * Implements theme_menu_link__[MENU NAME].
 */
function YOURTHEME_menu_link__[MENU NAME]($variables) {

  $element = $variables['element'];
  $sub_menu = '';

  // set the global variable in order to use it in hook_menu_tree()
  // I called it "level" to avoid confusing with the $depth
  global $level;

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
    $level = 1; // set the level as first for each list with submenu
  }
  else {
    $level = $element['#original_link']['depth'];
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

```
> 11 votes

---
Tags: routes
---


# Question
Title: Sync +- 70 000 records from CSV into drupal
I have a CSV file with approx. 70.000 records that I want to import into Drupal 7. Once this is done the client will provide a new CSV file on a daily base that has to sync the updated rows to Drupal.

I wrote a import with Feeds and the Migrate module, but in both cases it takes like forever to import the 70.000 rows. Is there any other solution to import the data faster in Drupal 7?

# Answer
> 1 votes
If you need an `update` feature of your records i'm not sure how you'd get around scanning for Diffs to find changes -- this takes time.

I've used Migrate to upload simple CSV files and tables. Have you looked at Migrate 2.6 `Hash()` function to track data changes in stuff to perform only updates from your source data? http://www.acquia.com/blog/migrate-26-framework-changes

> With Migrate 2.6, we have introduced the 'track\_changes' option to MigrateSource. If you pass 'track\_changes' =\> 1 in your options array on your source constructor, Migrate will hash the source data after prepareRow() is called and save the hash in the map table on initial import. On subsequent imports, it will again hash the incoming source data and compare it to the saved hash - if the hashes don't match, the object will be reimported and the new hash saved, otherwise it will be skipped. Of course, this is a slower method than highwater marks, but when you must pick up changed records and don't have a good highwater mark field in the source data, this is the way to go.

Is there any reason you cannot import your CSV file into MySQL tables and then import your data from there using Migrate or a Drush script? Once in tables you could partition the data/tables easily to run the inserts more concurrently for a speedup.

***EDIT***:

I hit a .NET webservice for 100,000s of records for campus data at an EDU. I found that parsing the data linearly took me on the order of an 1 hour from top of the XML file to the bottom. By requesting each department individually at-the-same-time (get ~60 XML files at once instead of 1 big xml file) and processing in parallel up to 8 threads (via Ultimate Cron) the same process now takes ~5 minutes.

At some point linear processing of data simply fails and you have to find other means.

# Answer
> 0 votes
You could bypass Drupal directly and sync the file directly to the database. This would give you the best possible performance. Here's one way of doing it http://www.tech-recipes.com/rx/2345/import\_csv\_file\_directly\_into\_mysql/

# Answer
> -1 votes
I am not sure what "forever" means in terms of actual time spent. However, i have used the user import framework and user import framework plus module and it works fine.

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


# Question
Title: Edit profile2 tab in view profile2 rendered with views
I have a profile created using profile2 module. I want this profile to be rendered as a separate page and I have done so using views. The profile can be viewed in a url: www.example.com/application/authors/username.

I want to provide to the owner of the profile a tab on the page for editing it.

This should be simple using hook\_menu, but it doesn't seem to work for me.

```

function MY_MODULE_menu() {
  $items['application/authors/%author/edit'] = array(
    'title' => 'Edit',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('profile2', 1),
    'access callback' => 'MY_MODULE_access_check',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
  );

  return $items;
}

```

Is the above code correct? Do I need to register the view as a parent tab?

# Answer
Profile2 provides a submodule Profile2 pages which does exactly that: allows the ability to render the profile separately and includes an Edit tab.
> 1 votes

---
Tags: 7, views, users, routes
---


# Question
Title: hook_field_attach_presave not saving - user profile field
**EDIT:** As per a suggestion below, I tried using hook\_field\_presave, but couldn't access any parameters of the field. I then tried hook\_field\_attach\_presave, but my alterations aren't being saved. My current module code is :

```
function module_field_attach_presave($entity_type, $entity) {
  $field = $entity->field_user_location;
  $locality = $field['und'][0]['locality'];
  $locality = ucwords(strtolower($locality));
  dpm($locality);
  }

```

The transformation is present when `Locality` prints out via `dpm`, but the transformation is not saved to the field itself. Any idea why?

**ORIGINAL:** I'm using an AddressField field in my user profiles, but I'd like to make sure that the cities that users enter are correctly capitalized. How can I do this?

I'm assuming it's some implementation of `str_replace`, but I don't know what to do with it.

# Answer
You'll need to implement hook\_field\_presave(). You can find out from the parameters passed in if it's being invoked for an address field saved to a user account and do the necessary transformation on the 'locality' of the address field value in the `$items` array.
> 5 votes

---
Tags: hooks, users, entities
---


# Question
Title: How to pull commerce_customer_address into the invoices view?
I'm using Drupal Commerce for a hotel booking site so it's not following the typical Commerce use case. It works very well except for an issue I'm having where the Billing Info is not being automatically populated with the Account Info. This works in Commerce but not the way I'm using it. I spoke to some Commerce peeps and they confirmed this. As a work around and since I'm not using the Billing Info fields anyways, I thought why not just use the Account Info fields?

Well the problem is that I can't seem to call on commerce\_customer\_address in the invoices view. I don't see it in the relationships section. Does anyone know how I can do this? As a proof of concept, I added an entity reference field to orders and was able to manually pull the address from Account Info. I'd like to automatically pull this info.

Thanks.

# Answer
> 1 votes
If I read your situation properly, it sounds like you want to establish a relationship from an order to the user account that created it and include a field from the user account in the Views results. If so, the solution is the core Drupal Commerce relationship *Commerce Order: Owner*. With this relationship, you should be able to put any property or field of the user account responsible for the order into your Views results.

This relationship is a part of the admin Orders View by default, so perhaps there's something else going on in your case. If so, it would be helpful to know more about your customizations.

---
Tags: views, commerce
---


title: Change "Enter your (website) username."

text:
# Question
Title: Change "Enter your (website) username."
I am setting up a personal site in Drupal, and at the Login page it will have "Enter your Josh Mustillo username." Is it possible to change the "Josh Mustillo" to something else like "Enter your Username"?

(Domain is www.joshmustillo.com),

# Answer
> 7 votes
You could do that by implementing the `hook_form_alter`, in your custom module.

```
function MODULE_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'user_login') {
    $form['name']['#description'] = t('Enter your username');
  }
}

```

# Answer
> 5 votes
You can use the string overrides module to replace the text.

It's a little bit trickier to change strings with variable parts so here is a video that explains how to do it.

# Answer
> 4 votes
If you look into default settings.php There is something called String overrides

```
/**
 436  * String overrides:
 437  *
 438  * To override specific strings on your site with or without enabling the Locale
 439  * module, add an entry to this list. This functionality allows you to change
 440  * a small number of your site's default English language interface strings.
 441  *
 442  * Remove the leading hash signs to enable.
 443  */
 444 # $conf['locale_custom_strings_en'][''] = array(
 445 #   'forum'      => 'Discussion board',
 446 #   '@count min' => '@count minutes',
 447 # );
 448

```

You can achieve this without any extra module.

---
Tags: users
---


# Question
Title: How to hide "Manage Fields" and "Manage Display" tabs
I'm making a website with Drupal 7, and I was looking through the permissions for Taxonomies. I wanted to give the website maintainers a central place to manage the vocabularies and add terms, sort the terms etc. So I gave their role the "Administer vocabularies and terms" permission under Taxonomy. This however resulted in an unwanted complication, mainly it gave them access to create new fields and manage their display ("Manage Fields" and "Manage Display" tabs).

Is there a way to give them access to the Vocabulary and Term edit screen which can be accessed through "Structure \> Taxonomy" but however disable the "Manage Fields" and "Manage Display" tabs on the vocabulary edit screen?

I'm quite familiar with the notion of overriding and hooks in Drupal 6, but I'm quite new to Drupal 7 (in fact this is my first D7 website, made about 5 or 6 D6 websites) so I don't mind some coding solutions to this if any. Just looking for an answer or a push in the right direction.

Since no one has answered yet, I wanted to add that I'm willing to look into alternatives to the central area to manage taxonomies (admin/structure/taxonomy). Maybe I could look into creating a page with Views to simulate the taxonomies admin page.

Is it feasible and has anyone done anything like this before?

# Answer
I know this was answered a while back, but there's a solution that doesn't require any custom or special modules.

If you disable the core **fields ui** module, the Manage Fields and Manage Display tabs will not show.

If this is a production site, this should be fine to do as you'll have already configured the fields how you want them. If you ever need to make a change, just enable the module again briefly.
> 8 votes

# Answer
Use field\_ui\_permissions module which controls whether "Manage Fields" and "Manage Display" tabs should be displayed or not based on role permissions.
> 7 votes

# Answer
The permission `administer taxonomy` is what's used to give field permissions, if you need to give them this permission in order to give them access to taxonomy administration you can create a new permission for the field ui.

The easiest way to set this, is with `hook_entity_info_alter` hook, since this is where the admin path for the field ui is added and the access permission for them. You could also use `hook_menu_alter` to change the permission, but this is a bit more work.
> 3 votes

# Answer
You might try using the hook\_menu\_alter() to edit the 'access callback' that are setup in field\_ui\_menu() function from field\_ui.module file. This is where the "Manage Fields" and "Manage Displays" menu items are setup.

In your hook\_menu\_alter() you could look for these two menu item entries for taxonomy paths (since you would want to keep the Content Type versions of these), and change the 'access callback' to a custom method that checks a new permission you create in hook\_permission().

I've done something similar in the past and would be happy to send code if needed.
> 2 votes

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


title: Custom template fields Drupal 7

text:
# Question
Title: Custom template fields Drupal 7
In Drupal 6, I was able to use a Row Style Fields template and create variables to arrange and print later i.e.:

```
foreach ($fields as $id => $field) {
  if ($field->label == "Phone") {
    $f_phone = $field->content;
  }
}
print "<h2 class='content'>${f_phone}</h2>\n";

```

Then I was able to use the variable `$f_phone` in other places in the template. This does not work in Drupal 7. I am instead getting variable not found errors.

How would I do this in D7?

# Answer
I figured I would reply to this question since I figured out an answer. Don't know if this is the best way, but it works.

If you use the `views-view-fields.tpl` templates, you can skip the loop and directly list and style your fields ie:

```
print $fields['title']->content;
print $fields['field_location']->content;

```

\**the code above is inside your php tags
> 1 votes

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