title: hide cck field not working

text:
# Question
Title: hide cck field not working
I want to expose the node add form for a particular content type to anonymous users but not with all the fields visible. I want limited fields to be visible to anonymous user. I have tried to hide the unwanted fields through display fields functionality of cck module, but it does not seem to work.

I also want to theme the node add form in a way that the various text fields with different text sizes should all appear of the same size to anonymous user. Just as a proper form.

Please tell me a way to do this.

# Answer
> 1 votes
You should also have a look at the Field Permissions module, which allows you to control granular permissions per field by role.

By default, if a user can edit a node they can edit all fields, but Field Permissions allows you to create specific privileges for the field if you need more granular control.

So for this instance, you'd want to enable edit privileges for the fields you want to hide from the anonymous users, then go to user permissions and grant edit permissions for those fields only to authenticated users. The result would be that the fields would be hidden from anonymous users, but still editable by authenticated users.

You could then use the Forms API as Dan described to make the fields all of a length for anonymous users, or use something as simple as CSS if your theme attaches a body attribute for logged-out users (many do).

# Answer
> 0 votes
Two different ways to do this are through creating a custom form in a drupal through the form API or the webform module. Either way it requires that you save the values into an array and deliever them to a Drupal hook that creates the node you want.

---
Tags: entities
---


# Question
Title: Displaying multiple child-grandchild-relationships properly through Views
I am using the most recent versions of Drupal (7.14), Views (3.3) and the Entity reference module (1.0 rc3).

I have three content types. The first of them (parent) contains a node reference field to the second (child), which has a node reference to the third (grandchild). Each of these reference fields have unlimited values.

I have set up a block view, with relationships for both node reference fields, and have defined a contextual filter for the parent node id.

This is what I want to display in the parent node, each with summaries and a few other fields from the referenced nodes:

```
Child 1
Grandchild 1
Grandchild 2
Grandchild 3

Child 2
Grandchild 4
Grandchild 5

```

With displaying an unformatted list of fields, I get the following result (aggregation doesn't help at all):

```
Child 1
Grandchild 1

Child 1
Grandchild 2

Child 1
Grandchild 3

Child 2
Grandchild 4

Child 2
Grandchild 5

```

Any suggestions for how I can get the display that I want?

# Answer
So you've tried going into your 'Settings' for the unformatted list style and setting a 'Grouping field' already?

If not, try the following, and make sure to check the box I've checked here as well:
> 2 votes

---
Tags: views, entities
---


# Question
Title: Views 3 "no results behavior" for different languages
I use i18nviews for the translation and it works fine! Under the Point "no results behavior" can i only choose Global:Textarea, but this is not allowed in different languages. What can i do?

# Answer
> 2 votes
This is a bug which is currently being worked on.

---
Tags: views, i18n-l10n
---


# Question
Title: Drupal 7 Commerce Price field not available to views
I am using Drupal 7.14, Commerce 7.x 1.3 and Views 7.x 3.3 I have created several products and also the corresponding content. Fields in the product type are the default fields - Product SKU, Title, Price and Status. The content type upon which the related content is based contains some extra fields - image, product reference, author and type. The products display singly perfectly with all the fields (image, Body, price, author, add to cart button and type). If I create a view to display this content the available fields do not contain the price field. All the others, however, display correctly. Why is the price field missing? Would be most grateful for anyone's help.

# Answer
> 6 votes
You should add **Content: Product** as a relation to this view. Then you'll have all the fields from the product available in the view.

---
Tags: commerce
---


# Question
Title: add name field with email to invite block
I want to capture the name of the user who is invited by an existing user, along with the conventional email field. This is because I want to use this name in the email that is sent to invited user so that he finds his own name on top of the mail bosy as "Dear 'name'" .

How can this be done?

# Answer
> 0 votes
I'm not exactly positive if this is what you're asking, so if I misunderstood the question, just let me know.

You can add any field you want to the user registration forms if you go right here on your site: /admin/config/people/accounts/fields

So even though there are not any 'First name' or 'Last name' fields by default, you can add anything you want and then get to those fields through views...

Does that help?

---
Tags: users
---


# Question
Title: How to publish content based on a Date field in custom content type in Drupal 7?
I have a Date field in a custom content type in Drupal 7. I would want to control the publishing of the content instance based on that particular Date. I want the job of the Scheduler module but have it as a field in my content type and access it accordingly. Is there a way to do it using triggers or Rules? Any thoughts on this would be really useful.

# Answer
> 3 votes
There is a patch to make the Scheduler "Publish On" date render itself as a field: http://drupal.org/node/1203958

This presents a new Checkbox called "Show Scheduling options in vertical tabs", which you can **uncheck** to display as a field. Then you give it some weight so it shows up where you want it to.

It's been working for me in production for a month or so.

**EDIT:** Here's a better way to make this happen with both Scheduler and Rules.

1. Create a Rule, "After saving new content"
2. Add a condition of "Content is of type"
3. Add an "Execute PHP" action with this:

$node-\>publish\_on = strtotime("\[node:field-datefield-here\]"); scheduler\_node\_insert($node)
4. Create a Rule, "After updating existing content"
5. Add a condition of "Content is of type"
6. Add an "Execute PHP" action with this:

$node-\>publish\_on = strtotime("\[node:field-datefield-here\]"); scheduler\_node\_update($node);

---
Tags: nodes, rules
---


# Question
Title: What is the proper file structure of a module that only contains sub-modules?
I have put together a module package that has 3 sub-modules. They must be contained in a single folder to be distributed and used by other devs. Are there drupal best practices for how a module's files structure should be if it contains just multiple modules?

e.g.

```
name_of_module/modules/module1/module1.info
name_of_module/modules/module2/module2.info
name_of_module/modules/module3/module3.info

```

or

```
name_of_module/module1/module1.info
name_of_module/module2/module2.info
name_of_module/module3/module3.info

```

or?

# Answer
For what i've seen, putting sub modules in a modules folder like your first example is most common best practice.
> 3 votes

# Answer
There aren't Drupal best practices about where to put submodules. You could:

* Put them in a separated sub-directory of "modules" contained in the directory containing the main module
* Put them in a separated sub-directory of the directory containing the main module
* Put them in the same directory containing the main module

Any of those directory structures is used:

* The Views module has a "modules" sub-directory, but that is not for sub-modules; both view.module and views\_ui.module are in the same directory that contains the main module.
* The CCK module has a "modules" directory where all the sub-modules are each contained in a separated directory.
* The Panels module has its sub-modules saved in a separated directory contained in the main directory.
* The Views Bonus Pack module uses three different sub-directories of the main directory.

There isn't actually a reason related to how Drupal handles modules, to choose a structure or another one.
There is a reason to choose the first two structures instead of the third one, and that is generally that each module comes with other files that are grouped in directories with the same name (e.g., css, js, templates), and you don't want to mix files that are for different modules.
> 2 votes

# Answer
I do the second one. Also please realize that the modules directory in Views does not contain modules at all.
> 0 votes

---
Tags: 7
---


# Question
Title: What's the default expiration time for block caches?
This article explains the cache setting in Drupal 7.

I'm using Blockcache\_alter to cache some blocks. It's not clear to me how long those blocks are cached.

# Answer
Nothing special here. It's the same as on your `admin/config/development/performance` page. Module *Block Cache Alter* just alters `'cache'` key for block and does not interfere with the mechanism of caching in Drupal.

```
Example 1:
Minimum cache lifetime: none,
Cron: every day,
Block cache will be flushed every day or if someone flush cache manually.
On node or comment submit: the whole block cache will be flushed.

```

In Example 1 the whole block and page cache will be flushed **immediately** on every new comment, node, vote submit because of `Minimum cache lifetime: none`. See where cache\_clear\_all() is called.

```
Example 2:
Minimum cache lifetime: 12 hours,
Cron: every 6 hours,
Block cache will be flushed every 12 hours or if someone flush cache manually.
On node or comment submit: only block cache older than 12 hours will be flushed.

```

Block and page cache items which are **older than 12 hours** will be flushed immediately on every new comment, node, vote submit. See where cache\_clear\_all() is called.

Cron period is important because Drupal tries to flush caches on every cron run.

This behaviour can be changed with Cache Expiration module.
> 6 votes

---
Tags: 7, caching
---


title: Choose Nodes within another Node

text:
# Question
Title: Choose Nodes within another Node
This is something I've struggled with for a long time in Drupal. I'm guessing it's a relatively easy answer but I haven't been able to find an elegant solution. Here's the problem:

Let's say I have an e-comm site with Categories, Coupons and Products(all are CCK content types). Each Category can have any number of Products and Coupons. I'd like the ability to have a menu within my Category node that will allow me to select any of the existing Product and Coupon nodes. Also, not necessary but ideally I'd like the ability to change the order of Products/Coupons within the Category.

Is this possible? Or, is there a better way to do this?

Thanks in advance.

# Answer
> 0 votes
May be you're better of creating a vocabulary for your categories. This way you can filter for vocabulary terms in views.

---
Tags: 7, nodes
---


# Question
Title: how can I remove registered .tpl.php file?
When I remove html.tpl.php file, I get this error:

```
Warning: include(/home/xxxx/public_html/sites/all/themes/cgame/html.tpl.php) [function.include]: failed to open stream: No such file or directory in theme_render_template() (line 1413 of /home/xxxx/public_html/includes/theme.inc).
Warning: include() [function.include]: Failed opening '/home/xxxx/public_html/sites/all/themes/cgame/html.tpl.php' for inclusion (include_path='.:/usr/lib/php:/usr/local/lib/php') in theme_render_template() (line 1413 of /home/xxxx/public_html/includes/theme.inc).

```

How can I remove this file to force drupal use core html.tpl.php file?

# Answer
> 1 votes
considering `White Screen of Death` problem you should clear cache from DB or change default theme to another theme so can clear cache from drupal admin interface, if you have access to DB first solution is easier and fast but in case you don't, use second one :

1.truncate `cache` table:

```
TRUNCATE cache;

```

2.set another default theme so you can clear cache from `admin/config/development/performance` page. you can simply edit `settings.php` and add `$conf['theme_default']= "new_theme_name"` variable to change default theme or edit `variables` table in DB and set `theme_default` name to another name, sample SQL:

```
UPDATE variable SET value='s:7:"garland"' WHERE name = 'theme_default';

```

then while this new theme is set you can clear cache as usual and then fallback to old theme without problem.

# Answer
> 1 votes
Simply clear the caches either on */admin/config/development/performance* or via *drush cc all* if you've configured drush.

---
Tags: theming
---


title: Where is htaccess located in Drupal 7?

text:
# Question
Title: Where is htaccess located in Drupal 7?
I'm looking for the .htaccess file that should be in the default installation of Drupal 7.

Normally it is supposed to be there. Does anyone know where it is located?

# Answer
The file's called `.htaccess` and it's in the root of the Drupal installation. A lot of operating systems hide files that start with a `.`, so that might be way you can't find it.

If it's simply missing, just download a fresh copy of Drupal and copy the default `.htaccess` file from there.
> 10 votes

---
Tags: installation
---


title: Creating a custom field/widget

text:
# Question
Title: Creating a custom field/widget
I'm trying to create a field that is a combination of two fields. The first field needs to a reference to another entity (just like in the entityreference module). The second field is just a text field (using the textarea widget).

Here's the code I have so far.

sample.install:

```
function sample_field_schema($field) {
    $schema = array(
        'columns' => array(
            'place_id' => array(
                'type' => 'int',
                'unsigned' => true,
                'not null' => true
            ),
            'quote' => array(
                'type' => 'text',
                'size' => 'big',
                'not null' => false
            )
        ),
        'indexes' => array(
            'place_id' => array('place_id')
        ),
        'foreign keys' => array()
    );

    $entity_type = 'place';
    $bundles = field_info_bundles('node');
    if (!empty($bundles['place'])) {
        $schema['foreign keys']['place'] = array(
            'table' => 'place',
            'columns' => array('place_id' => 'nid')
        );
    }

    return $schema;
}

```

sample.module:

```
function sample_field_info() {
    return array(
        'sample_field' => array(
            'label' => t('Label'),
            'description' => t('description.'),
            'default_widget' => 'sample_field_widget',
            'default_formatter' => 'sample_field_formatter',
            'settings' => array(),
            'instance_settings' => array(),
        )
    );
}

function sample_field_formatter_info() {
    return array(
        'sample_field_formatter' => array(
            'label' => t('sample formatter'),
            'field types' => array('sample_field')
        )
    );
}

function sample_field_formatter_view($entity_type, $entity, $field, $instance, $lang, $items, $display) {
    $element = array();

    switch ($display['type']) {
        case 'sample_field_formatter':
            // I'm not really familiar with these bits ... this is just to output *something*
            $element[]['#markup'] = var_export($items, true);
            break;
    }

    return $element;
}

function sample_field_widget_form(&$form, &$form_state, $field, $instance, $lang, $items, $delta, $element) {
    switch ($instance['widget']['type']) {
        case 'sample_field_widget':
            $element['place_id'] = array(
                '#type' => 'textfield',
                '#maxlength' => 1024,
                '#title' => t('Place'),
                '#default_value' => isset($items[$delta]['place_id']) ? $items[$delta]['place_id'] : null,
                '#required' => $element['#required'],
                '#weight' => (int)$element['#weight'],
                '#delta' => $delta,
                '#size' => 'big',
                '#autocomplete_path' => 'api/find/places'
            );

            $element['quote'] = array(
                '#type' => 'textarea',
                '#title' => t('Quote'),
                            '#default_value' => isset($items[$delta]['quote']) ? $items[$delta]['quote'] : null,
            );
            break;
    }

    return $element;
}

function sample_widget_error($element, $error, $form, &$form_state) {
    switch ($error['error']) {
        case 'sample_field_invalid':
            form_error($element, $error['message']);
            break;
    }
}

function sample_field_is_empty($item, $field) {
    if (empty($item['sample_field'])) {
        return true;
    }
}

function sample_field_widget_info() {
    return array(
        'sample_field_widget' => array(
            'label' => t('Sample Field Widget'),
            'field types' => array('sample_field'),
            'settings' => array(),
            'behaviors' => array(
                'default value' => FIELD_BEHAVIOR_NONE
            )
        )
    );
}

```

So this all gives me a new field type and a new widget for that field. When I edit/create new content that has this field type, the widget shows up properly with both fields but when I submit to insert/update the content, the fields are not saved. How can I get the form to save the field data for this custom field and how can I get that data to be loaded again when the content is edited?

# Answer
> 2 votes
It was my `hook_field_is_empty()` implementation. It was returning true in cases where it shouldn't have. Just make sure `hook_field_is_empty()` is properly checking for empty values.

# Answer
> 3 votes
You're missing hook\_field\_validate() which apparently is required for this to work. See this blog post (which you may have already -- I'm just comparing what he did to your code) ... http://www.agileapproach.com/blog-entry/compound-fields-drupal-7

