title: Set Custom value in checkbox

text:
# Question
Title: Set Custom value in checkbox
I have an array...

```
    $my_array = array(1 => 'Value One', 2 => 'Value Two',3 => 'Value Three');

```

In Form API, I want to create checkbox for each value.

```
    foreach($my_array as $key => $value) {
      $form['custom_field'] = array(
        '#type' => 'checkbox',
        '#title' => $value,
        '#default_value' => variable_get('custom_field'),
      );
    }

```

by default is stores in value, '0' or '1'. It should actuly be saving the $key as value.

I know this can be done simply using 'type' as 'checkboxes' but actuly I need to goroup it each time each check box with a text field.

```
    foreach($my_array as $key => $value) {
      $form['custom_field'.$key] = array(
          '#type' => 'checkbox',
          '#title' => $value,
          '#default_value' => variable_get('custom_field'),
        );
        $form['custom_field'.$key] = array(
          '#type' => 'textfield',
          '#title' => 'Limit',
          '#size' => 10,
          '#maxlength' => 10,
          '#default_value' => variable_get('limit_variable'),
          '#required' => TRUE,
        );
      }

```

\` Any help?

# Answer
You can try adding '#return\_value':

```
foreach($my_array as $key => $value) {
      $form['custom_field'] = array(
        '#type' => 'checkbox',
        '#return_value' => $key,
        '#title' => $value,
        '#default_value' => variable_get('custom_field'),
      );
    }

```
> 2 votes

# Answer
You can use Fieldset to group fields together. You cannot use same key for two form elements since they override existing. So, changed checkbox key value to **'custom\_field\_checkbox\_'.$key** and text field to **'custom\_field\_text\_'.$key**

```
foreach($my_array as $key => $value) {
        $form['custom_field_group_'.$key] = array(
          '#type' => 'fieldset',
          '#title' => t('Contact settings'),
          '#collapsible' => TRUE,
          '#collapsed' => FALSE,
        );
        $form['custom_field_group_'.$key]['custom_field_checkbox_'.$key] = array(
          '#type' => 'checkbox',
          '#title' => $value,
          '#return_value' => $key,
          '#default_value' => variable_get('custom_field'),
        );
        $form['custom_field_group_'.$key]['custom_field_text_'.$key] = array(
          '#type' => 'textfield',
          '#title' => 'Limit',
          '#size' => 10,
          '#maxlength' => 10,
          '#default_value' => variable_get('limit_variable'),
          '#required' => TRUE,
        );
      }

```
> 0 votes

---
Tags: forms
---


title: Create empty block

text:
# Question
Title: Create empty block
I want to create an empty block that could be edited by the administrator, but by default the block should contain a body.

The module block `block_custom_block_form()` contains the following code.

```
$form['body_field']['body'] = array(
'#type' => 'text_format',
'#title' => t('Block body'),
'#default_value' => $edit['body'],
'#format' => isset($edit['format']) ? $edit['format'] : NULL,
'#rows' => 15,
'#description' => t('The content of the block as shown to the user.'),
'#required' => TRUE,
'#weight' => -17,

```

);

How can I override this function to set #required to `FALSE`?

# Answer
block\_custom\_block\_form() is called from block\_block\_configure(), which an implementation of hook\_block\_configure(). Those hooks are called from block\_admin\_configure(), which is the form builder for admin/structure/block/manage/%/%.

The code used from the function to invoke the modules is the following one.

```
  $block = block_load($module, $delta);
  $form['module'] = array(
    '#type' => 'value',
    '#value' => $block->module,
  );
  $form['delta'] = array(
    '#type' => 'value',
    '#value' => $block->delta,
  );

  // Get the block subject for the page title.
  $info = module_invoke($block->module, 'block_info');
  if (isset($info[$block->delta])) {
    drupal_set_title(t("'%name' block", array('%name' => $info[$block->delta]['info'])), PASS_THROUGH);
  }

  $form['settings']['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Block title'),
    '#maxlength' => 64,
    '#description' => $block->module == 'block' ? t('The title of the block as shown to the user.') : t('Override the default title for the block. Use <em>!placeholder</em> to display no title, or leave blank to use the default block title.', array('!placeholder' => '<none>')),
    '#default_value' => isset($block->title) ? $block->title : '',
    '#weight' => -19,
  );

  // Module-specific block configuration.
  if ($settings = module_invoke($block->module, 'block_configure', $block->delta)) {
    foreach ($settings as $k => $v) {
      $form['settings'][$k] = $v;
    }
  }

```

Code similar to the following one should work.

```
function mymodule_form_block_admin_configure_form(&$form, &$form_state) {
    // Check the module implementing the block is the Block module, and not another one.
    if ($form['module']['#value'] == 'block' && isset($form['settings']['body_field']['body']))
    $form['settings']['body_field']['body']['#required'] = FALSE;
  }
}

```

The function is an implementation of hook\_form\_FORM\_ID\_alter(), where FORM\_ID is block\_admin\_configure, in your case.

If you are editing an enabled module, you need to first disable, and then re-enable it. Drupal saves in a cache the list of hooks implemented from modules; disabling, and re-enabling a module forces Drupal to clear that cache. Differently, Drupal will not notice you added a new hook to the already enabled module.
> 1 votes

# Answer
For adding a block with an empty body, the hook should be "mymodule\_form\_block\_add\_block\_form\_alter". You can use the hook code from espero's answer, something like this:

```
function sf_random_form_block_add_block_form_alter(&$form, &$form_state) {
    // Check the module implementing the block is the Block module, and not another one.
    if ($form['module']['#value'] == 'block' && isset($form['settings']['body_field']['body']))
    $form['settings']['body_field']['body']['#required'] = FALSE;
}

```
> 0 votes

---
Tags: forms, blocks
---


title: Drupal 6 memcache configuration

text:
# Question
Title: Drupal 6 memcache configuration
I'm trying to use: Memcache API and Integration | Drupal.org w/ my Drupal6 and unable to determinate what am I doing wrong as when I hit `memcache.php` (MEMCACHE INFO) my `Cache Usage` shows me `100%` of `Free`.

here is my info:

`settings.php`

```
$conf['cache_inc'] = './sites/all/modules/contrib/memcache/memcache.inc';
$conf['memcache_servers'] = array(
        '192.168.52.153:11211' => 'default'
);
$conf['memcache_bins'] = array(
        'cache'         => 'default',
        'cache_filter'  => 'default',
        'cache_menu'    => 'default',
        'cache_page'    => 'default',
        'session'       => 'default',
        'users'         => 'default'
);

```

`drush`

```
 Performance and         Memcache (memcache)                                 Module  Enabled        6.x-1.10
 Performance and         Memcache Admin (memcache_admin)                     Module  Enabled        6.x-1.10

```

`system`

```
# rpm -q php-pecl-memcache memcached
php-pecl-memcache-3.0.5-4.el6.x86_64
memcached-1.4.4-3.el6.x86_64
# service memcached status
memcached (pid  1482) is running...
#

```

`SELinux`

```
# getsebool httpd_can_network_connect_db
httpd_can_network_connect_db --> on
# getsebool httpd_can_network_memcache
httpd_can_network_memcache --> on
#

```

`iptables`

```
# iptables -L -n | grep 11211
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           state NEW tcp dpt:11211
ACCEPT     udp  --  0.0.0.0/0            0.0.0.0/0           state NEW udp dpt:11211
#

```

`netstat`

```
# netstat -an | grep 11211
tcp        0      0 0.0.0.0:11211               0.0.0.0:*                   LISTEN
tcp        0      0 :::11211                    :::*                        LISTEN
udp        0      0 0.0.0.0:11211               0.0.0.0:*
udp        0      0 :::11211                    :::*
#

```

# Answer
Even though I had following line in `settings.php`

```
# grep cache_inc XXX.XXX.XXX/settings.php
$conf['cache_inc'] = './sites/all/modules/contrib/memcache/memcache.inc';
#

```

something was "off":

```
# drush -r /var/www/html/current/ -l XXX.XXX.XXX vget cache_inc
No matching variable found.                                                                             [error]
#

```

I was able to pinpoint my issue inside of `setttings.php` file, that caused `cache_inc` not to loaded into array:

```
$conf = array(
        'mimedetect_magic' => '/usr/share/misc/magic.mgc',
);

```

So, I end up changing it to:

```
$conf['mimedetect_magic'] = '/usr/share/misc/magic.mgc';

```

And *NOW* my memcache start working right away! (I'm able to see HITs in `MEMCACHE INFO`)
> 0 votes

# Answer
First ensure that your cache confiuration are working witout Memcache. Disable memcache modules and enable caching through the UI or in settings.php

```
$conf['cache_lifetime'] = '1800';
$conf['cache'] = TRUE;

