# Question
Title: Custom 404 page in a theme doesn't work as expected,
I want to use a custom 404 page, I also have a theme installed.

This is what I did:

1. Go to Content, create a Node, I got path: node/28
2. Go to System-\>Site Information-\>Error Pages-\> 404 page, I enter node/28

Then I type some pages that are not exists, it doesn't link me to the `node/28`, instead, it still use the themes' 404 page.

Some hint here?

BTW, I am using Drupal 7 and the theme called MD magnum.

# Answer
> 0 votes
Do what @jdu said and check the theme's template files for an error page template. It will probably have the name page--error.tpl.php and probably be in /sites/all/themes/md\_magnum/templates/

After that set your new error page URL in admin/config/site-information to the node you created.

To verify it is set you can check in your database under the variables table for site\_404 to be set to that URL.

Make sure after you make these changes you clear cache completely and refresh your page. If you are in Chrome, you may have to clear browser cache as well if you are using the same URL.

---
Tags: theming
---


# Question
Title: Drupal 7 connection to MS SQLServer/PostgreSQL
I'm building an architecture of an integrated system of databases that are going to be the infrastructure of about 60 websites.

since databases are going to be massive (more than 30000 articles will be inserted in the database, thousands of books and its abstraction and etc) I'm really worry about the efficiency and ability of MySQL to handle the data.

I'm not very experienced in the theory of Database Management System, so this is my question, Can MySQL handle this amount of data? if not Can Drupal 7 connect to MSSQL Server and work with it as good as it works with MySQL? what about PostgreSQL?

Thanks

# Answer
> 1 votes
> Can MySQL handle this amount of data?

Yes, MySQL can theoretically handle many millions of rows (see How many rows in a database are TOO MANY?).

What actually matter are your server resources, configuration, and indexes. If you're not sure about the first two, consult with a professional dba who will be able to help you fine tune your settings for both Drupal, and, more importantly, the specific usage of your app.

Drupal core tables are heavily indexed (as are many tables provided by contrib modules), so it'll probably come down to the custom/contrib modules you have installed from that respect.

> if not Can Drupal 7 connect to MSSQL Server and work with it as good as it works with MySQL? what about PostgreSQL?

Yes, Drupal can use both MSSQL and PostgreSQL. How well any of those perform will entirely depend on the same things mentioned above. I doubt you'd see massive differences in any of them, unless your app is used in a particular way that one or another is better suited for (but the only way to work that out is by benchmarking).

---
Tags: database
---


# Question
Title: n00b question, form callback and form_alter
My highly-n00b question is: suppose I have a form callback which could be used as argument to drupal\_get\_form().

How can I specify an ID for the form so I can compare it inside hook\_form\_alter against the given-as-argument $form\_id?

This means: I want to give a form id to the form, e.g. "my-system-form", and distinguish it to apply some alter-logic (don't want to apply that logic to the rest of the forms).

# Answer
`hook_form_alter()` has `$form_id` as an argument:

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

```

Which is:

> String representing the name of the form itself. Typically this is the **name of the function that generated the form**.

(emphasis mine)

To understand the "typically" in there, have a read through the docs for `hook_forms()` (chances are it won't apply to your situation, or if it does, you probably already know about it).

So, generally speaking, you can use:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'MYMODULE_some_form') {
    ...
  }
}

```

Or, the more specific `hook_form_FORM_ID_alter()`, which will only be invoked for that specific form:

```
function MYMODULE_form_MYMODULE_some_form_alter(&$form, &$form_state, $form_id) {
  ...
}

```
> 1 votes

---
Tags: 7, forms
---


# Question
Title: How to migrate fields attached to files?
I'm writing a file migration using migrate/migrate\_d2d to migrate files from one Drupal 7 installation to another.

Images have custom fields attached to them, including a text field "field\_boilerplate". This field exists in the destination site's image type. When I run the migration, the image itself migrates and creates an image entity, but field\_boilerplate is not populated.

What am I doing wrong, and how can I migrate fields attached to files?

In mymodule.module:

```
/**
 * Implements hook_flush_caches().
 */
function mymodule_flush_caches() {
  mymodule_migrate_register_classes();
}
/**
 * Register dynamic migration classes
 */
function mymodule_migrate_register_classes() {
  // Arguments common to all migrations
  $common_args = array(
    'source_connection' => 'mysite_legacy',
    'source_version' => 7,
    'group_name' => 'mymodule_migration',
  );
  // Other migration arguments redacted for length
  // Image migration arguments
  $image_args = array(
    'machine_name' => 'images',
    'class_name' => 'MyModuleImageMigration',
    'description' => t('Migrate images'),
    'user_migration' => 'users',
    'default_uid' => 1,
    'source_dir' => 'http://example.com/sites/default/files',
    'destination_dir' => 'public://',
    'skip_pictures' => TRUE,
  );
  Migration::registerMigration('MyModuleImageMigration', 'images', $image_args + $common_args);
}
/**
 * Implements hook_migrate_api().
 */
function mymodule_migrate_api() {
  return array('api' => 2);
}

```

In an included file:

```
<?php
class MyModuleImageMigration extends DrupalFile7Migration {
  public function __construct($arguments) {
    parent::__construct($arguments);
    // Mappings
    $this->addFieldMapping('field_boilerplate', 'field_boilerplate');
  }
}

```

# Answer
> 2 votes
You need to specify the bundle type when registering the dynamic migration:

```
  $image_args = array(
    'machine_name' => 'images',
    'class_name' => 'MyModuleImageMigration',
    'description' => t('Migrate images'),
    'user_migration' => 'users',
    'default_uid' => 1,
    'source_dir' => 'http://example.com/sites/default/files',
    'destination_dir' => 'public://',
    'skip_pictures' => TRUE,
    'bundle' => 'image', // Need to add the bundle type
  );
  Migration::registerMigration('MyModuleImageMigration', 'images', $image_args + $common_args);

```

---
Tags: 7, entities, files, migrations
---


title: Current user geographical location

text:
# Question
Title: Current user geographical location
I am building a website which on the contact page will have a section to find your local sales representive. I intend to do this by having a content type of sales rep with a location field and creating a view from this content on the contact page.

As an improvement to this i would like it to automatically (if the user allows it) to take the geo location of the user and automatically filter the view by this showing the users nearest sales rep.

Are there any modules in existence which i can use to achieve this? Or am I likely to have to build a custom module?

# Answer
> 3 votes
You will need custom coding to provide the argument to the view, but you could use the following modules for the geolocation functionality:

Feature-rich, server-side solution: Smart IP

Simpler, ip-based server/client-side solution: geoPlugin

---
Tags: views, location
---


# Question
Title: Can I force users to join a group when registering?
I would like everyone to be a member of "our Community" by default.
I want everyone to be a member of a site-wide group so that we can have a site-wide wiki, events & all the other usual group stuff.

Do I miss the point? Is this already the case, or do I not really want what I think that I want?

# Answer
> 0 votes
I don't see any options such as Organic Groups offers.

The best that I could do is add some text to the registration guidelines and welcome email strongly recommending to join the group "Our Community".

I also made it a "featured group" so that it will appear on the front page.

Aha! If I (log in as admin and) edit the group, I see the option "Registration form May users join this group during registration? If checked, a corresponding checkbox will be added to the registration form" ... but that still doesn't enforce membership :-(

# Answer
> 1 votes
I am not sure, but if Organic Groups has rules integration; you might be able to create a Rule which automatically adds the user to the desired group.

# Answer
> 1 votes
Well, you could code it, but it's kind of a cheesy solution. Assuming you have a group called "My Group" you want everyone to join, you could write some code and embed it on a page that everyone hits. As soon as they land on it, they get added to the group automatically. PHP/Drupal code might look something like this (Drupal 7 example):

```
//get the user's id
global $user;
$uid=$user->uid;

//get the group's GroupID
$result=db_query("SELECT gid FROM og WHERE `label`=:groupName",array(':groupName'=>'My Group'));
$row=$result->fetchAssoc();
extract($row);

//check and see if the user is a member of the group already
$result=db_query("SELECT COUNT(id) AS og_count FROM og_membership WHERE etid=:uid AND gid=:gid",array(':uid'=>$uid,':gid'=>$gid));
$row=$result->fetchAssoc();
extract($row);
if($og_count==0 && $uid!=0)
  {
  $result=db_insert('og_membership')
  ->fields
    (
    array
      (
      'name'=>'og_membership_type_default',
      'etid'=>$uid,
      'entity_type'=>'user',
      'gid'=>$gid,
      'state'=>1,
      'created'=>time(),
      )
    )
  ->execute();
  }

```

This is not the preferred way to do it, but in a pinch you could add this code to a heavy traffic page and pretty much ensure your users get added. The down side is that you are doing an extra database dip or two to ensure your users are added to a specific group. Not very efficient, but it would likely do what you want.

As a caveat, this is based on what I know from playing around with Organic Groups. This code is from the top of my head, so there may be a parsing error here or there - be sure to check it out first. Also, this is direct dipping into og's table structure, which is frowned upon, as og could change their table structure in the future, during a code update...

# Answer
> 1 votes
I think you could use the Organic Groups - Multiple Mandatory Groups by Role module.

> The goal of this module was to extend the capabilities of the original og\_mandatory\_group module to allow as many mandatory groups as the user wants for:
>
> * All users
> * Group administrators/owners
> * any role
>
> As all of the changes constitute a module with drastically different capabilities, it didn't make sense to patch the original module with this code. Additionally, most of the old code was thrown out and a ton of new code put in place.

# Answer
> 1 votes
Use the Rules module. After a user registers, run PHP code that would add that newly registered member to a group. Then add a call to `drupal_set_message()`, notifying them that they are automatically member of a group.

# Answer
> 0 votes
In organic groups module you can set the "user: group audience field" to required and "show on registration page" in combination with the "show all groups" setting. That will force the user to select a group from the list when signing up.

I've only tested this in Drupal 7 but I'm pretty sure Commons uses organic groups as well.

# Answer
> 0 votes
what I found was this:

If you have one public group and all the rest are private groups, new members are added to the public group by default. May not help everyone but it solved the issue very easily for my use case.

I believe it is also necessary to edit the Group content type - Group Audience and/or - Group visibility fields and check the "required" box

Sean :)

