# Question
Title: How to create a block showing the sliding gallery of just 1 of the galleries?
I am running a site (D7.43, jQuery 1.10), with the jollyany (bootstrap) theme as the basis. Among other things the site has several image galleries, generated through Views. The set up is as follows: There is a content type called Projects, where you first enter a square picture, then any number of photos that form the actual gallery.

On the galleries page (have a look: http://wixschool.net/image-gallery) Views and masonry then generate an overview of all galleries (projects) that have been created, showing the square image + with mouseover and button etc. Click on one of them, and you are presented with that individual gallery, for example: http://wixschool.net/image-gallery/peace-mile-run-battersea-park.

What I want to do now is take an individual gallery, and show that on a single page somewhere as a block. That means I want to click on a link, and end up on a page that has the slider of that gallery as one part of its content, and skipping the masonry overview.

I can and have create(d) a block, but then end up with that block showing the masonry gallery (even if filtered to just the one gallery I want). I then have to click on the gallery, which opens a new full node (page) with just that gallery and nothing else.

I assume its a Views thing, contextual filters? Any help / instructions / solutions very very welcome!

**Edit**: the template that runs the Image Gallery (Project) page is `node--projects.tpl.php`:

```
<?php
    /**
     * @file
     * jollyany's theme implementation to display a single Portfolio node.
     */
    global $base_url;
    global $image_default;

    // Grabs the firsts image path and sets $imagePath.
    $imagePath = $image_default;
    if(isset($node->field_image['und'])) {
        $imagePath = file_create_url($node->field_image['und'][0]['uri']);
    }

    $next = jollyany_pagination($node, 'n');
    $prev = jollyany_pagination($node, 'p');

    if ($next != NULL) {
      $next_url = url('node/' . $next, array('absolute' => TRUE));
    }

    if ($prev != NULL) {
      $prev_url = url('node/' . $prev, array('absolute' => TRUE));
    }

    $image_slide = "";

    if ($items = field_get_items('node', $node, 'field_gallery')) {
      if (count($items) == 1) {
        $image_slide = 'false';
      }
      elseif (count($items) > 1) {
        $image_slide = 'true';
      }
    }

    $img_count = 0;
    $counter = count($items);

    $termid = arg(2);
?>

<?php if (!$page) : ?>
    <?php if( !empty($termid) ) : ?>
        <div class="col-lg-4">
    <?php endif; ?>
        <div class="portfolio_item">
            <div class="entry">
                <img src="<?php echo $imagePath; ?>" alt="" class="img-responsive">
                <div class="magnifier">
                    <div class="buttons">
                        <a class="st btn btn-default" rel="bookmark" href="<?php echo $node_url; ?>"><?php print theme_get_setting('project_text_button'); ?></a>
                        <h3><?php print $title; ?></h3>
                    </div>
                </div>
            </div>
        </div>
    <?php if( !empty($termid) ) : ?>
        </div>
    <?php endif; ?>
<?php else :?>
    <div class="row">
    <?php if(isset($node->field_layout['und']) && $node->field_layout['und'][0]['taxonomy_term']->name == 'Sidebar') :?>
            <div class="col-lg-12 col-sm-12 col-md-12 col-xs-12 single-portfolio">
                <div class="col-sm-7 padding-left-0">
                    <?php if(isset($node->field_video['und']) && !empty($node->field_video['und'][0]['value'])) :?>
                        <div class="portfolio_item">
                            <div class="entry">
                                <?php print $node->field_video['und'][0]['value']; ?>
                                <div class="post-type">
                                    <i class="fa fa-play"></i>
                                </div>
                            </div>
                        </div>
                    <?php elseif(isset($node->field_audio['und']) && !empty($node->field_audio['und'][0]['value'])) :?>
                        <div class="portfolio_item">
                            <div class="entry">
                                <?php print $node->field_audio['und'][0]['value']; ?>
                                <div class="post-type">
                                    <i class="fa fa-music"></i>
                                </div>
                            </div>
                        </div>
                    <?php elseif($image_slide != '') : ?>
                        <div id="aboutslider" class="flexslider clearfix">
                            <ul class="slides">
                                <?php while ($img_count < $counter) { ?>
                                    <?php /*?><li><img src="<?php echo image_style_url('image_650x312',$node->field_gallery['und'][$img_count]['uri']); ?>" class="img-responsive" alt=""></li><?php */?>
                                   <li><img src="<?php echo file_create_url($node->field_gallery['und'][$img_count]['uri']); ?>" class="img-responsive" alt=""></li>

                                <?php $img_count++; } ?>
                                <?php echo $img_count; ?>

                            </ul>
                        </div>
                        <div class="aboutslider-shadow">
                            <span class="s1"></span>
                        </div>
                    <?php else :?>
                        <div class="portfolio_item">
                            <div class="entry">
                                <img src="<?php echo $imagePath; ?>" alt="" class="img-responsive">
                                <div class="magnifier">
                                    <div class="buttons">
                                        <a href="<?php echo $imagePath; ?>" class="sf" title="" data-gal="prettyPhoto[product-gallery]"><span class="fa fa-search"></span></a>
                                        <a class="st" rel="bookmark" target="_blank" href="http://caoutchouc.co.uk"><span class="fa fa-heart"></span></a>
                                        <a class="sg" rel="bookmark" target="_blank" href="http://caoutchouc.co.uk"><span class="fa fa-eye"></span></a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
                <div class="col-lg-12 padding-right-0">
                    <?php /*?><div class="title">
                        <h2><?php echo $title; ?></h2>
                    </div><?php */?>
                    <?php
                        // Hide comments, tags, and links now so that we can render them later.
                        hide($content['field_live_demo']);
                        hide($content['field_tags']);
                        hide($content['field_category']);
                        hide($content['field_skill']);
                        hide($content['field_image']);
                        hide($content['field_gallery']);
                        hide($content['field_audio']);
                        hide($content['field_video']);
                        hide($content['field_layout']);
                        hide($content['links']);
                        hide($content['comments']);
                        print render($content);
                    ?>
                    <?php /*?><?php if(theme_get_setting('showsocial')): ?>
                    <div class="clearfix">
                        <div class="social-2 f-left a2a_kit">
                            <a class="a2a_dd" href="http://www.addtoany.com/share_save"><i class="fa fa-plus-square"></i></a>
                            <a class="a2a_button_linkedin"><i class="fa fa-linkedin"></i></a>
                            <a class="a2a_button_pinterest"><i class="fa fa-pinterest"></i></a>
                            <a class="a2a_button_google_plus"><i class="fa fa-google-plus"></i></a>
                            <a class="a2a_button_twitter"><i class="fa fa-twitter"></i></a>
                            <a class="a2a_button_facebook"><i class="fa fa-facebook"></i></a>
                        </div>
                    </div>
                    <?php endif; ?><?php */?>
                    <div class="product_details">
                        <?php /*?><h3><?php print t('Gallery Details'); ?></h3><?php */?>
                        <ul>
                            <?php /*?><li><strong><?php print t('Added by'); ?>:</strong> <?php print strip_tags($name); ?></li>
                            <?php if(isset($node->field_live_demo['und'])) : ?>
                                <li><strong><?php print t('Live demo'); ?>:</strong> <a href="<?php print $node->field_live_demo['und'][0]['value']; ?>"><?php print $node->field_live_demo['und'][0]['value']; ?></a></li>
                            <?php endif; ?>
                            <?php if(isset($node->field_category['und'])) : ?>
                                <li><strong><?php print t('Category'); ?>:</strong> <?php print jollyany_format_comma_field('field_category', $node); ?></li>
                            <?php endif; ?>
                            <?php if(isset($node->field_skill['und'])) : ?>
                                <li><strong><?php print t('Skill'); ?>:</strong> <?php print jollyany_format_comma_field('field_skill', $node); ?></li>
                            <?php endif; ?><?php */?>
                            <br /><span class="smallprint"><?php print t('Date posted'); ?>: <?php print format_date($node->created, 'custom', 'd M, Y'); ?></span>
                            <?php /*?><?php if(isset($node->field_tags['und'])) : ?>
                                <li><strong><?php print t('Tags'); ?>:</strong> <?php print jollyany_format_comma_field('field_tags', $node); ?></li>
                            <?php endif; ?><?php */?>
                        </ul>
                    </div>
                </div>

                <div class="clearfix"></div>
                <?php if($page && module_exists('prev_next')): ?>
                    <div class="next_prev text-center">
                        <ul class="pager">
                            <?php if(isset($prev_url)) : ?>
                                <li class="previous">
                                    <a href="<?php echo $prev_url; ?>">← Previous</a>
                                </li>
                            <?php endif; ?>
                            <?php if(isset($next_url)) : ?>
                                <li class="next">
                                    <a href="<?php echo $next_url; ?>">Next →</a>
                                </li>
                            <?php endif; ?>
                        </ul>
                    </div>
                <?php endif; ?>

            </div>

    <?php else :?>

            <div class="col-lg-12 col-sm-12 col-md-12 col-xs-12 single-portfolio">
                <div class="full_portfolio">
                <div class="backtogalleries"><a href="/image-gallery" target="_self" class="btn-primary btn-xs">back to gallery overview</a></div>
                    <?php if(isset($node->field_video['und']) && !empty($node->field_video['und'][0]['value'])) :?>
                        <div class="portfolio_item">
                            <div class="entry">
                                <?php print $node->field_video['und'][0]['value']; ?>
                                <div class="post-type">
                                    <i class="fa fa-play"></i>
                                </div>
                            </div>
                        </div>
                    <?php elseif(isset($node->field_audio['und']) && !empty($node->field_audio['und'][0]['value'])) :?>
                        <div class="portfolio_item">
                            <div class="entry">
                                <?php print $node->field_audio['und'][0]['value']; ?>
                                <div class="post-type">
                                    <i class="fa fa-music"></i>
                                </div>
                            </div>
                        </div>
                    <?php elseif($image_slide != '') : ?>
                        <div id="aboutslider" class="flexslider clearfix">
                            <ul class="slides">
                                <?php while ($img_count < $counter) { ?>
                                   <?php /*?><li><img src="<?php echo image_style_url('image_650x312',$node->field_gallery['und'][$img_count]['uri']); ?>" class="img-responsive" alt=""></li><?php */?>
                                   <li><img src="<?php echo file_create_url($node->field_gallery['und'][$img_count]['uri']); ?>" class="img-responsive" alt=""></li>

                                <?php $img_count++; } ?>
                            </ul>
                        </div>
                        <div class="slider-shadow"></div>
                            <?php else :?>
                        <div class="portfolio_item">
                            <div class="entry">
                                <img src="<?php echo $imagePath; ?>" alt="" class="img-responsive">
                                <div class="magnifier">
                                    <div class="buttons">
                                        <a href="<?php echo $imagePath; ?>" class="sf" title="" data-gal="prettyPhoto[product-gallery]"><span class="fa fa-search"></span></a>
                                        <a class="st" rel="bookmark" target="_blank" href="http://caoutchouc.co.uk"><span class="fa fa-heart"></span></a>
                                        <a class="sg" rel="bookmark" target="_blank" href="http://caoutchouc.co.uk"><span class="fa fa-eye"></span></a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>

                <div <?php /*?>class="col-lg-12"<?php */?>>
                    <?php /*?><div class="title">
                        <h1><?php echo $title; ?></h1>
                    </div>  <?php */?>
                    <?php
                        // Hide comments, tags, and links now so that we can render them later.
                        hide($content['field_live_demo']);
                        hide($content['field_tags']);
                        hide($content['field_category']);
                        hide($content['field_skill']);
                        hide($content['field_image']);
                        hide($content['field_gallery']);
                        hide($content['field_audio']);
                        hide($content['field_video']);
                        hide($content['field_layout']);
                        hide($content['links']);
                        hide($content['comments']);
                        print render($content);
                    ?>
                    <?php /*?><?php if(theme_get_setting('showsocial')): ?>
                    <div class="clearfix">
                        <div class="social-2 f-left a2a_kit">
                            <a class="a2a_dd" href="http://www.addtoany.com/share_save"><i class="fa fa-plus-square"></i></a>
                            <a class="a2a_button_linkedin"><i class="fa fa-linkedin"></i></a>
                            <a class="a2a_button_pinterest"><i class="fa fa-pinterest"></i></a>
                            <a class="a2a_button_google_plus"><i class="fa fa-google-plus"></i></a>
                            <a class="a2a_button_twitter"><i class="fa fa-twitter"></i></a>
                            <a class="a2a_button_facebook"><i class="fa fa-facebook"></i></a>
                        </div>
                    </div>
                    <?php endif; ?><?php */?>
                    <div class="product_details">
                        <?php /*?><h3><?php print t('Gallery Details'); ?></h3>
                        <ul><?php */?>

                            <?php /*?><li><strong><?php print t('Added by'); ?>:</strong> <?php print strip_tags($name); ?></li>
                            <?php if(isset($node->field_live_demo['und'])) : ?>
                                <li><strong><?php print t('Live demo'); ?>:</strong> <a href="<?php print $node->field_live_demo['und'][0]['value']; ?>"><?php print $node->field_live_demo['und'][0]['value']; ?></a></li>
                            <?php endif; ?>
                            <?php if(isset($node->field_category['und'])) : ?>
                                <li><strong><?php print t('Category'); ?>:</strong> <?php print jollyany_format_comma_field('field_category', $node); ?></li>
                            <?php endif; ?>
                            <?php if(isset($node->field_skill['und'])) : ?>
                                <li><strong><?php print t('Skill'); ?>:</strong> <?php print jollyany_format_comma_field('field_skill', $node); ?></li>
                            <?php endif; ?>
                            <li><?php */?>
                            <br /><span class="smallprint"><?php print t('Date posted'); ?>: <?php print format_date($node->created, 'custom', 'd M, Y'); ?></span>
                            <?php /*?></li>
                            <?php if(isset($node->field_tags['und'])) : ?>
                                <li><strong><?php print t('Tags'); ?>:</strong> <?php print jollyany_format_comma_field('field_tags', $node); ?></li>
                            <?php endif; ?>
                        </ul><?php */?>

                    </div>
                </div>

                <div class="clearfix"></div>

                <?php if($page && module_exists('prev_next')): ?>
                    <div class="next_prev text-center">
                        <ul class="pager">
                            <?php if(isset($prev_url)) : ?>
                                <li class="previous">
                                    <a href="<?php echo $prev_url; ?>">← Previous</a>
                                </li>
                            <?php endif; ?>
                            <?php if(isset($next_url)) : ?>
                                <li class="next">
                                    <a href="<?php echo $next_url; ?>">Next →</a>
                                </li>
                            <?php endif; ?>
                        </ul>
                    </div>
                <?php endif; ?>

            </div>

    <?php endif; ?>
    </div>
<?php endif; ?>`

```

# Answer
> Yes, the idea is I have a page (basic page node) for each class at the school, I include a block that shows 1 image gallery, only the one that belongs to that class. So if node 'nursery is opened, I would like the block to show image gallery 'nursery', and if node 'year one' is opened image gallery 'year one'.. So how do I code a Node ID into the template?

```
<?php

if ($node = menu_get_object()) {
  // Get the nid
  $nid = $node->nid;

  $node = node_load($nid);

}

?>

```

This will automatically pass the nid that you're on (have opened).
> 1 votes

---
Tags: blocks, views, media
---


title: print image as a background-image

text:
# Question
Title: print image as a background-image
The page.tpl.php prints the header image like so. I need to change it so that it prints it as a background image. i.e `<div style="background-image:"' . $url . '"></div>` When I make that change the value of $url changes and includes additional text, not just the path to the image as it does in this format. How can I change this?

```
if ($node->field_header_image && $node->field_header_image['und'][0]['uri']) {
        $url = file_create_url($node->field_header_image['und'][0]['uri']);
        echo '<img src="' . $url . '" width="100%">';

```

# Answer
You are retrieving the absolute url of the file correctly, but your quotes in style attribute are a little mixed up.

Try this:

```
<?php
print '<div style="background-image:url(' . $url . ');"></div>';
?>

```
> 2 votes

---
Tags: theming, media
---


title: Views No results Behaviour Show All

text:
# Question
Title: Views No results Behaviour Show All
I have a proximity search on views using Gmap and Location API, I've imported all the UK post codes into my zipcodes table in my database, and it all works great. The only thing I would like to change is the no results behaviour.

If a user enters a postcode, and there isn't a venue nearby, the map disappears, and I can show a no results message in its place.

What I would like to happen, is for the map to stay where it is, but showing all venues, with a message underneath saying "Please widen your search area".

Anyone know if this is possible? I've been searching for a similar post on Google, but can't find anything, as I'm not having any errors, just wondering if its possible, and can't seem to figure it out myself!

# Answer
You can embed a different View under "No results behaviour"

e.g a View that lists all venues.
> 5 votes

# Answer
BTW: If you want to show just **empty map** (without markers), you may add a 'Global: TextArea' to 'No Result Behaviour' and put the text area inside:

```
<script src="http://maps.googleapis.com/maps/api/js?&sensor=false"></script>
<script >
  window.onload = function () {var mapOptions = {
                center: new google.maps.LatLng(10, 10),
                zoom: 2,
                mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}
</script>
<div id="map_canvas" style="width:100%; height:485px;"></div>

```
> 1 votes

# Answer
To work around, add a dummy item inside the result array

```
/**
* Implements hook_views_pre_render.
* to render the map even if there is no results
**/
function ei_users_customize_views_pre_render(&$view){
  if( $view->name == 'map_view'  ){
    if( count($view->result) == 0 ){
      $view->result = array('' => '');
    }
  }
}

```
> 0 votes

---
Tags: views, google-maps
---


# Question
Title: Cannot re-order the blocks of Drupal 7 site
This error happens just on my local server (I use the last version of Acquia Dev Desktop, kind of XAMP for Drupal), not on our remote servers:

I am suddenly unable to re-order the blocks of our site (Drupal 7.23). The drag-and-drop functionality is not working and entering the weight numbers manually either. I have researched this problem and tried all solutions posted (Aggregate JS, disable LightBox2, change the DB block fields from tiny to INT...).

We have a large number of files in our website, and in some regions they have reached the magic number of 127. Reading a few posts, I see this may be the problem when you have some DB fields defined as tiny, but after changing all the tiny (4) fields of the blocks table to INT(11) I do not see any change.

Any clue?

Thank you very much in advance.

# Answer
If there's no javascript error in the console, and you have a lot of blocks, and are using the Suhosin extension, you may be hitting a Suhosin limit. If that's the case, you will need to increase the relevant values there. There may be more information in your server error log.

More info: http://www.hardened-php.net/suhosin/configuration.html#suhosin.post.max\_vars
> 4 votes

# Answer
Check your `max_input_vars` in php.ini If you have many blocks, this value may be exceeded leading to errors.

Try setting the value to 2000 (I had to use 5000 to cope with a specific site).
> 2 votes

# Answer
In my case adding `php_value max_input_vars 2000` in **.htaccess** fixed the problem.

I had to put it between the `<IfModule mod_php5.c>` tags (which already existed) for it to work, like so:

```
# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
php_value max_input_vars 2000
</IfModule>

```
> 1 votes

---
Tags: blocks
---


# Question
Title: Commerce Kickstart and product variations
I am relatively new to Drupal and I am trying to build an eShop with Drupal Commerce Kickstart.

One of the good features is the ability to have product variations and attributes in variation type which affect the price of the product.

Unfortunately, I have not managed to make it work correctly.

My main issue is that the "All Products" page show only main products and not the variations and that on this page the facets of the attributes that are in variation type are not show-up. They work only the facets that are for the attributes of the content type of the product.

If I do not find a solution soon, I will forced to give up these two very powerful features of Drupal Commerce and simply have products without variations.

How can I achieve what I want?

# Answer
> 1 votes
TLDR: This is due to how Commerce Kickstart is configured for entering new products. You enter product variations while adding the product.

When you create a *product* in Commerce Kickstart, you're actually creating the node that the customer will see. Scrolling down the page, you'll see the ability to add the individual *product variations* (which are the actual product entities) like so:

This is an Inline Entity Form (aka IEF). See, normally when you'd use Drupal Commerce, you'd need to create all of your individual entities and then add them to a product using a product relationship field. But this a Drupal field widget take takes that step out by letting you enter in your product data and relate it to the display node in one step.

If you want to see all of the product variations, there should be a tab at the top of the Products admin page that will take you to a listing:

You can edit products here, but you can't add them directly because of how Kickstart controls the product add process.

---
Tags: commerce
---


# Question
Title: I can't render default values on form element in theme_table()
For the last few days and some of last week I've been trying to fix up the interface of a page we have on one of our modules since it was difficult to use. I decided to take this data and just display it in a table so that it's simple and organized by column.

Here is a very basic recreation of the code.

```
function _ss_menu_zone_test($form, $form_state) {

  $formfield = array(
    '#type' => 'textfield',
    '#default_value' => '10' // default value set
  );
  $formselect = array(
    '#type' => 'select',
    '#options' => array(1,2,3,4,5,6),
    '#default_value' => 3  // default value set
  );

  $tablesort_headers =array(
    array('data' => t('Price'), 'field' => 'price'),
  );

  $tablesort_rows = array(
    array('price' => 'test row format 1'), // example of basic string row
    array('price' => array('data' => 'test row format 2')), // example of simple string but using data
    array('price' => drupal_render($formfield)),
    array('price' => array('data' => $formfield)),
    array('price' => drupal_render($formselect)),
  );

  // render the tablesort of menu items.
  $form['category_' . $tid]['items'] = array(
    '#theme' => 'table',
    '#header' => $tablesort_headers,
    '#rows' => $tablesort_rows,
    '#sticky' => TRUE,
    '#attributes' => array('id' => 'zone-items-' . $tid)
  );

  return $form;
}

```

In this example I have one column for the test data and a couple rows to show the differences. The primary issue I've run into here is if I try to add a form API textfield to a cell somewhere it drops value for the #default\_value. the field renders correctly with any other key I've specified.

Does anyone know how to go about getting this #default\_value to actually populate the field like it does EVERYWHERE else in the Form API?

# Answer
> 2 votes
In FAPI (and renderable arrays in general), keys starting with a # are considered properties - so not renderable elements. This means their children aren't processed for content properly.

There are several methods to do what you want, but the easiest is probably references. In your specific example, it would look like this (I've trimmed out some stuff to make my changes more clear):

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

  $tablesort_headers =array(
    array('data' => t('Price'), 'field' => 'price'),
  );

  // render the tablesort of menu items.
  $form['category_' . $tid]['items'] = array(
    '#theme' => 'table',
    '#header' => $tablesort_headers,
    '#rows' => array(),
    '#sticky' => TRUE,
    '#attributes' => array('id' => 'zone-items-' . $tid)
  );

  $formfield = array(
    '#type' => 'textfield',
    '#default_value' => '10' // default value set
  );

  //We need to include the field in the form so it's rendered. This wont display because we're using #theme => table.
  $form['category_' . $tid]['items'][] = array('formfield' => &$formfield);

  //These are your rows, note the byreference on the formfield.
  $tablesort_rows = array(
    array('price' => 'test row format 1'), // example of basic string row
    array('price' => array('data' => 'test row format 2')), // example of simple string but using data
    array('price' => array('data' => &$formfield)),
  );

  //Add your rows to the table.
  $form['category_' . $tid]['items']['#rows'] = $tablesort_rows;

  //Since we used references we want to unset the variables we created.
  unset($formfield);

  return $form;
}

```

# Answer
> 1 votes
I create the elements dynamicaly in ajax and i have common problem. The #default\_value if not acting in render() function, but #value does. You can ensure it watching the form\_select\_options() Using #value is bad practice.

May be post i found (below) could be useful in your case for form generation? https://www.drupal.org/node/1000568#comment-3840362

Also, no need to use render() is $row\[\]=\>('data'=\>) drupal will render on his own

Also take a look at this elegant trick *https:// passingcuriosity.com/ 2011/drupal-7-forms-tables/* **(remove spaces please my reputation dont allow me to post more than 2 links)**

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


# Question
Title: Drupal views show all taxonomy of specified vocabulary
I have a taxonomy vocabulary with the followings terms.

Benginner, Intermediate, Advanced.

I want to show a view that show these terms, but one term is associate to node, and I need stand out this term, but show all terms of this vocabulary, try to find the solution and nothing.

# Answer
> 0 votes
All you gotta do is create a view of Taxonomy Terms and use fields

Then use a template file for your view.

In your template file all you gotta do is load your node's taxonomy term field value and compare it the view's taxonomy term name. If it's equal we print the underline `<u>`.

```
<?php

    $node = node_load(arg(1));
    $node_term = check_plain($node->field_name[0]['value']);

    if ($fields["name"]->content == $node_term) {
        print '<u>' . $fields["name"]->raw == $node_term . '</u>';
      } else {
        print $fields["name"]->content;
      }

?>

```

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


# Question
Title: Ajaxified form in modal window does not dimiss
I have form in modal window with two selects. Second field hidden and appears with ajax after first field selected.

1. If i click Submit when first select is not defined and second is hidden - modal window dismisses;
2. If i click Submit when first select defined and second is visible (i.e. form was refreshed with ajax), instead of modal dismiss i see raw output in browser:

> \[{"command":"settings","settings":{"basePath":"/","pathPrefix":"","ajaxPageState":{"theme":"opie","theme\_token":"5OSo2MbF\_rbvJauMUEumH0Mm-gFubWX6Ai-FqvwO9lo"},"fancybox":{"options":{"padding":0,"scrolling":"visible","nextClick":1},"helpers":{"overlay":{"fixed":0}},"selectors":\["a\[rel=\u0022fancybox\u0022\]","a.fancybox","img\[rel=\u0022fancybox\u0022\]",".gallery-frame a"\]}},"merge":true},{"command":"modal\_dismiss"}\]

Can you help me to understand why is that?

Main code:

```
function modal_callback($mode = NULL) {
    if ($mode == 'ajax') {
        ctools_include('ajax'); ctools_include('modal');
        $form_state = array('ajax' => TRUE, 'title' => 'Title');

        $output = ctools_modal_form_wrapper('stage_form', $form_state);
        if (!empty($form_state['ajax_commands'])) $output = $form_state['ajax_commands'];

        print ajax_render($output); drupal_exit();
    }
    else return drupal_get_form('stage_form');
}

function stage_form($form, $form_state) {
    $form['#prefix'] = '<div id="form-wrapper">';
    $form['#suffix'] = '</div>';
    $form['start'] = array(
        '#type' => 'select',
        '#options' => array('1'=>'1', '2'=>'2'),
        '#ajax' => array(
            'callback' => 'form_refresh',
            'wrapper' => 'form-wrapper',
        ),
    );
    if (!empty($form_state['values']['start'])) {
        $form['stop'] = array(
            '#type' => 'select',
            '#options' => array('3'=>'3', '4'=>'4'),
        );
    }
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
    );
}

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

