title: Changing logo when signed in

text:
# Question
Title: Changing logo when signed in
In page.tpl.php, the logo section is handled as:

```
<?php if ($logo): ?>
  <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home" id="logo">
    <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />
  </a>
<?php endif; ?>

```

When user signs in, I want logo to change from `logo.png` to `inner_logo.png`

I can track where `$logo` comes from and add an if statement like `<?php if($user->uid <=0) { $logo = "logo.png" } else { ... ?>`

But would this be the correct practice? Is there a more practical Drupal way?

edit:

```
/* Override or insert variable into the pre-process_template*/
function bartik_preprocess_page(&$variables) {
    if (user_is_logged_in()) {
        $variables['logo'] = (drupal_get_path('theme', 'bartik') . '/images/inner_logo.png');
    }
}

```

# Answer
> 5 votes
In general, every .tpl.php has what is called a "preprocess" function. The default one for page.tpl.php is `template_preprocess_page()`. This sets up the variables that are available in the template. Other modules and themes can have their own; then don't replace each other, rather, they all run in a defined order.

So, you would add in a preprocess function for your theme's template.php like:

```
function MYTHEME_preprocess_page(&$variables) {
  if (user_is_logged_in()) {
    $path = drupal_get_path('theme', 'MYTHEME');

    $variables['logo'] = file_create_url($path . '/images/inner_logo.png');
  }
}

```

This will check to see if the user is logged in using the proper API call (program to the interface not the implementation), and then change the logo variable to a new path from within your theme. Just make sure you clear the Drupal caches from admin/config/development/performance first so the function gets picked up.

---
Tags: views, theming
---


# Question
Title: db_insert in Drupal 7 without field names
I have the following INSERT in a db\_query, but feel like I should convert it to a db\_insert, but can't figure out the syntax:

```
INSERT INTO {mytable} VALUES (23, 'foo', 'bar', 42)

```

This example is fairly short, but I do work with some legacy tables that have MANY fields.

```
$insert = db_insert('variables')->values(array(23, 'foo', 'bar', 42));
$insert->execute();

```

The above gives me "NoFieldsException: There are no fields available to insert with. in InsertQuery-\>preExecute()".

How can you perform an insert with db\_insert without needing to specify each field name? I can make it work in D7 with db\_query(\[INSERT...\]); but drupal\_write\_record does not work.

# Answer
> 3 votes
You can not do this with `db_insert()`. You could probably dig into the `InsertQuery` class and get it done, but that's no different than what you're already doing IMO.

I have never seen `INSERT` without specifying column names, for good reason, although apparently you can (mysql api). If you do this, it makes it more difficult for someone else to understand what you've done, and impossible to alter the table structure without causing headaches.

You can look at the way`drupal_write_record()` uses `drupal_get_schema()` to create the fields if you'd like to automate the process (although it would probably take just as long to write the `$fields` array one time).

---
Tags: database
---


# Question
Title: adding a background image to a Drupal site
I have a high-resolution white-paper texture background that I want to add to my Drupal site with the default Bartik theme.

I've looked at several posts across the web on how to do this with no clear answer.

I also haven't been able to find a Drupal module to do this. Most of the advice I've read is to modify the theme's CSS files.

But it's not clear which CSS file I should edit. Colors.css, style.css?

I'm almost certain that the line I need to add is

> ```
>  background-image: url("/images/papertexture.jpg").
>
> ```

But I'm not sure where to add the CSS.

# Answer
> 0 votes
You can try the background image module

> This is an api module that provides tools to add background images to html elements using the css "background" property. A basic settings page is supplied as well as functions to easily add the "background" property to the page.

---
Tags: theming
---


title: How do I check if a field is empty?

text:
# Question
Title: How do I check if a field is empty?
On my views-view-field template, I would like to print out 'field\_images' if 'field\_cover\_image' is empty.

I tried this solution here but it throws me this error message.

> Notice: Undefined variable: node in include() (line 45 of /sites/all/themes/mytheme/templates/views-view-fields--incubator.tpl.php).
>
> EntityMalformedException: Missing bundle property on entity of type node. in entity\_extract\_ids() (line 7539 of /includes/common.inc).

Is there any other ways to check if a field is empty or not?

Thanks!

# Answer
Been awhile but thanks again for sharing your solutions. I ended up using Views if Empty module and that saves me from creating a views .tpl
> 0 votes

# Answer
You get that error because `$node` is not one of the variables passed to views-view-fields.tpl.php, which receives:

* `$view`: The view in use.
* `$fields`: an array of $field objects.
* `$row`: The raw result object from the query, with all data it fetched.

Basing on the description, `$row` could be used to retried the node object. I cannot tell you the content of that variable, but using print\_r() from your template file can help to understand its content.
> 1 votes

# Answer
Use views preprocess API and check if(isset(field\['name'\])) and then do things as per your needs. Put this in a module to achieve your needs. This will be a long term solution.
> 1 votes

# Answer
The easiest solution for this is to add both fields but add field\_images first and mark is as 'exclude from display'. Then add the field\_cover\_image and in the 'NO RESULTS BEHAVIOR' section add the token for field\_images (can be found in replacement patterns). Done!
> 0 votes

---
Tags: 7, entities
---


title: How to add Javascript code into a block

text:
# Question
Title: How to add Javascript code into a block
I have a Drupal 7 site. I'd like to add Social Media follow buttons (i.e. Follow us on Facebook, Twitter, Linkedin). I grabbed some Javascript code from http://www.addthis.com which generates these buttons and also links to some analytics services I will be using. Now I need to figure out how to place the AddThis Javascript code I generated, to a Drupal block. Once it's in a block, it will be easy for me to move around my Drupal site pages.

# Answer
> 2 votes
Why not just use the addthis module rather than adding a block. If you however want to add a block, just go to **admin/structure/block** click on add block. Paste your script in and select filter type of php code and click save

If you do not have PHP filter in the filter type, enable it under the core module

# Answer
> 0 votes
In order to add Social Media follow buttons you can use the Follow module. If you need to add Social Media share buttons you can use the AddThis module or the Easy Social module.

To attach CSS or JS files to a specific block you will need to build a custom module that implements the hook\_block\_view\_alter to manipulate the block render array and then use Drupal 7 FAPI's #attached attribute to attach the file to the block.

---
Tags: blocks, javascript
---


title: Changing secondary menu format

text:
# Question
Title: Changing secondary menu format
Secondary menu links are listed with the default theme.

I want to add a hover option to it so that menu links will always pop up when a user hovers on a button.

I already built it with html but I couldnt integrate the existing codes in it.

html

```
<a class="button white_bg black_f btn-hasdd" href="#">
<div class="sub">
<ul class="white_bg lastcolor_f">
</div>

```

drupal default code

```
    <?php if ($secondary_menu): ?>
      <div id="secondary-menu" class="navigation">
        <?php print theme('links__system_secondary_menu', array(
          'links' => $secondary_menu,
          'attributes' => array(
            'id' => 'secondary-menu-links',
            'class' => array('links', 'inline', 'clearfix'),
          ),
          'heading' => array(
            'text' => t('Secondary menu'),
            'level' => 'h2',
            'class' => array('element-invisible'),
          ),
        )); ?>
      </div> <!-- /#secondary-menu -->
    <?php endif; ?>

  </div></div> <!-- /.section, /#header -->

  <?php if ?>

```

FYI: I couldnt locate to `function links__system_secondary_menu` in any of the files.

# Answer
You use CSS to style the links. Looking at your code, the secondary menu has an id `secondary-menu-links`. So target that within your CSS:

```
#secondary-menu-links a:hover {
  /* your pop-out effect here */
}

```
> 0 votes

---
Tags: views, theming
---


# Question
Title: What is the difference between DRUPAL_ROOT and file_directory_path() in drupal 6?
I want an alternative for `file_directory_path()` deprecated in Drupal 7. I got an alternative with `file_default_schema()`.

What is the difference between `DRUPAL_ROOT` and `file_directory_path()` or `DRUPAL_ROOT` and `file_default_schema()`?

# Answer
> 2 votes
DRUPAL\_ROOT is a root folder of Drupal's installation. `file_directory_path()` returns a path to directory meant for uploaded files, default `DRUPAL_ROOT/sites/example.com/files` (replace example.com with your site or `default`). If you will replace it with hardcoded path, your modules will break on sites configured to store files in other directory. So this is not the way.

If you need it for forms, use new `managed_file` form element. It takes care. No need to provide path.

For reading file, if you know it's ID it's easy again. Load it and access it's properties, like that:

```
file_load($fid)->uri; // get URI to display it

```

If you don't want to use managed files (you should, but no one can force you), use:

```
$dir = file_default_scheme() . '://' . $any_subdirectory_you_want;

```

This will create directory string Drupal functions understand. For example, you can use it as `$destination` in `file_save_upload($source, $validators, $destination, $replace)` \- again, no need for hard-coding actual path or using DRUPAL\_ROOT on your own.

---
Tags: 7
---


# Question
Title: How to programatically remove parent form taxonomy term?
I try to remove programatically all parents form my taxonomy terms. But I can't get it working. I tried this code:

```
$vid = 18;
$tree = taxonomy_get_tree($vid);
foreach ($tree as $term) {
   $term->parents = null;  # Does not work
   $status = taxonomy_term_save($term);
}

```

But after saving (although the function returns 2) the parents are still there. What is wrong?

# Answer
> 1 votes
`taxonomy_term_save()` treats `null` as "do not change parent", and `0` means "this term does not have any parents". Also, property is named `parent`, not `parents`. Change

```
$term->parents = null;

```

to

```
$term->parent = 0;

```

and you're done.

---
Tags: taxonomy-terms
---


# Question
Title: How to reset validation errors in ajax callback?
I would like to not validate fields if I submit button with ajax callback. Currently, on every button click it displays validation errors of another fields. The button doesn't submit the form, it does some another action (add more fields).

# Answer
You need to set limit\_validation\_errors to an empty array for it to ignore the rest of the fields in the form. Here's an example:

```
  $form['a_field'] = array(
    '#type' => 'button',
    '#limit_validation_errors' => array(),
    '#value' => t('Click here'),
    '#name' => 'a_field',
    '#submit' => array('my_submit_function'),
    '#ajax' => array(
      'callback' => 'my_function',
      'wrapper' => 'my_wrapper',
    ),
  );

```
> 2 votes

---
Tags: forms, ajax
---


# Question
Title: Grouping multiple columns in a view result for a report
I have a requirement in which I need to display the stock report for an application as in the below image

I want to know how to group the Quantity, Batch no and Expiry date fields together in another column (Opening Stock) in Views. I am using Drupal 7 and Views 3.