```

Then check the response headers for anonymous users and look for `x-drupal-cache`. If it is a `hit` then you have it working if it's a `miss` then you must investigate further. You can check the cache\_page table in the database table to start with.

If DB caching is working, proceed and add the memache settings and enable the module. Memcache integration only divert db cache to memcache. Once you do this, truncate the cache\_page table, then check it after visiting pages as anonymous user. You can also check Memcache statistics. If the table fills up then memcache is not working fine and we will need more info. You can use drush to check the settings. `drush vget |grep cache` and post back.

Lastly check cache settings at admin/performance/cache if it is set to external you need to change that to `normal` for Memcache to work.
> 0 votes

---
Tags: 6, caching
---


# Question
Title: How do I use FAQ module views with accordion effect?
I want to use a setup similar to the hard-coded `faq-page`, having the questions grouped by category, but having the answers hide/show with the accordion effect. I would like to add a jump menu attachment at the top of the page, but this requires setting up anchor links in the original view. I have tried using the various Views displays provided by the module, but these don't have the accordion effect. Is there a magic combination that I'm missing?

Thanks!

# Answer
> 1 votes
If the FAQ module uses views to display the answers, then you can install the Views Accordion module, which creates a new plugin in views to render each result.

**Views Accordion:**

> Views Accordion provides a display style plugin for the Views module.
>
> It will take the results and display them as a JQuery accordion, using the first field as the header for the accordion rows.
>
> For Drupal 7 the module integrates the jQuery UI Accordion plugin as a views style plugin. You can configure the options provided by the jQuery UI plugin.
>
> For Drupal 6 the module used it's own jQuery code, so a different set of features is available for D6.

---
Tags: 7
---


# Question
Title: Setting managed file default value from ajax request
I'm trying to create a form using the Form API with the following behavior:

For a custom slider module, users can choose to upload an image which is saved as a managed file. This works fine. They also have the option to populate the slide content (slide title,link and image) from an existing node of a custom type. The node is selected from an auto-populated select field which on change calls an ajax function to auto-populate the title and subtitle fields. If the selected node has an image attached to it, a checkbox is displayed allowing the user to use the already uploaded image associated with node as the slider image as well. The problem I have is that I can't get the manged\_file field to accept the nodes file id (fid) and re-render as managed\_file with a default\_value before returning it from the callback.

Here's my callback:

```
function load_image_callback($form,&$form_state) {
    // Load node from the selected value
    $node = node_load($form_state['values']['slide_nid'];

    // Set the managed_file default value to the nodes main image file
    $form_state['complete form']['slide']['slide_image']['slide_fid']['#default_value'] = $node->field_main_image[$node->language][0]['fid'];

    // Return the updated slide image wrapper to replace the existing one
    return $form_state['complete form']['slide']['slide_image'];
}

```

# Answer
> 2 votes
So after digging through Drupal core code I arrived at this solution:

In my ajax callback I load the actual file, set some managed file settings in the managed\_file array, and then physically call the file\_managed\_file\_process() function to setup the managed file display field array elements.

```
function load_image_callback($form,&$form_state) {
    // Load node from the selected value
    $node = node_load($form_state['values']['slide_nid'];
    $file = file_load($node->field_main_image[$node->language][0]['fid']);

    // Set the managed_file default value to the nodes main image file
    $form_state['complete form']['slide']['slide_image']['slide_fid']['#value'] = array('fid' => $file->fid);
    $form_state['complete form']['slide']['slide_image']['slide_fid']['#file'] = $file;

    // Process the managed file field with the set element
    $form_state['complete form']['slide']['slide_image']['slide_fid'] = file_managed_file_process($form_state['complete form']['slide']['slide_image']['slide_fid'], $form_state, $form);

    // Return the updated slide image wrapper to replace the existing one
    return $form_state['complete form']['slide']['slide_image'];
}

```

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


# Question
Title: Is there a way to re-invoke #ajax on forms when the form itself is returned with ajax?
I want to change the delete link on comments so that the delete confirmation is returned with Ajax and then the delete confirmation is executed with Ajax.

I have fixed the form so the delete confirmation at /comment/%cid/delete so now the submit action is performed with ajax.

Here is the code I used to accomplish this:

```
function awesomesite_comments_form_comment_confirm_delete_alter(&$form, &$form_state, $form_id) {

  // Add the Ajax Submit Function
  $form['actions']['submit']['#ajax'] = array(
    'callback' => 'awesomesite_comments_ajax_delete',
    'progress' => false,
  );

}

function awesomesite_comments_ajax_delete($form, $form_state) {

  // Get rid of all of the messages that have been set
  drupal_get_messages();

  // Get the comment & node objects
  $comment = $form_state['comment'];

  // Put all of the Ajax Commands into an array
  $commands = array();

  // Place the comment above the form
  $commands[] = ajax_command_remove('#comment-'.$comment->cid.', comment-'.$comment->cid.' + .comment');

  // Return the Ajax Commands Array
  return array('#type' => 'ajax', '#commands' => $commands);

 }

```

This works perfectly on the delete confirmation page, however, when I return the form with Ajax, the submit no longer is processed with Ajax and a standard page refresh takes place.

Here is the PHP code I have to for delivering the confirmation form via Ajax:

```
function awesomesite_comments_menu_alter(&$items) {
  $items['comment/%/delete/ajax'] = $items['comment/%/delete'];
  $items['comment/%/delete/ajax']['delivery callback'] = 'ajax_deliver';
  $items['comment/%/delete/ajax']['page callback'] = 'awesomesite_comments_ajax_confirm_delete_page';
}

function awesomesite_comments_ajax_confirm_delete_page($cid) {

  // Get the HTML of the detele page.
  $data = drupal_render(comment_confirm_delete_page($cid));

  // Put all of the Ajax Commands into an array
  $commands = array();

  // Replace the HTML
  $commands[] = ajax_command_html('#comment-'.$cid.' + .comment', $data, array('effect' => 'fade'));

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

}

```

And here is the Javascript I have for taking the "Delete" link on the comments and returning the form (from the callback above)

```
jQuery('a.ajax-link:not(.ajax-processed)').addClass('ajax-processed').each(function() {

        // Cret the element settings object
        var element_settings = {};

        // Get rid of the progress
        element_settings.progress = { 'type' : 'none' };

        // setup the click elements and add the href
        if (jQuery(this).attr('href')) {
            element_settings.url = jQuery(this).attr('href');
            element_settings.event = 'click';
        }

        element_settings.effect = 'fade';

        // Get the base
        var base = jQuery(this).attr('id');

        // Register the Ajax Request with Drupal
        Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings);

    });

```

I believe what is happening is that Drupal is processing all the forms on the page for #ajax when the page is loaded, however, since the form is loaded via AJAX it isn't setting up the #ajax information (which I can confirm is present). How can you force Drupal to check for new forms after an Ajax request? Or am I missing something?

any help would be greatly appreciated!

# Answer
I found the answer!

I simply was asking the wrong question. What I needed to do was re-attach the drupal behaviors with `Drupal.attachBehaviors()`.

I added this code to my JavaScript code.

```
jQuery('.ajax-processed').once().ajaxSuccess(function() {
    Drupal.attachBehaviors();
});

```

Voilà! Everything works as it should.
> 5 votes

# Answer
To make things a bit more clear, for beginners like me, use it in this way:

```
(function($)  {

    $(document).ready(function(){

        ..the JS code here..

    });

jQuery('.ajax-processed').once().ajaxSuccess(function() {
    Drupal.attachBehaviors();
});

})(jQuery);

```

Clive and David, thank you SO much
> 0 votes

# Answer
I'd built a number of ajax forms before running into a problem like this, it was strange some ajax worked and other parts just didn't.

The answer I discovered after digging deep into ajax.js and the data structures returned by ajax calls was that ajax.js seemed to be dependent on one of two conditions. Either your fapi \['#ajax'\] enabled elements must be without any 'id' information, or they must provide both a fapi \['#id'\] and a fapi \['#attributes'\]\['id'\].

Hopefully, for anyone running into this type of problem, can add this to the checklist to be sure.
> 0 votes

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


# Question
Title: How to create a custom page template suggestions for a node type?
My code like this.

But get Error!!!!!

Where the wrong??

# Answer
> 4 votes
hook\_preprocess\_page() will be run on every page, regardless of whether or not it is displaying a node, and `$variables['node']` is only defined when you are. Thus, you need to wrap this with something like:

```
if (isset($variables['node'])) {

  // do stuff when displaying a node

}

```

# Answer
> 3 votes
Shown below is how I achieve custom page templates.

Using this method, the node of content type 'blog' would have the template of 'page--blog.tpl.php'

```
<?php

function newyasi_preprocess_page(&$vars, $hook) {
  if (isset($vars['node'])) {
  // If the node type is "blog" the template suggestion will be "page--blog.tpl.php".
  $vars['theme_hook_suggestions'][] = 'page__'. str_replace('_', '--', $vars['node']->type);
  }
}

?>

```

I hope that is of some use to you, good luck.

---
Tags: theming
---


# Question
Title: "Theme info" checkbox not showing on non-admin pages
I'm using the Theme Developer module. When I enable it, the `Theme info` checkbox shows up in the admin pages, but it doesn't show on the non-admin pages (e.g. Home page). There aren't any JS errors from the console. What could I be missing to make it appear?

# Answer
Apparently, someone wrote a module in the project to unset the default Drupal JavaScripts. Just had to remove that code to make everything work the way they should.
> 0 votes

---
Tags: theming
---


# Question
Title: How do I use .htaccess to trigger mod_rewrites before D7's Clean URLs take over?
I am migrating from olddjango.com to newdrupal.com, and need a way to alter the URLs from the old style into the a format we've chosen for the new Drupal application.

In addition to rewriting them, I want the final "corrective" rule to redirect, to register the 301. The structure of the URL has a marker that I'm using as a RewriteCond, it is the last thing I change before the redirect (so the URI won't get rewritten unless it is from the old site).

I've written a small number of mod rewrite rules, which work well enough in http://htaccess.madewithlove.be/

If I put them in my /etc/httpd/conf/httpd.conf they work smashingly... but that isn't a viable option. (it theoretically COULD be... but only as a last resort)

However, when I put them in /.htaccess, they do absolutely nothing...

I put them at the top of the file, before anything else, I put them at the bottom... and in the middle. I tried with and without "RewriteBase /"...

I'm obviously missing something, or the nature of D7 disallows pre-empting the machinations of Clean URL. I've found at least one person saying it was possible, but no one saying there were any special tricks involved, or actual documentation... so I'm just trying to get an answer committed to the interwebs one way or the other.

This is the final rule of my section of rewrites:

RewriteCond %{REQUEST\_URI} ^/?gbnk/?.\* \[NC\]
RewriteRule ^/?gbnk/?(.\*) $1 \[NC,R=301,L\]

# Answer
Personally, I would see if the Redirect module works for your needs. Is it basically a UI interface for making 301 redirects. Off the top of my head, though, I don't recall if it will work with patterns.

If that doesn't work, then your best bet is to put them in the .htaccess right after the

```
# RewriteBase /

```

line.

Just remember that mod\_rewrite will continue to process rules **unless** you use the `L` flag. You also want to explicitly give the response code with the `R` flag. Something like this should work

```
# RewriteBase /

RewriteRule ^some/path/(.*) /other/place/$1 [R=301,L]
RewriteRule ^another/hierarchy/(.*) /different/thing/$1 [R=301,L]

# Pass all requests not referring directly to files in the filesystem to
# index.php. Clean URLs are handled in drupal_environment_initialize().
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]