# Answer
> 0 votes
You can do this programmatically.

Write a custom module that implements hook\_user\_insert. In hook\_user\_insert, call og\_group, which subscribes an entity to a group. So your .module file looks something like this:

```
/**
 * Implements hook_user_insert().
 */
function mymodule_user_insert($edit, $account, $category) {
  $values = array(
    'entity_type' => 'user',
    'entity' => $account->uid,
    'field_name' => 'field_group', // Must be the name of the field in user that references groups
  );

  og_group(group_type, group_id, $values); // replace group_type and group_id with the entity type of the group and its group id
}

```

---
Tags: organic-groups
---


# Question
Title: altering them for node edit page not working
I got the following to work by adding it to the admin template.php file. But I am not having any luck changing the one edit form to use boostrap\_subtheme vs the default admin theme. Any advice with that? To add a little more to this, I am using the following code to set the add node for data set to the default theme, how would you do this for a node edit page? The url for the node edit page contains the node id.

function mymodule\_menu\_alter(&$items){ $items\['node/add/data-set'\]\['theme callback'\] = 'mm\_get\_default\_theme';

}

function mm\_get\_default\_theme(){ return variable\_get('theme\_default', '0'); }

I am using the `hook_theme()` function to override the theme for a given node's edit form. This works when you create a new node but does not override the theme with the use clicks "edit". Any ideas? Path of the edit form is for instance `node/39/edit`.

```
$items['custom_node_form'] = array(
  'arguments' => array('form' => NULL),
  'render element' => 'form',
  'path' => drupal_get_path('theme', 'bootstrap_subtheme') . '/templates',
  'template' => 'custom-node-form',
);

```

# Answer
Its working on my site, although i haven't made a template but it should work with a template too. here is my code

```
function modulename_theme(){
     $items['article_node_form'] = array(
    'arguments' => array('form' => NULL),
    'render element' => 'form',
  );
    return $items;
}
function theme_article_node_form(&$var){
    $form=$var['form'];
    $output = '<h2>' . t('Please enter your information below') . '</h2>';
    $output .= drupal_render_children($form);
    return $output;

}

```
> 0 votes

---
Tags: forms, theming
---


# Question
Title: How do I combine two content types in one Views block and get them to sort correctly?
On my site, I have content types for Tradeshows and Webinars. I would like to have a block that shows the next 5 upcoming events by date, coming from either content type. I have Views set up to retrieve items from both types, and have the sort criteria set up with the date field from each type (they are different fields), in ascending order. Ie., the Sort Criteria section looks like: Webinar Date (asc), Tradeshow Date (asc).

If I set the Views pager to display all items, I see a list of all the tradeshows, followed by the webinars. It looks like Views retrieves the items from each content type, and sorts them correctly within their own group, but doesn't weave the two sets together, according to date. This means that if I set the pager down to 5 items (the goal), then I'll only see tradeshows, since there are more than 5.

Is there a way to get Views to shuffle the two types together, and show the next 5 events, combined?

Edit: attaching screenshot

# Answer
> 1 votes
In the end, using hook\_views\_query\_alter() turned out to be the simplest solution for my needs. I used code similar to that found in the solution below.

https://drupal.stackexchange.com/a/53128/18497

# Answer
> 0 votes
Use Same field to pick date for Tradeshows as well as Webinars using existing field in content type. After that sort view accroding to that date field.

---
Tags: views
---


title: html.tpl.php is ignored

text:
# Question
Title: html.tpl.php is ignored
I have Drupal 7 site using a custom theme, which was working just fine. I created some regions and then I went and extracted some parts of the `html.tpl.php` file and made them blocks to make them translatable. The idea was to display these new blocks in the new regions. But all of a sudden my theme stopped working and now drupal ignores my html.tpl.php file and uses the default. I have no idea what went wrong. Any help is much appreciated.

**EDIT**: I checked the logs and i noticed this error, just before the problem begun.

```
The directory /var/www/***********/tmp does not exist and could not be created.

```

I have a development server which runs the same site and this directory is specific to that. So i created a `/tmp` directory in the live site and set it in the configuration page but still the problem persists.

**EDIT2**: I am using a `template.php` file to send the blocks to the `html.tpl.php`. Something like this:

```
function <themename>_preprocess_html(&$variables) {
  $variables['footer_menu'] = block_get_blocks_by_region('footer_menu');
  $variables['info_bar'] = block_get_blocks_by_region('info_bar');
}

```

# Answer
> 1 votes
The question is bit confusing and contradicting. The `html.tpl` file is just there to take care of the HTML structure. If you need to add regions or change blocks, then `page.tpl.php` is the one you need to change.

SR

---
Tags: 7
---


# Question
Title: Add javascript scolbar & effects to Block from module
I have a block that was created with Social Feed Module. The block aggregate social feeds. I want to add a scroll-bar to the block it self. I have seen some examples:http://mydrupal.com/add\_scrollbars\_in\_blocks

However, I would like the block scroll-bar to be visible ONLY when the user hovers over the scroll-bar. I would think I would need to use javascript with the scrolbar? Any suggestions?

# Answer
> 1 votes
It's probably bad usability because you would want your users to know that a block has scrolling content, but you could do something like this.

```
$(".block .content").hover(function(){
  $(this).css("overflow","scroll");
  },function(){
  $(this).css("overflow","hidden");
});

```

---
Tags: blocks, javascript, feeds, theming
---


# Question
Title: When adding a relationship to the author, I'm unable to see any custom field
I'm trying to get the username of a blog last poster; I created a view that shows the blog's fields. If I click on "Add field" I can see all custom fields. However, when I add a relationship for *Author*, I now loose all custom content fields including any author-related fields. The only fields available are the ones like "Content: Nid" and "Content: Path."

Can anyone help me understand what is going on? I've tried everything and it's now day 2 hung up on this. Is Views broken?

# Answer
> 0 votes
Ideally it should work... Please find exported view below which displays Author Name of last blog post.. You can able to add more fields to the same view..

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

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Blog Last Poster';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '1';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Content: Author */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'node';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'uid';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'blog' => 'blog',
);

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');

```

---
Tags: views
---


# Question
Title: Deduct 10% transaction fee when user donates userpoints to another user using rules - Drupal 7
I want to use rules to deduct 10% of the transaction amount from a donor each time he donates userpoints to another user using the userpoints\_donate contrib module. Currently there are no rules events or actions from the userpoints\_donate contrib module

possible events: user donates points to another user

possible conditions: donation\_amount \<=\> a particular value

possible actions: grant points to donor = (donation\_amount * -0.1, i.e grant -10% of donation\_amount to donor)

How can i achieve this? Thanks

# Answer
If you see userpoints\_donate.module `userpoints_donation_giveform_submit` function is reponsible to award points to another user

```
/**
 * Submit function to give another user points.
 */
function userpoints_donation_giveform_submit($form, &$form_state) {
  global $user;

  $points = $form_state['values']['amount'];
  $to = $form_state['validated_account'];

  $tid = NULL;
  if (isset($form_state['values']['tid'])) {
    $tid = $form_state['values']['tid'];
  }

  $params = array(
    'uid'    => $to->uid,
    'points' => $points,
    'operation'  => 'userpoints_donation_received',
    'entity_type' => 'user',
    'entity_id' => $user->uid,
    'description' => $form_state['values']['reason'],
    'tid'    => $tid,
  );
  userpoints_userpointsapi($params);

  $params = array(
    'uid'    => $user->uid,
    'points' => -$points,
    'operation'  => 'userpoints_donation_given',
    'entity_type' => 'user',
    'entity_id' => $to->uid,
    'description' => $form_state['values']['reason'],
    'tid'    => $tid,
  );
  userpoints_userpointsapi($params);
}

```

As you see above

userpoints\_userpointsapi($params); is called to award $points with transaction operation userpoints\_donation\_received .

You can use hook\_userpoints($op, $params = array()) to act upon certain operations. When other modules award points to a user, your hook will be called, among others.

> $op: The operation to be acted upon. 'setting' Pass a field set and fields that would be displayed in the userpoints settings page. For example, this can be used for your program to ask the admin to set a number of points for certain actions your module performs. The function should return an array object conforming to FormsAPI structure.
>
> 'points before' Calls your module, and others, before the points are processed. You can prevent points from being awarded by returning FALSE.
>
> 'points after' Calls your module, and others, after points are processed. You can take certain actions if you so wish. Return value is ignored.
>
> The $params variable is the original $params array as sent to userpoints\_userpointsapi

* Using "Points after" $op and in $params check for operation "userpoints\_donation\_received" you make a call to deduct 10 % points using..

userpoints\_userpointsapi($params); API function..

```
<?php
function YOURMODULENAME_userpoints($op, $params) {
  if ($op == "points after") {
    if ($params['operation'] == "userpoints_donation_received") {
      $transaction_params = $params;
      $transaction_params['points'] = -( $transaction_params['points'] / 10);
      $transaction_params['operation'] = "userpoints_donation_transaction_fee";
      $transaction_params['description'] = "Transaction Fee";
      userpoints_userpointsapi($transaction_params);
    }
  }
}