function stage_form_submit($form, &$form_state) {
    $form_state['ajax_commands'][] = ctools_modal_command_dismiss();
}

```

# Answer
I'm not familiar with that ctools command, however try:

$commands = \[\];

$commands\[\] = ajax\_command\_name();

return \['#type' =\> 'ajax', '#commands' =\> $commands\];

What you ultimately want is for Drupal to receive and render the commands array which should trigger the dismiss and not print the commands to the screen.

(On phone, sorry for formatting)
> 0 votes

# Answer
I found the sollution. Problem was in my misunderstanding. Upper code supposes ctools\_modal\_command\_dismiss(); would be handled by modal\_callback(), but it's wrong way. Dismiss command demands own callback, handling all form ajax in modal window. Next code properly works with validation messages and dynamic form elements.

```
function test_menu() {
    $items['testpage'] = array(
        'page callback' => 'test_page',
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
    );
    $items['test'] = array(
        'page callback' => 'test_callback',
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
    );
    return $items;
}

function test_page() {
    // Load the modal library and add the modal javascript.
    ctools_include('modal');
    ctools_modal_add_js();
    return test_make_link('Magical modal');
}

function test_form($form, $form_state) {
    $form['#prefix'] = '<div id="test_frm">';
    $form['#suffix'] = '</div>';
    $form['name'] = array(
        '#type' => 'select',
        '#title' => t('Name'),
        '#options' => array(1 => 1, 2 => 222, 99999999 => '99999999'),
        '#ajax' => array(
            'callback' => 'test_form_ajax_handler'
        ),
    );
    $form['name1'] = array(
        '#type' => 'textfield',
        '#title' => t('Name'),
        '#value' => isset($form_state['values']['name']) ? $form_state['values']['name'] : '',
        '#maxlength' => '128',
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
        '#ajax' => array(
            'callback' => 'test_form_ajax_handler'
        ),
    );
    return $form;
}

