# Question
Title: Is it always bad to pass a variable through t()?
I have a little helper function for my hook\_schema:

```
function _bbcmap_schema_asr_field($description) {
  return array(
    'type' => 'int',
    'unsigned' => TRUE,
    'size' => 'small', // Up to ~66k with MySQL (equivalent up to ~660.00 adjusted)
    'not null' => FALSE,
    'description' => t($description),
  );
}

```

And then I can use it something like:

```
/**
 * Implements hook_schema().
 */
function bbcmap_schema() {
  $schema['la_data'] = array(
    'fields' => array(
      ...
      'mort_asr_male' =>    _bbcmap_schema_asr_field('The age standardised mortality amongst men (fixed point with scale factor 1/100)'),
      'mort_asr_female' =>  _bbcmap_schema_asr_field('The age standardised mortality amongst women (fixed point with scale factor 1/100)'),
      'incid_asr_male' =>   _bbcmap_schema_asr_field('The age standardised incidence amongst men (fixed point with scale factor 1/100)'),
      'incid_asr_female' => _bbcmap_schema_asr_field('The age standardised incidence amongst women (fixed point with scale factor 1/100)'),
      ...
    ),
  );
}

```

I know that the guideline is not to pass variables through `t()` but this seems very similar to how the menu system passes the callback's title through `t()` (by default). Any comments on this being good or bad style?

# Answer
The first argument of `t()` needs to be a literal string, which excludes:

* variables, even the parameters of a function: `t($description)`
* a concatenation of strings: `t('If you want to add a link, click on' . '<a href="http://example.com">this link</a>.')`
* the value returned from a function:`t(get_menu_description())`
* a constant: `t(MYMODULE_MY_WIDGET_TITLE)`, `t(MyClass::WIDGET_TITLE)`

The reason is that, apart few specific hooks (e.g. `hook_menu()`, `hook_perm()`, `hook_permission()`), the string to translate are found from a script that scan the code of a module, looking for code such as `t('This is an example.')`; when it finds a value that depends from runtime, such as the value of a variable, the script is not able to understand which is the string that needs to be translated, as a variable could contain a different value each times the code gets executed. In fact, http://localize.drupal.org reports a warning similar to the following one, in the case the argument for `t()` is not a literal string:

> The first parameter to `t()` should be a literal string. There should be no variables, concatenation, constants or other non-literal strings there. At `t($filter['name'])` in customfilter/customfilter.module on line 30.

If you are passing a dynamic value to `t()`, the script that extracts the strings to translate will not extract any value, in that case; the effect is the argument passed to `t()` will not be translated, which has the same effect of not using `t()` and using the dynamic output directly in the user interface. The only case for which the string will be translated is when the dynamic string is equal to the literal string a function passes to `t()`. Suppose, for example, that you have a library not thought for Drupal, which contains a function returning the name of the current month. With the following code, the value returned from that function would be translated.

```
function mymodule_calendar_page_title() {
  return t(Calendar::getCurrentMonth());
}

function mymodule_calendar_translations() {
  $translations = array(
    t('January'),
    t('February'),
    t('March'),
    t('April'),
    t('May'),
    t('June'),
    t('July'),
    t('August'),
    t('September'),
    t('October'),
    t('November'),
    t('December'),
  );
}

```

`mymodule_calendar_translations()` doesn't need to be called, nor to return any value. When the code of the module will be parsed, the call to `t()` will be found from the code that looks for literal strings passed to `t()`.

Translating the description given for a database table and its fields is then not something that you should do, as none of the Drupal core modules do that; for example, node\_schema() contains the following code:

```
function node_schema() {
  $schema['node'] = array(
    'description' => 'The base table for nodes.',
    'fields' => array(
      'nid' => array(
        'description' => 'The primary identifier for a node.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'vid' => array(
        'description' => 'The current {node_revision}.vid version identifier.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      // …
    );
    // …
  );

  // …

  return $schema;
}

```

The report that caused the removal of the calls to `t()` from any Drupal core implementations of `hook_schema()` is Remove t() from all schema descriptions, which has been open by webchick (Drupal 7 co-maintainer).

> In Szeged, we had a big long discussion about `t()` around the schema descriptions and it was the consensus of everyone at the table (who included Dries) that `t()`s should be removed from these descriptions. They mess up things because `t()` isn't available that early, and people discussed that no one is going to take the time to translate technical descriptions of stuff, and it doesn't really make sense since we also don't translate code comments, for example.

The article about converting a Drupal 6 module to Drupal 7, has a dedicated paragraph: Schema descriptions are no longer translated.
> 18 votes

# Answer
They are invariable strings, so it's good to pass them through `t()`. There are some overhaul of t() system for things like this, but I'm not sure it will happen in D8.

Currently, it is only bad if you pass something like `t($count . ' books')` where `$count` can take any value, as it will generate too many string for the translation.
> 2 votes

# Answer
It is, however, possible to use t() around a variable, and for it to work. I have done it with $title in page.tpl.php.

EDIT: Perhaps the strings don't get translated, but they can be used for string overrides.
> -1 votes

---
Tags: i18n-l10n, database
---


title: Image based on node taxonomy terms

text:
# Question
Title: Image based on node taxonomy terms
Here is what I am trying to do.

If there is an empty image field on a node I want it replaced based on what taxonomy terms are on the page, but the key is I want to apply it site wide so it will affect not only the tpl files but Views as well. I'm guessing this needs to be done via mytheme\_preprocess\_field in template.php but I'm not quite sure how to do it.

I can easily do this in node.tpl.php but I need it done site wide, not just in the node-type template.

* VID 1
    + TID 1
    + TID 2
    + TID 3
    + TID 4
* VID 2
    + TID 5
    + TID 6
    + TID 7
* VID 3
    + TID 8
    + TID 9
    + TID 10

Here is what I am trying to do.

```
// Set Variables
$term1 = $content['field_term1'][0]['#markup'];
// Must use if statement or else there will be an error
if ( isset( $content['field_term2'][0]['#markup'] ) ) {
  $term2 = $content['field_term2'][0]['#markup'];
}
// Must use if statement or else there will be an error
if ( isset( $content['field_term3'][0]['#markup'] ) ) {
  $travel_type = $content['field_term3'][0]['#markup'];
}
if (isset($content['field_node_image'][0]['#item']['uri'])) {
  $image_path = file_create_url($content['field_node_image'][0]['#item']['uri']);
} else {
  switch ($term1) {
    case 'TID 1':
      switch ($term2) {
        case 'TID 5':
          $term_type = '5';
          break;
        case 'TID 6':
          $term_type = '6';
          break;
        case 'TID 7':
          $term_type = '7';
          break;
      }
      break;
    case 'TID 2':
      $term_type = '2';
      break;
    case 'TID 3':
      switch ($term3) {
        case 'TID 8':
          $term_type = '8';
          break;
        case 'TID 9':
          $term_type = '9';
          break;
        case 'TID 10':
          $term_type = '10';
          break;
      }
      break;
    case 'TID 4':
      $term_type = '4';
      break;
  }
  $image_path = '/sites/all/themes/themename/term-images/' . $term_type . '.jpg';
}

```

# Answer
> 0 votes
I used to use the Taxonomy Image module. It has full views integration as well.

```
Features:

    Image configuration happens within existing admin/taxonomy menu structure.
    Admins can add custom tags to <img> markup when displaying images.
    Allows one-to-one term-to-image relationships.
    Allows many-to-one term-to-image relationships.
    Admin-permitted users can disable the images.
    Administrators can force images to be a standard size.
    May use the ImageCache module if it is available.
    Works with Views.
    Utilizes core file.inc and taxonomy.module APIs.
    Small module with specific, focused functionality.
    Add-on modules that virtually eliminate the need for theme changes.

```

# Answer
> 0 votes
If you want to do some custom coding based on what's in the node from the field template you can get to the node from $variables in preprocess\_field like so:

```
// Parent entity could be a node or custom fieldable entity, usually going to be a node.
if(!empty($variables['element']['#object'])){
  $parent_entity = &$variables['element']['#object'];
}

```

At this point you can do whatever you were doing in the node preprocess in the field preprocessor. This can potentially get a bit heavy, so beware

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