```
> 0 votes

---
Tags: 7, rules, userpoints
---


title: Drupal 7 #ajax callback on form submit

text:
# Question
Title: Drupal 7 #ajax callback on form submit
Hello I have created a custom form added a # ajax callback on form submit

```
    $form['hotel_book_form']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Check Availability'),
    '#ajax' => array(
      'callback' => "list_rooms",
      'wrapper' => "replace_hotelbook_div",
      'method' => 'replace',
      'effect' => 'fade',
    ),
  );

```

and I have added this wrapper as suffix to the form

```
    $form['hotel_book_form'] = array(
    '#type' => 'fieldset',
    '#title' => t('Book Hotel'),
    '#weight' => 5,
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
    '#prefix' => '<div id="replace_hotelbook_div"></div>',
  );

```

but when I click on form's submit button the page gets simply reloaded and the ajax callback function does not fire.

# Answer
You haven't actually wrapped the element, you've inserted an empty `<div>` immediately before it.

You need to use `#prefix` *and* `#suffix` to wrap an element in HTML:

```
...
'#prefix' => '<div id="replace_hotelbook_div">',
'#suffix' => '</div>'

```
> 4 votes

# Answer
this isn't quite consistent with the behaviour you describing, but you are adding an element to an array:

`$form['hotel_book_form']['submit'] =`

then you are replacing the entire array. So you need to change:

`$form['hotel_book_form'] =`

to

`$form['hotel_book_form']['someother_suitable_value'] =`
> 1 votes

# Answer
The problem might be simply on your rendered html For instance i got the same issue because my ajax call was fired on a button click rendered on a form as below

```
 <button class="mapping_remove">Remove Mapping</button>

```

Once i made sure the type of the elment is a button my form stopped submitting

```
<button type="button" class="mapping_remove">Remove Mapping</button>

```

NOTICE : I added type="button" as an attribute
> 0 votes

# Answer
If you are working with CTools form than try to add this to the top of your form or form alter hook:

```
if ($form_state['rebuild'] == TRUE) {
  ctools_include('wizard');
  $form = $form_state['wrapper_callback']($form, $form_state);
}

```

Here is an explanation: https://drupal.org/comment/5112672#comment-5112672
> 0 votes

---
Tags: 7, ajax, forms
---


# Question
Title: Create native Excel XLS and XLSX files from scratch and export directly to a PDF file
We are considering migrating a Cold Fusion application to Drupal and I am wondering if the below 2 capabilities that are current Cold Fusion application is doing can be done within Drupal 7.

1. The ability to create native Excel XLS and XLSX files (NOT HTML tables that Excel has to convert each time it opens) from scratch. This includes the ability to use native Excel functions, formatting, and multiple tabs/sheets. CFSPREADSHEET makes this a relatively simple task for us.
2. The ability to export directly to a PDF file. CFPDF and CFCONTENT makes this almost as simple as wrapping the desired output in a set of tags and it’s done in many cases.

# Answer
* PHPExcel. It uses PHPExcel library and supports native Excel export, import. We are using it in our project and it does it well.

> The PHPExcel module allows developers to export/import data to/from real Excel files.

* Print. It allows you to generate the printer-friendly, PDF, EPUB and Email versions of any node. It supports following libraries:

I'd recommend using the wkhtmltopdf library, since I'm using it an it creates a way better results than the others.
> 1 votes

# Answer
I've made a loads of PDF's using PHP and if you need to do anything complicated (particularly with tables) dompdf just can't handle it so I've stopped using it all together.

I've had great success with fpdf however I know a colleague has been using tcpdf for some really complicated ones (tables with dynamic content that may or may not break over multiple pages).

I agree with Елин that PHPExcel is the best choice for excel files.
> 0 votes

---
Tags: 7, files
---


# Question
Title: How to get number of node of particular content type?
I have one content type as "refund", I want all number of node of this content type according to month wise, year wise and per day. I can get total number of nodes of refund content type by query but how to get sorted by month wise, year wise and per day wise and then show through views?

Please help me to solve this issue. Thanks in advance

# Answer
> 0 votes
I don't think you can change the node number (and I wouldn't reccomend it). This is a unique number used by Drupal.

You could set the content type to have a date field, and then use the auto path module to pull this data into the URL. This information would also then be usable by Views.

If you want to count the number of nodes of that content type then use Serial Field \- that will also be accessible to URL alias and views. Details from its project page:

> Unlike Drupal's built-in auto-increment node ID, which is global and shared by nodes belonging to all content types, serial fields are managed per content type (D6) / entity (D7). For example, the serial field of an Invoice instance will generate a unique sequential number (starting at 1, then 2, etc.) exclusively for Invoice instances.
>
> The allocation of serial numbers by this module is atomic. In other words, the serial values are unique even when multiple instances of the same content type / entity are created simultaneously.

Brief explanation but can provide more step by step detail if you want.

---
Tags: nodes
---


# Question
Title: $form['redirect'] = "something=$someId"; doesn't work in Drupal 7
I am here again with a problem! I want to make a form redirect usign a url with ids and somethings else as parameter, but when the code is executed something encode my url, so, if I put something like this **$form\_state\['redirect'\] = "page=$nid";** I get this in the url "page\**%3D*\*123456789" %3D is the =$. So, how i have to do that? I tested with utf8\_encode too.

Can I use a drupal\_goto() inside a form? Why yes? Why not?

Thanks people!

# Answer
What you set in `$form_state['redirect']` can be:

* a string containing the destination, such as node/1, admin/reports/status, or user/1.
* an array of arguments compatible with drupal\_goto().

The examples shown in drupal\_redirect\_form() are the following ones:

* This redirect the form to *node*:

```
$form_state['redirect'] = 'node';

```
* This redirect the form to *node/123?foo=bar#baz*:

```
$form_state['redirect'] = array(
  'node/123',
  array(
    'query' => array(
      'foo' => 'bar',
    ),
    'fragment' => 'baz',
  ),
);

```

In your case, if you want to redirect to `page/$nid`, you should use the following code:

```
$form_state['redirect'] = "page/$nid";

```

If you really want to redirect to `page=$nid`, then you should use the following code:

```
$form_state['redirect'] = array(
  array(
    'query' => array(
      'page' => $nid,
    ),
  ),
);

```
> 10 votes

# Answer
How to achieve,the below issue in drupal SAVE and NEW button.

If I want out of ten fields the top four fields of the same form to be pre filled again with the same data as I click on the submit button.

Thanks In Advance.
> -1 votes

---
Tags: forms, redirection
---


title: Don't index certain content types

text:
# Question
Title: Don't index certain content types
I only want to have certain content types indexed, for the default Drupal 7 search. And I would like to do this without installing any other modules.

I would like to do this by hooking into the query (using hook\_query\_alter) that grabs all the nodes from the search\_dataset. This query is found in the node\_update\_index function (node.module):

```
$result = db_query_range("SELECT n.nid FROM {node} n LEFT JOIN {search_dataset} d ON d.type = 'node' AND d.sid = n.nid WHERE d.sid IS NULL OR d.reindex <> 0 ORDER BY d.reindex ASC, n.nid ASC", 0, $limit, array(), array('target' => 'slave'));

```

The problem is I never get the ability to alter this query in the hook, my code is as following:

```
function mymodule_query_alter(&$query) {
  var_dump((string)$query);
}

```

At some point it should print the db\_query\_range query. I've also tried printing my debugging to a file so I could catch those queries running ajax time.

Any ideas on what I might be doing wrong?

# Answer
You can only modify SQL queries that are tagged, which this one is not. Therefore you cannot use HOOK\_query\_alter() to do what you are trying to accomplish.

This is hacky, but the easiest way to do this might be to implement hook\_module\_implements\_alter() and prevent the Node module's hook\_update\_index() implementation from firing. You can then copy the node\_update\_index() function to your custom module, obviously replacing "node" in the function name with the name of your custom module, and modifying only the query to exclude whatever node types you want.

```
/**
 * Implements hook_module_implements_alter().
 */
function mymodule_module_implements_alter(&$implementations, $hook) {
  if ('update_index' == $hook) {
    unset($implementations['node']);
  }
}

/**
 * Implements hook_update_index().
 *
 * @see node_update_index().
 */
function mymodule_update_index() {
  $limit = (int)variable_get('search_cron_limit', 100);

  $result = db_query_range( /* Your custom query here */ );

  foreach ($result as $node) {
    _node_index_node($node);
  }
}

```
> 6 votes

# Answer
Well, you can borrow what Custom Search does, which is:

```
function custom_search_query_alter(QueryAlterableInterface $query) {
  if ($query->hasTag('node_access') && $query->hasTag('pager')) {
    $excluded_types = array_filter(variable_get('custom_search_' . variable_get('custom_search_delta', '') . 'node_types_excluded', array()));
    if (!empty($excluded_types)) {
      $tables = $query->getTables();
      foreach ($tables as $table) {
        if ($table['table'] == 'search_index') {
          $query->condition('n.type', $excluded_types, 'NOT IN');
        }
      }
    }
  }
}

```

You would just need to edit the `$excluded_types = ...` line for your content types.
> 3 votes

# Answer
Chris Pliakas's answer no longer works, presumably due to changes in core. Here's how we managed to do it in Drupal 7.22:

```

/**
 * Implements hook_module_implements_alter().
 */
function my_module_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'cron') {
    unset($implementations['search']);
  }
}

/**
 * Implements hook_cron().
 *
 * @see search_cron()
 */
function my_module_cron() {
  // We register a shutdown function to ensure that search_total is always up
  // to date.
  drupal_register_shutdown_function('search_update_totals');

  foreach (variable_get('search_active_modules', array('node', 'user')) as $module) {
    // Update word index
    $module == 'node' ? module_invoke('my_module', 'update_index') : module_invoke($module, 'update_index');
  }
}

/**
 * Implements hook_update_index().
 *
 * @see node_update_index()
 */
function my_module_update_index() {
  $limit = (int)variable_get('search_cron_limit', 100);

  // Only index the artist and label content types.
  $result = db_query_range("SELECT n.nid FROM {node} n LEFT JOIN {search_dataset} d ON d.type = 'node' AND d.sid = n.nid WHERE (d.sid IS NULL OR d.reindex  0) AND n.type IN (:types) ORDER BY d.reindex ASC, n.nid ASC", 0, $limit, array(':types' => array('artist', 'label')), array('target' => 'slave'));

  foreach ($result as $node) {
    _node_index_node($node);
  }
}

```