```

Keep in mind that rewrites can be frustratingly hard to debug, but logging can help. Also make sure you are using rewrites and not redirects. Mixing mod\_rewrite and mod\_alias in same .htaccess will cause all sorts of grief because of process order.
> 2 votes

---
Tags: .htaccess, uri
---


# Question
Title: is it ok to have multiple versions of jquery?
I'm facing some peculiar problems(my devel\_themer is also not working). There are multiple versions of jquery included. Its not me who included them, its different modules:

```
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>window.jQuery2 = jQuery.noConflict();</script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
<!--//--><![CDATA[//><!--
window.jQuery || document.write("<script src='/drupal/sites/all/modules/contrib/jquery_update/replace/jquery/1.10/jquery.min.js'>\x3C/script>")
//--><!]]>
</script>

```

I don't know if any of the following errors relate to problems:

```
SyntaxError: Using //@ to indicate sourceMappingURL pragmas is deprecated. Use //# instead jquery-1.9.1.min.js:1
Error: http://code.jquery.com/jquery-1.9.1.min.js is being assigned a //# sourceMappingURL, but already has one
SyntaxError: Using //@ to indicate sourceMappingURL pragmas is deprecated. Use //# instead jquery.min.js:1
Error: https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js is being assigned a //# sourceMappingURL, but already has one

```

should I remove them?

# Answer
Try using the jquery multi module. Drupal core relies on specific versions of jquery, but this module allows you to control which environments use which version. https://drupal.org/project/jqmulti

You shouldn't add jquery manually, nor should any modules. Drupal adds its own in core. Your errors may well be related, but that's hard to tell from the info you give. Do you know which module has added this?
> 1 votes

---
Tags: 7, javascript
---


# Question
Title: How do I nest two field in my node.tpl.php?
I have two fields of multiple values. When I print render($content\['field\_photo'\]) and render($content\['field\_photo\_caption'\]) I get:

```
<img>
<img>
<img>
<p>caption</p>
<p>caption</p>
<p>caption</p>

```

How do I nest the values to get:

```
<img>
<p>caption</p>
<img>
<p>caption</p>
<img>
<p>caption</p>

```

# Answer
Here is the code to solve problem

```
  $image = field_get_items('node', $node, 'field_text_multiple');
  $text = field_get_items('node', $node, 'field_multiple_second');
  foreach ($text as $key => $value) {
    $second_field[] = field_view_value('node', $node, 'field_multiple_second', $text[$key]);
  }
  foreach ($image as $key => $value) {
    $output = field_view_value('node', $node, 'field_text_multiple', $image[$key]);
    print render($output);
    print "<br>";
    print render($second_field[$key]);
    print "<br>";
  }

```
> 0 votes

# Answer
One option is to make a custom field formatter.

Find the field formatter that sets up the image to be rendered the way you want (look in image.field.inc). Clone it into your own module. You will need the info, view, and theme functions.

Then in your clone, you can grab the node from `$entity`. In the loop that builds up the images, you can get the field with the paragraphs, and stick them into the render tree.

Then, on your **Manage Display** for your content type, select your new formatter.

I normally make my field formatters pretty specific, but you can add options to let you select what field you want to pull in extra info from.
> 0 votes

---
Tags: entities, theming
---


# Question
Title: Views not found on disabling Page Title module
I've Views 7.x-3.7 and Page Title 7.x-2.7 installed. Since many months I'm using Meta tags and Page Title module but now I want to remove Page Title module as I don't need it since Metatag module provides equivalent functionality.

But on disabling Page Title module I'm getting **page not found(404)** for the Views Page display URL. Also when I go to edit that display in the View from Structure-\>Views I get the following screen:

>

When I go to view the Page url of the View Display I get this :

>

There is no information in the dblog except for this when I access the View Page url:

>

**What should I check to start debugging this?**

# Answer
The page\_titles module sets a lot of variables. I don't know if that would cause an issue like you are seeing, but it's best to remove these variables. Disabling the module will not remove them, but uninstalling it will. With page\_title disabled, go to admin/modules/uninstall, select the module, and click uninstall. This will unset all variables that were set by the module.
> 0 votes

---
Tags: 7, debugging
---


title: Custom Drupal admin theme per role

text:
# Question
Title: Custom Drupal admin theme per role
Under the "menu" \> "settings" navigation tabs there is the option to set primary and secondary links.

1. Is this strictly for backend or front end?
2. Can I use these settings for a backend, if so, how get\_variables()?
3. I want to be able to configure custom menus based on roles, I will implement a module to support this but any tips or pointers (API of interest) is greatly appreciated.

Thanks, Alex

# Answer
> 0 votes
* Regarding "Menu \> Settings" , You can able to select

Source for the Main Links (Primary menu)

> Select what should be displayed as the Main links (typically at the top of the page).

Secondary links

> Select the source menu for the Secondary links.

For example, If you created a new menu called Header Menu and added some links, now you would like to display Header Menu as Main Menu on top of page which is nothing but Primary Links. In that case you have to set "Source for the main links to " Header Menu.

* Reading these values

Yes, You can able to read these values using below code

```
$primary_menu = variable_get('menu_main_links_source', 'main-menu')
$secondary_menu = variable_get('menu_secondary_links_source', 'user-menu'),

```
* Regarding menus based on roles

You can try using Menu Item Visibility Module

> This module exposes configurable and extendable visibility settings for menu links. 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.

---
Tags: theming
---


# Question
Title: Custom Template for Comment based on node type
I'm trying to add a custom template file per content type for my comments. `comment--[contenttype].tpl.php` is not being picked up by default. I read where this may be a d7 bug or perhaps by design. Then I also read that I can add a preprocess function to my template.php, but I'm still a bit confused. I've added this to my theme;

```
function bartik_preprocess_comment(&$variables) {

}

```

but what additionally do I have to add to this function to get it to pick up the suggestions. If someone could give me the exact code for my example it would be much appreciated, assuming that my content type is called car.

# Answer
According to Drupal 7 Template Suggestions, the custom comment template for a content type should be named `comment--[node-type].tpl.php`. That is confusing, because the actual template you have to use for an `article` content type is `comment--node-article.tpl.php`.

Alternatively you could add your custom template suggestion inside template.php:

```
function bartik_preprocess_comment(&variables) {
  // Let's say you want to have a custom template like comment--custom-TYPE.tpl.php
  // e.g. for an article content type, the template file will be comment--custom-article.tpl.php
  $variables['theme_hook_suggestion'][] = 'comment__custom_' . $variables['node']->type;
}

```
> 7 votes

# Answer
You can copy the file comment.tpl.php form comment module folder and rename it to comment--node-content\_type\_name.tpl.php
> 0 votes

---
Tags: comments, theming
---


# Question
Title: Display content reference with another content
I just starting using Drupal and I have few question.

Currently I have two Content Types: `Project` and `Task`.

Project's field is:

* Project title
* Body
* Date

Task's field is:

* Task title
* Body
* Project (field\_project), Entity reference

And I create a view to display List of project.

The problem is, How to display List of task when a project detail is viewed

# Answer
> 0 votes
Create a view with title list in Task content type, in this create a Contextual filters with field\_project. Take the filter value from url arguments.

---
Tags: 7, views, entities
---


# Question
Title: Showing a message while downloading a file from hook_form_submit
I have a form which creates a csv file and starts a download if it is successful. I also attempt to show a success message at this point but it never shows up because I use drupal\_goto to download the file and since it is a file download the page does not refresh:

```
drupal_set_message("Student accounts created. Please keep the roster CSV filed that has just been download for your future use.");

drupal_goto( file_create_url($file->uri));

```

Another problem here is that any warning messages from previous failed validation (in hook\_form\_validate) remain on the page even after success. How Can I the page to refresh while starting a download from hook\_form\_submit?

# Answer
Your workflow lacks one step. What you want it to be, is:

1. Send user to "*Your download should start shortly*" page. On that page, place a script that will execute file download in new window after some arguably small timeout, and a `target="_blank"` link to the file, for cases when auto-downloading is disabled client side for security reasons.
2. When the script executes successfully and starts to download file for user, or when user clicks the link to direct download, use JS to send him to "*thank you*" page. Of course if JS fails, it might not get executed, so be sure all courtesy you really need is also displayed on the page mentioned in point one.
> 2 votes

---
Tags: forms, files
---


# Question
Title: Uploaded pdf file with multiple dots (.) in name are renamed for security reason
Authorized user gets an error each time when uploading a PDF with more than one dot in the name (other than the PDF extension, i.e this.is.an.example.10.pdf) but there are no disallowed extensions in the file name.

The error says "For security reasons, your upload has been renamed to..." (surprisingly the renamed file is the SAME as the original upload name!) Since there are no exe php etc in the filename, why is this PDF being flagged? I searched for some time to no avail. Thanks!

# Answer
when the upload file name contains multiple (.) in file name, after each dot it will be considered as extension of the file. In your case(this.is.an.example.10.pdf) it will check (is,an,examplem,10) in valid extension, It is not match with that it will add (\_)inthat. If your uploaded file name is not same after drupal changes it will give that error. For more detail check file\_munge\_filename
> 2 votes

---
Tags: 7, files
---


# Question
Title: Why does drupal set a menu link which redirects to a node as the active trail rather than the node's menu link?
I know the question might be hard to understand, so here's the problem:

I have this menu:

* a

+ b
    + c
* d

+ e
    + f (which has the url "/lorem/ipsum")

So, when I click on f the active trail is **d \> f**, just as supposed to be.

The problem is, inside submenu a shall be another menu link which has the same link as f, i.e. "/lorem/ipsum". So I added a menu link and the menu looks like this:

* a

+ b
    + c
    + g (which links to "/lorem/ipsum")
* d

+ e
    + f (which has the url "/lorem/ipsum")

So now, when I click on the menu link **g** the site "/lorem/ipsum" opens, but now the active trail is **a \> g** and not **d \> f**. I just want g to be a redirect to that node/url. How to do that?

# Answer
> 0 votes
The only working solution so far is to create a new node and add a global redirect from that node/nid plus url alias to "lorem/ipsum". This is really awkward...

---
Tags: navigation, routes
---


# Question
Title: 7: How to import simple channel-level rss data to the parent feed node created by Feeds module?
The Feeds module is properly importing Child/Feed Item-level data to the generated Child-level Drupal nodes.

What I need now is to import Parent/Channel/Feed-level info to the Parent/Feed=level Drupal entity that the Feeds module also creates.

It would/should be a simple mapping that imports the Parent/Channel-level RSS feed data (channel title, channel description, channel image etc) to the Parent/Feed Drupal node that the Feeds module creates (NOT the item/child-level nodes that it also creates.)

```
<channel>
  <title>Some Feed Title</title>
  <description>Some description...</description>
  <image>
   <url>http://example.com/image.jpg</url>
  </image>

  <item>item info starts here....</item>
  <item>more item stuff here....</item>
