# Question
Title: How do I divide taxonomy term pages by content type?
Drupal out of the box lists all of the content tagged with a term in a single list on a terms page. I would like to split up that list into sub pages based on content types tagged with that term. See mockup below. Seattle is the term page and the "Attractions, Museums, Restaurants and Shopping" are content types tagged with "Seattle". To achieve this, i cannot use quicktabs as it requires an admin to create a new quicktab collection everytime a new city is created. Also, panels is not an option on this project either. I am thinking it they are just views pages, with a term id from URL contextual filter, but I am lost on how to add them as secondary tabs on the term page. Unless I am heading in the worng direction. I would love some advice.

# Answer
> 2 votes
A couple approaches come to mind, I will outline the one that does not use panels.

Start by overriding the default taxonomy page by enabling the one that comes with views. At this point you will have the same behavior as the default taxonomy pages.

Clone the default taxonomy view and disable the clone (this is case you want to restore the view).

Now back to the taxonomy view

Remove the existing two contextual filters (not this means the depth feature will no longer be available)

Add a contextual filter on "Content: Has taxonomy term ID" Add another on "Content: Type".

Change the path to "taxonomy/term/%/page" (for page use the content type machine name you want for this tab)

Change "menu" setting to "default menu tab"

(A) Clone the "Page" display, I gave by clone the name of the content type for the tab

(B) Change the path so "page" is replaced with the next content type you want.

(C) Change "menu" setting to "menu tab"

Repeat (A) (B) and (C) for each content type/tab

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


# Question
Title: Trouble with Feeds Import CSV on Localhost
I'm using feeds node importer to import a csv file on my disk. It seems like no matter what I do, select the file from file system or put in the path for the file. I always get Error Message "Resource is not a file or it is an empty directory".

my localhost is at /var/www Drupal 7 Folder: /var/www/drupal7 I stored the file at /var/www/drupal7/sites/default/files/feeds/bsif.csv so I put the file path as public://drupal7/sites/default/files/feeds/bsif.csv but it's not working

# Answer
> 3 votes
* In the case where you manually upload the file and then map to it, try public://feeds/bsif.csv
* In the case where you try to upload using your browser, it should be working fine. It could be that you're unable to upload files in general, not just with the feeds import module. **Check your server's access to upload to /sites/default/files**... it could be that only your account has access to place the file there. Also, Apache/PHP uses a tmp directory for file uploads, so it will need access there as well.

---
Tags: feeds
---


# Question
Title: Allowing a user role to edit only their own content
I am having some difficulty setting up a user role that can access the admin/content/node section of the site but only view their own content.

For the user role i have some permissions set like so (events is a custom content type)

* **create events content**
* **delete own events content**
* **edit own events content**

The admin/content/node will not appear unless i set a permission.

* **administer nodes**

This allows the user role to create, edit, delete any content. Definitely not what i need!

Reference:

Can anyone shed some light on how to allow user roles to only access their own content?

# Answer
Your best bet would be to create a view that duplicates this functionality but only references content to the currently logged in user. You could then add in View Bulk Operations to add the edit/delete links usually found on that page.

You could give the view a path of /admin/content/node/self maybe.
> 2 votes

---
Tags: 6, users
---


title: revert view option is missing

text:
# Question
Title: revert view option is missing
I have exported my view, and I want to revert the same in other site environment; the revert view option is missing. Am I missing anything?

I am using Drupal 7 and Views 3.

# Answer
It should be in "admin/structure/views", click the little arrow next to "edit" link under Operations column. If your view has changed from what's exported in code, it should display "revert" option there.
> 1 votes

---
Tags: views, importing-exporting
---


title: How to access user account fields?

text:
# Question
Title: How to access user account fields?
When I look at $user like this

```
global $user
dpm($user);

```

I do not see the user account fields I added. How can I access them?

# Answer
You need to use:

```
$account = user_load($user->uid);

```

Then, dump the `$account` object and you will see profile field.
> 6 votes

# Answer
The global variable `$user` doesn't contain all the properties you would find in a user object; in particular, it doesn't contain the fields associated with the user entity. If you need the complete user object, you need to use the following code.

```
$account = user_uid_optional_load();

```