function test_form_submit(&$form, &$form_state) {
    $form_state['rebuild'] = TRUE;
}

function test_form_validate(&$form, &$form_state) {
    if (strlen($form_state['values']['name1'])<5) form_set_error('name', '!!!!!!!!!!!!!!!!!!!!!!');
}

function test_form_ajax_handler(&$form, &$form_state) {
    ctools_include('ajax'); ctools_include('modal');

    if ($form_state['executed']) {
        $link = test_make_link($form_state['values']['name']);
        $commands[] = ctools_modal_command_dismiss();
        $commands[] = ajax_command_replace('#magical-modal-link', $link);
    } elseif ($form_state['submitted']) {
        $commands[] = ajax_command_remove('#messages-wrap');
        $commands[] = ajax_command_before('#test_frm', '<div id="messages-wrap">' . theme('status_messages') . '</div>');
        $commands[] = ajax_command_replace('#test_frm', drupal_render($form));
    } else {
        $commands[] = ajax_command_remove('#messages-wrap');
        $commands[] = ajax_command_replace('#test_frm', drupal_render($form));
    }
    return array('#type' => 'ajax', '#commands' => $commands);

}

function test_callback($ajax) {
    if ($ajax) {
        ctools_include('ajax');
        ctools_include('modal');

        $form_state = array('ajax' => TRUE, 'title' => t('MyModule Modal Form'));

        $output = ctools_modal_form_wrapper('test_form', $form_state);

        if (!empty($form_state['ajax_commands'])) {$output = $form_state['ajax_commands'];}
        print ajax_render($output);  drupal_exit();
    } else {
        return drupal_get_form('test_form');
    }
}
function test_make_link($link_text = '') {
    // Set a default value if no text in supplied.
    if (empty($link_text)) {
        $link_text = 'Magical Modal';
    }

    return '<div id="magical-modal-link">' . l($link_text, 'test/nojs', array('attributes' => array('class' => 'ctools-use-modal'))) . '</div>';
}

