# Question
Title: Making fields, condition and join dynamic in db_select query
What is the Drupal way of creating queries which are dynamic in nature ? What I mean is for example- In my module I am asking the user to select some content types and the fields associated with each of them. If node type "article" is present the user can select it and also select some fields lets say- **field3, field4** \- out of all the fields present **field1-10**. This custom selection is then stored in a table lets say **"custom\_table"**

```
How can i create queries of the form-
db_select('node','n')
->fields('n','field3','field4') //fields are dynamic based on user's choice stored in custom_table
->condition('n.node-type', 'article') //node type is dynamic based on user's choice stored in custom_table
->join with fields table to get field value //only for value fields

```

I really dont want to use php string handling and create a "select from node..." type string while looping over values in **custom\_table**.

Is there a less time and space complex drupal way to achieve this ?

# Answer
Don't chain your query, just put in some ifs and add to the query. Like so

```
$query = db_select('node', 'n');
if(isset($field)) {
  // Add each field separate
  $query->addField('n', 'title', 'title');
}

if(isset($article)) {
  $query->condition('n.node-type', 'article', '=');
}

if(isset($join)) {
  $query->join()....
}

$query->execute();

```

I think this will get you to where you want. Please also see this thread: http://drupal.org/node/310075
> 2 votes

---
Tags: 7, entities, database
---


# Question
Title: Any ways to create count column like mysql "COUNT(*) as counted" Column with d7's db_select()?
hello everybody i have to make tableselect form with some extra fields. To make table sortable I have to show which DB fields is used for the column in header:

```
$header = array(
    'uid' => array('data' => t('UID'), 'field' => 'u.uid'),
    'name' => array('data' => t('Name'), 'field' => 'u.name'),
    'mail'=>array('data' => t('Mail'), 'field' => 'u.mail'),
    'last_access' => array('data' => t('Last Access'), 'field' => 'u.access'),
    'login_count' => array('data' => t('Login Count'),'field'=>'a.count_logins'),
    'join_date'=>array('data' => t('Join Date'), ),
    'post_count'=>array('data' => t('Posts Count'),),
    'comment_count'=> array('data' => t('Comment Count'),)
  );

```

then I created a query for this:

```
$query = db_select('users','u');
  $query = $query->extend('PagerDefault')->extend('TableSort');
  $query->leftJoin(db_select('mycustom_report','r')->fields('r',array('count(*)    AS  count_logins','uid'))->groupBy('uid'),'a','a.uid=u.uid');
  $uids = $query
    ->fields('u',array('uid','name','mail','access'))->fields('a',array('count_logins'))->where('u.uid!=0')
    ->limit(50)
    ->orderByHeader($header)
    ->execute()
    ->fetchAll();

```

this query gives me this error

```
PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'r.countAScount_logins'

```

any ways to create count field with db\_select method in drupal? db\_query() seems does not support -\>orderByHeader() method

my full query which works fine looks like:

```
select u.uid,u.created,u.name,u.mail,u.access,counted_login,counted_post,counted_comment
  from users as u
          left join (select r.uid, count(*) as counted_login  from mycustom_report as r group by r.uid ) as d on u.uid = d.uid
          left join (select r.uid, count(*) as counted_post from node as r group by r.uid ) as p on p.uid = u.uid
          left join (select r.uid, count(*) as counted_comment from comment as r group by r.uid ) as c on c.uid = u.uid;

```

# Answer
This error simply means that column does not exist in your database which means u have to write addExpression() method for solving these problem as follows and even you have not joined the table properly use your query as below

```
$query = db_select('users','u');
$query = $query->extend('PagerDefault')->extend('TableSort');
$query->leftJoin('mycustom_report','r','r.uid=u.uid');
$query->fields('r');
$query->fields('u');
$query->addExpression('COUNT(uid)', 'uid_count');
$result = $query->execute()->fetchAll();

```

this will surely removes your error the main issue with your query is that you are combining the db\_query syntax with db\_select
> 2 votes

# Answer
Here is the D7 approach to a count function. It will also rewrite it for you so you can have a single function/query and return the count or the actual query.

```
function example($count=FALSE) {
  $query = db_select('node', 'n')
    ->fields('n', array('nid'))
    ->condition('n.title', $title, '=');

  if($count) return $query->countQuery()->execute()->fetchField();
  // Or you can just return the results.
  return $query->execute();
}

```
> 1 votes

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


# Question
Title: Drupal Commons 3 and Original Drupal Core Updates
I'm may be planning to switch over to Drupal Commons 3. When the original Drupal core gets security updates, will I be able to get those updates in the Drupal Commons or do I have to wait for Drupal Commons to release their own patch? I'm not sure if Drupal Commons modifies the original Drupal Core's code. Sorry if this question is already answered in an FAQ somewhere but I couldn't find the answer and I'm pretty new to Drupal.

# Answer
The Commons team has committed to having a new release of commons within a short period after a core or contrib security release so you should just be able to upgrade by following the Commons upgrade procedure.

It's a bit risky to update core or contrib modules inside of a distribution. If you can do it on a test site first, confirm that it's working, and report your problems with the test site to the issue queue then you'll help getting the fully packaged Commons out.
> 3 votes

# Answer
I'm having the same dilemma. Advice I've received includes checking my requirements to see if I need everything that Commons 3 has, or rather, whether there is something in C3 that I couldn't build quickly with available modules. If the answer to both questions i No, then forget C3. Nevertheless, as a non-programmer/non-developer, I think Commons is great as an out of the box solution, but notwithstanding the option to test/experiment with modules/upgrades on your own, you are committing yourself to the Commons Team and their development cycle (and note the timescale for the Drupal 7 version).

Personally, I like Commons 3, and know that Acquia will continue its development, however.
> 1 votes

---
Tags: updating, security
---


# Question
Title: drupal 7 on virtual server with debian linux - inconsistent response time
I have drupal 7 test installation on shared hosting. Caching turned off (I do not want to use caching), cron disabled. According to devel, query execution times on page with 228 queries are approximately 1200ms.(some views blocks with relationships, page displayed using context) Loading time of this page is allways more than 1200ms. It is approximately 3 and more seconds. Due to time to first byte, which I am not able to cut down.
However, I decided to try the same install on virtual host running on debian linux 500mb ram. Devel shows on the same page (228 queries) time 50ms - which is great.
But, accessing time to pages is very inconsistent. Sometimes it is amazingly fast, sometimes it takes 8 seconds of waiting and then page loads. What is interesting - even if page loads after 8 seconds, the query time is allways small according to devel.
This leads me to conclusion, that there must be some bad setting on my linux installation. Can anybody point me to the right direction? Thank you

I am new to virtual servers and I think I am missing here something obvious.

# Answer
500 MB is not much, unfortunately :) and the default debian settings for Apache and MySQL are prepared for bigger servers. You should make sure the server doesnt swap.

Probably the most important setting for that is in the part `mpm_prefork_module` in the apache configuration (`/etc/apache2/apache2.conf`). You will want to have less Startservers, MinSpareServers and MaxSpareservers.

Installing APC helps, too (and is relatively easy). Even though you have to sacrifice some RAM, it speeds up the loading and reduces the RAM needed for every pageload. With 500MB, you will want to use APC only as opcode. Make sure you dont use much more stuff than 1 installation of drupal, or set APC so that other stuff doesnt get cached (the default settings caches every php file you use, thus probably pushing the important stuff away).

Enable the css + js aggregation - apart from saving roundtrips for the client, it also saves your server from serving extra files.

Also take into account that drupal does some caching internally and the times when it takes longer may be because of that - it is useful to "prime" the caches ie by crawling all pages before you start measuring.

2bits have great articles about optimizing for drupal.
> 2 votes

# Answer
I have messed with php resouce limits settings and increased Maximum HTTP POST size from 8 to 30mb. Now my website loads really fast but only for a few minutes. Now it is everthing back to slow.
> 0 votes

---
Tags: 7, performance
---


# Question
Title: Using S3BrowserUpload to Add Form to a Content Type
I have a content type with a machine name of "video" and I created a module called "df". I want to add a ***separate form*** to the content type (above or below the edit fields) that does a direct post to Amazon S3 using the S3BrowserUpload object from the AWS SDK. The steps I am trying to accomplish are:

1. Create additional upload form on "video" content type.
2. User enters information and specifies a file in the S3 upload form.
3. User clicks Save for the Add Content Type page.
4. Ajax fires the Amazon S3 POST form to upload the video file and handles the response to store the file's key path in a hidden field.
5. The normal drupal add content type fields are then posted back to the drupal site and processed. It would also have access to the hidden field that had been populated with Ajax.

I am new to Drupal forms so any assistance in integrating S3BrowserUpload with Drupal's forms API in my custom module to accomplish the steps above would be greatly appreciated.

# Answer
> 1 votes
Recently I worked on a project to integrate JW Player into a Drupal 7 site where the videos stream from an S3 bucket. There was also some Zencoder stuff going on but that is not really relevant here I don't think.

Currently we don't upload directly to S3 though, the project ran out of time before we could implement that. What the client does is upload the files directly to S3 and then reference the file in the content type using the Remote File Source module. That is not quite what you are trying to do though.

I have had a look around and see there is an Amazon S3 CORS Upload module which looks promising and might be able to help you. It creates a new form field #type which you can use in your module.

If none of that appeals to/works for you :) then you can use `hook_form_alter` to add a new custom upload field to the content type form, it is kind of messy but it will work. Then you add an extra submit handler to the form to catch your file. You can then use the code from this example to submit your file to S3.

The nicer way would be to create a new Field using the Drupal 7 Field API.

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


title: Adding JS to a specific URL

text:
# Question
Title: Adding JS to a specific URL
I want to add some JS to a particular page. In template.php, do I simply need to check request\_path() in my preprocess\_page() function in template.php? Is that the best way to do it?

# Answer
Yes, this is the function you are looking for:

```
function mythemename_preprocess_page(&$vars, $hook) {
  if(request_path() == 'your_path') {
    drupal_add_js(path_to_theme().'/js/yourjs.js');
  }

  $vars['scripts'] = drupal_get_js();
}

```

Request path is an easier way to do this than the \< Drupal 6.x method of reading the arg() string (ex. if arg(0) === 'node' && arg(1) === 'some node id')
> 1 votes

---
Tags: 7, javascript, theming
---


title: Custom user profile displays

