# Question
Title: Adding a product field to cart summary in views
I have a product image and product description as fields in the product entity. I want to add them to the cart summary displayed in the checkout, specifically it's the view "Shopping cart summary"

I added a relationship to the view: (Line items referenced by commerce\_line\_items) Commerce Line item: Product

And I added the two fields to the view.

When I preview it with an order number it works perfectly. the 2 fields are displayed as expected. But on the checkout page, the cart summary is blank...

What am I missing? How can i possibly debug this situation?

# Answer
> 1 votes
If anyone is interested, I found the answer here: https://drupalcommerce.org/discussions/1128/product-image-cart-form

It is a permissions issue. The solution was to enable the permission "view any product of any type" for anonymous users.

---
Tags: 7, views, commerce
---


# Question
Title: How to output child links based on the current page
When landing on a page which has a menu item that is a parent to other pages menu items, I would like to be able to show a list of those child menu items. I am using the following code.

```
$trail = menu_get_active_trail();
menu_build_tree('main-menu', array(
  'expanded' => array($trail[1]['mlid'])
));

```

However, the returned array looks like this (with a lot of unnecessary removed).

```
array
'49950 PKY Truck Beauty 312' =>
array
  'link' => &
    array
      'menu_name' => string 'main-menu' (length=9)
      'mlid' => string '312' (length=3)
      'plid' => string '311' (length=3)
  'below' =>
    array
      '49952 Seminars 314' =>
        array
          'link' => &
            array
              'menu_name' => string 'main-menu' (length=9)
              'mlid' => string '314' (length=3)
              'plid' => string '311' (length=3)
      '50000 HDMA Breakfast 316' =>
        array
          'link' => &
            array
              'menu_name' => string 'main-menu' (length=9)
              'mlid' => string '316' (length=3)
              'plid' => string '311' (length=3)
      '50000 MATS Concert 315' =>
        array
          'link' => &
            array
              'menu_name' => string 'main-menu' (length=9)
              'mlid' => string '315' (length=3)
              'plid' => string '311' (length=3)

```

Notice how 314, 315, and 316 are 'below' 312? They are siblings in my menu structure, and that seems to be verified by each one having the same value for `plid` (311). Obviously I can fix this by passing the array through another function, but I can't help but think I'm just missing something.

# Answer
> 8 votes
Just wanted to follow-up. I came back to this question and found the following: https://stackoverflow.com/questions/2716787/how-to-get-all-the-menu-items-below-a-certain-parent-in-drupal which is exactly what I needed.