```
> 0 votes

---
Tags: forms
---


# Question
Title: The AMP module requires the PHP AMP library
I installed Drupal 8 and amptheme. I downloaded the AMP module and the library files. When I tried to install the module, I got the following message:

> The AMP module requires the PHP AMP library.

The library files are in libraries/amp-library. I think the library location is incorrect.

How do I fix the error?

# Answer
> 3 votes
This module requires the use of Composer to install its libraries. You can learn more about Drupal and Composer on drupal.org's documentation hand book Installing modules' Composer dependencies in Drupal 8. The AMP module project page also has a brief description of how to install on Drupal 8.0.5.

---
Tags: 8
---


title: Use $base_url in a computed field?

text:
# Question
Title: Use $base_url in a computed field?
Using `$base_url` to build a link in a computed field, I get this error:

> Notice: Undefined variable: base\_url in eval() (line 1 of F:\wamp\www\mysite\sites\all\modules\computed\_field\computed\_field.module(468) : eval()'d code).

Is it a way to get the site base URL in a computed field?

# Answer
This is a global scope variable and you can access it by using $GLOBALS\['base\_url'\] instead or calling the core base\_path() function to pull it into your computed field definition.
> 0 votes

# Answer
Before using $base\_url, You need to declare it just like below

`global $base_url;`

After declaring you can use $base\_url in your code.
> -1 votes

---
Tags: entities, uri
---


title: Drupal 6 (basic): Change Login Page

text:
# Question
Title: Drupal 6 (basic): Change Login Page
I want to change default login page to html login page because I like the theme (bought theme but still in html). After googling: 1. I use bluemarine theme, as a start i modify page.tpl.php and replace all html parts 2. Place assets folder in the "themes/bluemarine" folder and replace "assets/.." to "themes/bluemarine/assets/..", until this step login page has been changed flawlessly

But, I don't know how to routing login page to normal destination. In the html code in point 1, I changed this:

```
"<form class="login-form" action="index.html" method="post">

```

to this one:

```
<form class="login-form" action="?q=dashboard" method="post">

```

Because I have a custom module called dashboard.

Please help me, thanks before...

# Answer
You shouldn't be replacing Drupal form code with static HTML code for various reasons. You can redirect users to specific URLs by using Rules or actions/triggers:

https://www.drupal.org/node/683696
> 0 votes

---
Tags: theming, users
---


# Question
Title: Contextual Filter not getting the correct NID from URL
I **THINK** my Contextual Filter from my view is not getting the correct NID from my URL.

I have a view page with a path of "node/%/agenda".

The link on my menu is "node/\[node:nid\]/agenda".

The view page will get the nid from a content type "Venue". Example: Venue: Rave = NID: 101 View page will be = "node/101/agenda"

I have a working block of "Upcoming Events" and this works perfectly fine on my venue content type. But when I use it on a view page it's not working anymore. Basically this block shows the "Upcoming Events" from "Event" content type that is related to the "Venue" content type.

BLOCK: Setting:

How it works on content type venue: This is the wrong part:

As you can see it does not get the same result on the view page, it does not even show the "No Result". I am calling the correct block.

Am I missing something big? I hope someone can help!

THANK YOU VERY MUCH!! ^\_^

# Answer
> 0 votes
According to what i can see from the screen shots, you didn't specify your relationship entity on advanced menu. If I were you, I would pick a entity reference, then i would pick a content contextual filters with Nid. Otherwise there is no way that block is gonna understand what the relationship is. Please update us your work. This is a very sensitive topic of drupal. Kind regards

# Answer
> -1 votes
Block displays have no source of arguments at all; they cannot pull arguments from the URL so Create a content pane instead of block in the view and in the "argument input" add the argument number.

---
Tags: views
---


# Question
Title: Why is my Drupal ajax form not populating the radio buttons
I have a form which send an ajax request to my server. The form is:

```
function dokimi_add_to_list_form($form, $form_state) {

  $form = array();

  $options=array(
      'option1'=>'option1',
      'option2'=>'option2'

  );

  $form['private_list'] = array(
    '#type' => 'radios',
    '#title' => 'Private lists',
    '#options' => $options,
    '#prefix'=>'<div id="list_list">',
    '#suffix'=>'</div>'
  );

  $form['add_new']= array(
    '#type' => 'fieldset',
    '#markup' => 'Add a list'
  );

  $form['add_new']['new_list']= array(
    '#type' => 'textfield',
    '#title'=> 'New list',
    '#default_value' => '',
  );

  $form['add_new']['add']= array(
    '#type' => 'button',
    '#value' => t('Add'),
            '#ajax'=>array(
              'callback' => 'add_to_list_callback',
              'wrapper'=>'list_list'
                  // 'wrapper' is the HTML id of the page element that will be replaced.
        )
      );

 return $form;
}

```

And the callback function is:

```
function add_to_list_callback($form, $form_state){

    $options=array(
      'newoption1'=>'newoption1',
      'newoption2'=>'newoption2',
      'newoption3'=>'newoption3'
  );
    $form['private_list'] = array(
        '#type' => 'radios',
        '#title' => 'Private list',
        '#options' => $options,
        '#prefix'=>'<div id="list_list">',
        '#suffix'=>'</div>'
  );

    $commands = array();
    $commands[]=ajax_command_replace('#list_list', render($form['private_list']));
    return array(
        '#type'=>'ajax',
        '#commands'=>$commands
    );

}

```

When the 'Add' button is clicked, a new array of options should be returned, but I get an empty list instead.

The form is rendered in a ctools modal if that is of importance.

Thanks for any help with this - it's driving me barmy.

# Answer
> 3 votes
I think you need to reorganize your code. First you need two \['Private\_list'\] at the same function Form and at this same function form you need to declare the array variables for each private list.

```
$list1_options = array(......);
$list2_options = array(.......);

```

\['Private\_list1´\]: these are the first choice the user need to do: here you use the ajax call back.

\['Private list2'\]: these one have the choices the user need to pick according to the first selection on \['Private\_list1´\]: at this 'Private\_list2' you use the wrapper prefix and suffix.

the ajax call back function should only look something like this most of the times:

```
function example_change_callback($form, &$form_state) {
  return $form['private_list2'];
}

```

Your basicly using the call back to identify wich form you need to update on event change.

I recommend you study this drupal dependent ajax example, dispate the example is using dropdown list, you should be able to aply it to radio buttons, just follow the same structure.

I hope i was hepfull, tell us later how it went... Have a good coding!

---
Tags: forms, ajax
---


title: How to make a Drupal Portfolio?

text:
# Question
Title: How to make a Drupal Portfolio?
I have to make a Portfolio for a school project.

I chose Drupal because i wanted to try and learn it.

I have chosen the following theme: https://www.drupal.org/project/portfolio\_zymphonies\_theme

I was searching for hours how to add styled content. I want to add circles with logos in it and the text underneath.

How can I do that?

# Answer
You could use blocks or Views if you want to display node content. Probably best to use blocks for your use case.

Another method, would be to edit or create a template file. They are located in `/sites/all/themes/YourTheme/templates` folder.

To style stuff, you need to use CSS, so edit your theme's `.css` file.
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: Config entity form field with multiple/unlimited cardinality
I have a config entity form that has a taxonomy field, and it currently works with 1 term

```
$form['integration'] = array(
  '#type' => 'entity_autocomplete',
  '#title' => 'Integration',
  '#required' => TRUE,
  '#target_type' => 'taxonomy_term',
  '#default_value' => $entity->getIntegration(),
  '#selection_settings' => array(
    'target_bundles' => array(
      'integration',
    ),
  ),
);

```

That works fine, but I need to be able to select multiple terms, I've tried setting `'#cardinality' => -1`, but it's only allowing 1 element. I added a taxonomy field with unlimited cardinality to a content type, then set a breakpoint on the form to see how it was being set up for the page rendering. It looks like it creates a `container` form element, then I assume iterates over an array containing all the terms?

I would have thought there would be a way to set the cardinality of an element by making use of field widgets on the config form page, but I'm not sure that's possible.

# Answer
(Content) fields have cardinality. There is no such concept for form elements.

However, entity\_autcomplete does have a #tags flag, which you can see in the getInfo() method of the class: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21Element%21EntityAutocomplete.php/function/EntityAutocomplete%3A%3AgetInfo/8.

If you set that to TRUE, then it allows you to select a comma-separated list of references.

If you're looking for the "Add another" functionality of entity\_autocomplete or any other form element, then you have to build it yourself.
> 3 votes

---
Tags: forms, 8, entities
---


# Question
Title: Block cache depending on current node and its last modification time
I am building a module with a block that outputs some informations from the current node.

When i return my render array i managed to get the cache as "node dependent" using (maybe not the best method ?) :

```
        '#cache' => [
            'contexts' => [
                'url',
            ],
        ],

```

The blocks are showing up the right contents on the right pages, but if i modify my node and it's fields, the block content remains pulled from the cache and is not updated with the latest values.

Is there anything to add in the #cache array or a way to invalidate this specific cache when node gets updated ?

# Answer
See my answer to a similar question here: Passing current node ID to the block template

In short, use the plugin context system to get the current node injected. It will automatically ensure that the right cache tags and contexts are added, based on where node is coming from.

Depending on what information you need exactly, you could also consider using the default entity view blocks provided by ctools. That allows you to view the node in a given view mode.
> 4 votes

# Answer
Allright, I found an answer using cache tags and the current node id like this :

```
'tags' => array('node:' . $node->id()),

```

The full cache array being :

```
'#cache' => array(
                'tags' => array('node:' . $node->id()),
                'contexts' => array('url'),
            ),

```

Ref : https://www.drupal.org/developing/api/8/cache/tags
> 2 votes

---
Tags: nodes, 8, blocks, caching
---


title: Add Legend to Text Format Fieldset

text:
# Question
Title: Add Legend to Text Format Fieldset
I'm working on making a site I maintain WCAG AA compliant. One of the items I'm getting flagged for is "Every FIELDSET element must contain exactly one LEGEND element." This error shows up on every page that has a comment function. It turns out it is due to the Text Format option for the comment body:

I've tried DMPing `$form` from a `form_alter` hook, but I can't seem to find this field set anywhere, at least it doesn't seem to be in the comment-form form.

The ID of that form Item is `edit-comment-body-und-0-format--2`, which when I check my DPM output, there is an entry in comment-body/0/#format, but it's null.

Where can I add a legend to this field set?

# Answer
I got this to work like this:

```
function mymodule_process(&$variables, $hook) {
  if($hook == 'comment_wrapper') {
    $variables['content']['comment_form']['comment_body'][LANGUAGE_NONE][0]['format']['#post_render'][] = '_mymodule_post_render_fieldset';
  }
}