text:
# Question
Title: Custom user profile displays
I have added some extra fields in User entity like address, twitter account e.t.c. The requirement is that each user should be able to choose whether his profile will be completely public to other users or some fields should be hidden. The user does not get to choose which ones are hidden or not, he only chooses via a select menu (term reference) what his profile view should be: "Complete" (all fields visible), "Partial" (some predefined fields are hidden) or "Basic Info" (only name and pic).

My question is, what is the best practice to implement the three different profile views according to the user choice? My thoughts so far:

1. via the respective template using if statements to display or not some fields
2. via custom display modes, but I don't know how to delegate to another mode conditionally when view\_mode is already set to "full"

Any other suggestions are welcome. Thanks in advance.

# Answer
I would suggest that following best practices this should definitely not be accomplished by modifying template files. If you change your theme for example, this functionality should not be effected.

A custom module would be a better place to accomplish this using hook\_user\_view() http://api.drupal.org/api/drupal/modules!user!user.api.php/function/hook\_user\_view/7 and modify $account-\>content to drop the fields that should not be displayed.
> 0 votes

# Answer
I would suggest using the Panels module (http://drupal.org/project/panels). Then you can override the default user profile view with whatever content you want :).
> 0 votes

---
Tags: 7, users
---


# Question
Title: Is there a way to change edit link for Nodes?
Is there a way to change edit link for Nodes?

Currently Edit looks like this: \[node/node\_id/edit\]

I required to look like this: \[node/edit/node\_id\]

# Answer
Try out this code. add it to your module

```
function mymodule_url_outbound_alter(&$path, &$options, $original_path) {
  if (preg_match('|^node/([0-9]*)/edit(/.*)?|', $path, $matches)) {
    if ($node->nid == $matches[1]) {
      $path = 'node/edit/$node->nid' . $matches[2];
    }
  }
}

```
> 2 votes

---
Tags: nodes, routes, navigation
---


# Question
Title: PDOException Error While saving the view
I get this Error when i save a view of format JCarousel.

> PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry 'slidersidebar' for key 2: INSERT INTO {views\_view} (name, description, tag, base\_table, human\_name, core) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4, :db\_insert\_placeholder\_5); Array ( \[:db\_insert\_placeholder\_0\] =\> slidersidebar \[:db\_insert\_placeholder\_1\] =\> \[:db\_insert\_placeholder\_2\] =\> default \[:db\_insert\_placeholder\_3\] =\> node \[:db\_insert\_placeholder\_4\] =\> Slider Sidebar \[:db\_insert\_placeholder\_5\] =\> 7 ) in views\_db\_object-\>save\_row() (line 2092 of /home/kumarang/public\_html/sites/all/modules/views/includes/view.inc).

# Answer
Run update.php for your site; clear cache as well.
> 0 votes

---
Tags: views, javascript
---


# Question
Title: PDOException: SQLSTATE[HY000]: General error: 1 cannot rollback
I have managed to cause this error while working with exposed filters weighting in views. Any idea how I can correct it? I am running Sqlite for database. Is it possible to clear transactions or something?

Thanks

> Additional uncaught exception thrown while handling exception.
>
> Original
>
> PDOException: SQLSTATE\[HY000\]: General error: 1 cannot rollback - no transaction is active in node\_save() (line 1152 of /home/site/public\_html/modules/node/node.module).
>
> Additional
>
> PDOException: There is already an active transaction in dblog\_watchdog() (line 154 of /home/site/public\_html/modules/dblog/dblog.module).

# Answer
Turns out it was a problem with my /tmp directory being full.. Devel module had filled it up. It's something to be aware of and here is a script to notify you when /tmp is nearing full http://forums.ultratechhost.com/thread-187.html
> 2 votes

---
Tags: database
---


# Question
Title: array_keys() expects parameter 1 to be array, null given in drupal_schema_fields_sql()?
i have developed a custom module which will calculate the employee salary . I have created the hook\_schema() like this

This is mymodule.install file with two entities

```
function payroll_schema() {
$schema['payroll'] = array(
  'description' => 'A detail payroll structure for an employee',
  'fields' => array(
    'payroll_id' => array(
      'description' => 'payroll id',//this is my primary key.
      'type' => 'serial',
      'unsigned' => TRUE,
      'not null' => TRUE,
    ),
    'paid_days' => array(
      'description' => 'Working days of an employee',
      'type' => 'int',
      'unsigned' => TRUE,
      'not null' => TRUE,
    ),
  ...
  ...
  'primary_key' => array('payroll_id'),
);
$schema['payroll_item'] = array(
  'description' => 'Details of payroll items',
  'fields' => array(
    'item_id' => array(
      'description' => 'item_id',
      'type' => 'serial',
      'unsigned' => TRUE,
      'not null' => TRUE,
    ),
    'payroll_items_id' => array(
      'description' => 'Payroll id', //foreign key
      'type' => 'int',
      'unsigned' => TRUE,
      'not null' => TRUE,
    ),
    ...
    ...

  ),
  'primary key' => array('item_id'),
  'foreign keys' => array(
    'payroll_items_id' => array(
      'table' => 'payroll',
      'columns' => array('payroll_items_id' => 'payroll_id'),
    ),
   ),
);
}

```

Here is the mymodule.module file with hook\_entity\_info()

```
function payroll_entity_info() {
  $return['payroll'] = array(
    'label' => t('Payroll'),
    'entity class' => 'Payroll',
    'controller class' => 'PayrollController',
    'base table' => 'payroll',
    'fieldable' => TRUE,
    'entity keys' => array(
      'id' => 'payroll_id',
      'label' => 'Payroll id',
    ),
    'module' => 'payroll',
    'view modes' => array(
    'full' => array(
       'label' => t('Full content'),
       'custom settings' => FALSE,
       ),
    ),
  );
  $return['payroll_item'] = array(
    'label' => t('Payroll Item'),
    'entity class' => 'PayrollItem',
    'controller class' => 'PayrollItemController',
    'base table' => 'payroll_item',
    'fieldable' => FALSE,
    'entity keys' => array(
      'id' => 'item_id',
      'label' => 'Item id',
    ),
    'module' => 'payroll',
    'view modes' => array(
    'full' => array(
      'label' => t('Full content'),
      'custom settings' => FALSE,
      ),
    ),
  );
  return $return;
}

```

Here is the entity\_load ()

```
function payroll_load($id) {
  $payrolls = entity_load('payroll', array($id));
  return reset($payrolls);
}

```

And here is my mymodule.controller.inc

```
class PayrollController extends DrupalDefaultEntityController {
  public function __construct($payroll) {
  parent::__construct('payroll');
  }
  public function create() {
  $payrolls = new StdClass();
  return $payrolls;
  }
}
class PayrollItemController extends DrupalDefaultEntityController {
  public function __construct($payroll_items) {
  parent::__construct('payroll_item');
  }
  public function create() {
  $payroll_items = new StdClass();
  return $payroll_items;
  }
}

```

When i am trying to install a module it gives a error as:

> Warning: array\_keys() expects parameter 1 to be array, null given in drupal\_schema\_fields\_sql() (line 6969 of mylocation/includes/common.inc).

Can you tell me where i may made any mistake ??

# Answer
You've forgotten to return anything from your implementation of `hook_schema()`.

Just add `return $schema;` to the end of the function, and re-install your module.
> 7 votes

---
Tags: database
---


# Question
Title: How do I change '|' to '-' in HTML page title?
I wan to change the HTML page title: It is displayed as "pagename | sitename"; I want to change it to "sitename - pagename."

How can I do this?

# Answer
> 1 votes
```
<?php $Title = explode('|',$head_title);
echo $Title[1]." - ".$Title[0];
?>

```

Add this in the html.tp.php file, inside the `<title>` tag.

# Answer
> 3 votes
I would have used existing `$head_title_array` variable like this:

```
<title><?php print $head_title_array['name'] . ' - ' . $head_title_array['title']; ?></title>

```

Reference: html.tpl.php

You can also do this with the Metatag module.

# Answer
> 3 votes
You can use Page Title module. After installing it, you can access the configuration page of the module by navigating to:

* Drupal 6: Administer › Site configuration › Page title
* Drupal 7: Administration › Configuration › Search and metadata

---
Tags: 7
---


# Question
Title: How do I set a picture as a background image/wallpaper?
I've been trying to set a picture as a background image/wallpaper. I added the module 'Background Images' but am confused since it hasn't done anything. I tried pointing it to a new content type I created that has an image, but nothing happened. I installed Dynamic Background which did what I wanted to happen, but only for admin...

So without any access to the CSS files, is there a way to set a picture as a background wallpaper? I don't have access to the website's CSS, not even through FTP yet.

My knowledge on Drupal is very limited, so if you could have detailed explanations that would be great

# Answer
> 0 votes
Try out Live CSS module

> Edit CSS live within the page, and save the changes back to any css file if you have write access.

---
Tags: media
---


title: Create a menu item with subitems

text:
# Question
Title: Create a menu item with subitems
How can I create a menu link for `main-menu` which has related subitems?

For example in main-menu I have Home About Products and for the Products menu item I want it to put all categories as subitems: Products -\> Shoes -\> Shirts ...

Is there a hook or an example so you can achieve this?

# Answer
> 1 votes
You can create a menu programatically through menu hooks, and a great source for sample code and explanation is the menu\_example portion of the Examples Module. You can also set up new menu items and strcutre through Drupal's admin menus management (admin/structure/menus)

# Answer
> 0 votes
In Your exaple You can use Taxonomy Menu module ;) It transform taxonomy vocabularies structure into menu tree.

But if You want to do this programmatically (but why?) the best way is to look at Example Module or other implementations of hook\_menu and creating your own module.

# Answer
> -1 votes
Why you want to do it programmatically? You can use GUI for it and use Superfish or similar module to display drop down menu and subitems?

---
Tags: 7, routes, navigation
---


title: Unable to create newsletters

text:
# Question
Title: Unable to create newsletters
I am logged in as user/1 and have created a News content type with publishing options as "Use as simplenews newsletter". I believe all the permissions are correct.

When I try to add new content using this content type I see these at the top of the page:

Add this newsletter issue to a newsletter by selecting a newsletter from the select list. To send this newsletter issue, first save the node, then use the "Newsletter" tab. Set default send options at Administration \> Configuration \> Web services \> Newsletters. Set newsletter specific options at Administration \> Content \> Newsletters.

Re: Add this newsletter issue to a newsletter by selecting a newsletter from the select list. To send this newsletter issue, first save the node, then use the "Newsletter" tab. I cannot see a "select list" on my create news page.

Re: Set default send options at Administration \> Configuration \> Web services \> Newsletters. I have created a newsletter category called "Ad Hoc"