Also I need a summary of the quantity in the footer of the view, for example sum of all quantity for a batch in the footer. Any help from the community is highly appreciated...

# Answer
> 1 votes
To group the quantity, Batch no and expiry date fields in another column, use the views secondary row module

> Provides a way to split a views table row into two. In the table style settings, select a "Secondary row" option.
>
> So if a table looks like this: Name | Description | Edit link | Delete link selecting "Name" as the secondary row option for "Edit link" and "Description" as the secondary row option for the "Delete link" will render two rows:

For summary of the quantity in the footer, use Views summarize

> Enables an extra display style which displays summaries of a column on the last row.

---
Tags: views, entities
---


# Question
Title: form button redirecting to .inc module file
I'm building a custom module and I would like to add some buttons that redirect the user to other .inc files on click.

My idea was something like this, in my **mymod.user.inc** file :

```
if ($form_state['storage']['step'] === 1) {

 $form['button']['addnew_form'] = array(
    '#type' => 'submit',
    '#value' => 'new form',
    '#submit' => array('mymod_form_user_newform_form'),
            );

$form['button']['addnew_form2'] = array(
    '#type' => 'submit',
    '#value' => 'new form 2',
    '#submit' => array('mymod_form_user_newformtwo_form'),
            );

 return $form;

}

```

I added a hook\_menu in my **myform.module** file :

```
function myform_menu(){
$items = array();

$items['myform/forms/newform'] = array(
    'title' => 'New form 1',
    'description' => 'New form 1',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymod_form_user_newform_form'),
    'file' => 'myform.newform.inc',
    'access callback' => TRUE
);

```

When I click on my button, it doesn't redirect to the new form page. Am I totaly wrong using this method ?

# Answer
> 3 votes
You redirect to a *URL*, you can't redirect to a PHP include file it's not possible.

The function you give as the `#submit` key is run on form submission, it's not used to build up the next page request or anything like that.

Your code should look more like this:

```
$form['button']['addnew_form'] = array(
  '#type' => 'submit',
  '#value' => 'new form',
  '#submit' => array('MYMODULE_form_submit'),
);

```

Then you'll need a submit handler to match that:

```
function MYMODULE_form_submit($form, &$form_state) {
  // Redirect to the appropriate URL.
  $form_state['redirect'] = 'myform/forms/newform';
}

```

You can add a second submit handler for your second button, with a different function name, and that redirects to a new menu item that you need to define which contains the second form.

---
Tags: 7, forms, redirection
---


# Question
Title: Programmatically add image already in public to node
I have very little experience working with Drupal and it may be possible that I'm missing something very basic here.

I have created a module to add/update nodes pro-grammatically from an XML file, this nodes have a file for images. For every node there's a French version and an English version, this means that they share the same images. When I import these nodes I would like to avoid refetching the images (since those are already into the `public://` folder) and populate only the image field.

The first run goes smoothly, the images are fetched and saved from URL for all the English nodes using this code:

```
if(!file_exists("public://" . $name)) {
    $file_temp = file_get_contents($URL);
    $file_temp = file_save_data($file_temp, "public://" . $name, FILE_EXISTS_REPLACE);
}

$node->field_image[LANGUAGE_NONE][$k]['fid'] = $file_temp->fid;
$node->field_image[LANGUAGE_NONE][$k]['title'] = $name;

```

The second round, for the french nodes, what I've done is:

```
else {
    $file_temp = new stdClass();
    // Get the image id corresponding to the $name parameter, returns string.
    $file_temp->fid = _xml_importer_get_image_id($name, $table, $fid, $title);
}

$node->field_image[LANGUAGE_NONE][$k]['fid'] = $file_temp->fid;
$node->field_image[LANGUAGE_NONE][$k]['title'] = $name;

```

This works, in a sense, meaning that the fields are populated correctly and the image are shared between the nodes, the problem is that I get warning and notices for this part.

This is the full dump:

> Warning: array\_flip() \[function.array-flip\]: Can only flip STRING and INTEGER values! in DrupalDefaultEntityController-\>load() (line 178 of /drupal/includes/entity.inc). Notice: Trying to get property of non-object in file\_field\_presave() (line 220 of drupal/modules/file/file.field.inc). Strict warning: Creating default object from empty value in file\_field\_presave() (line 221 of drupal/modules/file/file.field.inc). Notice: Undefined property: stdClass::$uri in file\_save() (line 566 of drupal/includes/file.inc). Warning: array\_flip() \[function.array-flip\]: Can only flip STRING and INTEGER values! in DrupalDefaultEntityController-\>load() (line 178 of drupal/includes/entity.inc). Notice: Trying to get property of non-object in file\_field\_presave() (line 220 of drupal/modules/file/file.field.inc). Strict warning: Creating default object from empty value in file\_field\_presave() (line 221 of drupal/modules/file/file.field.inc). Notice: Undefined property: stdClass::$uri in file\_save() (line 566 of drupal/includes/file.inc). SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry '' for key 'uri' Warning: array\_flip() \[function.array-flip\]: Can only flip STRING and INTEGER values! in DrupalDefaultEntityController-\>load() (line 178 of drupal/includes/entity.inc). Notice: Trying to get property of non-object in file\_field\_presave() (line 220 of drupal/modules/file/file.field.inc). Strict warning: Creating default object from empty value in file\_field\_presave() (line 221 of drupal/modules/file/file.field.inc). Notice: Undefined property: stdClass::$uri in file\_save() (line 566 of drupal/includes/file.inc). Warning: array\_flip() \[function.array-flip\]: Can only flip STRING and INTEGER values! in DrupalDefaultEntityController-\>load() (line 178 of drupal/includes/entity.inc). Notice: Trying to get property of non-object in file\_field\_presave() (line 220 of drupal/modules/file/file.field.inc). Strict warning: Creating default object from empty value in file\_field\_presave() (line 221 of drupal/modules/file/file.field.inc). Notice: Undefined property: stdClass::$uri in file\_save() (line 566 of drupal/includes/file.inc).

I looked for this kind of warnings/notices and I found out that somewhere I'm passing some parameters not in a correct way (e.g. arrays instead of strings) and for me doesn't make sense. My guess is that not invoking `file_save_data` has some effect on the `file_managed` table and gives missing or malformed parameter, anyway with my poor experience I may be very well mistaking.

This is the full code snippet I'm using:

```
for($k=0; $k<sizeof($file_list); $k++) {
    if(!file_exists("public://" . $file_list[$k]->name)) {
        $file_temp = file_get_contents($URL);
        $file_temp = file_save_data($file_temp, "public://" . $file_list[$k]->name, FILE_EXISTS_REPLACE);
    }
    else {
        $file_temp = new stdClass();
        // Get the image id corresponding to the $name parameter, returns string.
        $file_temp->fid = _xml_importer_get_image_id($file_list[$k]->name, $table, $fid, $title);
    }
    $node->field_image[LANGUAGE_NONE][$k]['fid'] = $file_temp->fid;
    $node->field_image[LANGUAGE_NONE][$k]['title'] = $file_list[$k]->name;
}

```

And this is the function \_xml\_importer\_get\_image\_id:

```
_xml_importer_get_image_id($image_name, $table, $field, $title_field) {

    $query = db_select($table, 'ill')
        ->condition('ill.' . $title_field, $image_name, '=')
        ->fields('ill', array($field))
        ->execute()
        ->fetchCol();

    if(empty($query)) {
            return false;
    }
    else{
        return (string)$query[0];
    }
}

```

# Answer
> 0 votes
I found that with my snippet I was totally bypassing the Drupal file management system, I corrected the issue in this way:

```
else {
    $file_temp = file_load(_xml_importer_get_image_id($image_xpath[$k]->value, $table, $field, $title));
}
$node->field_image[LANGUAGE_NONE][$k]['fid'] = $file_temp->fid;
$node->field_image[LANGUAGE_NONE][$k]['title'] = $file_list[$k]->name;

```

Another problem was that there was the same image name twice inside the XML file, had to check for duplicate to avoid breaking some unicity constraint from the database.

---
Tags: 7, nodes, media
---


# Question
Title: Change the default upload file path for a content type
The default file upload path used by Drupal is sites/default/files.

How can the default path be changed for a content type?

# Answer
> 2 votes
The public filesystem is a system-wide setting; it can't be different per content type.

There's a setting under every file field attached to your content types that will allow you to choose the sub-folder within public:// that files for that field are uploaded to.

As an extension you can get a more advanced version of that functionality with the File (Field) Paths module...but beware, there are issues with it and you'll need to test thoroughly before deploying to a live site.

One of those methods will likely be your best bet. There's lots more info at Working with Files in Drupal, including documentation on how to use the private file system (in case you can leverage that).

---
Tags: files
---


# Question
Title: How to use Form API when the form callback is a method?
How can I use `AClass::FormCallback()` as `$valid_callback` on the code below?

```
class AClass {
  public function FormCallback() {
  }
}

$valid_callback = ?

drupal_get_form($valid_callback);

```

# Answer
> 4 votes
drupal\_retrieve\_form() uses function\_exists() before calling the form builder, and that function doesn't work if you pass a string such as `'AClass::FormCallback'`. If you pass it an array, e.g. `array('AClass', 'FormCallback')`, you get an error about the function expecting a string.

What you can do is to use a custom function containing code similar to the following one, and use it as form builder.

```
function mymodule_form_builder($form, &$form_state) {
  $class = $form['#class_callback'];
  $method = $form['#method_callback'];

  if (method_exists($class, $method)) {
    $args = array_merge(array($form, &$form_state), $form_state['build_info']['args']);
    $form = call_user_func_array(array($class, $method), $args);

    return $form;
  }
}

```

The code is simplified, and it doesn't contain code to check any possible error condition. It works also just in the case of static methods.

For an explanation of the values passed in `$form_state`, see the documentation for drupal\_build\_form().

# Answer
> 1 votes
You can also use a wrapper function:

```
function mymodule_ajax_wrapper(&$form, &$form_state) {
  $ajax = $form_state['ajax_wrapper'];
  return $ajax['class']::$ajax['method']($form, $form_state);
}

```

then in your form definition:

```
function mymodule_myform($form, $form_state) {
  ...
  $form_state['ajax_wrapper']['class'] = 'myClass';
  $form_state['ajax_wrapper']['method'] = 'myMethod';
  $form['myfield'] = array(
    '#ajax' => array(
       'callback' => 'mymodule_ajax_wrapper',
    ),
  );
  ...
}

```

and in your class:

```
class myClass {
  static function myMethod(&$form, &$form_state) {
    ...
  }
}

```

---
Tags: forms
---