---
Tags: entities
---


title: drush sql-dump asking for password

text:
# Question
Title: drush sql-dump asking for password
Whenever I run drush sql-dump it will prompt me for the database password. Is there a way that this can be done automatically? I don't quite understand why its not just reading this from settings.php

When I do a drush status --show-passwords it is shown there.

I ask because I want to script db backups to happen via drush. Any advice? Thanks!

# Answer
I presume you are using postgres.

psql, the commandline tool that Drush uses to manipulate the database, has no provision to pass a password as a commandline option, so Drush cannot provide it even if it knows what it is. You may set up a .pgpass file in your $HOME directory to supply the password; it should contain entries that look like this:

```
localhost:5432:*:www-data:PASSWORD

```

If you create this file, and insure that it is chmod 600, then psql will no longer prompt for the password.
> 9 votes

---
Tags: drush
---


title: How to theme one tab of a node

text:
# Question
Title: How to theme one tab of a node
I have `hook_menu()` configured to show a tab for every node at `node/%node/summary`. The callback for that page returns the correct content, but I'd like to add a bunch of HTML to the page.

I believe I need to create a `.tpl.php` file in my custom theme. How do I know what to name the file and make sure that the template is used only on the correct pages?

# Answer
> 2 votes
In Drupal 6, this would be:

```
 page-node-summary.tpl.php

```

More information on Drupal 6 template suggestions can be found at http://drupal.org/node/1089642

In Drupal 7, this would be:

```
 page--node--summary.tpl.php

```

More information on Drupal 7 template suggestions can be found at http://drupal.org/node/1089656

In either case, I'd grab the default page.tpl.php of your theme as a basis for it.

# Answer
> 0 votes
The theme developer module allows you to point and click on any part of your page. It shows you all called and possible theme functions and template names.

---
Tags: theming, routes
---


# Question
Title: How to print block generated by views in the tpl file?
I have a block with name: "Share Product"(block number 5) generated by my view with name: "main\_product\_deal". In this view i have 9 blocks.

Now in my .tpl file i need to print this block.

I have seen the function 'module\_invoke' but not working. My code is:

```
//On my tpl file
<?php
$block = module_invoke('views','block','view',"main_product_deal-block_5");
print $block['content'];
?>

```

I working in drupal 6.x. Is it correct my code? Or exist another solution? Note: I can not set the block in the administration, because I'm programming certain things in the tpl

Thanks :D

# Answer
Have you tried views\_embed\_view()? http://drupalcontrib.org/api/drupal/contributions!views!views.module/function/views\_embed\_view/6
> 1 votes

# Answer
Do you actually need the block, or can you just output the results of the view? If you just need the results of the view:

```
$view = views_get_view('main_product_deal');
print $view->execute_display('default');

```
> 0 votes

---
Tags: 6, blocks
---


# Question
Title: Adding of social media links( Facebook, Google Plus)
In my site I've already added Facebook Like, Google Plus and Addthis modules.

Facebook like shows up only in the bottom of the article and it won't display if we're in the home page where no node is shown in full view.

Google Plus also won't show for home page in teaser mode

Addthis shows up in the bottom.

So I've gone ahead and copy pasted this code in the "content top" position in Acquia theme from Addthis.com account:

```
<!-- AddThis Button BEGIN -->
<div class="addthis_toolbox addthis_default_style ">
<a class="addthis_button_facebook_like" fb:like:layout="button_count"></a>
<a class="addthis_button_tweet"></a>
<a class="addthis_button_google_plusone" g:plusone:size="medium"></a>
<a class="addthis_counter addthis_pill_style"></a>
</div>
<script type="text/javascript">var addthis_config = {"data_track_addressbar":true};</script>
<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#pubid=ra-4ed5fa1d3aa24279"></script>
<!-- AddThis Button END -->

```

So this will make the buttons display on all url's. I just want to know if I'm doing the right way. When I added this same code to another site using Acquia theme in the same position then this code caused the buttons to show in staircase way. So I removed this code.

My main concern is that this code should not break layout in any browser/version.

# Answer
> 3 votes
Maybe should you try ServiceLinks, instead. Very straightforward to implement.

My two cents.

---
Tags: 6, social-network
---


title: PHP code in mail body - Rules

text:
# Question
Title: PHP code in mail body - Rules
In the Rules module, is it possible to write php code in mail body? There is no input format beneath body text area.

# Answer
If you are willing to use PHP, I suggest you create your own rule, using `hook_action_info()`.

You have a good example in the Examples module.
> 3 votes

---
Tags: 7, rules
---


# Question
Title: Have user register or login on cart instead of checkout in drupal commerce
Is it possible to have the user account pane in the cart instead of the checkout?

I need to have users logged in or registered on the cart, because when users checkout I have a custom rule to change the order to a custom state "awating approval", and sends the user to a custom page with some text. Once the order is approved by the staff the state is changed to another custom state "approved" and a custom rule sends an email to the user so he can checkout and finish paying.

The problem is that if the user hasn't enetered his details before attempting to checkout, the email won't be saved and we have nowhere to send the user an email to finish checking out once the order is appproved.

# Answer
Is it possible: Yes.
Should you do it: No.

Why?

Having the user account pane at the the cart is a bad idea, since it probably would be very complex to do, and that there isn't really anything that hinders the user to start the checkout flow. You are also forgetting a very important thing.

The Commerce checkout flow is very customizable. This means that you can define extra pages in the checkout flow, and via the interface customize what should be displayed in each page. A much better solution would be to create an initial checkout page with account info only, an extra page that displays info about the order being validated and not allowing to process the order until it is approved. Once approved, the link could simply be that checkout page which with the updated order status can be skipped.

This will keep the customer in the checkout process and leverage the Commerce flexibility.
> 1 votes

---
Tags: commerce
---


title: an image that is inside the content

