# Question
Title: How can I run PHP code without writing a module?
I need to attach a field to some bundles. A PHP snippet will do the job for me, so I don't need a module.The below snippet is what must be executed :

```
$field_name = 'field_custom_image';
// Create the field.
$field = array(
  'field_name' => $field_name,
  'type' => 'image',
);
field_create_field($field);

```

and then the snippet to add this field to bundle :

```
// Create the instance.
$instance = array(
  'field_name' => $field_name,
  'entity_type' => 'node',
  'bundle' => 'article',
  'label' => 'Image',
  'description' => 'An image for the article.',
  'required' => TRUE,
);
field_create_instance($instance);

```

Is there a way to run PHP code directly in Drupal, without the need to write a module, install it, make it run, and uninstall it?

# Answer
> 8 votes
If you're saying "I need to run some PHP" and "I don't need a module" in the same thought, I'd suggest that you're going down the wrong path, either in the approach to this specific problem, or the approach to building the site in general.

`drush scr` will help you if that's the direction that you really want to go, or you could write a standalone PHP script (basically just copy/paste everything through the `drupal_bootstrap()` call from index.php, and add your custom code after) but there are a couple other things you could look at:

* Export your content type (and it's field bases and instances) with the Features module. IMO, you should be doing this anyway.
* Create a simple "site modifications" module, and include things like this in update hooks. Note that if you want to do this, you should create an empty module (with no update hooks), enable it on your site, and then add your update hook to get Drupal to see the update.

Many sites that I've worked on have had a combination of both of those solutions. Config should mostly go into exported Features modules, and anything that can't (are you *really sure* it can't?) can go into an update hook.

# Answer
> 21 votes
Yes, there is, but given your description I wonder if it will help you:

1. Install module Devel
2. Go to http://yoursite/devel/php
3. Enter your code and execute it.

# Answer
> 16 votes
If you need to run code just once, you can do it without installing any module, including the Devel module.

Write a PHP file (e.g. *tasks.php*), put it where the cron.php file that comes with Drupal is, and add the following code.

```
/**
 * Root directory of Drupal installation.
 */
define('DRUPAL_ROOT', getcwd());

include_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
drupal_set_time_limit(240);

// Your code here.

```

If you are already using Drush for maintaining/deploying your site, then you could make a Drush script. In this way, it could be executed by CLI, and it could receive any arguments, making it re-usable for many occasions.

```
#!/usr/bin/env drush

// Your code here.
// Access the options with drush_get_option(), or any argument with drush_shift().

```

You could also execute a PHP script with `drush php-eval` (or just `drush ev`), for example:

```
drush php-eval 'print time();'

```

I would create a Drush script, but if you cannot install Drush, or you need to execute PHP code from the browser, the first method works fine.

# Answer
> 12 votes
Add your code snippet to a file and save the file as `file_name.php` in your Drupal site root folder. Then run the following command in a terminal, from within the Drupal site root folder as your working directory:

`drush scr file_name.php`

This command will execute your PHP file. (To get an idea of the execution, you may include some print statements in your file, which will output the text, variable values etc. to the terminal where you execute the drush command.)

**Note:** As a prerequisite, you need to have `drush` installed on your system.

# Answer
> 3 votes
You can use `Php` inline of Devel module but lets get you one of my tricks in drupal to running my custom code without any module.

first create a `menu item` in `hook_menu`

```
function yourmdoule_menu()
{

    $items['ytest'] = array(
        'title' => 'my debug and devel test tool ',
        'description' => 'create for debug and faster develop',
        'page callback' => 'my_function',
        'type' => MENU_CALLBACK,
        'access callback' => true,
    );
    return $items;
}

function my_function{

/// run every want you want
}

```

then clear the cache ( because menu items cached in drupal ), and put everything you want in `my_function` and just type `yoursite.com/ytest`

I hope it will help you in projects "dada" ;)

# Answer
> 2 votes
The goal of Drupal modules is to provide separate logic to certain components, so they can be disabled if something goes wrong.

### `hook_install`/`hook_update`

In your case which is creating a new field on one-time basis, the ideal scenario is to use either `hook_install` or `hook_update`.

If you don't have a custom module (btw. you can also use exported feature module for that), create a new one just for updates (e.g. `site_updates`). In Drupal 7, all you need is to create folder with 3 files: `.info`, `.module` and `.install` and define install or update hook in your `.install`. Using install/update hook is convenient in order to have consistent environments, especially when you've multiple Drupal servers (such as dev, test and prod), so the change can be invoked during the next deployment.

If you still don't want to create module, here are other methods.

### One-time execution

If you need only to execute certain PHP code only one time, you can:

* Activate *Devel* module and paste the code at `/devel/php`,
* Use `drush` CLI (and its `eval`/`ev` command) to execute PHP code, e.g.

```
drush ev 'field_create_field(["field_name"=>"foo", "type"=>"image"]);'
drush ev 'print_r(field_info_field("foo"));'

```
* Use `drush scr` to execute PHP script:

```
drush scr my_file.php

```

where `my_file.php` is your plain PHP script with your code to execute.

### Specific page execution

To execute custom code on certain pages or components:

### All page execution

To add and run PHP code on every page without writing a module, you can:

* Use a `settings.php` file for that. It is only recommended for simple code such as configuration override. Otherwise you should use `hook_init` for that as part of your custom module.
* Activate *PHP text filter*, then create a block with custom PHP code in it and place the block into footer region.

---
Tags: 7
---


title: Select Entity with condition on node id

text:
# Question
Title: Select Entity with condition on node id
I am trying to select an Entity with a condition on the node id.
Here's the query I use:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'event')
    ->propertyCondition('status', NODE_PUBLISHED)
    ->fieldCondition('nid', 'value', $id, '=')
    ->range($page, 1);
$result = $query->execute();

```

I get the following error:

> EntityFieldQueryException: Unknown field: nid in EntityFieldQuery-\>addFieldCondition()

How can I resolve this issue?

# Answer
For EFQ, you need to filter on the entity condition column `entity_id` which is the node id.

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
    ->entityCondition('entity_id', $id)
    ->entityCondition('bundle', 'event')
    ->propertyCondition('status', NODE_PUBLISHED)
    ->range($page, 1);
$result = $query->execute();

```
> 4 votes

---
Tags: 7, entities
---


# Question
Title: How to determine module path in drush which is outside of Drupal root?
I've downloaded Coder (7.x-2.x) module in the following way:

```
drush -y dl coder-7.x-2.x --destination=~/.drush && drush cc drush

```

And I would like to call function (`coder_review_reviews()`) from `drush` (using `eval`) which is defined in `~/.drush/coder/coder_review/coder_review.common.inc` and I need to include that file first, but I don't know how to determine my module path.

Normally when module is within Drupal root, you can use `module_load_include()` for that, but this function is not available when you're calling `drush` outside of your core. It seems I can't use `dd` either.

How can I achieve that without hardcoding the path to the module?

# Answer
> 3 votes
In Drush, the right way to do this is to use `drush_invoke_process()` to call a Drush function in coder that calls `coder_review_reviews()` for you, and returns the result as the function result of the Drush command implementation. I did not check to see if coder does this.

If the service you need is not exported, the alternative is to call `drush_get_commandfiles()`. The result you will get is a key / value pair, where the key 'coder' has the value of the full path to the coder.drush.inc file.

When commands do not export the functionality you need, it is better to submit a patch on their project providing the access you need. Directly including .inc files and calling internal functions is fragile, and at risk of breaking in new versions of the project.

# Answer
> 0 votes
So far I have found the following workaround by using ReflectionClass, for example:

```
drush ev 'require_once dirname((new ReflectionFunction("drush_coder_review"))->getFileName()) . "/coder_review.common.inc"; print_r(array_keys(coder_review_reviews()));'

```

---
Tags: drush
---


# Question
Title: Error: Undefined index: form_build_id in ajax_get_form()
I have a custom widget form that I use on a node reference field. The form outputs a list of nodes with a pager (jQuery Infinite Scroll plugin to append next results using the pager links) which can be selected via checkboxes. The results can be filtered via ajax based on a taxonomy term selection and the old results get replaced with new ones using the ajax command `$commands[] = ajax_command_replace`. So far so good.

The issue comes after the results are filtered using ajax and the infinite scroll (jQuery plugin) tries to call the next page of results (ie: page 2). Using firebug I can see the GET request returns a 200 ok status message but no results are appended to the dom. When I check the logs I see the following errors:

```
Undefined index: form_build_id in ajax_get_form() (line 320 of /var/www/html/includes/ajax.inc).

http://mywebsite.com/system/ajax?page=2|http://mywebsite.com/create/list|5372||Invalid form POST data.

```

This is the ajax callback when filtering the form:

```
    function nodereference_selector_field_widget_form_ajax_callback(&$form, &$form_state) {
      $commands = array();
      // Replace the old results when filtering occurs.
      $commands[] = ajax_command_replace('.form-item-field-list-und', drupal_render_children($form['field_list']));

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

```

This is the widget form function:

```
 function nodereference_selector_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element, $values = array()) {
  $all_categories = array(36, 38, 40, 41, 194, 327, 1308, 1335, 1336, 1337);
  $category = nodereference_selector_get_categories();
  $category = array('all' => t('Display All')) + $category;

  $element['itemswrapper'] = array(
    '#weight' => 0,
    '#suffix' => '<div id="item-area">',
  );

  $form['selectedwrapper'] = array(
    '#weight' => -10,
    "#markup" => '<div id="selected-items"><span id="instructions">Select items from the list to create your list.</span></div>',
    );

  $form['tid'] = array(
    '#type' => 'select',
    '#options' => $category,
    '#default_value' => isset($values['tid']) ? $values['tid'] : 'all',
    '#ajax' => array(
        'callback' => 'nodereference_selector_field_widget_form_ajax_callback',
        'progress' => array('type' => 'throbber', 'message' => 'Loading...'),
        'wrapper' => 'item-area',
    ),
    '#weight' => 0,
   );
  $values = isset($form_state['values']) ? $form_state['values'] : array('tid' => NULL);
  $radios = $field['cardinality'] == 1 && $element['#required'];
  $options = array();
  foreach ($field['settings']['referenceable_types'] as $type) {
    if (is_numeric($type) || !isset($instance['widget']['settings']['image_field_' . $type])) {
      continue;
    }
    $query = db_select('node', 'n');
    $query->addTag('node_access');
    $query->join('field_data_' . $instance['widget']['settings']['image_field_' . $type], 'fd', 'fd.entity_id = n.nid');
    $query->join('taxonomy_index', 'ti', 'ti.nid = n.nid');
    $query->fields('n', array('title', 'nid'));
    $query->fields('fd', array($instance['widget']['settings']['image_field_' . $type] . '_fid'));
    $query->condition('n.type', $type, '=');
    $query->condition('fd.delta', 0, '=');
    $query->condition('n.status', 1, '=');
    $query->condition('tid', $all_categories);
    $query->orderRandom();
    nodereference_selector_filter_query($query, $values);
    $result = $query->extend('PagerDefault')->limit(20)->execute();
    foreach ($result as $node) {
      $options[$node->nid] = theme('image_style', array(
          'style_name'  => $instance['widget']['settings']['image_style'],
          'path'        => file_load($node->{$instance['widget']['settings']['image_field_' . $type] . '_fid'})->uri,
          'title'       => check_plain($node->title),
        )
      );
    }
  }

  $defaults = array();
  if (isset($form_state['build_info']['args'][0]->{$instance['field_name']}[$langcode])) {
    if (!$radios) {
      foreach ($form_state['build_info']['args'][0]->{$instance['field_name']}[$langcode] as $value) {
        $defaults[] = $value['nid'];
      }
    }
    else {
      $defaults = $form_state['build_info']['args'][0]->{$instance['field_name']}[$langcode][0]['nid'];
    }
  }
  $element += array(
    '#type'             => $radios ? 'radios' : 'checkboxes',
    '#options'          => $options,
    '#element_validate' => array('nodereference_selector_validate'),
    '#attributes'       => array(
      'class' => array('clearfix'),
    ),
    '#attached' => array(
      'js'  => array(
        drupal_get_path('module', 'nodereference_selector') . '/js/nodereference_selector.js',
      ),
      'css' => array(
        drupal_get_path('module', 'nodereference_selector') . '/css/nodereference_selector.css',
      ),
    ),
    '#default_value' => $defaults,
  );

  // Attach the pager theme
  $element['pager_pager'] = array('#theme' => 'pager');

  $element["itemswrapper"]['#prefix'] =  "</div>";

  return $element;
}

```

# Answer
This is a long standing bug (first reported on the 6th of November 2012) in Drupal 7.x and 8.x. You can find the report here. Thanks to the guys that made the userpoints module and @anthony for pointing it out I made a function to handle this issue.

```
function mymodule_parse_input($form_state, $input) {
    $values = isset($form_state['values']) ? $form_state['values'] : array_map(function() {return NULL;}, $input);
    foreach ($input as $key => $value) {
        if (isset($values[$key])) {
            $_GET[$key] = $values[$key];
        }
        else {
            if (isset($_GET[$key])) {
                $values[$key] = $_GET[$key];
            }
            else if ($value) {
                $values[$key] = $value;
            }
        }
    }

    return $values;
}

```

At the top of your form function you need to put something like:

```
if ($_GET['q'] == 'system/ajax') {
    $_GET['q'] = $form_state['#mymodule']['real_url'];
}
else {
    $form_state['#mymodule']['real_url'] = $_GET['q'];
}
$form_values = array(
  'field1' => $field1_default_value,
  'field2' => $field2_default_value,
);
$values = mymodule_parse_input($form_state, $form_values);

```

You need to fill `$form_values` with the default values for your form. These values will be passed into the `$values` variable when the form is rebuilt. Be careful though because the values are unfiltered from the `$_GET` superglobal. If you don't want any default value for a field then simply pass it as `$field1 => NULL` and it will work. You can use `$values` as if it where `$form_state['values']`. For example the value for field1 would be `$values['field1']`.
> 1 votes

# Answer
Try $form\_state\['rebuild'\] = TRUE;
> 0 votes

# Answer
You cannot send a query param to system/ajax without POST data. Without POST data, system/ajax has no idea what you're talking about.

You should be sending the param to a page callback for your form. If you don't have one, create one. This will allow you to paginate using your JQuery Infinite Scroll. However, I notice you have a select for changing the category. If you don't mind this reseting the pagination, then it should work fine.
> 0 votes

# Answer
I resolved the issue by manually parsing the pager url. Drupal has bug that messes up pager urls when using ajax (still hasn't been resolved). After an ajax callback is called the pager links will point to `system/ajax` which will return a blank page.

I added this at the end of the `hook_field_widget_form` function:

```
  // If this is an AJAX request, update $_GET['q'] so that table sorting and
  // similar links are using the correct base path.
  if ($_GET['q'] == 'system/ajax') {
    $q = url('node/add/list', array('absolute' => TRUE));
    $_GET['q'] = $q;
  }

```

And copied a function from the userpoints module to parse the url:

```
   function hook_selector_parse_input($form_state, $tid = NULL) {
  // Enforce tid if passed in through the URL.
  $values = isset($form_state['values']) ? $form_state['values'] : array('tid' => NULL);
  if (!isset($values['tid'])) {
    if (isset($_GET['tid'])) {
      $values['tid'] = $_GET['tid'];
    }
    elseif ($tid) {
      $values['tid'] = $tid;
    }
  }

  if (isset($values['tid'])) {
    // Add tid argument to GET.
    $_GET['tid'] = $values['tid'];
  }

  return $values;
}

```
> 0 votes

# Answer
If you use ajax pager with form you need

1. make menu callback in hook\_menu

```
$items['mymodule/ajax/pager'] = array(
  'page callback'  => 'list_form_updated',
  'type' => MENU_CALLBACK,
  'delivery callback' => 'ajax_deliver',
  'theme callback' => 'ajax_base_page_theme',
);

```
2. ajaxify select pager list manually

```
jQuery('#list-form nav a').once('pager').each( function(){

  var url = jQuery(this).attr('href'); url_param = url.split('?'),
  // get the form_build_id
  form_build_id = jQuery('form#list input[name="form_build_id"]').attr('value');

  Drupal.ajax['pager'] = new Drupal.ajax(false, this, {
    url : window.location.protocol + '//' + window.location.hostname + '/mymodule/nojs/pager' + (typeof url_param[1] != undefined ? '?' + url_param[1] : ''),
    event : 'click'
  });
  // form_build_id for ajax_get_form() in $_POST('form_build_id;');
  Drupal.ajax['pager'].options.data.form_build_id = form_build_id;

});

```
3. render form element and return it with ajax command

```
/**
 * Pager callback for Pager form.
 */
function list_form_updated($type = 'ajax') {
  // in this point we have right $_POST array to get the form & $_GET for pager
  list($form, $form_state, $form_id, $form_build_id, $commands) = ajax_get_form();

  $form['updated']['list']['#options'] = _list_form_ajax_get_options($form, $form_state);

  $wrapper = 'list-form';
  $output = drupal_render($form['updated']);

  $commands[] = ajax_command_replace('#' . $wrapper, $output);

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

}

```

That is. Thnx
> 0 votes

---
Tags: forms, ajax
---


# Question
Title: After D8-rc1 install, homepage work but all other links gives a "page not found"
I upgraded my **Xampp** to version **Xampp 5.6.12** since Drupal 8 need PHP to be 5.5.9 or better. I checked out a couple of my Drupal 7 website under the **htdocs dir**. They are working fine.

I installed clean drupal 8 in the same **htdoc dir** under "**newd8**" folder. I used instructions so that I don't do make any mistakes.

The installation is fine and the default homepage came up at "http://localhost/newd8" and admin login account is working.

BUT clicking on any of the admin menu items, I get "page not found" drupal error. for example, if I click on "**people**", it goes to the link "localhost/newd8/admin/people" but I get a "**page not found**" page.

If I modify the URL to include index.php, thus "localhost/newd8/index.php/admin/people", it works. I get the right page.

This seem to be for all the pages. if I manually add "**index.php**" at the appropriate place, I get the required page.

I have modified the base URL in the `setting.php` file then its css file is not loaded properly even home page layout is totally disturbed

What am I missing?

# Answer
I fixed this.. Thanks to Sumit, I read the .htaccess file more carefully.. Inside the default .htaccess file that comes with the Drupal 8 download, around line 108, comments tells what to do if d8 is installed in a sub-directory instead of document root. I modified line to "RewriteBase /newD8" and now the site works. Even though the same comment is in the D7 version too, On the same Apache server and same document root, D7 works without the modification of the line but D8 needs the change. I don't know why. Because of Symfony perhaps?
> 2 votes

---
Tags: 8, installation
---


# Question
Title: Lost Social Connection Icons after uploading custom images
I created a subtheme for Commerce Kickstart / Omega. As part of the refresh, I want to use the existing "Connect with Us" block, but replace the existing icons with customized images (theme consistent colors).

I uploaded replacement files to `sites/all/SUBTHEME/images`, using the same file name and type as in the original theme:

* icon\_facebook.png
* icon\_twitter.png

Saved / refreshed: Icons disappeared from the block. If I was uploading to the wrong directory, I feel like it would continue to show the original yellow icons, but the icons no longer show at all.

Here's the code from the css file:

```
  #block-menu-menu-social-connection .content ul.menu li span,
  #block-menu-menu-social-connection .content ul.menu li a {
    color: #eeeeee; }
  #block-menu-menu-social-connection .content ul.menu li a.facebook {
    background: url("../images/icon_facebook.png") 2% 50% no-repeat;
    /* LTR */ }
  #block-menu-menu-social-connection .content ul.menu li a.twitter {
    background: url("../images/icon_twitter.png") 2% 50% no-repeat;
    /* LTR */ }
  #block-menu-menu-social-connection .content ul.menu li a.instagram {
    background: url("../images/icon_instagram.png") 2% 50% no-repeat;
    /* LTR */ }

```

# Answer
After troubleshooting with @nosssweat, it turns out this is an issue with Adobe PS saving empty PNG files. Surprise!

To fix, I switched to 24-bit PNG and was able to save the web-optimized format correctly. All issues fixed here.
> 1 votes

---
Tags: commerce, theming, media
---


title: How to check if View is empty with PHP

text:
# Question
Title: How to check if View is empty with PHP
I'm using Simplenews Scheduler to automatically send a digest of new nodes, by inserting a views token into Body field of the newsletter.

I need to prevent sending the newsletter if the View in question is empty (triggers No results).

Simplenews Scheduler allows for PHP evaluation (see at the bottom of the screenshot):

What do I need to enter there to ensure no new newsletter is created and sent if a certain view (with certain exposed filter or contextual filters options) has no results?

# Answer
I believe this will do:

```
!empty(views_get_view_result('your_views_machine_name','your_display_id'));

```

If you need to pass arguments, you can pass them as individual strings after the display id. See the API documentation. I'm not sure if you can pass exposed filter arguments, though (the above would work fine for contextual filter arguments).
> 1 votes

---
Tags: 7, views
---


# Question
Title: Node token in rules (Events: When an order is first paid in full)
In comments there is Product reference-Inline entity form-Single value, so when a product is posted in comments, it can be bought by somebody.

Is it possible to have a node token in Conditions or Actions in rules when in Events 'When an order is first paid in full' is used? For example, it would be nice to have a node token in Conditions-'Entity has field' and in Actions-'Set a data value'.

# Answer
You can have a node token for that action, but you must load one manually using **Fetch entity by id**.
> 0 votes

---
Tags: nodes, rules, entities
---


# Question
Title: Render image field from node in page.html.twig
I make my first steps with Drupal 8. I have a site with a header image. On a specific content type "Blog" I want to replace the standard header image with a node specific header image. So in the content type "Blog" i made a image field "field\_headerimage". I also made it possible to make a content type specific page.html.twig, see https://drupal.stackexchange.com/a/141397/31981. This works.

**Problem:** I want to render field\_headerimage in page.html.twig. There is a "node" variable, but it seems like this values aren't able to render.

# Answer
I would say that the Twig-ish way is to create a custom filter. The Drupal-ish way is to use a hook\_preprocessor. The general idea of the MVC rewrite is to keep logic out of the templates. I couldn't see how to add Twig filters in Drupal 8 (anyone?) so I'll go with preprocessor.

**Drupal 8 preprocessor**

In your theme's *template.php*:

```
function mytheme_preprocess_page(&$variables) {
  if ( $variables['node'] ) {
    $node = $variables['node'];
    // Optionally limit by bundle type. How do you get a bundle in D8?
    // if ( $bundle != 'blog' ) return;
    // Get your image URI.
    $header_image = $node->get('headerimage')->value;
    // Just guessing here: not sure what to do but it may involve styles.
    $header_uri = $header_image->getFileUri();
    // Override the variable that normally stores the header image.
    // Not sure what that would be. Look in page.html.twig
    $variables['headerimage'] = $header_uri;
  }
}

```
> 5 votes

---
Tags: 8, media, theming
---


# Question
Title: Hide Fieldset in an Ajax Callback Function
I have this code below:

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

    $form = array();

    $form['create_template'] = array(
        '#type' => 'button',
        '#value' => 'Create New ID Template',
        '#ajax' => array(
            'callback' => 'myid_create_template',
        ),
    );

    $form['myid_templates_editor'] = array(
        '#type' => 'fieldset',
        '#title' => t('Design your ID Template'),
        '#access' => FALSE,
    );

    return $form;
}

```

How will I show `$form['myid_templates_editor']`, when callback function `myid_create_template` is invoke?

```
//Callback function invoke by "$forms['create_template']" in myid_templates_form
function myid_create_template($form, &$form_state){
    $form['myid_templates_editor'] = array(
        '#access' => TRUE,
    );
}

```

Above code is not working.

**UPDATE:**

I changed `myid_create_template` from the above code to the code below, but nothing's changed. The field set still doesn't show.

```
//Callback function invoke by "$forms['create_template']" in myid_templates_form
function myid_create_template($form, &$form_state){

    $form['myid_templates_editor'] = array(
        '#type' => 'fieldset',
        '#title' => t('Design your ID Template'),
        '#access' => TRUE,
    );
    return $form['myid_templates_editor'];
}

```

# Answer
> 1 votes
Below is the code that has worked for me.

I used ajax wrapper to refer to form wrapper to mention what to be replaced on ajax callback.

From ajax callback the wrapper has to be replaced with right content, which is the whole form in my case. so returned form from ajax callback function.

One more thing to note is, I had to change #access to TRUE for all child elements of field set. Just changing the field set's access didn't display child elements for me.

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

$form['test_text'] = array(
    '#type' => 'textfield',
    '#title' => 'Test text field',
  );

  $form['test_fieldset'] = array(
    '#type' => 'fieldset',
    '#title' => t('Design your ID Template'),
    '#access' => FALSE,
  );
  $form['test_fieldset']['test_text2'] = array(
    '#type' => 'textfield',
    '#title' => t('Text 2'),
  );
  $form['test_btn'] = array(
    '#type' => 'button',
    '#value' => 'Create New ID Template',
    '#ajax' => array(
      'callback' => 'test_ajax_callback',
      'wrapper' => 'test_form_wrapper',
    ),
  );
  $form['#prefix'] = '<div id=test_form_wrapper>';
  $form['#suffix'] = '</div>';
  return $form;
}

function test_ajax_callback($form, &$form_state) {
  $form['test_fieldset']['#access'] = TRUE;
  foreach (element_children($form['test_fieldset']) as $child) {
    $form['test_fieldset'][$child]['#access'] = TRUE;
  }
  return $form;
}

```

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


# Question
Title: Fetch values from Field Collection or Multifield on Node to Entityform
I am working on a booking system where I have a content type of "Company" with an unlimited Field Collection of "Services". The "Services" field collection has 2 fields: "Service Name" and "Price".

I want users to be able to book any of the Services using an Entityform I have created, so that the Node Title, Service Name and Price fields be loaded automatically on the Entityform during submission.

I have tried using tokens and the Prepolutate module by passing the field values in the URL but I can't seem to pass the values from the Services field collection because field collections are entities on their own, and also this is not very secure as the price can easily be manipulated/changed in the URL.

How should I go about this? Or is there a module that load an Entityform from the URL for example http://www.example.com/company/nid/book, with values of fields and fields collection from the node. Every suggestion will be appreciated.

# Answer
Entity Form project page says that **Entity Form** supports Entity reference and Prepopulate Modules.

My suggestion is try with Entity reference autofill and Entityreference prepopulate Modules. Please make a try.

1. Add an entity reference field in your entityform.
2. The entity reference autofill will automatically fill reference value into field. We can load default value from URL. (`?field_name = value`)
3. Entityreference prepopulate will prepopulate the values. (you have to add existing fields for that.)

For more details please refer project page.

Another approach is,

> If you want to do this by coding, Just pass **nid** through url and use node\_load() to load that node and create an entity form submission. If you want to create entity form with node creation use hook\_node\_insert or hook\_node\_presave.

Hope this will help you.
> 2 votes

# Answer
The best way to do this is hook\_form\_FORM\_ID\_alter().

Modules can implement hook\_form\_FORM\_ID\_alter() to modify elements and values in the form before it is rendered. You'll have to look quite deep into the form array but it should be possible to set the #default\_value for the required elements.
> 1 votes

---
Tags: entities
---


# Question
Title: How to display a custom block as a pop on home page?
I have a custom block created, it contains 3 links in it. Now I want to display that block as a popup on home page. I looked at the Popup module but it didn't work.

# Answer
> 1 votes
Sounds like you are looking for the functionality of a Splash screen?

If so why don't you have a look at the Splashify module. It gives you quite a lot of options right out of the box.

If you are using Drupal 6; the Splash module might be a better bet.

# Answer
> 2 votes
There are other modules which provide you the popup functionality.

1. Popup message

> Display popup message for users once per browser session. Based on javascript code: http://yensdesign.com/2008/09/how-to-create-a-stunning-and-smooth-popup-...

2. Lightbox2

> The Lightbox2 module is a simple, unobtrusive script used to overlay images on the current page. It's a snap to setup and works on most modern browsers.

3. Shadowbox

> Shadowbox is a JavaScript modal media viewer application for viewing images, video, Flash and other content in a modal window.

---
Tags: blocks, javascript
---


# Question
Title: Can't use Google Analytics Statistics Module - Impossible to login
I'm trying to use Google Analytics Statistics module but it won't accept my login credentials. I know they're correct because I tried them independently multiple times on the same browser to login to Google directly. I've also now try entering them 10's of times in the module and it never takes them. It takes my username but then rejects my password and gives the error 'Invalid Google Analytics login.'

I thought I found the solution, here, and it seemed to work for everyone else, but not for me. https://www.drupal.org/node/1370742

I did the patch - didn't help. I ran cron and clear caches a million times. I re-installed the module. I made sure I was logging in from the same browser where I was already logged into Google.

Note: Google never sent me an email, not once, asking me to confirm my login as the referenced article above suggests it would do.

# Answer
> 1 votes
Turns out this module is no longer supported and it appears many others also have problems authenticating with it. I recommend NOT using it. I also tried Google Analytics Statistics Counter module, and while I was able to get it setup it wasn't as intuitive as I'd hoped so I just used the 'Statistics' core module, even if it's not the 'preferred' choice performance-wise. For now it will do.

---
Tags: google-analytics
---


# Question
Title: Why are some menus created for authenticated users not displaying?
Whatever menus created for authenticated user, some menus are displaying and some created menus are not displaying.

If I login as admin, it shows all created menus and its child menus.

Why is this?

# Answer
Some of the links are not visible to authenticated user, because the **URL** you provided to respective menu links are not accessible to authenticated user.

**Example**: Suppose menu link is **Add Article** and URL is **/node/add/article**. So here if authenticated user not having Article node add permission, then in such case **Add Article** will not be visible to that user.
> 1 votes

---
Tags: routes, navigation
---


title: Form with Ajax and without

text:
# Question
Title: Form with Ajax and without
I am constructing a form that is handled via Ajax. I need it to be avaible on browser where javascript isn't activated. For now, the submit part is like :

```
$form ['submit'] = array (
  '#type' => 'button' ,
  '#ajax' => array (
      'callback' => 'MODULE_form_ajax_callback',
      'wrapper' => 'result-div'
  ),
  '#value' => t ( 'Launch' ),
  '#weight' => 10000
);

```

Has anyone resolved a similar issue ?

Thanks,

# Answer
> 1 votes
try to change `'#type' => 'button'` to `'#type' =>'submit'` and then implement `hook_form_submit()`

# Answer
> 1 votes
Drupal delivers the submit elements with "nojs" and the submit works without ajax. If jquery is available, the first thing ajax does, is to replace the "nojs" with "ajax" to activate itself:

```
ajax.js:
Drupal.ajax = function (base, element, element_settings) {
  var defaults = {
    url: 'system/ajax',
    event: 'mousedown',
    keypress: true,
    selector: '#' + base,
    effect: 'none',
    speed: 'none',
    method: 'replaceWith',
    progress: {
      type: 'throbber',
      message: Drupal.t('Please wait...')
    },
    submit: {
      'js': true
    }
  };

  $.extend(this, defaults, element_settings);

  this.element = element;
  this.element_settings = element_settings;

  // Replacing 'nojs' with 'ajax' in the URL allows for an easy method to let
  // the server detect when it needs to degrade gracefully.
  // There are five scenarios to check for:
  // 1. /nojs/
  // 2. /nojs$ - The end of a URL string.
  // 3. /nojs? - Followed by a query (with clean URLs enabled).
  //      E.g.: path/nojs?destination=foobar
  // 4. /nojs& - Followed by a query (without clean URLs enabled).
  //      E.g.: ?q=path/nojs&destination=foobar
  // 5. /nojs# - Followed by a fragment.
  //      E.g.: path/nojs#myfragment
  this.url = element_settings.url.replace(/\/nojs(\/|$|\?|&|#)/g, '/ajax$1');
  this.wrapper = '#' + element_settings.wrapper;

```

So ajax in drupal works like you want out of the box.

---
Tags: ajax, forms
---


# Question
Title: Rules scheduler and views- how to show normal users the schedule?
I am using Rules Scheduler and Flag to handle troublesome users by issuing a one-week ban. I flag the user with a **temporary ban** flag, and then the user sees a special block that says "You have been temporarily banned for being a jerk." I have a rule that automatically schedules the user to be unflagged one week later.

However, I want to show users how much time they have remaining. My first thought was to create a block/content pane in Views, so I made a view of type **Rules scheduler**, but when I went to add the **UID** as a *Contextual Filter*, I realized that **Rules scheduler** views only provide these options:

* Null
* Component name

Is there some other way I can show the user how much time they have until an arbitrary Rules Scheduler action will be evaluated?

**What I tried**

Based on this question, I added a filter for **user-provided identifier**, set the value to a garbage value (*punishme*), and added `views_pre_view()` as follows:

```
function MYMODULE_views_pre_view(&$view) {
  global $user;
  if ($view->name == 'punishment_show_details') {
    if ($user->uid) {
      $newvalue = 'punish/' . $user->uid;
      $view->display[$view->current_display]->handler->options['filters']['rules_scheduler']['value'] = 'punish/' . $user->uid;
    }
  }
}

```

However, this doesn't work; for some reason, when I `dpm()` the view, the value for `filters` is empty.

# Answer
I solved this by creating a view with a filter of **user-provided identifier**, setting the default value to "changeme," and then adding the following code to a custom module to provide the correct identifier (to match the identifiers used to schedule my rules):

```
function MYMODULE_views_pre_view(&$view) {
  global $user;
  if ($view->name == 'punishment_show_details') {
    if ($user->uid) {
      $newvalue = 'punish/' . $user->uid;
      $view->display[$view->current_display]->handler->options['filters']['identifier']['value'] = 'punish/' . $user->uid;
    }
  }
}

```
> 0 votes

# Answer
Why not add a user profile field that stores the ban removal date? Then you could use the "Time ago" formatter with the "Time hence" setting and then just set or unset it using the rule (and it's associated de-ban rule). You can show that field using Views and/or on the user's profile page. Or panels. Or custom code... etc.
> 0 votes

---
Tags: views, rules
---


# Question
Title: Use multiple data blocks in the same chart created using forena reports
I have created a chart using Forena reports. I need to set the chart title dynamically based on the logged in user's country. At present I have hard coded the title as "Your Country". The data for this chart is coming from a data block (let's say data\_block\_1). And the logged in user's country can be obtained from a second data block(data\_block\_2).

How can I show the logged in user's country as the chart tile?

Though I have the second data block I don't know where to put the name or how to call that data block.

I am posting the screenshot of the body tag inside the frx file and also the chart I created thus and also the sql file.

# Answer
# Using data contexts

This question is a (great) example of using "**Data contexts**" in Forena. To see an example of a "data context" at work (in a demo site), refer to the example about Master Summary with drill down. If in the report you click any of the linked columns (such as for state = VA), you'll get the Users in state Virginia report. In that report you should note these things:

* ... in state **Virginia** (in the report title).
* ... state with code = **VA** (near the top of the report).

If in the above example you pick another state, such as **IL** (Illinois), you'll get the report specific to that state.

Read more about "Data Contexts" in the Forena documentation, which you can also find in your own site within `/reports/help.reportingfrx#datacontexts` (after you installed Forena).

Below are some details about what's needed in this specific case (to use the user's country as your chart tile), based on these assumptions:

* The user's country is contained in stored in a datablock named (say) "**pec\_reports/data\_block2**", within a column (say) "**UserCountry**".
* The user's country is (say) "**XYZ**".
* You want your chart title to be like (say) "**Chart for country XYZ**".

Based on these assumptions, this is what you should do:

1. Add a data context to the document in the section of the document, which are preloaded before the report is rendered. The example below illustrates the syntax for preloading data in the head section:

> ```
> <head>
>   ..
>   <frx:data id="countryinfo" block="pec_reports/data_block2"/>
> </head>
>
> ```
2. Any data from any other section of a report may be used by referencing the datablock by its id and appropriate column name of that datablock. The example below contains an example of referencing the `UserCountry` column contained in `pec_reports/data_block2`:

> ```
> <div> ... {countryinfo.UserCountry} ... </div>
>
> ```

The syntax for such reference is like so:

* "**Id**" of the datablock, followed by a "**.**", and followed by the "**ColumnName**".
    * Preceeded by a "**{**" and followed by "**}**".
3. Same is true for any of the tags used to specify the details of the chart you want to create. So in this case you could use something like so:

> ```
> frx:graph_title="{countryinfo.UserCountry}"
>
> ```

# Ensure your SQL returns the correct value(s)

If you get a blank chart title after applying the changes as I suggested above, then *most probably* that is because the value of that chart title is blank. Looking at the SQL statement for your `pec_reports/data_block2`, here are a few tips to further verify (debug?) the actual SQL statement you're using:

1. Create a temporary (for debugging purposes only) tabular report using that same `pec_reports/data_block2` data block, and run that report while logged in. Or as a variation, add that tabular report in your report with the chart, but in front of that chart. Do you get the expected "country" value for that user? I wouldn't be surprised if you get an empty output (which would confirm something is wrong in your SQL statement, and hence also explain your blank chart title). In that case continue with step "2." and/or "3." below.
2. In your **from** clause, change `users` to `{users}`, and rerun your temporary report in step 1.
3. In your **where** clause, change `current_user` to the value of the `uid` of your own user, and rerun your temporary report in step 1.

If none of the above seems to help, then I would use either (or both) of these other routes:

* Have a look at the data blocks (SQL statements) related to the ***Drupal Administration*** reports that are delivered with Forena also, such as:

+ Active Users
    + Logs for User
    + Role Details
* Use the query writing tool that comes with Forena, which is called the **Forena Query Builder**. This is a separated module that comes with Forena. It can be enabled as per standard Drupal instructions to enable an additional module. For a video tutorial about this query writing tool, checkout Define data blocks with optional filters.
> 0 votes

---
Tags: charts, forena
---


# Question
Title: Providing translations for custom modules
I'ld like to provide module specific translations for my custom modules. I followed the instructions in https://api.drupal.org/api/drupal/core!modules!locale!locale.api.php/group/interface\_translation\_properties/8.