Basically, we plug in our own `my_module_cron()` implementation instead of `search_cron()`, where we replace the `node_update_index()` call with `my_module_update_index()`. In `my_module_update_index()`, we have a modified query that only selects nodes of certain types for indexing.
> 0 votes

---
Tags: nodes, search, database
---


# Question
Title: How to resolve 500 - Internal server error?
I could not able to figure how to resolve this error i have tried searching on google.

> Server Error
>
> 500 - Internal server error. There is a problem with the resource you are looking for, and it cannot be displayed.

I have succesfully uploaded my site in a folder on godaddy's server and also import database.but when i am getting this error on browser, also checked my server log and also uncomment "rewritebase /" in .htaccess file

Please suggest how to resolve this error.

Thanks

# Answer
Could be any number of things.

Check the server error log or stick:

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

```

in your settings.php file (remove once in production environment) to force PHP to show errors.
> 1 votes

---
Tags: database, installation
---


# Question
Title: How to print field type image in views-view-fields--xyz--block.tpl.php
How to print field type image in this page?

I'm using this code:

```
print $fields['field_xyz']->content;"

```

Is it wrong?

# Answer
> 0 votes
Use field\_view\_field.

E.g.

```
$node = node_load($node_id);
print drupal_render(field_view_field('node', $node, 'field_your_field_name'));

```

Or if you don't want the label with the field then:

```
print drupal_render(field_view_field('node', $node, 'field_your_field_name', array('label' => 'hidden')))

```

---
Tags: views, media
---


title: How do I set a product image?

text:
# Question
Title: How do I set a product image?
When creating a product node for Ubercart, how do I set the product image?

I am using the following code to create a product node.

```
$node = new stdClass();

$node->name = "Title";
$node->title = $node->name;
$node->body = "Lorem Ipsum";
$node->type = "configurator_product"; //my own product class
$node->created = time();
$node-> changed = $node->created;
$node->promote = 0;
$node->sticky = 0;
$node->format = 2;
$node->status = 1;
$node->language = "en";
$node->default_qty = 1;
$node->sell_price = 55.00;
$node->shippable = 1;

```

The product node has a *field\_image\_cache* field which expects a file (extensions: png, gif, jpg, jpeg). I tried to set this field.

```
$node->field_image_cache = "Path/to/module/Images/image1.jpeg";
// Results in Fatal error: Cannot unset string offsets in
// path/to/modules/cck/content.module on line 1248

$node->field_image_cache[0]['value'] = "Path/to/module/Images/image1.jpeg";
// No errors, but when viewing the product in store administration there is no image

```

What is the correct way to set an image for a product?

# Answer
```
  $img_file = file_get_contents("Path/to/module/Images/image1.jpeg");
  $img_file = file_save_data($img_file, file_directory_path() .'/path2imagefield_folder/image1.jpeg', FILE_EXISTS_RENAME);
  $node->field_image_cache = array(
    array(
      'fid' => 'upload',
      'title' => basename($img_file),
      'filename' => basename($img_file),
      'filepath' => $img_file,
      'filesize' => filesize($img_file),
    ),
  );

```
> 1 votes

---
Tags: 6, ubercart
---


title: Drupal(.module file)

text:
# Question
Title: Drupal(.module file)
```
<?php
/**
Provides a block with query and store in database
*/
/**
* Implementation of hook_help().
*/
function demo_help($path,$args)
{
if($path=='admin/help#demo')
{
return t('To use this module, go to block page and turn on the       demo');
}
}

function demo_block_info()
{
$blocks=array();
$blocks['demo_member']=array(
'info'=>t('Demo member'),
'cache'=>DRUPAL_NO_CACHE,
);
return $blocks;
}

/**
* Implements hook_block_view().
*/
function demo_block_view($name)
{
if($name=='demo_member')
{
//$format2 = 'g:i a';
$content=db_query("SELECT entity_id FROM     {field_data_field_category_status}")->fetchField();
            $content.='';
            $block=array(
            'subject'=>t('Member'),
            'content'=>$content,
            );
            return $block;
    }

}
?>

```

i need to display 3 records by fetching array(.module file) i am getting single record: Member 1 i should get below Member 1 2 3

# Answer
> 2 votes
Change

```
$content=db_query("SELECT entity_id FROM {field_data_field_category_status}")->fetchField();
$content.='';

```

to

```
$records = db_query("SELECT entity_id FROM {field_data_field_category_status}")->fetchCol();
$content = implode('<br />', $records);

```

At the moment you're just getting the first record from the result set, not all of them.

As a side note, going directly into field tables isn't the best idea. Have a look at `EntityFieldQuery` for an alternative.

---
Tags: 7
---


# Question
Title: How to embed a comment in an entity-field query
In reviewing the slow query log, some of them are entity-field queries. With a normal select query, I can have something like:

```
$query = "/*" . __FILE__ . ":" . __LINE__ . "*/ SELECT...

```

and with pdo object notation, I can add

```
->comment(__FILE__ . ":" . __LINE__)

```

but how do I add a comment to an entity-field query? Apparently comment() is not a valid method.

# Answer
Provide the comment information via EntityFieldQuery::addMetaData, and then add the comment to the query in hook\_entity\_query\_alter().
> 0 votes

---
Tags: database
---


title: How to change taxonomy term path

text:
# Question
Title: How to change taxonomy term path
I am using taxonomy menu module but I want to change the taxonomy path from taxonomy/term/tid to subject/term title.

# Answer
> 1 votes
You need to use Path auto module .. Alias taxonomy term paths...

> The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias. This allows you to have URL aliases like /category/my-node-title instead of /node/123. The aliases are based upon a "pattern" system that uses tokens which the administrator can change.

---
Tags: taxonomy-terms
---


title: Drupal webform module problem occured

text:
# Question
Title: Drupal webform module problem occured
send email using webform. if email does not exist get failure message in inbox Do we need SMTP which module we need and settings(gmail) what we need???

# Answer
> 0 votes
Install the SMTP module

Step 1: Download the SMTP module for Drupal: https://drupal.org/project/smtp

Step 2: Extract to /sites/all/modules

Step 3: Enable the module on Admin - Modules

Step 4 (for Drupal 6 only): you have to install the PHPMailer package from Codeworx Tech., version supported is below 2.2.1. Place it in a directory named "phpmailer" in /sites/all/modules/smtp

For Drupal 7, this is no longer required. The SMTP module for Drupal 7 is shipped with the PHP Mailer. It works out-of-the-box

Configure with Gmail account

Step 1: Pls go to Admin - Configuration - SMTP Authentication Support

Step 2: On Install Options, please choose On

Step 3: On SMTP server setting, please enter

SMTP server: smtp.gmail.com SMTP backup server: SMTP port: 465 Use encrypted protocol: Use SSL Step 4: On SMTP Authentication: Enter user name and password of your Gmail account.

Step 5: On Email options: Enter your email from address (could be noreply@yourwebsite.com) and email from name (could be your site name).

Step 6: On Send test email: enter a email to test whether the module is working. Click on Save and go to your inbox to check. If there is an testing email then it is fine.

If it does not work, you may need to tick on the option "Enable debugging" and send a test email. The responses will be printed so you know more about the problem.

I attach the screenshot of a SMTP configuration.

---
Tags: webforms
---


# Question
Title: Is there a property that is set by the field API once fields have been attached to an entity?
Is there a property that is set by the field API once fields have been attached to an entity?

For example

```
$entity->fields_attached = TRUE

```

I have been unable to find any information on this, I am looking for a quick and easy way to know if fields have been attached to my own custom entities. If field API does not do something like I have suggested in the question I will handle it myself but I wanted to double check with you fine folks...

If not, I will make a suggestion for this for the Entity API in contrib whenever it attaches fields.

Many thanks in advance :)

# Answer
> 0 votes
No, there is no property on the entity, but you can use field\_info\_instances() to check on which bundles the field is in use.

---
Tags: entities
---


# Question
Title: Webservice endpoint with hook_services_resources()
I've stumbled upon some limitations of the services module. I wanted to create the following endpoints:

```
public/events/
public/events/categories
public/events/resources
public/blogs/