text:
# Question
Title: an image that is inside the content
Good morning, I use the Zen theme. I did override the node.tpl.php putting a copy in myzen / templates /, I saw that the content is printed with this statement:

```
print render ($ content);

```

my problem is that having made my own content type, content is an image and text, I would give a different width by css to my image and text. how do I make a reference with css at image and text placed separately?

# Answer
> 1 votes
The `$content` variable is an array (a 'render' array in Drupal parlance). You'll be able to render the parts of the content individually instead of all in one go if you want, and wrap them in specific HTML:

```
<div class="body">
  <?php echo render($content['body']); ?>
</div>

<div class="some-image-field">
  <?php echo render($content['field_some_image_field']); ?>
</div>

```

You can even provide a template file for just the content type you want to change, by calling it node--content-type-name.tpl.php, and just apply the changes to that particular content type.

For styling, each field will already be wrapped in HTML with many, many classes attached to it. Just fire up developer tools/firebug, inspect the elements, and you'll find the correct selectors to target with CSS. If that fails, you've can add the wrappers in yourself like in the code example above.

# Answer
> 0 votes
There are many ways you could this. You could use some of the preprocess functions in your themes template like THEME\_preprocess\_node() or maybe a bit deeper like THEME\_preprocess\_field().

---
Tags: theming, 7
---


title: AJAX dependent select

text:
# Question
Title: AJAX dependent select
I know this has been asked before and I'm trying to use the example at Dynamic select list in the form (dependent dropdown) but I am struggling to get the desired results.

The goal: Have a form that presents the user with a Platform select field. Once selected take the value from that field pass it to the a SQL statement to render an additional select field with a list of results from the query. Right now the following code displays both select fields when the form renders. I would like only the platform select field to be rendered until the user chooses an option.

I'm a little bit confused about the AJAX function and how you wrap another select item to be marked for replacement when the page is called again so any explanations or pointers would be great.

Per @Clive I've adjusted the code below. However I'm fighting with pulling the selected value into the model lookup query statement. Right now as is the form doesn't even render.

## Update 2

I've been cleaning up my code and catching small stupid errors. Which have yielded: 1)AJAX call back working. 2)Hiding the model select field when the platform select hasn't changed.

However I can't seem to make the model field appear when an option is selected in the Platform field. I suspect it's a problem with `if (isset($form_state['values']['platform'])) {`. Updated full code below. I feel close to completing this just need some guidance.

**Full Code**

```
function iosupload_menu() {
$items = array();
$items['ios_upload/form'] = array(
  'title' => t('IOS Upload'),
  'page callback' => 'iosupload_form',
  'access arguments' => array('access content'),
  'description' => t('IOS Upload'),
  'type' => MENU_CALLBACK,
);
return $items;
}

function iosupload_form() {
return drupal_get_form('main_iosupload_form');
}

function main_iosupload_form($form, &$form_state) {
//Define SQL Lookup Query
$sqlplatform = "SELECT vid, name FROM {taxonomy_vocabulary} WHERE vid >= 4";

$result = db_query($sqlplatform);
$options = array();
  foreach ($result as $row) {
    $options[$row->vid] = t($row->name);
  }

$form['platform'] = array(
  '#type' => 'select',
  '#title' => t('Select a Platform'),
  '#options' => array(
    0 => t('- Select -')) + $options,
  '#default_value' =>  0,
  '#required' => TRUE,
  '#ajax' => array(
    'callback' => 'ajax_select_callback',
    'wrapper' => 'replace_model_div',
    'effect' => 'slide',
   ),
);
if (isset($form_state['values']['platform'])) {
 $platform_value = $form_state['values']['platform'];
 $sqlmodel = "SELECT tid, name FROM {taxonomy_term_data} WHERE vid = $platform_value";
 $result = db_query($sqlmodel);
 $options = array();
   foreach ($result as $row) {
     $model_options[$row->vid] = t($row->name);
    }

$form['model_wrapper'] = array(
  '#type' => 'select',
  '#title' => t('Select a Model'),
  '#options' => $model_options,
  '#options' => t('$platform_value'),
  '#prefix' => '<div id="replace_model_div">',
  '#suffix' => '</div>',
);
}
return $form;
}
function ajax_select_callback($form, $form_state) {
  return $form['model_wrapper'];
}

```

# Answer
A few problems I can see:

* The `$model_options` variable is used both in the form and AJAX callback function, but isn't defined anywhere. Same thing with the `$platform` variable in the AJAX callback.
* You're putting a wrapper around a particular element, but instead of returning that element you're returning the entire form.
* It looks like you're attempting to put form-altering logic into the AJAX callback function - it should be used only to return the updated element, the actual building of it should be done in the form function.
* You're defining the AJAX callback wrapper as 'replace\_model\_div', and implementing it as a class name instead of an ID, and with a complete different name (`model-wrapper`).
* The function signature for your form is wrong (in Drupal 7 it's:

```
function form_name($form, &$form_state)

```

You should get some joy with code a bit more like this:

```
function main_iosupload_form($form, &$form_state) {
  //Define SQL Lookup Query

  $sqlplatform = "SELECT vid, name FROM {taxonomy_vocabulary} WHERE vid >= 4";
  $sqlmodel = "SELECT tid, name FROM {taxonomy_term_data}";

  $result = db_query($sqlplatform);
  $options = array();
  foreach ($result as $row) {
    $options[$row->vid] = t($row->name);
  }

  $form['platform'] = array(
    '#type' => 'select',
    '#title' => t('Select a Platform'),
    '#options' => array(
      0 => t('- Select -')) + $options,
    '#default_value' => isset($form_state['values']['platform']) ? $form_state['values']['platform'] : 0,
    '#required' => TRUE,
    '#ajax' => array(
      'event' => 'change',
      'callback' => 'ajax_select_callback',
      'wrapper' => 'replace_model_div',
      'method' => 'replace',
     ),
  );

  if (isset($form_state['values']['platform'])) {
    $model_options = function_to_get_model_options_by_platform($form_state['values']['platform']);

    $form['model_wrapper'] = array(
      '#prefix' => '<div id="replace_model_div">',
      '#suffix' => '</div>',
    );

    $form['model_wrapper']['model'] = array(
      '#type' => 'select',
      '#title' => t('Select a Model'),
      '#options' => $model_options,
    );
  }

  return $form;
}

function ajax_select_callback($form, $form_state) {
  return $form['model_wrapper'];
}

```
> 2 votes

---
Tags: forms, ajax
---


title: Module code within different files

text:
# Question
Title: Module code within different files
I wrote my own module that builds 4 forms with many features. Everything work great, but now i have reached 1000 lines of code and it's starting to get complicated to have all the forms on the same file. I would like to make some .inc files, maybe one for each form (the biggest form has 9 functions related to it) to make more order to my code and make it easier to maintain it, but I have no clue on how to split the code in a way it will work. How can i solve my issue?

# Answer
> 3 votes
You can split your code in as many files as you want. For every file except the \*. module file add a line to your \*.info file:

```
files[] = inc/my_form_1.inc

```

You can also place functionality into seperate files by specifying the path to the files in hook\_menu. Have a lookt at the `file` property in the `hook_menu` description.

---
Tags: 7, forms
---


# Question
Title: How do I create a form in a modal dialog with Drupal 7?
There seems to be many solutions for implementing a modal dialog including Ctools, Colorbox, Simple dialog, and Ctools Auto-modal. I'm not sure which is the best to use for simple coding through the Form API to create popup forms in a modal dialog.

The big issue seems to be validation. Are there any best practices for creating a modal form in Drupal?

# Answer
A good example for using forms on modal dialogs is in Ajax Login/Register module. You could see the module code and understand how it works(ajax\_register is using ctools\_modal).

Or you can render the form manually and use ctools only for the responses. For example:

*mymodule.module:*

```
function mymodule_form($form, &$form_state) {
  ...
  ctools_include('ajax');
  ctools_add_js('ajax-responder');

  $form['#prefix'] = '<div id="container">';
  $form['#suffix'] = '</div>';
  $form['actions']['submit']['#ajax'] = array(
    'callback' => 'mymodule_ajax_callback',
    'wrapper' => 'container',
  );
  ...
}

function mymodule_ajax_callback($form, $form_state) {
  if (!form_get_errors()) {
    $commands   = array();
    $commands[] = ctools_ajax_command_reload();

    return array('#type' => 'ajax', '#commands' => $commands);
  }

  return $form;
}

```

Now, you can anywhere render this form and show popup (using Twitter Bootstrap or Lightbox):

```
<a href="#container" data-toggle="modal">Show Form</a>
<div style="display:none;"><?php print drupal_render(drupal_get_form('mymodule_form')); ?></div>

```
> 5 votes

---
Tags: chaos-tool-suite, javascript, forms
---


# Question
Title: insert fields for the links in my content type
Good morning, I have to put in my content type of fields to collect a variable number of links (www.example.com). how can I do to allow insertion of variable numbers of fields and how do I then access them with php?

# Answer
> 0 votes
If I understood the your question, your solution is here.

It gives you the chance to insert link such as field. Once you enabled the module, you can add the field through "manage field" tab of your content type.

If you want to access via php, you can use the Devel module.

# Answer
> 0 votes
For every field you can define how many items it takes. Setting this to unlimited should do the trick.

1. Open the field management tab of your content type.
2. Click on edit for the link field.
3. Scroll down to "Number of values" and choose "unlimited".

To acces you node with php do a node\_load() with the appropriate nid and you get everything in a neat php sructure.

---
Tags: theming, 7
---


# Question
Title: How to set different paths to different images on the same views block
I have a situation where I have a block with 3 Images and links in the front page set in a block (drupal 7) and I am trying to make each image and link to point to a different section in the site but I can't :( I only managed to make them all point to the same page or to divide each to its own block (with views) but then it doesn't look so good visually...

is there a solution for that? Thanks

# Answer
> 1 votes
Ok, so here is a step by step "how to manage this" ;)

Step 1: be sure to have the content type for your images containing a field "link", where you can add the link to your specific page section.

Step 2: Add some content with image and URL to page section (e.g: node/13)

Step 3: Make sure you have some nodes like this:

Step 4: Create a new view for the block you want to fill with your content-type:

Step 5: Add the fields you want to show to the view: (here: the field for the image and the field for the link). If the link should be shown seperate from the image as well, you'll have to add the field for the link twice, because we'll "pass over" one link to the image)