But if I install the module no translations get imported. I've searched a lot for examples on the net, but it seems as no one else used it until now.

## Here's my module "custom\_module"

custom\_module.info.yml:

```
name: 'Custom module'
version: '8.x-1.0'
core: 8.x
project: 'custom_module'
datestamp: 1434014760
interface translation project: custom_module
interface translation server pattern: modules/custom/custom_module/custom_module-%version-%language.po

```

and a "custom\_module-8.x-1.0.de.po"-file with some messages in the module folder.

# Answer
I had a similar problem that it didn't work but it turned out that my problem was with file permissions that weren't set correctly on the PO file I was trying to import.

I debugged it as follows:

On the following url **`admin/reports/translations`** you can see where it looks and what it looks for. (handy for debugging the tokens) Expand the status information for the available language.

Every time you change your **info.yml** file don't forget to rebuild cache and trigger the translation update manually.
> 4 votes

# Answer
did you manage to get this imported?

Your server pattern and file do not match (there is a '-' instead of a '.' in front of your %language in the server pattern). That might explain why it does not import on install...

I had some issues when the custom module was already installed. Changes to the server pattern in the info.yml did not propagate, so it would not find updates to my .po files

Finally managed it by clearing some state from the key\_value table (delete from key\_value where collection = 'state' and name = 'locale.translation\_status';), clearing the cache, and then refreshing the translations.

Hope this helps,

Ewald
> 1 votes

---
Tags: 8, i18n-l10n
---


# Question
Title: Drupal views custom template array issue
I have made a view named **services** which fetches the fields of content type **services**, fields name : services\_text and services\_image. I have made a custom tpl named *views-view--services.tpl.php* with my own structure and want to access fields like `$row['services_text']` in for each, but it comes out as undefined index, as i can figure it out, by using `var_dump`, that this tpl is not getting any row rather plain html string for output so I even tried with views-view-unformatted.tpl.php, but still no use.

Kindly help.

# Answer
> 1 votes
Use views-view-fields--.tpl.php and render the field with your custom markup

For example:

```
<div class="product-item">
    <div class="row clearfix">
      <div class="product-image"><?php print $fields['field_images']->content; ?></div>
    </div>
    <div class="row clearfix text-center">
      <div class="product-attributes"><?php print $fields['title']->content; ?></div>
    </div>
    <div class="row clearfix text-center">
      <div class="product-attributes"><?php print $fields['title_1']->content; ?></div>
    </div>
    <div class="row clearfix  text-center">
      <div class="product-attributes price"><?php print $fields['another_field']->content; ?></div>
    </div>
</div>

```

---
Tags: views
---


title: AJAX post on node edit page

text:
# Question
Title: AJAX post on node edit page
I am trying to perform an AJAX post on node edit pages in a new module I created Proofread Bot. This module adds a button and clicking it performs an AJAX post to a URL for processing text. When I do this on node edit, it seems the whole page gets submitted. I tried adding an `event.preventdefault` call, but also returning `false` for the button doesn't work. Let me add the same code works like magic on node view. Here is the code:

```
function proofread_bot_node_prepare($node)  {

drupal_add_js('
    jQuery(document).ready(function(){
    jQuery("#edit-body").before(\'<div id="proofread_bot-button-holder"><button type="button"  id="proofread_bot-submit" onclick="return false;">Check with Proofread Bot</button></div>\');
    jQuery("#proofread_bot-submit").click(function(event){
      event.preventDefault();
      jQuery.ajax({
         type: "POST",
         url: "proofread_bot/check",
         dataType: "html",
         data: {"text": jQuery("#edit-' . variable_get('proofread_bot_field') . '").html()
          },
         success: function(proofread_result){
            jQuery("#proofread_bot-submit").after(proofread_result);
         }
        });
      });
    });
    ', 'inline');

}

```

# Answer
> 1 votes
The Drupal Ajax call is not affected by event.preventDefault in the above code, as neither the Click() or on('click') Jquery function gets executed on Drupal Ajax call. Please refer the link below

Jquery gobal ajax events

In the above code the ajaxSend() function can be used to stop the Ajax call even before getting started. And use event.preventDefault in the function to stop the Drupal Ajax Call before getting executed.

For Example:

`$( document ).ajaxSend(function() {
 event.preventDefault();
//add you code here.
});`

Please check if this code will work in the function your calling, i am not sure (may work) or else call this code directly in you attached JS file.

# Answer
> 0 votes
Try changing the button to an anchor.

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


title: Drupal Default Language Fallback