title: How to add more Fields using Form Api

text:
# Question
Title: How to add more Fields using Form Api
I want to add an add more button to an element in Drupal form (using Drupal Form API). Should I make it with javascript (append a new element) and check for `$_POST` in submission or is there another solution in Drupal API.

This is my code for that field, I want users to be able to upload more than one image:

```
$form['product'] = array(
  '#title' => t('product'),
  '#type' => 'managed_file',
  '#required' => TRUE,
  '#default_value' => variable_get('product', ''),
  '#upload_location' => 'public://',
  '#upload_validators' => array(
    'file_validate_extensions' => array('gif png jpg jpeg'),
    'file_validate_size' => array(0.6*1024*1024),
  ),
);

```

# Answer
Use Drupal's AJAX Form functionality to add elements to a form from the client.

If you try to update a Drupal form with JavaScript on the client side, it will not be submitted correctly. Drupal knows what was in the form when it was sent to the client, and expects that same structure to be sent back. Therefore, you need to use AJAX to tell Drupal the form is updated (with more fields, etc.).
> 3 votes

# Answer
You can allow multiple file uploads per field with the multiupload filefield widget module and if you need image support, extend it with the multiupload imagefield widget as well.
> 0 votes

# Answer
For your *specific* need to do multiple uploading of images another option would be to use the media gallery module (which requires media module).
> 0 votes

---
Tags: 7, forms
---


# Question
Title: How to display nodes in order on a daily base
I would like to display node of a specific content type with views. I want one node to be display every day in order based on node id and the node to change every day.

# Answer
You can use the views random seed module and on the sort criteria use Global: Random seed and set the reset seed to everyday

> Adds a random order handler with seed. If a constant integer argument N is specified in the sql RAND() function, it is used as the seed value, which produces a repeatable sequence of column values. This makes it possible to have paging and not having items show up twice. It's also possible to compute a custom seed using PHP, allowing you to create pseudo randoms numbers based on variables such as the date of the day.
> 1 votes

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


# Question
Title: Creating a store open hours widget using Field API
I need an open hours widget that outputs something like:

* Mon 8:00am to 5:00pm
* Tue 8:00am to 5:00pm
* Wen 8:00am to 5:00pm
* Thu 8:00am to 5:00pm
* Fri 8:00am to 5:00pm
* Sat 11:00am to 3:pm
* Sun Closed

I think the best way to do this is create a three column field table with day of week, open and close columns. Then create a field widget form with three drop down boxes and a formatter that puts it all together.

Has somebody already done this in Drupal 7? If not, does anybody have any ideas on how to do this best?

# Answer
> 3 votes
I would check out the Office Hours module. It has a dev version for D7, you can either help finish the port, or at the least pick up some ideas on how to best accomplish this.

# Answer
> 3 votes
I used Tablefield for this. Haven't seen the Office Hours module, will have to give it a spin. Tablefield is a bit more generic, but it's relatively stable (not sure if Office Hours is stable yet)

# Answer
> 3 votes
I couldn't get the Office Hours module to work in Drupal 7. I just went ahead and used the Field API to create a simple module that does what I need without a lot of overhead. If you're curious, I committed it to GitHub at adam-s/hours. I'll probably add more validation and jQuery to make it more user friendly as time goes on.

# Answer
> 1 votes
I would suggest the timefield module used together with the built-in 'add more' / 'add extra' fields functionality of data entry for Drupal fields in content types.

Download, install and enable the timefield module.

Add a field of type timefield to your content type.

Then configure to allow the user to add one or more fields of this type by going here on your site: `admin/structure/types/manage/YOUR CONTENT TYPE/fields/field_times` \- here there is an option where you can specify unlimited - which means no limit to the range of times you can add.

Where `YOUR CONTENT TYPE` is the name of your content type that you should insert here.

Then as an ordinary user, when you go to enter times when creating new content/editing existing content, you can add extra timefield fields for each different range of times. Another nice thing about time field is that it can be configured to provide checkboxes for each day where the opening times are the same - to save you having to enter in the same time for each day. See example here:

In the manage display for your content type, `admin/structure/types/manage/YOUR CONTENT TYPE/display` I recommend you choose the List of times Format setting for your timefield field as the other options, Duration and Calendar work but are not as readable in my opinion for displaying opening times, but experiment as you desire! If you do use List of times for your display you will find that this nicely (well in my opinion) lays out days where the opening hours are the same. See example here:

I also looked at opening\_hours and the 2 problems I had with this were: 1) no documentation and 2) the functionality for entering the times appears to be deliberately in a separate place from the other fields of the content type - not intuitive for some users perhaps. The functionality available through one of the tabs. I also looked at office\_hours and found this simply did not work (at time of writing) if hours for more than one day were entered - issue raised: https://drupal.org/node/2043237

Just an interest item, optional, only for your information: For even more advanced opening times that depend on certain times of the year, one might also be interested in the availability\_calendars and seeing how these could be made to interoperate for schedules that have irregularities (e.g. closed all of August, or closed on public holidays etc). I haven't tried anything with this availability\_calendars module yet but just thought I'd mention it, it's not necessary at all for to solve the question asker's problem here nor for other folks here.

---
Tags: 7, entities
---


title: Panel + views + taxonomy depth problem

text:
# Question
Title: Panel + views + taxonomy depth problem
following this tutorial I create a Panel Page for the taxonomy term to display all the content related to the taxonomy term and it works.

But I need to have in all the nodes related to the taxonomy terms in the url and children. So I sobstitute taxonomy term ID contex filter with taxonomy term ID (with depth) and do not work anymore -.-

This is the contex filter's setting

If I try this view block in view page \[putting 'taxonomy-name' as argument\] it works but not in the panel page.
Where is my mistake?

I don't know if this can help. This is the contex of panel page \[I setup the view to take argument from URL.. but maybe it can help\]

# Answer
You should try to add a "Content pane" display on the view instead of using a page display (enable "Views content panes" module). "Content pane" allows to set the argument input from the views settings. On the "argument input" you can select "From context" as source, and the required term context.

EDIT: Like I've wrote on the following comments, the correct contextual filter settings is:

1) Content: Has taxonomy term ID (with depth). Provide a default value: Taxonomy term ID from URL (Load default filter from term page). Specify validation criteria: Taxonomy term, Filter value type: Term ID

2) Content: Has taxonomy term ID depth modifier
> 0 votes

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


# Question
Title: How do I write an additional field formatter for an existing field
I would like to write a new field formatter for an existing field type. I don't want to replace any existing formatters but offer a new option.

Or am I better off using a theme\_preprocess\_field() to do minor alterations? But this seems to be harder to maintain and I'd like to keep my content editors options open (and in the GUI).

Can someone point me to an example of the proper way to do this?

# Answer
Personally I'd say a formatter is the better solution.

There are only two hooks you need to implement:

For example:

```
function MYMODULE_field_formatter_info() {
  return array(
    'my_formatter' => array(
      'label' => t('My formatter'),
      // The important bit...
      'field types' => array('field_type'),
    ),
  );
}

function MYMODULE_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $settings = $display['settings'];
  $element = array();

  if ($display['type'] == 'my_formatter') {
    foreach ($items as $delta => $item) {
      $element[$delta] = array('#markup' => $item['value']);
    }
  }

  return $element;
}

```

For a more in-depth look, download the Examples module and look at field\_example - there's plenty of code and documentation there to get you on your way.
> 14 votes

# Answer
you can develop a custom module or use "Custom formatters" module.

In the first case you have to write a module which implements some Drupal 7 hooks: `hook_field_formatter_info()`, `hook_field_formatter_view()` and `hook_theme()`. `hook_field_formatter_info()` Is used to declare the formatter type. This function returns an array with the formatter description. The key will be the formatter name and it will have an array with the label and the field types. After you have to implement `hook_field_formatter_view()` and `hook_theme()` in order to define the template. You can find more details about the Field Formatter API in the docs.

In the second case you can use Custom Formatters module which allows to create custom display formatters for every field. With this module you can create the formatter using custom PHP code or HTML code with tokens.

I suggest the second way because is very easy to use and to configure.
> 2 votes

---
Tags: entities
---


title: How to add a css class to view fileds

text:
# Question
Title: How to add a css class to view fileds
i have created a view block and added some fields to it,i want to change the style of those fields with css, is there a way that i can do it. "Thank you"

# Answer
> 2 votes
Click on the field you want to add a css class to, select style settings, and customize field html and check create a css class. Give it a name and simply add the class to the css file of your theme

# Answer
> 0 votes
If it's only one or two block displays of views, consider calling `template_preprocess_block()` in your `template.php` file, adding the class(es) you want to the block level, then styling the fields within the block using specificity in your CSS selectors. Example:

```
<?php
    function MYTHEME_preprocess_block(&$variables) {
        if (your condition here to target the blocks you want) {
            $variables['classes_array'][] = 'yourClass';
        }
    }
?>

```

While it would be best to have Drupal attach the CSS classes for you, a second option would be to use jQuery's `.addClass()` method, especially if it's only one or two blocks. Example:

```
$('#myBlock').addClass('myClass');

```

Hope that helps!

---
Tags: views
---


# Question
Title: Broken formatting while displaying both start and end date
I added Event content type in D7 and I have there Event **Start date**. I setup this field to collect an **End day** \+ it is collecting time and have option to check "All Day Event".

What I have in the exit when I created new Event is something like:

> ```
> Frida2013, 20-Sunda2013, 22, Frida2013, 20-Sunda2013, 22eptember Frida2013, 20-Sunda2013, 22, 2013 - h:ia(All day)-(All day)
>
> ```

When I go to Manage Display tab, I can set there for Event Date to display only Start Day for example and then this broken formatting disappears. But I need to be able to display both Start and End date.

Any suggestions appreciated. Thanks.

# Answer
> 0 votes
Juts found a solution. Please create custom formatting like this:

```
D, F d, Y (h:ia)

```

Key here is to wrap time in parentheses

> (h:ia)

after that trick formatting is fixed and looks something like:

> Sat, September 21, 2013 (All day) to Mon, September 30, 2013 (All day)

---
Tags: 7, datetime
---


# Question
Title: Drupal + Simpletest + Class Autoloading = FALSE?
Just a quick question which I couldn't Google : is class autoloading not "enabled" when running tests using SimpleTest?

I'm using the Drupal SimpleTest module, and I'm trying to instantiate a class which I have defined in files\[\] (in the .info) file. However, I just keep getting a message saying that the class could not be found.

# Answer
I assumed that all "autoloadable" files for the module I was testing would indeed be automatically loaded, but this seemed to be wrong.

I needed to add the following function to my testclass:

```
public function setUp() {
  parent::setUp('mta');
}

```

Please note that 'mta' is the module I'm testing, and which the "autoloadable" classes are defined for. I assume that if you need access to "autoloadable" classes defined for any other module, that you need to set up those modules too.
> 1 votes

# Answer
It should also be noted that unit tests and web tests behave differently. Unit tests tend to not have class loading set up.
> 0 votes

---
Tags: 7, testing
---


# Question
Title: Do we have Node Reference : Representative node similar to the Taxonomy term: Representative node
Using **Taxonomy term: Representative node** we can get a node that represents a taxonomy term. Similarly is there a way I can get a node that represents a particular node reference field.

Use Case : I have two content types College and Teacher. For each college, I want a teacher who was recently added to the college.

# Answer
The References module doesn't seem to provide a Views relationship like that. Here is one way to achieve the required functionality in your case:

1. Add a reverse Node Reference relationship to get teacher nodes referencing the college. This will get you all teachers for each college.
2. Implement `hook_views_query_alter()` and add the extra condition utilizing a subquery:

```
function mymodule_views_query_alter(&$view, &$query) {
  switch ($view->name) {
    case 'college_teachers':
      $expression = '
        field_college_node.nid = (
          SELECT n.nid
          FROM {field_data_field_college} fdfc
          INNER JOIN {node} n ON n.nid = fdfc.entity_id
          WHERE fdfc.entity_type = "node" AND fdfc.field_college_nid = node.nid AND n.type = "teacher" AND n.status = 1
          ORDER BY n.created DESC
          LIMIT 1)'
      $query->add_where_expression(0, $expression);
      break;
  }
}
```

(The Views-generated `field_college_node` alias is a bit misleading because in fact, it will reference the teacher node, not the college one.)
> 1 votes

---
Tags: nodes, database, views
---


# Question
Title: How would files be uploaded to a 2nd domain?
So I have a Drupal site on my company intranet, and when uploading files, it all goes to the default/files folder as normal, however when uploading video files specifically, the base url is different from the Drupal base, it's a second domain specifically created for hosting assets.

I.E.

Drupal base / source of all uploads except videos

```
server.domain.com

```

Source of videos

```
assetserver.domain.com/sites/default/files/movie.mp4

```

I have no access to the server outside of the Drupal back end, and I cannot find the settings for specifying a domain anywhere (within File settings, Media settings, etc). As far as I know, there is no mention of this 2nd domain (`assetserver`) anywhere within the drupal codebase or backend. I'm just wondering if there's a setting outside of Drupal that can be used to set this, for example in the .htaccess file or something along those lines?

Any insight from someone who has worked with similar issues will be appreciated.

# Answer
Remote stream wrapper may help...also look Media Mover module...and, at the end, take a look on THIS post...
> 0 votes

---
Tags: files, .htaccess
---


title: Change header style when users sign in

text:
# Question
Title: Change header style when users sign in
I am using the default template and I want the background color of the header change when a user signs in.

I know I will need to write a simple if statement like `if (user_is_logged_in()) { }` somewhere, but I don't know where to place it.

# Answer
Look at the body tag of your theme. Some themes add classes to it indicating whether or not you are logged in. If yours does, then you can do this via css by:

```
.logged-in #header
{
   background-color: #fff;
}

.not-logged-in #header
{
   background-color: #000;
}

```

If you don't have a body class that indicates logged in status, then you modify your page.tpl as user4035 suggested. There is no is\_user\_logged\_in function. Instead, it's

```
<?php
global $user;

if ( $user->uid ) {
  // Logged in user
}
else {
  // Not logged in
}
?>

```

Code Source - https://drupal.org/node/92218#comment-167984
> 3 votes

---
Tags: theming
---


title: Path Replacement Pattern - Views Module

text:
# Question
Title: Path Replacement Pattern - Views Module
I am using PathAuto to redirect user urls to the following pattern. `users/[user:name]`.

I have created a page using the views module which needs to show up as a tab on the user naviagation menu. Currently the PATH property for the page is set to `/user/%/seasons`.

Here is my issue.

My account is Uid=1, UserName = 'Declan'.

Pathauto renders that as '/users/declan' - which is what I want.

When I click on the 'Seasons' tab, the page is rendered, but the url is '/user/1/seasons'.

Is there any way to rewrite the PATH property in the view such that is will render '/users/declan/seasons'?

# Answer
Found the answer, the Sub-pathauto module does the job perfectly.
> 2 votes

---
Tags: views, path-aliases
---


# Question
Title: What is the variable for the human readable name of the node type?
In my node.tpl I have added `<?php print $type; ?>`. This gives me the machine name of the node type e.g. blog\_entry. What do I use to get the human readable form e.g. Blog entry?

Edit (Here is my current code)

```
<?php if ($display_submitted): ?>
  <div class="submitted"><div class="submitted-type submitted-item"><?php print $type; ?></div><div class="submitted-author submitted-item"><?php print $name; ?></div><div class="submitted-date submitted-item"><?php print $date; ?></div><div class="submitted-comments submitted-item"><?php print $comment_count; ?></div></div>
  <?php endif; ?>

```

# Answer
You can use the `node_type_load()` function to load up the node type object, and then extract the name:

```
$type_obj = node_type_load($type);
$name = $type_obj->name;

```

You can integrate with your current code like so:

```
<?php
  $type_obj = node_type_load($type);
  $human_readable_type = $type_obj->name;
?>

<?php if ($display_submitted): ?>
  <div class="submitted">
    <div class="submitted-type submitted-item">
      <?php print $human_readable_type; ?>
    </div>
  <div class="submitted-author submitted-item">
    <?php print $name; ?>
  </div>
  <div class="submitted-date submitted-item">
    <?php print $date; ?>
  </div>
  <div class="submitted-comments submitted-item">
    <?php print $comment_count; ?>
  </div>
</div>
<?php endif; ?>

```
> 8 votes

# Answer
You can look up this information using `entity_get_info()`. Here is a small code example of how to use this API call:

```
$content_type = 'blog_entry';
$entity_info = entity_get_info('node');
$human_name = $entity_info['bundles'][$content_type]['label'];

```

This call also returns lots of other useful information such as the fields attached to each bundle, but since it loads so much data it's probably better to use the solution Clive posted if you are going to be calling it every page load.

---

Expanding on Clives answer, if you would like to have the type accessible from the node template, add the following code to your `template.php` file inside your current themes file and ensure that you replace MY\_THEME with the name of your theme:

```
function MY_THEME_preprocess_node(&$vars){
    $type_obj = node_type_load($vars['type']);
    $vars['human_type'] = $type_obj->name;
}

```

Then anywhere inside your node templates you can use:

```
<?php print $human_type; ?>

```
> 4 votes

# Answer
D7 I use `node_type_get_name($node->type);`
> 3 votes

---
Tags: 7
---


# Question
Title: How do I change base URL when moving site from sub-directory to domain root?
I have developed a site in a sub-directory and now will be pointing a live URL to it. What do I need to do to ensure that the relative links in the menus etc will work under this new configuration. I have read that settings need to be changed in sites/default/settings.php however looking at the file it does not appear that a "base" URL is specified ... same with the .htaccess file under the root. This may be a fundamental question, but in WordPress for example having a new "base" URL requires a settings change otherwise relative links will end up pointing to a 404 page ... how is this handled in Drupal (7)

# Answer
> 1 votes
Unless you have made customizations to the URL-related settings in .htaccess or your settings.php, you won't need to update anything. Simply move your site, then clear the cache either via the "Clear Cache" button (on the Performance admin page), or the Drush utility, and you should be good to go.

---
Tags: uri
---


# Question
Title: Need to redirect Parent Taxonomy Term page to oldest child
I use the Views version of the taxonomy listing page. For performance reasons, I can't use a depth of 1 on the 'Taxonomy Term (depth)' contextual filter.

Unfortunately, for one taxonomy, ALL terms are a child of this one set of six terms (think Publication / Issues of a magazine). Is there a way I can, in my menu, link to the parent terms, yet have that listing page show only the nodes from the most recent child?

Otherwise, is there a way, in that View, to have an increased depth (1 vs 0) ONLY if there are no nodes for the particular term?

# Answer
So I figured this out, wasn't too complicated at all. Use hook\_menu. I didn't write my SQL using the Drupal DB API, but it works:

```
function ain_custom_menu() {

 $items = array();

  // Item1
  $items['taxonomy/term/218489'] = array(
    'title' => 'Title1',
    'page callback' => 'MYMODULE_find_newsletter',
    'page arguments' => array("218489"),
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
  );

  // Item2
  $items['taxonomy/term/218500'] = array(
    'title' => 'Title2',
    'page callback' => 'MYMODULE_find_newsletter',
    'page arguments' => array("218500"),
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;

}

function MYMODULE_find_newsletter($mytid) {
  $tid = db_query('SELECT max(tid) AS tid FROM taxonomy_term_hierarchy t1
    JOIN field_data_field_pubissue t2 ON t1.tid = t2.field_pubissue_tid
    JOIN node t3 ON t2.entity_id = t3.nid
    WHERE t1.parent = '.$mytid.' AND t3.status = 1')->fetchField();
  $latest = is_numeric($tid) ? 'taxonomy/term/' . $tid : '<front>';
  drupal_goto($latest);
}

```
> 0 votes

---
Tags: views
---


# Question
Title: Moving from Custom MySQL-Based Blog to Drupal
I currently have a database with the following schema:

Table: Articles Columns: ID, Title, Author, Content

Table: Authors Columns: ID, AuthorName, EmailAddress

Table: Categories Columns: ID, CategoryName

I'm interested in moving this over to Drupal. I do NOT actually need to preserve the authors or categories tables because we are revamping those sections in the migration. However I DO need to save certain rows (or all, if easier) of the articles table. This includes keeping the author ID linked to it. I'm willing to do manual queries in order to select which rows I want to move over to the new table, but I'm not sure exactly where I should do this. So my question is: How can I move these articles over to Drupal in the easiest, most seamless fashion?

# Answer
You can create nodes from external databases using the Feeds SQL module (requires Feeds). You should create a content type for the fields you want to import, and use the Feeds UI to select the external database table(s), add a query, and map the output to the fields in your content type.

Here are a couple of settings that you need:

Preparation: add your new source database to settings.php:

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'drupal_database',
      'username' => 'drupal',
      'password' => 'password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  'database_to_migrate' =>
  array (
    'default' =>
    array (
      'database' => 'database_to_migrate',
      'username' => 'migrateusername',
      'password' => 'password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
)

```

Now: go to the Feeds UI, and start configuring:

```
1. Basic - attach to - your new content type
   Import on submission - checked

2. Fetcher - click "Change" -> select "SQL fetcher", save

3. SQL Fetcher - click "Change" - select your source database

4. Parser - click "Change" -> select "SQL Parser", save

5. SQL parser - click "Change" -> Enter your query, select your database, save
   Verify that your query performed as expected, results are displayed.

6. Processor - select "Node Processor" for nodes

7. Node Processor - Settings: Here, you can choose the content type (again),
   the author associated with the new node, format, expiration, and other parameters.

8. Node Processor - mapping: Here, you have to map the fields from the sql query
   to the fields in your content type. After you save, you can map the next field

```

Since you only have a couple of users/authors, you could create accounts for them manually. In your SQL query, you can select the users as well as the content/title/etc., and the new articles will then be associated with the appropriate authors.

This has worked well for me with a limited number of nodes (\<1000). For large-number of nodes, I ran into time-out issues, and had to add a limit to the SQL query. Eventually, I just created a drush script to add the nodes from the command line (I had to add \>50,000 nodes).

Edited to add: I used this with Drupal 7. Please read the documentation for the modules for updated information: https://drupal.org/project/feeds, https://drupal.org/project/feeds\_sql
> 2 votes

---
Tags: migrations
---


title: facets appear "_empty_"

text:
# Question
Title: facets appear "_empty_"
I'm using the Apache Solr Search Integration and Facet API modules. I'm trying to implement facets for custom fields `publication_date`, `publication_author`, and `journal`, which are part of the content type `publication`.

These 3 fields are indexed successfully as `ss_date`, `ss_author`, and `ss_journal`. Furthermore, I can search against these fields on the default apachesolr search page. However, the facets for these fields show up as "\_empty\_". For example, when the search page loads, under the "publication\_author" facet header, one bullet item shows up as "\_empty\_ (10)", which to me means that the author field is being indexed successfully with value "NULL" or possibly literally "\_empty\_" for all 10 publication nodes. Code is below for just the author facet.

**define custom facets**

```
function HOOK_facetapi_facet_info(array $searcher_info) {
    $facets = array();
    // Facets are usually associated with the type of content stored in the index.
    if (isset($searcher_info['types']['node'])) {
        $facets['ss_author'] = array(
            'name' => 'ss_author',
            'label' => t('custom: author'),
            'description' => t('Shows the authors'),
            'field' => 'ss_author',
            'dependency plugins' => array('role'),
            'default widget' => 'links',
            'allowed operators' => array(FACETAPI_OPERATOR_AND => TRUE, FACETAPI_OPERATOR_OR => TRUE),
            'facet missing allowed' => FALSE,
            'facet mincount allowed' => FALSE,
            //'map callback' => 'not used for now',
            'max callback' => FALSE,
            'default sorts' => array(
                array('active', SORT_DESC),
                array('count', SORT_DESC),
                array('display', SORT_ASC),
            ),
        );
    }
    return $facets;
}

```

"ss\_author" is the name of the field added to the ApacheSolr document during indexing. If you'd like the code used to actually index these fields, let me know. Thanks very much!

# Answer
Facets, by their very nature, work best when you use them for 'select' type fields, not pure text. Facets work very well - and automatically - with taxonomy terms for example, because terms are re-used and it's easy to **group** based on select type fields.

Whenever I've wanted to use custom fields as facets, I've implemented them as terms (tagging) or select fields, and then they work properly.

So, I'm wondering - is that something you could do? Rather than setting up your fields as 'text', could you set them up as select-type fields (whether it's tags, which don't have to be predetermined or select options which you have to enter in advance)? That type of field is easier to **GROUP** by - which is what facets are really doing.

It may not be an option, but I have a feeling that would resolve your issue.

Let us know how this gets resolved!
> 1 votes

# Answer
I wasn't properly storing the values of my custom fields. Specifically, in `hook_apachesolr_index_document_build`, I was trying to get the value of "publication\_author" as

```
$author = $entity->field_publication_author;

```

while the actual value should be retrieved with

```
$author = $entity->field_publication_author[$entity->language][0]['value'];

```

The full hook follows:

```
function hook_apachesolr_index_document_build(ApacheSolrDocument $document, $entity, $entity_type, $env_id) {
    $author = $entity->field_publication_author[$entity->language][0]['value'];
    // get other fields
    $document->addField('ss_author', $author);
    // add other fields to document
}

```

Also remember you need `hook_apachesolr_query_alter` as well:

```
function hook_apachesolr_query_alter($query){
    $query->addParams(array('fl' => array('ss_author')));
}

```
> 1 votes

---
Tags: 7, search
---


# Question
Title: Views with both menu and jump menu taxonomy terms as contextual filters
I have a page view with a **category** taxonomy menu and a **city** jump menu. I want them to work together so that if the view shows all content and a user clicks on a **category** in the menu, the view will be fitered by **category** and if the user chooses a **city** in the jump menu, the view will be filtered by city. If a **category** has already been chosen and the user selects a **city**, the view should be filtered by both **category** and **city** and vice versa.

I know this should be possible but I don't know where to start or what the best way of doing it might be. If the best solution requires coding, I am capable of doing it.

# Answer
> 1 votes
I'm editing my response based on your latest comment!

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

One way I think you can do what you're trying to do is incorporate facets into your page with those specific taxonomy terms placed on the page as **facets**.

You'd need to use the Facet API module and the Faceted Navigation for Search module. You can see the module page for an example interface - do you see how the screenshot on the module page shows a site where you can narrow the results based on fields/facets on the side? I'm adding a screenshot from a site of my own that I've set up to use facets, though it's themed very differently. The other great thing about facets is that they show you how many nodes you have tagged with the fields/terms you want to filter on.

Essentially, what facets do is give you the ability to FILTER/narrow listings based on select-type fields or taxonomy terms. You can combine these filters, just as you describe.

I've only used the facet api with solr search, not core drupal, so I don't know if I can help you much on the exact setup, but perhaps this can at least guide you into another potential way to achieve your goal (if it's not overkill to learn all about facets and how you may be able to do this through search).

Let us know how it works out or if you figure it out!

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


# Question
Title: want to display values of content type Article in a page
I have following fields in my content type Article:

Year: \[have values - 2011,2012,2013,2014,2014,2016\] Volume: \[have values - 01,02,03,04,05\] Issue: \[have values - 1,2,3,4,5\]

Title: \[some value\] Description: \[some text\]

Now I want to display fields values like order below in views-view--archives--page.tpl.php

2013: \[Volume3: Issue1, Issue 2, Issue 3\] 2012: \[Volume2: Issue1, Issue 2\]

# Answer
Maybe you can write a custom template or a custom theme function to output the fields, you will have to play with delta. You can also create multiple content types and link them with a relation field to create the hierarchy. You can also use a specific module that handles this kind of dimensional representation like tablefield or sheetnode.
> 0 votes

---
Tags: nodes
---


title: Dynamic Form Generation

text:
# Question
Title: Dynamic Form Generation
I need to create a web form that functions as a skills checklist. The user will select a 'specialty' from a drop down and based upon that selection, a list (with as many as 50 radio selections) will be presented to the user. I'm trying to figure out the best way to do this in terms of performance and maintainability.

1) I can write the skills list as a huge single form and then use jQuery to to show and hide the elements based upon the drop down selection. However, this may lead to very long page load times since there may be upwards of 1000 fields in the form.

2) I could gather the 'specialty' information at an earlier time, then load it at run time and based upon that, run another query for all the fields I will need from the database and build the form in a foreach loop. This means that there will be upwards of 30 queries in the form and an extremely complex submit handler to insert all of the entered data into the database.

Any thoughts on the best way to accomplish this? This is part of a large web application with many different sections and performance and maintainability is a huge consideration.

Thanks

# Answer
> 0 votes
Do you know that Webform now supports `conditional` form items from the now merged webform conditionals module?

You can then manage this form like any drupal webform and show/hide child pieces of the form based on selection rules. If your form is huge good luck the conditional page/logic settings can get huuuge and cumbersome.

If you want to this in `php code` yourself I recommend this tutorial using the Ctools based Multistep Form. I've made multi-step forms using native drupal node forms -- just the stepping logic is very ugly. This is clear and precise using a multi-step ctools form.

You could even show/hide stuff I believe on 1 page of the form usig FAPI #states API. A tutorial explaining #states provided by Shane Graham is on this blog post. Also review this for more complicated XOR type logic in forms here on d.stackexchange: Multiple Values to Trigger #states

---
Tags: forms
---


# Question
Title: Do translated taxonomy terms have different tid's?
As per title; or are they translated in the same way user interface elements are handled?
Im using Drupal 7 btw.

# Answer
> 1 votes
No if you choose to localize your terms. Edit your vocabulary and tick this option: "Localize. Terms are common for all languages, but their name and description may be localized."

---
Tags: taxonomy-terms
---


title: Make drupal theme responsive

text:
# Question
Title: Make drupal theme responsive
How do i make a custom drupal theme i already have responsive. I mean the easiest way to do this?

What about integrating my current custom theme on top of a drupal base theme like omega?

# Answer
> 2 votes
You can retrofit your custom theme to make it responsive. Emma Jane Hogbin has written a great tutorial for this (available for purchase at http://www.responsivewebdesignguild.com/). I have used it to retrofit a couple of drupal sites that use the zen base-theme, the principles should work for any theme.

The basic principles/steps are:

Add a new style sheet to your css directory (and .info file) Determine break points in your theme depending on the content - what do you want to display wide - medium - narrow views, how do you want to reorganize the page Add media queries to the stylesheet reflecting the break points, like this:

```
@media screen and (max-width: 960px) {
  #main {width: 100%;}
}
@media screen and (max-width: 750px) {

}
@media screen and (max-width: 500px) {

}

```

Basically, adjust the width/etc. for the elements and width determined earlier. The navigation menu is a special case. At the max-width that makes it most likely that the user is using a table or a phone, the menu should be "fat-finger" enabled, by changing the ul and li styles so that each link has a larger width and height. For me, links changing from horizontal to "one link per line with padding" works best.

Then, copy the core html.tpl.php file into your theme/templates directory, and add the following to end of the header section:

```
<meta name="viewport" content="width=device-width; initial-scale=1.0" />
<meta name="HandheldFriendly" content="true" />
<meta name="MobileOptimized" content="width" />

```

Emma Jane demonstrated this approach for the Domicile theme, the result is available at: https://drupal.org/project/domicile\_responsive

---
Tags: theming
---


# Question
Title: How to theme table inside vertical tabs?
I have a simple test module:

```
function tabletabs_menu() {
  $items['tabletabs'] = array(
    'title' => 'Table Tabs',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('tabletabs_form'),
    'file' => 'tabletabs.module',
    'access arguments' => array('admin'),
  );

  return $items;
}

function tabletabs_form($form, &$form_state) {
  $form['tabs'] = array(
    '#type' => 'vertical_tabs',
    '1' => array (
      '#type' => 'fieldset',
      '#title' => 'Tab 1',
      'a' => array(
        'x' => array (
          '#markup' => '1-a-x',
        ),
        'y' => array (
          '#markup' => '1-a-y',
        ),
      ),
      'b' => array(
        'x' => array (
          '#markup' => '1-b-x',
        ),
        'y' => array (
          '#markup' => '1-b-y',
        ),
      ),
    ),
    '2' => array (
      '#type' => 'fieldset',
      '#title' => 'Tab 2',
      'a' => array(
        'x' => array (
          '#markup' => '2-a-x',
        ),
        'y' => array (
          '#markup' => '2-a-y',
        ),
      ),
      'b' => array(
        'x' => array (
          '#markup' => '2-b-x',
        ),
        'y' => array (
          '#markup' => '2-b-y',
        ),
      ),
    ),
  );
  return $form;
}

```

It gives me:

This is pretty much expected result. Now, if I add:

```
function tabletabs_theme() {
  return array(
    'tabletabs_form' => array(
      'render element' => 'form',
      'file' => 'tabletabs.module',
    ),
  );
}

function theme_tabletabs_form($variables) {
  $form = $variables['form'];
  $output = '';
  foreach ( element_children($form['tabs']) as $id_tab ) {
    if(is_int($id_tab)) {
      // Initialize the variable which will store our table rows.
      $rows = array();

      // Iterate over each element in our $form['tabs'] array.
      foreach ( element_children($form['tabs'][$id_tab]) as $id_row ) {
        $classes = array('');

        $rows[] = array(
          'data' => array(
            drupal_render($form['tabs'][$id_tab][$id_row]['x']),
            drupal_render($form['tabs'][$id_tab][$id_row]['y']),
          ),

          'class' => $classes,
        );
      }

      $header = array(t('x'), t('y'));

      $table_id = 'tabletabs';

      $output .= theme('table', array(
        'header' => $header,
        'rows' => $rows,
        'attributes' => array('id' => $table_id),
      ));
    }
  }
  $output .= drupal_render_children($form);
  return $output;
}

```

this cannot work. I'm rendering tables before vertical tabs, so of course they appear before, too:

But how do I render them to appear inside vertical tabs instead? I'm sure I'm missing something little and obvious (once you know it).

# Answer
Not sure if it's the right way to do, but you would create a new form element with the table, instead of adding a table directly.

```
function theme_tabletabs_form($variables) {

      // ....

      $header = array(t('x'), t('y'));

      // each ID has to be unique
      $table_id = 'tabletabs' . '-' . $id_tab;

      // create a new form element with the table
      $form['tabs'][$id_tab]['table']['#markup'] = theme('table', array(
        'header' => $header,
        'rows' => $rows,
        'attributes' => array('id' => $table_id),
      ));
    }
  }
  $output .= drupal_render_children($form);
  return $output;
}