Without any argument, user\_uid\_optional\_load() returns the user object loaded from the database for the currently logged in user. If you have a user ID (e.g. you don't need the user object for the currently logged in user, but the user ID is passed to your function as parameter), then it is better to use the following code.

```
$account = user_load($uid);

```
> 1 votes

---
Tags: 7, users
---


title: Views Full Pager alignment

text:
# Question
Title: Views Full Pager alignment
What would be the easiest way to make the Views PAGER text on a view aka first previous next etc, align center in the view?

Thank you!

# Answer
> 1 votes
In Drupal 7, Views 3, we added text-align: center to our stylesheet:

```
.item-list .pager {
    text-align: center;
}

```

And to make it only apply to one specific view:

```
.view-id-my_view_name.view-display-id-page_1 .item-list .pager {
    text-align: center;
}

```

---
Tags: paging
---


# Question
Title: Create a node programmatically on installing a module
I would like to have my module to create new nodes (page) when being installed and removing these pages on uninstall.

I tried the following with no success in my mymodule.install file:

```
<?php

function mymodule_install() {

  $node = new stdClass(); // We create a new node object
  $node->type = "page"; // Or any other content type you want
  $node->title = "Your title goes jere";
  $node->language = LANGUAGE_NONE; // Or any language code if Locale module is enabled. More on this below *
  $node->uid = 1; // Or any id you wish
  $node->path = array('alias' => 'your_node_path'); // Setting a node path
  node_object_prepare($node); // Set some default values.

  // Let's add standard body field
  $node->body[$node->language][0]['value'] = 'This is a body text';
  $node->body[$node->language][0]['summary'] = 'Here goes a summary';
  $node->body[$node->language][0]['format'] = 'filtered_html'; // If field has a format, you need to define it. Here we define a default filtered_html format for a body field

  $node = node_submit($node); // Prepare node for a submit
  node_save($node); // After this call we'll get a nid

}

```

This code is cut n' paste from this page.

When I disable/enable the module, the page is not created (at least it does not appear in Content and in the node table of the database).

How should I do it please?

# Answer
The problem is that install/uninstall and enable/disable are two separate things in Drupal.

When you enable or disable a module, `hook_enable()` and `hook_disable()` are invoked respectively.

When you install or uninstall a module, `hook_install()` and `hook_uninstall()` are invoked respectively.

If you want to keep your code in `hook_install()` / `hook_uninstall()` you'll need to disable the module, and then uninstall it at http://mysite.com/admin/modules/uninstall. Once you re-install it (which will also enable it), your code will be run.

It might be worth having a think if this code would be better served in `hook_enable()` / `hook_disable()`, but it will depend on your particular situation.
> 6 votes

---
Tags: nodes, installation
---


title: Extracting Views SQL

text:
# Question
Title: Extracting Views SQL
I would like to create a MySQL view for another application looking at the Drupal Database. I thought I would get a jump start on figuring out the select statement needed by creating a Drupal View, then copying the generated SQL output. After doing this however, it doesn't seem that the actual SQL statement is outputted. From Drupal views it is showing:

```
SELECT node.title AS node_title, node.nid AS nid, node.uid AS node_uid, node.created AS node_created, 'node' AS field_data_field_ticket_category_node_entity_type, 'node' AS field_data_field_client_username_node_entity_type, 'node' AS field_data_field_ticket_hostname_node_entity_type, 'node' AS field_data_field_ticket_priority_node_entity_type, 'node' AS field_data_field_ticket_source_node_entity_type, 'node' AS field_data_field_ticket_type_node_entity_type, GREATEST(node.changed, node_comment_statistics.last_comment_timestamp) AS node_comment_statistics_last_updated, 'node' AS field_data_field_ticket_owner_node_entity_type, 'node' AS field_data_field_vis_group_node_entity_type, 'node' AS field_data_field_ticket_status_node_entity_type, 'normalizedticket:page' AS view_name
FROM
{node} node
INNER JOIN {node_comment_statistics} node_comment_statistics ON node.nid = node_comment_statistics.nid
WHERE (( (node.status = '1') AND (node.type IN  ('ticket')) ))
ORDER BY node_created DESC
LIMIT 10 OFFSET 0

```

I don't understand what it is doing here: `'node' AS field_data_field_vis_group_node_entity_type` Is views doing some additional processing after this to get the data? Is there a way to get a query that when run against MySQL directly, it will output similar results to that of views?

# Answer
I believe your primary question is:

> Is there a way to get a query that when run against MySQL directly, it will output similar results to that of views?

You're probably getting an error when you try to run the query when copied directly from Views UI. **Change the {node} to myprefix\_node**, changing myprefix\_ to the prefix you gave your tables. If you didn't supply a prefix than simply replace {node} with node.

To respond to your other question:

> I don't understand what it is doing here: 'node' AS field\_data\_field\_vis\_group\_node\_entity\_type Is views doing some additional processing after this to get the data?

Views creates aliases for the columns that are returned by the query so that it can more easily reference it later on. In this case it is creating a hard-coded value of "node" for each result, which is interesting. And the hard-coded value has an alias of field\_data\_field\_vis\_group\_node\_entity\_type.
> 3 votes

---
Tags: 7, views, database
---


# Question
Title: Export content in features using UUID features
I read the UUID feature description and it says it is used to export content in feature. I installed the module but did not know how to export the content.

# Answer
> 6 votes
The uuid module has been reworked, and, as of 2012.05.25, uuid\_features has not been updated to address those changes (though there is a patch RTBC).

In the meantime, to export nodes using uuid\_features in Drupal 7:

* Install features version 7.x-1.0-rc2.
* Install uuid **version 7.x-1.0-alpha1**. *(Not the latest version.)*
* Install uuid\_features version 7.x-1.0-alpha1.
* Enable the `features` module, the `uuid` module, the `uuid_node` module, and the `uuid_features` module
* Go to Configuration \> System \> Universally unique identifiers, and click the "Create missing UUIDs" button
* Go to Structure \> Features \> Create feature, and from the "Edit components" dropdown, select "Content: uuid\_node", then pick the nodes you'd like to export into your Feature

# Answer
> 0 votes
Another way is using defaultcontent module

---
Tags: 7, entities, features
---


# Question
Title: Bulk upload via Form API, or, Please Warn Me
It appears that Drupal 7 lacks a good, user-friendly bulk node creation/file uploading module, and I'm wondering why.

Specifically, I'm wondering what unforeseen issues I'd run into if I tried to create my own. What hook would I use? What do I need to know about saving files and creating nodes out of them before embarking on this task? What terrifying monsters must exist in this terrain that it's never been tread?

My specific plan so far is to use the Form API and hook\_form\_alter to create a webform with a field that can do multi-uploads of images and then, upon submission, generate nodes with Title = image name and an image field that will get populated with the location of the image file.

Has anyone out there attempted anything similar with Drupal 7, and if so, what were your results / what warnings would you give?

# Answer
> 2 votes
I don't think there is any particular difficulties in bulk creation of a nodes from a set of uploaded files. What would be difficult and probably explain why there is not such feature implemented in Drupal 7 is that it would be difficult to make it generic and re-usable. Mapping files to node is not a straightforward process. Variability is probably to high to allow a meaningful re-usable implementation.

If you plan to do write custom code, don't start with Webform. Webform is great for forms that are content to be edited by end users of the site/CMS. They are not designed to be a developer tool to create complex forms with custom backend behaviors. Using Webform will force you to deal with two form APIs in code. While one of them is designed to serve UI users, not developer.

You, or your user, would probably love to have a single widget to upload multiples files (as opposed to multiple file form element). But I suggest you first get a working solution that rely on the Form API and the available file widget. Drupal's API are build to work with standard and old-style browser to server interactions. Introducing new interactions model early into the mix will likely make thing unnecessary difficult by forcing you to learn and understand Drupal's API and inner working only to find workaround for its limitations. Once you get a working solution, search solutions to build a better UI/UX using progressive browser side enhancement. OR at least, refactoring a working solution build on sane and understood bases.

Since processing multiple files and creating multiple nodes is likely a long running operation, you should use the Batch operations API.

# Answer
> 1 votes
One possible reason is that front-facing bulk node creation isn't commonly required functionality, at least in my experience. This ability is usually confined to privileged users who can use the Feeds module.

---
Tags: nodes, forms, media, files
---


# Question
Title: Inserting a select box before the search box (Drupal 7)
I am pretty new to Drupal dev world. I wanted to know how to insert a select box before the search box. I used the below code to alter the search form and set the #weight to a higher value but the select box still shows up after the search box.

```
function mymodule_form_search_block_form_alter(&$form, &$form_state) {
  $form['my_field']= array(
    '#type' => 'select',
    '#title' => t('whatever'),
    '#options' => array(
      0 => 'option1',
      1 => 'option2',
    ),
    '#default_value' => 255,
    '#weight' => 10,
  );
}

```

# Answer
If you need the form field to be placed before any other form field present in the form, you need to use, for the weight, a lower value than the one used from the present form fields. The default value is 0; use a negative value to be sure the form field is always shown first (e.g. −200).

search\_box() doesn't use any value for the field's weight, which means the default value is used.

```
  $form[$form_id] = array(
    '#type' => 'textfield',
    '#title' => t('Search'),
    '#title_display' => 'invisible',
    '#size' => 15,
    '#default_value' => '',
    '#attributes' => array('title' => t('Enter the terms you wish to search for.')),
  );
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Search'),
  );
  $form['#submit'][] = 'search_box_form_submit';

```

I have used the following code in a test module.

```
function code_testing_form_search_block_form_alter(&$form, &$form_state) {
  $form['my_field'] = array(
    '#type' => 'select',
    '#title' => t('whatever'),
    '#options' => array(
      0 => 'option1',
      1 => 'option2',
    ),
    '#default_value' => 255,
    '#weight' => -200,
  );
}

```

The search form appears as in the following screenshot.
> 0 votes

# Answer
Lowering the `#weight` will float and increasing it will sink the element in the form.

The `#weight` property is always honored by drupal\_render() function only if whole form is rendered at once. But if form is rendered manually by parts then there is no way except to override it.
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Regular session table crashes, on a large multi domain, multi site Drupal set-up
I have recently been assigned to a project that has regular session table crashes.

Drupal outputs an error like this one: "Warning: Table './\[database\]/sessions' is marked as crashed and should be repaired ..."

The problem with this site is that it started as a small drupal site and various companies have added (custom) modules to it. The site has also been ported to a number of different hosting providers with varying results. Currently it is being hosted at OVH on a shared hosting setup.

The site is rather large now with a constant base of 20 users inserting data simultaniously (on different accounts but through the drupal interface), mostly pictures through a multi upload module. At the same time there is a lot of traffic coming from anonymous users (who do not upload anything at this point).

I think the problem might be the shared hosting platform. I think it might not be able to cope with all of the different inserts and just crashes... Normally I would see if I could cause the crash in some way, but I can't take the site down since it will result in a major financial loss to the company.

I've read some other posts here regarding a large session table where they mentioned the "ini\_set('session.gc\_maxlifetime', 200000);" line in the settings.php file. The "answer" was to reduce the amount of sessions to 900-1800 which would result in a smaller session table, but I don't know if this would solve the problem?

To make matters worse my client cannot give me any information on when the crashes occur, if they are perhaps caused by using a custom module, etc. The site is running on Drupal 6.

I realize there is not a lot of useful information in my post and I apologize for that. I am a new Drupal developer and I don't know how to address this problem. (The developer who was handling this issue before I got here quit...)

Any help in this matter would be appreciated.

Thank you.

# Answer
I would convert the user & session tables to InnoDB. I would also check the memory limits for MySQL. It's not the most ideal tool, but if you're in a shared environment you can install a copy of Drupal Tweaks (http://drupal.org/project/drupal\_tweaks) and see if you are able to alter any of the MySQL configuration directive such as memory limit.
> 1 votes

---
Tags: theming, sessions
---


# Question
Title: How do I inspect from a user's view how a given page element was created by Drupal?
I would like to be able to access a Drupal site as a given user/user-type (maybe using Masquerade) and from their view of the site be able to inspect how/where the page's configs/scripts/modules/nodes/etc were loaded from.

**Background:** It's possible in the next week I'll need to take over 10+ existing Drupal sites and most likely the maintenance for the sites will be driven by request like "On this page, I'd like to change this." While it's likely that I'll just have to use what I know of Drupal and hunt down where/how the given page elements are being created/managed, it would be nice to have the option to inspect how/where a given page element is being set within Drupal given a URL and the user that accessed it; think Firebug for Drupal.

If possible. it would be nice if this worked for 6 and 7, since the sites I believe are in 6, but will likely be ported to 7.

# Answer
> Think Firebug for Drupal?

Try the Drupal for Firebug module and associated Chrome/Firefox extension :)
> 3 votes

# Answer
Anything that comes close in my mind is Devel Themer. But I don't think you're supposed to install this on a live website, only on dev servers.
> 1 votes

# Answer
I would have to second the vote for Firebug, (or better yet, Chrome's Inspect).

You will find. I'm sure with a certain amount of frustration, that the source of a page can come from a multitude of sources. Firebug or Chrome inspect will take you a long way in dropping hints as to how it was constructed. Then, just start looking for the code that did the deed.

As an aside, I don't think you'll get much milage from Devel for this particular problem.
> 1 votes

---
Tags: entities
---


# Question
Title: How to get rid of text box artifact with Fivestar module?
I'm using Drupal 7.14 and Fivestar 7.x-2.0-alpha2. There is a text box artifact displayed below the stars on all nodes with a Fivestar field (see screenshot below).

Here is the HTML/CSS source for this screenshot:

```
  <span rel="sioc:reply_of" resource="/node/1" class="rdf-meta"></span><div class="field field-name-comment-body field-type-text-long field-label-hidden"><div class="field-items"><div class="field-item even" property="content:encoded"><p>great</p>
</div></div></div><div class="field field-name-field-reader-rating field-type-fivestar field-label-above"><div class="field-label">Reader Rating: </div><div class="field-items"><div class="field-item even"><div class="clearfix fivestar-user-stars"><div class="fivestar-static-form-item"><div class="form-item form-type-item">
 <div class="fivestar-default"><div class="fivestar-widget-static fivestar-widget-static-vote fivestar-widget-static-5 clearfix"><div class="star star-1 star-odd star-first"><span class="on">3</span></div><div class="star star-2 star-even"><span class="on"></span></div><div class="star star-3 star-odd"><span class="on"></span></div><div class="star star-4 star-even"><span class="off"></span></div><div class="star star-5 star-odd star-last"><span class="off"></span></div></div></div>
<div class="description"><div class="fivestar-summary fivestar-summary-"></div></div>
</div>

```

I suspect that `<div class="fivestar-summary fivestar-summary-"></div>` is what is creating this empty text box.

This empty box being shown is despite having chosen `No text` in the `Text to display under the stars` dropdown menu for the Fiverstar field at `/admin/structure/types/manage/$content_type/display` (where `$content_stype` is a dummy for whatever content type I am editing).

Am I missing something?

* Is there another option somewhere to get rid of this annoying text-box?
* Is this the default behavior of Fivestar/would I need to manually modify Fivestar to fix this?
* Or is this a bug that noone has reported yet (I couldn't find anything that sounded like this issue here)? I would think that if this was a bug someone would have reported it already (it is pretty noticable) so I'm inclined to think I am just missing something--but if people think that this is a bug, please indicate as much and I will remove the question and file an issue!

Thanks in advance for any help.

# Answer
> 1 votes
Can't you get rid of it with CSS? `display: none;`

---
Tags: rating, entities
---


# Question
Title: How to configure Compass module with Basic theme?
I am trying to use compass framework with Drupal 7, Basic theme and Compass module on my local hosting on Windows. It is already installed on my computer.

Should i install it to my local webserver again somehow, how can i know the path of existing Compass exutable?

# Answer
Well the only real answer i can give is set up a real webserver on Unix system with ruby (rails or without rails) and use whatever you want. I did not managed to get it running on windows. But ---- windows, lads
> 0 votes

---
Tags: 7
---


# Question
Title: Prevent CSS/JS query hash when preformance is disabled
When working in a dev environment with performance caching and aggregation turned off is there a standard way to prevent the cache clear hash from being appended to CSS/JS file names?

I'd like to avoiding hooking into the output and removing this manually in a dev only module.

# Answer
Here's the solution (theme based) in template.php

```
function MYTHEME_process_html(&$vars) {
  if (variable_get('environment') == 'development' && !stristr($_GET['q'],'flush-cache')) {
    $vars['styles'] = preg_replace('/\.css\?.*"/','.css"', $vars['styles']);
  }
}

```

NOTE: This assume you have an environment setting in your settings.local.php file like so... `$conf['environment'] = 'development';` or `$conf['environment'] = 'production';`
> 2 votes

---
Tags: theming, caching, performance
---


title: How do I disable comment moderation?

text:
# Question
Title: How do I disable comment moderation?
I want to disable comment moderation and I want to show all comments by default. In the comment settings under content type, I can't find anything for this.

How do I disable comment moderation?

# Answer
Visit the /admin/people/permissions page. Select the *Post comments* and *Skip comment approval* permissions for the roles for which you want to disable comment moderation.

>
> 7 votes

---
Tags: 7, comments
---


# Question
Title: How to write a Drupal 7 query with "count" and "having" properties?
I am unable to make the following query work in drupal7 standards..Can anyone help me with this? Its little urgent...

```
SELECT n.nid AS nid, n.title AS title, count(n.title) AS ncount
FROM node n
INNER JOIN taxonomy_index tn ON n.nid = tn.nid
WHERE (n.type = 'test')
AND (tn.tid IN( 23,37))
AND (n.title LIKE '%name%')
AND (n.status = 1)
GROUP BY n.nid
HAVING ncount = 2

```

# Answer
> 25 votes
This is off the top of my head so use caution...

```
$query = db_select('node', 'n')
  ->fields('n', array('nid', 'title'))
  ->condition('n.type', 'test')
  ->condition('tn.tid', array(23, 37))
  ->condition('n.title', '%' . db_like('name') . '%', 'LIKE')
  ->condition('n.status', 1)
  ->groupBy('n.nid');

// Add the COUNT expression
$query->addExpression('COUNT(n.title)', 'ncount');

// Add the HAVING condition
$query->havingCondition('ncount', 2);

// Add the JOIN
$query->join('taxonomy_index', 'tn', 'n.nid = tn.nid');

$results = $query->execute();

```

---
Tags: 7, hooks, database
---


title: Why _block_load_blocks() does not work?

text:
# Question
Title: Why _block_load_blocks() does not work?
\_block\_load\_blocks() returns an empty array. `block_list($region)`, which uses `_block_load_blocks()` returns nothing as well. Why?

# Answer
There should be at least a block, as the "Main page content" block is always associated with a region. You always need to select a region for that block, as the "-None-" option is not available when selecting a region for it.

The list of blocks can be altered from modules. If a module is removing the "Main page content" block from the list, it doesn't appear in the list, and the list would be empty, if there aren't any other enabled blocks. `_block_load_blocks()` contains the following code.

```
$block_info = $result->fetchAllAssoc('bid');
// Allow modules to modify the block list.
drupal_alter('block_list', $block_info);

```
> 1 votes

---
Tags: 7, blocks
---


# Question
Title: How can I add new components to a fieldset?
I'd like to customize the webform everytime the user saves a webform node. I'm using rules with a custom action that updates the webform when the user saves the node. Looking at devel, I haven't been able to figure out what the proper key to specify a parent fieldset is.

In my action I have the following:

```
for ($j = 1; $j <= 5; $j++) {
  $node->webform['components'][$i] = array(
    'nid' => $node->nid,
    'cid' => $i,
    'pid' => 0,
    'form_key' => "participant$j",
    'name' => "Participant",
    'type' => 'fieldset',
    'value' => '',
    'weight' => $j,
    'display' => array(
      'addmore' => $i,
    ),
    'extra' => array(
      'description' => 'Please provide the participant information listed below. Required items are denoted with an asterisk.',
      'title_display' => 0,
      'private' => 0,
      'collapsible' => 1,
      'conditional_component' => '',
      'conditional_operator' => '=',
      'conditional_values' => '',
    'mandatory' => 0,
    'page_num' => 1,
    ),
  );
  $i++;

  $node->webform['components'][$i] = array(
    'nid' => $node->nid,
    'cid' => $i,
    'pid' => 0,
    'form_key' => "first_name$j",
    'name' => 'First Name',
    'type' => 'textfield',
    'value' => '',

    'parent' => "participant$j",
    'extra' => array(
      'display' => array(
        'addmore' => $i,
      ),
      'title_display' => 'inline',
      'private' => 0,
      'disabled' => 0,
      'unique' => 0,
      'maxlength' => 60,
      'width' => '',
      'field_prefix' => '',
      'field_suffix' => '',
      'description' => '',
      'attributes' => array(),
      'conditional_component' => '',
      'conditional_operator' => '=',
      'conditional_values' => '',
    'mandatory' => 1,
    'page_num' => 1,
    ),
  );
  $i++;
...

```

# Answer
> 0 votes
It looks like setting the pid to the parent fieldset's cid achieves my goal.

---
Tags: 7, webforms
---


title: Changing width in Bartik theme

text:
# Question
Title: Changing width in Bartik theme
How do I change the width in the Bartik theme (or better yet, allow it to adjust for different browser sizes)?

I've been trying to link to my drupal site via a Facebook page, and the default width is too large.

I've also downloaded the Bartik-Facebook subtheme, which made the width small enough for facebook, but also removed scrollbars, so that large pages were cut off and could not be scrolled down to.

I'd like the width to be smaller, but still allow scrollbars if the page has too much content.

I haven't yet done any coding regarding modules/themes, so a solution that is simply downloading a module/theme would be preferred, but if developing my own theme/module is the only way, I'm prepared to have a go at that.

# Answer
> 3 votes
If you're not committed to using Bartik, you could try one of the Adaptive Theme subthemes. These themes are very popular (one of them, Corolla, was intended for inclusion as the default theme in Drupal 7 but lost out to Bartik) and they allow you to change the width of the page easily on the settings page.

They are also responsive, which means that they will automatically adjust the columns on your page to display better on different screen sizes (by default, they provide PC, tablet, and smartphone layouts). You can also adjust the colors from within the UI just like Bartik. They are very newbie-friendly (the other major collection of newbie-friendly Drupal themes are the Fusion subthemes).

The base theme is Adaptivetheme, which you must install (though you won't actually use this theme). Then you can choose from Corolla, Sky, or Pixture Reloaded.

# Answer
> 2 votes
You need to edit the CSS file of bartik theme(AFAIK):

I have faced the same problem and I did the following:

```
themes/bartik/css/layout.css

#page-wrapper {
  min-height: 100%;
  min-width: 100px;
  width: 100%;
}

#page  {
  height: 100%;
  width: 1024px;  /* Whatever you want */
  margin: 0 auto; /* Center content    */
}

```

By the way, this may alter your structure and you need edit some other parts(It's not so hard).

I have used this modifications for this site: http://inforscience.net/fds\_proyecto/

Here is my modified bartik theme: http://inforscience.net/tmp/bartik.tar.gz

I hope this helps!

---
Tags: theming
---


# Question
Title: How do I create a field that accepts only unique values?
I am using the Field Collection module because I have some complicated relation between the fields, and I have tried to integrate it with the Unique field module, without success, because Unique field module is not supported by the Field Collection module.

Is there a simpler method to check if the value is unique, and the to display validation error, if the value is not unique?

Unfortunately, Drupal 7 has not this feature by default, so there must be a method to do this.

# Answer
> 1 votes
Finally here is how I did adapting and tacking suggestions form @tostinni, @stefgosselin, @uwe999 answers and others:

```
/**
 * implementation of hook_form_alter().
 */
function CUSTOM_MODULE_form_alter(&$form, &$form_state, $form_id) {
    switch ($form_id) {
        case 'MY_FORM_ID':
            // add custom validation callback
            $form['#validate'][] = 'CUSTOM_MODULE_MY_FORM_ID_validate';
            break;
            ...
        default:
            break;
    }
}

```

then all the functionality I implemented in:

```
/**
 * implementation of hook_form_FORM_ID_alter
 */
function CUSTOM_MODULE_MY_FORM_ID_validate(&$form, &$form_state) {

    //retrieve the value for your field
    $value = $form_state['values']['field_MY_FIELD']['und'][0]['value'];

    //Execute a count query to see if there's other similar values.
    $query = new EntityFieldQuery;
    $query->entityCondition('entity_type', 'field_collection_item')
            ->fieldCondition('field_MY_FIELD', 'value', $value)
            ->count();
    $count = $query->execute();
    if ($count > 0) {
        form_set_error('field_MY_FIELD', 'Unique field value is already used.');
    }
}

```

I have tried to work with `entity_metadata_wrapper` but unfortunately I have not succeed.

Thank you for your answers.

# Answer
> 8 votes
You need to implement this in a custom module, here is a sample code to achieve this:

```
function custom_node_validate($node, $form) {
  if ($node->type == 'page') {
    //retrieve the value for your field using Entity API
    $wrapper = entity_metadata_wrapper('node', $node);
    $value = $wrapper->field_collection->field_unique->value();

    //Execute a count query to see if there's other similar values.
    $query = new EntityFieldQuery;
    $query->entityCondition('entity_type', 'field_collection_item')
      ->fieldCondition('field_unique', 'value', $value)
      ->count();
    $count = $query->execute();
    if ($count > 1) {
      form_set_error('field_unique', 'Unique field value is already used.');
    }
  }
}

```

A few disclaimers:

* I am really stocked by the complexity of Field Field Collection API and it was pretty complicated to find good information about how to retrieve values and make queries.
* I really enjoy doing SQL queries (see How to change the legnth of field settings) but I tried to only use the API instead of doing a simple query on the table `field_data_field_unique`. However it may not yet be perfect so please feel free to chime in.
* The form\_set\_error() isn't highliting the field, I was unable to find the correct name.

Here are the documentation I used:

**Edit:** Following chx advice, to pass directly `field_name` to `fieldCondition()`.

# Answer
> 4 votes
I haven't programmed a module yet but it sounds like it might be easier to write a hook on form\_alter and then query against your existing "serial number" field to make sure it's unique.

# Answer
> 1 votes
Basically Ek Kosmos has the basic idea. The easiest would be to create a small *custom* module, this has the advantage of isolating the feature you want to build, and remember the #1 rule, you really never want to hack anything in core, unless you really cannot avoid it.

Once you have your .info file setup in a folder and .module file ready to go as indicated in the many how-to's on the subject, you leverage the power of hook\_form\_alter by writing a function named *your-module-name* \_form\_alter in your module file and you know that function will be called.

You would probably need a switch statement dependent in the form)alter to perform specific actions depending on the *form id*,

You would probably need to try adding an attribute (#validate) that adds a function call on the form array, being a function name of your own custom validation function.

Something like:

```
   // #validate adds callback to custom validator.
   $validators = $form['#validate'][]; // Save existing validation calls.
   //  Not clear in docs, but this is important!

  // In your case, you may want to add a method callback with this attribute.
  $form['#validate'][] = $validators . ' _custom_validate';

```

Of course, in your validation function you could log errors, redirect, assign error messages or notifications.

Do read the form api and download the form examples.

If you need help and examples galore, download contrib modules and see how others tackeled the beast, or post questions here as you go along.

Happy conding, good-luck.

# Answer
> 1 votes
Try with field validation module, use unique validator. Add a validation rule, choose unique scope, global, entity,bundle.

---
Tags: 7, entities
---


title: Can't sort by date in view

text:
# Question
Title: Can't sort by date in view
I have the simple view to display a list of nodes of a particular type. But I can't get it to sort by post date! I tried over and over, ascending and descending and it just won't sort!

I don't know what to do...

In the preview this is the sql statement:

```
SELECT node.nid AS nid, node.title AS node_title, node.created AS node_created
  FROM node node  WHERE (node.type in ('homepage_feat_video')) AND (node.status <> 0)

```

There is no sort directive. But I added a sort for sure!

EDIT: discovered that when I change the style to something other than table - it works. but why doesn't it work in a table?

# Answer
> 1 votes
OP asks for D6. For D6 make sure you have the latest version of the date and the views module. Older versions have a bug that tends to "forget" the sort part of the SQL statement.

---
Tags: views, 6
---


# Question
Title: Trying to create a view of a node that contains the titles of nodes that reference it
I'm looking for output that looks somewhat like this:

**Node title!**

Node body, this is the body of the "main" node, other nodes reference it!

create comments link, share links, some flag or something...

* Child node 1
* Child node 2
* Child node 3

The problem I'm having is that I can't figure out a way to do this in views that works with how this is going to be displayed.The main wildcard here is that I'm outputting a list of nodes, not a single one. So using something like an attachment wouldn't work, since that gets appended to the end of the entire view's output, rather than to the end of a row's output.

# Answer
> 1 votes
Have you tried the Entity Views Attachment module? Sounds like this is a perfect example for this module...

# Answer
> 0 votes
You have to add reverse node relationship with reference field then add node:title in display field which uses this relationship.

---
Tags: 7, views
---


# Question
Title: Use PHP in “Rewrite results” for a field
According How do I use PHP in "Rewrite results" for a field in a view? with the Views Custom Field module you can use PHP code in the rewriting section. I installed the module, but it consider my custom PHP code HTML (I use `<?php ?>`).

Where is the problem, and what is my mistake?

# Answer
You should tell which version of Drupal you're using.

Also, consider that embeding PHP via the UI is considered bad practice, for very good reasons.

You'd better use a field template for your field. This comment explains the basics for doing this.
> 1 votes

---
Tags: views
---


title: Image style copy or clone

text:
# Question
Title: Image style copy or clone
Is there a UI way to clone/copy image style?

/admin/config/media/image-styles

lists all styles. I wish to modify one of them but I don't want to override it and I don't want to start from scratch.

# Answer
> 4 votes
imagecache\_actions module implements this for D7 (brand new, in 7.x-1.x-dev only yet). It is based on a feature request for D8: #1403962. The dev version also implements a rudimentary export/import to copy between different systems (or the issue queue) without a need for features.

---
Tags: 7, media
---


title: Views and external DB Oracle

text:
# Question
Title: Views and external DB Oracle
my Drupal 6 installation is on a MySql server, while my own custom database is on Oracle. I have made a custom module that can read and write data into my external database, but i would like to use Views module to handle the data to show. I know that I can programmatically build views, but i don't know if I can build one for Oracle DB while Drupal is on Mysql.

# Answer
> 1 votes
You can create a view to a non-drupal table/database but you need to create a connection to it first using either one of the two connector modules: the Data module or the Table Wizard module.

You can also set it up using the Views API with `views_hook_data()`. (See documentation on views/help/api-tables.html.)

You'll need to add your new database connection settings in your settings file.

```
// In settings.php for your site
// Your drupal (site) database needs to be called 'default'
$db_url['default'] = 'mysqli://user:pass@host/drupal_db';
$db_url['oracle_db'] = 'mysqli://user:pass@host/other_db';

```

Then, in your view hook, define the tables the view should have access to.

```
$data[$table]['table']['base'] = array(
    'field' => 'Primary key',
    'title' => t('Field name'),
    'help' => t('Field description'),
    'database' => 'oracle_db',
    'weight' => -10,
);

```

---
Tags: views, database
---


# Question
Title: Where is the "Generate automatic URL alias" setting stored?
I have about a 100 nodes where I need to manually change the url alias in the url\_alias table. I want to make sure the "Generate automatic URL alias" setting is disabled for those nodes so the url doesn't change when a user changes the title.

# Answer
I was under the impression the "Generate automatic URL alias" setting would be saved in the database for each node. That's not the case.

Instead I just had to change the pathauto setting from "Create a new alias. Delete the old alias." to "Do nothing. Leave the old alias intact." (credits)
> 3 votes

# Answer
If you simply do not want them to change, then put this in your pattern for that specific content type:

```
[current-page:url:path]

```

**Disclaimer**: You probably want to test this once before updating all of them
> 0 votes

---
Tags: uri
---


# Question
Title: Use a form to filter table data in a module
I have made a module in Drupal 6 that builds a page that shows some data taken from an external database. I want to add a form that let the user filter the data (for example, limit the data output to a specific city instead all the cities). How can I get the value of the submitted form and use it as a filter condition on the page rendering function? The $form\_state variable doe not exist when running the page function and I have no way to load the value.

# Answer
> 2 votes
It sounds like your problem is about passing the selected value to your page rendering function, upon form submission. There are a few different ways to pass that value from within the form\_submit function, including via a URL argument, or setting a cookie, or using some javascript to post the value - or even using variable\_set() in the right circumstances. There might be easier better ways than those, and I'd like to know what they are if they exist.

Here's a way to do it via a URL argument:

1. In the form\_submit() function, pass the select data to the page rendering function via drupal\_goto(). Eg: drupal\_goto( 'this/page/' . $form\_state\['values'\]\['city'\]
2. Be sure that your page rendering function can accept the right argument. in your hook\_menu:
'page arguments' =\> array( 2 ),
(or you can just grab the argument using arg( 2 ) from within the page rendering function)

I'm not saying this is necessarily the best way to get the job done, but this should work.

# Answer
> 0 votes
You could make the external database table visible to Views by using hook\_views\_data(). Rather than add in a form, you could then leverage the power of Views and have exposed filters.

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


# Question
Title: CKFinder - Clicking 'send it to the server' when uploading an image does nothing
I am trying to get CKFinder to work correctly. The file manager and related functionality is recognized. When I click the little image in the toolbar to upload a photo the window comes up properly. I then select 'upload, browse (to select the file)' and then I click 'Send it to the server.'

At that point, nothing happens - the upload / file field disappears and greys out.

Nothing is actually uploaded, so, upload is not working.

Any thoughts as to why this might be happening?

# Answer
> 2 votes
The answer to this, as inspired by Nikit's comment, was to not use CKFinder at all.

CKFinder / CKEditor combination has to be one of the most frustrating experiences in all of Drupal, and it is the one thing I dread on each project. I have no idea why it has to be so complicated.

I kept CKFinder and used IMCE as suggested. The recipe works great; no complicated configuration; and is a much better module, in my opinion, for managing user images and file content. I would suggest trying it as well if you find CKE and CKF as frustrating as I do.

# Answer
> 0 votes
I was getting JS errors and PHP errors after following the README.txt "Installing CKFinder" instructions. The JS error was the following:

> Failed to load resource: the server responded with a status of 500 (Internal Server Error)
>
> http://example.com/sites/all/modules/contrib/ckeditor/ckfinder/core/connector/php/connector.php?command=Init&type=Images&id=Full

The PHP errors was:

> PHP Fatal error: require\_once() \[function.require\]: Failed opening required '../../../../../includes/filemanager.config.php' (include\_path='.:/opt/php/pear') in /var/www/example.com/htdocs/sites/all/modules/contrib/ckeditor/ckfinder/config.php on line 86, referer: http://example.com/sites/all/modules/contrib/ckeditor/ckfinder/ckfinder.html?Type=Images&id=Full&CKEditor=edit-body-und-0-value&CKEditorFuncNum=563&langCode=en

It was pretty obvious that I had incorrectly included the filemanager.config.php file. In my case, CKFinder is located under /sites/all/modules/contrib/ckeditor/ckfinder so I updated the require statement in /sites/all/modules/contrib/ckeditor/ckfinder/config.php (as indicated in the ckeditor module README.txt) to read:

```
require_once '../../../../includes/filemanager.config.php';

```

The filemanager.config.php is now properly included which fixed the issue.

---
Tags: 7, files, wysiwyg
---


title: Manipulate Database from Drupal

text:
# Question
Title: Manipulate Database from Drupal
I'm new to Drupal 7. Right now I'm trying to use D7 to build an interface that allows me to directly manipulate the tables in the database. I have installed a couple modules such as Data, Migrate, Feeds, and etc. I managed to create a view to display the table that I created using Data Module, but I need to add and update the rows from the interface. Furthermore, is it possible to set up relational tables so that I can update or delete related rows at the same time using Drupal?

Thanks in advance

Yea, I just started learning Drupal, even new to the whole CMS thing. I decided to take the chance to learn Drupal for my project. But thanks all for the help I really appreciate the helps. I will come back and vote up the answers when I have enough rep.

# Answer
Drupal isn't an MVC framework.

Content types and entities give you a way to insert records into a database, and edit them as well.

Making a "view" of one kind of record is possible with the Views module, and also the VBO module.

Deleting "related things" is trickier and requires the use of built-in hooks to remove related items from the database typically. Or if using Entities you could wire removing relationships into the Entity Controller.

Simply put, Drupal isn't a Ruby on Rails-like framework where you get CRUD capability for free; it currently acts more like the Linux kernel (in my opinion) where you register or "hook-into" the lifecycle of a thing and alter it to your needs.

You may find these 2 modules useful:

* Model Entities uses Entities to kind of create a CRUD like interfaces for custom objects built with D7 Entity(s).
* SBDO an ORM for custom object tables in drupal
> 4 votes

# Answer
The short answer is: yes, you can. I don't think you'll find a module that will provide a pointy clicky view of random tables and allow you to manipulate them. However, there are modules and frameworks that allow you to do just about anything you can imagine with your database. For example, OG provides a rich infrastructure for creating, modifying, deleting, and relating content.

For a more hands on approach, take a look at the Drupal 7 database abstraction layer documentation http://api.drupal.org/api/drupal/includes%21database%21database.inc/group/database/7
> 2 votes

# Answer
I found a way to get create, modify, and delete working just using feeds, views, and content type.

I create a content type and added fields for the table I wanted. And then I used feeds to import the csv file mapping to the content type I created. Use views to create a display to display the table, and then add extra field (Content: Edit Link) to provide a link to edit specific node.

Haven't figured out how to relate multiple tables yet, in this case, relating fields of different content type. But I got most of the work done.

Hope this can help someone else who happens to have the same goal.
> 2 votes

---
Tags: views
---


# Question
Title: Can't get custom content type page template to load
I'm running Drupal 7, and working with the Zen theme. I'm pretty sure I created a child-theme of Zen. My file structure looks like sites/all/themes/mytheme, with the original zen being located in sites/all/themes/zen. Not sure if any of that matters.

Anyway, I've created a custom content type and now I'd like to style the page differently (not just the node, but the entire page).

I've copied my page.tpl.php file and renamed it page-mycustomcontenttypename.tpl.php. This file is located in the same directory as my page.tpl.php file, which is sites/all/themes/mytheme/templates.

I then added the following code to template.php, which is in my theme's root folder:

```
<?php
/**
* Add / modify variables before the page renders.
*/
function phptemplate_preprocess_page(&$vars) {

// custom content type page template
  // Renders a new page template to the list of templates used if it exists
  if (isset($vars['node'])) {
    // This code looks for any page-custom_content_type.tpl.php page
    $vars['template_files'][] = 'page-'. str_replace('_', '-', $vars['node']->type);
  }
}

```

I then clear my site cache, but the changes I make to the custom template don't show up.

There's about a million places I could make a misstep here, so I'm not sure where to start? Any help is appreciated!

# Answer
> 2 votes
I'm totally an idiot. I tried this code previously but it didn't work, which is why I ended up with the code above (also didn't work).

I realized that in the code I tried the first time I failed to change the first line to my theme's name:

```
<?php
function thisshouldhavebeenmythemename_preprocess_page(&$variables) {
  if (!empty($variables['node'])) {
    $variables['theme_hook_suggestions'][] = 'page__node_' . $variables['node']->type;
  }
}
?>

```

---
Tags: theming
---


# Question
Title: how do i get the groups which i have joined
How can i display to my site users after joining into one group, need to display my Joined groups. suppose one person send invitation to his friend and he has joined in to his group after click link. then he has to see in his friend group he has joined using Views.

Like: My Joined Groups XXXXXXGroup Thanks

# Answer
> 1 votes
There is a view that comes with OG 7.x-1.x (I'm using 7.x-1.4) that displays all of the groups subscribed to. If you have views running, you could simply append /user-groups to your url and you should see it. After that, you can go into the view and modify it to meet your specific needs (e.g., make a block or whatever).

---
Tags: users, organic-groups
---


title: Pass parameters with tokens

text:
# Question
Title: Pass parameters with tokens
Is it possible to send parameters along with tokens?

I have a module that defines the mod1\_info and mod1\_tokens. If I enter %token:mod1:test on a page, it is replaced with `<a href='test.html'></a>`.

What I actually want is to enter %token:mod1:test\[variable\] and get `<a href='test.html'>variable</a>`.

Is this possible?

Behind the scenes, the *test.html* is being built with a few dynamic parameters so it actually looks similar to *test.html?param1=foo&param2=bar*. What I need is a way for someone editing the site to insert a token on any page, and be able to specify what appears as the link (an image, some text, or both).

# Answer
Using Drupal 7, modules can easily handle tokens similar to \[node:author:name\], where the part of the token after node:author is referring to a user token. Differently from the Token module for Drupal 6, the code that in Drupal 7 handles the tokens allows the creation of dynamic tokens. This is because on Drupal 7, modules implementing tokens can replace any token, not just the tokens they defined. The normal loop used in hook\_tokens() is the following one.

```
foreach ($tokens as $name => $original) {
  // Check the value of $name, and generate the replacement that is assigned to
  // $replacements[$original].
}

```

Using the following code, you could get what you are trying to achieve. Tokens have a specific format, which is different from the one you are describing, though. The code has not been tested.

```
function mymodule_token_info() {
  $type = array(
    'name' => t('Anchors'),
    'description' => t('Your description'),
  );

  return array(
    'types' => array('anchor' => $type),
  );
}

function mymodule_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  $sanitize = !empty($options['sanitize']);

  if ($type == 'anchor') {
    foreach ($tokens as $name => $original) {
      list($file, $title) = explode(':', $name);
      if (!empty($title) && !empty($_GET[$title])) {
        $title = $_GET[$title];
      }
      else {
        $title = '';
      }

      $replacements[$original] = "<a href='$file.html'>$title</a>";
    }
  }

  return $replacements;
}

```

The replacement for the tokens is so specific that I don't think you will find a module that does that. Your only possibility is a custom module you write.
> 8 votes

---
Tags: tokens
---


# Question
Title: How do I add a header to the contact form?
I want to add a text header to the core contact form (between the title and the "Name" field). How can I achieve this?

# Answer
> 3 votes
Just like Rylyn said you can use the `#prefix` attribute. You could change your form with the `hook_form_alter`:

```
 function YOURTHEME_form_alter(&$form, &$form_state, $form_id) {
    // replace the 'FORM-ID' with the actual id of the contact form
    if ($form_id == 'FORM-ID') {
       $form['name'] = array (
          '#type' => 'textfield',
          '#title' => 'your_title',
          '#prefix' => 'your_text_header'
       );
    }
 }

```

# Answer
> 1 votes
You can use "#prefix" attribute, like :

```
$form['name'] = array (
     '#type' => 'textfield',
     '#title' => 'your_title',
     '#prefix' => 'your_text_header',
);

```

And "#suffix" is opposite.

---
Tags: 7, emails
---


# Question
Title: The file upload in feeds importer is not working
I have been reading through all the documentation I can find, but I cant find a simple solution for this problem.

I can upload the first CSV file, and import it to a custom table with error handling and everything; when I try to upload the second CSV file, the importer imports the first file and the new file is not even uploaded to my server.

Does anyone know why this would happen?

So I have still been working on this issue and this is what seems to be happening. I "upload" a local file, this file is not actually uploaded to the server and is not recorded in the database in the "feeds\_source," or in the "files" tables. The only available file is the original file that had been uploaded, and this file is being re-imported into the database. This is why I am not getting any errors or warnings or watchdog reports.

Has anyone else experienced this?

# Answer
> 0 votes
I solved the issue by increasing the PHP upload limit, and the memory limit.

---
Tags: 6, feeds, importing-exporting
---


title: Tabs within a content type

text:
# Question
Title: Tabs within a content type
I have a question about tabs. I'm using a content type hotel with all the information about a hotel for example, hotel residence, location, food, spa, sports ... At this moment this is just one big list of text. I was trying to make tabs for it because this is I think the solution. I was trying it with the module quick tabs but there I have to use nodes or views to make the tabs so i don't know what to do know because it's impossible to put every element (location, food,...) from every hotel (40) in a view. Do you guys have any ideas? Thanks for your help.

# Answer
Sounds like you want to use the Field Group module.

This module allows you to group a number of fields on a content type together. You can then choose from a number of different display options for that group, including tabs.
> 4 votes

# Answer
I needed something similar for an estate agent style site and made Build mode tabs to allow you to use custom build modes (view modes in D7) as custom tabs. This worked well for me because I wanted some of the same fields shown on different tabs. It's only D6 but I'd be happy to port it if there was interest.
> 1 votes

# Answer
If I understand what you are trying to do ... views can certainly handle all the hotels etc. To do so:

1. Create taxonomy vocabularies that cover each category of information you want, such as location, food, amenities etc.
2. Create a new article content type with fields (requires Chaos Tools enabled) attached to each vocabulary. This permits you to create tags for each category stored in a field of the content type.
3. Create a view definition and configure a view page in it to filter on specific fields. Give it a path name such as `hotel/%/general` Set the menu type to default tabs (parent exists) and give the tab a name. THe % is a wildcard and is used for contextual filtering. This allows dynamic responses by views to the URL name you place in the % position.
4. Create another view page in the same view definition and configure its filters differently. Give it a path such as `hotel/%/<a different category>` and define its menu as menu tab (parent exists).

If properly configured, you would have a view that responds to `hotel/%` and displays the default filtered pages and two tabs, one for a default and the other for your other tab. IF you are new to DRupal, some of this may not make sense. I suggest you watch the video series "Taming the Beast"at nodeone.se to get a handle on what views does and then come back to Drupal.stackexchange, I am sure there will be more questions :)
> 0 votes

---
Tags: routes
---


# Question
Title: Address field validation-- how to allow only English/single-byte characters?
Using the Address Field module, I have created a country/state/city formatter to allow users to input their location.

On my site, about half of the users are Japanese.

Address Field provides a select list of countries by default, and I have added select lists for states/provinces.

However, users input cities in a standard text field. I am using Location Taxonomize to tag users with their cities, so I want all cities to be in the same language (in this case, English). I already have some help text on the form that asks users to input their data in English, but I'd like to add form validation to make sure.

Many Japanese sites do this by checking whether the user input is single-byte or double-byte; since Japanese characters are single-byte and standard English characters are single-byte, this is sufficient for my purposes.

Is there a function for checking this in the form API?

# Answer
> 4 votes
You could compare the length of the string by using strlen which doesn't account for double-byte characters and then using drupal\_strlen which does account for double-byte characters. If those functions think the length is different then there are some double-byte characters in there.

That comparison would need to go in a custom form\_validate function.

# Answer
> 3 votes
I don't think there's anything like that in Drupal core, but assuming your PHP library has the Multibyte String (mbstring) library built in, you could check that mb\_detect\_encoding() returns "ASCII".

```
<?php
print mb_detect_encoding("Tokyo");
// Prints "ASCII"
print mb_detect_encoding("東京");
// Prints "UTF-8" (at least on my machine)

```

Another option would be to use something like preg\_match(). The following example will set `$has_invalid_chars` to `TRUE` if `$city_name` contains any characters other than the English alphabet characters, the digits zero through nine, or the space character.

```
<?php
$has_invalid_chars = preg_match('/[^abcdefghijklmnopqrstuvwxyz0-9 ]/i', $city_name);

```

# Answer
> 0 votes
For reference, based on greggles' answer (accepted on this page) and Clive's answer here, here's the code that did it:

```
function MYCUSTOMMODULE_location_doublebyte_validation_handler($form, $form_state) {
  // Get the length
 $length1 = strlen($form_state['values']['field_MYADDRESSFIELD']['und']['0']['locality']);
  $length2 = drupal_strlen($form_state['values']['field_gen_MYADDRESSFIELD']['und']['0']['locality']);

  if ($length1 !== $length2) {
    form_set_error('addressfield', t('City names can only contain English characters; please write Asian city names using the English alphabet (no Japanese or Chinese characters).'));
  }
}

```

---
Tags: forms
---


# Question
Title: How can I show country icons in the select list provided by the countries module on the edit page?
I am using the 2.x series of the Countries and Country Icons modules. They are both installed properly on my site.

I have a country field called "Nationality" on the user profile page. I would like to show the flags in the drop-down list (the select widget) when users are editing their profiles.

There is an example of how to show countryicons with user info in the Country Icons documentation but this is for displayed comments, not an edit form.

Basically, what I want is to give the look that the Language Switcher Dropdown module does (screenshot on module page), but for a country field.

# Answer
> 0 votes
Following MotoTribe's suggestion, I filed a feature request which is already in progress. Exciting!

---
Tags: forms
---


# Question
Title: How to redirect according to URL parameter after form submission
Currently I'm using Drupal as my authentication system, and I would like to redirect user to our main site after login, according to an URL-passed parameter, for example user/login?redir=http://google.com. And yes I've found out there is a destination parameter however it doesn't work it the passed argument begins with http or somehow a non-Drupal path. Any ideas? hook\_drupal\_goto\_alter is a hook I found might be helpful, but not sure how to implement it.

# Answer
> 2 votes
The issue with `?destination=` is that it provides no mechanism for setting `external => TRUE` for the options in `drupal_goto()`, which Drupal needs to redirect to an off-site location.

I think the easiest way to get what you're looking for is to implement `hook_form_alter()` for the user login form, save the URL parameter if it's available, and then manually redirect in the submit handler.

Something like this:

```
function MYMODULE_form_user_login_alter(&$form, &$form_state, $form_id) {
  if (isset($_GET['redir'])) {
    $form['redir'] = array(
      '#type' => 'value',
      '#value' => $_GET['redir']
    );

    $form['#submit'][] = 'MYMODULE_user_login_redirect';
  }
}

function MYMODULE_user_login_redirect(&$form, &$form_state) {
  $form_state['redirect'] = array($form_state['values']['redir'], array('external' => TRUE));
}

```

---
Tags: forms, redirection, users
---


# Question
Title: Can drupal be setup for users to interact with and submit suggested changes to an article?
We will have static content. But we want the content dynamic in the sense that users can submit suggested revisions and the "community" can either vote or comment on that suggested change.

# Answer
> 2 votes
Yes - this is a common use case and is mostly done through adding and configuring the workflow module and some combination of a moderation module (ex. Moderator or Modr8) to control who has final say over publishing the node.

To add a voting component to this, you would add voting api and then a voting widget (ex. fivestar or vote\_up\_down) based on what kind of user experience you are looking for. Then when a revision gets a certain number of votes, your moderators could publish the content. If you wanted this to occur automatically, you should take a look at the Rules and Voting Rules modules.

---
Tags: nodes
---


# Question
Title: Boost. What does "Minimum Cache Lifetime" mean?
In Boost module setting, there are

```
Maximum Cache Lifetime
and
Minimum Cache Lifetime

```

settings.

"Maximum Cache Lifetime" is like re-generate the page after that amount of time.

How about "Minimum Cache Lifetime", what does it do?

Updated:

Just a copy / paste from boost handbook for a reference.

Max: Default is 1 hour and can be increased for sites that do not change very much. The maximum cache lifetime is the maximum amount of time that will elapse before the cache is emptied. Cache lifetime gets checked on cron runs. Flushing the content before it is expired can happen, for example when a node is edited.

Min: \[\< none\>\] (select box) none is fine for small sites. On high-traffic sites, it may be necessary to enforce a minimum cache lifetime. The minimum cache lifetime is the minimum amount of time that will elapse before the cache is emptied and recreated, and is applied to both page and block caches. A larger minimum cache lifetime offers better performance, but users will not see new content for a longer period of time.

# Answer
Check out this handbook page describing all settings (for 6.x but still relevant to 7.x):

"On high-traffic sites, it may be necessary to enforce a minimum cache lifetime. The minimum cache lifetime is the minimum amount of time that will elapse before the cache is emptied and recreated, and is applied to both page and block caches. A larger minimum cache lifetime offers better performance, but users will not see new content for a longer period of time."
> 2 votes

---
Tags: caching
---


# Question
Title: How to manipulate a Views grid output order?
For the content region of my homepage (under Drupal 7) I have 3 columns in which I need to display 3 different content types:

1. Regular article teasers (only image + summary as a link to full article)
2. Daily quote/citation/message (article with a short citation)
3. Advertising node (Advertising content type article)

Visually I have to respect the orderng of this layot (aren't designers wonderful):

# ===Column 1======Column 2=======Column 3=

=======Article=======Article=========Quote======= =======Article=======Article=========Article======= =======Advert=======Article=========Article======= =======Article=======Article=========Article======= =======Advert=======Article=========Article=======

I made a views block, which outputs a grid of a 3 columns and 5 rows filtering only articles "Promoted to the Frontpage". So far everything ok. Now following design decisions I'm trying to find a way to order the output of this view and particularily respect the positioning of the 2 Adverts elements, which will always be displayed in the 3rd and 5th row of the 1st Column. Same thing for the third column where the Quote element should always occupy the first postion on the 3rd column.

I'm a Views rookie so is there any Filter/Condition/etc that I'm missing and it would help me to achieve the required grid layout?

Thanks

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

# SOLUTIONS

After some research I found two methods to accomplish this that I'll go briefly in details in case other users come across the same needs as me.

1. Using Node in Block module. In the Node in Block general Settings, I created 3 blocks and assigned the content types I want to list. The great thing about this module is that it gives the option to give friendly names to the blocks themselves but also to the Fieldset labels. Very user friendly for content editors who just want to click and select on labels that have a meaning and especially for languages other than English. In the render mode options there are a couple of options. For now, I chose the teaser but I have to check on how to further style or hack to accomplish the required look. I gave to content editor role, the permissions to manage the Node in Blocks queue and now they've got a nice list of the nodes assigned to the block(s) during the node creation. What I missed the first time I installed this module was that it exposes a Row Weight option. Now editors can nicely drag and drop the nodes in any order they see fit. For further positioning and styling I installed the BlockClass module and added a class to each block to individually style/position them.
2. Another way to deal with this is to use Nodequeue module, create a queue list and add contents to it during node creation/modifications. Order the queue items as desired, then expose the contents of the Nodequeue list by creating a Views block with a grid output. At the moment the advantage of going through this compared to Node in Blocks, is that with Views every field can be assigned a class or the html output can be overridden, which would allow me to match 100% the required look. Since I'm not completely familiar with views and the workflow implications this will have for the editors, I'll just keep this in case the first scenario doesn't give me full styling liberty.

As always there are several ways to achieve things with Drupal, and that's what makes it exciting.

Tunox

# Answer
There are three module (two that come with ctools) that you probably should be looking at. Page Manager, Views content panes, and Panels

Also, one of the best screen cast tutorials addressing views can be found here: http://dev.nodeone.se/en/list-group-content-with-page-manager

The focus is OG, but the way views is being used seems to directly apply to what you described.
> 1 votes

---
Tags: 7, views
---


# Question
Title: Apply the timezone offset to my date field
I use the Date Module. My contenttype `event` dates are stored like

```
field_date['de'][0]['value'] = 2011-12-09T10:40:00 (String, 19 characters )
field_date['de'][0]['value2'] 2011-12-09T13:10:00 (String, 19 characters )
field_date['de'][0]['timezone'] Europe/Berlin (String, 13 characters )
field_date['de'][0]['timezone_db'] UTC (String, 3 characters )
field_date['de'][0]['date_type'] (String, 4 characters ) date | (Callback) date();

```

How to apply my timezones to the values? When I edit the date on my `field_date` and also when my dates are displayed, everything is fine. But I have to work with the raw DB values and need to apply the timezone. Doing it *by hand* with php +1h should work, but then it's summertime again....

# Answer
This took me a hot minute to figure out... Use the format\_date function, but be sure to specify how the date is stored in the db - usually UTC, and then offset by your date field's stored timezone - usually your drual admin specified default timezone.

```
foreach ($node->field_date['und'] as $date) {
  $unixdate = strtotime($date['value'].' '.$date['timezone_db']);
  print format_date($unixdate,'medium','',$date['timezone']);
}

```
> 11 votes

# Answer
I had the same problem but in Drupal 6. I found http://drupal.org/node/295105#comment-1969952 which has a nice function to do this, and it looks like there is a Drupal 7 version as well http://drupal.org/node/295105#comment-4884180 although I haven't tested it personally.
> 1 votes

---
Tags: 7, datetime
---


# Question
Title: How can I change active theme for specific paths or inside module?
I'm working on an online game engine website where users can create games online and other can play it.

All pages are displayed in normal theme except game play page which should be in full screen mode inside a minified version of main theme.

I know themekey is useful and I can change theme with it. but I don't want use a complex module for this purpose. is there any API function for changing theme inside module on specific paths?

# Answer
There are several modules you could use besides themekey:

Some of those are more focused for your task and don't have the overhead Themekey has (although it is a good module, just a bit heavy perhaps).
> 2 votes

---
Tags: 7, theme-negotiation
---


title: Add HTML to Ubercart's checkout table

text:
# Question
Title: Add HTML to Ubercart's checkout table
I have a product with an attribute called ID. This ID is a reference to an image the user has uploaded, its filename is id.jpg.

In the cart table where it lists attributes it has "ID: 4" for example but can I throw an img tag in there with src '...4.jpg'?

I'm a fairly competent developer however I haven't done any module development. Thanks!

# Answer
I just wrote a quick test of this hook and got what I think you're looking for...

Here is your chance to write your first module. If you're up on PHP, creating a module and enabling it is a 10 minute task.

Once you have a module that your drupal installation recognizes as enabled, you're well on the way. I tested hook\_cart\_item and found the entire content of the cart...

Note that there are several invocations of this hook, you'll want to inject your changes at the appropriate stage. In the example code below, I simply made a folder in sites/all/module/modcart Then, created a module called modcard.module, (as wall as a modcard.info file).

```
/**
  * Implementation of hook_cart_item()
 */
 function modcard_cart_item($op, &$item) {
  global $user;
  $test = $op;
 }

```

Reference: http://www.ubercart.org/docs/api/hook\_cart\_item

Hope this helps.
> 0 votes

---
Tags: ubercart
---


# Question
Title: How do I connect vocabularies and filter them to be depend on each others?
The vocabularies I use are:

* TV Channels
* TV Shows

The "TV Channels" vocabulary includes 6 terms, where each term represents a TV Channels (e.g. channel\<1\>, channel\<2\>, channel\<6\>).

The TV Shows vocabulary includes 30 terms, where each term represents a TV Show, but not all of them belong to a one TV Channel, but some of them belongs to channel\<1\>, and others for channel\<2\>.

I've already created a content type, and added various fields for these vocabularies using term references.

How do I make a filter? When I choose the TV channel from the filed, and then move to the next filed for the TV Show I should only find the ones belonging to this TV channel, and not the whole TV shows from all the channels.

---

This is a very clever idea, but will it allow me to list all TV Show episodes when I click on any given TV Show link?

Also about the main presenter, how can I add it to the content type the same way?

My point is to find a way to list contents in the website as a whole by:

1. TV channel
2. TV show
3. Main presenter and guest
4. Topic
5. Date of broadcasting

So I've created various taxonomies like the following:

* I created a vocabulary for each one of the above first four items.
* I added terms for each one of them:

1. TV Channel vocabulary
    2. TV Show vocabulary
    3. Main Presenter & Guest
    4. Topic
* I have installed these modules:

+ Chaos Tool Suite
    + Form Elements - Hierarchical Select
    + Panels
    + Taxonomy Menu
    + Views
* I added a content type with these fields:

+ TV Channel
    + TV Show
    + Main Presenter
    + Guest
    + Topic
    + Broadcasting Date: This one I need to make it in a pop up calender way so if I click on any given date to list all episodes for various TV Shows from any given TV Channel.

The first five fields are term reference fields.

# Answer
The alternative solution is to add a single vocabulary "TV" and make it two level. In first level all the "channels" will come and "shows" will be added as a child term (second level). Now for reference use "Hierarchical Select" module.
> 1 votes

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


# Question
Title: Create a RSS feed of file attachments to a particular node
I am looking to create a RSS feed of file attachments, filtered by the node they are attached to.

for instance the feed URL would be:

```
node/253/rss-attachments.xml

```

where `253` is the node ID in question. Using views 3 + drupal 7 I am able use 'files' as a base table, and create a list of files with a contextual filter of node ID, however upon adding the RSS display it complains saying:

> Style RSS Feed requires a row style but the row plugin is invalid.

I have the feeling that a custom row style plugin is required here. Does anyone have any ideas as to what options exist now for solving this issue?

Thanks

# Answer
> 3 votes
You can use Views RSS module for creating complex feeds with Drupal Fields. The module provides a lot of RSS settings:

1. RSS format plugin “RSS Feed - Fields” with settings
2. Support for core fields.
3. Enclosure elements

The result can look like this:

---
Tags: 7, views, feeds
---


# Question
Title: How to disable "Plain text" for a specific role?
I see that from `admin/config/content/formats/plain_text` I can not disable it for a individual role. How can I do this?

UPDATE: I can change the attributes of the format and rename it, however I see no way to change the machine name of the format. It should be a better way to achieve this.

# Answer
The "Plain text" input format cannot be disabled for any role. Even if you disable the permission to use the plain text format for a role, users with that role will be able to use the plain text format.

To allow all users to use the full HTML format, you need to:

* disable all the input format, except the plain text format (which is the only one you cannot disable), in admin/config/content/formats
* rename the plain text format in "HTML." You cannot rename it "Full HTML," or "full HTML" as Drupal will report you that a input format with that name already exists.
* change the settings for the input format as shown in the following screenshots, which show the settings before and after the changes.

>

>

(*PHP evaluator* will be visible only when the *PHP filter* module is enabled.)

You can also disable the "Convert line breaks into HTML" filter, if you want. In that case, the new line characters will not converted in `<br />` tags, and the text will not be wrapped in `<p>` tags. I would also disable the "Convert URLs into links" filter, which is the filter that changes texts like `http://example.com` in http://example.com (as it is done in SE sites). I would keep enabled the "Correct faulty and chopped off HTML" filter, which is the filter that fixes the missing closing tags; this avoids that a user can mess with the HTML layout of your site by leaving out a closing tag, such as `</b>` that would render all the page in bold, or `</table>` that would seriously mess-up the layout of the page.

To notice that the disabled input formats will not be visible anymore in the settings page, but the "filter\_format" table will still contain the data about those input formats; that is the reason you cannot rename the "Plain Text" format as "Full HTML." That database table is also the table that you need to alter, if you want to change the machine name of the input format; in that case, I would first delete the rows for the input formats you don't need.
> 5 votes

# Answer
Better Formats module will allow you to select the default input format per role, and disable the formats selection part of the node edit form http://drupal.org/project/better\_formats
> 7 votes

# Answer
> The "Plain text" input format cannot be disabled for any role. Even if you disable the permission to use the plain text format for a role, users with that role will be able to use the plain text format.

I have just had to deal with this particular issue. It is actually a little more subtle than that: all Drupal asks for is a fallback format, which is usable by any role. The good news is you can change it (see function filter\_fallback\_format()), so that you could set filter\_fallback\_format to filtered\_html in the variable table.
> 3 votes

# Answer
Drupal requires a single format to be available for all roles. This is called plain text by default, but can be modifying to function like any format you could create.
> 2 votes

# Answer
The default text input is configurable as well.
Instead of creating two input formats (i.e. Filtered HTML and Plain Text) you can just rename the default input format and uncheck the HTML to plain text conversion.
> 2 votes

# Answer
By enabling the filters for Plain text on `admin/config/content/formats/plain_text` you can make Plain text to Full HTML as default. And if still you require a Plain text field then you must create one text format and disable all the filters to use it as Plain text format.
> 2 votes

---
Tags: 7, nodes, users, input-formats
---


# Question
Title: created element with ajax ,not act autocomplete
i have a select option value , in change create a text field with auto complete feature, every thing is ok , but autocomplelete of this element not work!!!

part of my code

```
        $form['azlocation']=array(
            '#type' => 'select',
            '#title' => 'location',
            '#options' => array(1,2,3),
            '#default_value' => 1,
            '#description' => t('select your news location.'),
            '#ajax' => array(
                    'event' => 'change',
                    'callback' => 'country_select_f',
                    //'path' =>'roadtonowhere',
                    'wrapper' => 'city-term',
                    'method' => 'replace',
                    'effect' => 'fade',
            ),
            );
    $form['field_terms_city']= array(
            '#markup' => '<div id="city-term"></div>');

    function country_select_f(&$form, $form_state){
$form['city_list_item2'] =array(
        '#type' => 'textfield',
        '#title' => t('select city (optional)'),
        '#autocomplete_path' => 'user/autocomplete',
        '#weight' => -1,
        '#attributes' => array('id' =>'city-term-select'),
);

```

where is the problem?

# Answer
I've done it by this:

```
$form['azlocation']=array(
            '#type' => 'select',
            '#title' => 'location',
            '#options' => $tags,
            '#default_value' => 1,
            '#description' => t('select your news location.'),
            '#ajax' => array(
                    'event' => 'change',
                    'callback' => 'country_select_f',
                    //'path' =>'roadtonowhere',
                    'wrapper' => 'city-term',
                    'method' => 'replace',
                    'effect' => 'fade',
            ),
            );

    $form['field_terms_city']= array(
            '#markup' => '<div id="city-term"></div>');

function country_select_f(&$form, $form_state){

$form['city_list_item'] =array(
        '#type' => 'textfield',
        '#title' => t('select city (optional)'),
        //'#autocomplete_path' => 'user/autocomplete',
        '#autocomplete_path' => "events/autocomplete/".$form_state['triggering_element']['#value'],
        //'#autocomplete_path' => "events/autocomplete/".$form_state['triggering_element']['#value'],
        '#weight' => -1,
        '#attributes' => array('id' =>'city-term-select'),
);
return ('<div id="city-term">'.drupal_render($form['city_list_item']).'</div>');
}

```

My trick was to use:

```
return ('<div id="city-term">'.drupal_render($form['city_list_item']).'</div>');

```

I hope this be useful in the future for users with similar problem.
> 0 votes

# Answer
Try this.

```
$form['azlocation'] = array(
'#type' => 'select',
'#title' => 'location',
'#options' => array(1, 2, 3),
'#default_value' => 1,
'#description' => t('select your news location.'),
'#ajax' => array(
  'event' => 'change',
  'callback' => 'country_select_f',
  //'path' =>'roadtonowhere',
  'wrapper' => 'city-term',
  'method' => 'replace',
  'effect' => 'fade',
 ),
 );
 $form['field_terms_city'] = array(
 '#type' => 'textfield',
 '#title' => t('select city (optional)'),
 '#prefix' => '<div id="city-term">',
 '#suffix' => '</div>',
 );
 return $form;
}
function country_select_f($form, $form_state){
   $form['field_terms_city']['#autocomplete_path'] = 'user/autocomplete';
   return $form['field_terms_city'];
}

```
> 0 votes

---
Tags: forms, ajax
---


# Question
Title: One content type two different node--MYCONTENTTYPE.tpl.php for content style
I've got one content type, in the teaser I've limited the chars lenght for title and body through a script in the file .tpl.php

```
<?php $limited_title = (substr($title,0,60));
    print $limited_title."..."; ?></h2>

```

For the same content type I've got two views, both in "content" mode with a different filter criteria. What I wanna do is to have one view showing 60 chars of the title and the other view showing 100 chars of the title. Is it possible to create two different node.tpl.php like we do with the view giving the name of the page? like node--mycontentType--page-1.tpl.php.

if it's not, what the best way to get the result I want?

**No javascript please.**

Thanks in advance.

# Answer
> 1 votes
I think the best way is to change this by clicking the title field in the views page and using the "Trim this field to a maximum length" option under "Rewrite results". You can set it to 60 for the first view and 100 for the other.

---
Tags: 7, theming, nodes
---


# Question
Title: How can I add a class to a link output via a form?
Based on this answer, I'm attempting to add a cancel link. By default, however, the following code just displays a plain link with no ids and classes.

```
  if(arg(1) == 'add') {
    // If adding node link to node/add screen
    $link = l(t('Cancel'), 'node/add');
  }
  elseif(arg(2) == 'edit') {
    // If editing node, link to node view screen
    $link = l(t('Cancel'), 'node/'.arg(1));
  }
  $form['cancel'] = array(
    '#type' => 'markup',
    '#value' => $link,
    '#weight' => 0,
  );

```

How can I add arbitrary css classes and an id to the link that is output?

# Answer
> 2 votes
Take a look at the l() function:

```
l(t('link_text'), 'path', array('attributes' => array('class' => array('your_class'), 'id' => 'your_id')));

```

---
Tags: forms
---


# Question
Title: displaying fields of selected taxonomy term
I'm trying to create a minimalistic ordering system. No need for a full fledged solution like Commerce or UC in this case.

Orders are represented as nodes (or maybe as custom entities using ECK, have yet to decide). Products are organized into a taxonomy tree. Hierarchy\_select module gives the user a super convenient way of selecting the product.

But there is a problem. I need to display some fields of a product term selected by user. Is there a way to tackle it without writing much of custom code?

# Answer
> 2 votes
you need this functions:

load term by `taxonomy_term_load`, pass it to `taxonomy_term_view` then render it by `drupal_render`

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


title: How to render an image field

text:
# Question
Title: How to render an image field
What is the correct way to render a Drupal 7 image field and show the default image if the field is empty?

If I use `field_get_items` it will simply return `FALSE` when the field is empty.

# Answer
I think best practice would probably be to use `field_view_field()`:

```
$view = field_view_field('node', $node, 'field_image');
print render($view);

```

That will render the field as if it was attached to an entity view, and as such will provide the default image if none is available.
> 15 votes

# Answer
You can also image style (image cache presets in D6) like this:

```
render(field_view_field('user', $user, 'field_avatar', array('settings' => array('image_style' => 'avatar'))));

```
> 10 votes

---
Tags: theming, entities
---


# Question
Title: Drupal way of sending push notification to android devices
I am trying to send push notifications to Android, and Apple iOS devices. To store the device tokens, I am using `cocoa rest client`. For iOS devices that is fine, but I didn't understand how to store `RegId` and token for the Android devices. as we have only 4 attributes, namely:

* token
* uid
* type
* timestamp

Generally, for Android we have to store RegId and device token, but in the table we don't have any attribute to store Regid. I am giving post values as `type=android,token=device token`.

Will this help me to send push messages to Android devices? Without RegId, I think it is not possible.

I am using the Push Notifications module.

# Answer
> 1 votes
Try the Push Notifications module. I've never done this -- but you're basically asking how do I send X message type to a user (SMS, Email, whatever). I've sent emails and SMS messages before ...

Beyond wanting to send this notification from within drupal/php ... there isn't anything really drupal specific in your question in terms of the drupal API.

If you dont userstand the protocol or APIs you want to talk to I would suggest you research them more as well. I would start by looking at the source code for the PushNotifications module and see how it handles the logic of what you are asking about ...

---
Tags: 7, services
---


title: How to redirect a to a differnet url?

text:
# Question
Title: How to redirect a to a differnet url?
When the user makes a request to www.mysite.com/user he should be redirected to www.mysite.com/user/login. Is there any way by which i can do this. THought of using hook\_boot and drupal\_goto or headers. But not sure how to achieve this.

# Answer
For a permanent redirect like that, I'd set up a 301 Redirect in the .htaccess file.

```
  RewriteRule ^old_file_name http://www.example.com/new-file-name [R=301,L]

```

If for some reason you aren't able to modify your .htaccess file, there's the Global Redirect Module (supported in D7 and D6) as well.
> 2 votes

---
Tags: 7
---


# Question
Title: Drupal 7 Override Image Alt and Title attributes
In Drupal 6 I used the Imagefield Tokens module to set ALT and TITLE tags to default values if not specified (generally the node title).

I'm looking for applying this in Drupal 7, but I am having troubles. I found this thread, but it's a bit inconclusive.

Would it be possible to do this using a template preprocess or a field.tpl.php override?

# Answer
I think a template preprocess would be fine for this, specifically `hook_preprocess_image()`:

```
function MYTHEME_preprocess_image(&$vars) {
  // alt
  if (empty($vars['attributes']['alt'])) {
    $vars['attributes']['alt'] = DEFAULT_IMAGE_ALT;
  }

  // title
  if (empty($vars['attributes']['title'])) {
    $vars['attributes']['title'] = DEFAULT_IMAGE_TITLE;
  }
}

```

Pretty much all images (including those provided by a field) run through `theme_image()` so this is pretty much the best place for your code.
> 6 votes

---
Tags: media, tokens
---


title: Drupal Form PHP Passthru

text:
# Question
Title: Drupal Form PHP Passthru
I will preface my post with saying I'm new to Drupal and feeling the upward learning curve but I am working my way through api.drupal.org and The Definitive Guide to Drupal 7. That being said. Here is what I'm trying to achieve.

1) Have a form collect user input.
2) When that form is submitted pass that data to the PHP passthru command.
3) Return the results preferably real time of that command as it's running. (I will settle for just getting the results right now AJAX can come later)

Where I am at: I have built a custom module to display the form. I believe my submit handler is even working and the script is kicking off. I just can't get the resulted data. Tried using drupal\_get\_message but nothing seems to happen.

```
<?php

function my_module_menu() {
$items = array();
$items['ios_upgrade/form'] = array(
'title' => t('IOS Upgrade'),
'page callback' => 'ios_upgrade_form',
'access arguments' => array('access content'),
'description' => t('IOS Upgrade'),
'type' => MENU_CALLBACK,
);
return $items;
}

function ios_upgrade_form() {
return drupal_get_form('my_ios_upgrade_form');
}

function my_ios_upgrade_form($form_state) {
$form['ipaddress'] = array(
'#type' => 'textfield',
'#size' => 30,
'#title' => t('IP Address'),
'#required' => TRUE,
);
$form['username'] = array(
'#type' => 'textfield',
'#size' => 30,
'#title' => t('Username'),
'#required' => TRUE,
);
$form['password'] = array(
'#type' => 'password',
'#size' => 30,
'#title' => t('Password'),
'#required' => TRUE,
);
$form['ios'] = array(
'#type' => 'textfield',
'#size' => 30,
'#title' => t('IOS File'),
'#required' => TRUE,
);
$form['md5'] = array(
'#type' => 'textfield',
'#size' => 30,
'#title' => t('MD5 Hash'),
'#required' => TRUE,
);
$form['ftp'] = array(
'#type' => 'textfield',
'#size' => 30,
'#title' => t('FTP Server'),
'#required' => TRUE,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
'#submit' => array('sample_form_submit'),
);
return $form;
}
function sample_form_submit($form, &$form_state) {
if (isset($form_state['values']['submit'] ) ) {
$int = 0;
$ip = $form_state['values']['ipaddress'];
$usr = $form_state['values']['username'];
$pwd = $form_state['values']['password'];
$ios = $form_state['values']['ios'];
$md5 = $form_state['values']['md5'];
$ftp = $form_state['values']['ftp'];

$message = passthru("expect scripts/ios-upgrade.exp $int $ip $usr '$pwd' $ios $md5 $ftp  2>&1");

drupal_get_message($message);
}
}

```

Ideally the user would be redirected to a new page to get this output, which sounds like a multi-step form would be in order. I'm trying to build this one small step at a time though before I add more layers of complexity.

Thank you in advance.

# Answer
> 0 votes
`theme('status_messages')` will output all of your messages those are pushed using `drupal_set_message()`

EDIT:

If you are processing your form via ajax call then you can return the status messages by following code example. Use it in your ajax callback where form is being posted.

```
$messages = theme('status_messages');
drupal_json_output(array('status' => 'OK', 'data' => $messages));

```

---
Tags: forms
---


# Question
Title: Is there a better way of getting specific pieces of data from taxonomy_term_load()?
I have a taxonomy that has several fields attached to it. If I do a `taxonomy_term_load($tid)` on a specific item, it returns a huge object with multiple levels of nested arrays. I know which "parent" item (i.e. field name) I want, so I can do something like this:

```
$track_tax = taxonomy_term_load($value);
var_dump($track_tax->field_track_icon);

```

But even this returns a lot of nested levels:

```
array(1) {
  ["und"]=>
  array(1) {
    [0]=>
    array(15) {
      ["fid"]=>
      string(3) "702"
      ["alt"]=>
      string(0) ""
      ["title"]=>
      string(0) ""
      ["width"]=>
      string(2) "36"
      ["height"]=>
      string(2) "36"
      ["uid"]=>
      string(1) "1"
      ["filename"]=>
      string(24) "strategies_at_retail.jpg"
      ["uri"]=>
      string(44) "public://track_icon/strategies_at_retail.jpg"
      ["filemime"]=>
      string(10) "image/jpeg"
      ["filesize"]=>
      string(4) "1129"
      ["status"]=>
      string(1) "1"
      ["timestamp"]=>
      string(10) "1338391429"
      ["type"]=>
      string(5) "image"
      ["rdf_mapping"]=>
      array(0) {
      }
      ["image_dimensions"]=>
      array(2) {
        ["width"]=>
        string(2) "36"
        ["height"]=>
        string(2) "36"
      }
    }
  }
}

```

I know I can get the uri by doing something like this:

```
$uri = $track_tax->field_track_icon["und"][0]["uri");

```

Is there a better way? Some other function that will return specific pieces? Or do I need to address it level by level?

# Answer
> 1 votes
The `field_get_items()` function is very useful for this sort of thing. It doesn't produce shorter code, but it's more structured and a lot easier to get your head round than the endless arrays of data:

```
// Get the items for a particular field
$field_items = field_get_items('taxonomy_term', $track_tax, 'field_track_icon');

// Get the first item (fields can have multiple items so field_get_items always returns an array)
$first_item = array_shift($field_items);

// Get the URI
$uri = $first_item['uri'];

```

Using that method has the added benefit of automatic language negotiation, so you can avoid having to get that from context or just relying on `'und'`.

I should also say the use of this function isn't limited to taxonomy terms; you can use it to get field values for any type of entity.

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