Step 6: Now re-arrange the fields so that the order is the following. This is important, because the image field will hold a replacement pattern of the above Link field (which is excluded from display, because we don't want the link to show up, we only need its data).

Step 7: Now configure the first image field "excluded (mylink)" so that it is excluded from display and rewrites the output of the field with the replacement pattern for the "Raw url" value:

Step 8: Now configure the image field like this. Mark "Output this field as a link" and use the replacement pattern for the above link field "\[field\_mylink\]".

That's it. Now you have a view that pulls the URL from the content type and puts it on the image of it.

---
Tags: views, media, uri
---


# Question
Title: How to create "Custom Forms" that trigger own business-logic / do not create any Content
I'm new to Drupal, so sorry for this maybe simple question.

I'd like to create some kind of content-type, which a user can "create" and fill the forms, but instead of just saving the content to the database, i want Drupal to pass the values to a 3rd party software (which can be accessed by socket-communication), wich renders PDF's from the text the user entered.

The PDF should be displayed to the user after Form submission.

I know, i can use Drupal to render PDFs, but i want to connect to our legacy 3rd Party software.

So the question is: How and where can i hook-in to write my custom 3rd-Party socket-communication-phpcode and display the result to the user (or save it to drupal db, or, or, )?!

Thanks in advance!

# Answer
1. Create your form by using the drupa FAPI.
2. Set-up a path to your form using hook\_menu.
3. Call your custom communicatin code from your FAPI submit handler.
> 1 votes

---
Tags: forms, nodes, services
---


# Question
Title: Duplicate webform data to second database?
I want to duplicate the results from the webform module to a second database.

Is there a convenient way to do that, or will I need to manually write all the queries to store and retrieve data?

# Answer
> 4 votes
I wouldn't try to tackle this at the Drupal level to be honest, it'll be a lot more trouble than it's worth.

If it was me I'd just add a trigger on the webform table that runs a stored procedure to copy the data into the second database.

There might be something you can do with Replication, but I'm not sure if it's granular enough to go down to the table level.

---
Tags: forms, database, webforms
---


# Question
Title: Ajax call returning JSON forces IE8 and 7 to download file instead of reading it
I have a Drupal 7 site and I'm having this issue, commented here for Drupal 6

The thing is that, when ajax response is set as *Content-Type: **text/javascript**; charset=utf-8* IE 7 and 8 try to download the file. The solution they propose is to change a line in common.inc to declare the response as *Content-Type: **text/html**; charset=utf-8*

The solution they propose there means I have to modify Drupal core, I would prefer not to do that as this will be a problem in future Drupal updates.

So, have any of you found this problem? do you know another solution?

PS: When I enter my site, I also find a javascript error in consle saying *JQuery is not defined* in a lina of drupal.js where it does *jQuery.noConflict(); // Allow other JavaScript libraries to use $.* I don't think it's related but comment it just in case...

Thank you

# Answer
I finally located the error: it was because of the file codification, some of them were in *UTF-8* and other ones in *UTF-8 without BOM* so IE7 detected an strange character at the beginning of the json being unable to parse it, coding all files *(js* files, *php* and module files) in *UTF-8 without BOM* solved the problem
> 2 votes

---
Tags: ajax
---


# Question
Title: Drupal 7 with Display Suite and Apache SOLR search environments
I have the magnificent Display Suite working for search results but I can't for the life of me figure out how to use it to modify a search environment defined on admin/config/search/apachesolr/search-pages. Please can someone explain how do I use DS to change the display?

---

Outstanding. After a weekend of searching it turns out this is a known bug (http://drupal.org/node/1166114) which may be fixed in Drupal 8.

Does anyone know the best method for encouraging it to be fixed quickly in D7? I'd be prepared to contribute to a bounty.

# Answer
The second branch of Display Suite has full support for Apache Solr pages, it basically takes it over by default. This hasn't been committed to the first branch as it involves to much changes.

The second branch doesn't have much changes - you might get some notices first, but re-saving the Display configuration solves those.

The biggest change is the default template files which are a little different because the 'Hide empty regions' option has been removed. The logic for collapsing regions is now in the template file itself. That's why we now ship with a 2 column and 2 column fluid template for instance.
> 2 votes

# Answer
Change the active and default search modules in admin/config/search/settings to "Search Display".
> 1 votes

---
Tags: 7, search, display-suite
---


# Question
Title: How do I get items of a field of type list?
I have created a list field with 10 items(allowed values). Now I want to get that 10 items programmatically. How do I get them?

# Answer
Better create a vocabulary of taxonomy terms populated with your items.Then you can use taxonomy\_get\_tree() function to retrieve all those items
> 0 votes

---
Tags: 6, entities, nodes
---


# Question
Title: How to create a table during the module installation
I'm trying to create a module for Drupal 7 and I need to create 3 tables and populate it. But first i need to create it.

In the file mymodule.install I have got

```
function mymodule_install() {

}

function mymodule_uninstall() {

}

function myodule_schema() {
  $schema['mymodule_table'] = array(
    'description' => t('First table'),
    'fields' => array(
      'id' => array(
        'description' => t('My unique identifier'),
        'type' => 'int',
        'unsigned' => true,
        'not null' => true,
      ),
      'list' => array(
        'description' => t('list'),
        'type' => 'varchar',
        'not null' => true,
      ),
    ),
    'primary key' => array('id'),
  );
  return $schema;
}

```

What am I doing wrong? Every time I test the module, I disable it -\> uninstall -\> Performance clear cache -\> enable it.

# Answer
You're missing the `length` property for the `varchar` column ('list'). `length` is required so the `CREATE TABLE` query will fail.

From the Schema API docs:

> All parameters apart from 'type' are optional except that type 'numeric' columns must specify 'precision' and 'scale', and 'varchar' columns must specify 'length'.
> 11 votes

# Answer
`myodule_schema` has a typo. An `m` is missing after the `y`.
> 4 votes

---
Tags: 7, installation, database
---


# Question
Title: Displaying node reference select list as ordered menu list
I want to display the Node Reference Select List (usually a long list of nodes, unordered and generally quite long) as an ordered bunch of nodes, that replicate the structure of the menu system.

The whole idea, is for a user to be able to choose another Node, but as there are so many nodes already on the website - it can be difficult to find the correct one in the select list. I have attached a screenshot to show a random example of how I would like this to look. This is just a quick mock-up image that I hope can be achievable.

The new "menu style" select list makes it easier to find the particular nodes you want, as they mirror the menu system of the website.

I looked into using Views to replicate the structure of the menu in Drupal, but this doesn't seem possible either. If this was possible, I could simple use the "Advanced - nodes that can be referenced" and just list out the pages by the menu with the order - but it doesn't look possible to integrate Views and the drupal menu system.

Any help would be excellent with this. Thanks, Garry.

# Answer
> 1 votes
You can use view to display all node you want and use expose filter to search for a specific node or to display as tree I guess there is a module to display taxonomy as a tree reference to make it like parent and child so you can convert your node to be taxonomy to easy make it as a tree or change the module structure to display nodes

# Answer
> 1 votes
Using a view on the reference field and:

I have used

http://drupal.org/project/views\_hierarchy

or views tree

http://drupal.org/project/views\_tree

Could help you.

# Answer
> 1 votes
Most of the suggestions are for the display of hierarchy on the front end, however this requirement is to be able to get that on a Reference view, to be used for selecting a value in a nodereference field.

My solution was the following, which is dependent on path aliases reflecting the menu structure:

1. On the reference view add the field "Content: Path"
2. Install the module Views PHP or do a template override
3. Output the path of the node using the Global: PHP field like that below

nid); print substr($static, 0, strrpos($static, '/')).' - '. $row-\>title; ?\> The above giving you a list of node titles prepended by the menu path.

---
Tags: views, routes, nodes
---


# Question
Title: How to find out if a default image is used in content?
I have an Administration View for my content. I want to filter if a default image is used or if there is an already uploaded one.

I don't find a reference for this to use it as field and/or filter in views.

I tried the relationship for Content:Image, but this reveals nothing like "has default image" or something alike.

Any ideas?

EDIT: I now have a workaround for this. I added a field for the image as a mini-thumbnail, so a visual control if the default image is used is possible. The fields are in a table, so reverse sorting of the images reveals that all default-images come after custom images...

# Answer
i added a filter criteria on photo:fid(photo is field name for image) not equal to the name of default image and it worked. i hope this will help you
> 4 votes

---
Tags: 7, views, media
---


# Question
Title: Force drupal 7 to place "www" in front of urls
there is a problem when a use logs in after typing "domain.com", clicks on a internal link that leads to "www.domain.com/somthing" and they are no longer logged in until they navigate to "domain.com" again. I just want the system to force the url to add the www at the beginning.

# Answer
Adding this to your .htaccess file will do it...

```
RewriteCond %{HTTP_HOST} !^www\.YOURDOMAIN\.com [NC]
RewriteCond %{HTTP_HOST} !^$
RewriteRule (.*) http://www.YOUDOMAIN.com/$1 [R=301,L]

```
> 7 votes

# Answer
@New Talk is correct.

In Drupal 7 uncomment these lines:

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

```

Line 83 and 84.

@MPD is also correct. You will need to re-uncomment these everytime you update your drupal core version.
> 3 votes

---
Tags: 7, uri
---


# Question
Title: what does hook_field_is_empty actually mean?
I feel like I'm retarded but when I read the page at api.drupal.org I'm still wondering what the point is of the function. It says 'Define what constitutes an empty item for a field type'. I'd expect that this function would put NULL there if a value wouldn't be present, but it doesn't look like this is happening.

Also: is it required to write this function in my .module file to get a fieldname in my drop-down list of the Manage Fields page (you know, as a babystep)

# Answer
> 4 votes
I think it's used for fields that can accept multiple values, to determine whether or not the last item in the list has been filled out, or is in the 'new' state without having been filled out.

If this function didn't exist the field API wouldn't be able to make a distinction between what is classed as a filled-in row, and what is a 'New' row that hasn't been filled out, and for which the values should not be saved.

It can also be used to ensure that a minimum of columns in a field are filled out before it's classed as a save-able value.

If I remember rightly the hook is 'required' for modules that provide a field, so I'm not sure if you'll get away with leaving it out.

You could easily just implement it and return a `TRUE` or `FALSE` though for testing purposes.

---
Tags: 7, entities
---


# Question
Title: Generate price from item selected in drop down
I am using Drupal 7.14, Commerce 7.x 1.3 and Views 7.x 3.3. I want to have a drop down list on my product display form (or content display form) containing, say:

Full Price, no coach required - £ 200 Full Price, Glasgow coach - £ 230 Full Price, Edinburgh coach - £ 230 Full Price, Liverpool coach - £220 ....

and I want, when an item on the list is selected, the displayed price to change to the indicated value and, of course, this to be passed to the cart.

How can I do that.

# Answer
> 1 votes
You can do this using the Rules module: http://drupal.org/project/rules/. That should already be up and running if you're using Drupal Commerce.

So just go to admin/config/workflow/rules and add a new rule that looks something like this:

1. **Event**: Calculating the sell price of a product
2. **Condition**: Entity has field: \[commerce-line-item\], Field:
3. **Action**: Set the unit price to a specific amount; Parameter: \[commerce\_line\_item\]; Value: can either select another field to base this on or do a hard-coded value; Leave Price component type and Price rounding mode to their defaults
4. Test!

Let me know if this ends up working for you

---
Tags: commerce
---


# Question
Title: Is there a way to have a single field behave as a text field and a file upload/browser at the same time?
I need an option for users to have a single field behave as both a textfield so they can enter an external url or browse/upload field depending on which one they want to use. Having two fields will be confusing for users. Is this possible?

# Answer
Somehow the users have to decide what type of data they want to enter. An option would be to let them choose and then show the appropriate field only. The condotional field module could comme in handy here.
> 1 votes

# Answer
You can include 1 text field for the external URL and 1 Browse/Upload button to directly upload a file. That should keep your users from getting confused.
> 0 votes

---
Tags: 7
---


# Question
Title: Invoice module to run with commerce module?
I'm looking for the right module to include invoicing capabilities with the Commerce module, but none of them fully fit my needs. Are there any other modules to help with invoicing?

# Answer
The most up2date list of Drupal Commerce invoicing modules can be found at http://drupal.org/node/1535498
> 5 votes

---
Tags: commerce
---


# Question
Title: Programatically linking an image to content (Drupal 7)
When I create a block through views I can easily link it to the content page by setting link image to in the field's settings. But I also have some blocks that are created programmatically and I would like to similarly add links to these images. How would I do this?

EDIT: Here is the code I use to create the block:

```
  $block = array();
  $rows = array();
  $format = 'l, F j, Y  - G:i';

  $header = array('Project Name', 'Screenshot' , 'Submitted');
  foreach ($results['node'] as $nid_array) {
    $row = $nid_array->nid;
    $node = node_load($row);
    $path = $node->field_icon_thumbnail['und'][0]['uri'];
      $variables = array(
    'path' =>  image_style_url('icon_thumbnail',$path),
    'alt' => 'Thumbnail',
    'title' => 'Thumbnail',
    'attributes' => array('class' => 'some-img', 'id' => 'my-img'),
    );
      $image = theme('image', $variables);

      $rows[] = array(
    l($node->title, "node/$node->nid"),
    $image,
    date($format, $node->changed)
      );
  }
  $rows = array_reverse($rows);
  $table = array('rows' => $rows, 'header' => $header, 'empty' => 'No terms found');
  $block['content'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#empty' => t('No terms found')
  );
  return $block;

```

# Answer
> 8 votes
You can use the `l()` function to wrap the image in a link. As it's HTML you'll need to pass the `html` option to the function so that it isn't run through `check_plain()`:

```
$image = theme('image', $variables);

$linked_image = l($image, "node/$node->nid", array('html' => TRUE));

$rows[] = array(
  l($node->title, "node/$node->nid"),
  $linked_image,
  date($format, $node->changed)
);

```

---
Tags: 7, media, navigation
---


title: Confidential webform submissions

text:
# Question
Title: Confidential webform submissions
I'm using Webform to set up a number of enquiry forms on a company's extranet and they require submissions to be confidential. Since access to anything on the extranet requires user login, the forms can't be submitted anonymously and some user info is associated with each submission.

I can get around this issue in outgoing emails by removing the user-specific info from the email template, but submissions stored in the database still retain user info.

I suppose my question is this: how can I disable Webform submissions from being recorded in the backend, OR, how can I modify recorded submissions to remove user info (basically to store nothing but the date/timestamp and message)?

# Answer
Well you can always use form altering to provide you own submit function
> 2 votes

# Answer
Another option is the Webform Rules module. You likely have to implement your own action though. Here is an excerpt about it from the module's project page:

> ... adds rules integration on webforms.
>
> Did you ever want to react on webform submission using rules but couldn't find the proper event? Webform Rules makes it possible to catch webform submissions by rules and do whatever you'd like to do with it (meaning: do whatever rules let you do with it).
> 1 votes

---
Tags: webforms
---


# Question
Title: what to fill in after $items in hook_field_is_empty
I'm trying to build a module that constructs a field that needs to show in Manage Fields. I'm trying to understand what it is function by function. Looking at the example field module the code says

```
function field_example_field_is_empty($item, $field) {
  return empty($item['rgb']);
}

```

Where does this `'rgb'` come from? What is `$item`? How do I know what to put there in another field? My guess is that it just represents whatever is filled into the field, the actual value. Becuase the value of my field is going to be an HTML link, my guess is, for now at least, to type `$item['link']`. But I can't really verify it.

# Answer
`rgb` is one of the column names defined by the field\_example module's implementation of `hook_field_schema()`:

```
function field_example_field_schema($field) {
  $columns = array(
    'rgb' => array('type' => 'varchar', 'length' => 7, 'not null' => FALSE),
  );
  $indexes = array(
    'rgb' => array('rgb'),
  );
  return array(
    'columns' => $columns,
    'indexes' => $indexes,
  );
}

```

These columns are the actual storage for your field's various values, and represent the columns you'll find in the `field_data_*` and `field_revision_*` tables in a normal Drupal installation.

In the case of the rgb field there's only one column, but for many fields there are multiple columns (for example the image field which besides a 'fid' (file id) column has 'alt' and others).

The `$item` passed to `hook_field_is_empty()` is the representation of an instance of your field attached to an entity...essentially it contains the values filled in (or not as the case may be) by the user.

All of the columns you define in `hook_field_schema()` will be available in `$item` in `hook_field_is_empty()`...you then use whatever custom logic you need to decide whether the field has been sufficiently completed for storage, and return a `TRUE` or `FALSE` to represent that.
> 1 votes

---
Tags: 7, entities
---


# Question
Title: What's the minimum amount of code needed to have a field show up in Manage Fields?
I tried copying the functions from the field module in example modules to get a field to show up in Manage Fields without necessarily any functionality

Looking at the answer to this question, only field\_create\_field() and hook\_field\_info() should do the trick but I never got that working with the following code:

```
function entityreference_add_new_field_info() {
  return array(
       'entityreference_add_link' => array(
          'label' => t('Entityreference link'),
          'description' => t('Entityreference link'),
          'default_widget' => 'entityreference_link_widget',
          'default_formatter' => 'entityreference_link_formatter',
      ),
    );
  field_create_field('entityreference_add_link');
}

```

Putting `field_create_field()` outside of `hook_field_info()` returns 'call to undefined function' error.

**Update:** Here's one thing I've tried without success:

```
function entityreference_add_new_field_info() {
  return array(
       'entityreference_add_link' => array(
          'label' => t('Entityreference link'),
          'description' => t('Entityreference link'),
          'default_widget' => 'entityreference_link_widget',
          'default_formatter' => 'entityreference_link_formatter',
      ),
    );
    field_create_field('entityreference_add_link');

$instance = array(
    'field_name' => 'entityrefernce_add_link',
    'entity_type' => 'node',
    'label' => 'The Link',
    'bundle' => 'node',
  );

field_create_instance($instance);

}
enter code here

```

# Answer
> 0 votes
You have already created the definition of the field, but you also need to create an actual instance of that field to use it.

```
$instance = array(
    'field_name' => $your_field_name,
    'entity_type' => 'node',
    'label' => $your_field_label,
    'bundle' => 'node',
  );

field_create_instance($instance);

```

That plus what you have above should be the minimum you need to get a field to appear in your management screen.

See the field\_create\_instance() docs for more info about available options.

---
Tags: 7, entities
---


# Question
Title: Programmatically add more than one taxonomy term in Drupal 7
Just a quick question. I'm creating a node and adding a term to the node like this:

```
 $newNode->field_tags[$newNode->language][]['tid'] = "a digit here";

```

Fine, but how do I add more than one term per node? I've tried a comma-separated string of digits and an array of digits but neither work.

# Answer
> 7 votes
You can just keep adding to the array the way you're already doing:

```
$newNode->field_tags[$newNode->language][]['tid'] = "a digit here";
$newNode->field_tags[$newNode->language][]['tid'] = "another digit here";

```

Or you could loop instead:

```
$tids = array(1, 2, 3);
foreach ($tids as $tid) {
  $newNode->field_tags[$newNode->language][]['tid'] = $tid;
}

```

---
Tags: taxonomy-terms, nodes
---


title: Complicated views with dates

text:
# Question
Title: Complicated views with dates
I need a somewhat complicated view setup. I don't know if I can even do it with views...

I have a page, we'll say the url is "/example". When a user hits "/example", they'll see a main content area and a sidebar. The main content area has a list of nodes. The one requirement I can't seem to figure out is how to have this list be limited by time, rather than number. I want the last 3 months of nodes to show up, not a set number.

Then in the sidebar is an "archive" view (seems best to me to just have it be a separate view from the main one, even though it concerns the same content) where the years should be listed (if they have nodes) and under each year the months should be listed (again, only if they have nodes).

Such as:

```
2012
February
March
2011
April
December
2010
January

```

I see an example "archive" view in the default views, but it's not quite set up like this.

I know views is very capable, but can it do this?

# Answer
> 2 votes
For the second view , I think it's possible using agregation : you will have to select two times the field dates , the fist one will be displayed as year and second one month , then use group by the first date field. If it doesn't work then in the fields settings you will have to separate the date as one field for year , and one field for month , then you will have to group by the year field in the views.

Here is a great tutorial from nodeone.se of how to use agregation in drupal 7 :

---
Tags: 7, views
---


title: Admin Module with highly customized UI

text:
# Question
Title: Admin Module with highly customized UI
I have a web app with a complex database that I created for a previous project. I'd like to integrate that old project into my new drupal site. I don't need it to be fully drupal-ized, but I need to at least leverage drupal's user authentication.

I'm trying to find a good tutorial about creating a module which provides an admin page and has a very customized UI. I don't need drupal to create form items for me. Any suggestions?

My UI fetches and updates all of its info via AJAX, so I need each of those AJAX calls to be at least minimally managed by drupal for user authentication purposes.

Does that make sense? Any suggestions?

# Answer
Have a look at `hook_menu()`. It's the cornerstone to define pathes and who has access to them.

In drupal you define a path by implementing hook\_menu in a custom module. There you define what php functions are called and what user roles do have access to it. This way you can route your AJAX calls through drupal autentication and authorisation.
> 1 votes

---
Tags: 7, users
---


# Question
Title: Drupal 7 subtheme location best practice
I currently have an Omega subtheme located as a subdirectory of the .../sites/all/themes/omega. I think this location was a requirement for Drupal 6. Now that we're on Drupal 7, I'm looking for the best practice on where this subtheme should be located. Does it make sense to add it to .../sites/all/modules/custom/ or maybe create a new directory like .../sites/all/modules/themes/.

Any best practice advice would be great.

Thanks

# Answer
Themes should be stored in sites/all/themes, not sites/all/modules.

You could certainly add your custom theme to sites/all/themes/custom, but what I do is just add my custom theme(s) to sites/all/themes directly. I do this because I name my custom themes for the sites I am working on, so it's very clear that the particular theme is specific to the site.

The other reason I don't think a /custom directory is necessary is because, unlike modules, one generally only has five or six themes (at most) installed on a single site. So there is far less possibility for confusion.
> 3 votes

# Answer
I prefer to keep sites/all/ for themes and modules I get from drupal.org, and place custom themes and modules under sites/default/themes and sites/default/modules, directly. I do this so that the custom work is in the same place as the public files and the settings file. By keeping everything together, I only need to worry about a single tree, sites/default/, when moving between servers.

Drupal 7 Module Development says (pg 28) says that this is the current best practice, but I have never see this cross-referenced to official docs on drupal.org.
> 1 votes

# Answer
The best practice is: don't leave them in `/themes`. Whether you use `/sites/all/themes` or `/sites/mysite.com/themes` only matter for multisite codebases: `/sites/all` will be shared, while `/sites/mysite.com` will be site-specific. This means that @MPD's approach is useful, since contributed modules and themes should be shared (with shared and contributed patches). But keep in mind that updating a module in `/sites/all` will require running database updates on every site!
> 0 votes

# Answer
Sub-themes are not required to be in a sub-directory of the parent theme, in Drupal 6 and higher. Drupal 6 introduced the "base theme" property that should be used in the .info file of the child theme.

Creating a sub-theme says:

> The sub-theme to-be should be located in its own directory. Prior to Drupal 6, this directory had to be a subdirectory of its base theme; in Drupal 6 and 7 it can be placed outside of the base theme's directory.
>
> To declare your theme to be a sub-theme of another, it is necessary to alter the sub-theme's .info file. Add the following line to the sub-theme's .info to declare its parent or "base theme." Change "themeName" to the internal name of the parent theme (that is, the name of the parent theme's .info file, usually all lower case).
>
> ```
> base theme = themeName
> ```

As per the directory where to put a theme, these are the directories where Drupal looks for a theme:

* profiles/$profile/themes
* sites/all/themes
* $config/themes

$profile is the machine name of the currently used profile, and $config is the directory containing the settings.php file currently used. The subdirectories of those directory are also checked, which means (for example) that sites/all/themes/custom/bluecheese could be used to contain a theme.
In any case, the modules directory is not checked, if it is not a sub-directory of one of the directories I listed before. I would rather avoid mixing modules and themes, or using "modules" as name of a directory containing a theme.
> 0 votes

---
Tags: 7
---


# Question
Title: Where are the best places to post Drupal 7 RFP?
Do you have any thought on the best places to post an RFP for Drupal 7 development and theme work?

I have posted on drupal.org and groups.drupal.org but someone mentioned odesk, but I wasn't sure if that would be fruitful or just overkill.

# Answer
> 1 votes
drupal.org reaches a wide audience, and is a good venue. That said, please be aware that widely distributing an RFP can be harmful to your project. Many of the best shops don't respond to RFPs. Advomatic has published an interesting presentation on this topic.

# Answer
> 0 votes
There is the paid services forum on drupal.org and there is also the #drupal-consultants channel on chat.freenode.net, wher you can find consultants to discuss the project in real time.

---
Tags: 7, theming, community-official-site
---


title: Taxonomy per-node theming

text:
# Question
Title: Taxonomy per-node theming
This is something I don't even think Drupal has built-in features for. I'm trying to theme taxonomy term page's nodes. The actual major problem is, I want to theme them per item. This for the actual HTML hierarchy (this is only a **representation of the semantics** I want, this is not to be interpreted as a visual representation):

```
+------ DIV ------+
|+----- DIV -----+|
||     node 1    ||
|+---------------+|
|+----- DIV -----+|
||     node 2    ||
|+---------------+|
+-----------------+

+------ DIV ------+
|+----- DIV -----+|
||     node 1    ||
|+---------------+|
|+----- DIV -----+|
||     node 1    ||
|+---------------+|
+-----------------+

+------ DIV ------+
|+----- DIV -----+|
||     node 1    ||
|+---------------+|
|+----- DIV -----+|
||     node 1    ||
|+---------------+|
+-----------------+

```

I really need this setup and can't be bothered with using complex CSS selectors (eg. :nth-child(odd)) this due to browser compatibility.

The only way I can imagine (and read on some places on the interwebs) is creating views as a workaround and theme that. But I would like not to make these excessive measurements just to workaround the lack of theming abilities of the taxonomy module.

Any thoughts? I thank you in advance!

# Answer
This is the listing page for the taxonomy items, correct? the node page would be after you click on one of these to see the full content of that particular piece of content? And, if I understand correctly, you want a two column layout of this list? Here is a site I did recently that does that very thing.

http://noboribetsu-spa.jp/en/stay

This is very easy to accomplish. Just float left the class that wraps the item and all of them will fall into place. Let me know if I am not understanding what you are asking.
> 0 votes

# Answer
You could do this with Views grid style, set to two columns, then theme the template: views-view-grid--taxonomy-term--page.tpl.php to something like this...

```
<div class="<?php print $class; ?>"<?php print $attributes; ?>>
  <?php foreach ($rows as $row_number => $columns): ?>
    <div class="clearfix row <?php print $row_classes[$row_number]; ?>">
      <?php foreach ($columns as $column_number => $item): ?>
        <div class="col <?php print $column_classes[$row_number][$column_number]; ?>">
          <?php print $item; ?>
        </div>
      <?php endforeach; ?>
    </div>
  <?php endforeach; ?>
</div>

```

Then just float the cols:

```
.view-taxonomy-term .col {
  float: left;
  width: 50%;
}

```
> 0 votes

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


# Question
Title: How to Add rel="nofollow" in "Add new comment" link in teaser?
Is there a code to add rel="nofollow" in the "Add new comment" link under teaser?

This is the code in the teaser as generated by D7:

Add new comment

So how I do I add rel="nofollow" in that line?

# Answer
> 2 votes
You could do this by implementing `hook_node_view_alter` in your custom module or theme.

```
//replace MODULENAME below with your custom module's name
function MODULENAME_node_view_alter(&$build) {
  if ($build['#node']->type == 'book') {
    $build['links']['comment']['#links']['comment-add'] = "rel=\"nofollow\"";
  }
}

```

This is for node type *book*, you could replace it by the content type you are using.

Here is the Module developer's guide, which should get you started.

# Answer
> 2 votes
You can do this in preprocess as well. Better to use structured data as its meant to be an not push attributes as strings, that will bound to create an error at some stage because theme\_link() wants attribute arrays, not strings.

```
function themename_preprocess_node(&$vars) {
   if ($vars['node']->type == 'blog') {
    $vars['content']['links']['comment']['#links']['comment-add']['attributes']['rel'][] = 'nofollow';
  }
}

```

---
Tags: 7, hooks, comments
---


# Question
Title: Allow users to choose which layout to be applied
Is there any way to allow users to choose which layout to be applied (Omit the given media queries) for the Omega theme?

For example, ESPN has a switcher for choosing the layout: When browsing in iPad, it has a link to switch to desktop.

Do you have any idea on how achieving such functionality with the Omega theme?

# Answer
> 1 votes
Responsive designs usually rely on media queries to apply the styles, but you could make a copy of those styles and prefix its selectors with `body.desktop`. Then, when you want iPad users to see different styles, just add the class to the `body` element (using jQuery). CSS preprocessors like SASS will help you mantain those styles without duplicating the code — Zen 7.x-5.x has awesome out-of-the-box support to SASS/Compass and responsive designs. See the Sassy module as well.

There is also the adaptive design approach: it relies on browser sniffing to return device-specific markup and styles. The mobile tools module will surely help should you choose this approach.

---
Tags: theming
---


# Question
Title: Show block content inside custom node template
I've created a custom template (`node--<mytype>.tpl.php`), and I'd like to display the calendars from the Availability Calendars module. I don't understand how to load them.

I've tried with this code, but it doesn't work.

```
$block = module_invoke('availability_calendar', 'block_view');

```

Can you help me?

# Answer
> 1 votes
First, you have to make your block available inside your `node.tpl.php`, so edit `template.php` and add the following:

```
function YOURTHEME_preprocess_node($variables) {
  $YOURBLOCK = block_load('MODULENAME', 'BLOCKDELTA');
  $variables['YOURBLOCK'] = drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));
}