```

I wanted to place all the above under a single endpoint with path "public/". However, in the hook\_services\_resources the following is invalid:

```
/**
 * Implements hook_services_resources().
*/
function kw_api_services_resources() {
  $service_resources =
   'event/categories' => array(
      'operations' => array(
        'index' => array(

```

I ended up using two endpoints public/events and public/blogs. Is there a way to get around this? Meaning to user deeper than 1 level URLs.

# Answer
Example from the module itself, the child is defined in the relationships:

```
'events' => array(
  'operations' => array(
    'retrieve' => array(
      'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/node_resource'),
      'callback' => '_node_resource_retrieve',
      'args' => array(
        array(
          'name' => 'nid',
          'optional' => FALSE,
          'source' => array('path' => 0),
          'type' => 'int',
          'description' => 'The nid of the node to get',
        ),
      ),
      'access callback' => '_node_resource_access',
      'access arguments' => array('view'),
      'access arguments append' => TRUE,
    ),
    'create' => array(
      'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/node_resource'),
      'callback' => '_node_resource_create',
      'args' => array(
        array(
          'name' => 'node',
          'optional' => FALSE,
          'source' => 'data',
          'description' => 'The node data to create',
          'type' => 'array',
        ),
      ),
      'access callback' => '_node_resource_access',
      'access arguments' => array('create'),
      'access arguments append' => TRUE,
    ),
    'update' => array(
      'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/node_resource'),
      'callback' => '_node_resource_update',
      'args' => array(
        array(
          'name' => 'nid',
          'optional' => FALSE,
          'source' => array('path' => 0),
          'type' => 'int',
          'description' => 'The nid of the node to get',
        ),
        array(
          'name' => 'node',
          'optional' => FALSE,
          'source' => 'data',
          'description' => 'The node data to update',
          'type' => 'array',
        ),
      ),
      'access callback' => '_node_resource_access',
      'access arguments' => array('update'),
      'access arguments append' => TRUE,
    ),
    'delete' => array(
      'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/node_resource'),
      'callback' => '_node_resource_delete',
      'args' => array(
        array(
          'name' => 'nid',
          'optional' => FALSE,
          'source' => array('path' => 0),
          'type' => 'int',
        ),
      ),
      'access callback' => '_node_resource_access',
      'access arguments' => array('delete'),
      'access arguments append' => TRUE,
    ),
    'index' => array(
      'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/node_resource'),
      'callback' => '_node_resource_index',
      'args' => array(
        array(
          'name' => 'page',
          'optional' => TRUE,
          'type' => 'int',
          'description' => 'The zero-based index of the page to get, defaults to 0.',
          'default value' => 0,
          'source' => array('param' => 'page'),
        ),
        array(
          'name' => 'fields',
          'optional' => TRUE,
          'type' => 'string',
          'description' => 'The fields to get.',
          'default value' => '*',
          'source' => array('param' => 'fields'),
        ),
        array(
          'name' => 'parameters',
          'optional' => TRUE,
          'type' => 'array',
          'description' => 'Parameters array',
          'default value' => array(),
          'source' => array('param' => 'parameters'),
        ),
        array(
          'name' => 'pagesize',
          'optional' => TRUE,
          'type' => 'int',
          'description' => 'Number of records to get per page.',
          'default value' => variable_get('services_node_index_page_size', 20),
          'source' => array('param' => 'pagesize'),
        ),
      ),
      'access arguments' => array('access content'),
    ),
  ),
  'targeted_actions' => array(
    'attach_file' => array(
      'help' => 'Upload and attach file(s) to a node. POST multipart/form-data to node/123/attach_file',
      'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/node_resource'),
      'callback' => '_node_resource_attach_file',
      'access callback' => '_node_resource_access',
      'access arguments' => array('update'),
      'access arguments append' => TRUE,
      'args' => array(
        array(
          'name' => 'nid',
          'optional' => FALSE,
          'source' => array('path' => 0),
          'type' => 'int',
          'description' => 'The nid of the node to attach a file to',
        ),
        array(
          'name' => 'field_name',
          'optional' => FALSE,
          'source' => array('data' => 'field_name'),
          'description' => 'The file parameters',
          'type' => 'string',
        ),
        array(
          'name' => 'attach',
          'optional' => TRUE,
          'source' => array('data' => 'attach'),
          'description' => 'Attach the file(s) to the node. If FALSE, this clears ALL files attached, and attaches the files',
          'type' => 'int',
          'default value' => TRUE,
        ),
        array(
          'name' => 'field_values',
          'optional' => TRUE,
          'source' => array('data' => 'field_values'),
          'description' => 'The extra field values',
          'type' => 'array',
          'default value' => array(),
        ),
      ),
    ),
  ),
  'relationships' => array(
    'resources' => array(
      'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/node_resource'),
      'help'   => t('This method returns files associated with a node.'),
      'access callback' => '_node_resource_access',
      'access arguments' => array('view'),
      'access arguments append' => TRUE,
      'callback' => '_node_resource_load_node_files',
      'args'     => array(
        array(
          'name' => 'nid',
          'optional' => FALSE,
          'source' => array('path' => 0),
          'type' => 'int',
          'description' => 'The nid of the node whose files we are getting',
        ),
        array(
          'name' => 'file_contents',
          'type' => 'int',
          'description'  => t('To return file contents or not.'),
          'source' => array('path' => 2),
          'optional' => TRUE,
          'default value' => TRUE,
        ),
        array(
          'name'         => 'image_styles',
          'type'         => 'int',
          'description'  => t('To return image styles or not.'),
          'source'       => array('path' => 3),
          'optional'     => TRUE,
          'default value' => FALSE,
        ),
      ),
    ),
  ),

```
> 0 votes

---
Tags: 7, hooks, services
---


# Question
Title: Custom login block that redirects to password protected page that is not published otherwise
I realize that there are many ways and modules to accomplish this with, but this is the one particular way I need it and I'm having trouble finding a good solution. So here is what I'd like to achieve:

A custom block on a page with username and password fields. After entering the right combination (it'll be just one pair probably), the form would redirect the visitor to a content page that is unpublished.

Logged in visitors should not be Drupal users, nor should they go through a registration process. Certain people will know the right user/pass combo and only they should be able to access the protected page.

The Protected Pages module doesn't create a login block, password input only possible on the actual page that is protected.

I tought about creating a custom module with a form that would redirect after entering the right user/pass combo, but if the destination node is unpublished, it won't work anyway.

Do you have any good ideas for this one?

Thank you, Bálint

# Answer
> 1 votes
Giving users permission to view unpublished content could potentially be a security risk, and it's not (easily) possible to restrict it to just viewing a particular content type.

Why not publish the node, but only allow users with a certain role be able to view them using the Content Access module.

Then create a few accounts with this role, setting the usernames and passwords yourself.

Then just use the standard Drupal login form but then alter the redirect once logged in with hook\_user\_login:

```
function hook_user_login(&$edit, $account) {
    if (in_array('your_role', $account->roles)) {
        $edit['redirect'] = 'node/123';
    }
}

```

By creating the accounts this way it means you can use the main Drupal authentication system so reducing the amount of work that you need to do...

---
Tags: 7, users
---


# Question
Title: How to make "Time" part of a date field not required?
Using the Date module, how would one make the Time part of a date field not required when the whole field is set to "Required".

Also if possible, not display the Time on the front end when there's no time specified?

# Answer
> 3 votes
I'm not sure this is possible without some re-engineering of how the date module works, or at least writing your own custom date field.

The `date_field_validate()` function calls `DateObject::validGranularity()` which checks to make sure there are sufficient date parts for the granularity you've chosen. If the field instance is set to be required, it's necessary for that check to pass before you can save the field values. Obviously this check won't pass if you haven't provided all of the relevant date parts.

A simple way around the problem might be to use a field collection, to which you can add two fields: one for the date and one for the time. There is a Timefield module out there, I recommend the dev version as the alpha version has some weird problems.

That method would also help with your display issue as the date and time are now separate fields.

# Answer
> 1 votes
Currently it's not possible but it might be in the future though it's a long standing feature request. Besides the mentioned timefield you could use a select field wich has been described here or CCK Time.

---
Tags: 7, datetime
---


title: Custom Entity with a uid property

text:
# Question
Title: Custom Entity with a uid property
We seem to be experiencing a very unexpected problem.

We have created a custom entity called feature and it has a uid property. The schema is as follows:

```
$schema['feature'] = array(
  'fields' => array(
    'fid' => array(
      'description' => 'feature id',
      'type' => 'serial',
      'not null' => TRUE,
    ),
    'bundle' => array(
      'description' => 'bundle name',
      'type' => 'varchar',
      'length' => 32,
      'not null' => TRUE,
    ),
    'nid' => array(
      'description' => 'Node ID.',
      'type' => 'int',
      'not null' => TRUE,
    ),
    'tid' => array(
      'description' => 'Taxonomy Term ID.',
      'type' => 'int',
      'not null' => TRUE,
    ),
    'uid' => array(
      'description' => 'User ID.',
      'type' => 'int',
      'not null' => TRUE,
    ),
    'created' => array(
      'description' => 'created timestamp',
      'type' => 'int',
      'not null' => TRUE,
    )
  ),
  'unique keys' => array(
    'primary key' => array('fid'),
    'nid-tid-uid' => array('nid', 'tid'),
  )
);

```

An entity is then picked up with

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'feature')
  ->entityCondition('bundle', 'disabled')
  ->propertyCondition('tid', $tid)
  ->propertyCondition('nid', $nid)
  ->addMetaData('account', user_load(1));
$result = $query->execute();

if (isset($result['feature'])) {
  $features = entity_load('feature', array(reset($result['feature'])->fid));
  $feature =  reset($features); // $feature here as the wrong uid
}

```

However, no matter what permutation I try, the uid is always set to 1.

The database has the correct information - so the data is being stored correctly.

The entity has views integration and pulling the data in through views works correctly as well.

Outputting the $feature always gives a uid = 1.

I even have traced through the EntityAPIController with little luck.

I tried loading an unrelated entity (Field Collection Item). This entity does *not* have a uid field. However, after entity\_load it seems that a uid property is set.

Does this mean that having a uid property on an entity is just not possible? There does not seem to be any documentation to suggest that this is the case though.

I know that I can just rename it to aid or something else but am curious as to the cause here.

Thanks...

# Answer
> 0 votes
I left it overnight, and by the following day, the issue was gone.... :-/

---
Tags: 7, entities
---


title: How do I add javascript to a module?

text:
# Question
Title: How do I add javascript to a module?
I'm building a module with a basic form. This form has some js attached to it that I want to keep in the module, so that it's not cluttering my regular scripts file. How do I add it to my module?

I tried to add this is in my .module file but no luck.

```
function mymodule_init() {
drupal_add_js(drupal_get_path('module', 'mymodule') .'/myscriptfile.js');
}

```