function _mymodule_post_render_fieldset($content, $element) {
  $your_legend = '$0<legend>Your comment legend</legend>'; // $0 is the full matched string
  return preg_replace('/<fieldset[^>]*>/', $your_legend, $content);
}

```

Care to give this a try?
> 1 votes

---
Tags: 7, forms
---


# Question
Title: How to implement custom Checkboxes in Checkout
How can I implement custom checkboxes to drupal commerce checkout?

Those information I want to have attached to the order.

I have checked extra panes, but I haven´t found a way how to include those checkboxes.

# Answer
> 2 votes
Check out one of the following modules:

1. Commerce Checkout Field Group:

> Commerce Checkout Field Group turns Commerce order field groups into checkout panes. This allows to add custom fields to the checkout pages.
2. Commerce Fieldgroup Panes:

> This module creates for each field group of the order entity a new checkout pane. These panes can be activated or deactivated as usual.
> This enables an easy way to collect information in the checkout process. For example customer comments, feedback about where the customer founds the shop or any other fieldable information.

---
Tags: commerce
---


# Question
Title: Display message on initial login only once without a module
What method is there to show a message on a user that just logged into the site without using a module? I know rules can do it, but I dont want to install a module just to do that. Is there some type of indicator variable that gets set upon initial login?

# Answer
> 1 votes
I propose you to have a look at this: hook\_user\_login, it fires exact on user log-in. A sample code is provided on its documentation page ready to be configured and used.

# Answer
> 1 votes
I just did a preg\_match() on the $messages variable in the page.tpl.php file. I had it detect the string "Logged in" which gets displayed when you login.

```
<?php
  print $messages;

  if (preg_match("/Logged in/i", $messages)) {
    print '<div class="messages newfeat">*NEW FEATURE* - My Works Page [X]</div>';
  }
?>

```

---
Tags: users
---


# Question
Title: Programatically create field collection into Profile2 on new user creation
I've set up my own custom multi-step registration form, because I just couldn't find a way of making anything out there do what I want. I've found other questions on here like this one and this one which have basically got me 95% there. My main problem now is that I've got a series of field collections in my Profile2 fields, and I just can't seem to find out what my code needs to be in order to get it done properly.

\*At this point in the code I've created a new user ($user), and their profile2 ($profile2) and I'm trying to format my fields from my form so that I can throw them all into the $profile2 object.

field\_activities

* field\_start\_year
* field\_end\_year
* field\_text

My code so far is:

```
$field_collection = entity_create('field_collection_item', array('field_name' => 'field_activities'));
$field_collection->setHostEntity('profile', $profile2);
$field_collection->field_start_year = $entry['start_year'];
$field_collection->field_end_year = $entry['end_year'];
$field_collection->field_text = $entry['text'];
$field_collection->save(FALSE);

```

And the error I'm getting is:

> Fatal error: Call to a member function `setHostEntity()` on a non-object

Which would make more sense to me if `$profile2` wasn't an object, but it is.

I've got too many unknowns to figure this out at the moment, is it the right code? can I build a create a field collection item on a newly created profile2 object? do I populate all the fields of the profile object first, and then once it's saved, then add the field collections, etc.

# Answer
> 2 votes
> Fatal error: Call to a member function `setHostEntity()` on a non-object

The error means that you are trying to call `setHostEntity()` method on a **non-object**, in other words the `$field_collection` is **not** an object (NULL probably).

So please check one line before, which is:

```
$field_collection = entity_create('field_collection_item', array('field_name' => 'field_activities'));

```

So basically you are trying to load `field_activities` field collection, but it is not there, therefore your `$field_collection` is `FALSE` as per entity\_create API:

> Return value: A new instance of the entity type or `FALSE` if there is no information for the given entity type.

Therefore please make sure your `field_activities` exists as field collection (e.g. at `/admin/structure/field-collections`), or add additional failing scenario to your code, so when `$field_collection` is `FALSE`, do not execute further code.

For valid examples using field collections, check: Entity metadata wrappers page.

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


# Question
Title: 3 Level dependent dropdown. The 3rd list won't update
i'm trying to make a 3 level dropdown lists. Country -\> State -\> City.

So far i got it working with 2 levels, Country -\> State. But when i change state it doesn't give me the cities. I've been reading and i found this previously asked question wich have an answer, but i still can't comment the answer (just starting at drupal.stackexchange) to ask for clarification, because i don't understand the answer given, i don't i even know it that answer apply for my own code, i think it does.

Would some body help understand?

This is the code I'm using.

```
//define types of locations.
define("LOCATION_TYPE_COUNTRY", 1);
define("LOCATION_TYPE_STATE", 2);
define("LOCATION_TYPE_CITY", 3);

// START PROJECT CREATOR FORM
function project_creator_form($form, &$form_state) {
    global $user;
    $uuid = $user->uid;

     $countries = _location_get_countries();

  $flat_countries = array(
    '' => '-- Seleccione país --',
  );

  $flat_countries = location_flatten_locations_array($countries, $flat_countries);

  $flat_states = array(
    '' => '-- Seleccione departamento --',
  );

   $country_id = '';

 if(isset($form_state['values']['p_ctry'])) {
    $country_id = $form_state['values']['p_ctry'];

    $states = _location_get_states($country_id);

    $flat_states = location_flatten_locations_array($states, $flat_states);
  }

  $flat_cities = array(
    '' => '-- Seleccione ciudad --',
    );

  $state_id = '';

   if(isset($form_state['values']['p_dept'])) {
    $state_id = $form_state['values']['p_dept'];

    $cities = _location_get_cities($state_id);

    $flat_cities = location_flatten_locations_array($cities, $flat_cities);
  }

    $form['p_ctry'] = array(
    '#type' => 'select',
    '#title' => t('Seleccione país del proyecto'),
    '#options' => $flat_countries,
    '#default_value' => $country_id,
    '#description' => "Seleccione el país donde se ejecutará el proyecto.",
    '#required' => TRUE,
    '#ajax' => array(
        'event' => 'change',
        'callback' => 'location_country_change_callback',
        'wrapper' => 'state-wrapper',
        ),
    );

    $form['p_dept'] = array(
    '#type' => 'select',
    '#title' => t('Seleccione el departamento/estado'),
    '#prefix' => '<div id ="state-wrapper">',
    '#options' => $flat_states,
    '#default_value' => $state_id,
    '#suffix' => '</div>',
    '#description' => "Seleccione el departamento o estado donde se ejecutará el proyecto.",
    '#ajax' => array(
        'event' => 'change',
        'callback' => 'location_city_change_callback',
        'wrapper' => 'city-wrapper'
        ),
    );

    $form['p_city'] = array(
    '#type' => 'select',
    '#title' => t('Seleccione ciudad'),
    '#prefix' => '<div id ="city-wrapper">',
    '#options' => $flat_cities,
    '#suffix' => '</div>',
    '#description' => "Seleccione la ciudad donde se ejecutará el proyecto.",
    );

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

  return $form;

}

function location_country_change_callback($form, &$form_state) {
  return $form['p_dept'];
}
function location_city_change_callback($form, &$form_state) {
  return $form['p_city'];
}
function location_flatten_locations_array($array, $start = array()) {
  if(is_array($start)) {
    $result = $start;
  } else {
    $result = array();
  }

  asort($array['by_name']);

  foreach($array['by_name'] as $item) {
    $result[$item['id']] = $item['name'];
  }

  return $result;
}

function _location_get_locations($location_type){

    $location_type = intval($location_type);
    static $locations = array();

    if(!array_key_exists($location_type, $locations)) {

       db_set_active('civilproconstru');

      $query = 'SELECT * FROM `location` WHERE `location_type` = '.$location_type.' AND `is_visible` = 1';

      $result = db_query($query);

      foreach ($result as $row) {
          $name = $row->name;
          $id = $row->location_id;
          $parent = $row->parent_id;

          $record = array(
            'name' => $name,
            'id' => $id,
            'parent' => $parent,
          );

          $locations[$location_type]['by_name'][$name] = $record;
          $locations[$location_type]['by_id'][$id] = $record;
      }

       db_set_active();

    }
    return $locations[$location_type];
}

function _location_get_countries() {
  return _location_get_locations(LOCATION_TYPE_COUNTRY);
}

function _location_get_states($country_id = null) {
  $states = _location_get_locations(LOCATION_TYPE_STATE);
  if(!is_null($country_id)) {
    $closure = function($item) use($country_id) {
      return $item['parent'] == $country_id;
    };
    $states['by_name'] = array_filter($states['by_name'], $closure);
    $states['by_id'] = array_filter($states['by_id'], $closure);
  }
  return $states;
}

function _location_get_cities($state_id = null) {
  $cities = _location_get_locations(LOCATION_TYPE_CITY);
  if(!is_null($state_id)) {
    $closure = function($item) use($state_id) {
      return $item['parent'] == $state_id;
    };
    $cities['by_name'] = array_filter($cities['by_name'], $closure);
    $cities['by_id'] = array_filter($cities['by_id'], $closure);
  }
  return $cities;
}

function project_creator_form_submit($form, &$form_state) {

    db_set_active('civilproconstru'); //OPEN alter DATABASE.
    db_insert('project_info')
        ->fields(array(
        'p_ctry' => $form_state['values']['p_ctry'],
        'p_dept' => $form_state['values']['p_dept'],
        'p_city' => $form_state['values']['p_city'],

        ))->execute();
    drupal_set_message(t('The form has been sbmitted.'));
db_set_active(); //CLOSE alter DATABASE.
}
?>

```

# Answer
> 0 votes
After two weeks of looking for an error at this code, it turned out there is no error in the code. The error was at some values of the database, more exactly at the *is\_visible* value.

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


# Question
Title: Adding a Taxonomy term in a node via services
I am trying to submit a node via an android native app in java. I am using services 3.3, and I am able to login, and submit to a Content type assuming all of the fields are Text fields.

But I would also like to add some taxonomy terms as fields. The Tax term is already defined on the drupal system. I have a term NAME: "A". tid:37.

what is the services technique to submit a Tax term? or even some hints.

I also want to submit some images as well... another question perhaps

# Answer
I'm not familiar with Services module or drupal's web service (I usually use Symfony for such Services), but I don't think there are any specific rules for such task. Assuming there is a callback in your module which receives a data from external resource, e.g.:

```
function module_menu()
{
  ...

  $items['my-path/%'] = array(
    'title' => 'TITLE',
    'page callback' => 'myCallback', // this can be either `drupal_get_form` or your callback function..
    'page arguments' => array(1),
    ...
  );

  ...
}