text:
# Question
Title: Drupal Default Language Fallback
I have a multilingual website in Drupal 7. It has a menu bar with 10 menu items. Among them I have translated 5 menu items to Dutch. When I switch the language from English to Dutch, only the translated menu items appear. I would like to display those 5 menu items in Dutch as well as those items which are not translated in default English Language.

Could someone propose me a solution or a module to implement the same.

Most solutions are for individual content or entire Menu and not for individual menu items.

Thanks in advance for the help rendered :D

# Answer
> 0 votes
Multilingual menu's are quite nasty sometimes. I suppose you use i18n menu? Then have a look at the following:

Make sure the `Menu link enabled only for the [LANGUAGE] language`, on the menu tab of the node edit page is disabled. That makes sure the entry is shown on all pages.

Also make sure the menu entry is language neutral by going to admin \> structure \> menu's \> \[MENU NAME\] \> \[MENU ITEM\] and check the language drop-down.

---
Tags: i18n-l10n
---


title: Required fields in form not validated

text:
# Question
Title: Required fields in form not validated
I am currently constructing a form using an Ajax handler. The problem is that since i used Ajax, the submitting part is run without returning any error message. It is only when I clear the cache that all the errors appear (and the form disappear).

```
function My_Modile_form($form, $form_state, $arg){
     //constructing the form with REQUIREDfields
  $form ['submit'] = array (
      '#type' => 'submit',
      '#ajax' => array (
          'callback' => 'mymodule_form_ajax_callback',
          'wrapper' => 'result-div'
      ),
      '#value' => t ( 'Lancer la simulation' ),
      '#weight' => 10000
  );
}

function My_Module_form_validate($form_id, $form) {

  $form_numbers = array (
      'field_one',
      'field_two'
  );
  foreach ( $form_numbers as $form_number ) {
    $numb = $form ['input'] [$form_number];
    if (! is_numeric ( $numb )) {
      form_set_error ( $form ['complete form'] [$form_number] ['#title'], 'ERROR !' );
    }
  }
}

function mymodule_form_ajax_callback($form, $form_state) {
  $form ['simul_message_retour'] += mymodule_form_submit ( $form, $form_state );
  return $form ['simul_message_retour'];
}

function mymodule_form_submit($form, $form_state) {
    // Submitting part
}

```

Has anyone met this issue before with Ajax forms ?

Thank you,

EDIT: I just found that the hook\_form\_submit is called BEFORE the hook\_form\_validate

# Answer
Here you have the framework for Form-handling:

```
function customregister_custom_form($form, &$form_state){
  $form['first_name'] = array(
    '#title' => t('Vorname'),
    '#type' => 'textfield',
    '#default_value' => '0',
    '#required' => TRUE
  );
  $form['last_name'] = array(
    '#title' => t('Name'),
    '#type' => 'textfield',
    '#default_value' => '',
    '#required' => TRUE
  );
  $form ['submit'] = array (
    '#type' => 'submit',
    '#ajax' => array (
    'callback' => 'customregister_custom_form_callback',
      'wrapper' => 'customregister-custom-form'
    ),
    '#value' => t ( 'Lancer la simulation' ),
    '#weight' => 10000
  );
  return $form;
}

function customregister_custom_form_validate($form, &$form_state) {

  if (! is_numeric ( $form_state['values']['first_name'] )) {
    form_set_error ( 'first_name', 'ERROR !' );
  }
  if (! is_numeric ( $form_state['values']['last_name'] )) {
    form_set_error ( 'last_name', 'ERROR !' );
  }
}

function customregister_custom_form_callback($form, &$form_state) {
  drupal_set_message('custom_form_callback');
  //customregister_custom_form_submit($form, $form_state);
  $formular = drupal_get_form('customregister_custom_form');
  $formular = render($formular);
  return $formular;
}

function customregister_custom_form_submit($form, &$form_state) {
  drupal_set_message('custom_form_submit');
}

```
> 1 votes

# Answer
Try this:

```
function my_module_form($form, &$form_state) {
  $form['#prefix'] = '<div id="my_module_form_wrapper" class="wrapper-for-form">';
  $form['#suffix'] = '</div>';
  $form['other_elements'] = array(
      //code...
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#weight' => 5,
    '#value' => t('Submit'),
    '#validate' => array('my_module_form_validate'),
    '#ajax' => array(
      'callback' => 'my_module_form_submit',
      'wrapper' => 'my_module_form_wrapper',
      'method' => 'replace',
      'effect' => 'fade',
    ),
  );
}

function my_module_form_validate($form, &$form_state) {
  //Your validation logic
  $form_numbers = array(
    'field_one',
    'field_two'
  );
  foreach ($form_numbers as $form_number) {
    $numb = $form ['input'] [$form_number];
    if (!is_numeric($numb)) {
      form_set_error($form ['complete form'] [$form_number] ['#title'], 'ERROR !');
    }
  }
}

function my_module_form_submit($form, &$form_state) {
  drupal_validate_form('my_module_form', $form, $form_state);
  if (form_get_errors()) {
    $form_state['rebuild'] = TRUE;
    $form['your_elements']['#value'] = $form_state['input']['elements'];
    return $form;
  }
  else {
    // continue with your submit logic.
  }
}

```
> 1 votes

---
Tags: ajax, forms
---


title: Commerce shipping by weight and country

text:
# Question
Title: Commerce shipping by weight and country
I'm having trouble finding a solution for combining location & weight-based shipping with drupal commerce.

I need to have three shipping zones (DK, EU, ROW) with individually priced weight steps inside each zone (0-500g, 500-1000g, 1000-2000g, 2000-5000g).

I've gone through a bunch of tutorials and looked at other forums where people have similar requests. But haven't found a solution yet - which should be possible for such a 'simple' problem, right?

To sum up I need advice on how to configure the following shipping calculation rules:

* Free Shipping (no weight)
* DK Shipping (1-500g)
* DK Shipping (501-1000g)
* DK Shipping (1001-2000g)
* DK Shipping (2000-5000g)
* EU Shipping (1-500g)
* EU Shipping (501-1000g)
* EU Shipping (1001-2000g)
* EU Shipping (2000-5000g)
* ROW Shipping (1-500g)
* ROW Shipping (501-1000g)
* ROW Shipping (1001-2000g)
* ROW Shipping (2000-5000g)

I can't figure out how to check for a line item's weight in a rule?

I've got Shipping, Flat Rate, Physical Product, Physical Fields and Rules Extra enabled.

# Answer
> 3 votes
I ended up doing 12 rules as @nvahalik suggested. Here's an export of one of them. Doing the others is just a matter of cloning this rule and changing weight, territories and shipping price accordingly

```
{ "rules_dk_shipping_1_499g" : {
    "LABEL" : "DK shipping (1-499g)",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Commerce Checkout", "Commerce Payment" ],
    "REQUIRES" : [
      "rules",
      "commerce_physical",
      "commerce_order",
      "commerce_line_item",
      "commerce_shipping"
    ],
    "ON" : { "commerce_shipping_calculate_rate" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "commerce-line-item:type" ], "value" : "shipping" } },
      { "data_is" : {
          "data" : [ "commerce-line-item:commerce-shipping-service" ],
          "value" : "by_weight"
        }
      },
      { "entity_has_field" : {
          "entity" : [ "commerce-line-item:order" ],
          "field" : "commerce_customer_shipping"
        }
      },
      { "commerce_physical_rules_order_weight_comparison" : {
          "commerce_order" : [ "commerce-line-item:order" ],
          "operator" : "\u003E=",
          "value" : "1",
          "unit" : "g"
        }
      },
      { "commerce_physical_rules_order_weight_comparison" : {
          "commerce_order" : [ "commerce-line-item:order" ],
          "operator" : "\u003C",
          "value" : "500",
          "unit" : "g"
        }
      },
      { "commerce_order_compare_address" : {
          "commerce_order" : [ "commerce-line-item:order" ],
          "address_field" : "commerce_customer_shipping|commerce_customer_address",
          "address_component" : "country",
          "operator" : "is one of",
          "value" : "DK"
        }
      }
    ],
    "DO" : [
      { "commerce_line_item_unit_price_amount" : {
          "commerce_line_item" : [ "commerce_line_item" ],
          "amount" : "3300",
          "component_name" : "shipping",
          "round_mode" : "0"
        }
      }
    ]
  }
}

```

# Answer
> 1 votes
This would be doable with 12 individual rules (3 countries x 4 sizes = 12 rules). You can also try this module: Commerce shipping Province weight.

Shipping is one of the few areas where Commerce tends towards more customized solutions. But perhaps that one will help you.

---
Tags: commerce
---


title: Move file storage to another server

text:
# Question
Title: Move file storage to another server
Consider this:

* I have one fast server with a Drupal installation but this server does not have access to a lot of disk space.
* I have another server that isn't quite as fast but does have access to lot of disk space.

My drupal server is hosting a blog and some photo galleries. I would like my drupal server to use the file server to store its images and files.

How can I achieve such a thing? The file server can be accessed through ftp or sftp.

I'm considering using the storage api for this, it seems like a good fit (?) but I'm not sure how to implement it. The documentation seems a bit off.

Also, the blog uses the wysiwyg module + the media module to allow for image uploads in the body field. How can I make this functionality work with the storage api?

Is there anyone with experience in this field that can help me out?

# Answer
> 7 votes
If all you're looking to do is offload your Files directory to a different server, and you have complete access to both servers, I would suggest you create an NFS (network drive) mapping to the storage server.

Then you can simply change your Public/Private files directory to /mynfs/drupal-files instead of /drupal/sites/default/files, which will pretty transparently offload storage to your other server.

You'll want to do some research into NFS and its alternatives that do the same thing. I'm not familiar enough with the Storage API to know if it will work in your situation. After researching it a little bit it seemed like you would have to do a decent amount of work as well.

# Answer
> 4 votes
If you're using D7 I'm pretty sure you can write your own file stream wrapper to achieve this too http://drupal.org/node/560424. More work than just setting your file system up differently but thought you might like to know that it exists.

The obvious problem is that transferring every image from one server to the other through FTP as you need them will be really slow if your servers aren't in the same room.. Even imagecache won't help you there as the "cached" images are stored in the public files directory.

# Answer
> 1 votes
One of the simplest ways to do this is to set up an S3 bucket as your CDN. Make sure you have enabled curl (sudo apt-get install php5-curl) and then install:

**Library:** awssdk **Modules:** libraries amazons3 awssdk

The visit the documentation page for amazons3 at https://www.drupal.org/node/1371166

---
Tags: media, files
---


title: Anchor Tag Smooth Transition

text:
# Question
Title: Anchor Tag Smooth Transition
Right now my menu item will scroll to my anchor tag **\< front \>#tag1,** without a problem. However I do not like how "jumpy" it is. I would like a smoother scroll affect?