```

**Option #2:**

```
function theme_tabletabs_form($variables) {

      // ....

      $header = array(t('x'), t('y'));

      // each ID has to be unique
      $table_id = 'tabletabs' . '-' . $id_tab;

      // set the table as a value of each vertical tab item
      $form['tabs'][$id_tab]['#value'] = theme('table', array(
        'header' => $header,
        'rows' => $rows,
        'attributes' => array('id' => $table_id),
      ));
    }
  }
  $output .= drupal_render_children($form);
  return $output;
}

```

This will give following output:
> 3 votes

---
Tags: 7, theming, forms
---


# Question
Title: how to modify print--mail--node--node-type.tpl.php
I installed the module https://drupal.org/project/print , drupal 7x , but now we need to get control over each variable on the display node. I mean print out some variables content and other NO, also print it in two columns. well make a table is not a problem. the PROBLEM is how to get the variable content in order to print out?

I have this code, works, but print all the content by default, in an UGLY way.

I will appreciate ...Any ideas or suggestions.... please sent to me a basic example...

# Answer
I think that you can do this by changing display of content type. Just go to the *Manage display* page of the content type you print; at the bottom, expand *Custom display settings* and select *Print*. After saving, you'll see the *Print* tab (next to tabs like *Default* and *Teaser*).

Now you can change the page display settings. You can also change the page style using CSS.
> 1 votes

---
Tags: 7, nodes
---


title: Apply Modules to Previous Posts

text:
# Question
Title: Apply Modules to Previous Posts
I've recently imported my articles from another database (custom format) and I'd like to apply modules (like Colorbox and other such output-related modules) to those previous posts. Is the standard behaviour to allow this sort of thing, or am I supposed to manually adjust all previous posts?

I've only ever worked with WordPress before, and their plugins work on all articles (past and new).

# Answer
> 1 votes
For colorbox to work on your new posts, you need to edit the content type(s) of your new posts

```
Home » Administration » Structure » Content types » YourContentType

```

Click on "Manage Display". Here, you can choose the format "Colorbox" for the image field (and click that modal to customize, etc). It will be applied to all nodes of that content type.

Of course, you'll first have to install the colorbox module and library.

The same principle applies to other modules.

About posts/nodes and content types:

Typically, there are only very few content types configured in Drupal - by default there are "article" and "basic page", but you can create more as you need them.

You would import your old post into drupal using one or very few different content types.

The changes need to be done for the content type, meaning they'll get applied to all nodes (posts) in that content type.

You need to look which content type to imported your nodes (posts) into. When you go to http://www.example.com/admin/content, you see a list of your nodes, and in the "Type" column the content type.

Then you go to http://example.com/admin/structure/types/manage/yourcontenttype/display and manage the display as outlined in my answer.

For the article content type, this would be: http://example.com/admin/structure/types/manage/article/display

Of course, you need to change example.com to your url.

---
Tags: 7, migrations
---


# Question
Title: How to create independent sections, which consits of menu and more pages automatically
I have little problem with creating independent sections on the web.

I have content type named project. It is basically landing page, which has own menu and this menu can link multiple simple pages. These projects have simillar structure, on every on them is page like timeline, news & events... Now when I want to create new project, I need to create new project, than create multiple simple pages, create menu, add menu to this project and so on. It is really complicated. Is there any way how can this be automatized?

Example: I will create new project, and menu and simple pages will be created automatically.

# Answer
Try with field collection module and divide groups of fields in sections as explained in field collection module documentation. You will get what you want!
> 0 votes

---
Tags: routes, 7
---


# Question
Title: Organize node file attachments into groups
I have a content type with multiple file attachments to download. Is there a module to give authors the ability to divide all the attachments into groups, writing a title for every group, just like they can reorder and name them in edit mode? The final node display should be something like this:

```
Group Title 1
. File n.1
Group Title 2
. File n.2
. File n.3

```

I've been searching for a while and found FileTree, but it's too complicated. Files shouldn't be managed physically, just displayed in groups.

Thanx in advance.

# Answer
> 0 votes
You can use Field group module. Create multi-value field group, with single-value *Group title* sub-field and multi-value *File* field inside. That's pretty much all.

---
Tags: nodes, files
---


# Question
Title: How to style map popup from GMap module?
Does anyone know where I can find, or does anyone have, a solid explanation of how to style the popup that GMap provides when you click on a map marker? I've seen it done on other sites using the GMap module, but I can not for the life of me figure out how to style it myself.

I've done some searching around and found infobubble.js, apparently code made by Google to help with the styling, however I can't figure out how to apply it to Drupal or how to use it.

Any help would be appreciated, I'm at my wits end with this one.

This is Drupal 7 by the way, and the newest version of the GMap module.

# Answer
> 1 votes
infobubble.js is available as a patch: Add more theming options to popup bubble by using infobubble library plugin for Gmap module.

Have a look at it as it allows you to modify several parameters of the popups.

> **shadowStyle** \- Options: 0 (no shadow), 1 (default shadow), 2 (sharp shadow)
> **padding** \- Like the css property, the padding of the bubble.
> **borderRadius** \- Like the css property, the radius of the bubble's corners.
> **borderWidth** \- Like the css property, the width in pixels of the border.
> **borderColor** \- Like the css property, the hex or rgb color of the border.
> **backgroundColor** \- This is the background of the content of the bubble, but NOT the entire bubble itself.
> **bubbleBackgroundClassName** \- A css class for the entire bubble.
> **minWidth** \- Like the css property, the minimum width of the bubble.
> **maxWidth** \- Like the css property, the maximum width of the bubble.
> **minHeight** \- Like the css property, the maximum height of the bubble.
> **arrowSize** \- The width of the pointer arrow. NOTE: if you choose an arrow style that only uses half of the arrow, this number will be twice as wide as your arrow at its widest point.
> **arrowPosition** \- The percent from the left of the bubble where the arrow will appear. arrowStyle - Options: 0 (full triangle), 1 (half triangle leaning left), 2 (half triangle leaning right)
> **closeImage** \- The url of the image to use as the close button for the bubble An example of most of these options can be seen on the infobubble examples page.

---
Tags: theming, google-maps
---


title: How can I create an ajax on/off toggle?

text:
# Question
Title: How can I create an ajax on/off toggle?
I am trying to create a simple on/off link using jquery and ajax. Basically what I want to to is add a link to a page that when clicked will insert a row into my database and update the text of the link. Then when clicked again, that record will be deleted from the database.

So far everything works as expected but the problem is that the second time the link is clicked, the record is deleted like it should, but the page refreshes and redirects to the homepage.

I am following the "plus 1 vote widget" example from Pro Drupal Development and am trying to alter the code to suit my needs. Following is my .js file.

```
$(document).ready(function() {
  $('a.toggle-visibility-links').click(function() {
    var parentDiv  = $(this).parent();
    var toggleSaved = function (data) {
      $(parentDiv).html(data.toggleon);
    }
    $.ajax({
      type: 'POST',
      url: this.href,
      dataType: 'json',
      success: toggleSaved,
      data: 'js=1'
    });
  return false;
  });
});

```

Here is my "toggle\_visibility" module code

```
/**
 * Implementation of hook_menu().
 */