```

and define that callback:

```
function myCallback($data /* assuming $data is an array, but It can be another type, JSON, XML... */)
{
  if(empty($data)) {
    // some dummy check
    return 'Invalid data';
  }

  $node = entity_get_controller('node');
  $node->type = 'MY_TYPE';
  // set other base fields such as author...

  $nodeWrapper = entity_metadata_wrapper('node', $node);

  $nodeWrapper->field_MYTEXTFIELD->set($data['text_field_data']);
  $nodeWrapper->field_TERMFIELD->set($data['term_field_data']);
  ....
  $nodeWrapper->save();

  ...

  // finally return response
}

```
> 0 votes

# Answer
I am assuming that since you already have the TID, you wish to create a note with an association to that TID.

If you have a node with a field called "tags", then you must do the following:

Within the JSON you send to the node creation endpoint (endpoint/node), you must include a JSONObject with a key of "field\_tags". The value paired to that key should be a JSONArray named as per your language requirement (und, in many cases). This JSONArray should be populated with JSONObjects keyed by "tid".

Overall, this should be the structure of your JSONObject (Notice that the square brackets indicate a JSONArray):

```
"field_tags": { "und": [ { "tid": "37" } ] }

```
> 0 votes

---
Tags: taxonomy-terms, services
---


# Question
Title: 403 error in files while hosting drupal site in hostgator
I'm trying to host my drupal site in Hostgator. Here what i've done so far: a. uploaded files to server, created db and user and imported too. b. Change settings.php database content.

My site is up and running although my css and files are not being loaded..when i check my browser console it shows 403 error, even i can't access my backend whenever i try to access it shows 404 error,although it seems to be working fine on my localhost.. i know it's permission problem but i don't know how to deal with it is there any steps i leftover which i need to follow, is there any step by step documentation on hosting drupal site on cpanel any help would be great.Thanks in advance.

P.S.-i'm using nginx, and linux system for my development environment. And new to drupal :)

# Answer
> 0 votes
Read up on the basics of linux permissions. Figure out which user nginx is running under. Make sure that user has read access on files and read/execute access on directories.

---
Tags: files
---


# Question
Title: How to embed views in a particular custom block template
I have created a views block in D8 and thinking to embed it within a particular custom block template I created to override (e.g block--myblock.html.twig), I wonder how to do this ?

# Answer
> 0 votes
Ok, I have found a way to do so from another post, tested and it works ! So basically..

1) Create a new variable in **mytheme.theme** file located in your default theme folder.

```
function mytheme_preprocess_block(&$variables) {

  $variables['view1'] = views_embed_view('view_name', 'block_news');

}

```

*'block\_news' is your views block's machine name actually.*

2) And then use this twig in your block template.

```
 {{ view1 }}

```

---
Tags: theming, 8
---


title: How to change node save button text?

text:
# Question
Title: How to change node save button text?
I found a discussion with some methods for d6 here http://drupal.org/node/344802 on how to change the node "Save" button text to sg else.

Any tips for d7? I would prefer to use form api.

# Answer
> 19 votes
you could use string overrides module or use hook:

```
function yourmodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'name_of_form') {
    $form['actions']['submit']['#value'] = 'Your button text';
  }
}

```

# Answer
> 6 votes
Here is an example: I have created a module called `change_form_values` and the form ID of my content type is `content_type_test_node_form`:

this work for me in Drupal 7:

```
function change_form_values_form_alter(&$form, &$form_state, $form_id) {
    //dsm($form_id); // to see form ID
    if ($form_id == "content_type_test_node_form") {
    $form['actions']['submit']['#value'] = 'New button text';
    }
}

```

this work for me in Drupal 6:

```
function change_form_values_form_alter(&$form, &$form_state, $form_id) {
    //dsm($form['form_id']['#id']);
    if ($form_id == "content_type_test_node_form") {
    $form['buttons']['submit']['#value'] = 'New button text';
    }
}

```

I hope information be useful.

# Answer
> 0 votes
I found the excellent Node buttons edit module for this and it works really our of the box using admin. Here is an excerpt about it from the module's project page:

> This is a simple little module that allows one to change the text on the 'Save', 'Preview' and 'Delete' buttons on a node form.

# Answer
> 0 votes
For Drupal7 it's simple just:

```
$form['buttons'] = array(
    '#type' => 'submit',
    '#value' => t('Your desire text here'),
    );

```

Wihtout adicional functions...

---
Tags: 7, forms, nodes
---


# Question
Title: Making all REST Server calls to Drupal site as an authenticated user through Services
I am making REST Service calls to my Drupal 7 site to either retrieve or create content.

Is there a way I can make all these calls through one specific authenticated user?

Thanks.

# Answer
> 0 votes
You can use jdrupal.min.js. and set variables as follows in your js:

```
 Drupal.settings.site_path = "http://example.com"; // SET Drupal site Path
 Drupal.settings.endpoint = "services_endpoint_name";  // Set the Service Resource REST endpoint path FROM services module in Drupal site.

```

and you can use directly functions for for doing operation such as:

```
user_login(username, password, {
                        success: function (result) {
                          cosole.log(result);
                        },
                        error: function (xhr, status, message) {
                            console.log(status +" Error Message"+ message)
                        }
                    });

```

If login successful then you are logged in with the authenticated user in your Drupal site. And also you can do number of operations node save, update, delete etc.

---
Tags: services, 8, users, authentication-authorization
---


# Question
Title: Display different account fields for my account vs public account
How can display/hide some fields when viewing an account that isn't the current user vs. is the current user (e.g. the users/steve vs /user)?

I want to have a public profile that shows most of the same fields but hides a few fields that only the 'current' user can see.

# Answer
Field Permissions

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

You would want to use the view own value check and view any value unchecked.
> 0 votes

---
Tags: users
---


# Question
Title: Restrict coupon for same shipping address (or user creating multiple email ids)
We have scheme “Register & Earn Coupon of Rs. 200” Some users create multiple gmail accounts to avail multiple coupon. They get the order shipped at the same place. Is there a solution available to handle this?

# Answer
> 1 votes
There is surely a way to block this, you can alter the forms and add validations. But do you really want one to one mapping between shipping address and user account?

What if the old user wants to purchase the same product again, or a new user signing up stays in the same apartment?

Maybe you need to review your business rules and figure out a better way to restrict this behaviour.

Maybe IP address?

---
Tags: commerce
---


# Question
Title: How to export the log messages in .csv file?
How can I export the log messages (`Site Reports-->Recent Log Messages`) in a .csv file?

# Answer
You can use phpMyAdmin to export the watchdog table (or select entries) in csv format which excel can read.

If you do not have access of database, you can use Views, Views Watchdog and Views data export modules to accomplish this.
> 4 votes

# Answer
Create a "report" to select (and sort, etc) the log messages you want to export using the Forena module. And specify what kind of hyperlinks you want to make available for performing such "export". These hyperlinks correspond to various supported "formats", such as: CSV, PDF, XLS, XML, DOC, HTML ... (the "report designer" selects what the allowed/enabled export formats for a report are). To get an idea of how that would look like, visit the Customized Simple Table of States. Notice the links in it, such as "CSV" (upper right), which in this case would "export" the results in a CSV file.

### Drupal admin reporting

The Forena 'Drupal Admin' reports is 1 of the sets (categories) of reports, that come out of the box with Forena. By default they can only be accessed by users with role "admin" (unless you adapt the permissions to access them by other roles also). So if somebody installs Forena in a Drupal site, and they have the "admin" role, then they get access to all sorts of Drupal admin related reports (like **watchdog reports**) in their "own" environment. Some of those reports are:

* **Active Users** \- A variation of D7's admin/people, including hyperlinks to the Logs for User report.
* **Logs for User** \- Most recent watchdog log entries for a user (specified as a report parameter).
* **Role Details** \- A table displaying all users for a Drupal role (specified as a report parameter), and the Drupal permissions granted to them, with for each user hyperlinks to either view or edit the user's profile.

For this specific question, you should be interested in the "**Logs for User**" report. You could use it to clone (copy) it into a custom report that fits your exact needs. For an example of how I ever create a variation of that report, have a look at my answer to "Which Drupal log file is available to proof when exactly some content was deleted and by whom?". Here is how that variation (custom report) looks like:

### More details about Forena

For more details about Forena, 2 types of documentation are available:

* Community documentation, which includes a child page Video demos and tutorials.
* Documentation that comes with Forena, which you can access right after you install and enable of the module. Checkout the demo site for an online example of the current:

+ **Forena documentation** \- use the link 'Reporting documentation' or visit relative link /reports/help.
    + **Forena samples** \- use the link 'Reporting samples' or visit relative link /reports/samples (these samples are fully functional, so make sure to experiment a bit with it, such as the drill downs available on the SVG Graph sample).

**Disclosure**: I'm a (co-)maintainer of Forena.
> 1 votes

---
Tags: log-messages
---


title: Render form elements separately

text:
# Question
Title: Render form elements separately
How to render custom form's `$form['#action']` property in the controller's template when it actually contains some random string like `form_id_66dbsfds` ?

# Answer
> 1 votes
Previous answer is not an answer for my question. 1. `{{ form['#action'] }}` returns a string, which is not a url string, this is some kind of a route, but url generator does not recognize it. 2. If there's a need to render a form separately by the fields in a template - never use `#markup`, always use `#theme` and variables. 3. I did this like that:

```
    $request = $this->getRequest();
    $route = $request->attributes->get('_route');
    $routeParams = $request->attributes->get('_raw_variables')->all();
    $currentPath = $this->get('url_generator')->generate($route, $routeParams);

```

To get a current url. And then:

```
<form id="{{ form['#id'] }}" accept-charset="UTF-8" method="{{ form['#method'] }}" action="{{ currentPath }}">

```

The question was - how to get a proper action string from the form object.

# Answer
> 3 votes
I tried below code to render form in my controller class and it is working fine

```
$form = \Drupal::formBuilder()->getForm('Drupal\hollywood\Form\Hollywood');
$form = \Drupal::service('renderer')->renderRoot($form);

$content['exposed_filter'] = array(
  '#markup' => $form,
);

return $content;

```

Drupal\hollywood\Form\Hollywood is a namespace of the class.

---
Tags: forms, 8
---


# Question
Title: Display paragraphs items in comma-seperated series
I have a series of paragraphs items representing two different types of contributors to a publication: staff (user link) and non-staff (text). (See How to control the display of a user account connected via entity reference)