What should I do?

# Answer
You can declare the script file inside mymodule.info with

```
scripts[] = myscriptfile.js

```

This way it's gonna be included in every page of your site, exactly the same result you obtain adding it manually to hook\_init.

In case you want it only when you render a form, add this to the form declaration

```
$form['#attached']['js'][] = drupal_get_path('module', 'mymodule).'myscriptfile.js';

```
> 3 votes

# Answer
In a form you can set an #attached value. This value will allow you to attach javascript or css to the form.

I believe that is the best way. Here is an example below. (taken from drupal.org)

```
$form['#attached']['js'] = array(
  drupal_get_path('module', 'ajax_example') . '/ajax_example.js' => array(
  'type' => 'file',
  ),
);

```
> 0 votes

---
Tags: 7, javascript
---


# Question
Title: How can I sort Views output by whether or not field content matches a string?
I feel like there must be a module for this, but I can't find one.

What I have is a field with 4 possible values. I want to sort items with a specific one of the values to the top, then everything else in order by creation date.

In SQL, the query would look something like this:

```
SELECT fields FROM table ORDER BY textfield = "text" DESC, datefield

```

# Answer
Consider two different approaches here:

Add a single view with multiple sort criteria:

Create two views:

* The first view should include a filter criteria with operator "is one of" for the textfield value you want to use (ex. "text") and a sort criteria based on date.
* The second view should include a filter criteria for "is none of" for the textfield value used in the first view (ex. text).
* Within the second view, add a field "Global: View area" within the view header selecting the first view created.

The second option requires additional configuration, but should give you more control over the sorting of the different groups. In addition, using multiple sort criteria for text fields occasionally causes duplicates to appear and the multi-view approach avoids this problem.

**Update**

Check out Views Argument Extras. This module provides a method to sort based on argument criteria (such as arbitrary fields) without using weights. Here's my configuration:

The above configuration will be too simplified for your 'sort by day, then text field, then time configuration', but it's a good start. To sort by day, then text field, then time you'll need to use the date module and limit the elements that it sorts by (checkboxes).

If this is something you plan to apply globally, consider adding the Weight module and sort based on that instead of Views Argument Extras.
> 1 votes

---
Tags: views
---


# Question
Title: How do I let users view, edit or delete their own contents?
I am working on a website where there will be users publishing contents.

How can I restrict users from accessing other users' contents and only able to view, edit or delete their own contents?

# Answer
> 0 votes
After few days of research I finally find an easy way to manage users control over their own content.

* Step 1:

Visit http://drupal.org/project/workspace to download the latest version of "Workspace".

+ Step 2:

Extract the files into a folders on your desktop. The folder will be called "workspace".

+ Step 3:

Login to your site's files via FTP and navigate to /sites/all/. If there isn't a folder called /modules/ here, create one.

+ Step 4:

Upload the "workspace" folder to /sites/all/modules/

+ Step 5:

Go to Administer \>\> Site building \>\> Modules and enable Workspace. You'll need to check only one box.

+ Step 6:

When your users login they'll see a link in the admin menu called "My Workspace". When they click on it they'll see a screen like this:

# Answer
> 1 votes
You can set these permissions at `People > Permissions`. Take a look at the 'Node' section. Also, a very practical module for specific cases is Field Permissions.

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

# Answer
> 1 votes
You can use Node Access Rules module.This module control the access to a certain node or node group by Rules. It allows you to control the access to a node (create/view/edit/delete) by Rules.

# Answer
> 1 votes
What you're talking about is Drupal node access control.

The core's built-in support for node access control is rather course, in particular when it comes to *viewing* content. If your specific requirement is that user shall only be able only be able to view, edit or delete his/her *own* contents, the simplest solution is to *not publish* the content.

You do this by setting the the default state for a new node to unpublished. Navigate to *Administration » Structure » Content types*, and then pick the content type. Under *Publishing options* you untick the option *Published*. Then, to allow user to see his/her own content, navigate to *Administration » People » Permissions* and tick the permission *View own unpublished content* for the authenticated user. To allow the user to edit and delete his/her own contect rick the persmissions *Create new content, Editit own content, Delete own content* for *all* the content types you want your users to be able to use.

The above solution is for Drupal 7 and can be realized with the functionality in core alone.

If you for some reason can not use the solution outlined above, you must use some sort of node access control module to control the access to *view* the node (create new, and edit/delete own can still be controlled by means of core user permissions). There is a page at Drupal.org listing all node access modules, with a capsule review of each. I suggest you take a look at that page to see if you can find a suitable module.

---
Tags: users, nodes
---


# Question
Title: How to get the current active DB in Drupal 6?
You can easily print out the current db\_name, by printing out $db\_url. But there is no clear way in the API that allows you to print out the "key" for the active db. So I have two dbs, namely "testing" and "default". What php code can I run to find out whether I am currently using the "testing" db, or the "default" db?

I'm bascially looking for the inverse of "db\_set\_active". So If I do this:

```
db_set_active("default");

```

What can I call directly after it to find out which is the current active db (i.e. "default")?

# Answer
> 1 votes
Doesn't look like drupal allows it inherently, so I'm posting my hack in the meantime. I'm open to any suggestions on improving this:

```
global $db_url;
$activeDBName = db_result(db_query('select database()'));
$mode = '';
foreach ($db_url as $key => $url) {
    if(strpos($url, $activeDBName) !== FALSE) {
        $mode = $key;
    }
}

```

$mode will then be whatever the active db is.

---
Tags: database
---


# Question
Title: The update manager module makes admin pages very slow, what might be the causes and how could I solve this problem?
All of a sudden, my admin navigation started being slow, very slow. It takes between one and two minutes to load a single page (with very little content). When I unable the update manager module, the problem vanishes. Any hint on what causes this malfunction and how I could solve it? Thanks!

# Answer
Update module is slow when site is behind a router or firewall:

https://drupal.org/node/369145

> The Update Status module attempts to get update information using the internet. Many servers have firewalls that block this.

That means that Drupal tries to access the Internet, but if the site is behind a router or a proxy the petition probably is ignored, so Drupal is 'stalled' waiting for response. When Drupal is tired of waiting (the petition timeouts), usually several seconds after, the page request continues and finllay Drupal delivers the page. You feel that the site is slow, but in fact Drupal has been waiting same as you.

The solution is to disable Update module in dev environments, or allow the site to connect to Internet to get the update information.
> 5 votes

---
Tags: 7
---


# Question
Title: Rules - How can I put a link into an email sent by a rule
I would like to use rules to send an email to my admin staff when a new piece of content is created. It would be great if the email contained a link to the content to make it easier to find. Is there a way to insert the link? Perhaps there is a token that I could use.

# Answer
> 5 votes
You can use the following: `[site:url]user/login?destination=node/[node:nid]/edit`.

This will show login form to the users who are not authenticated and then redirect them to the node edit page.

If the user is already logged in, he/she will be immediately taken to the node edit page.

# Answer
> 1 votes
You can use this: \[node:edit-url\]

---
Tags: rules, emails
---


title: Blogs view for users

text:
# Question
Title: Blogs view for users
I have a drupal page with the blog module. Every user has his own Blog, reachable by site.name/en/blogs/user.name but on the blog entry i have added an new field where i can list all Authors. I need now a view which reads this information out of this and show all blog entries of this Author in his blog. Because now, there is the entry only on the blog of his owner. thanks (drupal 7)

# Answer
I have a solution. Install the Module Entity Reference, then create an multiple field wich is linked to the user Profile, at least you have to add a view to `blogs/%` and there you have to add an context filter wich filters to the field which refers to the Username.
> 0 votes

---
Tags: views
---


# Question
Title: Easy database reconfiguration for migration
I have build a Drupal site on my local development server and I am preparing to move it to my test server and eventually my live server. I know where to find the database settings in my settings.php file, but there only appears to be one set of database configurations. I would like to know if there is a good way to include three different database settings in my settings.php file, one for my development environment, one for my test server and one for my live server. I could simply add a settings section to the file for each and simply comment out the ones that I am not using, but I would like to use an automatic solution, one that can either allow me to specify a setting for all three locations, or tries each setting until it finds a setting that works.

# Answer
> 1 votes
Berdir wrote about a very nice solution some time ago, which also made it into Drupal 8 now.

It means that you keep separate settings.php's, which are included whenever available with a small code snippet.

---
Tags: 7, database, migrations, configuration, testing
---


# Question
Title: Can MySQL 5.6 be used with Drupal 6 and php 5.2.17
A server admin is looking to update the production mysql from the latest version 5.0 to latest 5.6. We are running a Drupal/Pressflow 6.22 and php 5.2.17. I believe this is going to bring on the apocalypse when it comes to things not working, but I need some concrete reasons on what may break and why.

Do anyone have any experience running a drupal 6 on mysql 5.6? Or PHP 5.2 with MySQL 5.6?

I know mysql 5.1 in acted strict mode in MySQL.

Anyone have any insight into if these will play nice with Drupal 6 and it's modules?

# Answer
MySQL 5.6 works fine; using the mysqli driver. PHP 5.4 works after fixing a couple of notices, and php 5.2 works without any modifications.

In your settings.php file change `$db_url = 'mysql://...'` to `$db_url = 'mysqli://...'` to use the mysqli driver; it's that simple.
> 1 votes

---
Tags: 6
---


# Question
Title: How can I change the redirect that happens after a node is edited?
Normally, after a node is edited, the user is sent to the node's display page. I would like to change this so that the user is sent to a different page. Is there a module for this or is there a native setting that I can use?

# Answer
You have a few options.

If you want to install a module and use a GUI you should be able to do that with Rules. Just install the module, and setup a new rule to react on saving new content.