function toggle_visibility_menu() {
  $items = array();
  $items['toggle-visibility'] = array(
    'page callback' => 'toggle_visibility_toggle',
    'access arguments' => array('toggle profile'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/*
 * page callback
 */
function toggle_visibility_toggle() {
  global $user;
  $toggle_sql = "SELECT * FROM {toggle_visibility} WHERE uid = %d";
  $toggle_result = db_query($toggle_sql, $user->uid);
  $num = mysql_num_rows($toggle_result);

  if (!$num) {
    db_query('INSERT INTO {toggle_visibility} (uid, visible) VALUES (%d, %d)', $user->uid, 1);
  } else {
    db_query('DELETE FROM {toggle_visibility} WHERE uid = %d', $user->uid);
  }

  if (!empty($_POST['js'])) {
    drupal_json(array(
        'toggleon' => '<a href="/toggle-visibility">Toggle My Profile On</a>'
        )
    );
    exit();
  }

  //UPDATE THIS TO RETURN TO THE SAME PAGE
  $path = drupal_get_path_alias('node');
  drupal_goto($path);
}

/**
 * Implementation of hook_theme().
 */
function toggle_visibility_theme() {
  return array(
    'toggle_visibility_link' => array(
      'arguments' => array(),
    ),
  );
}

/**
 * Return a message for no results
 */
function theme_toggle_visibility_link() {
  drupal_add_js(drupal_get_path('module', 'toggle_visibility') . '/toggle_visibility.js');
  global $user;
  $toggle_sql = "SELECT * FROM {toggle_visibility} WHERE uid = %d";
  $toggle_result = db_query($toggle_sql, $user->uid);
  $num = mysql_num_rows($toggle_result);

  if ( $num == 0 ) {
    $link = '<a href="/toggle-visibility" class="toggle-visibility-links">Toggle My Profile Off</a>';
  } else {
    $link = '<a href="/toggle-visibility" class="toggle-visibility-links">Toggle My Profile On</a>';
  }
  return $link;
}

```

Not sure what I'm missing.

Thanks!

# Answer
> 1 votes
In the javascript you should format the data as an object:

```
data: 'js=1'

```

replaced with

```
data: {js: 1}

```

The problem with the redirect is most likely an JS error caused by the returning value of the ajax callback. To be able to spot it you can hardcode the url in development and change the link simple be `<a href="#">xx</a>`, that would prevent a new page from loading in case of JS errors and would give you the possibility to read the error log from tools like firebug. Another options would be to insert breakpoints in your JS code, which can be a bit more tricky.

# Answer
> 0 votes
Hope this will help you,

In Drupal 7,

* You can use **ctools** for your requirement. No need to write extra JS for that. Just need to include ctools ajax, it will be done.
* After enabling the ctools, it can be done using ctools\_ajax\_text\_button which render text as a link.

Steps

* Generate the link

```
function create_link($id) {
  ctools_include('ajax');// Include the CTools tools that we need.
  if (!$id) {
    return;
  }
  if ($id)) {//Check for previous status(means already deleted?)
    $output = ctools_ajax_text_button(t("OFF link"), 'toggel/nojs/link/' . $id . '/0', t("OFF link"));
   //if you dont want the OFF as link then comment above Line and uncomment below Line
    //OR $output .= 'OFF';//without link
  }
  else {//not yet deleted
    $output = ctools_ajax_text_button(t("ON link"), 'toggel/nojs/link/' . $id . '/1', t("ON link"));
  }
  $link = "<div id='#toggle-link-" . $id . "'>";//must have unique ID for replacement
  $link .= $output;
  $link .= "";
  return $link;
}

```
* Create menu

```
$items['toggel/%ctools_js/link/%/%'] = array(
  'title' => 'Toggle',
  'page callback' => 'toggle_link',
  'page arguments' => array(1, 3, 4),
  'access callback' => TRUE,
  'type' => MENU_CALLBACK,
);....
 return $items;

```
* Toggle link callback

```
function toggle_link($js, $id, $status) {
  global $user
  // Include the CTools tools that we need.
  ctools_include('ajax');
  $output = '';
  if ($status == 0) {//ON link
    $output .= ctools_ajax_text_button(t("ON"), 'toggel/nojs/link/' . $id . '/1', t("ON LINK"), 'processed-wod-click');
  }
  elseif ($status == 1) {//OFF link
    //**mysql quere goes here**
    //you can have revert link if you like else send a html without link
    $output .= ctools_ajax_text_button(t("OFF"), 'toggel/nojs/link/' . $id . '/0', t("OFF link"), 'processed-wod-click');//OFF link
    //if you dont want the OFF as link then comment above Line and uncomment below Line
    //OR $output .= 'OFF';//without link
  }
  if ($js) {
    $commands = array();
    $commands[] = ajax_command_html("#toggle-link-$id", $output);
    print ajax_render($commands);
    exit;
  }
  else {
    return $output;
  }
}

```

Note:

Make changes as per your requirement.

---
Tags: javascript, ajax
---


# Question
Title: Ubercart checkout page country select overrules my attached javascript file
I have an ubercart checkout page with different payment methods for different countries. So when you change your country, it should show a different set of payment options. This is done by a jquery script, which fires if the Country input field changes. And this script works, as I can see when debugging the script with firebug/chrome developper kit.

However, shortly after that, ubercart decides to rebuild the whole payment methods checkout pane, and thus the jquery script becomes obsolete. How can I let my jquery script run after or again when the whole payment methods list is 'rebuild' or altered?

An example can be found at http://curvefever.com/cart/add/e-p1034\_q1-ipremium3months?destination=cart/checkout

Best regards,

Geert

Module code: I use it as follows (in uc\_moneybookers\_form\_alter):

```
if ($form_id == 'uc_cart_checkout_form') {
    $form['#attached']['js'] = array(
      drupal_get_path('module', 'uc_moneybookers') . '/CheckPaymentOptions.js' => array(
        'type' => 'file',
      ),
    );
  }

```

Jquery:

```
(function ($) {
var CheckPaymentOptions = CheckPaymentOptions || {};

CheckPaymentOptions.init = function() {
setDefaultOptions();
handleAddress("b");

$("#edit-panes-billing-billing-country").change(function() {
  handleAddress('b');
});

$("#edit-panes-billing-billing-address-select").change(function() {
  setTimeout("handleAddress('b')", 100);
});

$("#edit-panes-billing-copy-address").click(function() {
  var t = setTimeout("doIfChecked()", 100);
});
};

function handleAddress(paneFrom) {
if (paneFrom == "b") {

  var country = parseInt($("#edit-panes-billing-billing-country").val());
} else {
  var country = parseInt($("#edit-panes-delivery-delivery-country").val());
}
setDefaultOptions();
showForCountry(country);
};

function doIfChecked() {
var checked = $("#edit-panes-billing-copy-address").attr("checked");
if (checked) {
  handleAddress("d");
} else {
  handleAddress("b");
}
};

function setDefaultOptions() {
$('input[id*=moneybookers]').parent('div').hide();
$('input[id$=moneybookers]').parent('div').show();
$('input[id*=moneybookers-cc]').parent('div').show();
};

function showForCountry(num) {
switch(num) {
  case 276:
    $('input[id*=moneybookers-sft]').parent('div').show();
    $('input[id*=moneybookers-did]').parent('div').show();
    $('input[id*=moneybookers-gir]').parent('div').show();
    break;
  case 56:
    $('input[id*=moneybookers-sft]').parent('div').show();
    break;
  case 250:
    $('input[id*=moneybookers-sft]').parent('div').show();
    $('input[id*=moneybookers-gcb]').parent('div').show();
    break;
  case 528:
    $('input[id*=moneybookers-sft]').parent('div').show();
    $('input[id*=moneybookers-idl]').parent('div').show();
    break;
  case 756:
    $('input[id*=moneybookers-sft]').parent('div').show();
    break;
  case 826:
    $('input[id*=moneybookers-sft]').parent('div').show();
    $('input[id*=moneybookers-vsd]').parent('div').show();
    $('input[id*=moneybookers-mae]').parent('div').show();
    $('input[id*=moneybookers-slo]').parent('div').show();
    $('input[id*=moneybookers-vse]').parent('div').show();
   break;
  case 40:
    $('input[id*=moneybookers-sft]').parent('div').show();
    $('input[id*=moneybookers-eps]').parent('div').show();
    $('input[id*=moneybookers-mae]').parent('div').show();
    break;
  case 208:
    $('input[id*=moneybookers-dnk]').parent('div').show();
    break;
  case 702:
    $('input[id*=moneybookers-ent]').parent('div').show();
    break;
  case 100:
    $('input[id*=moneybookers-epy]').parent('div').show();
    break;
  case 246:
    $('input[id*=moneybookers-so2]').parent('div').show();
    break;
  case 752:
    $('input[id*=moneybookers-ebt]').parent('div').show();
    break;
  case 380:
    $('input[id*=moneybookers-psp]').parent('div').show();
    $('input[id*=moneybookers-csi]').parent('div').show();
    $('input[id*=moneybookers-vse]').parent('div').show();
   break;
  case 616:
    $('input[id*=moneybookers-pwy]').parent('div').show();
    break;
  case 372:
    $('input[id*=moneybookers-lsr]').parent('div').show();
    break;
  case 616:
    $('input[id*=moneybookers-pwy]').parent('div').show();
    break;
  case 36:
  case 554:
  case 710:
    $('input[id*=moneybookers-pli]').parent('div').show();
    break;
  case 724:
    $('input[id*=moneybookers-vse]').parent('div').show();
    break;
}
};

$(document).ready(CheckPaymentOptions.init);

}(jQuery));

```

# Answer
> 0 votes
You made one mistake. See Managing JavaScript in Drupal 7 \- you should make your code a behavior. That way, it will be run for every new element that appears on page. Don't forget to use `context` where needed. Using `$(document).ready()` directly is strongly discouraged for compatibility reasons, and your case looks like perfect example of a problems that may arise when you do.

---
Tags: javascript, ubercart
---


# Question
Title: Drupal 7: Cron claims webform module function to be undefined
I cant really figure this out.

I have a module which interacts with the webform module which just works perfectly fine.

But now I wanted to create a cron which updates certain submissions, but the cron function claims that suddenly the webform function `webform_get_submission` is undefined although all other mymodule functions use webform functions without any issues. How come?

```
// a whole lot functions which use webform functions
// [...]

function mymmodule_cron() {
    $conf = mymmodule_defaults();

    // check cron run
    if(true /* for testing */){

        // set writable User
        global $user;
        $original_user = $user;
        $old_state = drupal_save_session(FALSE);
        $user = user_load(1);

        // fancy sql statement
        $sql = array();
        // [...]
        $sql = join(" ",$sql);
        $result = db_query($sql);

        $queue = DrupalQueue::get('mymmodule_cron_archiveanon');

        foreach ($result as $row) {
            $row->anon = true;
            $queue->createItem($row);
        }

        // restore default user
        $user = $original_user;
        drupal_save_session($old_state);
    }

}

function mymmodule_cron_archiveanon_wrapper($item){
    $node = node_load($item->nid);

    if( function_exists('webform_get_submission')) {
        die("Yep.");
        // $submission = webform_get_submission($item->nid, $item->sid);
    }
    else {
        die("Nope.");
        // dies here
    }

    // custom function
    // mymmodule_contract_archive($node, $submission, $item->anon);

}

```

# Answer
That function is in a file that isn't included by default; you just need to include it yourself:

```
module_load_include('inc', 'webform', 'includes/webform.submissions');

```
> 4 votes

---
Tags: webforms, cron
---


title: "Taxonomy with depth" view

text:
# Question
Title: "Taxonomy with depth" view
I have a taxonomy tree like this:

* balls
    + basketball
        - color
            * red
            * green
    + volleyball
        - color
            * red
            * green

If a Taxonomy term has children, I want to show them; if there aren't children I want to show the nodes associated with the taxonomy term.

My view settings are the following.

This is similar to Show all child nodes of a taxonomy term D7, but I cant get it to work.

I use *Content: Has taxonomy terms (with depth)*, and I set the depth to 1. It doesn't work as expected.

# Answer
> 0 votes
You need Taxonomy Menu Trails module if you have a nested menu tree with taxonomy terms. Try this: https://drupal.org/project/taxonomy\_menu\_trails

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


# Question
Title: how to filter and show fields of content types in custom page tpl.php file
I have the following fields in content type ‘Articles’

Year: Volume: Issue: Title: Description: Upload file:

Now I want to create a custom pages tpl.php and categorized based on Year, Volume, Issue. So the output should be like below. On clicking issues, it should display the all the posts. (2013/volume 3/Issue 1)

2013 Volume3 – Issue1, Issue 2

2012 Volume 2 – Issue1, Issue 2, Issue 3

2011 Volume 1 – Issue1

# Answer
> 1 votes
Instead of modifying any template files, you should most probably be looking into the Views module, a module that, per its project page, is useful for a variety of tasks, one of which seems particularly on point here:

> You want a monthly archive similar to the typical Movable Type/Wordpress archives that displays a link to the in the form of "Month, YYYY (X)" where X is the number of posts that month, and displays them in a block. The links lead to a simple list of posts for that month.

# Answer
> 0 votes
I could be misreading your question, but it sounds like what you want is a view. To do this you will need the Views Module. Once it is installed (**Modules \> Install New Module**), you will create a new view (go to **Structure \> Views \> Add New View**); you can choose to display it as a page, a block, or both. Then, choose to return fields, pick the fields you want from your Article content type, and apply the proper sorting and grouping to get what you need.

If you want to use a `tpl.php` file to change the markup of your view results, check out this page on views template files.

Hope that helps!

---
Tags: theming, nodes
---


title: Spamicide field still visible

text:
# Question
Title: Spamicide field still visible
To prevent spambot making fake user accounts I've installed Spamicide.

I've enabled the module Spamicide (7.x-1.0-beta3) and enabled the field for form\_id user\_register\_form, filled in a Spamicide directory and chose a custom FORM FIELD NAME.

Now when creating a new account I still see a empty field with a description: *"To prevent automated spam submissions leave this field empty"*. I was expecting that this was hidden by CSS?

Also the directory name I've setup can't be found, is it not created by itself?

The flooding of spambots creating fake accounts is stopped, but the empty field and belonging message looks stupid for real users.

Can you tell me if I did setup something wrong or if this could be an bug?

# Answer
It's not really a bug. Simply hide it in your theme instead. Just try to use technique a bit less obvious than `display: none;` as many bots know it already. Note that newest version of Spamicide module (7.x-1.0-beta3 at the moment of posting) does not even provide CSS file. All it does is:

```
/**
 * #post_render callback on the spamicide field. This will wrap the field
 * in a div so it can be hidden with CSS.
 *
 */
function _spamicide_field_post_render($content, $element) {
    return '<div class="' . _spamicide_get_css_class($element['#name']) . '">' . $content . '</div>';
}

```

See line 81 of `spamicide.inc`.
> 1 votes

---
Tags: 7, advertising
---


# Question
Title: How can I get form_ids for all forms my module implements?
I have a custom contact module that we periodically add new forms to - how can I get a list of all forms implemented by this module?

I'm integrating mollom and I want to just loop through all my forms in hook\_mollom\_form\_list().

# Answer
Forms aren't implementations of anything as such, they're just plain PHP functions that happen to return a certain structure by convention. There's no registry of forms or anything like that, and the module that a form is defined in isn't tracked anywhere (it's not information that Drupal needs). Form functions don't even have to be named in any particular way.

There's also `hook_forms()` which allows you to map multiple form IDs to a single form callback function, so that's an extra layer of complexity that would need to be handled somehow.

I can't think of a single reliable way you could get that information through code. Well, I'm sure you could use reflection to write something very specific to your module, provided your own form functions follow a predictable naming convention; but as far a generic solution goes, I'm 99.9% sure it isn't possible. Unless there's a creative way around that I'm just not thinking of.

If it's just for this single module, why not just write a function which returns an array of all the known form IDs. Then when you add a new form, update that function manually. It will be much easier than implementing the reflection code to do this.
> 4 votes

---
Tags: forms, advertising
---


title: Secondary menu links

text:
# Question
Title: Secondary menu links
I have a main menu with links: menu1 menu2 menu3 menu4

When entering the menu1 I want to display a secondary menu with links: sub-menu1 sub-menu2 sub-menu3

and sub-menu1 to be activated as a default. Every sub-menu has to have a separate page, because in every sub-page the wallpaper will be different.

When entering the sub-menu2, there will be different content, wallpaper, the chosen sub-menu will be activated and also his parent menu, in this case menu1.

How can I do this?

# Answer
Seems all you need is normal menu 2 levels deep. Use Menu Block for greater control what to display where.

Make sub-menu1 and menu1 menu elements to point to the same node to get "sub-menu1 to be activated as a default" requirement.

For a background, just add background field to your content type, simple as that.
> 0 votes

# Answer
you can use menu\_tree to override your menu :

try this code in your template.php :

```
function THEMENAME_menu_tree__MACHINENAME($variables) {
$menuTree = menu_build_tree('MACHINENAME');
$output = '<ul id="nav">';
foreach ($menuTree as $item)
{
    $output .= '<li>' . $hasSub;
    if (count($item['below']) > 0)
    {
        $output .= '<ul class="sub-menu">';

        foreach ($item['below'] as $subItem)
        {
          $output .= '<li class = "'.$class.'"><a href="' . url($subItem['link']
          ['link_path']) . '">' . $subItem['link']['link_title'] . '</a></li>';
        }
        $output .= '</ul>';
    }
    $output .= '</li>';
}
$output .= '</ul>';
return $output;
}

```
> 0 votes

---
Tags: routes, navigation
---


# Question
Title: How to show/hide a link based on a permission?
I'm looking for a way to hide/show a link from the main-menu if the current user has a specific permission. The menu item has already been created and the menu item links to a node that is controlled by hook\_node\_access().

# Answer
By default, Drupal will hide all menu items that the user doesn't have access to, so the easiest thing to do, it to require the selected access for the page that the menu item is linking to.
> 4 votes

# Answer
What you can do is to alter the access callback associated with "node/%node" using hook\_menu\_alter(), and then writing the code for your access callback basing on the code of node\_access(). There are specific cases that you still want to handle as `node_access()` does; for example, users with the "bypass node access" permission would always access the node.

```
function mymodule_menu_alter(&$items) {
  if (isset($items['node/%node'])) {
    $items['node/%node']['access callback'] = 'mymodule_node_access';
  }
}

```

Consider that the access callback decides who can see a link, and who can access a page when the user writes the URL directly in the browser address bar.
> 2 votes

# Answer
You might want to consider drupal module menu\_item\_visibility

To quote the project page:

> For example, if you want to create a 'My account' link that points to /user, both anonymous and registered users have access to the /user path, so both will see the link, even if anonymous users do not technically have an account. Using this module will allow you to only have your 'My account' link visible to registered users, and hide it from anonymous users.
>
> The module uses the exact same UI used for block visibility settings for familiarity.

Or the menu\_views module - which provides a Views-based approach to menu generation (which I would think includes based on user)
> 1 votes

---
Tags: 7, theming, routes, users
---


title: Best solution for public shop

text:
# Question
Title: Best solution for public shop
I want to create a site where users can sell their products.

How best to do this kind of system?

Is it a good idea to use Ubercart or it may be better to use something else?

# Answer
> 0 votes
You have got two options. Ubercart or Drupal commerce With Ubercart you have to do some bits of configuration to get your store ready.

With commerce, you have a basic store setup for you if you use the Commerce kickstart distribution.

> Commerce Kickstart is the quickest way to get up and running with Drupal Commerce. It includes the latest versions of Drupal core, Drupal Commerce, and the other modules it depends on. It also gives you a set of options to create a fully-featured demo store out of the box complete with an attractive theme, catalog and search configuration, and a custom back office interface.
>
> Who should use Commerce Kickstart? Anyone who wants to skip weeks of configuration to build a commerce site on the Drupal Commerce framework.

---
Tags: ubercart
---


# Question
Title: Why are there "template_" and "theme_" prefixes instead one?
What's the difference between these ones in function names? I can overwrite each one in template.php, so?

# Answer
The functions whose name start with theme\_ are theme hooks, while the functions whose name start with template\_ are preprocess and process functions implemented by the module that implements the relative theme hook.

For example, theme\_image() is a theme hook that renders an image. template\_preprocess\_node() is the preprocess function implemented by the Node module, which the module implementing the *node* theme hook. (See the first code lines of node\_theme(), the hook\_theme() implementation done by the Node module.) There are other modules that can implement a preprocess function for the node *theme* hook, but for those modules, that preprocess function is named `MYMODULE_preprocess_node()`, not `template_preprocess_node()`.

A theme can implement both a theme hook (see bartik\_menu\_tree()) and a preprocess function (see bartik\_preprocess\_node()). The difference is that `bartik_menu_tree()` overrides the default implementation (theme\_menu\_tree()) when the current theme is the Bartik theme, while `bartik_preprocess_node()` doesn't override `template_preprocess_node()`, but it is executed after it. (See the documentation for theme().)

As for using two prefixes, the reason is to documenting the purpose of the function. Even if theme\_ were used in both the cases, the difference between `theme_image()` and `theme_preprocess_node()` would still be clear, but it would require you to read what follows theme\_. With the current implementation, you just read the first word of the function name.
> 3 votes

---
Tags: theming
---