According to Paragraphs preprocess paragraphs handles building the render array for its items in the same way as nodes, comments, etc, so maybe my question is much broader, but here's what I'm trying to do:

I want to send up with a basic comma separated list of items:

Person 1

or

Person 1 and Person 3

or

Person 1, Person 2, and Person 3

with links on the items that should be links. I guess I just am not getting render arrays and the theming functions well enough yet, that I understand how to do it.

The paragraphs preprocess question makes me think maybe I should be overriding the fields\_formatter, but what I've been working on up to this point is `theme_preprocess_paragraphs_items()`. That seems like it should allow me to do what I want, I can see that I could loop through `$variables['element']['#items']` or maybe the integer keys of `$variables['element']`, but how to change those so that they append ', ' or ', and ' or whatever as appropriate (outside of the link on link items is escaping me). (I do understand how to determine what should be appended, just not where to append it to make drupal output what I want.

# Answer
> 0 votes
> append ', ' or ', and ' or whatever as appropriate

You can use CSS to accomplish this

### HTML

```
<div class="paragraphs-items paragraphs-items-field-doc-editor paragraphs-items-field-doc-editor-full paragraphs-items-full">
  <div class="label-inline">
    Editor:
  </div>
  <div class="entity entity-paragraphs-item paragraphs-item-doc-other-contrib-pb" about="" typeof="">
    <div class="content">
      <div class="field-pb-doc-other-fullname">
        <div class="field-items">
          <div class="field-item even">
            Person 1
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="entity entity-paragraphs-item paragraphs-item-doc-other-contrib-pb" about="" typeof="">
    <div class="content">
      <div class="field-pb-doc-other-fullname">
        <div class="field-items">
          <div class="field-item even">
            Person 2
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="entity entity-paragraphs-item paragraphs-item-doc-other-contrib-pb" about="" typeof="">
    <div class="content">
      <div class="field-pb-doc-other-fullname">
        <div class="field-items">
          <div class="field-item even">
            Person 3
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="entity entity-paragraphs-item paragraphs-item-doc-other-contrib-pb" about="" typeof="">
    <div class="content">
      <div class="field-pb-doc-other-fullname">
        <div class="field-items">
          <div class="field-item even">
            Person 4
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="paragraphs-items paragraphs-items-field-doc-author paragraphs-items-field-doc-author-full paragraphs-items-full">
  <div class="field-doc-author inline">
    <div class="field-label">
      Author:
    </div>
    <div class="field-items">
      <div class="field-item even">
        <div class="entity entity-paragraphs-item paragraphs-item-doc-iges-contrib-pb" about="" typeof="">
          <div class="content">
            <div class="field-pb-doc-iges-staff">
              <div class="field-items">
                <div class="field-item even">
                  <a href="/person4">Person 4</a>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="paragraphs-items paragraphs-items-field-doc-editor paragraphs-items-field-doc-editor-full paragraphs-items-full">
  <div class="label-inline">
    Translator:
  </div>
  <div class="entity entity-paragraphs-item paragraphs-item-doc-other-contrib-pb" about="" typeof="">
    <div class="content">
      <div class="field-pb-doc-other-fullname">
        <div class="field-items">
          <div class="field-item even">
            <a href="/person5">Person 5</a>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="entity entity-paragraphs-item paragraphs-item-doc-other-contrib-pb" about="" typeof="">
    <div class="content">
      <div class="field-pb-doc-other-fullname">
        <div class="field-items">
          <div class="field-item even">
            <a href="/person6">Person 6</a>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

```

### CSS

```
.paragraphs-items { /* start each field on a new line*/
    clear: left;
}

.paragraphs-items div { /* eliminate the blocky results of div hell (eliminate some extra spacing in the process)*/
    float: left;
}

.paragraphs-items .entity-paragraphs-item .content:after { /* default to putting commas after every value … */
    content: ", ";
}

.paragraphs-items .entity-paragraphs-item:last-child .content:after { /* … except the last one */
    content: "";
}

.paragraphs-items .entity-paragraphs-item:nth-last-child(2) .content:after { /* The last two items in the series should be separated by a ", and " … */
    content: ", and ";
}

.paragraphs-items .entity-paragraphs-item:nth-last-child(2):nth-child(2) .content:after { /* … unless there are only two items, in which case it should be " and " */
    content: " and ";
}

```

# EXAMPLE DEMO

**Note** in `content: ", "` since it won't pick up the empty space (by pressing the space bar) I used the ALT+0160 trick to make the **empty space**.

---
Tags: 7, theming
---


title: Order total discount in ubercart?

text:
# Question
Title: Order total discount in ubercart?
I want to total order discount in ubercart on drupal 7. I want to 10% discount on total order.Is there any way to do that?

# Answer
> 0 votes
Commerce Discount Extra

> Provides a number of common discount condition and offer types:
>
> **Order discounts**
>
> **Condition types**
>
> * Order-owner role
> * Total items in order
>
> **Offer types**
>
> * Fixed amount per-quantity discount (Buy X product get Y (or X) product at discount up to some number of (or unlimited) times)
> * Percent per-quantity discount

Ubercart Discount Coupons

> A checkout pane, a cart pane and a block are available for customers to enter coupon codes, each of which can be enabled or disabled separately. Discounts can be shown as an item in the cart or applied on the checkout page.

---
Tags: 7, ubercart
---


# Question
Title: Is there a successor project to Omega 4?
I'm a big fan of the Omega base theme, trying to make sense of what's going on with that project.

**What I'm trying to do, is work with something similar to Omega 4 that is actively maintained on both 7 and 8 and will be capable of being upgraded to Drupal 8 in future.**

I've read that there was a public falling out among the maintainers and that **Omega 5 is progressing in a very different direction** with different aims to Omega 4. I've also read that the Omega 4 maintainers are giving it minimal maintainence with many hints that their efforts will be focussed on other projects under other namespaces, and there have been no new dev releases since July 2015:

> Omega 4.x is still minimally maintained (I am committing bug-fixes and other critical / major patches). However, I am not interested in further moving on with anything under this namespace as stated previously in other issues. The reasons for that are well known and have been publicly discussed... There won't be any extended effort from me (and probably not from Matt either) to expand on the existing functionality of 4.x or even work on a new version... I will keep maintaining the 4.x version of course though so you can totally feel safe when using that at least.

Is there a new project that continues what Omega 4 was trying to achieve under a new namespace, that will be actively maintained on Drupal 7 and 8?

---

I've seen Khan described as "the omega 4.x successor for drupal 8", but it's had no work since 2014 and its project page is... baffling. It looks more like a Drupal community in-joke than a serious project. There's a thread with many people asking about this, but no clear answers.

# Answer
I found what looks like an explanation from 2016. It looks like Omega 4 is not going anywhere.

> ...both new Omega versions (7.x-5.x, 8.x-5.x) probably have nothing in common with (7.x-4.x) and are not the successor of Omega 4.
>
> The successor to (7.x-4.x) is new project Khan so all the questions about that should be posted there. Truth to be told, there is not much activity there, since.
>
> So if you wish to make some sort of continuation of current 4.4 code base to D8, probably you will have to do it yourself. Personally, I do not think it will make much sense as the differences between D7 and D8 would not leave much in common.

The same user asked what the status of Khan is two months ago and hasn't received any reply. In another thread, the maintainer posted that Khan is postponed indefinitely:

> ...This is a serious project but since I am currently focusing on GraphQL for Drupal you can consider it postponed until I am done with the first release of that module.

So it seem fair to conclude that **there is no Drupal 8 successor to Omega 4** at time of writing.

---

Life is too short for drama, so I personally am going to (reluctantly) drop Omega and switch over to Bootstrap.
> 0 votes

---
Tags: theming
---


# Question
Title: Node reference - show parent node when viewing child
I'm using References module. I have parent node where I can choose multiple child nodes for it. This parent has reference-field. I have made views to list child nodes when viewing parent node.

Now I need to have views to show parent node when viewing child node.

This should be fairly easy to do(?), but I was not able to achieve it. I tried with reverse reference relationship, but it does not show nothing on child page.

How to show parent node (in views) when viewing child node?

# Answer
> 1 votes
Create one content type view with views module,

Set **relationship \>\> Content: Reference node** (field\_reference\_node)

In **contextual filter \>\> Content: Nid (relationship field\_reference\_node)**

Pass NID of child node within argument will result all node referenced with parent content.

---
Tags: 7, views
---


# Question
Title: How do I find the role id from role name?
On log in I want to check a third party data source (table in the db) for a user, and if found I want to add a role to that user.

I don't want to guess the rid of the role, I want to get it from the role name.

# Answer
This is quite straightforward with user\_roles() and array\_search(). Below is a function which will return the role ID if there is a role matching the name and FALSE otherwise.

```
function get_role_by_name($name) {
  $roles = user_roles();
  return array_search($name, $roles);
}

// Sample usage
$rid = get_role_by_name('administrator');

```

One liner would be:

```
$rid = array_search('administrator', user_roles());

```
> 21 votes

# Answer
Knowing the machine name of the role, it is enough to use `user_role_load_by_name()`.

```
if ($role = user_role_load_by_name('Role Name')) {
  // The role ID is in $role->rid.
}

```

If the Role might not exist...

```
$role = user_role_load_by_name('Role Name');

$role_id = $role ? $role->rid : NULL;

```
> 32 votes

# Answer
The best way to identify role and its id is from SQL. Run this query in your SQL editor.

```
select * from roles;

```

And you will get the list of Roles including the id and weight.
> -4 votes

---
Tags: 7, users
---


# Question
Title: Clear cache after save orders using draggable views in Drupal 7
I've used **Draggableviews 7.x-2.1** module to enable drag & drop options for particular views. It works well.

I've enabled cache for Anonymous users. Due to this, after save the ordering, the changes didn't affect orders for Anonymous users.

So I've tried to clear cache after submitting handler of draggable views. I've used below code:

```
function phponwebsites_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_form_test_views') {
    $form['#submit'][] = 'phponwebsites_draggable_custom_submit';
  }
}

function phponwebsites_draggable_custom_submit(&$form, $form_state) {
  print_r('ss');exit;
  drupal_flush_all_caches();
}

```

But my custom submit handler doesn't call. Is any other solutions?

# Answer
> 1 votes
Sometimes "#submit" functions of HOOK\_form\_alter are get changes. SO please try adding $form\['#after\_build'\]. Your code will be like.