</channel>

```

It seems the Feeds module does not account for this.

* I see mention of creating a new parser (https://drupal.org/node/622700) but that is still only affecting the creation of the child/item-level nodes yes?
* On that same page I see "Create a feed node programmatically" but that ignores the core Feeds child/item-level functionality yes?
* I have installed the Rules module (and its Feeds patch) and am able to get from the $source object the created Parent/Channel-level node ID that Feeds generates when importing the feed, but I don't have any of the feed's data to send to that ID (I don't think anyway - there is a FeedsFetcherResult numerical value but not sure that that is of any help.)

Any assistance in pointing me in the right direction would be much appreciated! Seems like a common need related to this module but oddly haven't seen any solutions out there. Thanks.

# Answer
> 0 votes
You can try to use the patch supplied in https://drupal.org/node/1689374?

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


# Question
Title: How to display number of flagged comments for each author
I am trying to copy the "thanked"-function seen in vBulletin forums. Here the author of a topic can thank the author of a comment and the number of comments a person have been thanked for is shown in the author pane.

I have used the Flag module to allow a comment-specific flag but I can't figure out how to display the count number of thanks for each user. I have tried to create a view and display it with views\_embed\_view but i don't know how to choose count for the specific author? I have also thought of using entityfieldquery but I don't think it can see which comments that are flagged?

Is there a solution to my problem?

# Answer
> 0 votes
Ok so I found a solution although I am not sure it is the best one. The problem was that the databases for the flag module only stores the comment id (when using a comment flag) and not the id of the authoring user. I am implementing the code in a PHP snippet in author pane template where the comment object isn't available. My solution was to do two queries:

```
$cid_array = db_query("SELECT cid FROM comment WHERE uid = :user", array(':user' => $account->uid))->fetchCol();
$thank_count = db_query("SELECT COUNT(*) FROM flagging WHERE entity_id IN (:cid) AND fid = 2", array(':cid' => $cid_array))->fetchField();

```

Thanks to Felix Eve for supportive comments

---
Tags: views, flags, database
---


# Question
Title: Is it possible to make a nested Search API query?
I need to make a query in the following form:

```
SELECT * FROM {index}
...
AND (
  (field1 = value AND field2 = value) OR
  (field1 = other_value AND field2 = other_value)
)
...

```

But it doesn’t seem to be possible with the existing createFilter and condition methods, as there is no way to pass another filter to a condition for example. Am I missing something, or is this (basic functionality?) really not there?

# Answer
> 5 votes
The AND ((field1 = value AND field2 = value) OR (field1 = other\_value AND field2 = other\_Value)) IS possible with sub-filters. For anyone else who ends up here trying to sort this out (as I did before working out the correct solution) you can create the above like this:

```
$filter = $query->createFilter('OR');

$subfilter1 = $query->createFilter('AND');
$subfilter1->condition('field1',value);
$subfilter1->condition('field2',value);

// Add this subfilter to the main filter.
$filter->filter($subfilter1);

$subfilter2 = $query->createFilter('AND');
$subfilter2->condition('field1',other_value);
$subfilter2->condition('field2',other_value);

// Now add the second subfilter
$filter->filter($subfilter2);

// Apply the filter to the query.
$query->filter($filter);

```

# Answer
> 1 votes
If you mean from UX, then it not has been implemented yet as the code states (file `search_api/includes/query.inc`):

```
// @todo Add fourth mode for complicated expressions, e.g.:
// "vanilla ice" OR (love NOT hate)

```

See: Parse mode for complicated/complex expressions

This should be implemented soon in Drupal 8.

If you mean programatically, you can write your own filter, as suggested.

Or by installing Apache Solr and using Search API Solr instead.

---
Tags: search
---


# Question
Title: Can't find custom block php code in the database
I've created a custom block in Drupal 7, to display, in the upper right corner on every page, a menu that is context sensitive. Based on certain user attributes some functionalities are enabled or disabled. This block displays a list of available functionality to the user.

small example:

```
<li><a href="?q=node/add/article">write new article</a></li>
<?php
    if (og_is_member('node', 12, 'user')){
        print('<li><a href="?q=board">Board of directors</a></li>');
        print('<li><a href="?q=admin/reports/pages">statistics</a></li>');
    }
?>
<?php
  global $user;

  // Check to see if $user has the administrator role.
  if (in_array('content_manager', array_values($user->roles))) {
            print('<li><a href="?q=comment_review">Manage comments</a></li>');
  }
?>
<a href="?q=user/logout">Log out</a></li>
</ul>

```

I've noticed that when I make an SQL dump on the live site and put it on my laptop's local database for backup, this context sensitive menu is not there, while on the production site it displays just fine. first I thought I just had to readjust the visibility settings of this new block on the backup site. But when I visited admin/structure/blocks the block wasn't even there. So I figures something must have gone wrong with the sql dump. So I tried again, still no block in the list.
This new block's name is 'nav\_menu\_block', so I did a text search on the sql dump from the production site. Nothing.... So I googled a bit to find out where the data for custom blocks is stored. Found a few web pages stating this is stored in the table "block\_custom". But when I go there with phpMyAdmin, this table is empty.

So now I have this problem: if I ever have to put the backup version up again it will not contain this new block, and who knows what else will be missing....

Can anyone PLEASE tell me where to find the data for this custom block with PHP code in the database?

many thanks

# Answer
> 1 votes
Universal solution to find something you know is in the database is:

1. Dump the entire database to SQL file.

* No compression, or uncompress after downloading.
    * Use one row - one line format - disable *"insert many rows in one `INSERT` statement"* and similar options.
    * Also, disable anything that looks like *"save BLOB columns in hex format"* \- you want serialised variables in human-readable form.
2. Use grep or similar text search tool to search for the string parts you think characteristic enough to the row you need to find.

# Answer
> 1 votes
The body for custom blocks, regardless of the filter format used, is 100% definitely stored in the `block_custom` table, in the `body` field; I just tried it.

This be the proof (with a bit of sensitive info blacked out):

I would check the obvious things like

* Make sure you're dumping the right database from the right server
* Run Hacked to make sure all of your core/contrib modules are doing what they were written to do, and haven't been interfered with.
* Clear the caches (not just db caches, any external caches like Memcache/Redis you might be using too)
* Identify any enabled modules that might affect/alter storage backends. Methodically disable those, adding new blocks with PHP code each time, to determine if they are causing the issue.

# Answer
> 0 votes
strange: after three days of looking for the record it suddenly appears in the block\_custom table, both in PHPMyAdmin table representation and in the SQL dump. I truly have no clue what happened. Anyway, I've made a good backup and migrated to a new database, now everything works fine.

---
Tags: blocks, database, location
---


# Question
Title: custom entityreference widget not saving field
I am trying to create a custom widget for the entity reference field type which will be a hidden field with its value set to the current page's node id. This is my code:

```
function my_example_field_widget_info() {
  return array(
    'my_example_hidden_nid' => array(
      'label' => t('Hidden nid field'),
      'field types' => array('entityreference'),
    )
  );
}

/* implements hook_field_widget_form*/
function my_example_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $element['hidden_nid'] = array(
    '#type'=>'textfield',
    '#description'=>t('The nid of the Photo node which product line item refers to'),
    '#default_value'=>arg(1),
  );
  return $element;
}
```

I first tried this as a textfield, and saw that the form field was being properly populated.

This field is attached to a Drupal Commerce Line Item, to produce some custom functionality. However, when I clicked Add to Cart, and the Line Item was saved, this entityreference field was not saved into the database. (Since I am adding a widget to a previously defined field type, I did not use any hook\_field\_schema()'s)

How can I fix this?

# Answer
> 0 votes
For one, in your hook\_field\_widget\_form, the $element should be built with a Union (like $element += array(...)) and not replaced. Refer this example at the api page.

---
Tags: commerce, entities
---


# Question
Title: Mark only event's start date and end date in event calender
I want to mark only the start date and end date in the event calendar. For example, if the event starts from 5th of a month and ends on 17th of the same month. I need to show the text *event1 opening* on 5th and *event1 closing* on the 17th.

An event calendar is instead shown as follows.

I'm using FullCalendar for this.

How can I achieve this?

# Answer
> 1 votes
If you're using FullCalendar to dispaly the calendar, you need to register two separate events:

1. Exhibit opening: Wild & Wonderful (starts end ends on the 5th).
2. Exhibit closing: Wild & Wonderful (starts end ends on the 17th).

Now, the opening and closing event will appear independent of each other,

---
Tags: javascript
---


# Question
Title: How to assign default values for an edit form?
In my form I create a field of type list (with the widget box is checked). By default, this field has no value.

In my hook\_form\_alter () method, I add options (via PHP) has this field.

```
$form['field_genric_domains']['und']['#options']= _get_domaine_options();

if($form['field_genric_domains']['und']['#default_value'] == NULL){
    $form['field_genric_domains']['und']['#default_value']  = array(_get_this_domain_id());
}