I found this module: https://www.drupal.org/project/scroll\_to\_destination\_anchors .

I have jquery and javascript enabled, but I can't seem to get a smoother affect. Any Help? I am using Drupal 7 core.

# Answer
Take a look at https://www.drupal.org/node/2492033 and check if your links to anchors are with or without a path. You could maybe use Void Menu to make special links without path.

As an alternative to this module I recommend to take a look at: Jquery Localscroll
> 1 votes

---
Tags: javascript
---


title: How can I render an entity in a string?

text:
# Question
Title: How can I render an entity in a string?
Is it possible? To use the viewBuilder of an entity to generate the complete html and save that output into a string instead of sending it to a browser.

It would open the possibility to have email messages render using twig templates.

I have been poking around the different services and using the renderer service I can render the page-specific output as html but I can't find a way to get the complete HTML code into a string.

Matt.

# Answer
Your question is "render a drupal 8 entity in a string". This is an example how to do this. Get an entity. Get a view builder for the entity node and us it to build your render array with the display mode "full". Render this with renderRoot to the string $html.

```
$node = \Drupal::entityManager()->getStorage('node')->load($nodeid);
$view_builder = \Drupal::entityManager()->getViewBuilder('node');
$renderarray = $view_builder->view($node, 'full');
$html = \Drupal::service('renderer')->renderPlain($renderarray);

```

You can do this for any entity. By default this will use the node.html.twig as configured in your theme. But you can change your render array before rendering.

Edit: For emails use renderPlain().
> 7 votes

---
Tags: 8, emails, theming
---


# Question
Title: In which cases should I not call user_access() in a form submission handler?
Reading the code for `user_register_form()`, I see the following comment:

> Pass access information to the submit handler. Running an access check inside the submit function interferes with form processing and breaks `hook_form_alter()`.

The code right after that comment is the following, where `$admin` is set to `user_access('administer users')`.

```
  $form['administer_users'] = array(
    '#type' => 'value',
    '#value' => $admin,
  );

```

Looking at `comment_form_submit()`, I notice that `user_access()` is being used.

```
  if (user_access('post comments') && (user_access('administer comments') || $node->comment == COMMENT_NODE_OPEN)) {
    // Save the anonymous user information to a cookie for reuse.
    if (user_is_anonymous()) {
      user_cookie_save(array_intersect_key($form_state['values'], array_flip(array('name', 'mail', 'homepage'))));
    }

    // …
  }

```

Is there any difference between the first case, and the last one? If there isn't any difference, what approach should I use in my code?

# Answer
> 1 votes
I did a little detective work to find when that `user_register_form()` code was committed and then traced the corresponding issue.

From comment #21 there:

> The problem is that you can't form\_alter out the admin behavior without rewriting the submit handler from scratch.

So I guess the approach you use just depends on whether you want to allow your access checks to be altered by other modules without them having to override your submit handler.

---
Tags: 7, forms
---


title: SQL Query to get all Products?

text:
# Question
Title: SQL Query to get all Products?
I have been given a broken site and a database that was formerly running Drupal commerce via Commerce kickstart. The site was hacked when Drupalgeddon happened, and I can't get the code to update (lots of missing component errors).

So I think we need to start over from scratch here, and I would like to know what the SQL query might be to get all of the product data out of the database? Is this something that can be done directly in SQL?

# Answer
Use entity field query and field api.

Something like this should be pretty easy to recover your products

```
$query=new EntityFieldQuery;
$query= $query->entityCondition('entity_type','commerce_product')->execute();

```

Thanks!
> 0 votes

# Answer
There isn't an easy solution for this since the field data is stored in multiple tables and is based on configuration which is also stored in the DB.

You're better off trying to use Registry Rebuild and Commerce Repair to get the site working and then using export tools to get the data.
> 1 votes

---
Tags: commerce
---


# Question
Title: Adding comments to a node via drush or commandline
I'm trying to set up a server documentation system using drupal 7. Each server would have it's own page/ node. Updates or changes made to the system would be noted as comments on the servers page. What I'm looking to do is to be able to add a comment via drush or some other command line tool so that I can create an alias on each server to add a comment to that servers page. I'm not a programmer so any help would be appreciated.

# Answer
Expanding on Shawn Conn's answer, below is a Drush command that adds a comment to a Drupal 7 node.

Usage:

```
drush add-comment --uid=1 --subject='A comment' 'This is my awesome comment.'

```

Save the script below as `add_comment.drush.inc`, and place it in your `$HOME/.drush` directory.

```
<?php

/**
 * Implements hook_drush_command().
 */
function add_comment_drush_command() {
  $items = array();

  $items['add-comment'] = array(
    'description' => "Add a comment to a node.",
    // Describe the arguments for this command.  Delete
    // this seciton if command takes no arguments.
    'arguments' => array(
      'comment' => 'The comment to add.',
    ),
    // List all options used for this command. Only options that
    // are listed here (or that are global Drush options) may
    // be specified on the commnadline; all others raise an error.
    'options' => array(
      'nid' => array(
        'description' => 'The node id to add the comment to.',
        'example-value' => '3',
      ),
      'subject' => 'The comment subject. Defaults to empty.',
      'uid' => 'The user id of the user to post the comment as. Defaults to anonymous.',
    ),
    // Give one or more example commandline usages for this command
    'examples' => array(
      'drush add-comment --nid=123 "This is my great comment."' => 'Do something.',
    ),
    'aliases' => array('addc'),
  );

  return $items;
}

/**
 * Implements hook_drush_help().
 *
 * @param
 *   A string with the help section (prepend with 'drush:')
 *
 * @return
 *   A string with the help text for your command.
 */
function add_comment_drush_help($section) {
  switch ($section) {
    case 'drush:add-comment':
      return dt("Brief help for Drush command add-comment.");
    // The 'title' meta item is used to name a group of
    // commands in `drush help`.  If a title is not defined,
    // the default is "All commands in ___", with the
    // specific name of the commandfile (e.g. add-comment).
    // Command files with less than four commands will
    // be placed in the "Other commands" section, _unless_
    // they define a title.  It is therefore preferable
    // to not define a title unless the file defines a lot
    // of commands.
    case 'meta:add-comment:title':
      return dt("add-comment commands");
    // The 'summary' meta item is displayed in `drush help --filter`,
    // and is used to give a general idea what the commands in this
    // command file do, and what they have in common.
    case 'meta:add-comment:summary':
      return dt("Summary of all commands in this command group.");
  }
}

/**
 * Implementation of drush_hook_COMMAND().
 *
 * Add a comment to a node.
 */
function drush_add_comment($comment) {
  $nid = drush_get_option('nid');
  $uid = drush_get_option('uid', 0);
  $subject = drush_get_option('subject', '');

  $comment = (object) array(
    'nid' => $nid,
    'cid' => 0,
    'pid' => 0,
    'uid' => $uid,
    'mail' => '',
    'is_anonymous' => ($uid == 0),
    'homepage' => '',
    'status' => COMMENT_PUBLISHED,
    'subject' => $subject,
    'language' => LANGUAGE_NONE,
    'comment_body' => array(
      LANGUAGE_NONE => array(
        0 => array (
          'value' => $comment,
          'format' => 'filtered_html'
        )
      )
    ),
  );

  comment_submit($comment);
  comment_save($comment);
}

```
> 4 votes

# Answer
There are 2 things you need to know here: how to create Drush script and how to add a Drupal comment programmatically.

* A Drush script is like a shell script that boots into the Drupal environment via Drush. Essentially, it's a PHP code script prefixed with `#!/usr/bin/env` drush or `#!/full/path/to/drush` instead of the `<?php` tag.
* Creating a comment programmatically is pretty easy in Drupal. There's an answer on StackOverflow that gives you a snippet on how to do it.

With that, you can create an executable script (e.g. `chmod +x add_comment.drush`) that can take a few arguments to comment on a node id with a specified title/body:

```
  #!/usr/bin/env drush

  //Check for valid args
  $args = drush_get_arguments();
  if(isset($args[2]) && isset($args[3]) && isset($args[4])) {
    $nid = $args[2];
    $title = $args[3];
    $body = $args[4];

    //@TODO: Any further checks

    //Create comment object and save it
    $comment = (object) array(
      'nid' => $nid,
      'cid' => 0,
      'pid' => 0,
      'uid' => 1,
      'mail' => '',
      'is_anonymous' => 0,
      'homepage' => '',
      'status' => COMMENT_PUBLISHED,
      'subject' => $title,
      'language' => LANGUAGE_NONE,
      'comment_body' => array(
        LANGUAGE_NONE => array(
          0 => array (
            'value' => $body,
            'format' => 'filtered_html'
          )
        )
      ),
    );
    comment_submit($comment);
    comment_save($comment);
  }

```

In the above example, this script named **add\_comment.drush** could be executed with the command `./add_comment.drush 100 "TITLE" "COMMENT"` to add a comment on node ID#100 with `"TITLE"` as the header and `"COMMENT"` as the comment body.
> 2 votes

---
Tags: 7, drush, comments
---


title: Alter form field from module

text:
# Question
Title: Alter form field from module
In my user profile, I have some fields I want to alter. For my regular fields I use:

`mymodule_form_alter(&$form, &$form_state, $form_id)`

That works, but inside the $form there are some fields missing. Like for example the Timezone settings and the Private Messages. So fields from another module (like Private Messages) or standard settings. How can I alter those?

I tried a custom template file for the user profile and there I have access to those fields inside the $form. But I shouldn't altern them in a template file, right? So what would be the right approach for this?

# Answer
hook alter normally works on contrib modules. I can see the reason why it has not been working is due to fact that the module needs to be altered got more priority than the altering module.

To overcome such scenario you need to manually change the priority of your custom module, this can be done by changing the value of **weight** column in **system** table.
> 0 votes

---
Tags: forms
---


# Question
Title: Creating mobile-applications (like Android applications) with Drupal?
First, sorry if the question seems a bit basic to veteran programmers here - I'm just a newbie student for JS programming and not that of a big user of smartphone applications in general, at least not yet :) . I'm also not experienced in PHP programming (have yet to actually try that) and just in my first steps to getting to know this whole world now.

I want to know if it's possible, or at least practical to create smartphone (and maybe even web) applications with Drupal, at least with Drupal 8. Please give the most basic and general detailing you can.

Thanks,

# Answer
> 1 votes
You can achieve this goal with services. Luckily Drupal 8 got services in core. All you need is to call your services from your android app. If you want to use Drupal 7 then you have to install and configure services module or restfull services.

Good luck

# Answer
> 2 votes
I would recommend to take a look at DrupalGap

Also especially regarding Drupal 8 I would recommend reading this article:

---
Tags: mobile-tools
---