```
function phponwebsites_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_form_test_views') {
    $form['#after_build'][] = 'phponwebsites_draggable_custom_afterbuild';
  }
}
function phponwebsites_draggable_custom_afterbuild($form, $form_state) {
  $form['#submit'][] = 'phponwebsites_draggable_custom_submit';
  return $form;
}
function phponwebsites_draggable_custom_submit(&$form, $form_state) {
  print_r('ss');exit;
  drupal_flush_all_caches();
}

```

---
Tags: caching, views
---


# Question
Title: How to use Rules to send an email to an email id based on a selected in a registration form?
I have created a rule for sending an email after a new user registered. I would like to add a Rules Condition to send the email to the target based on the selection in the registration form.

For example: if I select the country as india I need to send to india@gmail.com and for other others@gmail.com.

I have tried adding a condition in To mail receipt address:

```
$email = ($account->country == 'india'? india@gmail.com : 'other@gmail.com')
echo $email;

```

Can you suggest how to handle the scenario?

# Answer
> 1 votes
You should be able to get this to work by creating a single rule using the Conditional Rules module (and Rules of course). The rule should be trigger by Rules Event "*after saving a new user account*".

For some samples to put together such rule (in Rules export format), refer to my answer to either of these questions:

The actual Rules Action you want to use, should be pretty similar to the Rules Action included in my answer to "How to send an email via a Rules action using a field key?".

---
Tags: users, emails
---


title: How to print the prices node.tpl.php?

text:
# Question
Title: How to print the prices node.tpl.php?
I installed the Commerce Price Savings Formatter module. Can you explain me how to display the price in a file `node--scs.tpl.php`? it is for a newsletter.

When I put

```
 <? php print render($content[ 'product: commerce_price']); ?>

```

It displays the full price with the original price, percent discount and the reduced price.

I want to display each item in the "td" separate. I tried

```
<? php print render($content['product: commerce_price: Trade-price-savings-formatter-savings']); ?>

```

But it does not work.

thank you in advance

# Answer
Calling `render($content[...]);` renders the field—but you need to change *how* the field is being rendered. To do this, you'll need to modify it's display widget.

Go to Admin→Store→Configuration→Product types→*Product type*→Manage Display. Then, on the price field, change the the formatter (the first arrow):

This can be further configured by clicking on the gear icon (right arrow) to get access to more configuration.

If this still does not suffice, try these:

1. Add a `HOOK_commerce_price_savings_formatter_formatter` to your theme to override the theme provided by the module.
2. Create a new formatter (the price saving formatter modules can be used as an example) and then use that formatter to display your prices.
> 1 votes

---
Tags: commerce
---


# Question
Title: From where comes $scheme argument in image_style_deliver callback?
In core image.module there is a menu item:

```
  $directory_path = file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath();
  $items[$directory_path . '/styles/%image_style'] = array(
    'title' => 'Generate image style',
    'page callback' => 'image_style_deliver',
    'page arguments' => array(count(explode('/', $directory_path)) + 1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

```

As you can see, there is only one argument passed to it. But when we see "image\_style\_deliver" function, we see:

```
function image_style_deliver($style, $scheme) {

```

I don't know if I'm tired or what but... from where $scheme argument comes from? ;)

# Answer
Drupal passes on extra portions of the URL as parameters by default. So for example, a URL might look like this:

http://example.com/sites/default/files/styles/style\_name/public/foo/bar.jpg

Which resolves in `image_style_deliver` to

```
$style = 'style_name';
$schema = 'public';

```

The function then goes on to extract the rest of the unnamed arguments, and reconstitutes them to form the eventual path to the file.
> 0 votes

---
Tags: 7
---


# Question
Title: Putting new configuration files in module hook_update_N upgrade?
If I release a new version of a module, and want to include new configuration in the new version (particularly new fields, and updates to views to rely on those fields) by either making Drupal update the config.whatever.yml files, or writing something in hook\_update\_N() that will install them, how could I do it? I would want to make sure it only installs the new fields if they don't already exist, since I would want to include the fields' yaml files.

Or, should I require features and use that for adding new fields?

It's confusing to me, because I want to include a config.yml that has the most recent config information, right? Yet, I want to update anyone already using the module by installing the new fields that they don't have.

EDIT 2:

**Okay, no, never mind**. Don't use the below code. I thought it worked, but really the fields were just installed via the yml files when I installed the module. I don't know why I didn't realize that would happen. My update function never really ran. When I retried it the correct way, it failed, because FieldConfigStorage can't be loaded in this way. I still don't know how to install fields in a way that will create the tables.

EDIT:

The code resulting from Berdir's example:

```
// Don't forget to include a use-statement if you haven't already:
use Symfony\Component\Yaml\Yaml;

function some_module_update_8101() {
  $message = "";
  if ( !FieldConfig::load('example_field') ){
    $config_path = drupal_get_path('module', 'some_module') . '/config/install/field.field.node.some_node_type.field_example_field.yml';
    $data = Yaml::parse($config_path);
    \Drupal::configFactory()->getEditable('field.field.node.some_node_type.field_example_field')->setData($data)->save(TRUE);
    $message .= "FieldConfig installed for module some_module.\n";
  }
  else {
    $message .= "It didn't work!\n";
  }
  if( !FieldConfigStorage::load('example_field') ){
    $config_path = drupal_get_path('module', 'some_module') . '/config/install/field.storage.node.field_example_field.yml';
    $data = Yaml::parse($config_path);
    \Drupal::configFactory()->getEditable('field.storage.node.field_example_field')->setData($data)->save(TRUE);
    $message .= "FieldConfigStorage installed for module some_module.\n";
  }
  else{
    $message .= "That didn't work either!\n";
  }
  return $message;
}

```

# Answer
> 7 votes
You can parse and load the yaml file yourself, something like redirect\_update\_8003:

```
use Symfony\Component\Yaml\Yaml;

/**
 * Creates the new default redirect view.
 */
function redirect_update_8103() {
  $message = NULL;

  // Only create if the redirect view doesn't exist and views is enabled.
  if (\Drupal::moduleHandler()->moduleExists('views') && !View::load('redirect')) {
    $config_path = drupal_get_path('module', 'redirect') . '/config/install/views.view.redirect.yml';
    $data = Yaml::parseFile($config_path);
    \Drupal::configFactory()->getEditable('views.view.redirect')->setData($data)->save(TRUE);
    $message = 'The new redirect view has been created.';
  }
  else {
    $message = 'Not creating a redirect view since it already exists.';
  }
  return $message;
}

```

---
Tags: entities, 8, updating
---


# Question
Title: form_set_error not working in node form validation
I'm frustrated right now. This very reduced module code shows the problem:

```
<?php

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ('pic_node_form' == $form_id && !path_is_admin(current_path()) ) {
    $form['#validate'][] = '_mymodule_pic_add_form_validate';
  }
}

function _mymodule_pic_add_form_validate($form, &$form_state) {
  form_set_error(null, t('Keep calm bro'));
  // die("foo");
}

function mymodule_node_validate($node, $form, &$form_state) {
  form_set_error(null, 'test');
  // die("bar");
}

```

`pic_node_form` is the node add form for the content type pic. That form is exposed (hence `&& !path_is_admin(current_path())`). There is an image upload field involved.

The `form_set_error` doesnt do anything and nodes keep getting submitted. The `die()` functions actually work when I remove the `//`, so the functions do get invoked.

The form itself is placed via block:

```
function _mymodule_get_block_content($delta) {
  if ('pic_add_form' == $delta) {
    global $user;
    module_load_include('inc', 'node', 'node.pages');
    $node = (object) array(
      'uid' => $user->uid,
      'name' => (isset($user->name) ? $user->name : ''),
      'type' => 'pic',
      'language' => LANGUAGE_NONE,
    );
    $form = drupal_get_form('pic_node_form', $node);
    $form_rendered = drupal_render($form);
    $markup .= $form_rendered;

    return $markup;
  }
}

```

Any ideas what I am doing wrong?

# Answer
> 1 votes
I guess that you have to set the `$name` (first) argument of the form\_set\_error function to a field name instead to `null`.

# Answer
> 1 votes
If you check the source of `form_set_error()`, you will see that if you don't supply the name of the form element for which you are setting the error, error messages will not be set.

As long as the first argument is `NULL`, form will be submitted. Your code was being executed, but it didn't stop the submission.

What you need to do is to pass the name of the field for which you want the error to show. This goes as the first argument for `form_set_error()`.

Example:

```
form_set_error('YOUR_FIELD_NAME', t('Your message'));

```

---
Tags: 7, forms
---


# Question
Title: Send HTML email to all users of a role in action not display .....help me please
Send HTML email to all users of a role in action not display ; only send HTML-email display help me please.

# Answer
That action comes from the Mime Mail module, it's not one of Rules's defaults.

Once you've downloaded and installed the new module, just re-visit the Rules setup page and you'll find it in the list.
> 0 votes

---
Tags: emails
---


title: How to edit one time login URL?

text:
# Question
Title: How to edit one time login URL?
I want to change the one-time login URL, which is the link being sent to the user in order to reset his password.

I want to make it smaller and not have the random letters in its URL.

Is this possible? Where can I change this?

# Answer
It is possible to do that, but you definitely shouldn't do it.

The "random characters" are there for security purposes. Without them, it would be easier to reset passwords of other users, including the super administrator (uid: 1) for example. The hashes in URL are also longer in order to prevent collisions and make it harder for others to guess.

Password reset URLs are time-sensitive and expire after 24 hours (by default) if not used. Here is the breakdown of the password reset URL:

* User ID of the member who is trying to reset the password.
* Timestamp of when the password reset has been requested.
* Hashed password. This is the element that is checked against the token stored in the database, and verifies that the link is valid. It's a unique hash that is built using the timestamp of when the password reset request has been made, account login information, hashed password and user ID. By doing so, the system makes it almost impossible to generate this information on your own, meaning that only your website is authorized to issue those URLs. And those URLs are issued only if you know the username or email address of an existing account. See the source of `user_pass_rehash()` to understand this better if you want.

All of this was made so your users and your site would be more secure.

If you want to fully understand how this process works, open the `/modules/user/user.pages.inc` file, and check specifically the `user_pass_reset()` function. That function is responsible for validating the request, and allowing the users to reset their password.

Hope this makes sense; I wrote it pretty fast but it should cover the main points.
> 5 votes

---
Tags: 7, users
---