Re: Set newsletter specific options at Administration \> Content \> Newsletters. I have selected the All newsletters option from the dropdown menu. But no newsletters are available at the bottom of the page...

I am unable to get to Configuration \> Simplenews as per the readme file.

What am I missing in order to be able to create News (newsletters)?

# Answer
Workflow is the following:

1. Create category admin/config/services/simplenews
2. Add newsletter node/add/simplenews (Choose category beneath body)
3. go to node/%/simplenews and send it
> 0 votes

---
Tags: emails
---


# Question
Title: How can I change a file before save in programmatically?
I want to upload an audio file on Drupal, trim it, and save it in sites/default/files/audio/. I know how I trim the audio file; I only want to set my audio-trim-library in Drupal when the file is uploaded, and not when saved.

How can I do it?

# Answer
> 2 votes
My best guess is to use `hook_field_presave()` to alter it before it gets saved, for example:

```
function hook_file_presave($file) {
  // Change the file timestamp to an hour prior.
  $file->timestamp -= 3600;
}

```

See also: How do I change the uploaded file name after the node has been saved?

---
Tags: 7, files
---


# Question
Title: Services 3: How to retrieve the current logged in user ID
I can get a list of all users by going to //endpoint/user/ but how do I return the current user?

My primary goal is to find out if the user is authenticated.

# Answer
> 3 votes
To do this you can use the system resource "connect". Enable that resource:

* to go admin/structure/services/list/serp/resources
* expand "system"
* check "connect" Hit save

Then, you post (posting nothing) to /system/connect and it returns the current user info and session id.

---
Tags: services
---


title: Bulk operations: Taxonomy: Save

text:
# Question
Title: Bulk operations: Taxonomy: Save
I am just looking to do a bulk save on a bunch of taxonomy terms - need to trigger an update on a geofield - but there is no Save option in the bulk operations for Taxonomy Terms (as there is for Nodes). When I try to update a field on the terms with Modify Entity Value, I get an AJAX error... Ditto when I try to do a taxonomy\_term\_save($object) with Execute Arbitrary PHP Script. Any ideas?

Thanks!

Simon.

# Answer
taxonomy\_term\_save($entity); inside "Execute Arbitrary PHP Script" will do the trick. In D7, the variable is $entity, for D6 it is $object.
> 1 votes

---
Tags: 7, views, location
---


title: Views slideshow numbered pager

text:
# Question
Title: Views slideshow numbered pager
Im using Drupal 7, and I am trying to make a slide show with a numbered pager like the one shown in this page. I added PHP code in Views, thinking I could simple put PHP code, but the problem is that it is not producing the expected result.

I used this code, which is supposed to print "1 2 3 4", and that instead prints "1 1 1 1."

```
$i = 0;
$i++;
echo $i;

```

In this code I tried using one of the variables, and I think I am on the right track with this one, but it prints "10 9 8 7," while I want it prints "1 2 3 4."

```
$i = 0;
$i = $row->field_image;
echo $i;

```

I know that this is probably something simple, but I can't figure out how to save my life; any help is greatly appreciated.

# Answer
> 2 votes
The first code you wrote doesn't work because, all times it is invoked

* it initializes `$i` to 0
* it increments `$i` by 1
* it prints the value of `$1`

Because the first step, the result is always 1. To get a result that is different in any cases, the code should be similar to the following.

```
$i = variable_get('mycode_iterator_count', 0) + 1;
echo $i;
variable_set('mycode_iterator_count', $i);

```

The code is not optimized, and probably there is a better way to write the code; although, the code works, as it will print a different number every time it is invoked.
As the code is passed to `eval()`, using a static variable would not probably serve to the purpose because the static variable will probably be reset to 0 every time the code is executed through `eval()`. Probably the code would work even if it would use a global variable.

```
global $i;

if (empty($i)) {
  $i = 1;
}

echo $i++;

```

# Answer
> 5 votes
Much easier way:

1. Add "Global: View result counter" Field
2. Exclude it from Display
3. In Slideshow setting: choose that field as the Pager Type

# Answer
> 2 votes
Embedding PHP inside the view is a bad idea. PHP Views should be avoided. Instead I have come up with the following which works with default views:

1. Click "add" on the fields box.
2. Add a "Global: Math expression" field to your fields.
3. In the "Expression" field enter \[expression\] + 1
4. Click "Exclude from display".
5. Set your pager field to be the expression.

---
Tags: 7, views
---


title: taxonomy in block translated

text:
# Question
Title: taxonomy in block translated
I have a custom block code this block return a specific taxonomy in drop down list like this

```
function manufacturer_country_options() {
  $options = db_query("SELECT name,tid FROM {taxonomy_term_data} WHERE
    vid = 35 ");
  $rows[''] = t('-- Any --');
  foreach ($options as $row) {
    $rows[$row->tid] = $row->name;
  }
  return $rows;
}

```

but this function does not give me the translation of vocabulary how i can fix it to return the translation

# Answer
First I'm going to assume that you have enabled/installed `Taxonomy translation` module.

Second you need to filter `taxonomy_term_data` by the current language.

So your code should look like the following:

Translation mode: **Translate**

```
function manufacturer_country_options() {
  $query = db_select('taxonomy_term_data', 't')
    ->fields('t', array('name', 'tid'))
    ->condition('t.vid', '35');

  if(module_exists('i18n_taxonomy') && i18n_select_mode('taxonomy')) {
    $table_alias = i18n_select_check_table($query, 'taxonomy_term_data', 'tid');
    $query->condition($table_alias . '.language', i18n_select_langcodes());
    $query->addTag('i18n_select');
  }

  $options = $query->execute();

  $rows[''] = t('-- Any --');
  foreach ($options as $row) {
    $rows[$row->tid] = $row->name;
  }
  return $rows;
}

```

Translation mode: **Localize**

```
function manufacturer_country_options() {
  $query = db_select('taxonomy_term_data', 't')
    ->fields('t', array('name', 'tid'))
    ->condition('t.vid', '35');
  $options = $query->execute();

  $rows[''] = t('-- Any --');

  foreach ($options as $row) {
    $term = taxonomy_term_load($row->tid);

    if(module_exists('i18n_taxonomy')){
      $term = i18n_taxonomy_localize_terms($term);
    }

    $rows[$term->tid] = $term->name;
  }
  return $rows;
}

```
> 2 votes

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


# Question
Title: How can I allow admins to choose anything from an Entity Reference field while restricting it for everyone else?
I'm doing a job listings site. Users with privileges to list jobs have an Entity Reference field connecting them to a Company node. Job nodes have a similar field. So when an employer creates a Job, he should only be able to choose the Company in his own ER field.

This much I can do: I just created an Entity Reference View and limited it with a Referencing Entity Relationship and a Current User filter that uses that Relationship.

*However*, admins should be able to create Jobs for *any* Company. This is where I fall down. It seems like there's nothing I can do inside this View, since everything in this View has to do with the nodes being listed; there's no way to conditionally turn off a filter based on the current user.

So now I need other options. I see the obvious workaround: Make the User Company field accept multiple values, and give every single one to every admin user. That will be my last resort. Before I give up and go that route, does anyone have any ideas? Any answer will do, though if yours requires my admin users to grant themselves new permissions every time we create a company, I will probably disregard it. Thanks!

# Answer
The solution was to use `hook_views_pre_build`. That hook lets you edit the view's criteria before it actually gets run. Here's my full code:

```
function mymodule_permission() { // Create the permission for privileged users
    return array(
        'create jobs for any company' => array(
            'title' => t('Create Jobs for any Company'),
            'description' => t("Don't limit the Company field in the Job node type to only those Companies assigned to the user."),
        ),
    );
}

function mymodule_views_pre_build(&$view) {
    /* If it's the right view and the user has the above permission… */
    if($view->name === 'job_company_entity_reference' && user_access('create jobs for any company')) {
        /* …then get rid of the view criteria that limit the choices for everyone else.
        (I found these by enabling the devel module and calling dpm($view) at the top of this function.) */
        unset($view->filter['uid_current']);
        unset($view->relationship['reverse_field_company_user']);
    }
}

```
> 1 votes

---
Tags: views, entities
---


# Question
Title: Use a different template file if use is on a mobile device
I currently am using `page-front.tpl.php` to display my *Blog* content type in a View. I want to use a different template if the user is on a mobile device, and have them either redirected to the mobile view, or have the Drupal theme layer use a different template.

# Answer
To do this you need to setup some method that will detect whether the use is coming from a mobile device and than add a function in your template.php file to switch to your mobile template.