```

Then, on your node.tpl.php you can `print $YOURBLOCK;` anywhere you want.

And yes, you have to call two "private" functions from block module, see http://api.drupal.org/api/drupal/includes%21module.inc/function/module\_invoke/7#comment-15884

# Answer
> 0 votes
You can do it with `print $block['content'];`

Make sure that you're using appropriate arguments for `module_invoke` API

```
$block = module_invoke('block', 'block_view', 30);

@arg 1 : module name
@arg 2 : hook name like block_view, block_info
@arg 3 : id or delta of the block e.g 30, map-block_1

```

in D7 you can also try `block_load` API

---
Tags: 7, theming
---


# Question
Title: How to use Views 3 API to display custom tables?
I have some custom tables in the Drupal Database which are not of any content types. I want to use Views to display the values from the tables on to the website. Is there a way or a module that already provides this functionality? I am using Drupal 7 and Views 3 API.

# Answer
After lots of research and work, this answer is for people who faced the same problem. The Data module does this for you. This module allows you to adopt a table (created in your Drupal Database and is not a part of any content type, basically a standalone table) and creates a view for that table. The view can be customized. The requirement here is that the table must have a primary key. You can also index this view by creating a content type and using the Views References Module. This will facilitate the indexing of the content in the table and make it show up in search results. Hope this helps.
> 2 votes

---
Tags: views, database, theming
---


title: Change menu options order

text:
# Question
Title: Change menu options order
I am a beginner with Drupal. I have successfully installed it and:

1. Created the front page. I did it through Content, Add content, Basic page. Then Configuration, Site information and then in the Default front page I put the alias of my Basic page.
2. Created an Image gallery with ColoxBox plugin. I went to Structure, Views and created a new view. This view is linked to the Main menu in order to obtain a link in the Menu.

The problem is that my Galleries link came before the Home link.

How can I change the order of these links?

Any help will be appreciated.

# Answer
> 1 votes
Go to admin/structure/menu/manage/main-menu (drupal 7) You can drag the menus to set the order. Or give then weight.

---
Tags: routes, nodes
---


# Question
Title: MySQL master/slave database replication?
Since it's so easy to set up pagodabox with multiple databases (for free), I thought I'd experiment with master/slave database setups.

I have good credentials for both MySQL databases. Everything should be fine and dandy.

The trouble is: At no point does Drupal create tables on the slave DB. I made a module to show me the credentials, and verify the connection, but the DB simply has no tables.

Should it? Is Drupal supposed to do this? Or do I need to do the initial replication myself?

# Answer
No, Drupal doesn't.

Master/Slave replication is the job of the database management system, not Drupal's. All that Drupal does is use it, by using the slave server for specifically marked queries.

To be able to use replication, you either need a pre-configured hosting environment which already provides this or full access to the database server so that you can configure it. Replication happens on a server to server level, not database to database. In short, Pagodabox will most likely not allow you to set up replication.
> 4 votes

---
Tags: 7, database
---


# Question
Title: Views Group by date plus showing newest node
I have a view of photo nodes uploaded by users and want to group them by post date and user. That part is pretty straightforward once you patch views. Just set sort by "post date" with "day" granularity and add a username field to group by user and day.

I use "count distinct" for nid to show the number of photos by user. I even used "format plural", "no results behavior" and "rewrite output" to only show a link to more photos if there are more than 1 photos per user. So far so good ...

The challenge I'm having is when I try to show a photo and title. When I add the "title" field with "group results" it's now showing each photo instead of grouping. If I use "max" or "min" it will only show 1 photo per user but now the photo won't match the title.

So, how can I show a photo and matching title for photos grouped by day and user? At this point it doesn't matter much if the photo is the oldest or newest for that user and day.

thanks!

# Answer
In terms of the database there is two ways to make this happen.

1. Using GROUP BY (=aggregation)
    * group by *user* and *day*.
    * add additional sort criteria so that the photo you want to display is the first in this ordering.
    * mysql automatically displays the value of the first row in the group for each field that hasn't another aggregation function applied (and isn't grouped by).
    * Example to display the first photo per user and day (pseudo-SQL): `SELECT node.*, DAY(created) AS day FROM node GROUP BY user, day ORDER BY created`
2. Reformulate the problem and filter using joins
    * The first photo from each user per day can be reformulated as: The photo of each user (per day) that hasn't got an older one on this day.
    * In SQL this can be realized using joins
    * `SELECT n1.* FROM node n1 LEFT OUTER JOIN node n2 ON n1.uid=n2.uid AND DAY(n1.created)=DAY(n2.created) AND n2.created<n1.created WHERE n2.nid IS NULL`

In theory both ways should be expressible in views. But both are rather hard:

1. views doesn't support ungrouped/unaggregated fields in queries using aggregation. So to work with that you'd need to patch views.
2. Views provides no way to add additional conditions to relations.

The simplest way to achieve this is perhaps by using views to create the query without aggregation (like in 1.) and then use hook\_views\_query\_alter() to add the grouping:

```
function yourmodule_views_query_alter(&$view, &$query) {
  $query->groupBy('node.uid')->groupBy('day');
}