# Question
Title: How to publish and unpublish content depending on the type of user?
I have a site with content for two different user types: primary and secondary. I want to publish and unpublish some content depending on whether the current user is anonymous user, user primary or secondary user.

If the current user is an anonymous user:

1. to publish primaria/docentes
2. to publish secundaria/docentes
3. to unpublish primaria/docentes/kit
4. to unpublish secundaria/docentes/kit

If the current user is a primary user:

1. to unpublish primaria/docentes
2. to publish primaria/docentes/kit

If the current user is a secondary user:

1. to unpublish secundaria/docentes
2. to publish secundaria/docentes/kit

I try to do this with the the Rules module. The result of my configuration is this: \- In the computer 1, I login as a primary user. Everything works fine. \- In the computer 2, I login as a secondary user. Everything works fine. \- If I return to the computer 1, the things are not good. I see that everything works as if logged in as a secondary user.

My settings do not respect the rules for the user already logged on. Every time someone logs on to any part of the world, that user settings apply to all other users in the world.

Please help me. I attached screenshots of my settings. **:(**

All my rules:

Log in as an anonymous user.

When primary user logs.

When primary user logs off.

# Answer
Publishing and unpublishing is not the way to go.

**Step 1)**

Install the Node Access module and give access to each node or content type accordingly, this way people can't share direct links with other users that have a different role.

**Step 2)**

What you need is to create 3 different **view blocks**

One for anonymous which lists primaria/docentes & secundaria/docentes nodes.

One for primary which lists all the primaria/docentes nodes

One for secondary which lists all the secundaria/docentes/kit nodes.

> Hopefully node access module lets you filter your view by node access. Otherwise, you'll need to make the "kit", "primaria" and "secundaria" be a different content types so then you can filter by content type in your view.

Use view's access to role and select the role you want to be able to see the view. (see picture below)

Then you place all 3 view blocks wherever you need them (home page perhaps?) and since you have the view access by role, they will only see 1 view (the one they have access to).
> 3 votes

---
Tags: rules
---


# Question
Title: Entity reference get all related items in a view
I'd like to have a view block on my content page that shows ALL related content. ALL in the sense of chaining - if Node A references Node B which references Node C which references Node D, then nodes B, C, and D all show up on Node A's page even though it itself is only related to Node B. How can I set this up?

# Answer
One way of doing this in a non-programmatic way is to use views\_field\_view. With this method you will only get a set number of nesting levels - for example 4 levels: create a view of your specific node Content Type with 4 Pages, A, B, C, and D. In Page A, insert a Views Field that references Page B, in B a field to Page C, and in C a reference to page D. Pages B, C and D should have a contextual filter for a Node ID (nid). In each page, the Views Field View field should pass the Node Reference as an argument to the next Page. I hope this is clear. Let me know if it's not, and I can expand this.

EDIT: If you are looking for "infinite depth" I suggest that you look at the programmatic alternative for Views, EntityFieldQuery(). Perhaps a recursive call to a function that does the query, while you build a global multi-depth array with the data you need, then theme it as a table.
> 1 votes

---
Tags: entities, views
---


title: How to make full width image slideshows

text:
# Question
Title: How to make full width image slideshows
I am using bootstrap sub-theme as default theme. I created a views slideshow block. In the tpl file, I added this:

```
<div class="test-region">
 <?php print render($page['test']); ?>
</div>

```

I placed the slideshow block into the above region.I can see my slideshow on my site. I added the below css to make the image slideshows 100% full width but it is not working. When I refresh my page, I can see the image slideshows in full width for 1 sec but then images go back to original sizes.

```
.views-slideshow-cycle-main-frame-row-item .field-content img {
    min-height: 500px;
    width: 100%;
}

```

Do you know why images show in full width for a sec then go back to original sizes?

# Answer
> I can see the image slideshows in full width for 1 sec but then images go back to original sizes.