```

Then I set a default value. I set up a test that shows whether we are editing or creating.

When creating, it works perfectly, but when editing the table (# default\_value) is empty. Normally it should contain the values previously inquire.

Why? Thank you for your help

# Answer
> 0 votes
Found! Made in, when loading a form, drupal will verify that the value is in # default\_value also found in # options. If it does not find a match it displays an empty table.

As the set of options and # # default\_value is in the code, you must override the operation of drupal and make the comparison in the code before displaying

# Answer
> 0 votes
You need to check that value returned by \_get\_this\_domain\_id() function is in the array key used to create #options for form element \['field\_genric\_domains'\] .

Example :

If \_get\_domaine\_options() function returns array as :

array(1=\>'India',2=\>'USA');

Then \_get\_this\_domain\_id() should return key either 1 or 2 .That will set the default value depending on the array key .

---
Tags: forms
---


# Question
Title: Does "Maximum image resolution" resize before saving on the site?
I am building a site using Drupal 7, in which users can upload content and images.

When I set the "Maximum image resolution" (on the core image field settings) to be, for example - 800x600.

Is that mean that the pictures will first be resized and weight reduced, and only then will be saved on my Drupal site?

I don't want to have many pictures that weight a lot on my server. I prefer to save only the images that has been resized, in order to have more space on my server.

# Answer
that setting means that you can't upload an image with max resolution of 800x600. If you upload an images with a size more than that set, it will be not imported and drupal will return an error alter.
> 1 votes

---
Tags: media
---


# Question
Title: Unpublish blog content after a certain time
I have blog content (created with the Blog module). I want to create an archive which has 30 days of time. After that when we click on archive it will unpublish the blog content. Any idea how to do it?

# Answer
> 1 votes
https://drupal.org/project/scheduler

> This module allows nodes to be published and unpublished on specified dates.
>
> Dates can be entered either as plain text or with calendar popups. To use calendar popups you need to install the Date Popup module, which is part of the Date module.

# Answer
> 1 votes
The Scheduler modules does just that. If you end up having more advanced requirements, leveraging the Rules module with its Rules Scheduler sub-module could be a good option to go with.

# Answer
> 0 votes
I can think of another two approaches for this. One is to use the module Node Expire and let it unpublish or notify users upon expiration.

Another approach. more manual, is to use Views with Views Bluk Operations. You create a view with all nodes having post or update date before 30 days and you perform a bulk operation to unpublish them.

# Answer
> 0 votes
Use the scheduler module: https://drupal.org/project/scheduler it can both publish and unpublish nodes at a set time or age.

If you want to do it manually, you can unpublish content from the standard drupal content list at admin/content, or you could look into the views bulk operations module (https://drupal.org/project/views\_bulk\_operations). That would allow you to perform actions on content from a views list so you can filter your content to only show content older than the 30 days.

As another option you could look at learning rules and create an unpublish rule. The best rules tutorial I know of is at the Node One learning Library.

---
Tags: nodes
---


title: WSOD need help!

text:
# Question
Title: WSOD need help!
I am having problem with WSOD on my site. I have a lot of modules so my php execute time is 60s and allocated memory is 512MB. This error comes not regularly this is the biggest problem, and I **cannot reproduce** it.

The http request at that time is 200 what means its ok, my memory and processor usage is fine. But I have no error on php and apache2 level that means something dies even before it could log anything. If I try to debug it and put code in the index.php the problem dissapears and the site is visible, with the apache restart as well.

Other strange thing, I have a test copy of the site, on the same server. If I load the test site the problem dissappears like on apache restart.

I have this in my settings.php, and index.php file as well.

```
error_reporting(E_ALL);
$conf['error_level'] = 2;
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

```

The error reporting is setted on php and server level as well. Still no sign of errors and solutions.

Thanks, Adam

# Answer
Your best bet would be to take a local copy of your site and leverage XHProf (there's a module for that) to determine what exactly is causing your site to throw a WSOD (memory leak? too many DB calls? etc.).

That being said, you should probably start by identifying which modules aren't absolutely required for your site and uninstall them completely. Remember that any module enabled is being parsed on each page load and this causes unnecessary memory consumption. One way to mitigate this, though, is to make sure you have APC enabled on the server, or better, that you're running PHP 5.5.x which comes with Zend Opcode cache built-in (it might be more involved, though, for compatibility reasons).

Then, you should definitely try to find why you need as much as 512M of PHP memory to run the site. This is way too much for regular use cases. Part of it comes from the fact that you must have too many modules indeed, but it could also be caused by too many (uncached) Views and/or Panels or anything that is taking too long to load.

I'd recommend that you install the Memory Profiler module prior to getting to XHProf profiling (if you're not familiar with this already). It's a quick and lightweight way to determine paths that are possible culprits.
> 1 votes

---
Tags: 7, wsod
---


title: alias url to root

text:
# Question
Title: alias url to root
I was looking at `admin/config/search/` for adding url aliases. I wanted to add alias to the website/root so user can see same content to `mysite.com/somecityname` to same `mysite.com/`.

It seems like we can give alias to nodes only because the "Existing System Path". Is it possible at all? I guess there is a way to do this by defining it in `.htaccess` which is out of scope of Drupal, so I was wondering is there any way to achieve this?

I tried to give an alias to which is home page but it still shows 404

# Answer
While you can't alias something to an empty path, you can alias something to `node` (i.e. `mysite.com/node`, which will be your website root in a Drupal system set up by default).

If you're set your website root to be some *other* path than `node`, you should be able to use that path instead. Navigate to *Home » Administration » Configuration » System*, and notice what is in indicated in the text field "Default front page". If this field is *not* empty, you must use that as your path instead of `node`.

(The above solution uses the standard path alias function that is part of Drupal core - it doesn't require any external modules.)
> 1 votes

---
Tags: path-aliases
---


# Question
Title: Is there a means to pass some php.ini settings to the drush command?
Running `drush -d status` results in this error: `Drush command terminated abnormally due to an unrecoverable error`. The full output is add below.

> Drush bootstrap phase : \_drush\_bootstrap\_drupal\_site() \[0.12 sec, 7.41 MB\]
> \[bootstrap\] Initialized Drupal site default at sites/default \[0.12 sec, 7.41 MB\]
> \[notice\] Cache HIT cid: 5.7-commandfiles-2-c32acd775c18a90c5b41d0fc9accf5ab \[0.13 sec, 7.41 MB\]
> \[debug\] Drush bootstrap phase : \_drush\_bootstrap\_drupal\_configuration() \[0.13 sec, 7.41 MB\] \[bootstrap\] Drush bootstrap phase : \_drush\_bootstrap\_drupal\_database() \[0.16 sec, 9.16 MB\]
> \[bootstrap\] Successfully connected to the Drupal database. \[0.16 sec, 9.16 MB\] \[bootstrap\] Drush bootstrap phase : \_drush\_bootstrap\_drupal\_full() \[0.17 sec, 9.16 MB\]
> \[bootstrap\] Undefined index: sitename domain.module:2922 \[1.24 sec, 31.05 MB\] \[notice\] Undefined index: path domain.module:2923 \[1.24 sec, 31.05 MB\] \[notice\] Drush command terminated abnormally due to an unrecoverable error. \[1.24 sec, 31.06 MB\]
> \[error\]

Is there a way to configure a separate `php.ini` for `drush` in the `.drushrc` file or in `settings.php`, or pass some settings on the `drush` invocation?

# Answer
> 2 votes
First, remember that php.ini for Command Line Interface is separate and has nothing to do with php.ini your webserver is using. To find where that file is, follow this question on SO as this is not really on-topic on Drupal Answers.

If you want to set some php.ini values in drushrc.php, you need to use `ini_set()` PHP function. Just remember that not all values are changeable like that, only the ones with `PHP_INI_USER` (or `PHP_INI_ALL`, of course) on this list.

---
Tags: drush
---


# Question
Title: How to let the admin select multiple users
Probably something like that table with checkbox in people menu. Is there something like that in drupal, some API for creating this type of table? It needs to have pager, because i can't load all users. Is there any way, how to achieve this, or i need to do it by my self?

# Answer
You can use Views and Views Bulk Operations modules.

You create a new view of users and you specify which bulk actions you allow to be performed.
> 1 votes

---
Tags: users
---


# Question
Title: One-time link without valid email address Spam Registrations
I have a D6 site that gets a lot of SPAM account registration and they all follow a pattern, however from different IP addresses (often during the following process):

1) User account is created

2) One Time registration link is used to log in

3) account page is visited

4) node/add page is visited

* I am using both a Math captcha AND spamicide on the user registration form.
* Users have to be verified via email.
* Password Reset form also has a captcha and spamicide enabled
* I have found out that some of the email addresses being used are from servers that according to their operators are not in service to send or receive email.
* This often happens within 1-15 min and either from the same IPs or different IPS for the same username.

So, how are the bots logging into my site? How can they get the one-time link token without checking the email account.

EDIT: The email listed in users.mail is equal to users.init for almost all accounts. There are some that have changed but they look like legitimate users.

Any idea on how to stop this would be appreciated.

FAKE User Data:

```
uid     name        mail                init                modesortthreshold   theme   signature   signature_format    created access
1975    Gomez.S.    sele.99@hotmailit   sele.99@hotmailit   0   0   0           0       1359319030  0                   0

```

# Answer
> 1 votes
I can only think of a few ways this is possible:

1. There's a vulnerability in the one-time-login link system for new users (I'm not aware of one)
2. There's a vulnerability in some other module (in which case please give some more details of what modules you are running)
3. Your server does actually resolve the domain hotmailit or has a default place it sends mail and thus the mail is being delivered to somewhere which is then getting the login link and spamming.
4. Something about your configuration is different than you've described it (e.g. Users do not have to be verified before posting)

---
Tags: 6, users, security, advertising
---


# Question
Title: Trying to alter SKU field on ubercart product that is also a course
I'm trying to modify a course (from the course module) and a product (from ubercart). I want to remove the SKU (right now I'm just testing how to remove the required bit) and a few other fields as I'm selling only online products. I'm not great at using hook\_form\_alter() yet.

I'm trying to follow this tutorial, http://www.ubercart.org/comment/8749/Re-Removing-SKU-product-edit-page and I'm not quite sure where he is getting `$form_id == 'product_node_form'` \- is that related to the content type?

I'm trying to do this on a course content type, so if so, that would explain why it isn't working for me.

# Answer
> 1 votes
The ID for a node form is built up in `node_forms()`:

```
$forms[$type . '_node_form']['callback'] = 'node_form';