```

NOTE that this won't work as is and without testing. You'd need to take a closer look at the `$query` generated by views to do this right.
> 1 votes

---
Tags: 7, views
---


title: How to create a tab

text:
# Question
Title: How to create a tab
I would like to have a tab appear in the view of a node, like the "View, Edit, and in the example shown) the Group Tab. Any ideas? I'm guessing it is going to have to write some custom code.

(see attachement)

# Answer
> 0 votes
For creating tab in views you have to go to the menu option in your views and select menu tab option then create your menu that will reflect as tab. If you are not clear enough. Then let me know the exact requirement, like where do you want to create tab, on landing page after login or on custom view page.

You can do this without custom code as i have done same thing many times.

# Answer
> 1 votes
Drupal by default displays the tab to the users who have the permission to access the particular section. For example, you can see these tabs when you are logged in as administrator (user1) of the site. If any other role has the permission to edit the node, then the edit tab will be displayed to the user having that role, by default.

**EDIT:** Extra tabs may get added by adding contributed modules to the site (also depends on the permission to the users to access it). See the screenshot, it adds an extra tab `Devel` to the node type page. It is because I downloaded and enabled the Devel module.

# Answer
> 0 votes
If you are talking about default tab for any node you created then add a line to your page.tpl.php.

```
<?php if ($tabs): ?>
              <div class="tabs">
                <?php print render($tabs); ?>
              </div>
           <?php endif; ?>}