sounds like there is another css that is loaded after that is causing them to shrink. (perhaps it's in the views slide show css file). To prevent anything that is loaded after from overriding your css try adding the `!important` tag

so try this:

```
.views-slideshow-cycle-main-frame-row-item .field-content img {
    min-height: 500px !important;
    width: 100% !important;
}

```
> 1 votes

# Answer
Below is the answer:

```
 .views-slideshow-cycle-main-frame.views_slideshow_cycle_teaser_section, .views-slideshow-cycle-main-frame-row.views_slideshow_cycle_slide.views_slideshow_slide {
        height: auto !important;
        min-height: 550px;
        width: 100% !important;
    }

.views-slideshow-cycle-main-frame-row-item .field-content img {
height: auto;
    min-height: 500px;
    width: 100%;
}

```
> 1 votes

---
Tags: views
---


# Question
Title: Commerce kickstart select country and don't show product
I use commerce kickstat and I have some products on my site. I want to disable add to cart button when user is not form some country.. for example.. USA.. if user is from USA he can see add to cart.. other not

# Answer
> 0 votes
Your best bet is to add a `hook_form_alter` and modify the commerce add to cart form to remove the button and/or change it up to your liking:

```
/**
 * Implements hook_form_alter()
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if (strpos($form_id, 'cart_add_to_cart') === 0) {
    if (/* Insert your logic here */) {
      unset($form['submit']);
      $form['submit'] = array('#markup' => '<p class="not-available">Not available in your country</p>');
    }
  }
}

```

---
Tags: commerce
---


# Question
Title: Where is the $email_text variable set on ubercart?
With Ubercart, where is the $email\_text variable set, the variable that determines whether the "do not reply to this email" should be displayed in the email received by a customer after they place an order.

# Answer
> 0 votes
It's set in `template_preprocess_uc_order(&variables)` in the order module (`$variables['email_text']`).

If you're looking to override this variable for your site it can be overridden by defining a function `MYTHEME_preprocess_uc_order(&variables)` in your theme's **template.php**

---
Tags: ubercart
---


# Question
Title: How to trigger consecutive batch operations using the output of the first one?
I have 2 operations in a module using Batch API. Below is the code for the first one:

```
function get_first_data($qc, $path) {
    $testsets = some array...

    foreach ($testsets as $testset) {
    $operations[] = array('first_data_batch', array($testset));
  }

  $batch = array(
    'operations' => $operations,
    'finished' => 'first_data_batch_finished',
    'title' => t('First Data'),
    'init_message' => t('Import is starting...'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('An error has occurred')
  );

  batch_set($batch);
  batch_process('user'); // The path to redirect to when done.
}

function first_data_batch($testset, &$context) {
    // do something with $testset

    $context['message'] = "Processing...";
}

function first_data_batch_finished($success, $results, $operations) {
  if ($success) {
    drupal_set_message('First import is complete!');
  }
  else {
    $error_operation = reset($operations);
    $message = t('An error occurred while processing %error_operation with arguments: @arguments', array(
      '%error_operation' => $error_operation[0],
      '@arguments' => print_r($error_operation[1], TRUE)
    ));
    drupal_set_message($message, 'error');
  }
  drupal_set_message(l('Run again', 'my_module/batch'));
}

```

What I need is to have another operation that uses the output of the first one.

I think I can't set this second operation on the `foreach` cycle of the first one because the loop is completely different so I'm assuming I would repeate the code below for my second batch. The only issue is how to pass the output of the first one to the second one.

Another thing: in the `first_data_batch` function I generate part of the output that I want to feed in the second batch. The final array that I want to feed will be completed only after all the calls to this function end.

So, how can I pass this array to the second batch?

Thanks.

**================================ EDIT ================================**

I cleaned my code. This one is simpler but I still can't the information I need after the operation.

`testcases_raw` array (:

My code:

```
function mymodule_form_submit($form, &$form_state) {
  $testcases_raw = array...
  $batch = array(
    'title' => t('Working ...'),
    'operations' => array(),
    'finished' => 'mymodule_batch_finished',
    'init_message' => t('Starting ...'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('An error occurred during processing'),
    'progressive' => FALSE
  );

  if (isset($testcases_raw['Entity'][0])) {
    foreach ($testcases_raw['Entity'] as $folder) {
      $batch['operations'][] = array('batch_testsets_multiple', array($folder));
    }
  } else {
    $batch['operations'][] = array('batch_testsets_single', array($testcases_raw));
  }
  batch_set($batch);
}

function batch_testsets_multiple($folder, &$context) {
  $a = $folder;

  $id = $a['Fields']['Field'][51]['Value'];
  $parent_id = $a['Fields']['Field'][28]['Value'];
  $name = $a['Fields']['Field'][54]['Value'];

  $testset = array('id' => $id, 'parent_id' => $parent_id, 'name' => $name);
  array_push($testsets, $testset);
  dd($testset);
  $context['results'] = $testsets;
  $context['message'] = $testsets;
}

function batch_testsets_single($folder, &$context) {
  $testsets = $context['results'];
  $id = $folder['Entity']['Fields']['Field'][51]['Value'];
  $parent_id = $folder['Entity']['Fields']['Field'][28]['Value'];
  $name = $folder['Entity']['Fields']['Field'][54]['Value'];

  $testset = array('id' => $id, 'parent_id' => $parent_id, 'name' => $name);
  array_push($testsets, $testset);

  $context['results'] = $testsets;
  $context['message'] = $testsets;
}

function mymodule_batch_finished($success, $results, $operations) {
  if ($success) {
    $message = format_plural(count($results), 'One processed.', '@count processed');
  } else {
    $message = t('Finished with an error.');
  }
  foreach ($results as $result) {
    drupal_set_message($result);
  }
  drupal_set_message($message);
}

```

In this example, the `batch_testsets_multiple` function will run 4 times. In each of the iterations I get one new array (`$testset`). Below are the 4 arrays as outputed to file by `dd` command:

```
Array
(
    [id] => 132202
    [parent_id] => 38680
    [name] => _TestSet1
)

Array
(
    [id] => 132203
    [parent_id] => 38680
    [name] => _TestSet2
)

Array
(
    [id] => 132345
    [parent_id] => 38797
    [name] => _TestSet3
)

Array
(
    [id] => 132394
    [parent_id] => 38831
    [name] => _TestSet4
)

```

What I need at the end of the batch opearation `batch_testsets_multiple` is an array with the 4 arrays above so I can use that array as input for a second operation. I think this code is simplier to understand. Hope it really helps.

# Answer
OK, after some struggle I found the solution and it's very simple (maybe I was complicating?).

Here is how my solution looks like:

```
function batch_testsets_multiple($folder, &$context) {
  $id = $folder['Fields']['Field'][51]['Value'];
  $parent_id = $folder['Fields']['Field'][28]['Value'];
  $name = $folder['Fields']['Field'][54]['Value'];

  $testset = array('id' => $id, 'parent_id' => $parent_id, 'name' => $name);

  // Here I save the iteration results to an array.
  // The [] ensures that all iteration results ($testset) are saved;
  $context['results']['testsets'][] = $testset;
  $context['message'] = $testsets;
}

```
> 1 votes

# Answer
You can use `$context['results']` to pass data between operations.

```
function first_data_batch($data, &$context) {
  // Get the data from previous operation.
  $bar = $context['results']['foo'];

  // Do something with it...

  // And store the results for the next operation.
  $context['results']['foo'] = $bar;
}

```
> 0 votes

---
Tags: batch-operations
---


# Question
Title: Creating new bulk views operations (VBO) actions for custom entity types
I have the following code and created a view for my custom entity type. I just want to create a new action button to be able to change a field's text to something else. I'm not sure why this custom action isn't showing up. Under which window am I suppose to see it? *Execute arbitary php* or *modify multiple entity values*?

Where is a good example code of getting a custom action working? Is there a pre-built VBO action example I can just download to see how it's made?

```
/**
 * Implements hook_action_info().
 */
function rubik_custom_action_info() {
  return array(
    'hideit' => array(
      'type' => 'entity',
      'label' => t('Custom Action'),
      'configurable' => FALSE,
      'triggers' => array('any'),
      'behavior' => array('changes_property'),
      'vbo_configurable' => FALSE,
      'pass rows' => TRUE,
    ),
  );
}

/**
 * Action function for MY_ACTION_NAME.
 */
function hideit(&$entity, $context = array()) {
  drupal_set_message('ok it works');
}

```

# Answer
> 4 votes
There are several VBO examples within the VBO module itself. Take for instance delete.action.inc which allows you to delete any entity. I can't see anything explicitly wrong with your code, but I'd highly recommend you follow convention and rework it to look like the other `hook_action_info()` implementations:

```
/**
 * Implements hook_action_info().
 */
function MYMODULE_action_info() {
  $actions['MYMODULE_custom_action'] = array(
    'type' => 'node', // Here come's the name of your custom entity type
    'label' => t('Custom Action'),
    'configurable' => FALSE,
    'triggers' => array('any'),
    'behavior' => array('changes_property'),
    'vbo_configurable' => FALSE,
    'pass rows' => TRUE,
  );

  return $actions;
}

function MYMODULE_custom_action($entity, $context) {
  // Your action here.
}

```

Your function name is `rubik_custom_action_info`. You aren't trying to define this within a theme are you? Don't do that. Put it in a separate module. Themes are no place for this.

Another module that may be of help is the Commerce Bundle Helper sandbox. Not only does it declare VBO actions, but it shows how you can automatically add it into a View that already exists by altering the VBO configuration.

# Answer
> 4 votes
After your action has been defined, it can be added in the Views UI under **Selected Bulk Operations** in your *Bulk operations* field settings. It will be a separate checkbox ***alongside*** other actions like *Execute arbitrary PHP script*, etc. Once selected, it should show up as select option or action button (depending on how the VBO field is configured).

The VBO development guide on d.o. is a good example of working code for defining an action, adding a optional global/per-bulk setting form, & creating action handler.

Here's a very bare bones example:

```
//Will add a "User Action" option to Bulk Operations: User field in Views UI
function MYMODULE_action_info() {
  return array(
    'MYMODULE_user_action' => array(
      //Can be other entities used in a view (e.g. 'node')
      'type' => 'user',
      'label' => t('User Action'),
      'behavior' => array('changes_property'),
      'triggers' => array('any'),

      //Set to true if you an intermediate options form for your action
      //'configurable' => true,

      //Set to true if you want additional globaloptions
      //'vbo_configurable' => true,
    ),
  );
}

function MYMODULE_user_action(&$entity, $context){
  //$entity is the current entity being modified; it can
  //  modified directly to perform the action on the entity

  //$context is an array of contextual information about the
  //  current state of bulk processing  (e.g. items remaining)
  //  It also contains configurable options values if any were set (see below)
}

//If 'configurable' => true in hook_action_info() item this trio of functions
// will add/process an intermediate form just like any Drupal form
function MYMODULE_user_action($settings, &$form_state){
 //$settings['settings'] will contains settings set in
 //  MYMODULE_user_action_views_bulk_operations_form
}
function MYMODULE_user_action_validate($form, $form_state) {
}
function MYMODULE_user_action_submit($form, $form_state) {
  //return an array of values usable by MYMODULE_user_action
}

//If 'vbo_configurable' => true, in hook_action_info() this presents
// additional configurable options for the  VBO action.
// It returns a Drupal form array
function MYMODULE_user_action_views_bulk_operations_form($options) {
}

```

# Answer
> 1 votes
By the implementation of `hook_action_info()`, you need to write the name of your custom entity type, instead of just `entity`. For example; `node`, `user`, `comment`, `taxonomy_term`, `field_collection_item` etc. The action will be available as long as the base table for your view mathces the type of the given entity in `hook_action_info()`.

```
/**
 * Implements hook_action_info().
 */
function rubik_custom_action_info() {
  return array(
    'hideit' => array(
      'type' => 'node', // Here come's the name of your custom entity type
      'label' => t('Custom Action'),
      'configurable' => FALSE,
      'triggers' => array('any'),
      'behavior' => array('changes_property'),
      'vbo_configurable' => FALSE,
      'pass rows' => TRUE,
    ),
  );
}

```

# Answer
> 0 votes
Took some time to figure this out, but its working. I have a custom entity called office and I needed to create a new vbo visible toggle button.

I put this code in the custom office module. Originally I put it in the theme template.php file to test, but it didn't work for some reason as I'm guessing it fires too late in the drupal boot process.

```
/**
* Views Bulk Operation Custom Visible Toggle Button
*/
function office_action_info() {  //office was my module name
  return array(
    'action_off' => array(  //name of your function call
      'type' => 'entity',  //targets all entities on the site
      'label' => t('Toggle Visible'),
      'configurable' => FALSE,
      'behavior' => array('changes_property'),  //set the behavior type
      'triggers' => array('any'),
    ),
  );
}

function action_off($entity, $context = array()) {

  //Populate the variable using entity_load of the associated id.
  $eload = entity_load('office', array($entity->office_id));

  //Changes the field value for the entity. In this case its the Visible field
  $eload[$entity->office_id]->visible = ($eload[$entity->office_id]->visible == 1 ? 0 : 1);

  //After editing the entity array, save it. Used current() to get 1st result.
  entity_save('office', current($eload));

  //not exactly sure what this does, but its to clear the entity cache?
  entity_get_controller('office')->resetCache(array($entity->office_id));
}

```

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


# Question
Title: How to display only the years that have content in view filter?
**What I have done**

1. I have created a view.
2. I have added a content type to display .
3. I have added a filter to filter by node date content and have opted to display the post date as year in the filter.

**What I want actually**

I wanted to display only the years that have content. I am using Drupal 7.

Which are the ways to do this?

# Answer
> 1 votes
If you go to views page (/admin/structure/views), you will find a view "Archive", you can clone it and use it, it will be displaying content month+year using contextual filter "Content: Created year + month", as you want to display only year, use contextual filter ""Content: Created year" and remove "Content: Created year + month".

**Screenshot for contextual filter.**

**Screenshot of output.**

It will list all the years that have content added.

**Update**

What you can do is to create a block of the view, and place it on the page you want, and then when you will click on an year, you can have the content list accordingly on the same page.

# Answer
> 0 votes
* Add your fields to view

* Add filter Date: Date(node)

* Configure as shown in screenshot

* I've made it exposed filter, see what you want and do the configuration

* This is how i get the result

---
Tags: views
---


# Question
Title: How to make the subscriptions module produce notifications on a screen?
Really struggling with subscriptions on my site or users.

I'm currently trying the subscriptions module, but I am unable to have the user notified on the site iself. I can see it can send emails to the users which is good, but I also would like to have a little notification at the top like stackexchange has.

Anybody point me in the right direction?

# Answer
> 1 votes
Same thing I wanted to do for some kind of notification. Finally, this was the implementation:

* Added one function which returns the count and notification with HTML.
* Then added Ajax request to fetch the result and place it on the notification element which is already placed in page.tpl.php
* Added JS code to custom.js which works on every page of site.
* See below:

* But remember don't make it heavy ajax request, it may slow down your site. And remember to add JS code at bottom of page.
* Also you can do one thing, put ajax request on click of the element, look what StackExchage do:

* on click of notification they send request and fetch the data...

---
Tags: 7, notifications
---


# Question
Title: I am trying to create user registration form in js which beautiful and flexible
I am using drupal 7. I am trying to create user registration form with javascript which beautiful and flexible. Something like this:

How can I achieve this?

# Answer
You can do it by using these modules :

Fancy Login

> Fancy Login adds javascript based, lightbox-style login functionality to your site. When the user clicks on any link that links to /user/login, they screen dims and a login box is created in the center of the screen.

Better Login

> Styling Drupal login/password/registration forms are a mission most of the time because they form part of the theme... This module removes that issue, it is slightly inspired by the way Wordpress login forms work, and uses three page templates to change the style of the forms. It is very simple to use, just install the Better Login module and it starts working immediately.

Model Form

> Modal forms make use of the modal feature in the ctools module to open some common forms in a modal window.
> 3 votes

# Answer
Call User Login block in colorbox. Use colorbox module. For Forgot Password and Need and Account? Sign Up Link You can use form\_alter i.e. Drupal Form API

If you totally want to do it with JS then also you can use colorbox library.

```
jQuery("#id-of-link-which-on-click-will-open-colorbox").colorbox({
   inline:true,
   href:'#id-of-block-to-open-in-colorbox',
   width:"1000px",
   height:"600px",
   transition:"fade",
   scrolling: false
});

```

For Forgot Password and Sign Up Link You can use append / prepend HTML accordingly.
> 2 votes

---
Tags: users, javascript
---


# Question
Title: Drupal views table with multiple agregation
Is it possible to make drupal views table with multiple agregation like view number 2 below?

```
    1. View Team
+============================+
| Team      |  Sales person  |
|----------------------------|
| Team 1    |  Nick          |
|----------------------------|
| Team 1    |  Jack          |
|----------------------------|
| Team 2    |  Sarah         |
|----------------------------|
| Team 1    |  Joe           |
|----------------------------|
| Team 1    |  Nindya        |
|----------------------------|
| Team 2    |  Octo          |
|============================|
|  Total    |      6         |
+============================+

2. Views with agregation
+============================+
| Team      |  Sales person  |
|----------------------------|
| Team 2    |      2         |
|----------------------------|
| Team 1    |      4         |
|============================|
|  Total    |      6         |
+============================+

```

# Answer
> 2 votes
Yes you can do by using Views Merge Rows module.

> Sometimes when you use relationships in views you get a number of rows with the same content in some of the fields. This results in a huge table (grid, list, etc.) that affects the usability of your view. The Views Merge Rows module provides a way to combine rows with the same content in the specified fields.

---
Tags: views
---