```

Where `$type` is the name of each type retrieved from `node_type_get_types()`.

So generally speaking, if the content type is `product`, the form ID will be `product_node_form`, if the type is `course` the form ID will be `course_node_form`, and so on.

---
Tags: 7, ubercart, forms
---


# Question
Title: Retaining URL Alias without removing when modified nodes or run bulk update
I want to keep the old aliases when I have modified the content. I don't want the alias to be modified/removed. This is very import point in SEO perspective. How do I do this?

**Update:** I apologize if my question was not clear. I was under impression that its drupal naturally handles the aliases whenever I add/edit/update nodes and I was thinking experienced durpal community already know about this and help me. But I came to know it from gisli's comment that autopath is the module which is doing it and it has the settings how it handles it which I completly missed when I saw settings tab.

# Answer
> 0 votes
The path or alias doesn't change in Drupal when you modify content. There are, however, modules that you can install (such as PathAuto) that may do this. If this is what is breaking your aliases when content is changed/updated, you need to turn such modules off or tune their settings to avoid the problem.

# Answer
> 1 votes
Maybe the modules Redirect and Global Redirect will be helpful for you.

The modules have some good functionality concerning redirects SEO-wise. I have not evaluated them extensively, but they seem quite popular.

---
Tags: path-aliases
---


title: Drupal Error log services

text:
# Question
Title: Drupal Error log services
Can I create views for error logs, or directly expose them to services? How can I maintain my own error logs and expose them in services?

# Answer
> Can I create views for error logs?

Yep, you can create Views for pretty much any type of data. There are a couple of existing modules that already do this:

Or you could of course write your own.

To expose Views as services, you can use the Services Views module, or, again, you can write your own resources for the Services module if it doesn't do exactly what you want.
> 2 votes

---
Tags: views, services
---


title: Can a node belong to multiple menus?

text:
# Question
Title: Can a node belong to multiple menus?
I have a few pages such as a general "contact us" page. I'd like this page to exist inside of the Main Menu but be able to be linked from other menus (Theatre menu, for example). I create the contact us page and assign it to the Main menu on the node's form. Then, I add the link from the Theatre menu.

However, the contact us page now shows the Theatre menu.

How do I accomplish linking a page from multiple menus but keeping it inside of it's own menu?

I thought the old convention was to add existing links such as `http:/learn/contact_us`. If I add the link `learn/contact_us` to Theatre's menu, the Contact us page now shows the Theatre menu (instead of the Main menu).

Additional folks running across this problem: https://drupal.org/node/1314742

# Answer
Actually, the project menu token allowed me to find a good work around. I set it up as pictured below. By using the token \[site:url\] followed by an existing path, a effectively have a link to an existing node ***without changing the existing nodes current parent menu.***
> 1 votes

---
Tags: routes
---


# Question
Title: How do I implement hook_views_pre_render()?
I need to alter the result of a view. I read I can use `hook_views_pre_render()`, but in a custom module. I don't have any custom module implemented and I would like to know where and how should I put the code in my project.

# Answer
You need to read and understand the Module developer's guide first, then it's as simple as adding the following to your .module file:

```
function MYMODULE_views_pre_render(&$view) {
  // Do stuff with the $view object.
}

```
> 5 votes

# Answer
Views hooks should be implemented in a .views.inc files not in .module file
> 0 votes

---
Tags: views, hooks
---


# Question
Title: Get only some fields with EntityFieldQuery?
Drupal 7 has very promising ORM-like system of queries with EntityFieldQuery.

Currently, I understand how to make selection of nodes, but the result doesn't contain any specific information, like fileds, I'm looking for.

```
$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node')
                        ->entityCondition('bundle', 'event')
                        ->propertyCondition('status', 1)
                        ->fieldCondition('field_date', 'value', array('2011-03-01', '2011-03-31'), 'BETWEEN')
                        ->fieldOrderBy('field_date', 'value', 'ASC')
                        ->execute();

```

So we need to load entire data of nodes, if we would like to get only values of one field, for example 'field\_date' in current example.

```
$nodes = entity_load('node', array_keys($entities['node']));

```

If there is a way to get the value of fields, instead to load full data of all nodes, as it provokes some memory overload.

```
$nodesFieldDates = ???

```

# Answer
> 11 votes
Great question!

`EntityFieldQuery` is truly good stuff, but if you *really* want to get serious, you have to override the class in a custom module and add whatever behavior you need done in there.

I don't know your exact intentions, but I have referred myself to this article on the subject in the past. Credits to Neil Hastings for this well written write-up.

Look for code examples a bit into the article for nice examples of overiding.

Hope that helps, happy coding!

# Answer
> 11 votes
I found the answer for this! The Apache Solr module extends the EntityFieldQuery class in order to make it happen. It adds a new method called addExtraField.

```
<?php
$query = new ApachesolrAttachmentsEntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'event')
  ->propertyCondition('status', 1)
  ->fieldCondition('field_date', 'value', array('2011-03-01', '2011-03-31'), 'BETWEEN')
  ->fieldOrderBy('field_date', 'value', 'ASC')
  ->addExtraField('field_date', 'value', 'value')
  ->execute();
?>

```

If you don't have Apache Solr installed simply copy the code for extending that class.

# Answer
> 8 votes
You don't need to override anything or extend the class. You just need to use `field_attach_load()` to attach the field you want to the results from the `EntityFieldQuery` class.

See also Loading Only One Field From An Entity or Node in Drupal 7, a good article with examples on how to do it.

# Answer
> 0 votes
Anyone still wanting to get Fields from a EFQ take a look at the EFQ Extra Fields module.

> Warning : This module abuses EntityFieldQuery to return data from your database. It does not work with entities or any modules that build on them.
>
> It allows you to use addField within an EntityFieldQueryExtraFields object (extends EntityFieldQuery objects). Initially EntityFieldQuery only gives you back the entity id, bundle and entity type. This module adds an extra layer on top of that without doing some extra entity\_loads! Important if you want to work with massive amounts of data and you want to reduce the sql queries. Since EFQ already queries the database for this information, why not alter that query to also give you some additional fields. This means that not a single extra query will be performed to get that data.
>
> A word of caution, if you rely on some post-formatting/post-loading that happens in entity\_load or similar functions, this module won't take care of that. You have to ensure the validity of the retrieved data yourselves.

```
Example

Fetching the node title

$query = new EntityFieldQueryExtraFields();
  $result = $query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'my_bundle_type')
  ->propertyCondition('status', 1)
  ->addExtraField('field_myfield', value', value')
  ->addExtraField('field_mynodereffield', nid', nid')
  ->addExtraField('', 'title', 'title', 'node')
  ->fieldCondition('field_myfield', 'value', 'some_value_to_filter_on', '=')
  ->execute();
Possible combinations :
addExtraField($field_name, $column, $column_alias = NULL, $table = NULL)

field_name
Specify from which field the extra field should come. If it is from a base table, leave it empty and fill in the table argument

column
Specify the name of the column,

column_alias
Specify the alias of the column,

table
Optionally, add something like node or user here (the base table),

```

---
Tags: 7, entities
---


# Question
Title: How to create a module to allow for multiple instances of the same module with different variable parameters
How do you create a module to allow for multiple instances of the same module block with different variable parameters. I know how to create global parameters but that will apply to that block across the site.

this is an image of opening up the settings for the block on the panel

# Answer
Generate your blocks same way block module does: appending an id. Then store your configuration indexed by this id. You can store your values in a custom table (see schema api and install file syntax) or in the variable table (using variable\_get() and variable\_set()).

Whenever an operation with a block happens you receive the block id. Use the block id to access or set your configuration data. For example, the code for rendering a block should be the same for all your custom blocks, but you feed that code with different configurations that you read from your custom table or variable table using the provided block id.
> 1 votes

---
Tags: blocks
---


# Question
Title: How can user select attributes for a product when clicking on an add-to-cart link?
I'm trying to work out the best way of displaying an attribute selection form when a user clicks on an add to cart link (not on a product node). Ideally display a form in a shadowbox with attribute selection and quantity fields and a submit button. I feel like this option must exist somewhere, but I haven't found it.

Any pointers for me?

# Answer
> 1 votes
Very old one but why not answer?

Use Ubercart Cart LInks module (included in Ubercart Core). I think it allows links that operates on the cart, like empty cart or add a product what I guess includes product attributes.

Here it's explained, but is very old page, check module documentation.

http://www.ubercart.org/node/1427

---
Tags: ubercart
---


# Question
Title: how to set the source connection in drupal d2d migrate
I am migrating my taxonomy and users from d6 site to d7 site. How can I set the legacy connection of source db of d6 site.

The user is root and password id empty with source database name as d6 for the Drupal 6 site.

> hook\_flush\_caches().

```
 $common_arguments = array(
        'source_connection' => 'd6_migration',
        'source_version' => 6,
      );

```

will it migrate data from d6 to d7 when I install the custom migrate\_d6 module in Drupal 7 site?

My Settings file of Destination project is

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'd7',
      'username' => 'root',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  'd6_migration' =>
  array (
    'default' =>
    array (
      'database' => 'd6',
      'username' => 'root',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

```

# Answer
The migrate module provides basic migrate functionality while the migrate\_d2d module extends on that functionality providing interfaces for reading and importing into Drupal 5, 6 and 7. Migrate comes with Drush integration and supports rolling back migrations which is very handy during development.

Add the following code into your settings.php file or you can specify database connection details within your migration scripts:

```
<?php
// Our Drupal 7 database configuration.
$databases = array (
'default' =>
  array (
    'default' =>
    array (
      'database' => 'db_drupal7',
      'username' => 'drupal7_user',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  // Here we add in the connection to our Drupal 6 database.
  'legacy' =>;
  array (
    'default' =>;
    array (
      'database' => 'db_drupal6',
      'username' => 'drupal6_user',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

```

If you want to create the script for migrating the content than please have look at this useful tutorials:

http://devblog.com.au/migrating-drupal-6-to-drupal-7-with-the-migration-framework https://drupal.org/node/1813498

---

**Personal suggestion:** Now the migrate\_d2d module is providing a stable UI for migration the contents and that is very easy to do as well, have a look at it documentation here: https://drupal.org/node/1813498

Also if you have a larger database than you can use the drush commands to migrate the contents after setting up the database connections, the list of drush commands for migrating the content: https://drupal.org/node/1561820
> 9 votes

# Answer
You can enter the db connection inside the module without having to change the settings.php file, like this:

```
$common_arguments = array(
'source_version' => 6,
'source_connection' => 'legacy',
'source_database' =>  array('driver' => 'mysql','database' => 'dbname','username' => 'dbuser','password' => 'dbpass','host' => 'localhost','prefix' => '',)

```

);

I hope this will help you

Ciao r.
> 3 votes