The code, copied from the above-mentioned link and modified to fit my needs (mainly to use the current path to build the menu tree from, rather than using a hard-coded value:

```
$parent = menu_link_get_preferred($_GET['q']);
$parameters = array(
  'active_trail' => array($parent['plid']),
  'only_active_trail' => FALSE,
  'min_depth' => $parent['depth']+1,
  'max_depth' => $parent['depth']+1,
  'conditions' => array('plid' => $parent['mlid']),
);

$children = menu_build_tree($parent['menu_name'], $parameters);

return '<div class="content-sub-menu content-padder">' . drupal_render(menu_tree_output($children)) . '</div>';

```

# Answer
> 6 votes
It can easily be done with using **Menu block module** (it takes about 5 minutes to configure it).

All you have to do is

1. Enabling the module
2. Going to `admin/structure/block`
3. Clicking "Add menu block"
4. Set "Starting level" to "2nd level (Secondary)" and setting the region where it should be displayed under *"Specify in which themes and regions this block is displayed."*
5. Screenshots:

* This is the way the configuration page looks like
    * admin/structure/block page with the enabled Menu block module blocks
    * I generated some "Basic page" contents with Devel module, and provided some menu links to them, and created a nested menu hierarchy

    + This is the default front page with no submenus (The "Main menu - 2nd level" block can NOT be seen in the left sidebar, as it doesn't have any second level child items)
        + This is the second menu, with some child elements, you can already see the "Main menu - 2nd level" in the left sidebar, but only the 2nd level child elements can be seen
        + Now going deeper:

I think that using *Menu block* module for this task is one of the easiest and fastest solutions.

# Answer
> 0 votes
As noted in the comments, I ended up using the API function and then styling with CSS:

```
/* --------------- *\
    Sub-menus
    used on main pages
\* --------------- */
.content-sub-menu ul.menu {
  list-style: none;
  padding: 0;
  margin: 0;
}
.content-sub-menu > ul.menu {
  margin-bottom: 25px;
}
.content-sub-menu ul.menu a {
  font-size: 1.5em;
  padding: 10px;
  margin-top: 5px;
  display: inline-block;
  min-width: 33%;
}

```

# Answer
> 0 votes
This functions working correctly to get sub-menu of current page:

```
function build_left_menu()
{
    global $language_url;
    static $use_theme = NULL;
// Get the entire main menu tree
    $left_menu_tree = menu_tree_all_data('main-menu'); // Your main menu
$left_menu_tree_values = array_values($left_menu_tree); //get value only
    $html = "<div id=\"sidemenu\"><ul id=\"side-nav\" class=\"side-nav-content\"><h3>In this section:</h3>";
foreach ($left_menu_tree_values as $index => $item) {
        $link = $item["link"];
        if ($index === 0) {
            $item_class = "first-item panel side-menu ";
        } else {
            $item_class = "panel side-menu ";
        }
        $options_anchor = array();
        if ($item["below"]) {
            $options_anchor = array("attributes" => array('class' => array('dropdown-toggle'),
                'data-toggle' => 'dropdown',
                'data-delay' => 1000,
                'data-close-others' => "false",
                'data-hover' => "dropdown",
            )
            );
        }
        // Merge in defaults.
        $options_anchor += array(
            'attributes' => array(),
            'html' => FALSE,
        );

        //Default needed class
        $options['attributes']['class'][] = 'subpage-link collapsed';
        // Append active class.
        if (($link['link_path'] == $_GET['q'] || ($link['link_path'] == '<front>' && drupal_is_front_page())) &&
            (empty($options_anchor['language']) || $options_anchor['language']->language == $language_url->language)) {
            if ($item["below"]) {
                foreach ($item["below"] as $item_below) {
                    $link_below = $item_below["link"];
                    $options_anchor = array();
                    $html .= "<li class='" . $item_class . "'>";
                    $html .= override_left_l($link_below['link_title'], $link_below['link_path'], $options_anchor).'</li>';
                }
            }
        }
    }
    $html .= "</ul></div>";
    return $html;
}

```

Hope this help!

# Answer
> 0 votes
I have just finished posting a function that gets child menu items given a node's path. You can check it here: http://softkube.com/blog/getting-child-menu-items-drupal-menu-tree

I'm including the link to future proof the answer in case the post gets updated and I'll also copy/paste the full code at the end.

In your case, you can simply run something like this in your theme to list all child menu items. Modify the `echo` statement and theme to your liking.

```
$path = current_path();
$nids = skl_get_all_menu_node_children_ids($path);
$children = node_load_multiple($nids);
foreach($children as $c) {
    echo $c->title . ': ' . url('node/' $c->nid) . '<br />';
}

```

And here's the function's full code. Check the link for possible future updates.

Good luck.

```
/**
 * Returns node ids of all the child items, including children of children
 * on all depth levels, of the given node path. Returns an empty array
 * if any error occurs.
 *
 * @param string $node_path
 * @return array
 */
function skl_get_all_menu_node_children_ids($node_path) {
    //Stop and return an empty array if node path is empty
    if(empty($node_path)) {
        return array();
    }

    //Init empty array to hold the results
    $nids = array();

    //Init parent keys. Check 'foreach' loop on parent keys for more info.
    $parent_keys = array('plid', 'p1', 'p2', 'p3', 'p4', 'p5', 'p6', 'p7', 'p8', 'p9');

    //Collect menu item corresponding to this path to begin updates.
    //Reference: http://stackoverflow.com/a/11615338/136696
    //Note: we couldn't find a way to get the sub-tree starting from this item
    //only and hence we had to get the whole menu tree built and then loop on
    //the current item part only. Not so bad considering that Drupal will
    //most probably have the whole menu cached anyway.
    $parent_menu_item = menu_link_get_preferred($node_path);

    //Stop and return empty array if a proper current menu item couldn't be found
    if(empty($parent_menu_item['menu_name']) || empty($parent_menu_item['mlid'])) {
        return array();
    }

    //Init parent item mlid for easier usage since now we know it's not empty
    $parent_menu_item_mlid = $parent_menu_item['mlid'];

    //Build whole menu based on the preferred menu_name gotten from this item
    $menu = menu_build_tree($parent_menu_item['menu_name']);

    //Reset menu cache since 'menu_build_tree' will cause trouble later on after
    //you call pathauto to update paths as it can only be called once.
    //Check: https://www.drupal.org/node/1697570
    menu_reset_static_cache();

    //Init processing array. This will hold menu items as we process them.
    $menu_items_to_process = array();

    //First run to fill up the processing array with the top level items
    foreach($menu as $top_level_menu_item) {
        $menu_items_to_process[] = $top_level_menu_item;
    }

    //While the processing array is not empty, keep looping into lower
    //menu items levels until all are processed.
    while(count($menu_items_to_process) > 0) {
        //Pop the top item from the processing array
        $mi = array_pop($menu_items_to_process);

        //Get its node id and add it to $nids if it's a current item child
        //Note that $parent_keys contains all keys that drupal uses to
        //set a menu item inside a tree up to 9 levels.
        foreach($parent_keys as $parent_key) {
            //First, ensure the current parent key is set and also mlid is set
            if(!empty($mi['link']['mlid']) && !empty($mi['link'][$parent_key])) {
                //If the link we're at is the parent one, don't add it to $nids
                //We need this check cause Drupal sets p1 to p9 in a way you
                //can easily use to generate breadcrumbs which means we will
                //also match the current parent, but here we only want children
                if($mi['link']['mlid'] != $parent_menu_item_mlid) {
                    //Try to match the link to the parent menu item
                    if($mi['link'][$parent_key] == $parent_menu_item_mlid) {
                        //It's a child, add it to $nids and stop foreach loop.
                        //Link_path has the path to the node. Example: node/63.
                        if(!empty($mi['link']['link_path'])) {
                            $nids[] = str_replace('node/', '',
                                      $mi['link']['link_path']);
                            break;
                        }
                    }
                }
            }
        }

        //Add its child items, if any, to the processing array
        if(!empty($mi['below']) && is_array($mi['below'])) {
            foreach($mi['below'] as $child_menu_item) {
                //Add child item at the beginning of the array so that when
                //we get the list of node ids it's sorted by level with
                //the top level elements first; which is easy to attain
                //and also useful for some applications; why not do it.
                array_unshift($menu_items_to_process, $child_menu_item);
            }
        }
    }

    //Return
    return $nids;
}

```

# Answer
> 0 votes
@Chris Rockwell and @ Mario Awad

I am newbie in Drupal so its hard to understand for me where to add this function.. I apologize for that. But, can you guys please mentioned it that In which file, should we add this function?

I am trying to create side bar navigation that will display only child elements on each page. How to create navigation menu on sidebar with different navigation links displayed on different pages?

I Appreciate!

Thanks!

---
Tags: routes
---


# Question
Title: RewriteRule fails if called after line 112 of .htaccess
I'm having an issue that is similar to this question.

In short, I'm trying to use some custom RewriteRules to point old (no longer functioning) urls to new working urls. To accomplish this, I'm trying something similar to:

```
RewriteRule ^oldsite/directory/ABCD(.*)\.html? /search/$1 [NC,R=301,L]

```

The issue is, this is completely ignored (as mentioned in the question linked to before.) However, I've noticed that if I move my RewriteRule from the bottom of the .htaccess file up a bit to line 112, which is:

```
# 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]

```

The the rewrite rules work just perfectly fine. The answer to the previous question said that you couldn't use a clean url destination. So this would work:

```
RewriteRule ^home/code/([^/]+) ?q=home/software/node/&code=$1

```

but this won't:

```
RewriteRule ^home/code/([^/]+) home/software/node?code=$1

```

Problem is neither of them seem to work for me. I remember a few D7 updates ago there was an update to the .htaccess files. Could that be effecting this? Is there another way around this issue to get RewriteRules to work?

# Answer
> 2 votes
Just put it above line 112. The reason it doesn't work below that is line 117:

```
RewriteRule ^ index.php [L]

```

that \[L\] means that if the conditions above it match and that rule is applied no further rules will be checked. If you put it above that line clean or non-clean style url will work fine but probably don't want to include an L on the end of your rule so use:

```
RewriteRule ^home/code/([^/]+) home/software/node?code=$1 [R=301,NC]

```

on line 111 (well whatever actual content rule you need).

# Answer
> 0 votes
RewriteRule has issues for some reason, but RedirectMatch doesn't. I suspect this is because the RedirectMatch is part of mod\_alias, and the RewriteRule stuff is part of mod\_rewrite. Both get applied, but at different points in the processing, and is likely RedirectMatch is better suited in this situation.

So instead of:

```
RewriteRule ^oldsite/directory/ABCD(.*)\.html? /search/$1 [NC,R=301,L]

```

use:

```
RedirectMatch 301 /oldsite/directory/ABCD(.*).html$ /search/$1

```

Not sure why this works, but it does work.

---
Tags: 7, redirection, .htaccess
---


title: Limiting Date (Hours) In Form

text:
# Question
Title: Limiting Date (Hours) In Form
How can i limit Hours in Date field ? like it begins in 12 untill 21:00 . Any idea would be appreciate it ?

# Answer
The 'date restrictions' module might be what you need https://www.drupal.org/project/date\_restrictions
> 0 votes

---
Tags: datetime
---


# Question
Title: Blocks aren't being assigned to a region
Is there any reason that these blocks wouldn't be assigned to the regions specified? The only way I can get these to appear is to set them manually. Kinda defeats the purpose of defining a region in the first place.

```
function custom_module_block_info() {

  $blocks = array();
  $blocks['footer_touts'] = array(
    'info' => t('Footer Touts'),
    'status' => TRUE,
    'region' => 'footer',
  );

  $blocks['carrousel'] = array(
    'info' => t('Carrousel'),
    'status' => TRUE,
    'region' => 'hp_content',
    'visibility' => BLOCK_VISIBILITY_LISTED,
    'pages' => '<front>',
  );

  return $blocks;
}

```

# Answer
*(Luis already answered eir own question, in the comments above, but I thought I'd add something here; all kudos to Luis though.)*

The `status` property returned by a module's implementation of hook\_block\_info() must be `TRUE`. This is slightly unintuitive because when enabling blocks in the UI, one only has to choose the region—however, in doing so a block's status is also changed. Programmatically, we must set both `status` and `region` properties. (I'm not sure there would ever be any reason to set one and not the other.)

When doing this to an already-enabled module, it would seem that clearing the block cache (`drush cc block`) is not enough, nor is dis- and re-enabling the module; it must be uninstalled and reinstalled for the change to take effect (`drush dre custom_module` if you've got Devel).

Note also that Drush seems to get confused when doing this with a region that doesn't exist in the default theme (reporting that *"The block Carrousel was assigned to the invalid region hp\_content and has been disabled."*). This is not true; the block *is* enabled.
> 0 votes

---
Tags: 7, blocks
---


# Question
Title: How to show Comments (created with entity form) only to the Admin user and logged in?
I'm cool fresh drupal :)

I'm trying to filter views in a content type entityform for the user logged in and admin. In practice this form through the admin and user login should communicate.

problem: On page dein results I see only the one who wrote the admin, but the user responses.

Then I node (private area) with filtered content to the user, so each user sees the content added by the administrator for each user.

I would like each user to comment on the content that the administrator has reserved for each user.

Now I tried with modules or with the comments of core drupal views of seeps into single user comments and the admin.

example: There are three users, User "A" User "B", User "C", Each of these users comments posted content dall'aministratore reserved for them. The administrator shall have commmenti User "A".

The same node (private area) would like to display the comments and views with only the user "A" and the responses made administrator user "A". And so also for users B, C, D, F etc. ...

I hope to be as clear as possible. :)

Where am I wrong? help me. :)

Sorry for my bad english

# Answer
> 0 votes
You might try updating PERMISSIONS. By default, EntityForms only allows administrator to view, edit, or delete. If you want a user to be able to view their own EntityForm submissions, you have to update the permission for this. You can find it under PEOPLE-\>PERMISSIONS-\>EntityForms-\>View own entityform submissions-\> \[check\] AUTHENTICATED USER.

Good Luck!

Chrisjan

---
Tags: views, comments, entities
---


# Question
Title: Set path for favicon.ico and apple-touch-icon.png
I would like my favicon.ico to be accessible by http://example.com/favicon.ico and http://example.com/apple-touch-icon.png, but I can't manage that. I tried few things, but nothing helped. My favicon.ico/apple-touch-icon.png is located in the theme root folder.

How can I achieve this?

# Answer
> 2 votes
use a symlink, I typically keep my main favicon in my root theme folder, and then in the terminal navigate to the site root and symlink to that icon

```
ln -s PATH/TO/THEME/favicon.ico

```

it makes the most sense to me to keep my theme assets in my theme directory, but then I also like to have the same favicon accessible from the doc-root as well

# Answer
> 0 votes
Use Sumit Madan's answer for favicon.

You can put the touch-icon in the files folder too. And edit yourtheme's template.php

Put this:

```
  $appleIcon = array('#tag' => 'link', '#attributes' => array('href' => '/sites/default/files/apple-touch-icon-144x144.png', 'rel' => 'apple-touch-icon', 'type' => 'image/png'),);
  drupal_add_html_head($appleIcon, 'apple-touch-icon');

```

inside

```
function yourtheme_preprocess_html(&$variables) {

}

```

# Answer
> 0 votes
I would personally just do a .htaccess Rewrite rule:

```
RewriteCond %{REQUEST_URI} /favicon.ico
RewriteRule ^ /actual/path/to/favicon.ico

```

and same for apple touch icon

# Answer
> -1 votes
Just place your image in root folder and add the path as in screenshot :

---
Tags: files
---


# Question
Title: theme_hook_suggestions is ignoring my suggestions
I'm working in Drupal 7.

I'm trying to add a custom template file for a few pages I'm creating. I've done so in hook\_preprocess\_page in my template.php file.

This is the scenario:

I have four "Basic Page" pieces of content that will use the same template file. I've already coded page.tpl.php for other "Basic Page" content. The reason I want this template is because the look of these four basic pages is different from other pages. What I've done is added my suggestion to the theme\_hook\_suggestions array. It's ignoring what I'm adding. Just a note: after every step I'm clearing my caches. It isn't that.

I've tried this:

```
$variables['theme_hook_suggestions'][] = 'newbies';

```

This will add the 'newbies' suggestion to the array, but creating a 'newbies.tpl.php' file gets me nowhere. It's ignored. I've gone as far as doing this:

```
$variables['theme_hook_suggestions'] = array(0=>'newbies');

```

Which erases the suggestions array and adds only my suggestion, which I've verified with krumo. This also doesn't do anything and is ignored. My site doesn't even break when I do it.

From what I've read about theme\_hook\_suggestions, it would seem that Drupal only wants template suggestions for templates that it defines. For example, just creating an arbitrary template file (in this case 'newbies') instead of some system defined one like 'page--type--system--node......' etc.. will never work. I've decided to rule that out as being truth for now because I refuse to believe that a design flaw of that magnitude could be introduced into any software.

What am I missing?

# Answer
You're missing how the framework is designed.

If you're doing anything with hook\_preprocess\_page() you are affecting the 'page'.

The default template for page is 'page.tpl.php'.

If you want to 'override' this template Drupal needs to understand what's going on so has some conventions.

```
page--[front|internal/path].tpl.php

page--node--edit.tpl.php
page--node--1.tpl.php
page--node.tpl.php
page.tpl.php

```

*"Theme hook suggestions are made based on these factors, listed from the most specific template to the least. Drupal will use the most specific template it finds"*

See: http://drupal.org/node/1089656 and http://drupal.org/node/223440#custom-suggestions

In your case, your defining 'newbies.tpl.php' and expecting this to work but it's still going to use 'page.tpl.php' so to override this you want to do 'page--newbies.tpl.php' (same as 'page--node.tpl.php').

More to the point, you don't even need to set this with hook\_preprocess\_page() as Drupal will follow those conventions automatically.
> 4 votes

# Answer
I've struggled with this on many occasions and it still confuses the hell out of me, but I think I got it figured out finally (or again...):

If you try to overwrite a page with *hook\_preprocess\_page* your tpl filename **must** start with 'page--'. The next pitfall is that all hyphens will get replaced by underlines.

So let's say you want to overwrite the page.tpl and your file is called:

```
page--something-with-hyphens.tpl.php

```

Then your hook should look something like that:

```
mymodule_preprocess_page(&$vars) {
   if(something) {
      $vars['theme_hook_suggestions'][] = 'page__something_with_hyphens';
   }
}

```

Same goes for html.tpl overwrites. Just they have to start with 'html--'.

And do not forget to clear caches if you make a change :-)
> 2 votes

---
Tags: theming
---


# Question
Title: When managing fields for a content type, fields of type "list (integer)" can't be shared?
In the drop-down for "add existing field" not all fields are available for reuse. Specifically I would like to reuse a field of type "list (integer)" because I will be adding 300 of them to my content type with exactly the same settings (just different labels and machine names). Doing the manually is going to take me over eight hours since it takes about 1.5 min to add a field and configure it's settings. Is it possible to reuse fields of type "list (integer)"?

Thanks!!

ps: if you are unsure what I mean by reusing a field see here: Documentation for Field-UI and look at the section titled, "Reusing Fields".

# Answer
Here's the answer to this question:

I cannot use the same field within one content type. Only one instance of a field may be used within each content type. This is why the field which I have created is not showing up in the drop-down for "add existing field" - it is not available.
> 1 votes

# Answer
As you say, you can only have one instance of a field in each content type. To share a list of options between multiple fields of a content type (say, a list of colours for 'background colour' and 'foreground colour' fields), I think your best bet would be to set up a separate content type ('Colour' in this example) and then create multiple entity reference fields that point to it.
> 0 votes

---
Tags: entities, nodes
---


title: hook_form_alter isn't working

text:
# Question
Title: hook_form_alter isn't working
I've been trying to insert a placeholder for my search-bar, so in my page.preprocess.inc I call `hook_form_search_block_form_alter()`, then specify the form's array, and create the placeholder array, but it doesn't work. I've tried multiple things but none of them seem to affect the form in any way. I use devel themer, as both the devel page array and `<?php dpm() ?>` don't seem to work on my frontpage. My alternative would be to use jquery but I'd rather have this work then having to resort to the longer method.

Here's what I'm working with:

theme name - hitech\_wolf

**EDIT:** I'm using omega4

PAGE.PREPROCESS.INC

```
    <?php
        // Can Ignore, left in here just in case it influences the alter statement
        /**
         * Implements hook_preprocess_page().
         */
        function hitech_wolf_preprocess_page(&$variables) {
            $path = drupal_get_path('theme','hitech_wolf');
            drupal_add_js($path . '/js/iframe_colorbox_support.js');
        }

        /**
         * Implements hook_form_alter().
         */
    // Separate Attempts - present for example
    function hitech_wolf_form_search_block_form_alter(&$form, &$form_state) {
      $form['search_block_form']['#placeholder'] = array(
        t('Search...'),
      );
    }
    function hitech_wolf_form_search_block_form_alter(&$form, &$form_state) {
      $form['search_block_form']['#attributes'] = array(
        'placeholder' => t('Search...'),
      );
    }
    function hitech_wolf_form_alter(&$form, &$form_state) {
      if ($form_id == 'search_block_form') {
        $form['search_block_form']['#attributes']['#placeholder'] = t('Request your username');
      }
      if ($form_id == 'search_block_form') {
        $form['search_block_form']['#attributes'] = array('placeholder' => t('Request your username')
    );
  }
}
        // Check if anything works at all - doesn't
        function hitech_wolf_form_alter(&$form, &$form_state, $form_id) {
          hide($form);
        }
        function hitech_wolf_form_alter(&$form, &$form_state, $form_id) {
          unset($form);
        }

```

PICTURES - form id/location

# Answer
`hook_form_alter()` belongs to template.php, or in a module, as only there it can be recognized; it doesn't work the same as preprocess functions. See also this Reddit.
> 2 votes

---
Tags: forms, theming, debugging
---


# Question
Title: how do I add check boxes in form created with the Registration module?
I am getting a radio button in my form as default, but I want a checkbox.

I am using the Registration and the Entitiy Registration modules. How can I do that?

# Answer
At the time of Field Creation.

Select **FIELD TYPE : List (text)**

Select **WIDGET : Check boxes/Radio buttons** & save

> **Allowed values list :**
>
> **1|list1**
>
> **2|list2**
>
> **3|list3**

& save field setting.

You see that radio buttons are shown.

Now in **FIELD SETTINGS** : Select **Number of values : Unlimited** & save.
> 0 votes

---
Tags: 7, entities, users
---


title: Can you disable Rules Components?

text:
# Question
Title: Can you disable Rules Components?
Is there a way to disable a Rules Component? And if so, -how-?

Using Commerce, I've set up various Sales Taxes. If I understand, the Rule for Sales Tax triggers all 'Components' to be evaluated which are of type Sales Tax and then executes any/all that match the condition.

But in our case, we -know- ahead of time, that some of those Components will never be executed, so I was hoping for a way to prevent them from being evaluated and thus speed execution.

I'd prefer to keep some Components 'disabled' rather than delete them in case we need them in the future or for importing old orders.

# Answer
You can't disable Components.

* Components are configurations, so they already have an 'active' field available.
* Actions would be more difficult to disable.

You may read read from here Components: enable / disable
> 0 votes

---
Tags: rules, commerce
---


# Question
Title: Date module shows time field +5:30 ahead from input
I am using Date module with date popup . And I am creating these node pro grammatically and saving dates to them like:

```
$node->field_task_time[LANGUAGE_NONE][0]['value'] = "2014-12-18 23:15:00";
$node->field_task_time[LANGUAGE_NONE][0]['timezone'] = "Asia/Kolkata";
$node->field_task_time[LANGUAGE_NONE][0]['timezone_db'] = "UTC/GMT";
$node->field_task_time[LANGUAGE_NONE][0]['date_type'] = "datetime";

```

The values in db are stored correctly but when I edit this node form the values in the date field shows 2014/12/18 and in time field it shows 4:15. i Don't know what's happening .

# Answer
> 2 votes
It seems as default behavior of date module if you check its documentation you can see:

Time zone handling

**There are 5 different options for field Time zone handling:**

**Site's time zone -** When entering data into the field, the data entered is assumed to be in the site's time zone. When the data is saved to the database, it is converted to UTC. When retrieved from the database, the data is converted to the Site's time zone for anonymous users or the User's time zone for logged in users when User-configurable time zones is enabled.

**Date's time zone -** With this option enabled, the date field adds a select box to explicitly specify the time zone for the date entered. When the date is saved to the database, it is not converted & the time zone information is saved with the date. When retrieved from the database, no conversion is performed and the date is displayed exactly as entered.

**User's time zone** \- When entering data into the field, the data entered is assumed to be in the user's time zone. When the data is saved to the database, it is converted to UTC. When retrieved from the database, the data is converted to the Site's time zone for anonymous users or the User's time zone for logged in users when User-configurable time zones is enabled.

**UTC** \- When entering data into the field, the data entered is assumed to be in UTC time zone. When the data is saved to the database, it is converted to UTC (e.g. no conversion necessary). When retrieved from the database, the data is converted to the Site's time zone for anonymous users or the User's time zone for logged in users when User-configurable time zones is enabled.

**No time zone conversion** \- The date entered is not converted when saved to the database. When retrieved from the database, the data is NOT converted and is displayed exactly as entered.

so currently your settings are in site's timezone which is assuming that you entered date is in UTC hence the retrieved date is site's timezone which is UTC+5:30 **switch setting s to No time zone conversion and you can see retrieved date as entered one.**

---
Tags: datetime
---


# Question
Title: How do I alter the Price Component Title in Commerce Userpoints Discount without altering the module?
It seems that when a user adds a Userpoints Discount line item to their shopping cart it appears in the footer as 'Royalty', which will be totally confusing to users.

On line #382 of commerce\_userpoints\_discount.module there is this code:

```
function commerce_userpoints_discount_commerce_price_component_type_info() {
  return array(
    'userpoints' => array(
      'title' => t('Royalties'),
      'display_title' => t('Royalties'),
      'weight' => 1000,
    ),
  );
}

```

Without hacking this module, is there a way I can change this description? In my case, we will be using -two- Userpoints currencies (depending on the type of product the user orders) and we would like the description in the footer to be that userpoints description.

What I've already tried is to create my own hook with a higher weight. My hope was that my hook would take precedence over the default, but apparently not. Perhaps I don't understand 'hooks' well enough yet. If so, could someone tell me how to make -my- hook take precedence?

```
function my_module_commerce_price_component_type_info() {
  return array(
    'userpoints' => array(
      'title' => t('My Userpoints Currency'),
      'display_title' => t('My Userpoints Currency'),
      'weight' => 2000,
    ),
  );
}

```

In short, we want the Price Component title to match the currency type of Userpoints on the line item.

# Answer
> 0 votes
The implementations of `hook_commerce_price_component_type_info()` are invoked from `commerce_price_component_types()`, which uses the following code.

```
  // If it did not exist, fetch the types now.
  if (!isset($component_types)) {
    // Find components defined by hook_commerce_price_component_type_info().
    $component_types = module_invoke_all('commerce_price_component_type_info');

    // Add default values to the component type definitions.
    foreach ($component_types as $name => &$component_type) {
      $component_type += array(
        'name' => $name,
        'display_title' => $component_type['title'],
        'weight' => 0,
      );
    }

    // Allow the info to be altered by other modules.
    drupal_alter('commerce_price_component_type_info', $component_types);
  }

```

As with other hooks, if you want to alter what an hook implemented from another module returns, you need to implement an alter hook.

In your case, the code should be similar to the following one.

```
function my_module_commerce_price_component_type_info_alter(&$component_types) {
  if (isset($component_types['userpoints'])) {
    $component_types['userpoints']['title'] = t('My Userpoints Currency');
    $component_types['userpoints']['display_title'] = t('My Userpoints Currency');
    $component_types['userpoints']['weight'] = 2000;
  }
}

```

Generally speaking, this is only possible when the module using the hook is also calling `drupal_alter()`, such as in this case.

---
Tags: commerce, userpoints
---


# Question
Title: Is there a way to disallow spaces in the user name registration form in drupal 7?
I hate spaces in usernames, a user can easily add two or more spaces without realizing it. I need to have more control over the username format than Drupal allows by default.

# Answer
> 9 votes
I recently wrote a custom module to disallow spaces and other characters in usernames. Feel free to comment on the code. I also modified username\_check to do the same validations in the ajax callback.

```
//implement hook_form_FORM_ID_alter
function custom_form_user_register_form_alter(&$form, $form_state, $form_id) {
  //define validation function
  $form['#validate'][] = 'my_user_register_validate';
  //overwrite the username help text
  $form['account']['name']['#description'] = 'Username has to be between 5-15 characters long and can only contain letters and numbers';
}

function my_user_register_validate($form, &$form_state) {

  $output['error'] = FALSE;
  $username = $form_state['input']['name'];
  $password = $form_state['input']['pass']['pass1'];

  if (strlen($username) < 5 || strlen($username) > 15) {
    $output['error'] = TRUE;
    $output['msg'] = t('The username has to be between 5 and 15 characters long. ');
  }
  if (strpos($username,' ') > 0 || strpos($username,'.') > 0 || strpos($username,'-') > 0 || strpos($username,'_') > 0 || strpos($username, "'") !== FALSE ){
    $output['error'] = TRUE;
    $output['msg'] = t('Username cannot contain spaces . - _ ' . chr(39)  );
  }

//display username errors
  if ($output['error']){
    //drupal_set_message( $output['msg'], 'error');
    form_set_error('name', $output['msg']);
  }
}

```

# Answer
> 8 votes
User restrictions contrib module is a replacement for the 'access rules' functionality which was removed from Drupal 7.

You can make an access rule to prevent this with username creation.

Go to **administer » access control, tabs account rules » add rules** (admin/access/rules/add) and add the rules

```
% %
% %

```

(The last line has an ASCII 255 character)

Similar rules for dashes are also possible.

This is based on conversation at drupal.org

# Answer
> 1 votes
You can use a username validation in Drupal7 is easy to remove some type of characters and white spaces and you can add your own type of validation also , please check below function.

```
function my_module_my_form_validate($form, &$form_state) {

//birth year
  $year_of_birth = $form_state['values']['year_of_birth'];
  if ($year_of_birth && ($year_of_birth < 1900 || $year_of_birth > 2000)) {
    form_set_error('year_of_birth', 'Enter a year between 1900 and 2000.');
  }

//username
  $username = $form_state['values']['uname'];
  if (strpos($username,' ') > 0 || strpos($username,'.') > 0 || strpos($username,'-') > 0 || strpos($username,'_') > 0 || strpos($username, "'") !== FALSE ){
    form_set_error('uname','User name cannot contain spaces . - _ ' . chr(39)  );
  }
}

```

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


title: How to display admin login?

text:
# Question
Title: How to display admin login?
I have created two logo block in left and right in my page.tpl.php page. I am not able to see admin login.

Please guide me.

# Answer
if you would like to display it programmically This might be helpful. put it inside `page.tpl.php`. best of luck!

```
$elements = drupal_get_form("user_login");
$form = drupal_render($elements);
echo $form;

```
> 0 votes

---
Tags: users
---


# Question
Title: What would be the best way to setup a mobile theme for an existing domain with domain access module?
We have implemented a multidomain portal using domain access module. Now we would like to setup a mobile site for each domain added.

Initially we thought about going for responsive layout, but as the mobile portal has very simple layout with minimum elements, using responsive model might be an overkill as it load every html elements to mobile even if most of the elements are not used in mobile theme. Also there are few features/blocks like slider etc implemented differently in mobile theme.

The m.domain and separate theme for mobile site looks like a feasible solution. But I am not sure what would be the best way to integrate it with domain access.

We want all content in the desktop domain available in the mobile domain, only theme need to be changed. It would be good if we were able to setup a domain alias where we can provide the m.domain.com in the configuration for the main domain and use the same access control as main domain, only change will be the theme and the links rel="alternate" and rel="canonical"

Also we need to setup a http redirection when a user visit the site from a mobile device. (Any suggestion for switching back to the desktop theme from mobile device and vice versa)

Is there any way to implement something like this using domain access?

# Answer
You need these two modules to do this:

https://www.drupal.org/project/simple\_mobile\_redirect (detects mobiles and redirects them to pre configured paths) &

https://www.drupal.org/project/themekey (serves any theme (e.g. a customized mobile theme) under any pre configured path)
> 1 votes

# Answer
We have finally decided to go with the domain access for the separate m. website.

1. We have to create a domain variable to map the primary domain and its mobile domain
2. Assign all the content added from the primary domain to the corresponding mobile domain also. - This can be done programatically on node save.
3. Need to follow the standard practices for the mobile sites with separate urls. Here is a good documentation regarding what all need to be taken care of when we create a mobile site with different URL - https://developers.google.com/webmasters/mobile-sites/mobile-seo/configurations/separate-urls
4. Implement a UserAgent based mechanism in javascript/JQuery for redirecting the users access the site from a mobile device to m. website.
> 0 votes

---
Tags: 7, domain-access
---


title: hook_menu does not match

text:
# Question
Title: hook_menu does not match
I have a module where I try to catch an url to use a specific function.

```
function my_module_menu(){
    $items['beneficiaire/commande'] = array(
        'page callback' => 'test_view',
    );
    return $items;
}

function test_view(){
    var_dump('test_view');
    exit();
}

```

Unfortunately, when I call beneficiaire/commande nothing append. I know Drupal go through this hook because when I do

```
function my_module_menu(){
    die('poc');
}

```

I see 'poc'.

# Answer
> 0 votes
Your callback function is wrong:

```
function my_module_menu(){
  $items['beneficiaire/commande'] = array(
    'page callback' => 'commande_view',
  );
  return $items;
}

function commande_view(){
  var_dump('test_view');
  exit();
}

```

---
Tags: routes
---


title: Reading a field collection

text:
# Question
Title: Reading a field collection
I am trying to read a field collection and build an array in PHP.

The array I want to build goes like this:(*it's in JS notation but you can easily imagine the equivalent in PHP*)

```
highlights = [
{highlightTitle:A sample test title,
 highlightImage: a sample img url,
 highlightBody: a sample text body},
{highlightTitle:A sample test title,
 highlightImage: a sample img url,
 highlightBody: a sample text body}
]

```

As you can see it is just an array with objects inside, where each object represents a field collection entry. That field collection entry has 3 fields obviously, `highlightTitle`,`highlightImage` & `highlightBody`.

Now I want to read that field collection and build the array I described above.

> The thing I care about is best practises. What is the best possible way to do this?

Currently I use the following code dumped in `<?php ?>` brackets on the top of my layout's tpl files: (*I use Omega 4, and I have different layouts for different content types*)

**This is the code I use now:**

```
  $highlightsArr; //this is the result array
  $highlightsCounter = 0;
  $highlights = field_get_items('node', $node, 'field_highlights');

  foreach ($highlights as $item) {

    $fc = field_collection_field_get_entity($item);
    $highlightSnippet = $fc->field_highlight_snippet["und"][0]["value"];

    $arr = $fc->field_highlight_snippet["und"][$i]["value"];
    $innerArray = entity_load('field_collection_item', array($arr));

    $innerCounter = 0;
    foreach ($innerArray as $item) {

      $highlightsArr[$innerCounter]["sectionItemTitle"] = $item->field_highlights_title["und"][0]["value"];
      $highlightsArr[$innerCounter]["highlightsImage"] = file_create_url($item->field_highlights_image["und"][0]["uri"]);
      $highlightsArr[$innerCounter]["sectionItemPrice"] = $item->field_highlights_body["und"][0]["value"];

      $innerCounter++;
    }
  }

```

**The issue with the above code**:

The code above returns undefined variables/indexes on things that are obviously defined. When I first create a content type and want to view it's node, it returns errors. But as soon as I refresh the page the errors go away which seems rather strange to me.

---

In any case I would like to know best practises for doing this kind of stuff. Unfortunately I come from a strictly JS background (*I'm a front-end dev*), so Drupal and PHP is something new for me.

Many thanks in advance.

# Answer
> 1 votes
> The code above returns undefined variables/indexes on things that are obviously defined.

As long as your PHP installation is not buggy, that's not possible. If the variable is defined, PHP won't tell you it isn't defined.

> as soon as I refresh the page the errors go away which seems rather strange to me.

It's not strange - messages are held in the session so if you're doing something that invokes them in a template file (when the messages for the current page have already been prepared), you should expect to see this delayed reaction. Logic should never been in a template file, always a preprocess or process function.

Best practice is really a matter of opinion, but these are the two standard options for accessing fields on any entity type, Field Collection included.

Both alleviate the need to access the arrays directly, thereby decreasing the possibility of developer error.

# Answer
> 0 votes
I think its because of $i. Try to change the code :

```
$i = 0; // define $i here before foreach
foreach ($highlights as $item) {
  // Your code
  $i++; // Increment $i at end of foreach
}

```

---
Tags: 7, entities
---


# Question
Title: How to view several Colorbox images simultaneously after click on wide screen?
Usually I see only one big overlay image after click thumbnail with Colorbox.

Is there Colorbox settings to view several overlay images simultaneously on wide screen after click?

# Answer
> 0 votes
You need to choose `per page gallery` in colorbox formatter settings like in screenshot :

---
Tags: 7, javascript
---


title: Can I change the path to Drush?

text:
# Question
Title: Can I change the path to Drush?
I am trying to use omega-wizard but I think I am using the wrong version of Drush. I want to use the drush the is in Acquia Dev Desktop but when i type `which drush` I get the one that was last installed with MAMP (running OSX).

When trying to run `drush omega-wizard` I get this message:

```
The drush command 'omega-wizard' could not be found.  Run `drush cache-clear drush` to clear the commandfile cache if you   [error]
have installed new extensions.
                                                                                [error]
Drush was not able to start (bootstrap) the Drupal database.
Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a configured database. In this case you can select another
site with a working database setup by specifying the URI to use with the --uri parameter on the command line. See `drush
topic docs-aliases` for details.
 * connect the database through a socket. The socket file may be wrong or the php-cli may have no access to it in a jailed
shell. See http://drupal.org/node/1428638 for details.

Drush was attempting to connect to:
 Drupal version         :  7.34
 Site URI               :  `http://default`
 Default theme          :  garland
 Administration theme   :  garland
 PHP executable         :  /Applications/Dev Desktop/php5_5/bin/php
 PHP configuration      :  "/Applications/Dev Desktop/php5_5/bin/php.ini"
 PHP OS                 :  Darwin
 Drush version          :  6.2.0
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /Users/khrysztov/Sites/devdesktop/acquia-drupal-7.34.40.6204
 Site path              :  sites/default
 File directory path    :  sites/default/files

```

I cannot see any reference to the database there in the parameters and the default theme is not Garland.

Any ideas?

# Answer
> 0 votes
Answer by Paul worked (thanks):

alias drush='"/Applications/Dev Desktop/drush/drush"'

Needed inner double quotes to allow for space in Dev Desktop.

---
Tags: drush
---


# Question
Title: How to enable user defined module from the administration menu list?
I am beginner to Drupal 7. I am trying to start with Basic Form handling. I created a directory my\_module in sites/all/modules. Created my\_module.info file using notepad with the following contents

```
name = My module
description = Module for form api tutorial
core = 7.x

```

Then I created my\_module.module file with the following contents

```
<?php
/**
 * This function defines the URL to the page created etc.
 * See http://api.drupal.org/api/function/hook_menu/6
 */
function my_module_menu() {
  $items = array();
  $items['my_module/form'] = array(
    'title' => 'My form',
    'page callback' => 'my_module_form',
    'access arguments' => array('access content'),
    'description' => 'My form',
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function my_module_form() {

  // This form calls the form builder function via the
  // drupal_get_form() function which takes the name of this form builder
  // function as an argument. It returns the results to display the form.
  return drupal_get_form('my_module_my_form');

}

/**
 * This function is called the "form builder". It builds the form.
 * Notice, it takes one argument, the $form_state
 */
function my_module_my_form($form_state) {

    // This is the first form element. It's a textfield with a label, "Name"
  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
  );
  return $form;
}

```

But when I goes to module list and tries to enable the newly created module it is not being listed. Kindly help me to resolve this problem. I have gone through several techniques shown in different forums like deleting multiple copies of the files,providing permissions etc.But all in vain.

# Answer
You should follow these steps. This may help you to better understand that how to create *custom module*. If you have any query then comment below.

Link
> 0 votes

# Answer
You can add this to your info file:

package = My custom modules

That will tell drupal to put your module in the fieldset My custom modules. Also if you have the module module\_filter installed, the packages get their own tabs. It should be easier to find your custom module in the module list this way.
> 0 votes

# Answer
First, check the my\_module.info my\_module.module files. Maybe these have a wrong file permissions ? Make sure you dont have file of the same name somewhere else in the folder structure, It could stay from your old 'tests'.

Second, for displaying forms in the way you want you must use drupal\_render() or render()

```
function my_module_form() {
  // This form calls the form builder function via the
  // drupal_get_form() function which takes the name of this form builder
  // function as an argument. It returns the results to display the form.
  return drupal_render(drupal_get_form('my_module_my_form'));
}

```

In D7 drupal\_get\_form returns a renderable array, not HTML.

Another way, you can also get the form directly from the hook:

```
 $items['my_module/form'] = array(
   'title' => 'My form',
   'page callback' => 'drupal_get_form',
   'page arguments' => array('my_module_my_form'),
   'access arguments' => array('access content'),
 );

```
> 0 votes

---
Tags: 7
---


# Question
Title: How to efficiently divide entities into groups based on field values
**Problem**

I'm trying to create job alerts. So every user will select certain filter criteria on their account, which will then be used to perform a search api query returning the relevant new jobs.

To my inexperienced programmer brain this sounds like a lot of queries that will scale terribly.

So I'm trying to construct something which will organise the users into groups who have the same criteria thus avoiding repetition of queries.

(i.e. divide a set of entities into groups based on field values).

My question is, is there a function or commonly used set of procedures for doing this? (Perhaps a module which I could look to for the design?)

Or another option, would the performance change be minimal, because of things like memcache and APC which would cache the queries which repeated?

**My current design**

In order to do this, my current thinking revolves around creating a branching set of queries.

First divide users by field a options, then divide each sub option into field b options and so on.

Each time you'd check to see if you ended up with 0 or 1 users in which case you could stop the tree.

Because I already use SearchAPI and have indexes running for users and nodes I would use this to query. (I'm assuming it would be faster than pulling from the database).

# Answer
> 0 votes
As it turns out implementing the Search API Saved Searches modules is pretty much as easy as turning it on and it works great... No great insights here, just an excellent module.

It allows you to save searches with full facet information (i.e. filter search with 4 different facets and then save that.)

---
Tags: 7, entities
---


# Question
Title: How can I add text into ckeditor textarea in drupal 7?
I'm using ckeditor-7.2 version. How can I set the values to my ckeditor text area from out side.

# Answer
Assuming you want to set some value at the beginning -

Get the id of the form. https://www.drupal.org/project/get\_form\_id

Get the id of the field you want to alter.

Make a small custom module, with hook\_form\_alter() and set #default\_value to that :

```
function YOURCUSTOMMODULENAME_form_alter(&$form, &$form_state, $form_id) {
  if ( YOUR_FORM_ID == $form_id) {
    $form['YOUR_FORM_ID']['YOUR_FIELD_ID']['#default_value'] = 'some default text'
  }
}

```

For adding some text after taht that, use jQuery.

```
$('#input-field-id').val('some text');

```
> 1 votes

---
Tags: 7, wysiwyg
---


title: How to alter a form's name attribute

text:
# Question
Title: How to alter a form's name attribute
I'm trying to override the Drupal Login form. I have been able to unset and modify pieces of it, but the last thing I am struggling with is the name attribute on the submit button. Currently, the button looks like this:

```
 <button class="btn btn-default form-submit" id="edit-submit" name="op" value="Log in" type="submit">Log in</button>

```

I am trying to get rid of the name attribute, but I don't see it listed as a array element when I dpm($form). How do I alter this

EDIT: I almost figured it out. I found that the below can be used to alter the name attribute, but I cant remove it, even if I set it equal to NULL. When set to null, it defaults to 'op':

```
$form['actions']['submit']['#attributes']['name'] = 'submit';

```

# Answer
Ok, I finally found a solution, but if someone has a better one, please let me know.

I found that I wasn't able to modify the name attribute from the hook form alter, so I went higher up. I first tried altering the button with a preprocess function, which didn't work. I was only able to do it by overriding the actual theme\_button. Code below (note: I'm using a bootstrap subtheme):

```
/**
* Overrides theme_button().
*/
function mytheme_button($variables) {
  $element = $variables['element'];
  $label = $element['#value'];
  element_set_attributes($element, array('id', 'name', 'value', 'type'));

  // If a button type class isn't present then add in default.
  $button_classes = array(
    'btn-default',
    'btn-primary',
    'btn-success',
    'btn-info',
    'btn-warning',
    'btn-danger',
    'btn-link',
  );
  $class_intersection = array_intersect($button_classes, $element['#attributes']['class']);
  if (empty($class_intersection)) {
    $element['#attributes']['class'][] = 'btn-default';
  }

  // Add in the button type class.
  $element['#attributes']['class'][] = 'form-' . $element['#button_type'];

  if($element['#type'] === 'submit') {
    unset($element['#attributes']['name']);
  }
  dpm($element);
  // This line break adds inherent margin between multiple buttons.
  return '<button' . drupal_attributes($element['#attributes']) . '>' . $label ."</button>\n";
}

function mytheme_preprocess_button($variables) {
    if($variables['element']['#type'] === 'submit') {
      unset($variables['element']['#name']);
 }
 dpm($variables);
}

```

I found that I was able to remove the name attribute with this code in the mytheme\_button

```
unset($element['#attributes']['name']);

```

but from inside the mytheme\_preprocess\_button, I was able to remove the #name attribute from the array with this

```
unset($variables['element']['#name']);

```

but it didn't actually remove the name from the form. In the preprocess, 'name' is not a sub element under '#attributes'.

Does this make sense? I would think the most Drupal solution would be to use the preprocess, if I can.
> 0 votes

# Answer
It's possible that "op" is a default that gets applied if there's nothing already there.

Try:

```
$form['#submit']['#attributes']['name'] = 'thing-you-want-to-call-it';

```
> 0 votes

---
Tags: forms
---


# Question
Title: Drupal 7 disable submit when pressing enter on an autocomplete field
In Drupal 7, when you are within an autocomplete field on a node edit form (in my case, it is specifically an entity reference autocomplete field), pressing the Enter key submits the entire form.

How do I disable this behavior?

# Answer
> 3 votes
Here's a nice solution that will allow the user to press Enter in order to select an autocomplete option.

```
<script>
(function($) {

Drupal.behaviors.ACChangeEnterBehavior = {
  attach: function(context, settings) {
    $('input.form-autocomplete', context).once('ac-change-enter-behavior', function() {
      $(this).keypress(function(e) {
        var ac = $('#autocomplete');
        if (e.keyCode == 13 && typeof ac[0] != 'undefined') {
          e.preventDefault();
          var fauxEvent = $.Event('mousedown'); // Create an event to trigger
          $('li.selected', ac).trigger(fauxEvent);
        }
      });
    });
  }
}

})(jQuery);
</script>

```

Note: This will only override the behavior of Enter while the autocomplete dropdown is visible. Otherwise, pressing Enter does the normal behavior (submits the form).

But if you want to halt form submission via Enter in any input field, try the following:

```
<script>
(function($) {

Drupal.behaviors.DisableInputEnter = {
  attach: function(context, settings) {
    $('input', context).once('disable-input-enter', function() {
      $(this).keypress(function(e) {
        if (e.keyCode == 13) {
          e.preventDefault();
        }
      });
    });
  }
}

})(jQuery);
</script>

```

# Answer
> 1 votes
A slightly more concise version of answer #2 (the faux event is not needed).

```
<script>
!(function ($) {
  'use strict';
  Drupal.behaviors.ACChangeEnterBehavior = {
    attach: function (context, settings) {

      // Prevent the autocomplete from triggering the submit event.
      $('input.form-autocomplete', context).once('ac-change-enter-behavior').keypress(function (e) {
        if (e.keyCode === 13 && this !== undefined) {
          e.preventDefault();
        }
      });

    }
  };
}(jQuery));
</script>

```

# Answer
> 0 votes
Pressing enter in many fields would trigger the form submit. The only way you can disable this behavior is by custom JS, as you've done.

---
Tags: entities, ajax
---


# Question
Title: Changing Drush make default subdir for install profiles
I have a drush make file which has a default subdir for projects:

```
defaults[projects][subdir] = contrib

```

This places all modules into the `sites/all/modules/contrib` folder, which is great.

The trouble is, it also places my install profiles into the `profiles/contrib` folder. Now when I run `drush site-install`, it doesn't work because the install profile is in the wrong folder.

Is there any way to tell drush make to NOT put the install profiles into a subdir?

# Answer
I just tested this and the following works:

```
projects[my_install_profile][subdir] = ""

```
> 0 votes

---
Tags: 7, drush
---


# Question
Title: Geofield Display Format Data Options (Using Bounding Box)
I am using Geofield to store point and polygon features. Input works fine with all the different widgets I have tried.

Display formats (GeoJSON, WKT, KML) with Data Options "Use full geometry" and "Use centroid" work fine with either point or polygon geometries. When I use the Data Option " Use bounding box" it does not work with any geometry and get the following error:

Exception: Cannot construct Point. x and y should be numeric in Point-\>\__construct() (line 23 of ....../sites/all/modules/geophp/geoPHP/lib/geometry/Point.class.php).

Is this a known bug? My search did not find any reports. Or is it my configuration?

* Drupal 7.20
* Geofield 7.x.1.1
* geoPHP 7.x.1.7
* PHP (MAMP) 5.4.4

# Answer
i had the same problem and found a quick and dirty solution: in the referenced file Point.class.php the following function throws the error:

```
  public function __construct($x, $y, $z = NULL) {
    // Basic validation on x and y
    if (!is_numeric($x) || !is_numeric($y)) {
        throw new Exception("Cannot construct Point. x and y should be numeric");
    }

```

adding "echo $x;" before the "throw" showed me the problem: the numbers for $x and $y where in the wrong "local" format.

e.g. 9,34124 instead 9.34124

```
  public function __construct($x, $y, $z = NULL) {
    $x = floatval(str_replace(',', '.', str_replace('.', '', $x)));
    $y = floatval(str_replace(',', '.', str_replace('.', '', $y)));
    // Basic validation on x and y
    if (!is_numeric($x) || !is_numeric($y)) {
     throw new Exception("Cannot construct Point. x and y should be numeric");
    }

```

is my dirty fix for this...

regards nicolaj
> 1 votes

---
Tags: location
---


title: Module to embed content in a iframe?

text:
# Question
Title: Module to embed content in a iframe?
I'd like to add a button to every of my article pages, that would open a box containing an iframe code embedding for example the title, the content and the image of the article in another page. Does it already exist a module doing this? I tried Iframe and Entity Iframe, couldn't get what I want though.

Thanks for your help.

# Answer
In your node--contenttype.tpl.php you can add a div (optionally with a textbox) which is hidden by default and fill it dynamically with the title and content of your node. Create a button that uses the colorbox module to show that div when pressed and your done.

```
<div>
  <textarea>
    <iframe>
      <h2><?php echo $node->title;?></h2>
      etc..
    </iframe>
  </textarea>
</div>

```

Alternatively you could just use javascript to copy the content of your page to a div when the button is pressed.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Webform theming field labels through webform-form.tpl.php
I'm theming a Webform I created by using a custom webform-form-\[nid\].tpl.php template. I've been able to render individual fields fine, but I'm having a problem with the date field which is split into 3 fields (month, day, year).

To wrap each item in custom HTML, I render each of those fields like this:

```
 <?php print drupal_render($form['submitted']['birthdate']['day']); ?>
 <?php print drupal_render($form['submitted']['birthdate']['month']); ?>
 <?php print drupal_render($form['submitted']['birthdate']['year']); ?>

```

But the label is automatically being rendered separately, so how can I render it manually?

This is the output that I'm getting: (simplified for ease of understanding)

```
<div class="row">

  <div class="column">
    <label for="month">Month</label>
    <select name="submitted[birthdate][month]">
      <option selected="selected" value="">Month</option>
      <option value="1">Jan</option>
      ...more options...
    </select>
  </div>

  <div class="column">
    <label for="day">Day</label>
    <select name="submitted[birthdate][day]">
      <option selected="selected" value="">Day</option>
      <option value="1">1</option>
      ...more options...
    </select>
  </div>

  <div class="column">
    <label for="year">Year</label>
    <select name="submitted[birthdate][year]">
      <option selected="selected" value="">Year</option>
      <option value="2014">2014</option>
      ...more options...
    </select>
  </div>

</div>

<!-- this gets generated automatically -->
<div class="webform-component--birthdate">
  <label for="birthdate">Birthdate</label>
  <div class="webform-container-inline">
    <!-- empty container here where date fields were being rendered -->
  </div>
</div>

```

So I need to somehow print that "Birthdate" label manually so I can place it wherever I need, like so:

```
row
  column label
  column month
  column day
  column year
/row

```

I need to do this so I can wrap each element with CSS classes for a responsive grid.

# Answer
You can simply hide the label from date field setting and add like this :

```
<div class="date-wrapper">
  <label>Label here</label>
  <div class="date-field">
    <?php print drupal_render($form['submitted']['birthdate']['day']); ?>
    <?php print drupal_render($form['submitted']['birthdate']['month']); ?>
    <?php print drupal_render($form['submitted']['birthdate']['year']); ?>
  </div>
</div>

```
> 2 votes

# Answer
So this is what I ended up doing. Please let me know if this is a good approach or not.

I hid the date fields like this:

```
<?php hide($form['submitted']['birthdate']); ?>

```

This way the date fields (and label) don't get rendered automatically at all. Only when I manually render them like in my initial example.

And then I add the label manually, like Sumit Madan suggested.
> 0 votes

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


# Question
Title: How can I hide the title in a custom page made with hook_menu?
I need to hide the title on a custom page created using hook\_menu. I don't have a nid, so probably I can't use one of the existing modules to do that.

```
function mymodule_menu() {
  $items['mypath'] = array(
    'title' => 'My title',
    'page callback' => 'mymodule_page_callback',
    'access arguments' => array('access content')
  );
  return $items;
}

```

I know this could be done using this css

```
body#pid-mypath {
  h1.title {
    display: none
  }
}

```

but I want to know if there are other alternatives. I'm working with Drupal 6.

# Answer
> 1 votes
Not sure if processed on time but I would try using drupal\_set\_title. And making sure you have an if statement around the h1 or h2. So use drupal\_set\_title to create empty title and use:

```
if(!empty($title)){
echo '<h1>' . $title . '</h1>';
}

```

---
Tags: 6, routes
---


# Question
Title: Uploaded file not shown in custom content type / Image not attached to content type
In Drupal 7, I am trying to upload an image that belongs to a custom type.

I click the Browse button, choose the file and upload. Until there, all seems to work well.

However, when I click next, instead of the add alt, title and text, I get only a screen that says Destination \*, and with a Previous and Next buttons, as shown below. The save button is never displayed, and the image is not shown.

However, the image is there if I check the files through the admin, moreover, all goes well If I add the image through the file/add, it is just in the custom type that I get the error.

I am logged in as an administrator and I have all the permissions checked in Media and File Entity

My files folder permissions are 755, and the javascript console shows: 'Attr.nodeValue' is deprecated. Please use 'value' instead. in jquery.js

Resource interpreted as Script but transferred with MIME type text/html: "about:blank" in browser?render=media-popup&types\[\]=image&activePlugins=&enabledPlugins=&schemes\[\]=public&schemes\[\]=…:92 (anonymous function)

Thanks in advance for your help.

Update, this doesn't work with Image widget nor Media Browser widget. Same site works in PROD, I suppose it is something with the file system settings?

# Answer
These fixed it:

-I changed the content type to image instead of media browser.

-Reviewed the permissions for file and this particular content type.

-Changed the field display of the content type
> 0 votes

---
Tags: 7, media
---


# Question
Title: How to add an exposed filter to a view programatically?
How would one go about adding an exposed filter item to any given view programatically?

EDIT 1: This needs to happen during the request. So, I'm guessing some views hook needs to be used.

# Answer
> 0 votes
Depends on the filter you need, but, let's say you want to filter by Node type, then you would use the following in a views.inc file included into your module within a hook\_views\_default\_views() function.

```
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
    'news' => 'news',
);
$handler->display->display_options['filters']['type']['expose']['operator'] = TRUE;

```

For a sample of what this file may look like, pull up the node.views\_default.inc file in the views module. You can also create a view and choose to look at what the code behind it if you need the particular syntax for a filter. The option to export is found at the top right of the view within the edit screen. I would search hook\_views\_default\_views() for additional information.

---
Tags: 7, views
---


# Question
Title: Drupal 7 trim user input and other checks to prevent security issues
What is the recommended way in Drupal to perform trim and other checks before accepting user input to avoid sql injections and other similar security issues?

Thanks.

# Answer
> 0 votes
I recommend reading this article : https://www.drupal.org/writing-secure-code Really a lot of good tips

---
Tags: 7, forms, webforms, input-formats
---


title: menu callback path construction

text:
# Question
Title: menu callback path construction
It seems there is hardly any documentation on page call backs using URLS

This being the case I have 2 questions:

What is a legal callback path? and what becomes the URL to access that path?

Here is the code on my custom module:

```
  $menu['tipFeed/arguments/%'] = array(
'page callback' => 'tipfeed_create',
'page arguments' => array(2),
'access arguments' => array('access arguments page'),
'type' => MENU_CALLBACK,
);

```

Here is the function it refers to:

```
function tipfeed_create($first){
     return 'cool';
}

```

My module is called tipFeed.

why is the URL http://www.example.com/tipFeed/arguments/1 saying page not found?

Any help would be great, thank you

# Answer
> 0 votes
everything is ok, just try to clear cache and **don't forget never, after any change in hook\_menu clear cache**

---
Tags: hooks, uri, routes
---


# Question
Title: How to add multiple terms to a taxonomy via feeds and tamper
I am importing nodes with taxonomy terms for one vocabulary. I have a set of terms that I would like to use that are set up with their own columns.

I know feeds tamper can explode a set of data in one column using a delimiter and apply that to a term, but I need each taxonomy term to be in it's own column. This is easier for readability for the people who are setting up the database.

How can I do this?

Thanks!

# Answer
Feed Tamper gives you a feature to import multivalued field data using any separator like comma(,) using implode plug-in

**If you have csv file like below**

**You need add implode plugin for that field in tamper tab in feeds form**

For a detailed tutorial refer this Awesome link!!!!
> 4 votes

# Answer
If I understand correctly, it is possible to simply map multiple columns in your csv to the same Taxonomy.

In the Mapping of your importer:

Assuming that you have created the taxonomy "Equipment" (and are adding to it with the import), and Equipment1 and Equipment2 are columns in your csv.
> 2 votes

# Answer
Unfortunately, I do not think this is possible at the moment.

If you map several columns to the same taxonomy term field in a Feeds importer what will happen is that the last input (furthest to the right in the input CSV, or possibly last in the order given in the mapping) will override the previous ones, and only if there is data in that input. This might be useful in some cases but does not provide the functionality you are looking for.

I think your best bet is to write a new script to implode your columns, and then use tamper to get them into the nodes.
> 0 votes

# Answer
The best option is as Sam says, implode the columns into one first with there own delimiter and then import properly.

A dirtier way is to make as many dummy fields as you need on the node so you have something to map each column too then use feeds tamper to implode the mapped fields into your vocab.
> 0 votes

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


# Question
Title: View of date field showing time on all day events
I have a Event content type with a body and date field from the Date module.

I have a view that shows the events as a block in ascending order, and everything looks cool when I view as an admin. All day events are displayed without a time.

> Event Foo 12/06/2014 to 12/09/2014

However when I look at the block as an anonymous user all day events show up as starting and ending at 2:00

> Event Foo 12/06/2014 - 02:00 to 12/09/2014 - 02:00

How can I get rid of the time?

Edit: How the Date field looks in the node edit form:

# Answer
Fixed this issue by creating a custom date format and date type. /admin/config/regional/date-time
> 0 votes

---
Tags: datetime
---


# Question
Title: Show Block view of Restricted Content Type
I have a content type of Events which i make restricted for anonymous users via content\_access module. But on the home page there is a block view of most recent Events. I don't want that block view to be hidden from anonymous users. I have selected all roles in the view settings so that i should show but i think because of contect\_access restrictions on Event Content Type its not displyaing the block.

How can i show that block ?

Thanks

# Answer
> 0 votes
In the Views UI there is a setting under 'Advanced' called 'Query Settings'. Click on 'Settings' next to it, then in the next popup make sure to select 'Disable SQL rewriting'.

> Disabling SQL rewriting will disable node\_access checks as well as other modules that implement hook\_query\_alter().

---
Tags: views, blocks, nodes, users
---


# Question
Title: Notify users of new logged heartbeat activity
I am using Heartbeat module for a notification system, I've created a pop up block which shows all the logged activity targeted to a certain user. Is there a way to alert the targeted users of new logged activities.

For example, like the notifications on Facebook or twitter?

Any help would be greatly appreciated.

# Answer
> 0 votes
Try to use Notify or Notifications module. I think from these modules you can solve your query.

---
Tags: notifications, heartbeat
---


# Question
Title: Programatically Create Nodes with Body and Custom Fields
I need to write a module that will fetch remote content via an API and store it as nodes. These nodes have custom fields defined within the module. I have already accomplished this by modifying the Node Example Module.

I can add nodes via the admin end with all the custom fields, but when I'm trying to programatically create the nodes from hook\_install(), the body and custom fields are not saving.

The code for creating the fields is largely the same as the example I linked. Here's the function i'm using to create the nodes:

```
function sm_add_mashup_item_node($remoteId, $site, $text, $image, $time){

    $node = new stdClass();
    $node->type = 'rscg_mashup';
    node_object_prepare($node);

    $node->title = "My Awesome Title";
    $node->language = LANGUAGE_NONE;
    $node->created   = time();
    $node->timestamp = time();
    $node->changed   = time();

    $node->status = 1;
    //$node->uid = 1;
    $node->promote = 1;
    $node->sticky = 0;
    $node->format = 3;
    $node->language = 'en';
    $node->revision = 0;

    $node->body[$node->language][0]['format'] = 3;
    $node->body[$node->language][0]['summary'] = 'summary';
    $node->body[$node->language][0]['value'] = 'dfg sdgdfs gsdg sdfg sdfg sdfg sdfg sdfg sdfg sdgsdf';

    // Try to set your custom field
    $node->rscg_mashup_image_url[$node->language][0]['value'] = "Too many to count...";

    echo "\n Edited: \n";
    print_r(node_load(526));

    echo "\n Pre-Save: \n";
    print_r($node);

    $node = node_submit( $node );
    node_save($node);

    echo "\n Loaded: \n";
    print_r(node_load($node->nid));

    return;

```

I've tried countless variations of the above.

Here is the debug output from the function:

https://gist.github.com/agroff/1c2c22920c20e3775b0d

This is a screenshot of the field list.

# Answer
> 1 votes
try using like below

```
$node->body[LANGUAGE_NONE][0]['format'] = 3;
    $node->body[LANGUAGE_NONE][0]['summary'] = 'summary';
    $node->body[LANGUAGE_NONE][0]['value'] = 'dfg sdgdfs gsdg sdfg sdfg sdfg sdfg sdfg sdfg sdgsdf';

// Try to set your custom field
    $node->rscg_mashup_image_url[LANGUAGE_NONE][0]['value'] = "Too many to count...";

```

---
Tags: entities
---


# Question
Title: How to change a user reference field from select list to autocomplete in a Views exposed filter?
In Views filter I have added user reference field and its showing me as select drop-down. I have exposed that field in the filter.

Those user reference fields are related to a content type, but I want those as auto-complete fields instead of drop-down, just as taxonomy fields can be drop-down or auto-complete fields.

The issue with select list is that there are thousands of users in that list and it is taking time to load all values and render the page.

How can I achieve this?

# Answer
To get **User Reference** Field as autocomplete exposed filter,

* Let me consider you have created a user reference field in your content type as `Users-ref`

**Now in your View :**

* Add a relationship for your entity reference field for **Eg:** `Entity Reference: Users-ref` and make it required.
* Now add a filter criteria `User:Name` with the relationship `Entity Reference: Users-ref`
* you should find `(User entity referenced from field_users_ref) User: Name (exposed)` in your filter criteria now.
* And this should be an autocomplete widget!!

**There is also a module named Views Autocomplete Filters along with this wonderful tutorial!!**
> 2 votes

---
Tags: 7, views, users
---


title: Drupal commerce price field settings?

text:
# Question
Title: Drupal commerce price field settings?
I've set GBP as my default and only enabled currency.

I have an exposed filter on my view so users can enter a maximum price. Say the user enters 300 the filter works and displays only items that go up to £300. The same for it the user entered 300.00 - it works.

However, when the user enters 300,000, i think Drupal is thinking of the comma as a decimal, so it thinks 300,000 and 300,00 means 300 and so my view shows results over 300 and up to 300 thousand.

Can I fix this, if so how? Thanks for reading

# Answer
'300,000' isn't a number, it's a string. If you run

```
print (int) '300,000';

```

You'll get "300" as the response. '300.00' *is* a number, which is why it's treated as one.

So your issue isn't with Drupal Commerce, rather PHP and your users' input.

You'll need to implement some validation to correct your users' input before Commerce uses it. You can either do this by adding an extra validation function to the form using `hook_form_alter()`, or with some simple Javascript attached to the input box(es).
> 1 votes

---
Tags: 7, commerce
---


# Question
Title: How to get acces to XML tag attributes via XPath parser settings?
I need to parse XML attributes via Feeds Importer **XPath parser**

exitsting XML tag structure is:

```
<MunicipalUnion Id="2a1c7bdb-05ea-492f-9e1c-b3999f79dcbc" Name="Moscow" TypeMU="city"/>

```

If i write **@Id, @Name, @TypeMU**, result is:

# Answer
Solution is: using Xpath string() function

string(@Id)

string(@Name)

string(@TypeMU)
> 1 votes

---
Tags: feeds
---


# Question
Title: Are there Get/Set methods for addressing commerce line_items and order object properties?
Are there get/set functions/methods for all line item and order properties?

I find myself manipulating line items thus:

```
$line_item->commerce_unit_price['und'][0]['currency_code'] = $whatever;

```

I was thinking there must be a better way to (ie. without addressing array members?) My concern is that the structure may change as Commerce develops.

# Answer
> 1 votes
What you're doing is correct for Commerce 1.x. Drupal 7 just uses stdClass objects for entities, no methods. Fortunately Commerce 1.x isn't seeing any significant changes - any time we make an API change it will be heavily noted in the change log of a new release. Additionally, Commerce 2.x on Drupal 8 is actually able to use robust classes for entities, so the future is brighter.

---
Tags: commerce
---


# Question
Title: want to make user-login before view contain
i am making a online tutorial site where a user can view can different contain but i want then to go through login.

For example: you have a home page. after login, user get redirected to the video page. but i dont want to display video page at the homepage.

# Answer
you can go for LoginToboggan module .

```
 The LoginToboggan module offers several modifications of the Drupal login system
 in an external module.

    Allow users to login using either their username OR their e-mail address.

    Allow users to login immediately.

    Provide a login form on Access Denied pages for non-logged-in (anonymous) users.

    Customize the registration form with two e-mail fields to ensure accuracy.

    Optionally redirect the user to a specific page when using the 'immediate login' feature.

    Optionally redirect the user to a specific page upon validation of their e-mail address.

    Optionally display a user message indicating a successful login.

    Optionally combine both the login and registration form on one page.

```
> 0 votes

---
Tags: users
---


# Question
Title: How to automatically populate /node/add/ form fields via simple logic?
I have created a content type and the form looks like this:

Home team: Reds
Away team: Blues
Batted first: Reds
Batted second:
Fielded first:
Fielded second:

If Reds batted first, I know the Blues batted second, fielded first and that the Reds fielded second. How can I get Drupal (7) to populate these fields automatically via some simple logic?

I'm thinking the Computed Field module, but the values are not in the database yet: the form hasn't been submitted. So, I'm not sure I can access the Batted first value. Perhaps only via the &$form\_state array? - but can the Computed Field module access this array?

Anyway, how can I acheive this? Any suggestions are welcome. Thanks.

# Answer
> 1 votes
Module Conditional Fields does the job.

It lets you assing values, visibility etc. of fields depending on other fields in the same form.

https://www.drupal.org/project/conditional\_fields

# Answer
> 0 votes
You'll have to resort to javascript (jQuery) for this one like monymirza suggested in the comments. Reason being that if the inserted values are not submitted to the server then Drupal/PHP don't know about their existence which means that the task must be solved client-side.

The general approach could be that you add jQuery's `change` or `blur` event handler to the the "Batted first" field. When it's triggered you grab the "Batted first" field value and compare it to "Home team" and "Away team". If a match is found you can fill "Fielded second" with that and "Batted second" + "Fielded first" with the other value.

---
Tags: forms
---


# Question
Title: Trying to create a new prebuilt list in webform
I'm attempting to define a new prebuilt list for our site, and even though everything looks like it should be fine, based on the examples I could find, the list doesn't appear.

My module is appearing in the list of modules, under "Other", and it is enabled.

This is the content of the AddressList\_webform\_select\_options.module file.

```
<?php

/**
 * Implementation of hook_webform_select_options_info().
 * See webform/webform_hooks.php for further information on this hook in the Webform API.
 */

function AddressList_webform_select_options_info() {
  $items = array();
  $items['Address'] = array(
    'title' => t('Select Address'),
    'options callback' => 'AddressList_options_Address'
  );
  return $items;
}

?>

<?php

/**
 * Build an options list for use by webforms.
 */
function AddressList_options_Address() {
  $options = array();
    $options[] = "1|city2 - Address1 - Floor - Building Name";
    $options[] = "2|city2 - Address2 - Floor - Building Name";
    $options[] = "3|city2 - Address3 - Floor - Building Name";
    $options[] = "4|city1 - Address4 - Floor - Building Name";
  return $options;
}

?>

```

This is the content of the .info file.

```
name = Address List
description = Creates a prebuilt list that contains all current addresses.
core = 6.x
dependencies[] = webform

```

Please tell me I'm missing something simple.

# Answer
When you are building option list in code, don't use human-readable syntax. Use machine-readable one. So instead of this:

```
$options[] = "1|city2 - Address1 - Floor - Building Name";

```

you should use this:

```
$options[1] = "city2 - Address1 - Floor - Building Name";

```

Second very bad thing you did is:

```
?>

<?php

```

It is highly discouraged to ever close php block. Everywhere except template files you should have `<?php` as the very first 5 bytes, and no `?>` at all. What you apparently did was outputting few empty lines to the user's screen where nothing expected them.
> 0 votes

---
Tags: 6, webforms
---


title: How stop HOOK node form submit

text:
# Question
Title: How stop HOOK node form submit
My question is in the title, when i add a new element of entity "intervenant" I check, if there is already an intervenant with the name used in form\_state, if the query returned me a result, i want to stop the insert into and be redirected in my front page.

I used `return FALSE;`

But it's didn't work.. You can see my code :

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'intervenant')
    ->fieldCondition('field_int_projett', 'target_id', $idProject, '=')
    ->fieldCondition('field_int_numero_lot', 'value', $lot, '=')
    ->fieldCondition('field_int_intervenants', 'target_id', $intervenant_id, '=')
    ->propertyCondition('status', 1);
$intervenant_externe_pjt = $query->execute();

if(!empty($intervenant_externe_pjt['node'])) {
    return FALSE;
}

```

How can i stop the submit, if it's possible ?

Thanks

# Answer
Stopping a submit is best done in a validation function. You need to have this code in a custom validation handler that you add to the form, and then you set a validation error on it.

Learn how to add custom validation to an existing Drupal form

Redirecting on form validation fail seems to be a problem. Look here for workaround:

Redirect form in validation fail

As to hook\_node\_submit, the docs have this to say:

> Act on a node after validated form values have been copied to it.
>
> This hook is invoked when a node form is submitted with either the "Save" or "Preview" button, after form values have been copied to the form state's node object, but before the node is saved or previewed. It is a chance for modules to adjust the node's properties from what they are simply after a copy from $form\_state\['values'\]. This hook is intended for adjusting non-field-related properties. See hook\_field\_attach\_submit() for customizing field-related properties.

This hook is not a good place to try and stop submission, as form validation has already passed. It is therefore assumed that the node should be saved to the db.
> 1 votes

---
Tags: forms, database, nodes
---


title: Drupal #ajax callback executing twice

text:
# Question
Title: Drupal #ajax callback executing twice
I am creating a custom paginator in Drupal 7.

The paginator is working fine, the only problem is that every time I click to the next page button, increases the step in 2 (For example I can see pages 0,2,4,6,etc...)and that's because the submit button is executed twice and increases the number of the page by two.

As you can see in the callback I use AJAX to replace two different sections on the page, and that might be the cause.

Any idea?

Submit function:

```
function club_paginator_form_submit($form, &$form_state) {
$values = $form_state['values'];

if ($form_state['triggering_element']['#value'] == '>')
{
    $form_state['values']['current_page'] = intval($form_state['values']['current_page'])+1;
}
else
{
    $form_state['values']['current_page'] = intval($form_state['values']['current_page'])-1;
}

$form_state['rebuild'] = TRUE;

```

}

Forms: (...)

```
$form['next'] = array(
    '#name' => 'paginator-next',
    '#type' => 'submit',
    '#value' => t('>'),
    '#weight' => 5,
    "#ajax" => array(
        "callback" => "ajax_club_paginator_next",
        "effect" => "fade",
    ),
    '#prefix' => '<div id="club-paginator-page-replace">'.$page.'</div>',
    '#attributes' => array('class' => array('button')),
    '#submit' => array('club_paginator_form_submit'),
);

```

(...)

Callback:

```
function ajax_club_paginator_next($form, &$form_state)
{
    $page = intval($form_state['values']['current_page']);

    $html = '';
    $html .= '<div id="club-paginator-content-replace">';
    $html .= draw_clubes_page($page);
    $html .= '</div>';

    $paginator = '<div id="paginator">';
    $form = drupal_get_form('club_paginator_form', $page);
    $paginator .= drupal_render($form);
    $paginator .= '</div>';

    return array(
        '#type' => 'ajax',
        '#commands' => array(
            ajax_command_replace("#club-paginator-content-replace", $html),
            ajax_command_replace("#paginator", $paginator)
        )
    );
}

```

# Answer
> 1 votes
I Finally found the error...

drupal\_get\_form was calling the submission again, I was creating a new form like the one I was substituing, but I was also updating the old.

Instead of creating a new form, I just used the $form variable instead of drupal\_get\_form.

Please find the new logic below!

```
function ajax_club_paginator_next($form, &$form_state)
{
    $page = intval($form_state['values']['current_page']);

    $html = '';
    $html .= '<div id="club-paginator-content-replace">';
    $html .= draw_clubes_page($page);
    $html .= '</div>';

    $paginator = '<div id="paginator">';

    //Not Needed!
    //$form = drupal_get_form('club_paginator_form', $page);

    $paginator .= drupal_render($form);
    $paginator .= '</div>';

    return array(
        '#type' => 'ajax',
        '#commands' => array(
            ajax_command_replace("#club-paginator-content-replace", $html),
            ajax_command_replace("#paginator", $paginator)
        )
    );
}

```

# Answer
> 1 votes
In addition to Xavi's excellent answer to his question...

watch out for unnecessary use of drupal\_get\_form within an ajax callback function

e.g.

```
function your_callback($form, &$form_state) {
  $commands = array();
  $commands[] = ajax_command_replace('#result', drupal_render(drupal_get_form('your_form')['result']));
  return array('#type' => 'ajax', '#commands' => $commands);
}

```

It is only necessary to use drupal\_get\_form in the above callback if you need to deal with a different form from the one invoking the callback. If that's not the case, stick to the version below

```
function your_callback($form, &$form_state) {
  $commands = array();
  $commands[] = ajax_command_replace('#result', drupal_render($form['result']));
  return array('#type' => 'ajax', '#commands' => $commands);
}

```

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


# Question
Title: Is there a way to register on my Drupal site with mobile number and password instead of email?
Is there a way to register on my Drupal site with mobile number and password instead of email?

I would like to have my users register on my Drupal site with either mobile number and password or email and password. The confirmation code is sent to the corresponding destination and the user is activated.

# Answer
Yes, it is possible, but you will have a lot of work to do it.

First thing first, you need a way to communicate with your users. Drupal sends quite a lot of data to users, like password restoration mails. If you want phone numbers to replace mail, you need to be able to send SMS messages. SMS Framework seems to be your friend here. There is no stable version for Drupal 7, but as far as I know it is most stable at the moment anyway.

When you have a way to communicate using their mobile numbers, you need to override mail sending, to convert mails into SMS messages. There are, generally, two ways to achieve this:

1. SMTP Authentication Support \- It is possible to configure mailserver to send sms messages if address is in *phone\_number*@sms.local or similar format. This does not even require any SMS framework in Drupal, really.
2. Use Mail System and create your own `MailSystemInterface` implementation that will detect sms addresses and use SMS Framework instead of whatever mail system you are using.

If you don't want to mess with mail systems, you will need to effectively write user module from scratch and replace core one with your own - it relies on mails too much, writing `alter`s would not be feasible.

Last thing: For all Drupal forms, you need to use form alter and detect required email, changing it into two fields, at least one required. And provide relevant storage. Actually, this seems to be an easy part.

**Note** pretty much every modern phone can receive emails, so I hardly see a point in this.
> 5 votes

---
Tags: users
---


# Question
Title: Migrating site from localhost to production some images does not show
I am in process of creating a new website from old Joomla based site. I manage to import with feeds module all the old content. On the localhost server there is no problem but on production server all of the imported images and their derivatives are not showing. The problem links looks something like this

```
news_thumb/public/field/image/274f1bf2bd18e7f0d33d6244e658426e.jpg?itok=AUwo0SYX

```

My first suggestion was that this images have problem with the image style 'itok' token

Any suggestion would be deeply appreciated. Thanks.

What I tried so far: First all images were imported with single space after the extension so the link looks like this:

```
news_thumb/public/field/image/274f1bf2bd18e7f0d33d6244e658426e.jpg%20?itok=AUwo0SYX

```

I didn't catch it before uploading finished site on production where all the images disappeared so I thought that this is the problem and after trying some weird things with no avail import again all joomla based content without the space. Second I presume that I have some problem with itok token and flushed all images and regenerated them again.

Now I uploaded the whole site on different hosting where all worked correctly so after conversing directly with the gays from original hosting company it turns out that they are updating their server on the fly during working hours and all my jumbo mumbo with database and files were restored few times on the row.

So I finished with apologies from them and one day spend searching for something that was not there.

# Answer
> 0 votes
First, make sure your images are actually uploaded to the server and accessible (go to `http://SITEURL/sites/PATH/TO/IMAGE/DIR/image/274f1bf2bd18e7f0d33d6244e658426e.jpg` to check), then make sure the file and directory permissions are correct. Check the `admin/config/media/file-system` page, and click "save" – if it's not setup correctly it should display an error message and you'll most likely have to change directory permissions.

Don't worry about the tokens or anything after .jpg (ie: `?itok=AUwo0SYX`) –– those are merely for cache-clearing, and can be safely ignored, it has no impact on accessing the images on the server.

---
Tags: feeds, migrations
---


title: hook_preprocess_html(&$vars) not firing

text:
# Question
Title: hook_preprocess_html(&$vars) not firing
I am attempting to add css classes to the body depoendant on what the page contains.

I am using the following...

```
function myTheme_preprocess_html(&$vars){
    //code here
    //eg.
    $vars['classes_array'][] = 'a-new-class-for-a-node';
}

```

I cannot get this to fire or add anything to the page. It will not drupal\_set\_message, echo or more importantly add any classes to the body tag.

What am I doing wrong here please? I am using Drupal 6.

# Answer
> 2 votes
I might be terribly wrong here, but there appears to be no such hook for Drupal 6. If so, it will never fire.

See https://api.drupal.org/api/drupal/6/search/hook\_preprocess\_html.

Perhaps you're backporting a theme from D7?

---
Tags: theming
---


# Question
Title: Drupal 6 make a content edit form be in a specified theme
This is in Drupal 6.

How to make a content edit form be in a specified theme?

The administration theme is 'seven', and use admin theme for content edit. Site configuration: /admin/settings/admin Administration theme: Seven \[x\] Use administration theme for content edit

Create a new content type 'example'.

In the module, this function makes 'example' edit form in example\_node\_form.tpl.php template. But this template will be in 'seven' theme, themes/seven/example\_node\_form.tpl.php

```
function modulename_theme() {
  return array(
    'example_node_form' => array(
    'template' => 'example-node-form',
    'render element' => 'form',
    ),
  );
}

```

Want 'example' edit form in another theme, not 'seven' theme?

How to make a content edit form be in a specified theme?

# Answer
Implement hook\_form\_alter in custom module and check for current theme :

```
global $theme;
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'example_node_form_id' && $theme != 'theme_machine_name') {
    // redirect anywhere using drupal_goto.
  }
}

```
> 0 votes

---
Tags: theming
---