```

# Answer
> 0 votes
in your module you can add menu with its function callback

```
$items['user/%user/group'] = array(
    'title' => 'Group',
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'user_group_page',
    'access callback' => TRUE,
  );

```

this should be in yourmodule\_menu() hook function. user\_group\_page() will return content for this tab you should define it in your code

---
Tags: routes
---


title: Fields API vs. fields in hook_schema

text:
# Question
Title: Fields API vs. fields in hook_schema
Can someone please explain what is the advantage of using Fields API to create fields for an entity rather than just declaring them in hook\_schema as values?

It's a bit of work to get all the fields defined, instances, options, allowed and default values, etc. and then you have to deal with getters and setters and finally uninstalling everything is not as simple as db\_delete, esp if you have reference fields in use by other entities.

# Answer
> 7 votes
The most important advantage of using fields, rather than custom data in a custom table, is that your data has immediate integration with the rest of the system; including (but in no way limited to):

* Automatic integration with Views
* Potential to use `EntityFieldQuery`s
* Fields can be managed using the standard system UI, even if built in code
* Automatic integration with Features
* There are many contributed widgets that can enhance the UI of a field (e.g. the Term Reference Tree widget
* No need to load your custom data onto the node/entity in a load hook, the core field system does that for you
* No need to define CRUD operations for your data

I'm sure there are many, many more.

Basically, if you want fine-grained control over the operation/performance of your extra data then use a custom table. If you want the system to handle all of that for you, use a field. For what it's worth I pretty much always use a field to store any entity data these days.

# Answer
> 2 votes
As mentioned in the comment of Clive's answer, when having a custom entity built on top of Entity API's controllers invalidates most of Clive's points. You get CRUD, entity properties\*, you can easily make your entity exportable, EFQ support, even views integration for free. And you have better performance because your data is in a single table and avoid to carry around the field definitions.

There still are a few advantages of using fields, though:

* Fields supports multiple values of every field type.
* You can store values for different languages and you get an UI for this with the Entity translation module.
* The Field UI, that allows to add additional fields to your entity. So for a re-usable entity, you might want to make it fieldable even if you don't add any fields yourself.
* Generated based on the schema, so you probably need to tune them a bit and add the proper type (boolean, date instead of int and so on).

# Answer
> 0 votes
Berdir and Clive are fully right.

In practice I found only one reason not to use fields: database performance. Every write/update of a field causes two INSERT statements. If you have 50 fields and you do a node\_save() this will trigger 100 INSERTs.

Please note that this is not important if you have a few thousand nodes and write to them a few times an hour. But updating 10 million nodes in a batch is an other story. For such situations you should think about a custom entity built on top of Entity API's controllers as berdir mentioned or have a look at an alternative storage like MongoDB.

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


# Question
Title: Giving Add and remove option to select and deselect from one list to another
I want to make user able to chose from one list of select options to another . A good example is in the picture here .

. Could you please tell me if there is a module to achieve this? I tried using two select elements in the form and some jquery . But that is not working perfectly . The problem is when user once select the options and visit next time , the previously chosen list does not appear . Thank you .

# Answer
I think you're probably looking for the Improved Multi Select module.

> The Improved Multi Select module replace the default multi-select boxes with two pannel list and search.
>
> The first panel holds the options that are available, and the second panel holds the options that have been selected.
>
> Two panels are separated by "add" and "remove" buttons. You can select an item from the first box, click the "add" button, and add it to the second box. Likewise, you can select an item from the second box, click the "remove" button, and it goes back into the unselected box.

The screenshot from the module page looks pretty similar to the screenshot in your question, except there's no drag-and-drop re-ordering built in (you would need to implement that yourself I think):
> 2 votes

---
Tags: 7, javascript, forms
---


title: Custom template for custom block

text:
# Question
Title: Custom template for custom block
I'm tying to show all the taxonomy terms from a specific vocabulary linked to the current node being viewed. I'm doing this with a new block defined in my module.

In my hook\_block\_view i need to give a $block\['content'\] a value, i'm putting a 'foobar' in it because i won't use it, and i add a new key 'tags' which is a array with my tags to render. Then in my block.tpl.php i check the block name and change the rendering if my custom block is rendered.

I guess there must be a better way of doing this...

I would love to add a custom template file, that will be used on my specific block. Is this possible?

Thanks, Jonathan

# Answer
This is a good article on what trying to do...

http://www.pixelclever.com/how-theme-specific-blocks-drupal
> -1 votes

---
Tags: blocks, theming
---


title: Collapsible fields with Views

text:
# Question
Title: Collapsible fields with Views
This is a follow-up to this question about automatic node title generation.

I'm using the "Question of the Week" content type. Its fields are "Date," and "Answer;" "Question" is its title.

What I want is a view with a collapsible field for "Answer." The view is used in a block shown in the front page ("This week's questions"), and on a page ("Past questions").

How can I get a view that has a collapsable field?

* Automatic Node Title doesn't work the way I want it (can't hide hours, Doesn't update title when content is changed, etc)
* View Accordion won't let me hide last of three fields (so I can't show two fields, "Date," and "Question," while hiding answers with VA).
* Collapsable Text plugin screams about depreciated functions and breaks other stuff.
* I don't see how to combine two fields into one in Views.

I either need to be able to collapse/hide a single field within a view, or combine two fields into one for the view. I'm looking "Computed field" now; I am not sure how to create a field via PHP, though.

I'm trying to make this into a computed field that adds the two fields together, "Date" and "Question," but all the examples I can find are Drupal 6.

# Answer
What I ended up doing...

I have 3 fields in the "content type: Question of the Week":

```
Date (Date of Question)
Question (Question of the week)
Answer (Answer, needs to be "hidden" and shown on click)