# Answer
Can you please delete the semicolons after `'legacy' =>` and `'default' =>`? This is almost the only settings.php example you find by google. Yeah, the error is already in http://devblog.com.au/migrating-drupal-6-to-drupal-7-with-the-migration-framework where you cited from. It should look like this: `'default' =>
 array (
 'default' =>
 array (
 'database' => 'db_drupal7',
 'username' => 'drupal7_user',
 'password' => '',
 'host' => 'localhost',
 'port' => '',
 'driver' => 'mysql',
 'prefix' => '',
 ),
 ),
 // Here we add in the connection to our Drupal 6 database.
 'legacy' =>
 array (
 'default' =>
 array (
 'database' => 'db_drupal6',
 'username' => 'drupal6_user',
 'password' => '',
 'host' => 'localhost',
 'port' => '',
 'driver' => 'mysql',
 'prefix' => '',
 ),
 ),
);` Thank you for the example. Rare that nobody have noticed this before :-) Drush directly shows errors for the two semicolons. Sorry, that i'm not writting a comment to your post. I've not enough bucks. 50 is minimum.
> 2 votes

---
Tags: migrations, backups
---


# Question
Title: How would I override misc/ui/jquery.ui.theme.css
I have theming being automatically applied by misc/jquery.ui.theme.css that I need to modify. I am using Views Accordian plugin in an instance of EVA for a FAQ category.

What is the Drupal way to override some of the css in this instance?

I read the "How to override a theme function?" but I don't think it would work in this case, I could be wrong.

# Answer
I don't have enough rep to add comments, but here is my two cents. In addition to Clive's comment, take a look at the `weight` and `group` option being used in `drupal_add_css`, in `views_accordion.module`. You can implement your own stylesheet here and assign a `CSS_THEME` for its `group` and a larger `weight` number than that of `views_accordion`, which I'm pretty sure would have used `CSS_DEFAULT` instead. Here are the docs page. drupal\_add\_css
> 0 votes

# Answer
I ended up using theme roller for the jquery parts I needed. Thanks.
> 0 votes

---
Tags: javascript
---


# Question
Title: Is there a way to pass additonal php.ini settings to a drush command?
I want to specify additional `php.ini` settings to a `drush` invocation in the manner they would passed using `-d` option if drush was a php script that could be passed to `PHP` using the -f parameter.

On looking at drush shell script - `/usr/bin/drush` \- I see that it executes the drush.php script in that manner.

Is there a way to add more of those through the command line?

# Answer
> 7 votes
In the Drush README file, in the section titled "CONFIGURING PHP.INI", you will find instructions on how to set php configuration variables without modifying the drush script:

```
export PHP_INI='/path/to/php.ini'
export DRUSH_INI='/path/to/drush.ini'
export PHP_OPTIONS='-d memory_limit="128M"'

```

The first option replaces the entire php.ini file with one of your choosing. The second option allows you to specify an ini file that is merged in with the standard php-cli ini file. The last option allows you to specify commandline options to set configuration values. Note that the second option effectively works the same way as the third option -- all of the settings are converted to commandline options. See the php documentation for more information on php commandline options.

If you want to do this for just one call:

```
alias specialdrush='/usr/bin/env PHP_OPTIONS="-f /path/to/my/php.ini" drush'

```

# Answer
> 3 votes
reading through /usr/bin/drush, i found this part :

```
# Check to see if the user has provided a php.ini file or drush.ini file in any conf dir
# Last found wins, so search in reverse priority order
for conf_dir in "`dirname "$SELF_PATH"`" /etc/drush "$HOME/.drush" ; do
  if [ ! -d "$conf_dir" ] ; then
    continue
  fi
  # Handle paths that don't start with a drive letter on MinGW shell. Equivalent to cygpath on Cygwin.
  if [ -n "$MINGW" ] ; then
    conf_dir=`sh -c "cd \"$conf_dir\"; pwd -W"`
  fi
  if [ -f "$conf_dir/php.ini" ] ; then
    drush_php_ini="$conf_dir/php.ini"
  fi
  if [ -f "$conf_dir/drush.ini" ] ; then
    drush_php_override="$conf_dir/drush.ini"
  fi
done
# If the PHP_INI environment variable is specified, then tell
# php to use the php.ini file that it specifies.
if [ -n "$PHP_INI" ] ; then
  drush_php_ini="$PHP_INI"
fi
# If the DRUSH_INI environment variable is specified, then
# extract all ini variable assignments from it and convert
# them into php '-d' options. These will override similarly-named
# options in the php.ini file
if [ -n "$DRUSH_INI" ] ; then
  drush_php_override="$DRUSH_INI"
fi

```

if i read it right, you would have to do one of these : \- add a file somewhere \- fill in a variable

---
Tags: drush
---


# Question
Title: How to change the page of a view block display programmatically
I have a view with a block display. Is there any way to change the block pager page programmatically? Currently i am embedding theview using the views\_embed\_view and i am passing the url arguments. What i need is to pass also the pager index argument also. Is this possible?

Thanks in advance

# Answer
This is how you can get a view programmatically:

```
  $view = views_get_view('view_name');
  $view->set_display('view_block_name');
  $view->set_arguments(array($argument_goes_here));
  $view->pre_execute();
  $view->execute();
  print $view->render();

```

The views object has many functions which can be viewed here.

You can set current page for the pager with `$view->set_current_page($page);`
> 1 votes

---
Tags: views
---


title: Discount for Roles

text:
# Question
Title: Discount for Roles
I am using Drupal Commerce and I would like to know if it is possible to have discounted prices for registered users and much better for roles.

For example, the nomral price is $100 but when a user logs in that belongs to Role1 for example, he will see different prices with the percentage discount that I will have assigned to that role. How can I accomplish such a feature?

# Answer
> 5 votes
You can set this up with Rules. Using the calculate sell price of a product, you can create different conditions (The users role) and add discount depending on the role the user have.

Note if you do this for several roles, you need to take care about the weight of the Rules and how you set discount, as you otherwise might end up with cumulative discounts or wrong discounts if you have users with multiple roles.

# Answer
> 2 votes
Steps for Applying Discounts by Role in Drupal Commerce

1. Create a new role
2. Go to admin/commerce/config/product-pricing and Add a Pricing Rule
3. Call this new rule: Apply \[role\] Discount. Save
4. Conditions:
    1. Add condition - user has role(s), value \[your new role\]. Save
    2. Optional condition - Order contains products of particular product types -
        1. Data Selector: commerce-line-item:order
        2. Product Type: whatever ones you want.
5. Add action - Commerce Line Item: Multiple the unit price by some amount.
6. Data selector: commerce-line-item (use hyphenated, not the one with underscores)
7. Amount: Value: 0.85 (for 15% discount, so 85% of the price).
8. Price Component Type: Value: Discount. Save

Now when logged in as a user that has the role to allow for a discount, the discounted price will show for the item and on checkout it will show that a discount was applied.

# Answer
> 1 votes
I got this problem right now, googling around i found Og and Profile2 modules that could be configured to accomplish this need, but my customer need a really easy-to-manage solution, so i took another way:

1. I created a node content-type called "Discount"
2. Added a integer field "Discount percentage" to the "Discount" node type
3. Created a simply module that add a "Discount" node every time a new Role is created
4. Added 2 fields to the user profile (admin/config/people/accounts/fields), one for manual discount and another that gets calculated with roles.
5. In the Store Pricing rules, I created a rule for the event `Calculating the sell price of a product` with action `Subtract an amount from the unit price` and a custom PHP code.

This is the pricing rule amount code:

```
global $user;
$user_load = user_load($user->uid);
$discount_value = 0;
// Give precedence to an optional manual discount
if(isset($user_load->field_discount_manual['und'][0]['value']) AND (int)$user_load->field_discount_manual['und'][0]['value'] > 0)
{
    $discount_value = (int)$user_load->field_discount_manual['und'][0]['value'];
}
else if(isset($user_load->field_discount_role['und'][0]['value']))
{
    $discount_value = (int)$user_load->field_discount_role['und'][0]['value'];
}

if($discount_value > 0)
{
    return ($value * $discount_value) / 100;
}
// no discount
return 0;

```

This way let my customer to assign a discount to every role, managing them easly as other types of nodes (just play with Views to semplify the process).

# EDIT

Indeed, was a bit insane all that discount calculations every time a product's price get displayed. So i edited the module to make the calculations only when the user log in, and update the `field_discount_role` (that you have to add too) on the user profile, so the whole gear should be a bit less haevy.

The new module can be found here, but please note that **you will need the Field Permission module too**, or your customers can change they're own discount! (what a dream!)

# OLD POST

Just in case the log-in behavior doesnt fit your needs, this is the first-approach.

Pricing rule amount code:

```
global $user;
$user_load = user_load($user->uid);
$discount_value = 0;
// Give precedence to an optional manual discount
if(isset($user_load->field_manual_discount['und'][0]['value']) AND (int)$user_load->field_manual_discount['und'][0]['value'] > 0)
{
    $discount_value = (int)$user_load->field_manual_discount['und'][0]['value'];
}
else
{
    // Get the discount nodes.
    // If user has multiple roles (usually _authenticated user_ and the discount role) i take the one with
    // higher discount. Depending on your customer neds, is up to you to sum, avg or do whatever you want.
    foreach($user->roles AS $role_name)
    {
        // using an IN() clause?
        $query = db_select('node', 'n');
        $record = $query->fields('n', array('nid'))
            ->condition('n.type', 'discount')
            ->condition('n.title', $role_name)
            ->execute()
            ->fetchObject();
        if($record !== false)
        {
            $discount = node_load($record->nid);
            if(isset($discount->nid))
            {
                if(isset($discount->field_discount['und'][0]['value']))
                {
                    $discount_value = (int)$discount->field_discount['und'][0]['value'] > $discount_value ? (int)$discount->field_discount['und'][0]['value'] : $discount_value;
                }
            }
        }
    }
}
if($discount_value > 0)
{
    return ($value * $discount_value) / 100;
}
// no discount
return 0;

```

Here you can find my module (please note is a quick'n'dirty module, you'll have to edit few settings in the .module file) and here the pricing rule I used (my customer asked to apply discounts only if the user has 3 or more items in the cart, so you'll find this condition in the rule).

Now im looking on how to do that calculation when the user login, put the user discount in the session or somewhere else and use this value instead of recalculate all every time, but this is a (needed) optimization.

Hope it helps.

---
Tags: commerce
---


# Question
Title: Count items in nested field array for if/then in template
I'm sure I'm missing something very straightforward here: I want to prevent the thumbnail slider in my image gallery from being rendered if there's only one image for the node. My first thought was, optimistically:

```
  <?php if (count($content['field_media']) > 1): ?>
    <div id="carousel" class="flexslider clearfix">
      <div class="slides">
        <?php print render($content['carousel']); ?>
      </div>
    </div>
  <?php endif; ?>