If you do not plan on using Rules for anything else, it is probably wiser to just use a hook\_form\_alter in your custom module. Just edit the forms `$form_state['redirect']` in a submit callback. Something like:

```
function test_form_alter(&$form, &$form_state, $form_id){
  if($form_id=='MY_FORM') {
    array_push($form['#submit'], 'test_userlogin_submit');
  }
}

function test_userlogin_submit(&$form, &$form_state){
  $form_state['redirect'] = 'MY/NEW/PATH';
}

```
> 2 votes

---
Tags: 7, redirection, nodes
---


# Question
Title: A way to put a unique ID on a node based on the taxonomy it has?
I've been tasked with building a system that assigns job numbers categorized by client. Each job number is made up of a 3 letter abbreviation of the client, the current year, and a numerical number, starting from 0 and counting up for each job created.

For example a job # would look like this: ABC1400001

The 2nd job number under client ABC would be ABC1400002 etc etc

ABC = the abbreviated client name 14 = the current year 00001 = the first job created under client ABC

I'm trying to figure out a way to do something like this with drupal where each node would be a job and each client would be a taxonomy term. Grabbing the "ABC" is easy as it could just be the taxonomy term. 14 is easy as it would just be the year. The part that is tripping me up is how to get that numerical value of 00001, 00002, 00003 etc. Then lets say I had another client named DEF the first job under that client would need to start at 00001 as well. So its not as easy as just appending a node ID on to it unfortunately.

Any ideas on how I could accomplish this?

# Answer
This looks very possible with the Serial Field module in combination with Rules and Token modules

Serial Field module page reads:

> This module provides an auto-increment (serial) field.
>
> Unlike Drupal's built-in auto-increment node ID, which is global and shared by nodes belonging to all content types, serial fields are managed per content type (D6) / entity (D7). For example, the serial field of an Invoice instance will generate a unique sequential number (starting at 1, then 2, etc.) exclusively for Invoice instances.
>
> The allocation of serial numbers by this module is atomic. In other words, the serial values are unique even when multiple instances of the same content type / entity are created simultaneously.
> 1 votes

---
Tags: 7
---


# Question
Title: View published content - but only if you posted it
I have two different users on my site, content posters and content reviewers. The posters should only be able to view their own content, but reviewers need to be able to see everyone's content. I tried to set this up using permissions, but permissions only gave me control over editing and deleting (not viewing, except for the over-arching "View published content" which seems to refer to everything.) How do I accomplish my goal? I am using views to present the users with different pages of content... Could I effectively limit content viewing by using views? How can I prevent an unauthorized person from visiting a views page?

# Answer
> 1 votes
Node view Permissions fits perfectly for your needs and it is lightweight too. Its a drupal 7 module.

> Node view permissions module enables permissions "View own content" and "View any content" for each content type on permissions page as it was on Drupal 6. It's as simple as that.
>
> It's implemented in a non-conflict way, so you can use it with any other permissions related module.

# Answer
> 0 votes
You shoukld try the Workflow module. This module is intended to solve problems like the one you have, that's helping with publishing workflows (or other kind of workflows).

> This module allows you to create arbitrary Workflows, and assign them to Entities.
>
> Workflows are made up of workflow states. Transitions between states can be allowed per role. For example, a workflow with the states Draft, Review, and Published could be assigned to the Story node type. Only users with role 'chief editor' can set Stories to the published state. You can set up the Workflow to alter states from form, page, comment and a special workflow tab.

# Answer
> 0 votes
Workflow module as said above is the best option. If that doesn't do what you want you could maybe try https://drupal.org/project/field\_permissions which if I remember off the top of my head has an option for setting permissions for the whole node per content type. It allows you to set some people to be able to view and others to view own etc.

That's another option if the Workflow module is too 'heavy'. However the better option is definitely the Workflow module as mentioned above.

---
Tags: 7, views, users, nodes
---


# Question
Title: Why does user_load($id) NOT return FALSE when an invalid id is passed in?
I'm making a module that lets users manage database records for various organizations. I'm using Drupal 7 and an very new at it. I'm logged in as the admin user. I have a menu item 'cb' that checks args and returns content generated by various functions, here it is in the menu:

```
function org_menu() {
  $items['org'] = array(
    'title' => 'My Orgs',
    'page callback' => 'org_show_orgs',
    'access callback' => TRUE,
  );
  $items['org/create_org'] = array(
    'title' => 'Create New Org',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('org_create_form'),
    'access callback' => TRUE,
  );
  $items['org/search_orgs'] = array(
    'title' => 'Find Orgs',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('org_search'),
    'access callback' => TRUE,
  );
  $items['org/cb'] = array(
    'type' => MENU_CALLBACK,
    'page callback' => 'custom_callback',
  );
  return $items;
}

```

And this is the cb function that determines what I am trying to do, and calls the appropriate content function:

```
function custom_callback () {
  if ( arg(2)=="edit" )
    return org_edit_org();
  if ( arg(2)=="view" ) {
    return org_show_orgs();
  }
  return "<H3>Invalid callback function: '".arg(2)."'";
}

```

and the actual org\_get\_orgs function:

```
function org_show_orgs() {
  global $user;
  $acctid=arg(3);
  if ( !$acctid && $user->uid==0 )
    return array('my_content' => '<H3>My Orgs</H3>Please log in to view your orgs.'.
                    '<BR><H3>Find Orgs</H3>', drupal_get_form('org_search'));

  if ( $acctid ) {
    //return "case1 arg0=".arg(0)."<BR>arg1=".arg(1)."<BR>arg2=".arg(2)."<BR>arg3="
    //              .arg(3)."<BR>arg4=".arg(5)."<BR>acctid=$acctid<BR><BR>";
    $account=user_load($acctid);
    //return "case2 arg0=".arg(0)."<BR>arg1=".arg(1)."<BR>arg2=".arg(2)."<BR>arg3="
    //              .arg(3)."<BR>arg4=".arg(5)."<BR>acctid=$acctid<BR><BR>";
    if ( $account===FALSE )
      return "<H3>Invalid acctid "+$acctid+"</H3>";
    else
      return "<H3>account was not FALSE</H3>";
  }
}

```

cb() gets called correctly and the org\_show\_orgs() function gets called as expected. arg(3) is the user id, so I can allow a user to view another user's orgs.

I hit the url http://example.com/?q=org/cb/view/1 and it works - I see admin's orgs. If I pick a userid for another user, it works - I see their orgs as well. The problem is when I tinker with the url and pass in an id of a user that doesnt exist - then I get all kinds of weirdness. For example, if I hit

http://example.com/?q=org/cb/view/4

If I uncomment that case2 line, I clearly see all my variables are correct:

```
case2 arg0=org
arg1=cb
arg2=view
arg3=4
arg4=
acctid=4

```

but if I try to test if $account===FALSE, I get the maintenance page. If I change the id to 3, I get an 'access denied' page. If I change the id to 2, I see a 'page not found' page. If I try return print\_r($account,TRUE); I get the menus and a completely blank content cell. No error, which I'd get it it was a non-array object. If I try get\_class($account) after I retrieve it, I get the menus but no css, and everything is just listed down the left side, no regions, themes, nothing.

Besides the $account issue, is there a better way to be doing this than that callback menu, or is that the drupal way?

# Answer
> 1 votes
The account test probably is working, but this is wrong:

```
return "<H3>Invalid acctid "+$acctid+"</H3>";

```

If the $acctid is an integer, it's evaluating that and returning an integer. The proper php concatenation operator is '.' (without the quotes), change your return statement to

```
return "<H3>Invalid acctid ".$acctid."</H3>";

```

It'll evaluate to the string you're presumably expecting.

# Answer
> -1 votes
Actually, the value returned by user\_load() is an array. If the $id is not valid, it will return an empty array.

Try changing your test to `if (empty($account))`.

# Answer
> -1 votes
These tests will not work in recent PHP, because account is an object array. Use the following condition: `if (count($account) > 0)`

---
Tags: 7, users
---


# Question
Title: Custom image style used on image upload causing errors
The site is running in a Windows Server environment.

I have a custom content type, which has a single "image" field.

I have created a image style, called "slider" with the dimensions 800x480

Images uploaded have some issues:

1. The original file names are kept but all uploads stored in the same folder. Ideally these names would be timestamped or hashed to prevent duplicate collisions
2. The file dimensions do not seem to be applied in resizing the image, does this only apply if the uploaded image is larger? Do I add a "scale" filter if I want to enlarge the image to fit the dimensions?
3. Uploaded images go to:

http://www.mydomain.local/sites/default/files/park/pics/BHP\_beach.jpg (this exists)

but the preview: http://www.mydomain.local/sites/default/files/styles/slider\_desktop/public/park/pics/BHP\_beachjpg?itok=lR2G\_oG3 (this does not exist)

This latter path is not valid, rather there is no image by this name in this directory??? Why are no files being written here? I just noticed another error which is probably related to the last point I make:

> Warning: imagejpeg() \[function.imagejpeg\]: Unable to open 'public://styles/slider\_desktop/public/park/pics/BHP\_beach.jpg' for writing: Invalid argument in image\_gd\_save() (line 270 of C:\mywebsite\modules\system\image.gd.inc).

How do I enable public:// stream wrappers???

Lots of questions I know...but all related to the same thing I think.