For the mobile detection, there are a number of modules available for this but for this specific use case, I would recommend Mobile Switch because it provides a specific variable you can use for testing in your theme (others like Mobile Tools might as well, this is just one I've used before). From documentation:

```
Development with Mobile Switch.

The module provides four system variables:

1. mobile_switch_ismobiledevice
2. mobile_switch_istablet
3. mobile_switch_ismobiletheme
4. theme_mobile

```

From here, you just need to add a template suggestion to your theme through the preprocess\_page function using this variable, ex:

```
function YOURTHEME_preprocess_page(&$variables) {

  global $mobile_switch_ismobiledevice;

  if ((request_path() == 'YOUR_PATH') && $mobile_switch_ismobiledevice) {
    $variables['template_file'] = 'mobile-YOURTEMPLATE';
  }

}

```

This method assumes you want to specifically switch between two template files, if you would prefer to use a separate mobile theme, than the Mobile Switch or Mobile Tools module have configuration options to help you do this.
> 2 votes

# Answer
You should be able to use a combination of Browscap and Mobile Switch.

**Browscap**

> Browscap provides an improved version of PHP's get\_browser() function.
>
> The get\_browser() function can be used to tell what a visitor's browser is capable of \[...\]

**Mobile Switch**

> The Mobile Switch module provides a simple automatic theme switch functionality for mobile devices, detected by Browscap or Mobile Detect.

If you're looking to do it through code (e.g. you would prefer to put something in your existing `tpl.php`) then Browscap provides a handy `browscap_get_browser()` function which is a kind of replacement for the PHP function `get_browser()`, so you could do something like the following (pseudo-code):

```
$browser = browscap_get_browser();

if ($browser == "MOBILE_BROWSER") {
 print $MY_MOBILE_VIEW;
}
else {
 print $MY_DESKTOP_VIEW;
}

```
> 1 votes

---
Tags: 6, theming
---


title: Transpose Article to Media (Image)

text:
# Question
Title: Transpose Article to Media (Image)
I am rebuilding a Drupal 7 site, making some changes to the data structure along the way. On the old site, I have a content type with an image, a description, and a couple other text fields. On the new site, I need this content to appear as images within a gallery (Media Gallery module). I also need to preserve the description field.

I'm not sure where to start. I used the Feeds module to migrate some other content types to their new versions, but that module cannot create this "Media" object, only nodes.

Thanks.

# Answer
> 0 votes
Media Feeds should allow you to create media objects that you can use in your gallery.

> **This module is the Drupal 7 solution for Media Feeds Integration.** It provides mappers for the Feeds module. The target can be a Media asset, image or file field on an entity (such as a node).

---
Tags: media
---


title: Country specific nodes

text:
# Question
Title: Country specific nodes
Let's say we navigate to http://example.org/ch/de/node/1 (with pathauto enabled `/ch/de/hallo-welt`)

Now I want to specify somewhere the country Switzerland (**ch**) and set the available languages to **de** (for German), **fr** (for French), **it** (for Italian), **rm** (for Rhaeto-Romanic)

So when I navigate to that link above, there should be a language switcher that shows me all translations for that country.

But now I have other countries specified. For example Canada (ca) with the languages **en** and **fr** but **en** should not be visible on node/1 And of course now I have a node at `/ca/en/hello-world` with a translation in **fr**. Now the other languages should not be visible on that node.

How can I do that with modules?

# Answer
> 0 votes
I would suggest you look at This helps you translate whatever you need to have translated

Internationalization

The default language is always enabled as a detection method and that will give you a fallback language if none of the other language detection methods are available.

(if your using Entity Translation) You will have to enable the translation of nodes or entities that would be translatable at admin/config/regional/entity\_translation.

After that you should :

> Be able to enable "Multilingual support: Enabled, with content translation" on the content type edit form under "Publishing options". For example, for a content type named "example", this would be at admin/structure/types/manage/example/edit in the "publishing options" fieldset.

// Randy Fays answer to this

Try to check out this, It might also be helpfull depending on how you want to go about it

Entity Translation

Title module will help you translate node titles

Sources I used in this answer

Randy Fays blog - Multi Lingual (thank you, for making this great post

I found this helpfull too.

Multi Lingual Setup Guide

I hope it was helpfull

Best regards

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


# Question
Title: How do I send out an email every Monday at 8:00am?
How do I send out an email every Monday at 8:00am using rules?

# Answer
> 1 votes
For finer grained control over scheduled jobs, you sould have a look at the Elysia cron module. Drupal out of the box is not capable of that degree of scheduling control.

# Answer
> 0 votes
Maybe you can use Rule Scheduler and action 'Schedule Component Evaluation' to call the same component "+1 week" after sending the first e-mail exactly on Monday 8AM

---
Tags: rules
---


title: Inline image update url

text:
# Question
Title: Inline image update url
I've got a content type with a field who contains a default value. In this default value there is an image and I would like to change the source of this image to all the existing contents.

from `<img src="sites/file/image.jpg" />` to `<img src="sites/file/images/image.jpg" />`

How can apply this to the existing contents?

Thanks in advance.

# Answer
You may do a SQL query to update the field.

Table: field\_data\_field\_NAME

Column: field\_NAME\_value

Table: field\_revision\_field\_NAME

Column: field\_NAME\_value

```
UPDATE `db_name`.`field_data_field_NAME` SET field_NAME_value = replace(field_NAME_value, '/sites/files', '/sites/files/images');

```

You may want to update the revision table of the field as well

```
UPDATE `db_name`.`field_revision_field_NAME` SET field_cc_NAME_value = replace(field_NAME_value, '/sites/files', '/sites/files/images');

```
> 1 votes

---
Tags: 7, entities, media
---


title: Adding a Custom Menu Fields

text:
# Question
Title: Adding a Custom Menu Fields
I am new to Drupal and I am trying to create a menu (top navigation links) where a small description would be visible under the main Title.

I am trying to replicate this sites menu.

Is there any module that would allow me to do this? Or is there something I missing that would allow the Description that you type to show up the way I am looking for. Any help with this would be greatly appreciated!!

# Answer
You can do this with theme\_menu\_link().

A menu item's description is by default output as a tooltip (ie, in the `title` attribute). Here's a thread that shows how to do take advantage of that using `hook_menu_link()` to achieve more or less the result you want.
> 1 votes

---
Tags: routes
---


title: Tons of file_usage queries

text:
# Question
Title: Tons of file_usage queries
I'm attempting to debug a site with intermittent slowness, and I've managed to track it down to a long series of file\_usage queries which appear to be coming from a search\_index rebuild.

```
SELECT base.fid AS fid, base.uid AS uid, base.filename AS filename, base.uri AS uri, base.filemime AS filemime, base.filesize AS filesize, base.status AS status, base.timestamp AS timestamp
FROM
file_managed base
WHERE  (base.fid IN  ('50545'))

```

And

```
SELECT f.module AS module, f.type AS type, f.id AS id, f.count AS count
FROM
file_usage f
WHERE  (fid = '22638') AND (count > '0')

```

These queries appear to be triggered on random page loads, and they continue until they are killed, or the page times out.

I thought it might have something to do with rebuilding the search index, so I've added

```
$conf['search_cron_limit'] = '0';

```

To settings.php to no avail. There are a whole lot of modules on this site, so I don't really know where to start.

# Answer
> 1 votes
As it turns out, in the system\_cron was ultimately causing the query storm. The particular bit of offending code was:

```
$result = db_query('SELECT fid FROM {file_managed} WHERE status <> :permanent AND timestamp < :timestamp', array(
    ':permanent' => FILE_STATUS_PERMANENT,
    ':timestamp' => REQUEST_TIME - DRUPAL_MAXIMUM_TEMP_FILE_AGE,
  ));
  foreach ($result as $row) {
    if ($file = file_load($row->fid)) {

```

As it turns out, there were about 200k files which matched that first query. It would then loop through them all and check to see if they had any references remaining. Since it had to do this check that may times, it was hammering the database and causing a decent amount of slowdowns. Additionally, it wouldn't find anything to prune since all of those files are still presently in use.

The solution in my case was to simply set the status field to 1 on all of the offending records, since they weren't going to change any time soon (these are product images whcih don't get updated often). The full consequences of that are unknown to me, but it seemed like a reasonable fix.

---
Tags: 7, performance
---


title: error creating a basic page

text:
# Question
Title: error creating a basic page
when I create a simple basic page like About Us and I click Save Preview I get the errror ”The trimmed version of your post shows what your post looks like when promoted to the main page or when exported for syndication. You can insert the delimiter "" (without the quotes) to fine-tune where your post gets split.” How can I get rid of this?

# Answer
saadlulu is right - this is a notice (not an error) provided by the core node module and relates to the preview functionality you have enabled. Are you trying to disable preview?

If you just want to disable the message, try the 'disable messages' module and make sure to heed the advice here and use the following wildcard:

```
The trimmed version of your post shows what your post looks like when promoted to the main page.*

```
> 0 votes

---
Tags: nodes
---


# Question
Title: Change format of webform emails via hook
I'm trying to alter the output of webform submissions in emails. At the moment, I'm just looking for the correct function. I can see there is a hook to alter the rendered output, which is being hit, but it is not changing the output of the emails. Am I replacing the Theme function in the correct place?

```
function seven_webform_submission_render_alter(&$renderable) {
  $renderable['#theme'] = 'seven_webform_submission_table';
  dpm($renderable);
  kpr($renderable);
}

function  seven_webform_submission_table($node, $submission, $email, $format) {
  return 'test';
}

```

# Answer
> 1 votes
The hook you are looking for is hook\_mail\_alter.

To modify webform submissions emails your code should look like:

```
function MYMODULE_mail_alter(&$message){
  if ($message['module'] == 'webform' && $message['key' == 'submission']){
    /*** Place your code here ***/
  }
}

```

This will alter just the webform submissions emails.

# Answer
> 1 votes
Read Documentation here that may help you.

Customising the emails sent by webform

---
Tags: hooks, webforms
---


title: Translate Guestbook

text:
# Question
Title: Translate Guestbook
I am trying to create a website in 2 languages, Greek and English. While I translated almost everything, I can't seem to get Guestbook to translate. It only shows in 1 language. Any ideas of how to use the Guestbook module in a multilingual way? The module I am using is this.

# Answer
You can download Guestbook project translations from here.
> 1 votes

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


# Question
Title: How to customize a contributed module's template
I have a contributed module with a theme file in the module's directory. I want to change it a bit by creating a template file in my custom theme directory. I thought I could just copy and paste the template file into the directory and it would be overridden. That doesn't work, so what am I missing?

Here is the implementation of hook\_theme() that's in the .module file:

```
function wunderground_api_theme() {
  return array(
    'wunderground_api_block' => array(
      'template' => 'wunderground_block',
      'variables' => array(
        'weather_data' => NULL,
      ),
    ),
  );
}

```

# Answer
To apply changes in templates, you must first rebuild Drupal's theme registry.

Navigate to `/admin/config/development/performance` and click on "Clear all caches" button.
> 1 votes

# Answer
Clear all caches and visit appearance page to reflect theme changes. Theme related cache will be cleared when you are visiting appearance page.
> 0 votes

---
Tags: 7, theming
---


title: Getting VERY strange AJAX/JS 404 errors

text:
# Question
Title: Getting VERY strange AJAX/JS 404 errors
I'm at a loss as to what could possibly be wrong, but I'm definitely seeing some crazy 404 errors, all of which seem to stem from /user/0/orders

For example, if I add a page using the CKeditor for the body, then edit it, the console error will be `POST http://www.mysite.com/user/0/orders 404 (Not Found)` and the CKeditor will not be displayed.

I'm also receiving an error on some autocomplete fields as follows:

```
An AJAX HTTP error occurred.
HTTP Result Code: 404.
Debugg information follows.
Path: http://www.mysite.com/user/autocomplete
StatusText: Not Found
...
Page not found
The requested page "/user/0/orders" could not be found.
...

```

Anyone have a suggestion I might try?

Thanks.

# Answer
> 1 votes
Ok well I seem to have "solved" the issue.

I had a node with the following PHP code to take the user to their order page when accessing user/me/orders:

```
<?php
  global $user;
  $orderpath = 'user/'.$user->uid.'/orders';
  drupal_goto($orderpath);
?>

```

When I deleted that PHP code, everything started working again.

Anyone know why the above code could cause the problems indicated in my question?

---
Tags: 7, ajax, javascript
---


title: Adding Image for banner

text:
# Question
Title: Adding Image for banner
I want to add the banner image from the Admin page. The banner is slider. The slider contains text, Read more link and Images.

These three options user have to add from the admin page. The slider appears only in the home page.

Is there any plugin or Content type is advisable.

# Answer
> 3 votes
When i Google drupal image sliders the second result leads me to this.

### Available modules

There are many modules that provide some sort of slideshow / rotator functionality.

* Views Slideshow Liquid Slider - A fully responsive, HTML5 jQuery content slider for both web and mobile devices.
* Content Glider - Another jQuery plugin for image slider, very easy to use.
* Flex slider - provides a client-side automatic adaptation of the slides size according to the window size (Responsive). Can work with the Views module. Poor documentation.
* jCarousel - This module allows developers and themers to make use of the jCarousel jQuery plugin. It includes a developer API that other modules can use, as well as Views integration in the 2.0 version so that you can turn any list of content or images into a carousel.
* Dynamic display block - Enables you to create and present blocks of content in a dynamic and attractive way. Uses the jQuery Cycle Plug-in.
* Views Nivo Slider - a Views style plugin using the Nivo style slider. Drupal 6 version requires imagecache, imagefield and jquery update.
* Views Slideshow - a Views style plugin using jquery cycle. Provides an extensible API that allows other cycles, rotators, and carousels to plug into the module, so they don't need to recreate the Views functionality.
* Views Slideshow: Dynamic display block - a Views slideshow plugin which enables you to present slideshows in an attractive way.
* Views Slideshow Xtra is an enhancement module for Views Slideshow, providing the ability to create animated slideshow overlays. This module can also help automate the creation of any Drupal 7 Views Slideshow, using the Views Slideshow Xtra Example sub-module, which creates a Slide content type, a default Slideshow View, and example Slide nodes.
* Views Slideshow: ImageFlow - offers an ImageFlow option to Views Slideshow, similar to Apple's CoverFlow.
* Slideshow Creator - adds an input format filter to allow you to add slideshow creation code to the body of a node and other text fields.
* Featured Content Slider - select nodes based on content type and create up to 3 blocks of featured content.
* Slider - create a "slider" content type with a multi-value nodereference field to create carousel-style sliders of the referenced nodes.
* Ajax Slideshow - Sequential presentation of any of the site nodes, using various effects. The slideshow is ajax-based which means the page load-time is agnostic to the amount of content included.
* Media Nivo Slider - Provides the ability to expose the content of a Media Gallery to a Nivo Slider block.
* Nivo formatter - Nivo formatter is an image field formatter that transform any image field
to awesome Nivo Slider image gallery.
* Nivo Slider - Nivo Slider is a stand-alone solution for creating a simple slideshow for your website.

---
Tags: 7, media, javascript
---


title: Uploading youtube videos to the site

text:
# Question
Title: Uploading youtube videos to the site
I would like to be able to upload youtube videos to the new site I am currently building. I would like to have a page which will list ALL the youtube videos uploaded, and then on the homepage, I would like to have a single video selected from the list of already uploaded youtube videos (changeable).

I would like it to be as simple as possible. I was thinking of a YouTube Field module. Is this simple enough?

I was thinking of possibly using Views to list all the Youtube Videos... but how would I embed the one on the homepage?

Any feedback and advice would be appreciated.

# Answer
> 0 votes
I am not sure what you are trying to do, but I recently tried a module that allows you to upload your videos via your website to Youtube. Check it out:

http://drupal.org/project/video\_upload

On the other hand, if you simply want to integrate existing Youtube videos to your website (as fields), simply use the Media modules:

First of all, you need Embedded Media Field module: http://drupal.org/project/emfield

Then install Media: Youtube to integrate your videos: \_http://drupal.org/project/media\_youtube

You can list, sort, filter all your nodes (that contain your video field) very easily with views.

I hope this help, feel free to ask some more details.

---
Tags: files
---


# Question
Title: Associating a timer on flag click on individual nodes for individual users
I have a custom field "Time to Finish" in my custom content type in Drupal7. The "Time to Finish" is basically a timer of sorts. whenever the users click a flag (which is placed on nodes of that custom content type) the timer should start. The difficulty associated with this is that:

> 1. Every node of that content type has different Time to Finish
> 2. The timer should start on flag click (the flag is same on all node, "Start Flag")
> 3. Every user would have their own timer then depending on when they click on the Start Flag

The admin while creating the content **should** have the option to fill in the field "Time to Finish" and on flag click the timer should start. Any suggestions. Would really appreciate it.

Thanks

**Edit: I found this module which solves half of my issue,i.e, to assign every individual node their own Time To Finish field. Countdown Timer Field helped with this. Now i need that on "START FLAG" click the timer should start, not before that.**

EDIT 2: i have opened a feature request issue for this at http://drupal.org/node/1948958 but can anyone help me do this. It will not only solve my use case but i think is a necessary feature to be added

EDIT 3: if there is any other solution i am eager to hear it as well.

# Answer
Create tpl file for field `field--field-name.tpl.php`. place it to your

> if Field nameis: **field\_page\_photos**
> then File name will: **field--field-page-photos.tpl.php**

clear cache.

paste below code to your tpl field file.

```
<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>: </div>
  <?php endif; ?>
  <div class="start-timer">START FLAG</div>
  <div class="starttime">
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php print render($item); ?></div>
    <?php endforeach; ?>
  </div></div>
</div>
<script type="text/javascript" charset="utf-8">
(function($){$('.starttime').hide();$('.start-timer').click(function(){$('.starttime').show();});})(jQuery);
</script>

```
> 1 votes

---
Tags: 7, nodes, users, datetime
---


# Question
Title: create email id for registered users in Drupal 7 and Nginx
I am working on a `Drupal 7` site which lets users to register using their email, when the user verifies their email address, I am planning to create new email address for them to use, which has extensions as my domain.

Suppose my Domain is `http://abcd.com` When `Mr. X YZ` register and verify his registration he will automatically get new email address from me as `x.yz@abcd.com`.

How do I accomplish this with `Drupal` ? Can this be done via `server-side` if so then I have `Nginx` server, do I need `SMPT {}` Block for that ?

I was thinking to ask users to use `google mail service` to login to their email address provided by me. Still, not sure how to accomplish that one as well.

I feel I am really missing something, as I was searching around, there were few suggestions about `Postfix` but I really don't know what it is, and how it works.

# Answer
Nginx won't help you. It can act as a mail proxy. But you need an MTA: Sendmail, Postfix to create a new mail account on your domain. Take a look here:

https://stackoverflow.com/questions/5273163/how-can-create-email-id-using-shell-exec-or-exec-in-php

You will require root permissions.
> 0 votes

---
Tags: 7, emails
---


# Question
Title: While developing a custom module, which function creates table in database?
While developing a custom module in Drupal 7, which function actually creates tables in the database?

I have implemented `hook_schema` in `mymodule.install`, `mymodule.info`, `mymodule.module` file and defined the Controller class and creates an StdClass object, but still I can't seem to find my tables in my database.

Can anybody tell me what I could be doing wrong?

# Answer
> 3 votes
First things first, you are using the correct hook.

If your module is already enabled, then the implementation of `hook_schema()` won't get called. This is also the case if the module has been enabled, and then disabled without uninstalling.

I would try disabling your module, and then ensuring it is uninstalled by either heading to ***admin/modules/uninstall/*** or (if you have Drush installed) run `drush pm-uninstall mymodule`

From the documentation:

> The tables declared by this hook will be automatically created when the module is first enabled, and removed when the module is uninstalled. This happens before hook\_install() is invoked, and after hook\_uninstall() is invoked, respectively.

I'm not sure why you'd be defining a controller class though, or even which one you're defining. Drupal 7 does this with an array, it's not very OO (Drupal 6/7 is array soup).

If this doesn't solve your issue perhaps you could paste a munged version of your implementation of `hook_schema`.

---
Tags: 7, database
---


title: Checkbox in user edit page

text:
# Question
Title: Checkbox in user edit page
I have customized the user-edit page in Drupal7 using `user-profile-edit.tpl.php`. I have also added reCAPTCHA to it using the reCAPTCHA module.

I would also like it so that there is an *"I agree to terms and conditions"* checkbox, and only when the user clicks this check box should the information be saved (i.e, it should be a required field).

How can I do that?

I found the Terms of Use module and the Legal module but they appear only on the registration form, whereas I want it in user-edit page (form). I thought of adding a field to the account settings for users but I am not getting any desired field for that.

Any suggestions?

Following the answer below, I was able to do some progress. However I want it to be a required field and if I click on that in its field setting then automatically it is shown on the user registration page which I do not want .

# Answer
> 2 votes
You can select the Boolean field and widget type as Single on/off check box...This should solve your problem...No need to use any modules

# Answer
> 0 votes
You should be able to use the Field Permissions module in combination with the checkbox you've already set up if I'm reading your requirements correctly.

1) Set up your Boolean field as you already have

2) Set the field permissions so that only registered users can see/edit it

This will mean that when a user registers, they will not be able to see or edit the field, but as soon as they have registered they get the permissions on the field and it will become viewable on the user edit page.

---
Tags: users, entities
---


title: Redirect visitor based upon geolocation

text:
# Question
Title: Redirect visitor based upon geolocation
On a Drupal website I want to redirect the visitor to a landing page based on the users location. I need this to be more specific than just the users country, but rather I need the province inside the country. When the user does not allow to be located, the user will go to the standard landing page...

Is there an (easy) way to achieve this? I am fairly new to the world of Drupal.

# Answer
I've had pretty good results previously with SmartIP, and now there is Rules integration which can react to which country the user is in.

So you should be able to set a Rule similar to the following psuedo-rule:

> **EVENT:**
>
> Page is going to be viewed
>
> **CONDITION:**
>
> * Page is: *Front page*
> * IP Address is in country: *whatever country you want*
>
> **ACTIONS:**
>
> Go to page: YOUR COUNTRY SPECIFIC LANDING PAGE

I know you said you were new to Drupal, so you can find some really useful Rules tutorials at NodeOne: Learn the Rules Framework.

**EDIT**

I've just twigged you said you want it to the province level rather than country (sorry, that was glaringly obvious - my fault), so you might be looking at some custom code.

Last time I used it, I used SmartIP to get the latitude and longitude of the user, and then the Location API for the nitty gritty.

You should be able to combine this with `hook_init()` and `drupal_goto()` to redirect the user to the relevant page.
> 1 votes

---
Tags: redirection, location
---


# Question
Title: How do I access the Node Access User Reference configuration?
I've installed the References and Node Access User Reference modules on my Drupal 7 system. I've added a User Reference field to a content type, and can happily add user references to nodes.

However, on the Node Access User Reference's project page, it shows a screenshot of a configuration form which I cannot find. I want to grant referenced users editing rights, but cannot find where to do this. Where do I find this form?

# Answer
I found a clue in the README.txt which I'd previously missed

> Create a field to reference users in a content type using the Field UI. The field's configuration page will contain the settings for Node access user reference.

I edited the User Reference field I'd created, and on the Edit tab was a collapsed heading for *Node access user reference* that I'd previously missed. Clicking the heading revealed the configuration form.
> 2 votes

---
Tags: 7, users
---


title: Displaying menu items?

text:
# Question
Title: Displaying menu items?
I am trying to create a view by pulling in a secondary menu I created. How do I do this?

I would like 8 items displayed over two columns (which means 4 items in each column) on the homepage.

# Answer
You can't use menus/menu items in Views (yet), but it sounds like you want some kind of megamenu solution.

Megamenu, OM Maximenu and Superfish are all good solutions for this.
> 0 votes

---
Tags: views
---


title: Generated CSV cannot be read by Feeds

text:
# Question
Title: Generated CSV cannot be read by Feeds
Using Views Data Export module, I am generating a CSV file of the latest 10 content. Then on another Drupal site, I am trying to import those nodes with Feeds.

The problem is when I give the url of the generated CSV, Title and Body fields cannot be imported. The nodes are generated, but those two fields are empty. Other fields like tags, date, etc are imported fine.

When I manually download the CSV, put to server via FTP, then make Feeds get the CSV from there, everything works OK.

I also tried the option "Provide as file" from the Views Data Export settings. Not working either.

What is the problem with generated CSV's address?

# Answer
> 0 votes
It drove me crazy but in the end, I found the issue.

The website has a default language other than English. When I look at the CSV url (as a logged in user) I see the correct headers in the CSV (because my language is English). But when an anonymous user looks at the url, he sees the translated headers :) So the headers dont match with the ones I set up in the Feeds settings.

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


# Question
Title: Drupal 7 View display "Page not found" without contextual filter
I have created a drupal view for my content type "Work", it has a relationship "Taxonomy terms on node" and a contextual filter "(term) Taxonomy vocabulary: Machine name". My path is /work/%.

When I go to work/sector, then it displays correctly all from content type work with the vocabulary sector. But when I go to just /work I get a "page not found".

Is there anything I need to be looking out for?

# Answer
Click on your second argument, under Contextual Filter.

You should see an option - "When the filter value is not in the URL". That's where you specify what to do when the argument, i.e. "/sector" is not present. Provide the appropriate selection, and make sure Show "Page not found" is not selected.
> 2 votes

---
Tags: 7, views
---


# Question
Title: Upon clicking save, how do I stop the node from inserting?
Upon saving a new node, I need to check against a function, if its field value is available. If not, I need to prevent the node from saving.

```
function mymodule_node_insert($node) {
    $uniqueName = $node->field_name['und'][0['value'];
    if (checkIfAvailable($uniqueName) == FALSE) { die; }
}

function checkIfAvailable($uniqueName) {
    return FALSE;
}

```

# Answer
I would probably just use Unique field, as all of the legwork is done.

> This module performs additional validation when a node is created or updated by a user to require that a node's title, author, language, and CCK fields are unique within a given context.

If you really want it in code though, I'd take a look through the source of this module and see how it adds the extra validation.

I know you said you'd prefer it in code, but I've left this here just in case it benefits anyone with the same question as you :-)
> 1 votes

# Answer
You should actually be using `hook_node_validate()` as opposed to `hook_node_insert()`

> Perform node validation before a node is created or updated.

Then to prevent it saving you can implement `form_set_error`

You'll want to check the node type first, so your code would look *something* like the following.

```
function MYMODULE_node_validate(&$node, $form, $form_state) {
  if ($node->type == 'MYNODETYPE') {
    $valuetocheck = $node->field_name[$node->language][0]['value'];
    $available = MYMODULE_checkifavailable($valuetocheck);

    if (!$available) {
      $errormessage = t('Sorry, this field has failed validation');
      form_set_error($node->field_name, $errormessage);
    }
  }
}

function MYMODULE_checkifavailable($valuetocheck) {
  //Do all your checking and return true or false
}

```

Note that I've "namespaced" your custom function here - it's up to you whether or not you do this, but it's good practice to do so :-)

Please also excuse my blatant exploitation of variables here, it's mainly so it's easier to read on this site - but it is also good practice to keep line lengths below 80 characters. I think this comes form the old character based terminal days only being able to show 80 characters/24 lines - knowledge is power ;-).
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: Image field in content type not displaying the image
Created a content type called Gallery and added the image style for that. The images are to be displayed in the `page--front.tpl.php`

I have fetched the images using this,

```
<div class="bannerSlider">

            <div class="slider-wrapper theme-default">
                <div id="slider" class="nivoSlider">
                        <?php
                        $nid=11;
                        $node = node_load($nid);
                        $imgcount = count($node->field_img['und']);
                        for ($i = 0; $i < $imgcount; $i++) {
                        $image_uri = $node->field_img['und'][$i]['uri'];
                        // url
                        $masthead_raw = image_style_url('gallery-thumb', $image_uri);
                        ?>
                            <img src="<?php print $masthead_raw; ?>">

                     <?php } ?>
                </div>
             </div>.

```

The image is not displaying.Please guide me.

# Answer
> 2 votes
You need to convert that `public://myname.jpg` to an actual URI to pass to an `img` tag

Try image\_style\_url

Replace your code with this

```
<div class="bannerSlider">
 <div class="slider-wrapper theme-default">
  <div id="slider" class="nivoSlider">
    <?php
    $nid=11;
    $node = node_load($nid);
    $imgcount = count($node->field_img['und']);
    for ($i = 0; $i < $imgcount; $i++) {
//$image_uri = $node->field_img['und'][$i]['uri'];
      $yourimagestylename = 'MY_IMG_STYLE';
      $image_uri = image_style_url($yourimagestylename,$node->field_img['und'][$i]['uri']);
// url
      $masthead_raw = image_style_url('gallery-thumb', $image_uri);
      ?>
      <img src="<?php print $masthead_raw; ?>">

      <?php } ?>
    </div>
  </div>

```

---
Tags: media, javascript
---


# Question
Title: How to log in to site after removing login form
After I logout. I couldn't login. I didn't assign the block for the user login. I tried out ,

1. ?q=user
2. $block\['content'\] = drupal\_get\_form('user\_login\_block');
3. $form = drupal\_get\_form('user\_login');

It displays:

> User account Error
>
> The website encountered an unexpected error. Please try again later.

How to get the log in. Please help me

# Answer
Best bet is to reset the default theme to Bartik or one of the other core themes to log in, then you can fix your mistake there.

**Using Drush:**

```
drush vset theme_default bartik

```

**Not using Drush:**

Look in your `variables` table and switch out whatever is currently in `theme_default` for `bartik` (ensure that the number following from `s:` matches the number of letters in the theme name, so Bartik would be 6, Garland would be 7)

```
UPDATE variable SET value='s:6:"bartik"' WHERE name = 'theme_default';
TRUNCATE cache;

```

(Modified from Unusable theme - How To reset your theme)
> 2 votes

---
Tags: users
---


# Question
Title: building a query with the database api and groupby multiple fields in drupal 7
first of all I simplified my query so it might be more useable to other users on this site.

I'm looking for a solution to use group by on multiple fields.

This query selects the values of the pop\_links module where only unique values can remain. resulting in 1 value per day, node and hostname. ( to display only one click per hostname a day )

Here's my plain sql query:

```
SELECT cid, nid, from_unixtime(timestamp) FROM pop_links_stats p
GROUP BY date(from_unixtime(timestamp)), hostname, nid ORDER BY timestamp

```

Here is a simplified version of the drupal 7 query I'm currently using:

```
$query = db_select('pop_links_stats','p');
$query->fields('p', array('cid','nid','timestamp'));
$results = $query->execute()->fetchAll();

```

I'm also already using the join method of the db api but I don't know how to add the above conditions.

Adding this below will group the fields by every day but I want to groupby on 3 fields.

```
$query->groupBy('DATE(FROM_UNIXTIME(p.timestamp))');

```

# Answer
> 5 votes
Turns out you you can 'stack' the groupby methods like so:

```
$query->groupBy('DATE(FROM_UNIXTIME(p.timestamp))')->groupBy('nid')->groupBy('hostname');

```

Which generates the following query string under the hood:

```
GROUP BY DATE(FROM_UNIXTIME(p.timestamp)), nid, hostname

```

resulting in the following drupal query for this question:

```
$query = db_select('pop_links_stats','p');
$query->fields('p', array('cid','nid','timestamp'));
$query->groupBy('DATE(FROM_UNIXTIME(p.timestamp))')->groupBy('nid')->groupBy('hostname');
$results = $query->execute()->fetchAll();

```

---
Tags: 7, database
---


title: Manage empty item in item_list theme

text:
# Question
Title: Manage empty item in item_list theme
Imagine this simple

```
 $items = array(
   'string',
   'string2',
   $extra_items,
 );

```

And theme a block content like

```
 $content = array(
   'subject'   => t('Block title'),
   'content'   => array(
     '#theme'  => 'item_list',
     '#items'  => $items,
     '#attributes' => array('class' => 'my-UL'),
   ),
 );

```

`$extra_items` is getting values from a custom hook that may be empty!In that case theme\_item\_list() brings an empty `<li></li>` for that item that is `NULL`

How can i ensure that this `<li></li>` is displayed only when this item has a value?

# Answer
> 0 votes
You simply need to run array\_filter on `$items` \- this will remove the empty entries.

Whether this should be handled by theme\_item\_list or not is debatable. It doesn't make semantic sense to theme empty list items - however in most cases the filtering would not be necessary, so from a performance point of view it doesn't make sense for theme\_item\_list to do it.

---
Tags: 7, theming
---


# Question
Title: Adding text to a field before save (Drupal 7)
I run into a situation where I need to wrap text inputted into a field **before** it is saved. I'm not sure the best way to do this, seems pretty straightforward but I'd like to find the "recommended way", to pull this off.

I have a node type called Post.
There is a field that captures ID -\> field\_id
Now I want to wrap this in HTML.

For example -\> (some html) . field\_id . (/some more html)

Key point is that this append needs to happend before the save, rewritting the field in Views UI happens after the fact.

# Answer
you could create your own module and implement this hook:

hook\_node\_presave

This hook allows you to modify the node object (and corresponding fields) before it is saved or updated within the database.
> 0 votes

---
Tags: entities, input-formats, uri, nodes
---


# Question
Title: How to override default class of custom text field in views?
How can I change the *nothing* in the "views-field-nothing" class of a custom text field in views?

I just can't find the appropriate setting...

# Answer
> 5 votes
Just found it myself. Sometimes you have to ask to look into something unexpected...

In style settings it's the "Customize field and label wrapper HTML" -settings i was looking for. With "create a css-class" you can override the default setting of the wrapper.

Thanks for looking anyway...

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


# Question
Title: what is the use of the migrate module UI in drupal 7
Guys do i still have to code object oriented coding when i use the migrate module in drupal 7? like this one example here.

http://miss-hana.com/migrate-contents-from-drupal-6-to-drupal-7-using-migrate-2/

if so, then what's the use of the UI for migrate module provided in drupal 7? i cant post a screenshot of the UI i nee 10 reputation for that. But it is in the 3rd tab in the content page.

if i still have to code, anyone can guide me to a very good tutorial or video on how to code this step by step. Because im not into object-oriented programming. :(

# Answer
> 1 votes
The UI just acts as a display for the mappings that you create, it also tells you how many nodes have been imported and how man haven't so you can manually do it.

There is lots of documentation on the drupal website here http://drupal.org/migrate and the example migrations are worth a look.

To migrate from drupal 6 to 7 I used created an xml view in drupal 6 and then created my mappings to use that in Drupal 7.

Cheers

---
Tags: 7
---


# Question
Title: Mediafront Youtube playlist feed playlist problem
I installed the MediaFront 7.x-2.0-rc2 module and MediaFront: Youtube Playlist Feeds 7.x-2.0-rc2.

I want a player with the playlist on the side. The feed imports fine and creates the nodes. In my player, I have the video, but for the playlist, I have blank videos, each with a "Sample Title" title. When I click on a blank video, it correctly plays the video in the main player, so the view knows about the other videos.

What am I missing?

# Answer
> 0 votes
Oh, I thought I answered this. Sorry! I figured out the problem was I didn't have thumbnail pics enabled. I thought I didn't need to since I didn't have accompanying thumbnail images, but it still is required to fill the thumbnails with the title and video still.

# Answer
> 2 votes
this i found useful: https://gdata.youtube.com/demo/index.html

which got me a functioning feed URL for MediaFront and so I still can create a playlist as a MediaFront preset. But its still another problem, yet to be solved, to get that MediaFront YouTube playlist preset to show as a node!!

Because when I add the same URL into an empty preset, its fails, complaining URL is bad!!

good luck and let me know how it goes for you ;-)

Richard

---
Tags: 7, media, files
---


# Question
Title: Change values of user input in hook_field_validate?
I have setup a custom field and have a validater setup for it. I would like to be able to adjust and actually change the user input from within my validator. so say this is a multi value field, each set of values shows up in $item. I have adjusted and changed the values in this function, but how I can I save them and make sure the rest of the form processes using the changed values?

```
mycustomfield_field_validate($obj_type, $object, $field, $instance,$langcode,   &$items, &$errors){

  foreach($items as $item){
  // validation check is here
  }
}

```

# Answer
Perhaps hook\_field\_attach\_submit can be used in your case?
> 0 votes

---
Tags: entities
---


# Question
Title: Rules Comparison Operator Is Missing The Direct Input Method
I have an "equipment" content type, which has a "manufacturer" field applied to it. The "manufacturer" field is a taxonomy term reference to a taxonomy which contains all of the manufacturers.

When "equipment" is flagged, I want a "task" to be created. The problem is, I need different tasks created depending on what manufacturer it is.

Task A applies to manufacturer terms 1,2, and 5.

Task B applies to manufacturer terms 3 and 4.

When I set this up in Rules, I use a "Data Comparison" to check what manufacturer the equipment belongs to. When I use only one manufacturer, the "Data Comparison" gives me a Direct Input to compare to, I set the comparison operator to "Equals", and I can type in, for example, 2. Everything works.

However, I want this rule to apply to manufacturers 2, 1, and 5, so I set the comparison operator to "Is One Of". Suddenly, the Direct Input Method disappears, and I'm sunk.

Is there a way in Rules to compare if a field equals one of several taxonomy terms (OR logic)?

# Answer
The key to this problem was that the data comparison was actually comparing against a field belonging to an entity that was referenced to an entity that was referenced to the entity in question. The structure was: Task -\> Ticket -\> Equipment: field-manufacturer.

The solution was to specifically declare the field in Rules using "Entity has field". In this case, I was using two entity references, so I had to use "Entity has field" once to bridge to the first entity, twice to bridge to the second entity, and a third time to identify the particular field on that entity that I wanted to compare data against.

After I set the "Entity has field" conditions in place, I was able to compare data using "is one of" and it gave me a field to type in multiple TIDs.
> 1 votes

---
Tags: taxonomy-terms, rules
---


# Question
Title: Allow downloading files from private filesystem when paths to files are built without Drupal
I have set up files under private filesystem (large tree of dirs and files). Drupal does not know anything about those files, because they are not added by file upload field, but links are manually defined as strings (in special field in content type), and put in place with ftp.

Also, path to those files are not completely contained within string, but constructed in **field--field\_myfiled.tpl.php** (some taxonomy magic adds parts of the path, so in actual string i have only filename).

Now, adding just **system/files/** before link constructed in **field--field\_myfiled.tpl.php** returns privilege errors, so I guess i need to tell Drupal somehow to allow downloading these files. I am not sure - could I use `hook_file_download` in this case, and how I could implement this or simmilar function or approach to give access to those files ?

**EDIT:** My latest findings are that it seems that hook\_file\_download is triggered whenever you try to access a valid link to a file in private filesystem. No need for anything except hook\_file\_download here!

# Answer
> 1 votes
Here are a few modules that should help you configure the way files are served.

* Storage API module. It provides advanced file storage and serving options; such as to upload or serve from a separate server, via ftp, etc. It's my favorite option. I currently use it to host all files on a separate server.
* CDN module. Designed for CDN related tasks, but can be used in your case to specify an alternative file location for specific file types.
* Remote Steam Wrapper module. Not sure if this will work for private files. It makes it easier to serve external files.
* Media Mover module. Provides advanced file serving possibilities, i.e. get files from a FTP server, provide file tokens for authentication, get files from CCK fields, etc. It's only available in development version.

**Update**

If you want to do it via custom code, use field\_view\_value() function to pull the URL from the field. Use file\_create\_url to create URL for streaming. You'll also need to use hook\_file\_download to allow the file to be downloaded; otherwise you will get a page not found.

**Update**

If I understood correctly, you have a field, where you enter the file name (i.e. myFile.pdf), and you rewrote its field theme (field--field\_myfield.tpl.php) to generate the full location of the file. The problem here, is that you cannot include hooks/functions within a theme. Your solution would be to construct the file location in a custom module or template.php.

Example of rewriting the field value via template.php. Replace MYTHEME with your theme name.

```
function MYTHEME_preprocess_field(&$vars) {
  if($vars['element']['#field_name'] == 'field_myField') {
    $filePath = '/secret/location/' . $vars['items']['0']['#markup'];
    $vars['items']['0']['#markup'] = file_create_url($filePath);
    return;
  }
}

```

If you want to check for permissions, use hook\_file\_download.

# Answer
> 0 votes
First i would make sure you can access these files directly via **system/files/myfile.txt**.

If it doesnt work, you'll have to check your .htaccess file and enable that directory for public viewing or just 755 permissions that folder.

if that does work, then I would create a View as either a block or page depending on the flexibility you need and add in the fields or terms associated with your tpl and create another text related field and rewrite the results of the previous field to construct your links using tokens.

---
Tags: files
---


title: Change node author with Rules

text:
# Question
Title: Change node author with Rules
I have field in content type called field\_new\_author which is User reference field.

I need to make a Rule to change Node author field to match value in field\_new\_author. I tryed this solution: Change node author on node save with rules

But I'm getting database error: `PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '4141-0-all' for key 'PRIMARY': INSERT INTO {node_access} (nid, realm, gid, grant_view, grant_update, grant_delete) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5); Array ( [:db_insert_placeholder_0] => 4141 [:db_insert_placeholder_1] => all [:db_insert_placeholder_2] => 0 [:db_insert_placeholder_3] => 1 [:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => 0 ) in node_access_write_grants() (line 3440 of /home2/test/modules/node/node.module).`

I also tryed different setups in Rules but could not find anything that would work.

# Answer
I assume you are using D7 with Entity Reference. You should be able to do this with stock Rules, without any PHP code:

1. Create a new rule
2. Event, select "After updating existing content"
3. Condition, select "Content is of type" to match whatever content type it is. This will qualify the fields so that you can use them later
4. Condition, select some other limiting condition so that you don't target every single node with updated content. You could, for example, do a data comparison to check if the content has a given taxonomy term
5. Action, select "Set data value". Your target should be node(updated content):author. Your new value should be node(updated content):field-new-author
> 1 votes

# Answer
I'm not that experienced with the Rules module so I can't help you in that regard. However you could create your own module and implement this hook:

hook\_node\_presave

This hook allows you to modify the node object before it is saved or updated within the database. You'll then be able change the Node author value to the value of your User reference field within your own module. Remember to check the content type of the node first to ensure values are only changed on your intended nodes.
> 0 votes

---
Tags: 7, users, rules
---


# Question
Title: Add a "class selection" field to content item via CCK?
I have a single content type (webform) that I want to display in two or three different styles on my site. For instance, I may want to have some of the webform's CCK fields floated to the right on one webform page, and have them floated to the left on another. There will be many unique webform content items on the site, so individual CSS per-page styling would not work well, and I am looking for a point-and-click solution.

I was hoping that there would be a way for me to add a CCK field (or something similar) to the Webform content item that would allow me (or another admin user) to simply choose "style 1", "style 2", or "style 3" from a drop-down menu, and that style would be added to that Webform's page or div classes, allowing that form to be stylized according to one of three pre-created style sets.

Is this possible with an existing module? Any other ways in which I can go about accomplishing this?

Thanks!

# Answer
> 1 votes
```
// This code will add a class to the node based on a field in that node
function THEME_preprocess_node(&$vars) {
$node = $vars['node'];
$output = '';

switch($node->type) {
  case 'advertisement':

  // Set class based on editor color selection; code duplicated for clarity.
  $field = field_get_items('node', $node, 'field_background_color');
  if($field) {
    $theme = field_view_value('node', $node, 'field_background_color', $field[0]);
    $term_name = $theme['#title'];
    $term_name = str_replace(' ', '-', $term_name);
    $css_name = strtolower($term_name);
    $vars['classes_array'][] = $css_name;
  }
  break;
  }
}

```

# Answer
> 0 votes
I found a great way to accomplish this using the Context module.

http://drupal.org/node/1257822

First, I added a Taxonomy CCK field to the Webform content type, and then...

> In Admin /Structure /Context, in a context, add a "Taxonomy" Condition of tag, "Theater," and set a "Theme HTML" Reaction.

This adds whatever class you specify to the body class for the webform page, depending on whether you select one of the qualifying taxonomy terms from the Taxonomy CCK field when editing that Webform.

---
Tags: 7, entities, webforms, theming
---


# Question
Title: How can I create a customised add/node form in D7?
How can I create a customised add/node form in D7?

I am not talking about a form for gathering information that is not content for the site, like an event registration form. I'm talking about the node/add form where you create content for your site.

What I want to replicate is just some simple html tables, arranged together, and some css to make it look good. Lots of boxes in which to insert numbers, mainly, a few drop-downs and text fields too. Imagine you navigate to node/add/scorecard and something like this appears:

Thanks.

**SOLUTION**

This is the solution I have arrived at:

(1) Create a module (.INFO and .MODULE files).

(2) Implement hook\_menu (in your new module) to create a url and page where the form is to reside.

(3) Add a function to render the HTML of the form using drupal\_get\_form.

(4) Add a form builder function and construct your form using an array called $form (see form API for details).

(5) Add a submit button at the end of your form.

(6) To make the form look the way you want it to there are several methods: (i) create a theme function to add to the elements of $form; (ii) use #prefix and #suffix properties to add additional HTML and CSS ids/classes to the rendered form; (iii) manipulate the many ids/classes, rendered by drupal\_get\_form, with CSS; (iv) use the #markup properties to add additional HTML and CSS ids/classes to the rendered form (not recommended). I used a combination of (ii) and (iii). I could not work out how to do (i) but it is probably the 'most correct' method.

(7) Add a validation function.

(8) Add a submit function using node\_save (for nodes) and drupal\_write\_record (for fields) to insert your form values into the relevant database tables: node, field\_data\_field\_my\_field etc.

# Answer
> 2 votes
you may try using Webform module.

> Webform is a module that aids in making various one-off forms such as contact forms, surveys, order forms, reservations, CRM requests, and more.
>
> To install the module, download the module and add it to your sites/all/modules directory. Enable it under /admin/build/modules.
>
> You will now have a new node type called "Webform". From there you simply give the webform a title, description, confirmation message, set up email settings and the like.
>
> Finally, you can add several components (think fields). There are several component types available: fieldset, pagebreaks, grid, textarea, textfield, select (checkboxes, pulldown lists), email addresses and more.

Here's the documentation. Let me know if you need more information.

-------------------- UPDATE ----------------------

To customize the HTML of the form you can copy the file webform-form.tpl.php and copy it into you template. Inside there is the array $form\['submit'\] that contains the compontents of the form. write dsm($form\['submit'\]) and it will print the compontents. Then you may do something like

```
<div class="my_class" id="my_id">
<?php print render($form['submit']['YOUR_FIELD']); ?>
</div>

```

Then you may want to assign this template to that node, so it will be webform-form-NID.tpl.php

# Answer
> 0 votes
You can certainly use modules like Webform, but if you are truly looking for a customized form - two options based on what you are trying to do.

1. If this is customizing an existing form (like node add form?) - use hook\_form\_alter().
2. If this is a brand new form, use hook\_menu()

# Answer
> 0 votes
Use Entityform Types. That way, you will have more control. It has custom fields, and it integrates with the Views module.

---
Tags: nodes, forms
---


# Question
Title: How do I display a list of nodes that reference a given node on the node content page?
I have a central content type that is being referenced by many child content types. The child content types all have an entity reference field pointing to the central content type.

Now, on the node page, I want to display a list of all the nodes that are referencing this particular piece of content.

It seems I can use Field View to set up a view showing the desired content, and then embed it as a field, but I'm not sure how to pass the value of the currently-being-viewed content to the view in order to make it limit the results properly.

Any advice or other ways to approach this problem?

# Answer
In your view set up a contextual filter (under 'Advanced') on the entity reference field. Then configure the filter to provide a default value if the filter is missing. Select 'Content ID from UrL'.

When you display the view, it will list the children which point to the page you are currently displaying.
> 1 votes

---
Tags: views, entities
---


# Question
Title: What is the best way to use Panels with the Omega theme?
I am new to drupal 7 so I have some questions about Omega theme.

I've installed Panels/Views and Omega Theme. Using the omega-tools I created a subtheme. How can I use the panels with the omega theme? I see there are two conflicting methodologies here. Is there any tutorial that can help me understand ?

# Answer
> 4 votes
If you want to use Panels, Omega is probably not the way to go. The lead Omega developer is a big supporter of the Context module (as noted by Letharion) and you can see an example of the slow uptake of panels support on this thread.

If you're new to Drupal and want to use Panels, I would recommend trying Adaptivetheme, especially the 3.x branch (currently rc1 but due for a stable release soon). Adaptivetheme has a long history in the Drupal community and has nearly 30,000 sites using it; it also has the best Panels support of all the major theme frameworks. The 3.x version of Adaptivetheme adds support for responsive design in Panels, easy CSS resets, etc., making it very comparable to the Omega theme but allowing for excellent Panels support. There are also a variety of subthemes available (links on the module page) that should give you a good idea of what this theme is capable of.

# Answer
> 1 votes
I was able to convert a "flexible" panel into an omega compatible region simply by adding the CSS class `grid-4` to the panel container in the panel's CSS settings. The result is a collapsible omega grid on the front end. However, the downside is that in the backend, the columns are not visible (you just see stacked regions in the backend).

You could use `grid-1` through `grid-12` in a similar manner to accomplish this. You might then need to add some CSS to cancel out the default "flexible" panel stuff:

```
.panels-flexible-region-inside,
.panels-flexible-column-inside,
.panels-flexible-row {
  padding: 0;
}
.panels-flexible-column-1-main,
.panels-flexible-region-1-center {
  float: none;
  width: auto;
}

```

You'd then need to adjust `margin-left` and `margin-right` accordingly...

It's not a perfect solution, but it worked for me so I figured I'd share this because it's helped me get responsive panels in a very simple omega-based theme.

---
Tags: views, panels, theming
---


# Question
Title: Get taxonomy terms page based on exposed filters value
I've created two taxonomy vocabs: Language and Genre. LANGUAGE consists of the following terms: English,Spanish,French,etc and GENRE consists of Rock,Pop,etc.

Am using the taxonomy term page view with exposed filters for language and genre.

When am in a page that list all songs under the term english, the filter for genre and language also appears. All good till here.

Now, If i select spanish from the filter..i want the term page to reload and show the relative results. How can i work this out???

# Answer
It will be easier if you will use just one vocabulary. Smt like this:

```
English
- Rock
- Pop
- etc.
Spanish
- Pop
- Rock
- etc.

```

Then you can use hierarchical\_select module to filter exposed lists automatically.

If you can't change vocabulary structure, you should use `hook_form_alter()` ...
> 0 votes

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


# Question
Title: file upload works with only one specified extension but not more than one
I can't figure out what is wrong with this code for file uploads. I am trying to specify multiple extensions for the file upload - it works with a single extension, but if I specify more, it fails and only accepts the last item in the list, even though the error message appears to be self-contradicting. If no extensions are specified the system default list works correctly, but I need to add some extensions.

I am enclosing the minimal code, since after trying everything, modifying this code was the only difference between success and failure:

This works (regardless of the extension)

```
$file = file_save_upload('sequencefile',
    array(
             'file_validate_extensions' => array('seq')));

```

This fails on 'jpg', but works on 'seq'; moving jpg to the end of the list works for jpg, but then fails for the others.

```
$file = file_save_upload('sequencefile',
     array(
             'file_validate_extensions' => array('jpg, jpeg, png, gif, txt, doc, docx, ab1, seq')));

```

The error message on a jpg file is as follows, even though jpg is clearly in the list:

```
"The specified file mbpdpermissionsP2.jpg could not be uploaded. Only files with the following extensions are allowed: jpg, jpeg, png, gif, txt, doc, docx, ab1, seq."

```

What am I missing? it should be very simple and yet I can't get it to work.

thanks!

# Answer
> 1 votes
Don't use a comma separation, separate extensions just with space

```
'file_validate_extensions' => array('jpg jpeg png gif txt doc docx ab1 seq')));

```

---
Tags: files
---


# Question
Title: how to select a non-drupal (souce db) database in a migrate module
can i still use a db\_select(); if my source database is a non-drupal site? how can the migrate module know what database im referring? i cant see any configuration for migrate module on how to change database selection.

```
$query = db_select('sourcedb.brands', 'b');
$query->addField('i1', 'foreign_key', 'foreign_key');
$query->addField('i1', 'locale', 'locale');
$query->addField('i1', 'content', 'brand_description');
$query->addField('b', 'name', 'brand_name');
$query->addField('b', 'owg_id', 'owg_id');
$query->join('sourcedb.i18n', 'i1', 'i1.foreign_key = b.id');
$query->condition('i1.locale', 'spa', '=');
$query->condition('i1.model', 'Brand', '=');
$query->condition('i1.field', 'description', '=');
$query->orderBy('i1.foreign_key', 'ASC');

```

is the "sourcedb" in 'sourcedb.brands' a keyword in drupal? or can i replace it directly with the table name?

# Answer
> 0 votes
It would probably be better if you looked at the Feeds module using the Feeds Database fetcher.

---
Tags: 7, migrations
---


# Question
Title: How to add Cancel button to Batch operation?
How to add Cancel button to Batch operation? Is this even possible?

# Answer
There is no good way to interrupt a batch process, afaik. There used to be a hackish trick in Drupal 6 though, see http://drupal.org/node/894222. Maybe if you can figure out how that worked, you can make Drupal 7 do the same.
> 1 votes

# Answer
Define your operation like this:

```
$batch = array(
  'title' => t('Exporting'),
  'operations' => array(
    array('my_function_1', array($account->uid, 'story')),
    array('my_function_2', array()),
  ),
  'finished' => 'my_finished_callback',
  'file' => 'path_to_file_containing_myfunctions',
);

```

http://api.drupal.org/api/drupal/includes!form.inc/group/batch/7
> -3 votes

---
Tags: 7, batch-operations
---