```

I saw why that didn't work when I examined the node structure. In an example case for a node with one image, I have

```
 field_media (Array, 1 element)
    und (Array, 1 element)
        0 (Array, 17 elements)

```

the last one being the actual file element with an fid, etc. The corresponding field for a node with two images is

```
 field_media (Array, 1 element)
    und (Array, 2 elements)
        0 (Array, 17 elements)
        1 (Array, 17 elements)

```

So the array I need to count is nested inside the 'und' array. I know I've used that in other templates, like $field\_external\_link\['und'\]\[0\]\['url'\]. But when I print count($content\['field\_media'\]\['und'\]), I get 0. How do I evaluate the number of elements in that array?

# Answer
You can use field\_get\_items api function to read values.

```
<?php

$images = field_get_items('node', $node, 'field_media');
if (count($images) > 1) {
  // Print Carousel
}
?>

```
> 1 votes

---
Tags: theming
---


# Question
Title: Views: Filter by whether a node is <front>?
Is there a way to filter a view by whether the item is set to \<front\>? Seems simple but it's not as easy as I'd have guessed.

# Answer
> 1 votes
You can solve above problem using Views PHP module.

> This module allows the admin account (user 1) to add fields, filters and sorts to views which use PHP code. It also supports additional accounts when the core PHP Filter module is enabled.

All you need to do is create a filter Global PHP and below code in the php filter. **It's highly recommended that you include this within a module rather than directly in views. If it breaks it could be difficult to recover from.**

```
function yourmodule_exclude_front($data) {
  if (!empty($data)) {
    $front_url = variable_get('site_frontpage');
    $url_parts = explode("/", $front_url);
    if (($url_parts[0] == 'node') && ($url_parts[1] == $data->nid)) {
     return TRUE; //Exclude the node
    }
  }
  return FALSE;
}

```

Then within your view php filter you would do something like:

```
 if (module_exists('yourmodule')) {
   return yourmodule_exclude_front($data);
 }

```

Exported view code below (not including module code from above, but inline code)

```
$view = new view();
$view->name = 'front_view_node';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Front View Node';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Front View Node';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'node';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Global: PHP */
$handler->display->display_options['filters']['php']['id'] = 'php';
$handler->display->display_options['filters']['php']['table'] = 'views';
$handler->display->display_options['filters']['php']['field'] = 'php';
$handler->display->display_options['filters']['php']['use_php_setup'] = 0;
$handler->display->display_options['filters']['php']['php_filter'] = '$front_url = variable_get(\'site_frontpage\');
$url_parts = explode("/", $front_url);
if ($url_parts[0] == \'node\' && $url_parts[1] == $data->nid) {
  return FALSE;
}
else {
  return TRUE;
}';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'front-view-node';

```

---
Tags: views
---


# Question
Title: User register and login functions are called from hook_form_alter, but user isn't logged in
**Background**

I'm attaching the user register form, to the node create form with `hook_form_alter`. that way I create a node and user at once.

In order to validate and register the user, in `hook_form_alter` I add the relevant functions to my node form submit and validation calls.

```
function mymodule_form_alter form_alter(&$form, &$form_state, $form_id) {
   ....

    $form['#validate'][] = 'user_account_form_validate';
    $form['#submit'][] = 'user_register_submit';

```

**Problem**

The node is created and the user is created but the user isn't logged in.

* Why isn't the user logged in?

The user register and login code seems to be running ok (see below), I can only think somehow the node creation is logging the user out? I have no idea how to continue debugging this.

**Debugging**

Thanks to Felix, I was able to debug by logging dpm (because it doesn't appear on the page) and the code is running correctly.

`user_login_submit` is called from `user_register_submit`

```
function user_login_submit($form, &$form_state) {
  global $user;
  $user = user_load($form_state['uid']);
  $form_state['redirect'] = 'user/' . $user->uid;
  user_login_finalize($form_state);
}

```

And then `user_login_finalize` is called.

```
function user_login_finalize(&$edit = array()) {
  global $user;
  watchdog('user', 'Session opened for %name.', array('%name' => $user->name));
  // Update the user table timestamp noting user has logged in.
  // This is also used to invalidate one-time login links.
  $user->login = REQUEST_TIME;
  db_update('users')
    ->fields(array('login' => $user->login))
    ->condition('uid', $user->uid)
    ->execute();

  // Regenerate the session ID to prevent against session fixation attacks.
  // This is called before hook_user in case one of those functions fails
  // or incorrectly does a redirect which would leave the old session in place.
  drupal_session_regenerate();

  user_module_invoke('login', $edit, $user);
}

```

I printed out `$edit` and `$user` and `$edit` is `$form_state` and `$user` is the newly created user. I can't see anything going wrong. The session opening is logged by watchdog, however perhaps it's never assigned?

How else could I continue to debug this? Could `drupal_session_regenerate()` be logging me out?

EDIT: I switched the `user_register_submit` to `logintoboggan_user_register_submit`, which worked on my dev environment but then broke on production with the same problem as above.

It doesn't appear to be a code problem, but something to do with the database or a setting. I dropped my production front end in front of my dev backend and it works fine, so it's some sort of database setting (which could of course effect the front end code).

# Answer
Well the minute I put up a bounty I spot the answer. The problem was the switch between HTTPS and HTTP was killing my session. I'd accidentally secured the URL Alias not the actual URL.

Spotted it from another bountied question answer by @Alexei Reyu so waiting to see if he'll come and put his answer up here.
> 2 votes

# Answer
If a redirect is happening after print('x') then it will be lost. dmp() should show up however I prefer using Devel Debug Log in these instances so you know if then code is running then it will output to the log.

You can use the function ddl('log message') or ddl($array) and then check the report of what has been output once your code has run.

I realise this isn't actually answering your question but may make debugging easier...
> 2 votes

# Answer
```
       1.  https://drupal.org/node/1545970
       2.  http://drupal.org/node/910598

```

It is may be problem of https and http . check session variables is present or not.Please check this both ulr. it is may be help to your output
> 0 votes

---
Tags: 7, users, forms
---


# Question
Title: Modifying my theme's template.php requires apache restart to see changes
When I make modifications to my .tpl.php file, I assure that changes are "reloaded" by executing "drush cc all".

But when I change my template.php file, the only way I have to see the output of my new code, such as adding a simple dpm($form) statement, is by restarting apache.

I've tried:

* drush cc all
* Devel module -\> Clear cache.
* Configuration -\> Performance -\> Clear all caches.
* Check that in Configuration -\> Performance -\> CACHING -\> disabled.
* Clear browser cache.
* Test it in a different browser.

But the changes only appear when I issue /etc/init.d/httpd restart.

Any idea of why?

# Answer
Thanks to Clive and MPD, that pointed to the answer.

It was because of APC.

I've installed the module apc\_admin, which allows to access the APC interface (apc.php) from within drupal (Configuration » Development » Performance » APC). That includes the "**Reset APC cache**" button. Just by pressing it, the changes in my template will show up.

Hope this helps also other users.
> 0 votes

---
Tags: 7, caching
---


# Question
Title: Selectively applying image style to a class
On a page that displays pictures that have two different classes, how to I apply an image style to one class and not to the other?

Or, how do I apply different image styles to images that have different classes?

Thanks. :)

# Answer
Image styles and HTML classes on images are completely unrelated, so you would have to do some sort of manual hack to achieve this. A very basic effort might be to use `hook_preprocess_image_style` like so:

```
function MYTHEME_preprocess_image_style(&$vars) {
  if (array_search('some-class', $vars['attributes']['class']) !== FALSE) {
    $vars['style_name'] = 'some_style';
  }
  elseif ($another_condition) {
    $vars['style_name'] = 'some_other_style';
  }
}

```
> 1 votes

---
Tags: media
---


# Question
Title: Is there a way to avoid implementing a logic in the view template?
Some where I have read that we should use views template xxxxx.tpl.php file to not implement complex logic. I want to show a search results message to the user. The message is not made of mere row count but it has little bit of logic depending on what options he has selected.

I have implemented this logic in my view mymodule-view-grid--apartments--listing-row-filtered.tpltemplate.tpl.

I don't think this is complicated logic that's why I went on and implemented this logic but a question always bothers me is that where should I implement this logic if at all I have to implement it outside and how to pass this variable to this template.

```
<?php

  $view = views_get_current_view();
  $rowCount = $view->total_rows;

  isset($view->exposed_input['field_location_tid'])?$ltid = $view->exposed_input['field_location_tid']:$ltid = 'All';

  //force to all if landing directly
  $city = taxonomy_term_load($view->exposed_input['field_city_tr_tid'])->name;
  $locationName = $ltid == 'All'?'':' in ' . taxonomy_term_load($view->exposed_input['field_location_tid'])->name;
  //
  $resultText = "Properties in $city: Your search criteria matched $rowCount properties$locationName";

?>

<h3><?php print($resultText);?></h3>
... and rest of the template follows unchanged

```

# Answer
> 3 votes
Templates are for displaying content, not building it, so you're right to want to avoid this.

Drupal allows you to preprocess any theme function to add variables. I guess in your case it would be something like

```
function MYTHEME_preprocess_views_view_grid(&$vars) {
  if ($vars['view']->name == 'some_view') {
    $vars['foo'] = markup_building_function();
  }
}

```

Then back in the template file you can output that var like so:

```
<?php echo $foo; ?>

```

---
Tags: views, theming
---


# Question
Title: Views Slideshow gives duplicate row classes
I use views\_slideshow and I use it's option Items Per Slide and I set it to 2, so it shows two nodes at a time. Problem is now, I cannot give both nodes separate styling, i.e. I want first row to have padding to right and second row to have padding to left, I could do that if it didn't have identical row-number classes:

>

# Answer
> 0 votes
You could easily achieve what you need with a small workaround using css pseudo classes `:first-child` and `:last-child`, apply them to the surrounding div and easily get the paddings for first and last elements. See this and this.

---
Tags: theming, views
---