```

The problem was that Views Accordion would NOT hide two fields at once and I couldn't get views to combine two fields.

I found "computed\_field". Using computed field, I made a field with this "Computed Code":

```
$timestamp = mktime(0, 0, 0,
     substr($entity->field_jcqotw_date[LANGUAGE_NONE][0]['value'], 5, 2),
     substr($entity->field_jcqotw_date[LANGUAGE_NONE][0]['value'], 8, 2),
     substr($entity->field_jcqotw_date[LANGUAGE_NONE][0]['value'], 0, 4));
$formatted = date("M-d-Y", $timestamp);

$entity_field[0]['value'] = $formatted . '<br />' . $entity->title;

```

And this "Display Code":

```
$display_output = $entity_field_item['value'];

```

I have PHP 5.3 installed on my server and need to look at possibly using DateTime instead of Date... but this works for my means as of right now. It gives me date/time for
> 1 votes

# Answer
To merge fields you should override a template in your view. ( Views 3 and HTML5 - how to override output for markup? )

I'm new to theming in drupal and wanted to merge fields myself to make collapsible fields few days ago as well, but with no luck. Then I used a css-only workaround without merging fields or modifying any markup. I used it recently in a comision work:

http://aelasoca.cat/web/

The frontpage is an unformatted view using fields. Each 'new' has the standard separate fields in separate divs (Title, image, date, intro-text, category). I used relative/absolute css positioning and opacity to show/hide text and put it over the image. Then with :hover behaviors and changing opacities and positions again I can make appear or dissapear fields. I've used this as reference:

http://www.sohtanaka.com/web-design/css-on-hover-image-captions/
> 1 votes

# Answer
There is also a setting in Views to "rewrite" fields, which you can use to combine content in several fields into one. Open a field setting and check out the "rewrite" options. In particular, check out the "rewrite the output of this field" option, and the replacement patterns you can use.

Some more info is found here: http://drupal.org/node/1578524
> 0 votes

---
Tags: 6, views
---


title: Accessing a field collection

text:
# Question
Title: Accessing a field collection
My content type uses a field collection (field\_site\_web) to allow users to enter multiple websites, consisting of a name (field\_site\_name) and an internet connection (field\_link).

I want to use a `foreach()` loop to get those value, but I do not know how to access these fields. How can I do?

EDIT

how can I do to avoid the error in the line of the foreach? I tried so, but does not work:

```
if($fc_fields != false){
  // Extract the field collection item ids
  $ids = array();
  foreach ($fc_fields as $fc_field) {
    $ids[] = $fc_field['value'];
  }
}

```

# Answer
> 12 votes
The field collection is an entity in it's own right; the values stored against your node are a list of field collection item ids that you'll need to load manually to loop over. Something like this:

```
// Get the field collection items.
$fc_fields = field_get_items('node', $node, 'field_field_collection_field');

// Extract the field collection item ids
$ids = array();
foreach ($fc_fields as $fc_field) {
  $ids[] = $fc_field['value'];
}

// Load up the field collection items
$items = field_collection_item_load_multiple($ids);

// Loop through the items and extract field values
foreach ($items as $item) {
  $link_fields = field_get_items('field_collection_item', $item, 'field_link');
  $link = array_shift($link_fields);
  $url = $link['url'];

  $site_name_fields = field_get_items('field_collection_item', $item, 'field_site_name');
  $site_name = array_shift($site_name_fields);
  $name = $site_name['value'];
}

```

---
Tags: theming
---


# Question
Title: Exclude a not-hidden field in the content
In Drupal 7, I'm tying to show all the taxonomy terms from a specific vocabulary linked to the current node being viewed. I'm doing this with a new block defined in my module.

I added a field called tags in my contenttype and gave this field the whole taxanomy behavior. This made it possible to get the terms with:

```
$node = menu_get_object();
$node->field_tags <- array of tags to use

```

But, here comes the problem, this field is only there when it's set to visible in admin/structure/types/manage/page/display . But when i do that it also becomes visible in the content. If i put it to hidden it does not only get removed in the content/node view, but it's also gone from the whole $node object.

It there a way of getting the fields from the current node that are set to hidden?

Thanks, Jonathan

# Answer
> 0 votes
The field shouldn't be removed from the `$node` object...if it is then I'd check what custom/contrib modules you have installed that might be causing this to happen. It's not supposed to.

A sure-fire way to make sure all fields are attached to the object is to re-load it:

```
$node = node_load($node->nid, NULL, TRUE);

```

That will re-load the `$node` fresh from the database, with all fields attached. You do take a performance hit doing this. However, Drupal core will never have removed the field from the `$node` object in the first place, so if you've got some other theme/module that's doing this you'll either have to find/repair/remove it, or use a more a extreme method like the one above.

---
Tags: nodes, entities
---


title: Query to save 10 fields

text:
# Question
Title: Query to save 10 fields
Using Drupal 7, I created a node with the 10 fields; these fields are inserted as a table.

What query can I use insert the field values to the multiple tables, since multiple tables are the multiple fields?

# Answer
> 2 votes
Use the API: node\_save().

Saving data directly to field tables is not possible, you shouldn't even consider this. There are many ways to import data into nodes, for example the Migrate or Feeds modules, if that's what you're after.

# Answer
> 1 votes
You should not worry about the query to use, normally, as Drupal saves the fields for you, if you are using the node edit form.

If you are not using the node edit form, you should use the functions Drupal provides to save entities, such as node\_save() for nodes, or user\_save() for user objects.

The reason you should not save field data directly in the database is that there is an API for field storage: the Field Storage API. The default field storage module uses the local SQL database to implement these operations, but that could not be true for other implementations of the field storage; this is what happens with the MongoDB field storage module, part of the Mongodb project.
Drupal doesn't take assumptions about the field storage, and so should your code.

---
Tags: nodes, entities
---


title: Profile2 taxanomy and views

text:
# Question
Title: Profile2 taxanomy and views
i have a problem considering drupal 7 and views. i have a taxonomy view the lists al the terms: http://conversal.w0p.be/feesten

Now i have used profile2 for tagging my profiles an made a second view that listens to an argument /feesten/%

But now if i want to get all the http://conversal.w0p.be/feesten/evenementen profiles i et the page that gives the detail of that term and not the profiles. Ive googled a lot and can't find any good answer related to this :s

THNX in advance !

# Answer
Have it working now :) made 2views 1taxonomy view and 1profile view and renamed the taxonomypath to something else. and rewrite the taxonomy-name url in the taxonomy view
> 0 votes

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


# Question
Title: best location for features related theming customizations
The following is a simplified scenario of an organizational problem I'm facing.

I have a site with a single `features` module which handles all my content types. My `features` module is called `foo` and my `zen` subtheme is called `bar`.

One of my content types (e.g `event`) needs a special class on it so I have 2 options.

Add the class via the `foo.module`:

```
function foo_preprocess_node(&$vars) {

  if ('event'==$vars['type']) {
    $vars['classes_array'][] = "extra-class";
  }

}

```

or add the class via the `template.php` of `bar` theme:

```
function bar_preprocess_node(&$vars) {

  if ('event'==$vars['type']) {
    $vars['classes_array'][] = "extra-class";
  }

}

```

Which one of the two is the best location for this theme related customization? Without the `feature` there will be no `event` content type. So it feels like placing the code in the `feature` module file together with the content types is the best place.

On the other hand this css class is theme related so it also feels correct to place it in the `template.php`.

# Answer
This is just my opinion...

The HTML class itself is not related to the theme, it's related to the module defining the element on which it's placed (if it is a feature specific class name as @barraponto points out in the comments).

The *styling* for elements with that class is the theme's responsibility.

I would suggest that your code would be more appropriate inside the feature module. If it's not, imagine what will happen if you change themes...you'll lose the class that was on that element, meaning it can no longer be targeted for styling.
> 2 votes

---
Tags: 7, theming, features
---


title: How can I theme webform?

text:
# Question
Title: How can I theme webform?
I've got a website with a custom theme who was developed by an external group. I would like to custom the webform appearance.

In my form, there are grid fields. And these grid fields need to have a description. But in my custom theme, the description appears under the grid and I would like it appears just between the label and the grid. I hope you see what I mean.

In the `theming.txt` it seems that I have to edit the `webform-form.tpl.php` and save it to my theme folder. But in this file, there are only PHP code. So, how can I modify the HTML structure?

# Answer
I found the solution.

Editing the template.php file of my custom theme and more specifically the theme\_form\_element() function. In that function, simply move these 3 lines where I want :

```
if (!empty($element['#description'])) {
    $output .= ' <div class="description">' . $element['#description'] . "</div>\n";
}

```
> 0 votes

---
Tags: 6, theming, webforms
---


# Question
Title: How to add selective js on the page load?
I have initialized four js files in .info file.Now on a single page if i want to load only two of .js files not all ,how can i do this?

# Answer
JS included in your theme's .info file will be loaded on every page, there's no option to make them conditional (that I know of).

If you have files that need to be conditionally loaded you should do so in your theme's template.php file (perhaps in a `hook_preprocess_page()` function), and use `drupal_add_js()`:

```
function MYTHEME_preprocess_page(&$vars) {
  if ($some_condition) {
    $path = drupal_get_path('theme', 'MYTHEME') . '/path/to/file.js';
    drupal_add_js($path);
  }
}

```
> 6 votes

---
Tags: nodes
---