# Answer
1. Files will be renamed to prevent collisions. Off the top of my head it adds something like `_1` to the filename.
2. Yes that's correct. I'm not sure about the scale but that sounds like it would work. If the image is too small, it will get scaled up. If the image is too big, it will be resized down then scaled and the scaling shouldn't have any effect.
3. That all sounds like it's working as intended. You have a simple problem with directory permissions within your `sites/default/files` directory. If you're in a dev environment try doing `chmod -R 777 files` (Then you know it's a permissions problem and you can set them properly). Problems like this are usually either because the file cannot be read or written, in your case it looks like writing. The PHP stream wrappers mentioned in the error message are enabled and working, don't worry about that, it's standard PHP. If `chmod` doesn't work, try changing ownership with `chown`.
> 0 votes

---
Tags: media
---


# Question
Title: Paginate results of entity reference widget type
I have entity reference field with checkboxes/radio as the widget type. The issue is the I have hundreds of nodes and this results in a having a big list. Is there a way to paginate the results or have a "load more" button/link which loads more results via ajax?

I should mention that I tried the entity\_view\_widget module but had other issues with it and can't really use it for this project.

# Answer
Found a nice article related to Entityreference Multiselectors here.

You can choose one from variety of options mentioned in above article which suggests using of

Hope one of the above works for you :-)
> 0 votes

---
Tags: nodes, paging, entities
---


# Question
Title: What is causing this error message when using search module?
I have a website using drupal 7. It has a site search that produces and error only when I search the word "application".

This is the error:

Fatal error: Cannot redeclare my\_form() (previously declared in /home/leader40/public\_html/modules/php/php.module(80) : eval()'d code:8) in /home/leader40/public\_html/modules/php/php.module(80) : eval()'d code on line 257

Any ideas on how to solve this or why it's happening?

# Answer
> 1 votes
You are declaring **my\_form** function in two places somewhere in your block / view / Node where you are using php as filter. That is causing above issue.

Since you see above issue only in search page it should be an issue with blocks that are enabled in search page or search content...

Search in your database with keywords my\_form using phpmyadmin or some other tool on all tables that will give you an idea from where the php code is getting executed !

---
Tags: search
---


# Question
Title: Calling form validation function from new button
I've attached a **Process** button on the node edit form. But on clicking it - in it's validation function `form_set_error` is not working.

In my form\_alter I've this code:

```
$form['buttons']['process'] = array(
            '#type' => 'submit',
            '#value' => 'Process',
            '#validate' => array('disavow_process_validate'),
        );

        $form['#validate'][] = 'disavow_validate';

```

So on pressing "Process" button validator function `disavow_process_validate` is called with $form and &$form\_state. But `form_set_error` and assigning values in the $form\_state are not working as working in the normal validation function `disavow_validate`

**What could be the problem?**

# Answer
See below example which works perfectly...

```
function drup_custom_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "page_node_form" && arg(2) == "edit") {
    $form['buttons']['process'] = array(
            '#type' => 'submit',
            '#value' => 'Process',
            '#validate' => array('disavow_process_validate'),
    );
  }
}

function disavow_process_validate($form, &$form_state) {
  form_set_error('title', 'Something wrong here !');
}

```

Please update what you are trying to do inside validate function..
> 1 votes

---
Tags: 7, forms
---


# Question
Title: How to check if field in Field Collection is required?
I'm running into a problem of programmatically checking fields in a field collection.

What I want to do is loop through all fields within a field collection and check which ones are required.

I've tried these codes so far but haven't got any positive results.

```
$collections = field_collection_item_load_multiple($collection_ids);
foreach ($collections as $collection) {
   foreach($collection as $key => $va) {
        if (strpos ($key, 'field') !== false) {
            if (isset($va['und']) && is_array($va ['und']) && isset($va['und'][0]['value'])) {
                print "Field ".$key." ".$va['und'][0]['value'];
            }
        }
    }
}

```

This shows me the data and the label of the fields, not really their properties.

Thank you for your help.

# Answer
> 0 votes
Great Question :-) After re-engineering Field UI module found a simple way to retrieve above details...

```
  $bundle = field_extract_bundle('field_collection_item', 'field_my_collection_fields');

  $instances = field_info_instances('field_collection_item', $bundle);

  foreach ($instances as $field_name => $field_properties) {
   if ($field_properties['required'] == 1) {
     drupal_set_message($field_name . " is  required");
   }
   else {
     drupal_set_message($field_name . " is  not required");
   }
  }

```

Replace field\_my\_collection\_fields with your field collection field name in above code ...

---
Tags: entities
---


# Question
Title: How do I let users be able to view, update and delete their own content?
I want to let users view a list of their own content and also be able to edit or delete them same as "/admin/content" page.

However, giving access to edit and delete their own content can be achieved using Node Access Rules or setting the access to user type at Permissions tab.

Thanks for the help.

# Answer
> 0 votes
The easy way will be to use Workspace module

* Step 1:

Visit http://drupal.org/project/workspace to download the latest version of "Workspace".

+ Step 2:

Extract the files into a folders on your desktop. The folder will be called "workspace".

+ Step 3:

Login to your site's files via FTP and navigate to /sites/all/. If there isn't a folder called /modules/ here, create one.

+ Step 4:

Upload the "workspace" folder to /sites/all/modules/

+ Step 5:

Go to Administer \>\> Site building \>\> Modules and enable Workspace. You'll need to check only one box.

+ Step 6:

When your users login they'll see a link in the admin menu called "My Workspace". When they click on it they'll see a screen like this:

# Answer
> 1 votes
You can use Views. Create a view of content on your site and use table format, list the fields as listed in admin/content. Add a relationship to the content:author so as to get access to the user table. In contextual filters (arguments for drupal 6), add user:uid =\> provide default value =\> user id from logged in user. Add a page display to your view and optionally provide a normal menu entry (or do that with the menu system) and Save your view. Go to the page you created, you should see only the content you created. To be able to mass delete or perform other bulk operations on the content, use Views Bulk Operations

---
Tags: users, nodes
---


title: Advanced Forum: Hide Form Label

text:
# Question
Title: Advanced Forum: Hide Form Label
How can I hide the label of form in advanced forum?

My content type:forum topic-\>comment display-\>comment:label is already set to be hidden

Edit : I realised that it's a form

# Answer
> 1 votes
1. Log into the Drupal 7 admin dashboard.
2. Using the top menu bar, locate and click on the Structure option.
3. From this next page, click on the Content Types link.
4. On the Content Types page, find the type of content you want to work with. I have been working with Basic Pages so I will stick with that. After locating your desired content type, click on the correct Manage Display link.
5. From this page you will need to find the filed row you want to hide and then the Label dropdown. Set the Label field to to remove the label from the image field.
6. Once finished, click on the Save button at the bottom.
7. Clear cache

Or you can use Automatic Nodetitles module

"auto\_nodetitle" is a small and efficient module that allows hiding of the content title field in the form. To prevent empty content title fields one can configure it to generate the title by a given pattern.

---
Tags: entities, nodes
---


# Question
Title: How do I set a node/page's background image to that content's image?
I've installed both 'Background Image' and 'Dynamic Background' but am having trouble trying to configure them for my situation. In the website I am trying to edit, there are content types of 'Performer,' 'Venue' among others. Now each content type has an image as one of their fields and I would like to have that image as the background image for that content's page.

Background Image only gives me option to do this for 1 content type, and when I tried setting it up, nothing appears.

I'm pretty sure I could do this with Dynamic Background, but the process would be really inefficient; I would have to add the pictures again to Dynamic Background's library.

So is there another way to do this? Or what can I do with Background Image to make it work?

# Answer
This can be done without installing extra modules:

1. Add an image field in the content types you want to enable a dynamic background image.
2. Use this code: template.php:

```
function THEME_preprocess_page(&$vars) {
    if (!empty($vars['node'])) {
        $node = $vars['node'];
        if (!empty($node->field_background_image)) {
            $image = file_create_url($node->field_background_image[LANGUAGE_NONE][0]['uri']);
            $vars['background_image_css'] = 'style="background: url(' . $image . ') no-repeat scroll center center / cover #FCFCFC;"';
        }
}
}

```

Add this in your div#content in page.tpl.php: `print (!empty($background_image_css)) ? $background_image_css : ''; ?>`

Updated version: template.php:

```
function THEME_preprocess_page(&$vars) {
 $node = menu_get_object('node');
 if (!empty($node) && !empty($node->field_background_image)) {
        $image = file_create_url($node->field_background_image[LANGUAGE_NONE][0]['uri']);
        drupal_add_css('div#content {background: url(' . $image . ') no-repeat scroll center center / cover #FCFCFC; }', array('type' => 'inline'));
 }
}

```
> 3 votes

# Answer
Background Image is using a content-type as some kind of interface for "global" background-images. So if you want to tie your backgrounds to nodes, i recommend the BackgroundField module.

> BackgroundField started as an extension of the CCK ImageField that allows a CSS selector and background attributes to be set for a content-type. This is particularly helpful for allowing your node authors to add images to a node that are integrated into the theme of the site. With the inclusion of the Image field in Drupal 7, BackgroundField was rewritten to extend that core functionality.
> 0 votes

---
Tags: 7, media
---


title: How to send emails to the subscriber?

text:
# Question
Title: How to send emails to the subscriber?
I have two content types movie types(say comedy, horror, action are node titles) and movies. where I am using movie types node titles as a node reference in the movies content type. here user can subscribe to the movie types and can watch all the movies under the type. Now where i am stuck is to send a mail to the subscriber when new movie is uploaded under the type he/she subscribed. Please help me to sort out this issue.

# Answer
Check out Subscriptions.

> This module enables users to subscribe to be notified of changes to nodes or taxonomies, such as new comments in specific forums, or additions to some category of blog. Once enabled, all nodes will have an additional link that allows the user to change their subscriptions. Users have tab on their user screen to manage their own subscriptions. Users can also set an auto-subscribe function which notifies the user if anyone comments on posts they have made. Admins can turn this on by default.

It provides a very powerful and flexible subscription framework, and there are many ways to configure subscriptions with this module.

One that probably will match your use case is to use taxonomy terms for the type of movie (comedy, horror, action, etc.) and let the users subscribe to the type of movie they're interested in by taxonomy term.
> 0 votes

---
Tags: rules, flags
---