# Question
Title: Anonymous user's can't views/download files uploaded via file field
I have a node with a File field and i am using public file system. I have uploaded a file via File field and checked the mark "display" in the list of attached files to node, but still, anonymous user's can't even view it (also they can't download it), till i check this permission:

But i think it's security vulnerability. Is drupal 7 file access system broken? Or am i missing something?

**Manage display page**

# Answer
> 3 votes
Figured out! I have uploaded a .rar file, so drupal wouldn't recognize this as existed file types e.g. audio, image, document. I had to go in **admin/structure/file-types/manage/document**

And add mimetypes for .rar and .zip extension:

```
application/rar
application/zip

```

Then just reuploaded file and gave anonymous user's permission:

```
Document: Download any files

```

---
Tags: 7, users, files
---


title: Hook_mail, drupal_mail and MIME mail

text:
# Question
Title: Hook_mail, drupal_mail and MIME mail
I've successfully managed to send email by using drupal\_mail and hook\_mail, but the next step is to send attachment within the email. I've read that this is not possible without adding extra modules, like MIME and Mail System.

OK, here's my code that sends email without attachments:

```
<?php
//The form page callback
function mymodule_news_page($form, &$form_state) {
    $form['title'] = array(
        '#type' => 'markup',
        '#markup' => '<div class="add-news-title">Add news</div>',
    );
    $form['upload'] = array(
        '#type' => 'managed_file',
        '#title' => t('Upload image'),

    );
    $form['description'] = array(
        '#type' => 'textarea',
        '#title' => t('Description'),
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
        '#submit' => array('mymodule_news_submit'),
    );

    return $form;
}

function mymodule_news_submit($form, &$form_state) {
    $upload = $form_state['values']['upload'];
    $description = $form_state['values']['description'];

    $params = array('upload' => $upload, 'description' => $description );
    drupal_mail('mymodule', 'mymodule_news_mail', 'myemail', language_default(), $params);
    drupal_set_message(t('Message sent!'));
    //dpm($form_state);
}

/*
** Implements hook_mail().
*/
function mymodule_mail($key, &$message, $params) {
    switch($key) {
        case 'mymodule_news_mail':
            $message['subject'] = t('Hello');
            $message['body'][] = t('This is a test for adding news');
            $message['body'][] = t('Image upload: @upload', array('@upload' => $params['upload']));
            $message['body'][] = t('Description: @description', array('@description' => $params['description']));
        break;
    }
}

```

As you can see I have a form that has three fields: upload, description and submit button. I'm trying to upload a image, but on submitting I receive an email with filled description and the uploaded image is not in the email, but it shows some numbers like 110...

Now I've enabled the MIME and Mail System module, and from their README module I can see this line: "'attachments': Array of arrays with the path or content, name and MIME type of the file (optional)."

I guess this is for uploading files, but there's no other documentation, so it's not clear how can I use MIME mail with hook\_mail and drupal\_mail().

What do I have to add in my code, so the uploaded file will be sent into the email?

# Answer
No, the part in the documentation is not referring to file uploads, but indeed to mail sending. The expected array structure can look like this:

```
'attachments' => array(
  array(
    'filename' => 'text.csv',
    'filepath' => $filepath,
    'filemime' => 'application/csv',
  ),
),

```

or

```
'attachments' => array(
  array(
    'filename' => 'text.csv',
    'filecontent' => 'test content',
    'filemime' => 'application/csv',
  ),
),

```

Also have a look at this for another example: https://drupal.org/comment/5617230#comment-5617230

**Edit**: The attributes that you can use

* `filename`: This is the name of the file as it will appear for the mails recipient. So you can freely choose this name.
* `filepath`: If you want to attach a file that exists on your server, then this is the attribute that you want to use. Specifiy the full path to the file (e.g. image).
* `filecontent`: If the attachement doesn't exist on your server but you want to send some content *as* an attachment, then you can use this attribute to pass on the content.
* `filemime`: Here you can specifiy the mimetype of your attachment. This information gives the users mail application some basic information what to do with the attachment. An attachment of type *application/pdf* will probably open in the local pdf application, if the mimetype is *image/jpeg* it will probably open in an image viewer application.

`filepath` and `filecontent` are somewhat mutual exclusive. I'm not sure what will be the result, when you specify both.
> 4 votes

---
Tags: forms, hooks, emails
---


title: drupal_json_output() output ascii

text:
# Question
Title: drupal_json_output() output ascii
I have a module that populate commerce cart product titles. The function looks like this:

```
   function spcart_get(){
  global $user;
$order = commerce_cart_order_load($user->uid);
$wrapper = entity_metadata_wrapper('commerce_order', $order);
//var_dump(commerce_line_item_load(176)->line_item_label);
$line_item_id_sp;
$cart_product_array = array();
for ($i=0 ; $i < sizeof($order->commerce_line_items['und']); $i++){
    $line_item_id_sp = $order->commerce_line_items['und'][$i]['line_item_id'];
    $line_item = commerce_line_item_load($line_item_id_sp);
    $cart_product_array[] = commerce_product_load($line_item->commerce_product['und'][0]['product_id'])->title;
}

$output = (object) array('products' => $cart_product_array);
return drupal_json_output($output);
}

```

but the output of the function is in ascii: {"products":\["\u05d0\u05d5\u05e8\u05d6","\u05d0\u05d5\u05e8\u05d6"\]}

I want that the output json will be un regular UTF-8 letters... What is the problem?

# Answer
drupal\_json\_output actually echos out the code its self so you don't need to return it's output, but you do need to exit after calling it:

```
drupal_json_output($output);
drupal_exit();

```

I'm not sure if this will fix your problem but certainly won't hurt...
> 0 votes

# Answer
You can probably blame `drupal_json_encode_helper()`, and the fact that you're running a PHP version \< 5.3. That function is used in place of `json_encode()` for earlier versions of PHP, and, rightly or wrongly, escapes unicode characters in the way you're describing.

If I recall correctly you're right, this is an unnecessary (and evidently annoying, sometimes) step. JSON's preferred encoding is UTF-8, and there are only one or two forbidden characters.

You can probably get around it by using plain old `echo json_encode($output);` instead.
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: Display nodes under Parent Taxonomy in Views
I am using Drupal 7, and I created a two-level vocabulary used it as a field for term reference. I created it using Simple hierarchical select module.

*edit* : I have my node tagged with both the parent(State field), and child (City field) term.

**Location**

```
 - State1
   - City A
   - City B
 - State2
   - City C
   - City D

```

Then I have a page View, where I use the Location field as an exposed filter, so that visitors can sort the content.

I have no problem in getting the results when the user selects for example:

> * Illinois
>     + Chicago

Then all content that has the term `Illinois` **and** `Chicago` will be displayed.

The problem comes when I only want to sort using the parent term, so if you sort for example using only

> * Illinois

It should display every node that has the term `Illinois`. But my Views returned nothing, when selecting only the parent term and applying that exposed filter.

I have checked that when you look view the taxonomy of `Illinois` everything displays properly, but not on the exposed filter in Views.

How will I proceed on displaying the nodes in my Views using exposed filters?

# Answer
I have managed to work this one out.

Apparently you can add a filter using two methods:

* "Simple hierarchical select"
* "Content: Has taxonomy terms (with depth; Simple hierarchical select)"

Select the second method `Content: Has taxonomy terms (with depth; Simple hierarchical select)` as the filter.

Then after selecting the filter, you then have the option to select which taxonomy term to use. After that just select `Simple hierarchical select`.

Next step was to just simply expose the filter to users, so they can manipulate it.
> 1 votes

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


# Question
Title: Accessing data on Drupal with external application
I'm developing a native iOS application for a small company. The company has a career website on which they publish job offers. The contents such as job descriptions and contact person information are maintained with Drupal. Is there a way to get the plain data of the contents from an iOS application? I never used Drupal before, please help me.

Thanks a lot in advance!

# Answer
Yes, you can use module Views to create content listings (http://drupal.org/project/views) with Services (https://drupal.org/project/services) and combine them to web services with the content listings using Services Views module (https://drupal.org/project/services\_views).

Also, look at Drupal iOS SDK (https://github.com/kylebrowning/drupal-ios-sdk) for some basic already implemented connectors from ios to drupal. (Retrieving specific single user/piece of content, retrieving already mentioned views etc...)

I would start with downloading and enabling the modules, understanding views (https://drupal.org/node/1911062), then read the documentation for services (contained in the module)
> 1 votes

---
Tags: database
---


# Question
Title: Check if viewing teaser in hook_node_access
Is there a simple way that I can forcibly allow **everybody** to view **all** teasers no matter what, overriding any other permissions set by Content Access, etc.

I was thinking something like this:

```
function mymodule_node_access($node, $op, $account) {
  if( $op == 'view' && ... viewing teaser ) {
    return NODE_ACCESS_ALLOW;
  }
  return NODE_ACCESS_IGNORE;
}

```

and then I would set the module weight really high. But I'm not sure how to check `if viewing teaser`. I would also need Views to respect the access I'm granting.

# Answer
> 0 votes
This is not possible in `hook_node_access`, Drupal does not allow for this so easily. Instead, you could use module Premium Content (https://drupal.org/project/premium\_content) and do this in configuration.

Btw., this question has already been answered: Show teasers to anonymous visitors but not allow access to the body/node

---
Tags: views, hooks, users, nodes
---


# Question
Title: How do I pre-configure default blocks for my drupal 7 theme
I'm open-sourcing a custom drupal theme, and I'm looking to provide a good out-of-the-box experience to those who use it. However, when the theme is enabled for the first time, many of the default drupal blocks (search, user login, "powered by drupal," etc.) are all jammed in the first block-region (pre-header), which pushes everything down and makes the page look broken.

I'd like to do one of the following things:

1. Unassign all blocks by default for the theme, to give users a clean slate
2. Pre-position the blocks into more appropriate regions

I don't want to do it in an install profile or a module, to keep things simple for end-users. Any ideas?

# Answer
You can't control this from the theme at the time it's being enabled.

Drupal will try to assign each block enabled for the default theme to the same region in your theme, if available. If there's no region with a coincident name, it will drop the block to the default region, that is the first region defined in your theme's .info.

So there're two things you can do:

* use more standard region names (sidebar\_first, sidebar\_second, footer)
* in theme's .info, declare in the first place the more suitable region for orphaned blocks
> 3 votes

# Answer
Features extra is a module that extends features, which allows you to export block settings, including region. You mentioned you don't want to accomplish this in a module which is essentially what Features generates, but hopefully this answer is helpful to others who run across your question searching.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Is there a way to add infinite number of Add More on webforms in Drupal 6
Simple question for all of you here dealing with Drupal 6.x...

With Drupal's Add More module, is there a way to configure my webform so that there is no limit on how many of a specific fields I can add more of?

For instance, I have a web form where users can request titles. I would like to enable the user to add as many titles as they would like. Is this doable or does there have to be a theoretical limit?

# Answer
> 0 votes
I believe the answer is no. At least I've never found a way to do it. I've always had to add 10+ fields and use webform\_conditional to hide them until they fill in one and then show the next, or provide a drop down so they can select how many fields to fill. Not ideal but I'm not sure any other way to do it.

---
Tags: 6, webforms
---


title: Dynamic locations in page content

text:
# Question
Title: Dynamic locations in page content
My company website has several physical locations / branches that need to be referenced all throughout the website on basic pages.

I would like to create one central table with one instance of each location so that when details change for that location I can make that one change and it will dynamically update all instances of that location across the site.

I could create a block for each location and reference that block where applicable, but the location content needs to go within the actual body of the pages and not in a block region. Is this possible?

# Answer
You could try something like the following:

* Custom content type 'location' with the fields you need for your locations
* Consider addressfield if these are address locations, or geofield if not
* if you need mapping, consider leaflet
* To use/display these locations elsewhere, you could add an entity reference field to other nodes or entities, and populate the field with links to the required location(s).
* if you need to embed locations (e.g. in the body of a node ) perhaps node embed or advanced entity token (I've not used either one)
* If you need to add additional view modes, you can use display suite or entity\_view\_mode

So, the general idea is that you define locations as needed using a custom content type. Then you attach these locations to other nodes/entities using fields or by embedding using a module that uses tokens or another special syntax.

With either approach, each location is stored just once, and the location is rendered on a page using a view mode that makes sense in that particular context.

To address your question about blocks specifically: you could indeed create blocks for company locations. To associate these blocks to pages/nodes, you could either embed the block in a node with something like insert block (https://drupal.org/project/insert\_block), or attach the block to a node using block reference (https://drupal.org/project/blockreference).
> 0 votes

# Answer
This answer worked perfectly! I was able to use addressField and Node Embed modules to accomplish exactly what I needed. The only issue I had was getting the node embed plugin to work with CKEditor toolbar, but manually adding the node ID token into the page content renders just fine. Thanks for the answers.
> 0 votes

---
Tags: nodes, 7, location, database
---


# Question
Title: Anonymouse users can't see Openlayers Data Overlay
I have a map view displaying the Openlayers Data Overlay. It's displaying a list of GPS tracks from a "Map Feature" content type I made.

Logged in with the Administrator, I can see all the tracks on the map fine. The preview for the Data Overlay shows all the data coming through great.

When I few the map as an Anonymous user, not logged in, none of the GPS tracks show up. The map displays on the page but none of the data from my Data Overlay.

I've looked all over the place trying to find content permissions that are wrong that are screwing things up but I can't find anything.

Why is the data on the map showing for the administrator and not Anonymous users?

# Answer
> 0 votes
The pages were cached for anonymous users. I went into Performance -\> Caching and cleared the caches and it worked. I had cleared my own cache but not on the site.

---
Tags: javascript
---


title: Cron Authentication Error

text:
# Question
Title: Cron Authentication Error
I can not seem to find out what cron.php is doing exactly that it needs to have an ssl connection with Google. I keep getting the following error:

> ERROR: Authentication with Google failed. Reason: BadAuthentication

I've Googled it and basically come up with nothing that seems to be similar to my issue. Is there some cron.php configuration parameters I should be setting somewhere?

Thanks in advance,

**SOLVED**

The "Search" module is the culprit. Here's how I found it. I hacked my cron.php file to add a couple functions it was calling so I could add logging information to help me track down the module. I copied both the module\_invoke\_all() and drupal\_cron\_run() functions into my cron.php, renaming them dev\_module\_invoke\_all() and dev\_drupal\_cron\_run(). The dev\_module\_invoke\_all() is the logging is added and is shown below. The change I made in my dev\_drupal\_cron\_run() was simply to change the module\_invoke\_all('cron') call to dev\_module\_invoke\_all('cron'), so I am not pasting it. Then the cron.php call to drupal\_cron\_run() is changed to dev\_drupal\_cron\_run() to use my functions. I could then look in the "Recent log entries" under the Report menu to see the last module cron\_hook() called. For me, it was the "Search" module. I disabled it, re-ran cron, and it successfully completed.

This is with a Drupal 6 installation.

```
function dev_module_invoke_all() {
  $args = func_get_args();
  $hook = $args[0];
  unset($args[0]);
  $return = array();
  foreach (module_implements($hook) as $module) {
    /*This logs a message out to the Recent Log Entries report.*/
    watchdog('cron', "Calling module: " . $module . " cron_hook: " . $module . '_' . $hook);
    $function = $module . '_' . $hook;
    $result = call_user_func_array($function, $args);
    if (isset($result) && is_array($result)) {
      $return = array_merge_recursive($return, $result);
    }
    else if (isset($result)) {
      $return[] = $result;
    }
  }
  return $return;
}

```

Even more info. I added watchdog logging to the search.module's search\_cron() to determine which module it was calling and tracked the issue to the node module. I then added watchdog logging to the node.module \_update\_index function to log out which node was being indexed. I then re-ran the cron and found the offending nodes. There turned out to be a couple of issues: A PHP page trying to do openssl authentication which was my original error. That page had been deprecated, but was still in the node list. I deleted the page.

Dan

# Answer
> 0 votes
Check if you have a module that uses any of the Google's API (translate, maps, youtube, calendar,...).

Seems that one of the modules implements hook\_cron() where is trying to access to one of the Google services through its API.

If that is the case at Google Cloud Platform you can configure a key to solve the issue.

If that is not the problem, try to check the logs to see if you can get more info about this error.

---
Tags: cron
---


# Question
Title: How to a use a template file to theme a form?
While nodes, comments, blocks and many other things in Drupal are themed using theme template files (like node.tpl.php), forms are a different story. There are no theme template files for forms. How can I get a particular form to use a custom theme template?

# Answer
It's completely reasonable to want to use a tpl file to display a form. You can use lots of extraneous CSS and `#prefix`/`#suffix` properties to achieve similar results, but by using tpl's you don't have to clutter up the separation of your logic and presentation layers and don't have to target ugly CSS selectors like `#user-login label`. Here's an example in Drupal 7...

**mytheme/template.php:**

```
function mytheme_theme($existing, $type, $theme, $path) {
    // Ex 1: the "story" node edit form.
    $items['story_node_form'] = array(
        'render element' => 'form',
        'template' => 'node-edit--story',
        'path' => drupal_get_path('theme', 'mytheme') . '/template/form',
    );

    // Ex 2: a custom form that comes from a custom module's "custom_donate_form()" function.
    $items['custom_donate_form'] = array(
        'render element' => 'form',
        'template' => 'donate',
        'path' => drupal_get_path('theme', 'mytheme') . '/template/form',
    );

    return $items;
}

```

**custom\_donate\_form():**

```
function custom_donate_form($form, &$form_state) {
    $form['first_name'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('First name')),
    );
    $form['last_name'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('Last name')),
    );
    $form['address'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('Address')),
    );
    $form['city'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('City')),
    );
    $form['state'] = array(
        '#type' => 'select',
        '#options' => array(
            'default' => 'State',
            '...' => '...',
        ),
    );
    $form['zip'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('Zip')),
    );
    $form['email'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('Email')),
    );
    $form['phone'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('Phone')),
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
    );

    return $form;
}

```

**mytheme/template/form/donate.tpl.php:**

```
<div class="row">
    <div class="small-12 medium-12 large-8 columns">

        <div class="row">
            <div class="small-12 columns">
                <h5>Contact Information</h5>
            </div>
        </div>

        <div class="row">
            <div class="small-12 large-6 medium-6 columns">
                <?php print render($form['first_name']); ?>
            </div>
            <div class="small-12 large-6 medium-6 columns">
                <?php print render($form['last_name']); ?>
            </div>
        </div>

        <div class="row">
            <div class="small-12 medium-6 large-6 columns">
                <?php print render($form['address']); ?>
            </div>

            <div class="small-12 medium-6 large-6 columns">
                <?php print render($form['city']); ?>
            </div>
        </div>

        <div class="row">
            <div class="small-12 medium-3 large-3 columns">
                <?php print render($form['state']); ?>
            </div>

            <div class="small-12 medium-3 large-3 columns">
                <?php print render($form['zip']); ?>
            </div>

            <div class="medium-6 large-6 columns"></div>
        </div>

        <div class="row">
            <div class="small-12 medium-6 large-6 columns">
                <?php print render($form['email']); ?>
            </div>

            <div class="small-12 medium-6 large-6 columns">
                <?php print render($form['phone']); ?>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="small-12 medium-12 large-8 large-offset-2 columns">
            <?php print render($form['submit']); ?>
        </div>
    </div>
</div>

<!-- Render any remaining elements, such as hidden inputs (token, form_id, etc). -->
<?php print drupal_render_children($form); ?>

```

This is using Foundation, which gives us a form like this:
> 75 votes

# Answer
You have to implement hook\_form\_alter() in a module or template.php and set the form's **#theme** property:

```
/**
 * Implements hook_form_alter().
 */
function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_login') {
    $form['#theme'] = array('overwrite_user_login');
  }
}

```

Then implement new theme:

```
/**
 * Implements hook_theme().
 */
function hook_theme($existing, $type, $theme, $path){
  return array(
    'overwrite_user_login' => array(
      'render element' => 'form',
      'template' => 'form--user_login',
      'path' => $path . '/templates',
    ),
  );
}

```

And then add form--user\_login.tpl.php template with follow code to render form:

```
<?php print drupal_render_children($form) ?>

```
> 19 votes

# Answer
Even though you may be able to use kiamlaluno's solution I personally wouldn't.

What is your reason for needing a template file for a form? If it's because you want slightly different markup for an existing form? If so then you can use `hook_form_alter()` to modify the form before it is rendered. Using the Form API you you can modify all the form fields inject html elements etc.

Here is an example of `hook_form_alter()` that I've created that modifies the standard drupal login form block:

```
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {

  switch ($form_id) {
    case 'user_login_block':

      // Form modification code goes here.
            $form['divstart'] = array(
                '#value' => '<div style="background-color: red;">',
                '#weight' => -1,
            );

            $form['instruct'] = array(
                '#value' => '<p>Enter your username and password to login</p>',
                '#weight' => 0,
            );

            $form['divend'] = array(
                '#value' => '</div>',
                '#weight' => 4,
            );
      break;
  }
}

```

The above example wraps the entire form within a DIV which has an inline style to turn the background colour to red. It also adds a paragraph of help text to the beginning of the form.

This is what my user login form looks like now once the above code is loaded:

See the Form API reference for more information: Form API Reference
> 13 votes

# Answer
I have actually never needed to use a template file for a form.
As far as I can see, Drupal core code uses theme functions, when a form, or part of a form needs to be rendered in a particular way; a theme function that calls drupal\_render() is normally enough for any purposes.

To reply to the question, creating a template file for a form is not different from creating a template file that is not for a form.

Define a theme function, using as theme function the name of the form builder callback. The code should be similar to the following:

```
/**
 * Implementation of hook_theme().
 */

 function mymodule_theme() {
   return array(
     'mymodule_form' => array(
       'template' => 'mymodule-form',
       'file' => 'mymodule.admin.inc',
       'arguments' => array('form' => NULL),
     ),
   );
 }

```

If the form contains the value `$form['field_1']`, its value will be available in the template file as `$field_1`. The template file will be also able to use any values passed from `template_preprocess_mymodule_form()`.
> 12 votes

# Answer
I would always style by adding to my CSS file using selectors to identify the element to be styled as follows for the core login form

```
#user-login
{
   border:1px solid #888;
   padding-left:10px;
   padding-right:10px;
   background-image: url(http://www.zaretto.com/images/zlogo_s.png);
   background-repeat:no-repeat;
   background-position:right;
}

#user-login label
{
    display: inline-block;
}

```

The above I simply add to `sites/all/themes/theme-name/css/theme-name.css`

If what you need to style doesn't have an ID or a sufficiently accurate selector then it is necessary to use the `hook` approach to modify the HTML too add identifiers.

IMO using inline style on elements is a **very bad practice** that should be deprecated and replaced by use of `class` and `id`
> 1 votes

# Answer
To theme a form, you can use a custom css, as explained in **Themeing Drupal 7 Forms (Including CSS and JS)**.

Basically you need to perform these steps:

1. Register a path to the form using hook\_menu()
2. Define the form
3. Register a theme function with hook\_theme()
4. Write the theme function
5. Create the CSS and JavaScript files
> 0 votes

# Answer
I'm pretty sure you're able to use a template for forms, but you have to use hook\_theme to register the template in the first place. I had a situation where the form *really* needed to be table based rather than div based and the simple #prefix and #suffix changes didn't really cut it. If interested I could probably try and dig up an example.
> -2 votes

---
Tags: forms, theming
---


# Question
Title: Views of products just showing the first time a taxonomy term is used?
OK, so I have my product in Drupal Commerce basically sorted by two major taxonomies - Sport and Product Category.

What I want to do is set up a view that prints out the available product categories for a particular sport (i.e. if a product has a particular sport associated with it, then sort through that list and find what product categories are available for that sport).

I have the view somewhat figured out - but it keeps giving me repeats of the product category, where I only want a particular product category name to show up once.

For instance, if I search for the sport 'Football' - I get a list that looks like this: \- Balls & Tees \- Shirts \- Balls & Tees \- Balls & Tees \- Pads \- Shirts \- Shoes etc. . .

What I want is for those duplicates to be removed (so Balls & Tees only show up once).

In my current view, I have it set up to return fields of content - with the Taxonomy name of Product Category as my only field.

I have a conditional filter of the parameter set.

I do have a relationship set of Content: Taxonomy terms on node.

I tried using aggregation DISTINCT option, but that doesn't seem to help.

I have looked through this topic -https://drupal.org/node/1200536#comment-4957410 \- but I am not sure if its related or not.

Any ideas?

# Answer
Did you build your view based on nodes or on taxonomy terms? (https://drupal.org/node/770782)

I think a taxonomy terms based view is the preferred way. Maybe you already did this.

> 1) add a new view of view type "term" (not the default "node" option!) by ticking the correct option after clicking 'add view'
>
> 2) add the Taxonomy Term to the list of Fields
>
> 3) Add a relationship "Taxonomy: Node" and make it obligatory
>
> 4) In the basic settings enable the 'distinct' option.
>
> 5) Add some filters to narrow the results as needed.

When setting filters you can try to use a contextual filter Term-ID with a default value set from the node page, only from the term list sports. You will also need to set a normal filter with term list product category.
> 0 votes

---
Tags: views
---


title: Create theme file for content type?

text:
# Question
Title: Create theme file for content type?
In Drupal 6, if you had a content type with the system name "stock-photo", you could override it using:

```
node-stock-photo.tpl.php

```

How do you do this in Drupal 7?

# Answer
> 2 votes
You can add custom `node.tpl.php` for any kind of content type like

```
node--[node-type].tpl.php

```

I would suggest you to use hook suggestion at `template.php` for this :

```
function MYTHEME_preprocess_page(&$variables, $hook) {  // Add theme suggestion for all content types
    if (isset($variables['node'])) {
        if ($variables['node']->type != '') {
            $variables['theme_hook_suggestions'][] = 'page__node__' . $variables['node']->type;
        }
    }
}

```

So that I can have `node--wine.tpl.php` for content type **wine**.

Note -- Don't forget to clear your cache after this :)

# Answer
> 5 votes
I think `MYTHEME_preprocess_page()` function doesn't need for it.

The `node--[node-type].tpl.php` is only enough for it.

---
Tags: 7, theming
---


title: How to insert ® value in database

text:
# Question
Title: How to insert ® value in database
I am inserting users from drupal6 to drupal7 using a custom script. I am using db\_insert function. In one of the D6 entry I am getting ® mark in a field and because of this that particular value become blank in D7 database. D6: imatter® -\> D7:

Anyone has any idea about how to insert this value in database?

Collation is same in both database: utf8\_general\_ci And in phpmyadmin its look like same as above, means no html code for ®

# Answer
> 0 votes
In the case that your insertion script is not capable of handling UTF-8 encoding (it sounds like this is the case), you can get around this by inserting this character as 7-bit HTML entities (i.e. `®` or `®`) *provided* the field where it appears is going to be rendered as HTML (and not as plain text). Just do a search and replace and replace all occurences of ® with `®` in the source text file.

If this workaround doesn't work (because the field is supposed to be plain text, or for some other reason), you must do two things:

1. Make sure your file containing these characters is UTF-8 (*not* ISO-8859-1 or some other encoding incompatible with UTF-8).
2. Make sure your insertion script is capable of handling UTF-8 (`db_insert` is, but I don't know what other components you use).

# Answer
> -1 votes
Try `utf8_encode` before store you variable

```
$username=$olduser.'®';
$newusername =  utf8_encode($username);

```

or Drupali method

```
$username=$olduser.'®';
$newusername =   drupal_convert_to_utf8($username,'utf-8');

```

---
Tags: database
---


# Question
Title: How do I make a custom block that has an image background with hotspots?
I am working on making a custom module with a block that contains a floor plan. It will be an office, when you hover over employees desks it will have a bubble appear showing that employees project status and other information. All instructions I can find for setting the image in the block uses css. Is this how I need to do it? Will i be able to set regions for mouse over this way?

# Answer
You can try the module jQuery Map Hilight which uses jQuery maphilight plugin (visit the link to view demos).

Download from David Lynch blog / GitHub.
> 2 votes

# Answer
In Drupal 7 you can use

* **qtip** module.
* If you don't want to use the module you can use jQuery qtip plugins.
* Its better to make an Ajax request to get the user details, if you are trying to load more user details.
> 0 votes

---
Tags: blocks, media
---


# Question
Title: Search text box for Search API + Database + Search Views + Facets API + Facets Bonus
I have check boxes and radio buttons (after a few patches) in my facets, using Search views. I want to be able to present the user with a text search box so they can search for a title and another text field. I can't seem to find this, however.

Do I need to create a new facet, or am I just missing this functionality?

# Answer
> 5 votes
You should enable title and other fields for search in your search index. Select type as "Fulltext". Reindex content. After that add new exposed filter in your search view. It's fulltext search filter. In settings of this filter you can select your fields from index.

---
Tags: 7, views, search
---


# Question
Title: how to put "add friend" link with flag friend with views
Flag Friend Add Friend Link with views. Flag friends shows a link to add friend in my account page but i want to display this link on in a field for a view.

# Answer
> 2 votes
In `views` you have to go to `advanced setting` and in `relationship` you can add your flag.

After that you will be able to add your field.

# Answer
> 1 votes
If I understood you correctly you want to add *flag link* to the view (as a field).

Here is a video demonstrating it. Quoting from this:

* Install the Views PHP module and enable it. This will allow you to embed php into a view cell.
* Add a new nid/node id field to your View. Make sure to check the “Exclude from display” checkbox.
* Rearrange your fields so that your hidden nid field is at the top of all fields. This is important. It needs to be “available” as an element to the custom php field we are about to add, and if it’s after, the custom php field won’t see it.
* Add a new Global: PHP field. add the following code to the "Output Code" section of the field (in php): `<?php print flag_create_link("the_machine_name_of_your_flag", $row->nid); ?>`
* Click the apply button

---
Tags: views, flags
---


title: Multiple Ajax submit, same Form ID

text:
# Question
Title: Multiple Ajax submit, same Form ID
I have a page with a table of nodes each one with it's own submit button. When pressed the button should call a custom ajax function which creates a cookie with the corresponding orm ID as its value.

My code:

```
function custom_cart_form_alter(&$form,&$form_state,$form_id){
    if ((stristr($form['#form_id'], 'uc_product_add_to_cart_form')) != FALSE){
        $form['#submit'][] = 'set_custom_cookie';
    }

    return $form;
}

function set_custom_cookie($form, &$form_state){
    user_cookie_save(array($form['#form_id'] => TRUE));
}

```

However, when the set\_custom\_cookie() function is called it receives the last value of $form\['#form\_id'\] and not the ID of the corresponding form.

To clear things up: if I add the following at the end of hook\_form\_alter() :

```
function custom_cart_form_alter(&$form,&$form_state,$form_id){
    if ((stristr($form['#form_id'], 'uc_product_add_to_cart_form')) != FALSE){
        $form['#submit'][] = 'set_custom_cookie';
    }

    $form['#form_id'] = "test123";  //Added this line to demonstrate the issue
    return $form;
}

```

then function set\_custom\_cookie() will receive "test123" on call as the value of $form\['#form\_id'\].

How can I make set\_custom\_cookie() receive the corresponding form ID?

I'm using Drupal 7.

# Answer
You should be able to get the form id from the `$form_state` variable as `$form_state['build_info']['form_id']` inside your submit handler.
> 1 votes

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


# Question
Title: Adding website logo as the first top level menu item in tb megamenu
I am usting tb megamenu module to get a main menu on my site. Is there a way to add the website's logo as a top level menu item (NOT SUBMENU ITEM)

# Answer
> 1 votes
You are looking for Menu Icons module.

> This module allows you to upload an image in the menu-item's configuration form. After uploading the image, the icon data will be added to the menu link's options array.
>
> When a menu link is goes through the theme layer, it will receive an extra class which by default is used to attach the images as a background image to the corresponding menu item. These class names are also compatible with Nice Menu's.

---
Tags: navigation
---


title: Hide row in view if any field is empty

text:
# Question
Title: Hide row in view if any field is empty
I have a **Drupal 7 view** that uses **fields** as display type.

There are three fields, and I don't want to show the row if any one field is empty.

Currently, I am adding a filter for each of the three fields to achieve this. meaning if I have 20 fields, I would have to go for 20 filters.

Is there an easier way of doing this?

**P.S.** I can do this by overriding the row style output template file, and then add some custom php code. But I want to know is there an easier way using the views administration interface.

# Answer
> 2 votes
You can add filter criteria corresponding to the field on which you want to hide
the row .
Suppose you want to hide the row if content: body is empty then you can add filter criteria as Content:Body **not equal to** "" (where value field should be left empty).
This will automatically hide the row if the specific field is empty .

---
Tags: 7, views
---


title: How to find the ID of a webform?

text:
# Question
Title: How to find the ID of a webform?
I am working with webform module , I have added two different forms in my website.
I have customized the forms according to my convenience, as I have changed the css. These changes are reflected in the two forms.
Now i need to get the id of these forms so i can further customize one of them.
I have added this css code for form

```
.form-text,
.form-textarea {
   width: 100%;
}

```

# Answer
> 2 votes
Try the Get Form ID module:

> By **hovering over any form** you will see a contextual link available. By expanding the link you will see **the form ID**. Click on the link and you will see a modal window with copyable form id and hook\_form\_FORM\_ID\_alter() hook suggestion.

Step 1: hover over the form.

Step 2: expanding the contextual link.

Step 3: Click on the link and a new window will open with copyable form id and hook\_form\_FORM\_ID\_alter() hook suggestion

# Answer
> 2 votes
You can get the form id from the form\_id hidden field of the webform. Go to source view of the form from your browser and search for form\_id.

# Answer
> 1 votes
Just another method. If you use Devel module, you can add this code snippet to your custom module to view the form id.

```
function [module_name]_form_alter(&$form, &$form_state, $form_id){
  dpm($form_id);
}

```

# Answer
> 1 votes
You can use **firebug**

* Just right click the FORM using Chrome Browser and click **Inspect Element**
* Select form tag, you can see the FORM ID inside ID attribute

# Answer
> 0 votes
Webform forms usually have the id webform\_client\_form\_nid. Where nid is your node id.

---
Tags: webforms, theming
---


# Question
Title: Remove default › between breadcrumbs in panels breadcrumbs
Is it possible to remove the › between the breadcrumbs in the panels breadcrumbs module? I tried modifying the part of the .module file shown below (which I know is bad practice, but I just wanted to try it out) but that did not work.

```
// Finally, render the breadcrumb
foreach ($breadcrumbs_info as $crumb) {
if (isset($crumb['href']) && $crumb['href'] == '<none>') {
  $crumb['localized_options'] += array('attributes' => array(), 'html' => TRUE);
  $breadcrumbs[] = '<span ' . drupal_attributes($crumb['localized_options']['attributes']) . '>' . ($crumb['localized_options']['html'] ? $crumb['title'] : check_plain($crumb['title'])) . '</span>';
}
else {
  $breadcrumbs[] = l($crumb['title'], $crumb['href'], $crumb['localized_options']);
}

```

}

# Answer
If you have your own custom theme (or a sub-theme you can edit), you can override theme\_breadcrumb(). Actually I'm not sure this is completely supported by panels\_breadcrumbs but I assume it is.

```
THEMENAME_breadcrumb() {
  $breadcrumb = $variables['breadcrumb'];

  if (!empty($breadcrumb)) {
    // Provide a navigational heading to give context for breadcrumb links to
    // screen-reader users. Make the heading invisible with .element-invisible.
    $output = '<h2 class="element-invisible">' . t('You are here') . '</h2>';

    $output .= '<div class="breadcrumb">' . implode(' CUSTOM SEPARATOR ', $breadcrumb) . '</div>';
    return $output;
  }
}

```

EDIT: Alternatively, there are other breadcrumb-customizing modules that allow to specify a custom separator between the breadcrumb items.
> 1 votes

---
Tags: panels, breadcrumbs
---


# Question
Title: What format should date (ISO date) be when using Migrate Module?
I have a large amount of date rows that I'm migrating over from a legacy application to Drupal 7. My destination field is Date (ISO Format) with year, month and day selected. What format should this be in when I'm migrating it across?

I can see that it's stored as `2010-01-01T00:00:00` in the database so I'm using prepareRow() to manipulate the data like:

```
<?php
public function prepareRow($row) {
  // DOB not migrated correctly - old = serialised array
  //    watchdog('temp', print_r($row, TRUE));
  if ($row->profile_dob) {
    $dobarray = unserialize($row->profile_dob);
    watchdog('temp', print_r($dobarray, true));
    $row->profile_dob = date('Y-m-d\T00:00:00', mktime(0, 0, 0, $dobarray['month'], $dobarray['day'], $dobarray['year']));
    watchdog('temp', print_r($row->profile_dob, true));
  }
}
?>

```

This returns the expected format for the date however the data is not populated in the database. I've tried using 'c' as the date format as well with no luck.

# Answer
For date migration, you should use Migrate Extras module. Then you will be able to remove your code from prepareRow(), and just map the date field.

Migrate Extras will take care of reading you date and parse it.

In my migration I just had to set the timezone when I was importing birth dates.

Here's my mapping, as an example:

```
$this->addFieldMapping('field_birth_date', 'birthdate')->arguments(MigrateDateFieldHandler::arguments('Europe/Rome', 'Europe/Rome'));

```
> 1 votes

# Answer
I had similar issue and the issue got fixed when I updated the date module to the latest version which is "7.x-2.7". This doesn't have a separate date migration module and is merged with the date module.

I don't think Migrate Extras module is required for date migration. The link to Migrate Extras specifies that the date migration is built into the Date module.
> 0 votes

---
Tags: 7, datetime, migrations
---


# Question
Title: Form with managed_file value as link in email
Like the title says I want to make managed\_file value to be a link on form submissions in the email.

Webform has this option. When a user uploads file, on the email form submission there's a link with the path of the uploaded file. I want to achieve this with custom module. This is my code:

```
<?php

function mymodule_page($form, &$form_state) {
    $form['description'] = array(
        '#type' => 'markup',
        '#markup' => t('Add description'),
    );
    $form['file'] = array(
        '#type' => 'managed_file',
        '#title' => t('Upload image'),
        '#upload_location' => 'public://files',

    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
        '#submit' => array('mymodule_page_submit'),
    );

    return $form;
}

function mymodule_page_submit($form, &$form_state) {
    $file = file_load($form_state['values']['file']);
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);

    //dpm($file);

    $description = $form_state['values']['description'];

    $params = array('file' => $file->uri, 'description' => $description );
    drupal_mail('mymodule', 'mymodule_news_mail', 'myemail', language_default(), $params);
    drupal_set_message(t('Message sent!'));
}

/*
** Implements hook_mail().
*/
function mymodule_mail($key, &$message, $params) {
    switch($key) {
        case 'mymodule_news_mail':
            $message['subject'] = t('Hello');
            $message['body'][] = t('This is a test');
            $message['body'][] = t('Image upload: @file', array('@file' => $params['file']));
            $message['body'][] = t('Description: @description', array('@description' => $params['description']));
        break;
    }
}

```

As you can see it from my code I'm saving the file properly into the server. After that with dpm($file-\>uri) I can see the string public://files/file\_name.

How can I display the link from the path of the uploaded file on the email, so will be able to click on the absolute path?

# Answer
Thanks to Jaypan from drupal.org, I've got the answer:

```
<?php
file_create_url($file->uri);
?>

```

Simply with adding this code and make another variable that will use the code, I've got the right result.
> 0 votes

---
Tags: forms, hooks, files, emails
---


# Question
Title: Feeds Importer Xpath import where guid is at the top of the context
Trying to import from an XML feed using Feeds Importer XPath XML. I have had an import working from this same feed before but with uniqueness based on a title field which is no longer apropriate.

I'm trying to alter the import so that I now use a guid. The problem is that the ID I need to use is only located within the top level element where the context starts.

XML looks like:

```
<vacancies>
  <vacancy id="111427">
    <uri>https://data.ox.ac.uk/id/vacancy/111427</uri>
    <url>https://data.ox.ac.uk/doc/vacancy/111427</url>
    <webpage>https://www.recruit.ox.ac.uk/pls/hrisliverecruit...</webpage>
    <label>Postdoctoral Scientist - Protein Biochemistry</label>
    <opens>2014-01-16T09:08:14+00:00</opens>
    <closes>2014-02-17T12:00:00+00:00</closes>
    ...

```

My context is /vacancies/vacancy and I am mapping my guid to @id which I think is the correct syntax.

The import doesn't work correctly, I get no nodes and no errors. What am I doing wrong (if anything)? There is nothing I can do about the XML schema incidentally, if that is where the problem is.

# Answer
I just did a quick test of this, with your sample data, and it works correctly.

In the debug options you can enable error reporting, as well as, show the outputs of various queries.
> 0 votes

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


# Question
Title: How to copy blocks placement and settings between themes?
How can I copy blocks placement and settings between themes?

I've found this module: https://drupal.org/project/blockregion and this code to do it in the database. But both are for D6. How can I do this for D7

First, clear the existing block information for the new theme:

```
DELETE FROM blocks WHERE theme = 'NEW_THEME_NAME'

```

Now, copy all the block information from the old theme:

```
INSERT INTO blocks (module, delta, theme, status, weight, region, custom, throttle, visibility, pages, title, cache) (SELECT module, delta, 'NEW_THEME_NAME', status, weight, region, custom, throttle, visibility, pages, title, cache FROM blocks WHERE theme = 'OLD_THEME_NAME')

```

Also found this, but for D5: http://pierrerebours.com/blog/duplicating-block-settings-across-themes-drupal

# Answer
> 2 votes
I changed a little bit the code and it worked:

Before running this code you should be sure that both themes have the same regions and, if needed you will have to create the missing regionsin the new theme.

```
DELETE FROM block WHERE theme = 'NEW-THEME'

INSERT INTO block (module, delta, theme, status, weight, region, custom, visibility, pages, title, cache, i18n_mode) (SELECT module, delta, 'NEW-THEME', status, weight, region, custom, visibility, pages, title, cache, i18n_mode FROM block WHERE theme = 'OLD-THEME')

```

---
Tags: blocks, theming
---


# Question
Title: Hyphenated nodeName or DTD nested in XML causes Feeds XPath Parser failure
I am using Feeds and Feeds XPath Parser.

I have an XML source like this.

```
<xml>
  <records>
    <record>
      <EAC-CPF xmlns:eac="http://jefferson.village.virginia.edu/eac" xmlns:edit="http://nla.gov.au/nla.party" xml:id="_cb2bf3c2-b54c-42c3-a890-048c06549e45#10" xsi:schemaLocation="urn:isbn:1-931666-33-4 http://eac.staatsbibliothek-berlin.de/schema/cpf.xsd">
        <cpfDescription>
          <identity>...</identity>
        </cpfDescription>
      </EAC-CPF>
    </record>
  </records>
</xml>

```

Which I am trying to import with field settings like

```
EAC-CPF/cpfDescription/identity/...

```

With debugging turned on I can see that fields *outside* of the EAC-CPF node are correctly found whereas those within are not. I've tried various escaping of EAC-CPF but I'm wondering if its a limitation of XPath in PHP or the Parser module. Or is it the nested namespace and schema?

# Answer
There are 2 errors regarding the xml:id and xsi:schemaLocation, but they are not fatal. I'm guessing the xsi namespace is defined previously.

There's nothing wrong with nested namespaces.

Is there a default namespace declare somewhere passed the root? That could be because of https://drupal.org/node/1220834.

The hyphen in EAC-CPF is not causing the problems.

Remember that if elements have a namepsace, the namespace must be present in the XPath query.
> 0 votes

---
Tags: feeds, 8
---


# Question
Title: How can I display the Google rich snippets when a view is on "Show: fields" and the panel enabled?
I am building a site using Drupal 7 and the schema.org module and the microdata module.

The site is live on production server (and works good).

When checking a url from my site site on the google rich snippets tool, I can't see all the fields I want to appear in the snippets.

When using panels, views, microdata module and schema.org module - the snippets does not work. When I deactivated the microdata module, and disabled the specific panel on the page the snippets work!
So, I decided to disabled the microdata module, and work only with the schema.org module.

With the the schema.org modules:

* When views is on "show: content" and the panel Enabled - snippets work!
* When views is on "show: fields" and the panel Disabled - snippets work!
* When views is on "show: fields" and the panel Enabled - snippets do NOT work!

Can I use the *Rewrite* option on a view to add some code to fields and make it work? How can I display the Google rich snippets when a view is on *Show: fields* and the panel enabled?

# Answer
I see that you are using views fields mode for populating the values. That might be the issue.

In your overall HTML check that an entry for `itemtype="http://schema.org/Recipe">` is present. In your current html I feel you wouldn't have this. If that is the case then change the mode in your views to `node` from `fields`.

Then recheck your HTML and you should find the entry. If you do find the entry then the reason is that your fields(in old view mode) are not enclosed within a `recipe` tag.

In the above case you can install schema tokens module and then in your fields view, hide all the fields and then add a Global text field within which you can use these tokens to get the desired output.
> 0 votes

---
Tags: views, panels, 7
---


title: How do I get template updates to show

text:
# Question
Title: How do I get template updates to show
I'm sure this is a very simple fix, but I'm new to Drupal and would be very appreciative if someone could help. I have a theme that I am using on a Drupal site. I make some changes to the underlying text in the themes PhP files (e.g. "Page not found" -\> "Page is not found!"). I then reload the page and I do not see the changes on the site. I have tried clearing Drupal's cache and then reloading, but this also doesn't seem to help. After I make changes to a theme, how do I get them to show up on the site?

# Answer
The symptoms you describe is usually due to some caching happening. Make sure you've turned off *all* caching in Drupal (sometimes, just clearing the cache isn't enough). Also, make sure that you clear your *browser's* cache (SHIFT+reload).
> 0 votes

---
Tags: theming
---


# Question
Title: local copy of my drupal site doesn't seem to link
I isntalled a local LAMP system and basically copied my site into `/var/www/` for some local "experiments" (without messing around with the live site). I've mirrored the db and everything. Now when I go to `http://127.0.0.1/` my home page is loaded well but all the links (e.g. `http://127.0.0.1/content/lodge`) won't load, I just get **404 Not Found**. I assume I'm missing some kind of php or apache setting.

**edit1**

I did

```
sudo a2enmod rewrite
sudo /etc/init.d/apache2 restart

```

but this didn't seem to have made a change at all. Now within `/etc/apache2/sites-available/` I have two files `000-default.conf, default-ssl.conf`.
`000-default.conf` contains:

```
ServerAdmin webmaster@localhost
DocumentRoot /var/www
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined

```

and `default-ssl.conf` contains

```
ServerAdmin webmaster@localhost
DocumentRoot /var/www
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
SSLEngine on
SSLCertificateFile      /etc/ssl/certs/ssl-cert-snakeoil.pem
SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key
<FilesMatch "\.(cgi|shtml|phtml|php)$">
SSLOptions +StdEnvVars
</FilesMatch>
<Directory /usr/lib/cgi-bin>
SSLOptions +StdEnvVars
</Directory>
BrowserMatch "MSIE [2-6]" \
nokeepalive ssl-unclean-shutdown \
downgrade-1.0 force-response-1.0
BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown

```

and I'm not exactly sre where to add `AllowOverride All`, can you be a little more specific?

Oh and `.htaccess` is in `/var/www/` too

**edit 2**

okay, now what I did, I installed a fresh copy of drupal in `http://127.0.0.1/alternatives/Quaaout/` and if I use the original site folder with a new db, urls like `http://127.0.0.1/alternatives/Quaaout/?q=user` work just fine! But if I use my `site/` directory from the live site, this url automatically leads me to a `404` at page `http://127.0.0.1/alternatives/Quaaout/user` and the difference makes which `database` I have setup in my `settings.php` \- with the new db from the fresh copy, `?q=user` works fine, with the live copy it doesn't. So I thought it may be the `url redirections` I have setup in table `redirect` but I cleared it and it still didn't work. So it's not the redirections, what else would be causing this?

# Answer
here's a copy of a working vhost file (000-default.conf):

```
<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www
    <Directory />
            Options FollowSymLinks
            AllowOverride All
    </Directory>
    <Directory /var/www>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride All
            Order allow,deny
            allow from all
    </Directory>

    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
    <Directory "/usr/lib/cgi-bin">
            AllowOverride All
            Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
            Order allow,deny
            Allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog ${APACHE_LOG_DIR}/access.log combined

Alias /doc/ "/usr/share/doc/"
<Directory "/usr/share/doc/">
    Options Indexes MultiViews FollowSymLinks
    AllowOverride None
    Order deny,allow
    Deny from all
    Allow from 127.0.0.0/255.0.0.0 ::1/128
</Directory>

```
> 1 votes

# Answer
Make sure apache has mod\_rewrite enabled, and that the drupal .htaccess file is there in your drupal root. If you're on debian/ubuntu, you should be able to do:

```
sudo a2enmod rewrite
sudo /etc/init.d/apache2 restart

```
> 2 votes

---
Tags: 7
---


# Question
Title: How to add custom user fields to their comments?
My users have the following fields: 'Avatar' (image) and 'Year' (number). When a user leaves a comment, I'd like to display these fields, the username and the user's current userpoints next to each other on top of the comment. The end result should look something like this:

The fields shouldn't be updated: when they change in the future, they should maintain the value they had at the moment the comment was posted.

How can I achieve this?

# Answer
> 0 votes
I haven't tried this out for sure, so this is kinda just spit balling, but the way I would do this would be to write a small little custom module. So, example:

You could have the date/avatar field stored as a field in the user table. Then in the comments, add both a date/avatar flied to the comment (under /admin/structure/types/manage/\[node type\]/comment/fields). So now you would have to two places to save the info.

To hook them up, I would write a custom module that uses hook\_comment\_presave to intercept the date and avatar field before the comment is saved, load the user info from the commenting user, and then replace the comment date/avatar from the user date/avatar. That way, the information that was with the user at the point of commenting will be forever with the comment.

You will of course need to theme it, and you will need to hid those comment fields from the user in the comment form. Your also gonna want to make sure the avatar is persistent, but I think this should be a workable solution. At least, that's where I would start.

---
Tags: 7, entities, comments
---


# Question
Title: How to desactivate jquery_update logic for the homepage
The objective of this is to remove all legacy javascript files from the homepage except for the new javascript files I specifically want to load.

Here is how I remove all the Javascript files I don't need:

```
function phptemplate_preprocess_page(&$vars) {
    $template_files = $vars['template_files'];
    $scripts = drupal_add_js();

    if (in_array('page-front', $template_files === true) {
        // Here I unset all the javascripts that I don't want to be loaded in the homepage
        unset($scripts['theme']['themes/"theme_name"/js/jquery.jcarousel.min.js']);
        ...
        // Once cleaned up all unncessary javascripts, I load them into $var['scripts']
        $var['scripts'] = drupal_get_js('header', $scripts);
    }
}

```

This works fine, however it only works when the jQuery Update module is desactivated. If the jQuery Update module is active, somehow it overseeds this logic and all the javascript files are loaded anyways.

I don't want to use the jQuery Update logic in the homepage, but I'm affraid that if I disable this module, I can provoke negative side effects in the other pages of the website.

Conclusion: I want to desactivate jQuery Update logic for handling javascript files but only for the homepage.

Any other alternative solution / conclusion to this problem is also welcome.

# Answer
The reason why your **theme\_preprocess\_page** function isn't working, is because the jQuery update module uses a clever implementation of **hook\_theme\_registry\_alter** to ensure it's implementation of **hook\_preprocess\_page** is called last.

What I recommend you do is create a new module and implement your own **hook\_theme\_registry\_alter** and **hook\_preprocess\_page** functions. See a simple example below which has taken some code snippets from the jquery update module:

```
function mymodule_theme_registry_alter(&$theme_registry) {

  if (isset($theme_registry['page'])) {
    if (count($theme_registry['page']['preprocess functions']) > 0) {
      if ($key = array_search('mymodule_preprocess_page', $theme_registry['page']['preprocess functions'])) {
        unset($theme_registry['page']['preprocess functions'][$key]);
      }
    }

    // Now tack it on at the end so it runs after everything else.
    $theme_registry['page']['preprocess functions'][] = 'mymodule_preprocess_page';
  }
}

```

This hook implementation tells Drupal to invoke our custom **hook\_preprocess\_page** function ***after*** all other modules have run their hooks.

Then we need to define our own custom implementation of **hook\_preprocess\_page** which will alter the scripts included on the front page:

```
function mymodule_preprocess_page(&$vars) {

  // Only do this for pages that have JavaScript on them.
  if (!empty($vars['scripts'])) {

    $template_files = $vars['template_files'];
    $scripts = drupal_add_js();

    if (in_array('page-front', $template_files === TRUE)) {
      // Here I unset all the javascripts that I don't want to be loaded in the homepage
      unset($scripts['theme']['themes/"theme_name"/js/jquery.jcarousel.min.js']);
      // Once cleaned up all unncessary javascripts, I load them into $var['scripts']
      $vars['scripts'] = drupal_get_js('header', $scripts);
    }
  }
}

```

Using this approach in your own custom module will make sure that any alterations you want to make to your javascript includes will happen very last.

Good luck! :)
> 1 votes

---
Tags: 6, performance, theming, javascript
---


title: When to create a new content type?

text:
# Question
Title: When to create a new content type?
This question always comes up when I need to design a structure for data. When should I create distinct content types and when should I differentiate between nodes based on custom fields.

For example, say I have a gallery of people and a gallery of places. they differ only by one field that i use in the people gallery and not in the places gallery. in code i can easily know when it's people or places based on this field.

this is just one example from the top of my head. i'm asking for general guidelines, and not a solution to this specific problem.

these are the points i've come up with to help decide between different content types or different fields:

1. what are the chances one node will need to change type (people gallery suddenly becoming places gallery)?
2. how much do the fields differ?
3. how much you will need to create view with both types or with a single one?

any more thoughts?

# Answer
It's a really open question, but I'll try to help you a bit.

Basic example is : I have to create "vehicules", some "cars" and some "motos". Should I create one content type (CT) with one field "type" (with "cars" and "motos" as available values") or 2 CTs "cars" and "motos".

Here is the points I look into before choosing:

* fields: if the fields are the same between content types, just create one CT, if they're really different, then create 2 CTs.
* display: if the display is the same, then chose 1 CT, if not, create 2 CTs.
* views: will I make list of both CTs, or will they always be separated?
* cross content: is it possible that a node is part of both CTs? For example, is a "can-am spyder" a moto, a car or both of them? If you have cross content, then I would suggest to have only one CT, which a multiple select for the "Type" attribute. So people searching for cars or for motos will find the spyder anyway.
* how "smart"/involved are you Back-Office users? Usually when you choose to keep only one content type, you end up having a lot of extra fields to configure the theming, the little differences between your different types, etc. So the edit form can be really long and confusing. If you're the one configuring everything, that's fine. But if you need to explain the form to a lot of editors/contributors, this can be painful.

After counting the pro and cons, you can make your decision. Usually, I give 2 points for "fields" and "display", one point for "views", "cross content" and BO users... Make the sum and decide :)
> 1 votes

# Answer
I would always create a new content type. Here are some of my reasons:

1. You can easily make a View, or Page override from a Content Type.
2. You can administer different Content Types separately, and, thereby...
3. Control user access with more granularity.
4. Control visibility of secondary content with more granularity. Advertising, etc.
5. Many components add features based on Content Type. Taxonomy, for example.

I could probably go on, but granularity, while it does add to the administrative overhead sometimes, pays dividends in the long run.
> 0 votes

---
Tags: 7
---


# Question
Title: Create custom template for a specific node without node ID?
I want to create a custom tpl for a specific node. However I dont want to use node id in the file name (page--node--11.tpl.php). Is there any way to do it?

# Answer
> 1 votes
Sure, you can use hook\_preprocess\_node() or hook\_preprocess\_page() to suggest any template you want for a node or a page. I am suggesting both because of the name you gave in your question `page--node--11.tpl.php` is really a page template not a node template.

Regardless, you could do this:

```
function YOURTHEME_OR_MODULE_preprocess_node(&$variables) {

  if ( /* whatever logic */ ) {

    $variables['theme_hook_suggestions'][] = 'node_whatever_you_want_to_call_it';

  }

}

```

or

```
function YOURTHEME_OR_MODULE_preprocess_page(&$variables) {

  if ( /* whatever logic */ ) {

    $variables['theme_hook_suggestions'][] = 'page_whatever_you_want_to_call_it';

  }

}

```

and now when that node is rendered, it will use `node-whatever-you-want-to-call-it.tpl.php` or if the page, `page-whatever-you-want-to-call-it.tpl.php`.

# Answer
> 0 votes
Check for any attributes you are using to determine if it is the correct node in template\_preprocess\_page (in your themes template.php) and then add to the $variables\['theme\_hook\_suggestions'\] array.

Something like this:

```
function YOUR_THEME_preprocess_page(&$variables) {
    if(isset($variables['node']) && $variables['node']->your_field_name[LANGUAGE_NONE][0]['value']=='some_value') {
        $variables['theme_hook_suggestions'][] = 'page__your_template';
    }
}

```

---
Tags: theming
---


# Question
Title: How to hide the "Add to cart message" on mobile site"?
I'm using two different themes for main site and mobile site. I want to hide the Add to cart message on mobile site because I've created a custom window with custom messages but I want it to be displayed on the main desktop site. How can I hide it on mobile site?

# Answer
> 0 votes
Thank you everything for your time. I figured it out this way. I put a condition in the show add to cart mesage in rules where I call a function. The function returns false if it's a mobile theme and returns true if it's another theme. Thus it's not showing anymore on the mobile theme :).

# Answer
> 0 votes
One way to do it would be to use hook\_node\_submit to override the submit handler for `commerce_cart_line_item_views_form_submit`. Check for your theme and apply messages appropriately. However, that will only work for this single message. You would have to rewrite all of the cart functions that have messages.

Another way: I know you can do this with CSS. You just need to target the product pages only. I don't know your CSS structure, but if you look at the classes in the `<body>` element, you should see classes that you can use to cascade down and set `display: none;` to the message region. I don't know what other messages will show up that you care about on the product pages. If you do have some, then the first option is your only option. (Or the non-recommended option below.)

You could also edit the cart source but that is not a good option because it breaks your upgrade path.

If you are using Kickstart, I can find the function to override there as well. (I have sites running both.)

---
Tags: commerce, rules, status-messages
---


# Question
Title: Multiple Group Managers in Organic Group
The "Owner / Group Manager" of a group appears to be the person that created the container (let's say a node). That, of course, is controlled by the UID of that node.

Is it possible to have multiple "Group Managers". If that is possible, it would seem to mandate something else controlling the status of "Group Manager".

# Answer
OK, so intuition told me that this was a can do... Really, membership and controlling the permissions of members is largely what OG is about.

Anyway, the brief solution that I was looking for is this:

1. Edit the node containing the group in question from group manager account
2. Click Group Tab
3. Click Add people
4. Add user name
5. Go back to /admin/people (this is where the magic happens)
6. Check the box beside the username in update options.
7. open dropdown box
8. Select **Administrator member** click Update

Voilà!

There is much more that can be done (for example adding custom roles). Explore on!
> 1 votes

# Answer
I think there could be only one Group Owner / Group Manager for a group, because there is only one author for a node.

When you change the author of that group, you will change the owner / manager of that group either.

BUT, if you only concern about the permissions, you can just grant the "Administer group" permission for the group role, then users of that group role will have the same ability as the group manager has, e.g. delete the group. And if you are looking for the opposite, revoke "Administer group".
> 1 votes

---
Tags: organic-groups
---


title: Form element #default_value and AJAX

text:
# Question
Title: Form element #default_value and AJAX
I can't get a form to display a (default?) value after an AJAX call. I am using the following code:

```
function foo_form ($form, &$form_state, $foo) {

  $form['#prefix'] = '<div id="foo-form-wrapper">';
  $form['#suffix'] = '</div>';

  $form['copy'] = array(
    '#type' => 'submit',
    '#value' => t('Copy foo'),
    '#limit_validation_errors' => array(),
    // #submit is required to use #limit_validation_errors
    '#submit' => array('foo_form_submit'),
    '#ajax' => array(
      'wrapper' => 'foo-form-wrapper',
      'callback' => 'foo_form_callback',
    ),
  );

  $form['description'] = array(
    '#type' => 'textarea',
    '#title' => t('Short description'),
    '#required' => TRUE,
    '#maxlength' => 255,
    '#default_value' => $foo->description,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
  );

  return $form;
}

function foo_form_callback($form, $form_state) {
  return $form;
}

function foo_form_submit ($form, &$form_state) {
  if (!isset($form_state['triggering_element']['#ajax'])) {
    $foo = (object)$form_state['values'];

    entity_get_controller('foo')->save($foo);

    $form_state['redirect'] = 'admin/foo';
    return;
  } else {
    form_set_value($form['description'], 'description text', $form_state);
    $form_state['rebuild'] = true;
  }
}

```

As I understand it, the form should automatically try to display the value if it is set in $form\_state. When the callback is executed and the form is built, $form\_state\['values'\]\['description'\] is the value set in foo\_form\_submit. However, nothing is being displayed.

# Answer
> 1 votes
I've experienced similar problems especially with textfields, checkboxes and radios. The solution I found (and I can't guarantee is the "correct" solution) is to change the `$form_state['input'][VARIABLE]` field. Do this in the validation function:

```
function foo_form_validate ($form, &$form_state) {
  // this will take a entered value from one element and make it display in another
  $form_state['input']['some_value_to_change'] = $form_state['values']['another_element'];
}

```

# Answer
> 4 votes
I know this is late, but for people like me who are still experiencing similar problems with ajax and forms in Drupal, here's how I fixed this. In your ajax callback function, instead of returning just the render array, you need to call the form\_builder() function and return its result. Eg., my code goes like this:

```
function inventory_purchase_item_add_ajax(&$form, &$form_state) {
    //...

    unset($form_state['input']['line']);
    unset($form_state['values']['line']);

    //Update the form's lines array
    $lines = update_inventory_purchase_form_lines($form_state['node']->line, $purchase_item_count);
    $form['vtab1']['purchase']['items_wrapper']['line'] = $lines;
    return form_builder($form['#id'], $lines, $form_state);
}

```

# Answer
> 3 votes
this bug even exists in drupal 8 and is presented HERE.

simplest simple solution is to remove `input` value of form element in form builder function before creating that element:

```
unset($form_state['input']['description']);
$form['description'] = array(
    '#type' => 'textarea',
    '#title' => t('Short description'),
    '#required' => TRUE,
    '#maxlength' => 255,
    '#default_value' => $foo->description,
 );

```

Another solution:

in some cases where there is no java script event handler attached to that element you can have different name for element so `input` doesn't come in the way, example:

```
$name='description_'.rand();
$form[$name] = array(
    '#type' => 'textarea',
    '#title' => t('Short description'),
    '#required' => TRUE,
    '#maxlength' => 255,
    '#default_value' => $foo->description,
 );

```

and save the name in `$form` for later use (in validation,submittion,...):

```
$form['a_unique_name']=$name;

```

# Answer
> 0 votes
thanks, this code works for me, the `input` method works for me ...

```
if (isset($form_state['values']['task-name'])) {
  $form_state['input']['task-description'] = show_task_description($form_state['values']['task-name']);
}

```

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


title: enable field groups programmatically

text:
# Question
Title: enable field groups programmatically
I have created a field groups programmatically using this code:

in \*.module file

*```
/**
 * Implements hook_ctools_plugin_api()
 */
 function field_test_module3_ctools_plugin_api($module, $api) {

      if ($module == 'field_group' && $api == 'field_group') {
        return array('version' => 1);
  }
}

```*

# in \*.field\_group.inc

/\** * Implements hook\_field\_group\_info() \*/

```
function field_test_module3_field_group_info(){

 $field_groups = array();
 $field_group = new stdClass();
 $field_group->disabled = FALSE; /* Edit this to true to make a default field_group disabled initially */
 $field_group->api_version = 1;
 $field_group->identifier = 'generale|node|field_esempio3|form';
 $field_group->group_name = 'generale';
 $field_group->entity_type = 'node';
 $field_group->bundle = 'field_esempio3';
 $field_group->mode = 'form';
 $field_group->parent_name = '';
 $field_group->data = array(
   'label' => 'Generale',
   'weight' => '2',
   'children' => array(
     0 => 'coverage',
   ),
   'format_type' => 'fieldset',
   'format_settings' => array(
     'formatter' => 'collapsed', //collapsible
     'instance_settings' => array(
       'description' => 'provo a creare un field group',
       'classes' => '', //generale field-group-fieldset
       'required_fields' => 1,
     ),
   ),
 );
 $field_groups['generale|node|field_esempio3|form'] = $field_group;

 return $field_groups;
}

```

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

Field groups is created but not dysplayed. Bottom of the page there is a section "Disabled fieldgroups" where it appears

If it's enable there are no problem but I need that fieldgroups is activated automatically. There is a way to enable this fieldgroups programatically?

Thank you.

# Answer
You can use the following code.

```
foreach($field_groups as $field_group){
    ctools_export_crud_enable('field_group',$field_group->identifier);
}

```
> -1 votes

---
Tags: 7, entities
---


title: how to create a "my comments" view

text:
# Question
Title: how to create a "my comments" view
I just want to create a view that show each user their own set of comments only. would I add something in contextual filters?

Thanks Tony

# Answer
Yes, add the contextual filter "Comment Author uid". Then, under the section "When the filter value is NOT available", select,

"provide a default value".

You can then select:

"User ID from logged in user"

or

"User ID from URL".

To use the latter, you will have to display the view as a block on a page that has the user-\>uid in the system path, such as the user account page (user/%uid). If you use the former, the view can be displayed anywhere, and will always show the current user's comments.
> 1 votes

---
Tags: views, comments
---


# Question
Title: Custom view mode for entity references - getting rid of title
I have an entityreference field that displays content in a custom view mode. It works great.

The only problem is that in addition to the fields that I placed in my custom view mode, it also displays the title as a link to the content. I would like to replace it and have another field (that is already in the view mode) be used as the link to the content. Also the title is appearing in the markup outside the entityreference field's view mode's wrapper, making styling a bit cumbersome.

So right now I have something like the following as field output

The title of the node

> *headline*
>
> **My cool description that has some words in it**
>
> \[and a picture\]

I want essentially the same thing, but minus the title, and with the headline as the link, like so:

> *headline*
>
> **My cool description that has some words in it**
>
> \[and a picture\]

How do I go about getting rid of the title and substituting the headline?

# Answer
> 1 votes
I had almost the same problem as you recently. Eventually I changed the node--content-type.tpl files of the referenced content type tot suit my needs.

# Answer
> 2 votes
You could do this with display suite as follows:

1. Enable display suite and display suite extras (important)
2. At structure \> ds \> list \> extras \> Other, enable Page title options
3. At Manage Display \> \[view mode\] \> \[layout\], enable a DS layout for your view mode
4. Manage Display \> \[view mode\] \> custom page title, hide the page title

DS has a lot going on. But if you need custom display modes and need to hide the page title in some cases it works well. Plus you get a lot of other nice features.

# Answer
> 1 votes
If you don't want to use display suite, you can create a new view mode in your custom module like so:

```
function MYMODULE_entity_info_alter(&$entity_info) {
  $entity_info['node']['view modes']['VIEW_MODE_NAME'] = array(
    'label' => t('VIEW_MODE_NAME'),
    'custom settings' => TRUE,
  );
}

```

You can administer the new view mode in the display settings for each content type. You can also enable custom template files for the view modes of each content type by adding the following in your theme's template.php file:

```
function MYTHEME_preprocess_node(&$vars) {
 switch($vars['view_mode'] ){
    case 'MY_VIEW_MODE':
      $vars['theme_hook_suggestions'][] = 'node__' . $vars['type'] . '__MY_VIEW_MODE';
      break;
    case 'teaser':
      $vars['theme_hook_suggestions'][] = 'node__' . $vars['type'] . '__teaser';
      break;
  }
}

```

This enables you to create template files with filenames like node--CONTENT\_TYPE--MY\_VIEW\_MODE.tpl.php.

---
Tags: entities
---


# Question
Title: Require First and Last Name on Comments in Drupal 7
I enabled Comments on a content block in Drupal 7. I would like to have First and Last Name required on the comments. How do I make that happen?

# Answer
In Drupal 7, Comment fields are managed the same way Node fields are managed.

Go to structure-\>Content types-\> edit link. If comment is enabled for selected content type, It will add a tab for "comment fields" on top besides manage fields tab.

For article content type url will be "admin/structure/types/manage/article/comment/fields" and tab looks like the image attached below.
> 1 votes

---
Tags: comments
---


# Question
Title: updating webform submission display by using form
So, this is what I'm trying to do. I've got a webform submission filled in and saved to the database. When viewing the submission (node/nid/submission/sid). I want to show a form, which ask the user for a key. When the key is filled in I want to change the display of the submission (not the data in the database) using the webform\_submission\_load() hook. This is the code right now:

```
// webform hook
function mymodule_webform_submission_load($submissions) {
   $key_status = mymodule_get_key_status();
   if($key_status) {
      //change the submission display values
   }
}

// return TRUE or FALSE, depending on form submit
function mymodule_get_key_status($setkey = FALSE) {
   $status = &drupal_static(__FUNCTION__);
   if(!isset($status)) {
      $status = $setkey;
      // display form when key is not provided
      if(!$status) {
         $getform = drupal_get_form('mymodule_form');
         $output = drupal_render($getform);
         drupal_set_message($output, 'form', FALSE);
      }
      // key provided in form, so don't display the form
      else {
         $errors = drupal_get_messages('form');
      }
   }
   return $status;
}

// form submit callback
   function mymodule_form_custom_submit($form, &$form_state) {
       if (isset($form_state['values']['form_value'])) {
          $key = $form_state['values']['form_value']);
          drupal_static_reset('mymodule_get_key_status');
          mymodule_get_key_status(TRUE);
       }
    }

```

When viewing a submission I see the submission and the form. When I submit the form nothing changes and the form is displayed again. When I debug the return value of the mymodule\_get\_key\_status function the following happens. First the function return FALSE, then the form calls the function and the function returns true. After that the function is called again by the webform hook. The function returns false again... Not what I expected. When I call `mymodule_get_key_status();` in the form submit callback it returns true. So the drupal\_static is set properly.

Why isn't the code working as I expected?

# Answer
Well, i figured it out myself. After the form submit callback drupal fires a redirect to the same page. So the values set in `mymodule_get_key_status` are flushed after the redirect. I add `$form_state['redirect'] = false;` to my submit callback and now everything works as expected.
> 0 votes

---
Tags: hooks, webforms
---


title: Passing arguments to the child view

text:
# Question
Title: Passing arguments to the child view
I'd like to ask a question concerning the Views field view module.

I can see in the parent view a list of tokens available to pass as arguments to the child view but I can't see any way to *grab* those arguments from within the child view.

How can I achieve this?

# Answer
> 3 votes
The recieving end doesn't require any configuration that's specific to Views field view. The arguments are passed on as if they came from the URL, so they are used just like regular arguments/contextual filters.

It's important to note that it's *easy* to completely wreak your server performance with this module. A medium-sized site could suddently execute a thousand views or so if this module is (ab)used.

# Answer
> 1 votes
As I had a lot of trouble setting context filters properly for Views Field View, and couldn't find any documentation on the subject or proper answers, I'll provide more detailed walk-through here:

I want to have a list generated like this from different content types:

* First group of things
* Some data about that group

+ name of first thing from that group
    + name of second thing from that group
* Second group of things
* Some data about that second group

+ name of first thing from the second group
    + name of second thing from the second group

---

1. I've created parent view "my\_group\_of\_things" showing fields from content type "my\_group"
2. I've created child view "list of things" showing fields from content type "thing"
3. The content type "thing" has a field ("field\_my\_group") of type node reference that references to selected "my\_group" and has a label "Content: MyGroup"
4. In parent view ("my\_group\_of\_things") I add field Content: Nid
5. In the same parent view I add field Content: View and set it to "list of things"
6. While setting the Content: View field I enter \[!nid\] in the CONTEXTUAL FILTER text box
7. Don't forget to apply the Content: View and save the View
8. In child view ("list of things"), in ADVANCED tab, I add a CONTEXTUAL FILTER
9. While setting this contextual filter I choose Content: MyGroup (field\_my\_group)
10. In the same contextual filter I set WHEN THE FILTER VALUE IS NOT AVAILABLE to "Hide view"
11. Apply and save. It should work now.

Very simple, but without documentation and arrogant answers like "yeah, i got it now", or "just set up contextual filter" it took me a whole day to figure out.

---
Tags: views
---